text:
Q: How can I stop SAX parsing? I am using a SAX parser (xml.sax) and it works how I want to. However, I am parsing quite a large file (hence why I use SAX) and I would like to stop parsing at some point (e.g., when I reached a certain limit, or when I found a certain piece of data).
class ProductHandler(xml.sax.ContentHandler):
  def startElement(self, tag, attrs):
    [.. process start ..]

  def endElement(self, tag):
    [.. process end ..]

  def characters(self, content):
    [.. process characters ..]

product_handler = ProductHandler()
parser = xml.sax.make_parser()
parser.setContentHandler(product_handler)
parser.parse(xmlfile)

How do I do that? Is there a certain return value I can return at one of the handler methods? I checked the documentation, but I couldn't find anything in this direction.

A: Using this example data, if we want to find a <description> that contains the word "sourdough", maybe we would write something like this:
import xml.sax

class IAmAllDone(Exception):
    pass

class ProductHandler(xml.sax.handler.ContentHandler):
    def __init__(self):
        super().__init__()

        self.description = None
        self.name = None
        self.tree = []

    def startElement(self, name, attrs):
        self.tree.append(name)

    def endElement(self, name):
        self.tree.pop(0)

    def characters(self, content):
        if self.tree[-1] == "name" and content.strip():
            self.name == content
            print("name:", content)
        elif self.tree[-1] == "description" and "sourdough" in content:
            self.description = content
            raise IAmAllDone()

product_handler = ProductHandler()
parser = xml.sax.make_parser()
parser.setContentHandler(product_handler)
try:
    parser.parse("data.xml")
except IAmAllDone:
    pass

if product_handler.description is not None:
    print("found description:", product_handler.description)

The above will output:
name: Belgian Waffles
name: Strawberry Belgian Waffles
name: Berry-Berry Belgian Waffles
name: French Toast
found description: Thick slices made from our homemade sourdough bread

As you can see, we stop the SAX parsing before reading the final "Homestyle Breakfast" item.


text:
Q: Speaking words with Pololu 3pi Robot At each instersection I play different music for the compass direction the robot decided to go. Any ideas how to get the robot to speak the words "West", "East", "South", "North"?
      if (current_direction == 'W')
        OrangutanBuzzer::play("!T240 L8 a gafaeada");
      if (current_direction == 'E')
        OrangutanBuzzer::play("!T240 L8 a gfgfgfgf");
      if (current_direction == 'S')
        OrangutanBuzzer::play("!T240 L8 a efgefgef");
      if (current_direction == 'N')
        OrangutanBuzzer::play("!T240 L8 a abcabcab");

Full code:
// The following libraries will be needed by this demo
#include <Pololu3pi.h>
#include <PololuQTRSensors.h>
#include <OrangutanMotors.h>
#include <OrangutanAnalog.h>
#include <OrangutanLEDs.h>
#include <OrangutanLCD.h>
#include <OrangutanPushbuttons.h>
#include <OrangutanBuzzer.h>

Pololu3pi robot;
unsigned int sensors[5]; // an array to hold sensor values
int last1 = 0;
int last2 = 0;
int last3 = 0;
int stop_robot = 0;
int already_stopped = 0;
int use_pattern = 0;
char pattern[] = {'S', 'S', 'S', 'S', 'S', 'S', 'S', 'R', 'R', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'L', 'L', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'R', 'R', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'R', 'S', 'S', 'S', 'R'};
int pattern_length = 39;
int i = -1;
int pattern_loop = 1;

// This include file allows data to be stored in program space.  The
// ATmega168 has 16k of program space compared to 1k of RAM, so large
// pieces of static data should be stored in program space.
#include <avr/pgmspace.h>

// Introductory messages.  The "PROGMEM" identifier causes the data to
// go into program space.
const char welcome_line1[] PROGMEM = "Tim's";
const char welcome_line2[] PROGMEM = "Self";
const char demo_name_line1[] PROGMEM = "Driving";
const char demo_name_line2[] PROGMEM = "Robot";

// A couple of simple tunes, stored in program space.
const char welcome[] PROGMEM = ">g32>>c32";
const char go[] PROGMEM = "L16 cdegreg4";
const char melody[] PROGMEM = "!L16 V8 cdefgab>cbagfedc";
int play_intersection_music = 0;
int be_random = 1;
int speed = 1;
int stop_protection = 0;
int do_calibration = 0;
int variable_speed = 0;
int do_compass = 1;

char current_direction = 'W';

// Data for generating the characters used in load_custom_characters
// and display_readings.  By reading levels[] starting at various
// offsets, we can generate all of the 7 extra characters needed for a
// bargraph.  This is also stored in program space.
const char levels[] PROGMEM = {
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111
};

// This function loads custom characters into the LCD.  Up to 8
// characters can be loaded; we use them for 7 levels of a bar graph.
void load_custom_characters()
{
  OrangutanLCD::loadCustomCharacter(levels + 0, 0); // no offset, e.g. one bar
  OrangutanLCD::loadCustomCharacter(levels + 1, 1); // two bars
  OrangutanLCD::loadCustomCharacter(levels + 2, 2); // etc...
  OrangutanLCD::loadCustomCharacter(levels + 3, 3);
  OrangutanLCD::loadCustomCharacter(levels + 4, 4);
  OrangutanLCD::loadCustomCharacter(levels + 5, 5);
  OrangutanLCD::loadCustomCharacter(levels + 6, 6);
  OrangutanLCD::clear(); // the LCD must be cleared for the characters to take effect
}

// This function displays the sensor readings using a bar graph.
void display_readings(const unsigned int *calibrated_values)
{
  unsigned char i;

  for (i=0;i<5;i++) {
    // Initialize the array of characters that we will use for the
    // graph.  Using the space, an extra copy of the one-bar
    // character, and character 255 (a full black box), we get 10
    // characters in the array.
    const char display_characters[10] = {
      ' ', 0, 0, 1, 2, 3, 4, 5, 6, 255     };

    // The variable c will have values from 0 to 9, since
    // calibrated values are in the range of 0 to 1000, and
    // 1000/101 is 9 with integer math.
    char c = display_characters[calibrated_values[i] / 101];

    // Display the bar graph character.
    OrangutanLCD::print(c);
  }
}

void no_stopping() {
  OrangutanLCD::clear();
  OrangutanLCD::print("No\nStopping");
  delay(1000);
}

// Initializes the 3pi, displays a welcome message, calibrates, and
// plays the initial music.  This function is automatically called
// by the Arduino framework at the start of program execution.

void setup()
{
  unsigned int counter; // used as a simple timer

    // This must be called at the beginning of 3pi code, to set up the
  // sensors.  We use a value of 2000 for the timeout, which
  // corresponds to 2000*0.4 us = 0.8 ms on our 20 MHz processor.
  robot.init(2000);

  load_custom_characters(); // load the custom characters

    // Play welcome music and display a message
  OrangutanLCD::printFromProgramSpace(welcome_line1);
  OrangutanLCD::gotoXY(0, 1);
  OrangutanLCD::printFromProgramSpace(welcome_line2);
  OrangutanBuzzer::playFromProgramSpace(welcome);
  delay(1000);

  OrangutanLCD::clear();
  OrangutanLCD::printFromProgramSpace(demo_name_line1);
  OrangutanLCD::gotoXY(0, 1);
  OrangutanLCD::printFromProgramSpace(demo_name_line2);
  delay(1000);

  OrangutanLCD::clear();
  int bat = OrangutanAnalog::readBatteryMillivolts();
  OrangutanLCD::print(bat);
  OrangutanLCD::print("mV");
  OrangutanLCD::gotoXY(0, 1);

  delay(2000);
  OrangutanLCD::clear();
  if (!play_intersection_music) {
    //OrangutanLCD::clear();
    OrangutanLCD::print("No");
    OrangutanLCD::gotoXY(0, 1);
    OrangutanLCD::print("Stopping");

  }
  else {
    //OrangutanLCD::clear();
    OrangutanLCD::print("Do");
    OrangutanLCD::gotoXY(0, 1);
    OrangutanLCD::print("Stop");
  }
  // Display battery voltage and wait for button press
  while (!OrangutanPushbuttons::isPressed(BUTTON_B))
  {

    //delay(100);
    if (OrangutanPushbuttons::isPressed(BUTTON_A)) {
      OrangutanPushbuttons::waitForRelease(BUTTON_A);
      OrangutanLCD::clear();
      if (play_intersection_music) {
        play_intersection_music = 0;
        //OrangutanLCD::clear();
        OrangutanLCD::print("No");
        OrangutanLCD::gotoXY(0, 1);
        OrangutanLCD::print("Stopping");

      }
      else {
        play_intersection_music = 1;
        OrangutanLCD::print("Do");
        OrangutanLCD::gotoXY(0, 1);
        OrangutanLCD::print("Stop");

      }
    }
  }

  OrangutanPushbuttons::waitForRelease(BUTTON_B);
  delay(1000);

  // Always wait for the button to be released so that 3pi doesn't
  // start moving until your hand is away from it.

  // Auto-calibration: turn right and left while calibrating the
  // sensors.
  for (counter=0; counter<80; counter++)
  {
    if (counter < 20 || counter >= 60)
      OrangutanMotors::setSpeeds(40, -40);
    else
      OrangutanMotors::setSpeeds(-40, 40);

    // This function records a set of sensor readings and keeps
    // track of the minimum and maximum values encountered.  The
    // IR_EMITTERS_ON argument means that the IR LEDs will be
    // turned on during the reading, which is usually what you
    // want.
    robot.calibrateLineSensors(IR_EMITTERS_ON);

    // Since our counter runs to 80, the total delay will be
    // 80*20 = 1600 ms.
    delay(20);
  }
  OrangutanMotors::setSpeeds(0, 0);

  OrangutanLCD::clear();

  OrangutanLCD::print("Go!");

  // Play music and wait for it to finish before we start driving.
  OrangutanBuzzer::playFromProgramSpace(go);
  while(OrangutanBuzzer::isPlaying());
}

// This function, causes the 3pi to follow a segment of the maze until
// it detects an intersection, a dead end, or the finish.
void follow_segment()
{
  int last_proportional = 0;
  long integral=0;

  while(1)
  {
    // Normally, we will be following a line.  The code below is
    // similar to the 3pi-linefollower-pid example, but the maximum
    // speed is turned down to 60 for reliability.

    // Get the position of the line.
    unsigned int position = robot.readLine(sensors, IR_EMITTERS_ON);
    if (!do_compass)
      display_sensors();
    // The "proportional" term should be 0 when we are on the line.
    int proportional = ((int)position) - 2000;

    // Compute the derivative (change) and integral (sum) of the
    // position.
    int derivative = proportional - last_proportional;
    integral += proportional;

    // Remember the last position.
    last_proportional = proportional;

    // Compute the difference between the two motor power settings,
    // m1 - m2.  If this is a positive number the robot will turn
    // to the left.  If it is a negative number, the robot will
    // turn to the right, and the magnitude of the number determines
    // the sharpness of the turn.
    int power_difference = proportional/20 + integral/10000 + derivative*3/2;

    // Compute the actual motor settings.  We never set either motor
    // to a negative value.
    if (variable_speed)
      speed = random(1, 7);
    const int maximum = speed * 30; // the maximum speed
    if (power_difference > maximum)
      power_difference = maximum;
    if (power_difference < -maximum)
      power_difference = -maximum;

    if (power_difference < 0)
      OrangutanMotors::setSpeeds(maximum + power_difference, maximum);
    else
      OrangutanMotors::setSpeeds(maximum, maximum - power_difference);

    // We use the inner three sensors (1, 2, and 3) for
    // determining whether there is a line straight ahead, and the
    // sensors 0 and 4 for detecting lines going to the left and
    // right.

    //if (sensors[0] > 200 && sensors[1] > 200 && sensors[2] > 200 && sensors[3] > 200 & sensors[4]) {
    //  OrangutanBuzzer::playFromProgramSpace(go);
    //  while(OrangutanBuzzer::isPlaying());
    //}

    if (sensors[1] < 100 && sensors[2] < 100 && sensors[3] < 100)
    {
      // There is no line visible ahead, and we didn't see any
      // intersection.  Must be a dead end.
      return;
    }
    else if (sensors[0] > 200 || sensors[4] > 200)
    {
      // Found an intersection.
      return;
    }

  }
}

// Code to perform various types of turns according to the parameter dir,
// which should be 'L' (left), 'R' (right), 'S' (straight), or 'B' (back).
// The delays here had to be calibrated for the 3pi's motors.
void turn(unsigned char dir)
{
  if (play_intersection_music == 1) {
    OrangutanMotors::setSpeeds(0, 0);
    OrangutanBuzzer::playFromProgramSpace(melody);
    while(OrangutanBuzzer::isPlaying());
  }
  switch(dir)
  {
  case 'L':
    // Turn left.
    OrangutanMotors::setSpeeds(-80, 80);
    delay(200);
    if (current_direction == 'W')
      current_direction = 'S';
    else if (current_direction == 'E')
      current_direction = 'N';
    else if (current_direction == 'S')
      current_direction = 'E';
    else if (current_direction == 'N')
      current_direction = 'W';

    break;
  case 'R':
    // Turn right.
    if (current_direction == 'W')
      current_direction = 'N';
    else if (current_direction == 'E')
      current_direction = 'S';
    else if (current_direction == 'S')
      current_direction = 'W';
    else if (current_direction == 'N')
      current_direction = 'E';
    OrangutanMotors::setSpeeds(80, -80);
    delay(200);
    if (do_calibration) {
      int counter;
      for (counter=0; counter<80; counter++)
      {
        if (counter < 20 || counter >= 60)
          OrangutanMotors::setSpeeds(40, -40);
        else
          OrangutanMotors::setSpeeds(-40, 40);

        // This function records a set of sensor readings and keeps
        // track of the minimum and maximum values encountered.  The
        // IR_EMITTERS_ON argument means that the IR LEDs will be
        // turned on during the reading, which is usually what you
        // want.
        robot.calibrateLineSensors(IR_EMITTERS_ON);

        // Since our counter runs to 80, the total delay will be
        // 80*20 = 1600 ms.
        delay(20);
      }
    }
    OrangutanMotors::setSpeeds(0, 0);
    break;
  case 'B':
    // Turn around.
    if (current_direction == 'W')
      current_direction = 'E';
    else if (current_direction == 'E')
      current_direction = 'W';
    else if (current_direction == 'S')
      current_direction = 'N';
    else if (current_direction == 'N')
      current_direction = 'S';
    OrangutanMotors::setSpeeds(80, -80);
    delay(400);
    break;
  case 'S':
    // Don't do anything!
    break;
  }
}

// The path variable will store the path that the robot has taken.  It
// is stored as an array of characters, each of which represents the
// turn that should be made at one intersection in the sequence:
//  'L' for left
//  'R' for right
//  'S' for straight (going straight through an intersection)
//  'B' for back (U-turn)
//
// Whenever the robot makes a U-turn, the path can be simplified by
// removing the dead end.  The follow_next_turn() function checks for
// this case every time it makes a turn, and it simplifies the path
// appropriately.
char path[100] = "";
unsigned char path_length = 0; // the length of the path

void display_sensors()
{
    unsigned int position = robot.readLine(sensors, IR_EMITTERS_ON);

  // Display the position measurement, which will go from 0
  // (when the leftmost sensor is over the line) to 4000 (when
  // the rightmost sensor is over the line) on the 3pi, along
  // with a bar graph of the sensor readings.  This allows you
  // to make sure the robot is ready to go.
  OrangutanLCD::clear();
  OrangutanLCD::print(sensors[0]/10);
  //OrangutanLCD::print(sensors[1]/10);
  //OrangutanLCD::print(sensors[2]/10);
  //OrangutanLCD::print(sensors[3]/10);
  //OrangutanLCD::print(sensors[4]/10);
  OrangutanLCD::gotoXY(0, 1);
  display_readings(sensors);
}

// Displays the current path on the LCD, using two rows if necessary.
void display_path()
{
  // Set the last character of the path to a 0 so that the print()
  // function can find the end of the string.  This is how strings
  // are normally terminated in C.
  path[path_length] = 0;

  OrangutanLCD::clear();
  OrangutanLCD::print(path);

  if (path_length > 8)
  {
    OrangutanLCD::gotoXY(0, 1);
    OrangutanLCD::print(path + 8);
  }
}

// This function decides which way to turn during the learning phase of
// maze solving.  It uses the variables found_left, found_straight, and
// found_right, which indicate whether there is an exit in each of the
// three directions, applying the "left hand on the wall" strategy.
unsigned char select_turn(unsigned char found_left, unsigned char found_straight, unsigned char found_right)
{
  i = i + 1;
  if (use_pattern) {
    if (pattern_loop) {
      return pattern[i % pattern_length];
    }
    else if (i >= pattern_length) {
      stop_robot = 1;
      return 'B';
    } else {
      return pattern[i];
    }
  }
  // Make a decision about how to turn.  The following code
  // implements a left-hand-on-the-wall strategy, where we always
  // turn as far to the left as possible.
  if (be_random == 1) {
    if (found_left && found_straight && found_right) {
      int picked_choice = random(0, 4);
      if (picked_choice == 0)
        return 'B';
      if (picked_choice == 1)
        return 'L';
      if (picked_choice == 2)
        return 'S';
      if (picked_choice == 3)
        return 'R';
    }
    if (found_left && found_straight && !found_right) {
      int picked_choice = random(0, 3);
      if (picked_choice == 0)
        return 'B';
      if (picked_choice == 1)
        return 'L';
      if (picked_choice == 2)
        return 'S';
    }
    if (found_left && !found_straight && found_right) {
      int picked_choice = random(0, 3);
      if (picked_choice == 0)
        return 'B';
      if (picked_choice == 1)
        return 'L';
      if (picked_choice == 2)
        return 'R';
    }
    if (found_left && !found_straight && !found_right) {
      int picked_choice = random(0, 2);
      if (picked_choice == 0)
        return 'B';
      if (picked_choice == 1)
        return 'L';
    }
    if (!found_left && found_straight && found_right) {
      int picked_choice = random(0, 3);
      if (picked_choice == 0)
        return 'B';
      if (picked_choice == 1)
        return 'S';
      if (picked_choice == 2)
        return 'R';
    }
    if (!found_left && found_straight && !found_right) {
      int picked_choice = random(0, 2);
      if (picked_choice == 0)
        return 'B';
      if (picked_choice == 1)
        return 'S';
    }
    if (!found_left && !found_straight && found_right) {
      int picked_choice = random(0, 2);
      if (picked_choice == 0)
        return 'B';
      if (picked_choice == 1)
        return 'R';
    }
    if (last1 == 0)
      last1 = 1;
    else if (last2 == 0)
      last2 = 1;
    else if (last3 == 0)
      last3 = 1;
    else
      stop_robot = 1;
    return 'B';
  }
  else {
    if (found_left)
      return 'L';
    else if (found_straight)
      return 'S';
    else if (found_right)
      return 'R';
    else
      return 'B';
  }
}

// Path simplification.  The strategy is that whenever we encounter a
// sequence xBx, we can simplify it by cutting out the dead end.  For
// example, LBL -> S, because a single S bypasses the dead end
// represented by LBL.
void simplify_path()
{
  // only simplify the path if the second-to-last turn was a 'B'
  if (path_length < 3 || path[path_length-2] != 'B')
    return;

  int total_angle = 0;
  int i;
  for (i = 1; i <= 3; i++)
  {
    switch (path[path_length - i])
    {
    case 'R':
      total_angle += 90;
      break;
    case 'L':
      total_angle += 270;
      break;
    case 'B':
      total_angle += 180;
      break;
    }
  }

  // Get the angle as a number between 0 and 360 degrees.
  total_angle = total_angle % 360;

  // Replace all of those turns with a single one.
  switch (total_angle)
  {
  case 0:
    path[path_length - 3] = 'S';
    break;
  case 90:
    path[path_length - 3] = 'R';
    break;
  case 180:
    path[path_length - 3] = 'B';
    break;
  case 270:
    path[path_length - 3] = 'L';
    break;
  }

  // The path is now two steps shorter.
  path_length -= 2;
}

// This function comprises the body of the maze-solving program.  It is called
// repeatedly by the Arduino framework.
void loop()
{
  if (!stop_robot || !stop_protection) {
    follow_segment();

    // Drive straight a bit.  This helps us in case we entered the
    // intersection at an angle.
    // Note that we are slowing down - this prevents the robot
    // from tipping forward too much.
    OrangutanMotors::setSpeeds(50, 50);
    delay(50);
    if (!do_compass)
      display_sensors();

    // These variables record whether the robot has seen a line to the
    // left, straight ahead, and right, whil examining the current
    // intersection.
    unsigned char found_left = 0;
    unsigned char found_straight = 0;
    unsigned char found_right = 0;

    // Now read the sensors and check the intersection type.
    unsigned int sensors[5];
    robot.readLine(sensors, IR_EMITTERS_ON);

    // Check for left and right exits.
    if (sensors[0] > 100)
      found_left = 1;
    if (sensors[4] > 100)
      found_right = 1;

    // Drive straight a bit more - this is enough to line up our
    // wheels with the intersection.
    OrangutanMotors::setSpeeds(40, 40);
    delay(200);

    // Check for a straight exit.
    robot.readLine(sensors, IR_EMITTERS_ON);
    if (sensors[1] > 200 || sensors[2] > 200 || sensors[3] > 200)
      found_straight = 1;

    // Intersection identification is complete.
    // If the maze has been solved, we can follow the existing
    // path.  Otherwise, we need to learn the solution.
    unsigned char dir = select_turn(found_left, found_straight, found_right);

    // Make the turn indicated by the path.
    turn(dir);
    if (do_compass) {
      OrangutanMotors::setSpeeds(0, 0);
      OrangutanLCD::clear();
      OrangutanLCD::print(dir);
      OrangutanLCD::gotoXY(0, 1);
      OrangutanLCD::print(current_direction);
      if (current_direction == 'W')
        OrangutanBuzzer::play("!T240 L8 a gafaeada");
      if (current_direction == 'E')
        OrangutanBuzzer::play("!T240 L8 a gfgfgfgf");
      if (current_direction == 'S')
        OrangutanBuzzer::play("!T240 L8 a efgefgef");
      if (current_direction == 'N')
        OrangutanBuzzer::play("!T240 L8 a abcabcab");
      while(OrangutanBuzzer::isPlaying());
    }

    // Store the intersection in the path variable.
    path[path_length] = dir;
    path_length++;

    // You should check to make sure that the path_length does not
    // exceed the bounds of the array.  We'll ignore that in this
    // example.

    // Simplify the learned path.
    simplify_path();

    // Display the path on the LCD.
    //display_path();
  }
  else {
    OrangutanMotors::setSpeeds(0, 0);
    if (!already_stopped) {
      OrangutanLCD::clear();

      OrangutanLCD::print("Stopped");
      already_stopped = 1;
    }
  }

}

A: Microcontroller controlled SD card + sound player modules are available for around $6 (and up). These have a memory card reader, MP3, ADPCM or WAV file deciding, and PCM audio output, with a 0.1" header for connecting to the microcontroller board of choice. Your application can trigger specific files to be played back on events of interest.
So simply record the "north", "south", "east", "west" and any other speech into separate files, and play back the appropriate file as needed.
At a slightly higher price point, similar modules with a chip amplifier on board can be found, for louder sound output. Some of these modules offer stereo 3W + 3W or higher outputs, but stereo does not seem a requirement for the application described.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to draw these diagrams? I am writing my Masters thesis and I need to draw some diagrams that look like this:

I have been drawing many Feynman diagrams already, but I am not completely sure if this can be drawn with the same package (tikz-feynman) or if I need something different.

A: Ok, here is one way to do it in tikz. Some remarks:

*

*use some constants for radii to position text around the circles

*the left circle accepts polar coordinates "as is"

*the right one needs some center and shift like: \draw (r) to +(40:\RD) ...;

*the - at R draws a white line on a white background, making it "invisible"

*notations are in math-mode

*pifont provides the bullets \ding{108}

*because tikz-feynman uses tikz, this diagram works fine with both

\documentclass[border=3mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
\usepackage{pifont}

% ~~~ some constants ~~~~~~~~~~~~~
\newcommand\RD[0]{12mm}
\newcommand\RDD[0]{8mm}
\newcommand\RDP[0]{5.5mm}

\begin{document}
    \tikz [LR/.style={shape=circle,fill=gray!40,draw=black}]{
        % ~~~ L and R ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        \node[name=l,LR] at (0,0) {L};
        \node[name=r,LR] at (2,0) {R};

        % ~~~ + and - ~~~~~~~~~~~~~~~~~~~~~~~
        %     + , using polar coordinates
        \node at (-26:\RDP) {$+$};
        %     trick: draw white line to node colored in black
        \draw [white] (r) to +(-154:\RDP) node [black] {$-$};

        % ~~~ drawing the lines ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        %     between circles, with text above
        \draw (l) -- node [above] {$\hat P_I$} (r);

        %     lines leaving L
        \draw (l) to (140:\RD) node [fill=white] {$\hat 1 ^-$};
        \draw (l) to (210:\RD) node [fill=white] {$n ^+$};

        %     lines leaving R
        \draw (r) to +(40:\RD)   node [fill=white] {$\hat 2 ^-$};
        \draw (r) to +(15:\RD)   node [fill=white] {$3 ^+$};
        \draw (r) to +(-6:\RDD)  node [fill=white] {\tiny\ding{108}};
        \draw (r) to +(-27:\RDD) node [fill=white] {\tiny\ding{108}};
        \draw (r) to +(-50:\RD)  node [fill=white] {$n-1 ^+$};
    }
\end{document}


text:
Q: tengo una duda, es porque no se por que el servidor y cliente no se conectan "Código Servidor"
import socket
import threading
import sys
import time

def Enviar_mensaje():
    print("Has selecionado la opción 1")
    Mensaje = input("Escribe algo:  ")
    print(Mensaje)
    primer_socket.send(Mensaje)

def Ver_mensaje():
    print("Has selecionado opción 2")
    Mensajes = []
    try:
        Mensajes = Mensajes + primer_socket.recv(1024)
        if Mensajes != []:
            print("Bandeja", "\n", Mensajes)
        else:
            print("Bandeja", "\n", "No tiene Mensajes.")
    except:
        print("¡Ups!, Ocurrio un error, no hay ningun cliente conectado.")

def MessageChat():
    mi_socket= socket.socket()
    mi_socket.bind(('localhost', 8000))
    mi_socket.listen(5)
    while True:
        conexion, addr = mi_socket.accept()
        print("Estableciendo conexión")

        print("Bienvenido al Chat", "\n", "¿Cuál opción desea realizar?", "\n", "Opción 1 = Enviar mensaje", "\n", "Opción 2 = Ver Mensaje")
        Opcion = input("¡Ingrese su opción aquí!  ")
        if Opcion == "1":
            return Enviar_mensaje()
        if Opcion == "2":
           return Ver_mensaje()

"Codigo cliente"
import socket
import threading
import sys
import pickle

def Ver_mensajes():
        try:
            datos = []
            datos = datos + mi_socket.recv(1024)
            if datos != []:
                print("Bandeja", "\n", datos)
            else:
                print("Bandeja", "\n", "No tiene ningún mensaje :'( ")
        except:
            print("Ups!, ha ocurrido en un error")

def Enviar_mensaje():
    print("Has selecionado la opción 1")
    Mensaje = input("Escribe algo:  ")
    print(Mensaje)
    mi_socket.send(Mensaje)

def ClienteChat():
    mi_socket = socket.socket()
    mi_socket.connect(('localhost', 8000))#Procedemos a conectar el socket con nuestro servidor.
    print("Bienvenido al Chat", "\n", "¿Cuál opción desea realizar?", "\n", "Opción 1 = Enviar mensaje", "\n", "Opción 2 = Ver Mensaje")
    Opcion = input("¡Ingrese su opción aquí!  ")
    if Opcion == "1":
        return Enviar_mensaje()
    if Opcion == "2":
        return Ver_mensajes()


text:
Q: .NET 2.0 issue with assembly not found i have to fight against a strange issue in my company. we have 2 .net 2.0 (old, i know) apps, which start with an .asmx-file. the code-behind calls a c#-file, which includes a include abcd directive, whereby abcd originates from a 3rd-party company.
one app is in test and it works fine. the identical one is in production and fails with the error Could not load file or assembly 'abcd.dll' or one of its dependencies. The specified module could not be found.
when i look in the related web.config-files, none of them includes a pointer to abcd.dll, which i first do not understand in the context of the productive environment, where everything works. secondly when i look inside the \bin-folder, i see the related assembly/dll. again: this is identical in both systems.
the only difference of both systems is the fact that visual studio 2.0 (does this really exist?) is available on the test system.
please note: i am aware that assemblies have to be added via solution explorer in visual studio too. but i cannot do this as such an installation is not allowed  here. but again: in web.config on the test server no reference can be found in the related web.config and everythings works fine.
so my question is: how to get this thing working in productive env?
thanks in advance

A: You may want to run Dependency Walker (depends.exe) http://www.dependencywalker.com/ and point it at to detect if any dependencies are missing.
I'd also look in the GAC (C:\Windows\assembly) to see if there are any related differences there.
Also, compare IIS setting on the two machines.


text:
Q: Silverlight Installation Got Corrupt I am facing the problem from 3 days and i think it all started when i installed Visual studio 2013 on my machine that already has VS2010 and VS2012.
Don't remember the exact steps after that but one thing is confirm it happened after vs2013 installation.
Previously it showed some kind of error in Microsoft.Expression. on designer while loading the windows phone page and it happened on all of the pages of all projects.
It vs2012 didn't recognize even the  tags  etc.
I uninstalled VS2013 and vs2012, installed vs2012 again bt still no remedy. Now when i open vs and try to create even a new windows phone project it shwos following
below is the image of error i see every time i try to open my existing windows phone projects.

Below are the last entries in the file mentioned in the image above.

A: I'm wondering if you upgraded to Windows 8.1. That upgrade has fracked most people's Silverlight development environment. I am working through that issue myself and if you upgraded to 8.1, you may want to search for solutions for that.
Here's a link with further information:
http://social.msdn.microsoft.com/Forums/silverlight/en-US/960abca1-5f10-4608-ad72-93ecef6e70a7/windows-81-killed-my-silverlight-development-environment?forum=silverlightdevtools
I did just the uninstall and install of the developer exe and that solved my problems.
Hope that helps!


text:
Q: Data Binding works in code-behind, but not in XAML Possibly ItemsControl Issue I have several bindings in my code, but I'm not sure why only this one fails in xaml.
       <ItemsControl.ItemTemplate>
          <DataTemplate>
              <wpfExp:SignalGraph
                  x:Name="signal_graph"
                  Height="{Binding ElementName=signal_box, Path=GraphHeight, Mode=OneWay}"
                  <!--PenWidth="{Binding ElementName=signal_box, Path=GraphPenWidth, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"-->
                  Signal="{Binding}"
                  signal_graph_window_width="{Binding ElementName=signal_box, Path=signal_graph_window_width, Mode=OneWay}"
                  X_Scale="{Binding ElementName=signal_box, Path=X_Scale, Mode=OneWay}"
                  MaxTimeValue="{Binding Source = {StaticResource ResourceKey=signal_data}, Path = MaxTimeValue, Mode=OneWay}"
              />

only the commented line fails. Meanwhile, if I go into code behind:
private void SignalGraph_Loaded(object sender, RoutedEventArgs e)
{
      loaded = true;

      Binding b1 = new Binding();
      b1.ElementName = "signal_box";
      b1.Path = new PropertyPath("GraphPenWidth");
      b1.Mode = BindingMode.OneWay;
      b1.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
      this.SetBinding(PenWidthProperty, b1);

      Width = signal_graph_window_width;
      SignalBox sb = VisualTreeUtilities.FindVisualParent<SignalBox>(this);
      DrawSignals();

}
this works. To me they both seem the same.
But the only possible explanation that I can think of is that maybe when I write the binding in xaml, the Binding takes place at a different time rather than on load event like the code behind.  If it is too early, before signalgraph is actually created, then maybe it doesn't bind correctly? but i'm not getting a binding error message.  Quite confused.

A: So I figured out what was going on. Basically I accidentally had set a value to the DependencyProperty using the .net property setter and it was overwriting the binding. When I did the bind in code behind, I put the binding in the loaded event block, but in xaml, the binding was occurring in the constructor for the higher level control, so it would get overwritten later.
thanks for all the ideas and help thinking about it


text:
Q: A countable subset of R without isolated points Is there a countable subset of $\mathbb{R},$ which doesn't have any isolated points?
It is an easy consequence of the Baire Category theorem that any closed countable set of reals has an isolated point. I am just wondering, if we can drop the condition about the set being closed.

A: How about $\Bbb Q$?  I don't think it has any isolated points.


text:
Q: How to keep comments in this AWK command I have a zipped file. I want to split it into multiple files by the first column. The command below does that but it's also skipping comments. How do I include the header/comments # in the output? Also, I would like to save the output as "[the value in column 1].vcf". How do I do that?
zcat 1000G.vcf.gz | awk '!/^#/{print>$1}'

Sample 1000G.vcf
# header 1
# header 2
# header 3
1    A    B
1    C    B
1    C    D
2    A    B
2    C    D
2    C    E
3    A    B
3    B    D

I want the awk command to create 3 vcf files:
1.vcf
# header 1
# header 2
# header 3
1    A    B
1    C    B
1    C    D

2.vcf
# header 1
# header 2
# header 3
2    A    B
2    C    D
2    C    E

3.vcf
# header 1
# header 2
# header 3
3    A    B
3    B    D

A: For your second question, you can concatenate the extension to the column 1 value.
awk '!/^#/ { file = $1 ".vcf"; print > file } '

For the header lines, append them to a variable. The first time you write to a file, write the comments to it.
awk '/^#/ { comments = comments ? comments "\n" $0 : $0 ; next }
     !files[$1] { file = $1 ".vcf"; print comments > file; files[$1] = 1 }
     { file = $1 ".vcf"; print > file }'


text:
Q: ClickOnce Silent installation I'm looking for a possibility to install ClickOnce applications silent. I already read like a million of threads but nothing helped. I tried VSTO, Copying the files and registry keys, silent parameters...
Is it possible to hide the window or just the prompt on which you have to press Yes or No to install?
I don't care about the kind, just share with me please

A: Click once deployment is the best solution and choose the option
Application should check for updates after the application starts


text:
Q: Change operator time and battery level In Swift is there any chance to change operator name, time, and battery level in app?
I want to change them temporarily in my joke app.
If Apple does not allow it how can I do it early?

A: I have no idea whether Apple allows an app to show a fake status bar or not but you can easily do it while your app is running. You can't show a fake status bar when your app isn't running.
To show a fake status bar in your own app, simply hide the real status bar and show your fake one at the top of your app's view.
See the following for information on hiding the status bar.


text:
Q: log cron job in real time I have a Python process which I run nightly via a crontab. It scrapes an API which I have limited access to so regularly has to stop and wait for an hour.
By my estimates the job should take 5-6 hours to complete.
At the moment I have a crontab as such:
05 01 * * * python3 /home/{my username}/path/to/process/main.py >> /var/log/process_name.log 2>&1

This is great and has proven to show that the file runs, but I can only check the output after it has finished running, which for me is not ideal. Considering the time it takes to run I would prefer cron to log output and errors in real time.
This is a bit more of a problem now as it seems my estimates are off and I can be waiting far longer than I think I should - in which case I would like to see what is being logged so I can understand why.
Is there a way to log cron output in real time?

A: What you need is a mechanism called flushing: forcing a process to write its output, which would otherwise remain buffered until completion.
Shell scripts flush on a line by line basis. If you need the output of a shell script before the script is ended, make sure it contains a newline.
Python programs can explicitly flush their stdout by calling the flush method:
import sys
sys.stdout.flush()


text:
Q: How to make areas available in homepage? I have a second thing in my RouteConfig:
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    }

I need to change controller, but the problem is that it is placed in Areas.
I tried to change MapRoute to this:
url: "{area}/{controller}/{action}/{id}",
defaults: new { area="Purchase", controller = "Card", action = "Index", id = UrlParameter.Optional });

but it's not working.
Also I have this in AreaRegistration:
    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Purchase_default",
            string.Format("{0}/{{controller}}/{{action}}/{{id}}", AreaNames.Purchase),
            new { controller = "Card", action = "Index", id = UrlParameter.Optional });
    }

And here I have seen something similar but I didn't got how to use it.
What am I doing wrong and how should it be done?


text:
Q: Proof- division. Is it a true statement or false Prove that $\forall a,b,c,d$ E Z, if $a | c$ and $b | d$ then $(a+b) | (c+d)$
I've got up to here
$$c=ax$$
$$d=by$$
So
$$c+d = ax+by$$
I believe that this a false statement but I don't know where to go from here


text:
Q: Do you prove all theorems whilst studying? When you come across a new theorem, do you always try to prove it first before reading the proof within the text? I'm a CS undergrad with a bit of an interest in maths. I've not gone very far in my studies -- sequence two of Calculus -- but what I'm trying to understand right now, though, is how one actually goes about studying so that when finished with a good text, there's more of an intuitive understanding than superficial.
After reading "The Art Of Problem Solving" from the Final Perspectives section of part eight in 'The Princeton Companion to Mathematics', it seems to hint at approaching studying in that very way. A quote in particular, from  Eisenstein, that caught my attention was the following -- I'm not going to paraphrase much:

The method used by the director was as follows: each student had to
  prove the theorems consecutively. No lecture took place at all. No one
  was allowed to tell his solutions to anybody else and each student
  received the next theorem to prove, independent of the other students,
  as soon as he had proved the preceding one correctly, and as long as
  he had understood the reasoning. This was a completely new activity
  for me, and one which I grasped with incredible enthusiasm and an
  eagerness for knowledge. Already, with the first theorem, I was far
  ahead of the others, and while my peers were still struggling with the
  eleventh or twelfth, I had already proved the hundredth. There was
  only one young fellow, now a medicine student, who could come close to
  me. While this method is very good, strengthening, as it does, the
  powers of deduction and encouraging autonomous thinking and
  competition among students, generally speaking, it can probably not be
  adapted. For as much as I can see its advantages, one must admit that
  it isolates a certain strength, and one does not obtain an overview of
  the whole subject, which can only be achieved by a good lecture. Once
  one has acquired a great variety of material through [...] For
  students, this method is practicable only if it deals with small
  fields of easily, understandable knowledge, especially geometric
  theorems, which do not require new insights and ideas.

I feel that this type of environment is something you don't often see, especially in the US -- perhaps that's why so many of our greats are foreign born. As I understand it, he does go on to say that he wouldn't particularly recommend that method of study for higher mathematics, though.
A similar question was posed to mathoverflow where Tim Gowers (Fields Medal) went on to say that he recommended similar methods to study: link
I'm not quite certain that I understood the context of it all, though. Upon asking a few people whose opinion mattered to me, I was told that it if time were precious to me, it would be a waste going about studying mathematics in that way, so I'd like to get some perspective from you math.stackexchange. How do you go about studying your texts?
Edit: Broken link added fixed.

A: I did try to prove propositions in my textbooks before reading proofs when I was studying subjects like linear algebra, real analysis... But later on when things becoming more and more difficult, I had to give it up, and today I am still wondering if that was worthwhile...Because on one hand, there are many benefits of doing so: you may gain better understanding of the statement, improve you skill of proving things (), and you get great joy when you work something out! On the other hand, you will process very slowly (if not then congratulation!), but there is tons more to explore.
However, I do have some little suggestions:

*

*if you develop the hobby of proving everything on you own, do not forget to zoom out from your proof of a specific statement and review the big picture of a lecture, a section or even a subject once for a while.

*if you don't want to prove it, read others' proof, don't skip it.

*maybe you can pick one or two subjects which are most important or interesting for you.

A: See my question on mathoverflow for books that are designed for this sort of study:
https://mathoverflow.net/questions/12709/are-there-any-books-that-take-a-theorems-as-problems-approach
Also, from a short bio of S.Ramanujan:

At sixteen, Ramanujan borrowed the English text "Synopsis of Pure Mathematics". This work was to prove a deep influence on Ramanujan's development as a mathematician, for it offered mathematical theorems without accompanying proofs, thereby prompting Ramanujan to prove the material by his own mathematical cunning.

Full text here: http://myhero.com/go/hero.asp?hero=s_ramanujan

A: There is a continuum in the way one understands a theorem.
At one end  of the spectrum mathematicians  just try to understand the statement and use it as a black box .
At the other end they understand the theorem so well that they improve on it: this is called research.
An important thing to keep in mind is that your attitude toward a result is not fixed for ever: you may first consider  it as a black box and solve exercises by blindly using it, then see how it is quoted in proving corollaries or other theorems and finally come back to it and realize that it is actually quite natural.
Professors  have  the advantage that they really have to understand a theorem if they want to teach it well and answer the students' questions.
One of the great aspects of this site is that everybody can be a teacher:
 I strongly advise you to try and answer questions here.  They are at all possible levels and I am sure you can find some that you will  answer very competently.
A paradoxical way of expressing what it means to have understood a theorem is to say that ideally you have to reach the stage where you consider that all its proofs in the literature are "wrong": it is a patently absurd statement but it conveys the idea that the theorem is now yours because you have integrated it into your own mathematical world.
Edit
Since Neal asks about this in his comment, let me emphasize that when I say that proofs in the literature are "wrong" I mean that, although they are technically 100% correct, they don't correspond to the subjective way one has organized one's understanding of the subject.
For example, the definition I like for a finite  field extension $K/k$ to be separable is that it is étale i.e. that the tensor product with an algebraic closure of $k$ is split: $K\otimes_k\bar k\cong \overline {k} ^n$ .
I know this is rather idiosyncratic and of course I know the equivalence with the usual definition, but then I feel that long proofs that $\mathbb C\otimes _\mathbb R\mathbb C$ is not a field are "wrong" since I know,  by the  definition of separable  I have interiorized, that  $\mathbb C\otimes _\mathbb R\mathbb C=\mathbb C^2$.
Let me emphasize  that all this a completely personal and secret [till today :-)] attitude within myself and that I absolutely don't advocate that other mathematicians should change their definition of separable.


text:
Q: Unable to clear float:left I have the problem in this JS Fiddle.
Main problem is with the float: left property.
I have the code which allows to drag and drop the elements which have the float: left property. They are creating the problem when I want to placing the controls parallel in the next div area.
The problem is more clear, if you look into the JS Fiddle. Following are the steps to go through Fiddle

*

*click on the add div button

*it divides the red div into the two boxes

*now drag at least two or three upper controls(e.g firstname, last name) into the left side red box

*now drag the another control to the right side box

Here is the problem, the control in the right side div is placed left to the last control of the left side div.
Myhtml.html
<input type="button" class="Mybutton" value=" Add div" />

            FirstName :

            <input name="FirstName" type="text" id="FirstName" style="width:90%;;border:none;resize:none;float:left;">

            LastName :

            <input name="LastName" type="text" id="LastName" style="width:90%;;border:none;resize:none;float:left;">

            Web :

            <input name="Web" type="text" id="Web" style="width:90%;;border:none;resize:none;float:left;">

            Mobile :

            <input name="Mobile" type="text" id="Mobile" style="width:90%;;border:none;resize:none;float:left;">

            jot :

            <input name="jot" type="text" id="jot" style="width:90%;;border:none;resize:none;float:left;">

Myjquery.js
function makeDraggable() {
            $(".selectorField")
                .draggable({
                containment: $('body'),
                helper: "clone",
                stack: "div",
                cursor: "move",
                cancel: null
            });
        }

        $(function () {
            var _ctrl_index = 1001;
            // function docReady() {

            $(".Resizable").resizable({
                handles: 'e'
            });

            makeDraggable();

            $(".droppedFields").droppable({
                accept: ":not(.ui-sortable-helper)",

                drop: function (event, ui) {

                    var draggable = ui.draggable;
                    draggable = draggable.clone();
                    draggable.appendTo(this);
                    //   $(ui.draggable).hide();

                    makeDraggable();
                }
            });

            var count = 0;
            $('.Mybutton').click(function () {
                count++;
                if (count < 5) {
                    // alert("aa");

                    var a = $("

").appendTo("#Section1");
                    a.droppable();
                    a.resizable({
                        handles: 'e'
                    });
                    a.droppable({
                        accept: ":not(.ui-sortable-helper)",

                        drop: function (event, ui) {

                            var draggable = ui.draggable;
                            draggable = draggable.clone();
                            draggable.appendTo(this);
                            //   $(ui.draggable).hide();

                            makeDraggable();
                        }
                    });

                } else {
                    alert('No more divs to add');
                }
            });
        });

A: You are very, very close.  Simply use vertical-align like so:
 #Section1 > div {
     display: table-cell;
     /*width: 1%;*/
     border-right: 1px dotted red;
     text-align: center;
     vertical-align: top;  /* vertical-align to the rescue!!! */
 }

Just need a tiny fix, vertical-align will be your friend!! :)
http://jsfiddle.net/tdorbbv6/106/


text:
Q: Express js and Php Function I'm working on a project that uses expressjs, Php, Html and MongoDB
I have this code in my   "Index.Html"   File
<form action="/Login" method="POST">
  <input type="text" placeholder="name" name="Username">
  <input type="Password" placeholder="Password" name="Password">
  <button type="submit">Submit</button>
</form>

I have this code in my   "Server.js"   File (Expressjs)
app.post('/Login', (req, res) => {
   //to know that I really had recieve a data from my index.html
   console.log(req.body)
   //to collect data from my database (MongoDB)
   db.collection('User').find(req.body,{Username:"",password:""}).toArray(function(err, results) {
   //show result from the database
   console.log(results)

    //The Question Starts here.
  })
})

How can I send both of those data (req.body and result) to my php file? so I can Validate it.
and also how can I send the data back from the PhP back to the server so the server could send the data back to the client?

A: You can use fetch to post a request to a php server. Example from the docs:
fetch('flowers.jpg')
.then(function(response) {
  return response.blob();
})
.then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});


text:
Q: ScreenUpdating does not allow to close workbooks I have some problem with closing workbooks in my macro. I wanted to speed up my macro by using:
Application.ScreenUpdating = False
'my code
Application.ScreenUpdating = True

But when it finish, suddenly all workbooks which I have been using open together. I wanted to close them so I add * Workbooks.Close * lines. Unfortunately, error appears when VBA reaches this code line.It is because excel "can't see" my workbooks. When I close error windows and try to run closing lines once again everything works properly, because workbooks had enough time to open. Probably excel need some time to update and open all workbooks, so I should postpone my code. I have tried * Application.Wait * and * Do Until loop *, but it did't work. I also have tried to close those workbooks before screen updating but excel just  ignored those lines.
My last code lines:
Application.ScreenUpdating = True

Application.DisplayAlerts = False

Workbooks(wb_1).Close
Workbooks(wb_2).Close

Application.DisplayAlerts = True

Thanks in advance for help!

A: As Damian said,
try to add:
Workbooks(wb_1).Close savechanges:=false
Workbooks(wb_2).Close savechanges:=false

or true if needed


text:
Q: Log error messages in Oracle stored procedure We plan to configure a stored procedure to run as a batch job daily using Oracle DBMS scheduler package. We would like to know what would be the best way to log an error message when there is an error occured. Is logging to a temporary table an option? or is there a better option. Thanks in advance.

A: If you decide to roll your own logging and log into a table you might go the Autonomous Transaction route.
An Autonomous Transaction is a transaction that can be commited independently of the current transaction you are in.
That way you can log and commit all the info you want to your log table independently of the success or failure of your stored procedure or batch process parent transaction.
CREATE OR REPLACE PROCEDURE "SP_LOG" (
    P_MESSAGE_TEXT VARCHAR2
) IS
  pragma autonomous_transaction;
BEGIN

    DBMS_OUTPUT.PUT_LINE(P_MESSAGE_TEXT);

    INSERT INTO PROCESSING_LOG (
        MESSAGE_DATE,
        MESSAGE_TEXT
    ) VALUES (
        SYSDATE,
        P_MESSAGE_TEXT
    );
    COMMIT;

END;
/

Then if you call it like this, you can still get messages committed to your log table even if you have a failure and roll back your transaction:
BEGIN
  SP_LOG('Starting task 1 of 2');

  ... code for task 1 ...

  SP_LOG('Starting task 2 of 2');

  ... code for task 2 ...

  SP_LOG('Ending Tasks');

  ... determine success or failure of process and commit or rollback ...

 ROLLBACK;
END;
/

You may want to tidy it up with exceptions that make sense for your code, but that is the general idea, the data written in the calls to SP_LOG persists, but the parent transaction can still be rolled back.

A: You could use log4plsql http://log4plsql.sourceforge.net/and  change the choice later by configuration changes not code changes
The log4plsql page gives a list of various places it can log.
It also depends how applications and systems are monitored in your environment - if there is a standard way fir example a business I worked add used used irc for monitoring - then you might want a function that calls to that.

A: that depends on how you will deal with errors: if you just need to be notified, the email is the best option; if you need to manually continue process the error, the table is good choice.

A: You say that you don't have a lot of control over the DB environment to install logging packages - if this is the case then you'll be limited to querying the information in the dba_scheduler_job_run_details and dba_scheduler_job_log system views - you'll be able to see the history of executions here.  Unhandled exceptions will show up in the ADDITIONAL_INFO column.  If you need notification you can poll these views and generate email.


text:
Q: Programmatically set constraints to textViews created at run-time? The code below creates a varying amount of textViews at run-time depending on the number of keys in friendMap:
        generatedViews = new TextView[numberOfFriends];
        int count = 0;
        for (String k : friendMap.keySet()) {

            TextView textView = new TextView(this);
            textView.setVisibility(View.VISIBLE);
            textView.setText(k);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f);
            textView.setGravity(Gravity.CENTER);

            String mutual = friendMap.get(k);

            if (mutual.equals("no")) {
                textView.setBackgroundColor(Color.RED);
            } else {
                textView.setBackgroundColor(Color.GREEN);
            }
            linLayout.addView(textView);
            generatedViews[count] = textView;
            count++;
        }

My question is: how can I set constraints to the created textViews so they don't bunch?

A: It's simple:
Set the layout parameters of the LinearLayout with:
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(100, 20, 100, 20);
            linLayout.addView(textView, layoutParams);

A: As @TheWandered said you should probably use RecyclerView.
But if for some reason it's not an option, here is how you can do it:
First thing, you are going to have to generate ID for each TextView, so you can target the constraints and then:
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(constraintLayout);
constraintSet.connect(text_view_id,ConstraintSet.TOP, previous_text_view_id,ConstraintSet.BOTTOM,0);
// is equal to "layout_constraintTop_toBottomOf="previous_text_view_id"
constraintSet.applyTo(constraintLayout);


text:
Q: iOS - Add custom URI of our app to the event stored in calendar programmatically i have a scenario where i am adding the event in calendar from my application. i have a custom url scheme for my app as myapp://
the code i am using to store the event in calendar is
-(void)addEventToCalender
{
NSDateComponents *components = [[NSDateComponents alloc]init];
[components setYear:2014];
[components setMonth:6];
[components setDay:15];
[components setHour:10];
[components setMinute:15];

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *eventDateAndTime = [cal dateFromComponents:components];
NSLog(@"Event Date and Time : %@",eventDateAndTime);

EKEventStore *store = [[EKEventStore alloc]init];

EKEvent *event = [EKEvent eventWithEventStore:store];

event.title = @"ttrrpp Trip";
event.notes = @"Go to application myapp://";
event.startDate = eventDateAndTime;
event.endDate = [[NSDate alloc]initWithTimeInterval:600 sinceDate:eventDateAndTime];

[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
 {
     if (granted)
     {
         [event setCalendar:[store defaultCalendarForNewEvents]];
         NSError *err = nil;
         [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
         NSString *savedEventId = event.eventIdentifier;
         NSLog(@"Saved Event ID : %@",savedEventId);

     }
     else
     {
         UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"ttrrpp" message:@"You have denied to provide access to calender. No events will be added." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
         [alert show];
     }
 }];

}
The event is added in calendar but i want to pass the url of my app to the notes so that it opens my app when the link in event notes is clicked. Kindly help me.
Thanks in advance.

A: You are very close ;-) . Assuming you have defined your custom URL scheme in your .plist, add a 'host' and 'path' to your custom URL scheme being placed in event.notes. (eg. myapp://myhost/mypath) Then something like...
-(BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url { - deprecated
-(BOOL) application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

    if (!url) {
        return NO;
    }

    if([[url host] isEqualToString:@"myhost"])
    {
        //can also check [url path] if you want to
        //do whatever
    }

    return YES;
}

PS: deprecated method worked for me with iOS6/7, haven't tried new method.


text:
Q: Eclipse CORBA plugin howto I'm new to CORBA and I need to learn how to use it with C++.
I see that there is a CORBA plugin for Eclipse, is there some tutorial on how to use this plugin? Are there better ways to use CORBA with Eclipse? Or any other way without Eclipse ;-)
Thanks in advance,
Pedro

A: There should be a CORBA IDL 'compiler' or 'translator', that creates C++ code from CORBA's IDL, after that, all you have to do is use the code created by the CORBA IDL to C++ translator in order to communicate your distributed software components.
There are several implementations of these 'translators' here: http://patriot.net/~tvalesky/freecorba.html


text:
Q: Distribution of marginal Wiener process. Let $(W^1,W^2)$ be a two-dimensional Wiener process with correlation $\rho$. Let $\mathcal{F}^1_t$ be the filtration generated by $W^1$ up to $t$.
I would intuitively think that for $h$ measurable and integrable we have
$$
E[h(W^2_T) \lvert \mathcal{F}^1_T]  = E[h(W^2_T) \lvert W^1_T] ,
$$
since $W^1_T$ contains all the information in the path. I am though unable to prove it. Is it true and how do I go about showing it?


text:
Q: What calls Dispose() method in c# MSTest unit test? I currently reviewing a test class that uses MSTest and implements IDisposable. The test itself is testing a custom client and has an instance of

MockHttpMessageHandler by RichardSzalay.MockHttp

which implements the IDisposable interface.
The following code has been added at the bottom of the class and gets called after each test. I am looking to confirm what calls the Dispose method that is declared in the test class
public void Dispose()
{
    _mockHttpHandler.Dispose();
}

A: MSTest performs a type conversion check using the as operator and then calls the Dispose method in this case:
 private void RunTestCleanupMethod(object classInstance, TestResult result)
{
  MethodInfo methodInfo = this.Parent.TestCleanupMethod;
  try
  {
    try
    {
      if (methodInfo != null)
        methodInfo.InvokeAsSynchronousTask(classInstance, (object[]) null);
      Queue<MethodInfo> methodInfoQueue = new Queue<MethodInfo>((IEnumerable<MethodInfo>) this.Parent.BaseTestCleanupMethodsQueue);
      while (methodInfoQueue.Count > 0)
      {
        methodInfo = methodInfoQueue.Dequeue();
        if (methodInfo != null)
          methodInfo.InvokeAsSynchronousTask(classInstance, (object[]) null);
      }
    }
    finally
    {
      (classInstance as IDisposable)?.Dispose();
    }
  }


text:
Q: Axios response interceptor not working when a request interceptor is in use ReactJS I have a ReactJS project, where I'm using an axios interceptor to set a jwt token into each request that requires it. I'm also trying to use a response interceptor, which I've defined to be included in the same "custom" instance. However, the response interceptor doesn't trigger after any requests, as long as my request interceptor is active.
If I remove the request interceptor (by just commenting it out), my response interceptor starts working. It seems like my request interceptor is canceling out any further intercepting by axios.
My interceptor file exporting the custom axios instance including the intercept-logic:

import axios from 'axios'
import { utils } from './index'

let user = null
let token = null

const customAxios = axios.create({})

// Request interceptor
customAxios.interceptors.request.use(
  (req) => handleRequest(req),
  (e) => {
    console.log('Error from request interceptor: ', e.response)
    return handleError(e)
  }
)

// Response interceptor
customAxios.interceptors.response.use(
  (res) => handleResponse(res),
  (e) => {
    console.log('Error intercepted from response: ', e.response)
    return handleError(e)
  }
)

const handleRequest = (request) => {
  addTokenIfExists(request)
  // TODO: future custom request modifiers
  return request
}

const handleResponse = (response) => {
  console.log('Intercepted response:', res)
  // TODO: future custom response modifiers
  return response
}

const handleError = (e) => {
  // TODO: when this works for response add to Redux error variable to display in app
  if (e.response.status === 401) {
    console.log('Code was 401: Authorization error from response')
  }
  return Promise.reject(e)
}

const addTokenIfExists = (req) => {
  user = JSON.parse(window.localStorage.getItem('loggedUser'))
  token = `Bearer ${user ? user.token : null}`

  // Check if token is expired with every request, if it is, remove it from localStorage
  token = utils.checkIfTokenExpired(user, token)

  // Add token to each request if it's found
  if (token) {
    req.headers = {
      ...req.headers,
      Authorization: token,
    }
  }

  console.log('Intercepted request:', req)

  return req
}

export default customAxios

My user-service file, as an example using the custom axios instance:

import axios from '../services/interceptors'

const baseUrl = '/users'

const getUser = async (id) => {
  let res = null

  await axios
    .get(baseUrl + '/' + id)
    .then((req) => {
      res = req.data
    })
    .catch((e) => {
      return Promise.reject(e)
    })

  return res
}

const userService = {
  getUser,
}

export default userService

I'm planing to use the response interceptor to modify the errors and add custom error-objects for the front-end of my application, but for now I can't even get the response to print in my console from the handleResponse() function, unless i remove the request interceptor, as mentioned in the description of my problem.
Could someone help me understand why the response interceptor isn't getting triggered?
Edit: seems like there was a bug with past Axios version (0.21.2), updating to 0.25.0 resolved the issue.


text:
Q: Update array of document embedded A question if I want to update all documents embedded in a document, how could I do? because when you run the following command
.update({'sites':{$elemMatch:{'status':true}}},{$set:{'sites.$.status': false}},{multi:true})

only the first found embedded document is updated
documents example:
{
  '_id': 1,
  sites: [

    {'status':true,'url':'http://google.com'},
    {'status':true,'url':'https://university.mongodb.com'},
    {'status':true,'url':'https://docs.mongodb.org'}
]}

A: This isn't possible, the closes you can get is to update the entire element.  e.g.:
db.test.update({
    _id: 1
},
{
    $set: {
        sites: [
            {'status':true,'url':'http://1.example.com'},
            {'status':true,'url':'http://2.example.com'},
            {'status':true,'url':'http://3.example.com'},
        ]
    }
})


text:
Q: How to use SAGA ShapesToGrid via Processing in a Python plugin? I run these lines in my code:
vectorlayer_vector =  ftools_utils.getVectorLayerByName(inputLayer)
Elevation = self.lineAttrib.currentText()
cellSize = int(self.linePix.value())
outPath = self.inputLayerCombo3.text()
output = ftools_utils.getRasterLayerByName(outPath)

Processing.runAlgorithm("saga:shapestogrid", vectorlayer_vector, Elevation, 0, 0, 4, None, cellSize, output)

When I run, I get an tiff image but with nothing. The .aux file is not created and when I try to open the tiff image that I created appears this message:
c:...teste3.tif is not a supported raster data source
So, I guess that the output is wrong. What I have to do to get a correct output? What I missing?

I update my code but I have no results yet.
Please see if you can help me.
My code are:
inputLayer = self.inputLayerCombo.currentText()
Elevation = str(self.lineAttrib.currentText())
cellSize = int(self.linePix.value())
outPath = self.inputLayerCombo3.text()

Processing.initialize()
Processing.runAlgorithm("saga:shapestogrid", inputLayer, Elevation, 0, 0, 4, "10000.0,14000.0,50000.0,54000.0" , cellSize,outPath)

Is a simple code but I don't have any results. I don't know what else to do.
It doesn't create a raster.

A: If you look at the file "processing_qgis.log" in the folder ".qgis2/processing", it lists all the processed commands from Processing and their status(success, errors)
If I apply "Shapes to grid", leaving the field "Output extent(xmin, xmax,ymin,ymax)" empty (your None):

the result in "processing_qgis.log"  is:
ALGORITHM|Mon Nov 18 2013
16:57:17|processing.runalg("saga:shapestogrid","/Users/testbounds.shp","z",0,0,4,"266390.660211,273780.851652,151462.899477,154949.346806",100,"/Users/Shared/testshapegrid.tif")

*

*testbounds.shp - > your vectorlayer_vector

*"z" -> your Elevation

*"0,0,4" = Methods for multiple values, Method for Lines,Preferred Target Grid Type

*"266390.660211,273780.851652,151462.899477,154949.346806" -> Output extent(xmin, xmax,ymin,ymax) and None in your script

*100 -> cellSize

*shapegrid.tif ->  output

Your None must correspond to the bounding box of the shapefile:

[Leave blank to use min covering extent]


text:
Q: iScroll not working on iPhone for jquery show/hide I am building a phonegap application with iscroll used for scrolling. I am facing a problem when I dynamically append controls to a div and show/hide the div on click. The div shows up and then hides automatically. I have given the code samples below. Would greatly apperciate any help.
First I tried with scroll.refresh() alone, but since it did not work, I tried destroying and recreating according to a forum post in google. But, it does not work either.
HTML

JS
$('#search-user-type-div').hide();
$('#usertype-link').bind('click', function () {
    if ($('#search-user-type-div').is(":visible")) {
        $('#search-user-type-div').hide();
        $('#usertype-link').removeClass('open').addClass('close');
    }
    else {
        $('#search-user-type-div').show();
        $('#usertype-link').removeClass('close').addClass('open');
    }
    //scroll.refresh();
    searchpreferences.rebuildScroll();
})

rebuildScroll: function () {
    scroll.destroy();
    scroll = null;
    scroll = new iScroll('wrapper', { vScrollbar: true, hScrollbar: false, vScroll: true, hScroll: false, onBeforeScrollStart: null });

    //setTimeout(function () {
    scroll.refresh();
    //}, 0);
}

Any help would be appreciated.
Priyan

A: I don't have an exact solution, but I recommend to use the most recent version of iScroll (v5). It was totally rebuild and maybe fixes your problem.


text:
Q: Dielectric in Parallel Plate Capacitor Given a parallel plate capacitor of width $w$, length $l$, with a dielectric moving along the length $l$. Let the dielectric be from $x$ onwards.
The capacitance will be $\frac{w \epsilon_0}{d} (\epsilon_r l - \chi_e x)$. Griffiths (p. 195) says that the total charge $Q$ in the $C=\frac{Q}{V}$ expression is constant as the dielectric moves. But $Q$ here refers to the free charge, and the free charge definitely increases as you move the dielectric in increasing $x$. What am I misunderstanding?

A: If the plates of the capacitor are isolated then the total amount of free charge on the capacitor plates cannot change.
Put another way, if the capacitor pales are isolated where could more/less free charge come from / go to?
The situation would be different if there was a voltage source connected to the plates.
In that case the free charge on the plates would change to ensure that the potential difference across the plates is kept constant.


text:
Q: How do I query UUID values without having to explicitly cast them to string in HTSQL I have a table that is indexed by a UUID field, using postgres' uuid-ossp extension, everything running on a python application. Every time I filter the UUID field I have to explicitly cast the uuid field:
htsql = HTSQL('pgsql:///my_database')
htsql.produce("/product.filter(string(id) = '00002094-b1c3-11e3-92b8-6bb3666a756f')")

If I do not cast the id I have the following error:
htsql.produce("/product.filter(id = '00002094-b1c3-11e3-92b8-6bb3666a756f')")

Cannot coerce values of types (opaque, untyped) to a common type
While translating:
    /product.filter(id = '00002094-b1c3-11e3-92b8-6bb3666a756f')

It seems HTSQL do not recognize UUID type. So my question is:
Is there any way to tell HTSQL how to recognize a UUID? Can I do this on the command line interface as well?

A: By looking at HTSQL's source code, my current solution to this very problem is using its instrospection classes to tell HTSQL to recognize UUIDs as Text:
class IntrospectPGSQLUUIDDomain(IntrospectPGSQLDomain):
    call(('pg_catalog', 'uuid'))

    @classmethod
    def __enabled__(cls):
        return True

    def __call__(self):
        return TextDomain()

And then telling HTSQL to instrospect it after creating the database connection:
htsql = HTSQL('pgsql:///my_database')
with htsql:
    introspect()

This solves my problem on the python application, but I still have to figure out a way to do this on the command line.


text:
Q: Why in exposed WSDL of Web Service,  tag is changed to an  tag I'm new in SOAP and I'm developing a hello world web service using Camel and Springboot.
In the WSDL file of my service I'm using <xsd:include> to refer to my XSD file
<wsdl:types>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        targetNamespace="http://com/blog/demo/webservices/accountservice" >
        <xsd:include namespace="http://com/blog/demo/webservices/accountservice"
                     xmlns="http://com/blog/demo/webservices/accountservice"
                     schemaLocation="../schema/AccountService.xsd">
        </xsd:include>
    </xsd:schema>
</wsdl:types>

When I run the service, in the exposed WSDL the <xsd:include> tag is changed to <xsd:import>
<wsdl:import location="http://localhost:8090/soap-api/service/accounts?wsdl=AccountService.wsdl" namespace="http://www.briansdevblog.com/Accounts/"> </wsdl:import>

I'd like to know why this happens and how can I avoid this behavior
Here is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.briansdevblog</groupId>
    <artifactId>boot-cxf-soap-demo</artifactId>
    <packaging>jar</packaging>
    <version>1.0.0</version>
    <properties>
        <cxf.version>3.3.2</cxf.version>
        <java.version>1.8</java.version>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http-jetty</artifactId>
            <version>${cxf.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-features-logging</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-codegen-plugin</artifactId>
                <version>${cxf.version}</version>
                <executions>
                    <execution>
                        <id>generate-sources</id>
                        <phase>generate-sources</phase>
                        <configuration>
                            <sourceRoot>${basedir}/src/main/java</sourceRoot>
                            <wsdlOptions>
                                <wsdlOption>
                                    <wsdl>${basedir}/src/main/resources/wsdl/Accounts.wsdl</wsdl>
                                </wsdlOption>
                            </wsdlOptions>
                        </configuration>
                        <goals>
                            <goal>wsdl2java</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
Q: Getting embedded nul string while reading an excel csv I'm trying to open an Excel CSV file within R Studio but I get this error:

Error Is this a valid CSV file? embedded nul in the string: 'C\0a\0m\0p\0a\0g\0n\0e\0_\0N\0o\0C\0a\0r\0a\0v\0a\0g\0g\0i\0o\0_\0C\0o\0s\0t\0o\0>\00'

the file is generated automatically by the Google Ads platform as Excel csv and it works normally with Excel but in order to open it on R Studio I have to convert it as .xlsx
is there a way to bypass this or to convert the file without opening it?
otherwise the script which is based upon this file needs a manual passage to convert the source file

A: What function are you using to open it? Check your file and see if you have other commas within a column value; this may confuse the function. Also, it is worth trying to use the "Import dataset" option in the environment window within Rstudio. Try to use the readr option and adjust your import options until you have it correct. Check the package RAdwords maybe you can extract your Google Ads information without the CSV exporting step.


text:
Q: How to hide command prompt window when using Exec in Golang? say i have the following code, using syscall to hide command line window
process := exec.Command(name, args...)
process.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
err := process.Start()
if err != nil {
    log.Print(err)
}

but when i compiled it and tried to run it in Windows, command line window showed up again
what can i do to prevent command line window from appearing?
PS i already know how to compile golang source into a Windows GUI executable using go build -ldflags -H=windowsgui, but doing so only ensures the program itself doesn't bring up a command line window, Exec will show those windows anyway

A: If you build with -ldflags -H=windowsgui, each exec.Command will spawn a new console window.
If you build without the flag, you get one console window and all exec.Commands print into that one.
My current solution is thus to build without the flag, i.e. have a console window on program start, then immediately hide the console window with this code at the start of my program:
import "github.com/gonutz/w32/v2"

func hideConsole() {
    console := w32.GetConsoleWindow()
    if console == 0 {
        return // no console attached
    }
    // If this application is the process that created the console window, then
    // this program was not compiled with the -H=windowsgui flag and on start-up
    // it created a console along with the main application window. In this case
    // hide the console window.
    // See
    // http://stackoverflow.com/questions/9009333/how-to-check-if-the-program-is-run-from-a-console
    _, consoleProcID := w32.GetWindowThreadProcessId(console)
    if w32.GetCurrentProcessId() == consoleProcID {
        w32.ShowWindowAsync(console, w32.SW_HIDE)
    }
}

See this thread for the details about the process ID stuff.
What happens is that all exec.Commands now print their output to the hidden console window instead of spawning their own.
The compromise here is that your program will flash a console window once when you start it, but only for a brief moment before it goes into hiding.

A: Instead of hiding the console window, you should be able to prevent it with:
cmd := exec.Command(...)
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: 0x08000000} // CREATE_NO_WINDOW

A: There is a better solution, which can run exec.Command() without spawn a visible window, ( ͡° ͜ʖ ͡°).
Here is my code:
Firstly import "syscall"
cmd_path := "C:\\Windows\\system32\\cmd.exe"
cmd_instance := exec.Command(cmd_path, "/c", "notepad")
cmd_instance.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
cmd_output, err := cmd_instance.Output()

Origin:
https://www.reddit.com/r/golang/comments/2c1g3x/build_golang_app_reverse_shell_to_run_in_windows/


text:
Q: WCF service reference GET request I add WCF service as service reference on my project and try to call get methods. I got error "(405) Method Not Allowed." how I can modify the request verb from POST to GET.
MyServiceClient client = new MyServiceClient();
var testObj = client.GetCategories();


text:
Q: Can't import python libraries with Crontab I'm trying to run my python scripts with Crontab.
The problem is I can't import the libraries.
I tried with three different crontab lines:
 * */1 * * * /Library/Frameworks/Python.framework/Versions/2.7/bin/python /Users/martinbouhier/Desktop/Github/klipfolio/Scripts/clientes_us.py
 * */1 * * * python /Users/martinbouhier/Desktop/Github/klipfolio/Scripts/clientes_us.py
 * */1 * * * /usr/bin/python /Users/martinbouhier/Desktop/Github/klipfolio/Scripts/clientes_us.py

I received an email with:
Subject: Cron <martinbouhier@ops-mac> python /Users/martinbouhier/Desktop/Github/klipfolio/Scripts/clientes_ar.py
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=martinbouhier>
X-Cron-Env: <USER=martinbouhier>
X-Cron-Env: <HOME=/Users/martinbouhier>
Date: Thu, 20 Sep 2018 11:12:01 -0300 (-03)

Traceback (most recent call last):
  File "/Users/martinbouhier/Desktop/Github/klipfolio/Scripts/clientes_ar.py", line 10, in <module>
    from Modulos_epl.logins_us_ar import (
  File "/Users/martinbouhier/Desktop/Github/klipfolio/Scripts/Modulos_epl/logins_us_ar.py", line 2, in <module>
    import requests
ImportError: No module named requests


text:
Q: Multiple windows accessing same terminal prompt There are numerous tools for using numerous terminal prompts from a single window, like gnu screen---but I'm wondering about the opposite.  I'd like to access the same prompt from different windows.  In particular, I'm using NoMachine to run a virtual desktop where there is a particular tty I'd like to access from a normal SSH session.  Is there a way to attach to the same tty session from the SSH session?

A: You can use either screen or tmux to attach to the same (remote) tty from multiple other source (client) locations.
But you might be asking how to make either screen or tmux gain control of an existing tty.  I don't know how to do that, but you could re-parent an existing process (perhaps even a shell) to a tty that is owned by screen or tmux using reptyr.  See one of multiple references on use of reptyr: here orhere.  Others exist, I'm sure.


text:
Q: How do I auto adjust the font size of a cells content to fit the tableview width? I have a table view that shows the user what trips they have logged in. Except if the trip name is too long and doesn't fit within the table views width, it doesn't fully show. I would hope it's possible to simply resize the font so that it can fit within the table view, similar to the "Adjust to Fit" option that text fields have. Thanks!

A: As long as your label is properly constrained within the tableViewCell, you can simply set:
label.adjustsFontSizeToFitWidth = true

Or if you're using the default UITableViewCell's textLabel, then in cellForRowAtIndexPath:
cell.textLabel?.adjustsFontSizeToFitWidth = true


text:
Q: Cannot get SDL_LoadBMP to display an image(C++)?     void MainGame::drawGame() {
    glClearDepth(1.0);
    // clear colour and depth buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    windowSurface = SDL_GetWindowSurface(_window);
    menuImage = SDL_LoadBMP("\Liam C\Documents\Visual Studio 2015\Projects\graphicsPractice\graphicsPractice\ForehalenIntro_Screen.bmp");
    if (menuImage == NULL) {
        fatalError("Unable to load bitmap, 'ForhalenIntro_Screen.bmp'!");
    }
    //swap buffer/window displayed and draw to screen
    SDL_GL_SwapWindow(_window);
}

// Wont exit unless _gameState is equal to EXIT
void MainGame::gameLoop() {
    while (_gameState != GameState::EXIT) {
        procInput();
        drawGame();
    }

}

I am trying to display a bitmap image onto my window. I created an SDL_Surface for my window, and an SDL_Surface for my image initialized to NULL. My error, "Unable to load bitmap, 'ForhalenIntro_Screen.bmp'!" is returning, so I know the code is failing at the line where menuImage is assigned the bitmap function with the path to the image as the argument. I've double checked the file name, location and path. I've tried having just the filename as the path. The file is in the same folder as my vcrxproj file and main.cpp file. Where have I gone wrong? I am not getting any syntax errors and I have obviously included the necessary header files.
EDIT:
I've now also tried it with SDL_image but it still didn't work.

A: Your issue here is unintentional escaping (and most likely an incorrect path).
menuImage = SDL_LoadBMP("\Liam C\Documents\Visual Studio 2015\Projects\graphicsPractice\graphicsPractice\ForehalenIntro_Screen.bmp");

Assuming this is in the default directory Visual Studio creates for you, the correct path would be: "C:\Users\Liam C\Documents\Visual Studio 2015\Projects\graphicsPractice\graphicsPractice\ForehalenIntro_Screen.bmp"
In most programming languages, a \ is used to create a special character that cannot normally be typed, such as a null character ('\0') or a Unicode character (u16'\u263A' or u32'\U0001F60A'). So your use of the \ character in your string is (accidentally) trying to make special characters from '\L', '\D', '\V', '\P', '\g', '\g', and '\F'.
You can either double up the backslashes ('\\' makes a \ character) or change the separators to forward slashes:
menuImage = SDL_LoadBMP("C:\\Users\\Liam C\\Documents\\Visual Studio 2015\\Projects\\graphicsPractice\\graphicsPractice\\ForehalenIntro_Screen.bmp");
// OR
menuImage = SDL_LoadBMP("C:/Users/Liam C/Documents/Visual Studio 2015/Projects/graphicsPractice/graphicsPractice/ForehalenIntro_Screen.bmp");


text:
Q: python3 reversi game code I have a 2 files for the reversi game for python 3. My first file is called reversi.py.
It implements (a) the high level control of the game play (e.g., getting moves from the computer player and the human player, determining whether a player runs out of moves, determining the end of the game and declare the result of the game), (b) the rendering of the game through QuickDraw, as well as (c) taking the input from the human player.
Heres the file:
from game import *
from copy import deepcopy
from time import sleep
import sys
from subprocess import PIPE,Popen
from threading import Thread
from queue import Queue,Empty

def ParseEvent() :
    r=receive()
    if r==None:return None,None
    s=[x.rstrip().strip() for x in r.split(":")]
    return s[0],s[1]

def highlight(move):
    send( 'color 255 0 0\n circle %d %d 11\n' % \
        (240+(move[0]+0.5)*40, 100+(move[1]+0.5)*40))

def stone(x,y,turn):
    send('color %d %d %d\n' % \
        (255*(1-turn),255*(1-turn),255*(1-turn)))
    send('fillcircle %d %d %d\n' % \
        (240+(x+0.5)*40, 100+(y+0.5)*40, 17))

def draw(board):
    send('color 20 20 20\n clear\n color 15 15 100\n')
    send( 'button button1 600 20 100 20 "Calculate W:L"')
    send('fillrect %d %d %d %d\n' % (240,100,320,320))
    send('color 0 70 0\n')
    for i in range(1,8):
        send('line %d %d %d %d\n' %\
            (240+i*40,100, 240+i*40,420))
        send('line %d %d %d %d\n' %\
            (240, 100+i*40, 560, 100+i*40))
    for i in range(8):
        for j in range(8):
            if board[i][j] >= 0:
                stone(i, j, board[i][j])

def makeBoard():
    board = []
    for i in range(8):
        board.append([])
        for j in range(8):
            board[i].append(-1)
    board[3][3], board[4][4], board[3][4], board[4][3] = 0,0,1,1
    return board

def _queueqd(ip,q):
    for line in iter(ip.readline,b''):
        q.put(line)
    ip.close()

def send(*args):
    s=""
    for a in args:
        s+=str(a)
        if s[-1]!=" ":s+=" "
    if s!="":
        op.write((s[:-1]+"\n").encode('utf-8'))
    else:
        op.write("\n".encode('utf-8'))

def receive():
    try:
        return qdq.get_nowait().decode('utf-8')[:-1]
    except Empty:
        return None
def running():
    return qdp.poll()==None

def simulate(numTimes=1000):
    w=0
    b=0
    for i in range(numTimes):
        goesFirst=i&1
        gb=makeBoard()
        sg = Game(gb, goesFirst)
        count = 4
        while count < 64: # max num of stones is 64
            sg.get_moves()
            if sg.moves == []:
                sg.turn = 1 - sg.turn
                sg.get_moves()
                if sg.moves!= []:
                    continue
                sg.turn = 1 - sg.turn
                break
            if sg.turn==0:
                mv = sg.select_move()
            else:
                mv= sg.moves[int(len(sg.moves)*random.random())]
            sg.play_move(mv)
            sg.turn=1-sg.turn
            count+=1
        num_white, num_black = sg.final_result()
        if num_white>num_black:w+=1
        if num_black>num_white:b+=1
    return w/b

try:
    qdp = Popen("java -jar quickdraw.jar",shell=True,stdout=PIPE,stdin=PIPE)
    op=qdp.stdin
    qdq = Queue()
    qdt = Thread(target=_queueqd,args=(qdp.stdout,qdq))
    qdt.daemon=True
    qdt.start()
except:
    print("quickdraw.jar must be in the same directory as this python script.")
    quit()

send( "mouseclick True\n" )
# initialize the board, get ready for the game

board =makeBoard()
draw(board)

# game time, let's play...
# human player is white and moves first

g = Game(board, 0)
count = 4
while count < 64: # max num of stones is 64
    g.get_moves()
    if g.moves == []:
        g.turn = 1 - g.turn
        g.get_moves()
        if  g.moves!= []:
            continue
        g.turn = 1 - g.turn
        break
    if g.turn == 0:
        while running():
            event, val = ParseEvent()
            if event == "MouseClicked":
                val=[ int(x) for x in val.split(",")]
                move = [(val[0]-240)//40, (val[1]-100)//40]
                if move in g.moves: break
            elif event=="ButtonClicked":
                send("colour 20 20 20\nfillrect 600 50 200 50\ncolour 255 255 255")
                send('text "Calculating..." 600 80')
                r=simulate()
                send("colour 20 20 20\nfillrect 600 50 200 50\ncolour 255 255 255")
                send("text ",'"W:L=',r,'"'," 600 80")
    else:
        move = g.select_move()
    stone(move[0], move[1], g.turn)
    highlight(move)
    sleep(1)
    board = deepcopy(g.board)
    g.play_move(move)
    g.turn=1-g.turn
    for i in range(8):
        for j in range(8):
            if board[i][j]!= g.board[i][j]:
                stone(i,j,1-g.turn)
    sleep(1)
    stone(move[0], move[1], 1-g.turn) # redraw to de-highlight
    count += 1

# game over, let's announce the result:

num_white, num_black = g.final_result()
send('color 255 255 255\n')
if num_black > num_white:
    send('text "black wins!" 370 470\n')
elif num_black < num_white:
    send('text "white wins!" 370 470\n')
else:
    send('text "tie!" 390 470\n')
send('text "black:" 325 500\n')
send('text "%d" 375 500\n' % num_black)
send('text "white:" 425 500\n')
send('text "%d" 475 500\n' % num_white)

while running():
    pass

And this file is done. My second file is called Game.py. The first file imports this one for the moves the player can make.
import random

class Game:
    delta = [[0,-1],[1,-1],[1,0],[1,1],[0,1],\
                [-1,1],[-1,0],[-1,-1]]

    def __init__(self, board, turn):
        self.board = board
        self.turn = turn
        self.moves = self.get_moves()

    def check_move(self, move, d):
        pass #which I have to figure out!

    def get_moves(self):
        pass ##################

    def select_move(self):
        pass ##################

    def play_move(self, move):
        m,n=move[0],move[1]
        for d in range(8):
            i, j = m, n
            if self.check_move(move,d):
                i, j = i+self.delta[d][0], j+self.delta[d][1]
                while self.board[i][j] == 1-self.turn:
                    self.board[i][j] = self.turn
                    i, j = i+self.delta[d][0], j+self.delta[d][1]
        self.board[m][n]=self.turn

    def final_result(self):
        black, white = 0, 0   # color 0 is white
        for i in range(8):
            for j in range(8):
                if self.board[i][j] == 0: white += 1
                elif self.board[i][j] == 1: black += 1
        return white,black

I am supposed to fill in the three missing definitions. The check move(self, move, d) method checks whether a given move is validated along a certain direction d, assuming the given turn of play. It returns True or False accordingly. In other words, if starting at the grid specified by move, a number of opponent stones along the direction d can be captured, then a True should be returned. This method may be convenient to use in other methods such as get moves() and play move().The get moves(self) method finds all the valid moves for the current turn, and returns them in a list. For example, if there are two moves at [2,4] and [3,6], then the return value should be [[2,4], [3,6]]. The select move(self) method picks a move from self.move and returns it. Apparently the easiest way is to return a random move. SO basically I know what each of the three functions should do and why they are needed for the game, but I don't know exactly how to code them... any help or guidance would be appreciated!!
so basically I have this is a base for "check_move" function:
def check_move(self,move,d):
    check neighboring tile:
        if empty:
            False #can't move
        if enemy present:
            while there are enemy pieces:
                True #can move

is that the right direction?
ALso for the get_moves I have this reasoning:
def get_moves(self): # grid[ij]
    for i in range
    for j in range
        check for possible move directions:
            check move again:
                if yes then append[ij] to a list of valid moves
        return list of valid moves

A: I think you should first, before you start writing code, think about what defines a valid move in Reversi. Try writing in English what the definition is. For instance, here's the conditions I can think of in a few seconds:

*

*The tested tile must be empty

*The tested tile must have an enemy piece next to it in the selected direction.

*Past that enemy piece in the given direction, there may be more enemy pieces.

*Past all the enemy pieces, there must be a friendly piece (not an empty space or the edge of the board).

I'm not sure if that's comprehensive or not, but it's a reasonable start. Then, think about how to test each of those. Some may easily flow from each other, while others may be separate tests.
I'd also not be shy about reading and adapting the existing code you've been given. For instance, the play_move method just below the method's you're going to implement does a very similar loop to what you're going to want in your check_move method (though it's flipping the tiles, rather than checking that they can be flipped).


text:
Q: dispatch_time calculations are failing on Apple Silicon I have some Objective-C code that works on Intel Macs, but fails on Macs with the M1 chip.
dispatch_time_t now = dispatch_time(DISPATCH_TIME_NOW, 0);
dispatch_time_t delta = (uint64_t)(1 * NSEC_PER_SEC);
dispatch_time_t when = dispatch_time(now, delta);

NSLog(@"now: %llu", now);
NSLog(@"delta: %llu", delta);
NSLog(@"when: %llu", when);
NSLog(@"real delta: %llu", when-now);

It'll print something like this:
now: 1272914827933
delta: 1000000000
when: 1272938827933
real delta: 24000000

1272914827933 + 1000000000 = 1273914827933, NOT 1272938827933. Why the hell is this failing, and only on some Macs?
Edit: this is also broken when running on an actual iPhone device. Just create a new Xcode project using Obj-C, paste the code into the AppDelegate, and run on your phone.

A: dispatch_time() second argument (delta) is in nanoseconds, however the returned dispatch_time_t depends on the CPU architecture. For Intel, the returned value is measured in nanoseconds. For Apple Silicon, the value is in ticks.
Since the two values are not measured the same way, you can not calculate numbers this way.
Here is a new test. Notice mac_absolute_time is always in advance of the dispatch_time now time.
// cc -framework Foundation  -o dispatch_time dispatch_time.m
#include <time.h>
#include <mach/mach_time.h>
#import <Foundation/Foundation.h>
int main() {
    dispatch_time_t now = dispatch_time(DISPATCH_TIME_NOW, 0);
    dispatch_time_t delta = (uint64_t) (1 * NSEC_PER_SEC);
    dispatch_time_t when = dispatch_time(now, delta);

    NSLog(@"mac_absolute_time: %llu", mach_absolute_time());
    NSLog(@"now: %llu", now);
    NSLog(@"delta: %llu", delta);
    NSLog(@"when: %llu", when);
    NSLog(@"invalid: when-now delta: %llu", when-now);
    return 0;
}