text:
Q: How to save files onto an iPhone? I have a question that most of you might find a little odd. I am making an application for OS X, but I need it to write text files into an iPhone folder. I know the iPhone will have to be connected to the computer, and I do not think that emailing will work.
I thought it would be as simple as finding a path to the iPhone while it was connected (such as /iPhone/Documents), but I cannot figure out what the path is. If anybody can tell me how to find the path, or can give me a link to some useful information, I will be very greatful
EDIT: although it was not the answer I wanted, I got what I needed. I think all of these answers gave me an equal amount of information, so I had a hard time choosing which answer to accept. I accepted the one that provided me with an alternative way to get the files onto the iPhone. Thanks for all of the help, everyone!

A: That's not going to be possible. The iPhone connects over a proprietary(-ish) connection to iTunes, so you don't have any access into the iPhone's filesystem in your custom app. Besides which, apps in the iPhone have separate document folders so there isn't a single "documents" location on the device.
If you're writing your own iPhone app and want to support sharing documents with the Mac, you can either implement a Bonjour-based syncing service, sync via DropBox or iDisk, or use iTunes File Sharing. The options and trade-offs are well documented in this technote.

A: You will only be able to transfer files to and from your application using iTunes.
In order to get this to work your app must register for sharing documents in the Info.plist file by setting the UIFileSharingEnabled key to YES. When this is done your app will when installed and the device in connected show up on the "Application" tab in iTunes at the bottom. Highlight the app in the list to the left, and drag and drop files to the list on the right.
This way any file stored in the applications documents folder will be visible to iTunes, and any file copied to the device in iTunes will show up in the documents folder. You find the documents folder in your app like this:
NSArray* paths = NSSearchPathForDirectoriesInDomains(
                     NSDocumentDirectory, NSUserDomainMask, YES);
NSString* path = [paths lastObject];

A: The iPhone doesn't have a mass storage mode, as Apple wants iTunes to be the ONLY method of transferring files to/from the iPhone. Maybe iTunes has an API for this that you can exploit, but otherwise the only way to get access to the file system in there is on jailbroken devices or via apps


text:
Q: How to count all the rows in a fixed range containing a specific word in one of the cells and the sum of other two cells being greater than a const? I've made an Excel sheet to ease some calculations, but I'm stuck to the point explained in the title. The data is a list of rows containing a date, two names, and two numbers, like the following one:

and so on.
I do need a formulae capable to count all the rows containing for example "Jane" where amount1+amount2 > 4.
So far I've made some test with COUNTIFS(...): this is a working example of a formula which counts all the rows containing the word "Jane" in both NameA and NameB fields where amount1 > 0 and amount2 > 0:
=SUM(COUNTIFS(A1:A100,"Jane",D2:D100,&">0",E2:E100,&">0"),COUNTIFS(B1:B100,"Jane",D2:D100,&">0",E2:E100,&">0"))

Same approach doesn't seem to work trying to search for the sum of the two amount fields, as follows:
=SUM(COUNTIFS(A1:A100,"Jane",D2:D100,"+"&E2:E100"&>4"),COUNTIFS(B1:B100,"Jane",D2:D100,"+"&E2:E100"&>4"))

A: COUNTIFS does not work with addition like that.  One will need to switch to SUMPRODUCT:
=SUMPRODUCT(((A1:A100="Jane")+(B1:B100="Jane")>0)*(D2:D100+E2:E100>4))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Soft wdt Reset - ESP8266 / NodeMCU using Stepper motor I'm running very basic code and my ESP8266 times out during the stepper motor function. I get a "Soft wdt Reset" about 1600 ms into the myStepper.step function call.
The program works for a MyStepper.setSpeed of 38, but not for 37. This happens on two out of two boards I've tried. Is there a way around this problem? I'm using the Arduino programming software, code is below.
#include <Stepper.h>

const int stepsPerRevolution = 200;
unsigned long startT;

// initialize the stepper library:
Stepper myStepper(stepsPerRevolution, 14, 12, 13, 15); //D5, D6, D7 & D8

void setup() {
  // set the speed at in rpm:
  myStepper.setSpeed(37); //38 good (~1571 ms), 37 bad (~1614 ms)

  // initialize the serial port:
  Serial.begin(9600);
  Serial.println("Started stepper_oneRevolution_mk-------------------------");
}

void loop() {
  startT=millis();
  // step one revolution  in one direction:
  Serial.print("clockwise took: ");
  myStepper.step(stepsPerRevolution);
  Serial.println(millis()-startT);
  delay(1000);
}

A: The Watchdog Timer is complaining you are hogging the processor for too long.
myStepper.step() is blocking, so other processes can't use the processor until the motor has finished moving.
During this time, processes like WiFi communication and managing the TCP/IP stack also can't run, and the Watchdog Timer is there to reset the ESP8266 in such cases.
You can avoid this by making the stepper motor move just a few steps per loop, and add a yield() if necessary, or up the speed so it makes a full rotation before the watchdog gets angry.
You could try a quick & dirty way by doing 20 steps, then a short delay() or a yield(), and do that 10 times in its own for loop. You would have to experiment to arrive at something that doesn't trigger the watchdog, and compensate the time measurements you do.
You could also use an Arduino or an ESP that has an extra core dedicated to the WiFi, or find a stepper library that isn't blocking.

A: This is how I solved this issue.

*

*I could step the motor once in the time period allowed by watchdog

*So instead of telling the motor to step 30 times

*

*myStepper.step(stepsPerRevolution * 30);

*I tell it to step 1 revolution, 30 times. :)

*

*The key here is calling yield() between each revolution

Oversimplified
int steps = 30;
while(stepsTaken < steps){
    yield(); // Let other things run
    myStepper.step(-stepsPerRevolution * 1);
    stepsTaken++;
}

Yielding for ESP8266 (sparkfun)
More complete example. This is missing all the wifi and mqtt bits but should give you the gist.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
// D1 and D2 is set by the Board selection
// It will error as not defined if you have the wrong board
// specified in the Arduino ID
#include <Stepper.h>

// I need to be able to complete this before watchdog runs
const int stepsPerRevolution = 800;

// First Pin is Step
// Sec Pin is Dir
Stepper myStepper(stepsPerRevolution,D1,D2);

// you need to define your mqtt client, wifi ect.

// This is the callback you define for your mqtt client
// client.setCallback(callback);
void callback(char* topic, byte* message, unsigned int length) {
StaticJsonDocument<256> messageTemp;
deserializeJson(messageTemp, message, length);

if (String(topic) == "esp32/output") {
    const char* dir = messageTemp["dir"];
    int steps = messageTemp["steps"];
    int stepsTaken = 0;
    while(stepsTaken < steps){
      yield();
      if(String(dir) == "up"){
        Serial.println("up");
        myStepper.step(stepsPerRevolution * 1);
      }
      else if(String(dir) == "down"){
        Serial.println("down");
        myStepper.step(-stepsPerRevolution * 1);
      }
      stepsTaken++;
    }
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(D1,OUTPUT);
  pinMode(D2,OUTPUT);
  // set the speed at 60 rpm:
  myStepper.setSpeed(60);

  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

}


text:
Q: How to get Array Items inside of List c# How to get Array Items inside of List c#
IEnumerable<object> enumerable = c1._getbrandrequest(object[]);

List<object> brand = enumerable.Cast<object>().ToList();

List<Brand> brands = new List<Brand>();

for (int i = 0; i <= enumerable.Count(); i++)
{

    var brnd = enumerable.ElementAt(i);

    // brnd (intellisense only produce)
    // brnd. { Equals, GetHashCode, GetType, ToString }

}

Image of ArrayItems from Web Services
thanks in Advance!

A: If enumerable contains Brand objects, then what you need is cast the element returned by enumerable.ElementAt(i):
var brnd = enumerable.ElementAt(i) as Brand;

A: I think your code can be a bit cleaner in this way:
IEnumerable<object> enumerable = c1._getbrandrequest(object[]);
List<Brand> brands = enumerable.OfType<Brand>().ToList();

foreach (Brand brnd in brands)
{
  // Do things with brnd.
}

The OfType only returns objects that have a runtime type Brand, and the result is an IEnumerable, the ToList() makes them into a fresh list.

A:         var enumerable = c1._getbrandrequest( Object[] );

        List<Brand> brands = new List<Brand>();

        foreach (var brnd in enumerable)
        {
            Brand model = new Brand();

            model.sid = brnd.sid;

            brands.Add(model);

        }


text:
Q: USB stick: medium not found Trying to flash a USB with a bootable OS.
lsblk does not detect the disk. ls /dev/disk/by-id/ reveals the disk lives at /dev/disk/by-id/usb-NAND_USB2DISK-0:0.
sudo fdisk /dev/disk/by-id/usb-NAND_USB2DISK-0\:0
and
sudo fsck /dev/disk/by-id/usb-NAND_USB2DISK-0\:0
each fail with: No medium found while trying to open /dev/sda
What concept am I missing?


text:
Q: Fatal exception main I am building an app which convert different units and I'm getting the "Fatal exception main" message, but my code runs as far as starting up the app and showing the four buttons, but when you click on either button it crashes. I have no other errors.
MainActivity:
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.lacrym0sadevelopment.convertix";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void unitLength(View view) {
    Intent intent = new Intent(this, CalculateLength.class);
    EditText editText = (EditText) findViewById(R.id.button1);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}// unitLength

public void unitWeight(View view) {
    Intent intent = new Intent(this, CalculateWeight.class);
    startActivity(intent);
}// unitWeigth

public void unitVolume(View view) {
    Intent intent = new Intent(this, CalculateVolume.class);
    startActivity(intent);
}// unitVolume

public void unitSpeed(View view) {
    Intent intent = new Intent(this, CalculateSpeed.class);
    startActivity(intent);
}// unitSpeed

}// MainActivity

CalculateLength:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class CalculateLength extends Activity {

private EditText text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    text = (EditText) findViewById(R.id.editText1);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void calculate(View view) {

    RadioButton feetButton = (RadioButton) findViewById(R.id.radio0);
    RadioButton metreButton = (RadioButton) findViewById(R.id.radio1);
    RadioButton kmButton = (RadioButton) findViewById(R.id.radio2);
    RadioButton milesButton = (RadioButton) findViewById(R.id.radio3);

    if (text.getText().length() == 0) {

        Toast.makeText(this, "Enter a Value", Toast.LENGTH_LONG).show();
    } else {

        double inputValue = Double.parseDouble(text.getText().toString());

        if (feetButton.isChecked()) {
            text.setText(String.valueOf(convertToFeet(inputValue)));

            feetButton.setChecked(true);

            metreButton.setChecked(false);

            kmButton.setChecked(false);

            milesButton.setChecked(false);

        }
        if (metreButton.isChecked()) {
            text.setText(String.valueOf(convertToMetre(inputValue)));

            feetButton.setChecked(false);

            metreButton.setChecked(true);

            kmButton.setChecked(false);

            milesButton.setChecked(false);

        }
        if (kmButton.isChecked()) {
            text.setText(String.valueOf(convertToKm(inputValue)));

            feetButton.setChecked(false);

            metreButton.setChecked(false);

            kmButton.setChecked(true);

            milesButton.setChecked(false);

        }
        if (milesButton.isChecked()) {
            text.setText(String.valueOf(convertToMiles(inputValue)));

            feetButton.setChecked(false);

            metreButton.setChecked(false);

            kmButton.setChecked(false);

            milesButton.setChecked(true);

        }
    }

}

private double convertToFeet(double inputValue) {

    return (inputValue * 3.2808);
}

private double convertToMetre(double inputValue) {

    return (inputValue / 3.2808);
}

private double convertToKm(double inputValue) {

    return (inputValue / 0.62137);
}

private double convertToMiles(double inputValue) {

    return (inputValue * 0.62137);
}

}//CalculateLength

Logcat output:
01-10 04:58:34.599: E/AndroidRuntime(1155): FATAL EXCEPTION: main
01-10 04:58:34.599: E/AndroidRuntime(1155): Process: com.lacrym0sadevelopment.convertix, PID: 1155
01-10 04:58:34.599: E/AndroidRuntime(1155): java.lang.IllegalStateException: Could not execute method of the activity
01-10 04:58:34.599: E/AndroidRuntime(1155):     at android.view.View$1.onClick(View.java:3814)
01-10 04:58:34.599: E/AndroidRuntime(1155):     at android.view.View.performClick(View.java:4424)
01-10 04:58:34.599: E/AndroidRuntime(1155):     at android.view.View$PerformClick.run(View.java:18383)
01-10 04:58:34.599: E/AndroidRuntime(1155):     at android.os.Handler.handleCallback(Handler.java:733)
01-10 04:58:34.599: E/AndroidRuntime(1155):     at android.os.Handler.dispatchMessage(Handler.java:95)
01-10 04:58:34.599: E/AndroidRuntime(1155):     at android.os.Looper.loop(Looper.java:137)
01-10 04:58:34.599: E/AndroidRuntime(1155):     at android.app.ActivityThread.main(ActivityThread.java:4998)
01-10 04:58:34.599: E/AndroidRuntime(1155):     at java.lang.reflect.Method.invokeNative(Native Method)
01-10 04:58:34.599: E/AndroidRuntime(1155):     at java.lang.reflect.Method.invoke(Method.java:515)
01-10 04:58:34.599: E/AndroidRuntime(1155):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
01-10 04:58:34.599: E/AndroidRuntime(1155):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
01-10 04:58:34.599: E/AndroidRuntime(1155):     at dalvik.system.NativeStart.main(Native Method)
01-10 04:58:34.599: E/AndroidRuntime(1155): Caused by: java.lang.reflect.InvocationTargetException
01-10 04:58:34.599: E/AndroidRuntime(1155):     at java.lang.reflect.Method.invokeNative(Native Method)
01-10 04:58:34.599: E/AndroidRuntime(1155):     at java.lang.reflect.Method.invoke(Method.java:515)
01-10 04:58:34.599: E/AndroidRuntime(1155):     at android.view.View$1.onClick(View.java:3809)
01-10 04:58:34.599: E/AndroidRuntime(1155):     ... 11 more
01-10 04:58:34.599: E/AndroidRuntime(1155): Caused by: java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.EditText
01-10 04:58:34.599: E/AndroidRuntime(1155):     at com.lacrym0sadevelopment.convertix.MainActivity.unitLength(MainActivity.java:31)
01-10 04:58:34.599: E/AndroidRuntime(1155):     ... 14 more

A: seems that you're trying to cast Button into an EditText here:
EditText editText = (EditText) findViewById(R.id.button1);

which causes
Caused by: java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.EditText


text:
Q: accessing properties of a property from a method in a property of a class in coffeescript I want to be able to access a property of a class property from a method of a class property.
// lets say
class foo
  constructor: () ->
  vars: {
    bar: "somevalue"
  },
  op: {
    baz: () ->
      #get the value of foo.vars.bar
  }

How do I do it, it returns undefined if i try foo.vars.bar
EDIT
Sorry for not making it so clear, I want
baz: () ->
  something = foo.vars.bar

Is there a simple way to do it, because
baz: () ->
   something = foo.prototype.vars.bar

works fine.

A: I can think of two ways you can do this:  always access foo.vars via the foo prototype (as you've discovered) like this:
foo::vars.bar

(foo:: is a shortcut for foo.prototype in coffeescript)
Or you could ensure that the context of bar is bound to an instance of foo when it's called.  One way to do this would be to bind it in the foo constructor:
class foo
  constructor: () ->
    @op.baz = @op.baz.bind @
  vars: {
    bar: "somevalue"
  },
  op: {
    baz: () ->
      console.log @vars.bar
  }

Which of these is most suitable probably depends on whether you want to use the same vars object across all classes or not.  The second option probably isn't suitable if you want the context of baz to be something other than a foo instance.

A: One potential way is to have the parent instance variable defined in the scope:
class foo
  this_foo = null # So that the var is available everywhere within this context block
  constructor: () ->
    this_foo = @
  vars: {
    bar: "somevalue"
  },
  op: {
    baz: () ->
      this_foo.vars.bar
  }
console.log (new foo).op.baz() # => somevalue

Fiddle: http://jsfiddle.net/XL9aH/3/
This solution will allow this instance of foo, this_foo (rename to your liking) to be accessed in other ops as well without binding them or changing their value for this (or coffee-script @).


text:
Q: Дебаг SQL CLR функций в консольном приложении Можно ли SQL CLR проект подключить, как библиотеку к консольному приложению и дебажить ее там без деплоя на SQL-сервере?
Что-то попробовал такой хинт провернуть, так мне при запуске проекта предлагают законектится на сервер.

A: Создания проекта для дебага SQL CLR описано тут

*

*Start Visual Studio 2012 with Elevated permissions of Administrator

*Create SQL Server Project

*In Project Settings/Debug Pane, Provide Connection String for Database Connection

*From View Menu, Open SQL Server Object Explorer, If your connection string provided in Project doesn't create Instance of Server, then Recreate connection here...

*Right click on Instance and Select Allow SQL CLR Debugging, it will show some warning accept everything but read warnings carefully.

*Save Project and perform Rebuild, and test a Publish of project by Generated Publish Script.

*Now Create a non-deployment script in project, put a break point press ALT+F5 to execute script with Debug option, when clr-procedure will occur and try to go inside it, it will ask for process to attach with windows, Please allow to Attach


text:
Q: How to add digit before first character of string in javascript? I have a string, and I need to get its first character. if that character is alphabetic (between A to Z or a to z)then i want add any digit in-front of that character
var x = 'somestring'
alert(x.charAt(0));

in above string first character has alphabet then i need to attach any digit (0 to 9) before string
4somestring

How can I fix my code?

A: if (/[a-zA-Z]/.test(x.charAt(0))) {
    x = (Math.floor(Math.random() * 10)) + x;
}

Simply use regexes, the test method, and Math.random.
You could also use an anchor so you don't have to call charAt:
if (/^[a-zA-Z]/.test(x)) {

Here is a fiddle.

A: var x = 'somestring';
if (! /^\d+$/.test(x[0]))
    x = 5 + x; // or some other number


text:
Q: Change color of selected cell in a gridview _RowCommand() I have a Gridview of 10 rows and 3 columns. I want to change the color of a cell when it is clicked. Then if the user clicks it again, remove the color.
By this code I already have my row number stored in index.
Protected Sub GridView6_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView6.RowCommand
        Dim index As Integer = Convert.ToInt32(e.CommandArgument)
                    // Here I want to change my selected cell color

A: Should work
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
If (GridView1.Rows(index).BackColor = Drawing.Color.Aqua) Then
    GridView1.Rows(index).BackColor = Drawing.Color.White
Else
    GridView1.Rows(index).BackColor = Drawing.Color.Aqua
End If

A: Finally I found a trick. I am not sure if it is a right way but yeah it worked for me.
Protected Sub GridView6_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView6.RowCommand
    Dim index As Integer = Convert.ToInt32(e.CommandArgument)
    Dim r As GridViewRow = GridView6.Rows(index)
    Dim cell1 As Button = r.Cells(0).Controls(0)
    Dim c1 As String = RTrim(cell1.Text)
    Dim cell2 As Button = r.Cells(1).Controls(0)
    Dim c2 As String = RTrim(cell2.Text)
    Dim cell3 As Button = r.Cells(2).Controls(0)
    Dim c3 As String = RTrim(cell3.Text)

    Dim cellname As String = RTrim(e.CommandName)

     If c1 = cellname Then
        If cell1.BackColor = Drawing.Color.OliveDrab Then
            cell1.BackColor = Drawing.Color.Linen

        Else
            cell1.BackColor = Drawing.Color.OliveDrab

        End If
    End If
    // AND same for C2 and C3

It worked both way to color and discolor ;)

A: If this is a webpage(since you tagged asp.net) I would do it client sided, with javascript.
Or else the page would be reloaded on-select and reselect.
Add the cells to a class, and put an click event to them.
Either changing the css background or adding them to a new class.


text:
Q: Program skipping sections its not supposed to I have written a Home Siding Calculator program that I am including (I apologize for the length). When I run it I get no errors but it skips directly from Section I to Section VI to Section XI. It does not do any of the in-between parts. I do not understand why. Without the integer checks the program ran flawlessly.
print ("Siding Calculator")

CurrentWallNumber = 1
CurrentWinDoorNumber = 1
WallFactor = 0
WinDoorFactor = 0
GTotWallInches = 0
GTotWDInches = 0

#Section I: Number of walls input

def get_int(prompt): #WallFactor integer test
    while True:
        try:
            WallFactor = int(input("How many Walls? "))
            print("Number of Walls: ", WallFactor)
            break
        except ValueError:
            print('Please enter a number! ')
    return WallFactor
for i in range(1):
    print(get_int('Enter a number: '))

#Section II: Current Wall number check

if int(CurrentWallNumber) <= int(WallFactor):   #Start CurrentWallNumber Loop
    print("Current Wall Number: ", CurrentWallNumber)

#Section III: Wall Height input & calculations

    def get_int(prompt):    #HeightFeet integer test
        while True:
            try:
                HeightFeet = int(input("How many feet high? "))
                break
            except ValueError:
                print("Please enter a number! ")
        return HeightFeet
    for i in range(1):
        print(get_int("Enter a number: "))

    def get_int(prompt):    #HeightInches integer test
        while True:
            try:
                HeightInches = int(input("How many extra inches? "))
                TotHFtIn = int(HeightFeet) * 12  #Number of HeightFeet in inches
                TotHInches = int(TotHFtIn) + int(HeightInches)  #Total Height in inches
                break
            except ValueError:
                print("Please enter a number! ")
        return HeightInches
    for i in range(1):
        print(get_int("Enter a number: "))

#Section IV: Wall Width input & calculations

    def get_int(prompt):    #WidthFeet integer test
        while True:
            try:
                WidthFeet = input("How many feet wide? ")
                break
            except ValueError:
                print("Please enter a number! ")
        return WidthFeet

    for i in range(1):
        print(get_int("Enter a number: "))

    def get_int(prompt):    #WidthInches integer test
        while True:
            try:
                WidthInches = input("How many extra inches? ")
                TotWFtIn = int(WidthFeet) * 12  #Number of WidthFeet in inches
                TotWInches = int(TotWFtIn) + int(WidthInches)  #Total Width in inches
                TotWallInches = int(TotHInches) * int(TotWInches)  #Wall Area in inches
                WallArea = int(TotWallInches) / 144  #Wall Area in Square Feet
                print ("Wall Area: ", WallArea, "sqft")
                GTotWallInches = GTotWallInches + TotWallInches
                print("\n")
                break
            except ValueError:
                print("Please enter a number! ")
        return WidthInches

    for i in range(1):
        print(get_int("Enter a number: "))

#Section V: Current Wall Number increment

CurrentWallNumber = CurrentWallNumber + 1   #End CurrentWallNumber loop

#Section VI: Number of Windows and Doors input

def get_int(prompt):    #WinDoorFactor integer test
    while True:
        try:
            WinDoorFactor = input("How many Windows & Doors? ")
            print("Number of Windows & Doors: ", WinDoorFactor)
            break
        except ValueError:
            print("Please enter a number! ")
    return WinDoorFactor
for i in range(1):
        print(get_int("Enter a number: "))

#Section VII: Current Windows & Doors number check

if int(CurrentWinDoorNumber) <= int(WinDoorFactor):     #Start CurrentWinDoorNumber loop
    print("Current Window/Door Number: ", CurrentWinDoorNumber)

#Section VIII:  WinDoor Height input & calculations

    def get_int(prompt):    #HeightFeet integer test
        while True:
            try:
                HeightFeet = input("How many feet high? ")
                break
            except ValueError:
                print("Please enter a number! ")
        return HeightFeet
    for i in range(1):
        print(get_int("Enter a number: "))

    def get_int(prompt):    #HeightInches integer test
        while True:
            try:
                HeightInches = input("How many extra inches? ")
                TotHFtIn = int(HeightFeet) * 12  #Number of HeightFeet in inches
                TotHInches = int(TotHFtIn) + int(HeightInches)  #Total Height in inches
                break
            except ValueError:
                print("Please enter a number! ")
        return HeightInches
    for i in range(1):
        print(get_int("Enter a number: "))

#Section IX: WinDoor Width input & calculations

    def get_int(prompt):    #WidthFeet integer test
        while True:
            try:
                WidthFeet = input("How many feet wide? ")
                break
            except ValueError:
                print("Please enter a number! ")
        return WidthFeet
    for i in range(1):
        print(get_int("Enter a number: "))

    def get_int(prompt):    #WidthInches integer test
        while True:
            try:
                WidthInches = input("How many extra inches? ")
                TotWFtIn = int(WidthFeet) * 12  #Number of WidthFeet in inches
                TotWInches = int(TotWFtIn) + int(WidthInches)  #Total Width in inches

                TotWinDoorInches = int(TotHInches) * int(TotWInches)  #Window/Door Area in inches
                WinDoorArea = int(TotWinDoorInches) / 144  #Window/Door Area in feet
                print ("Window/Door Area: ", WinDoorArea, "sqft")
                GTotWDInches = GTotWDInches + TotWinDoorInches
                break
            except ValueError:
                print("Please enter a number! ")
        return WidthInches
    for i in range(1):
        print(get_int("Enter a number: "))

#Section X: CurrentWinDoorNumber increment

CurrentWinDoorNumber = CurrentWinDoorNumber + 1     #End of CurrentWinDoorNumber loop

#Section XI: Final Total

TotInches = int(GTotWallInches) - int(GTotWDInches)  #Total Wall inches - WinDoor inches
TotSqFt = int(TotInches) / 144  #Total Square Feet
print("Cumulative Area: ", TotSqFt, " SqFt")

A: The reason your program skips blocks 2,3 and 4 is because the value of the global variable WallFactor,that you have defined at the beginning of the script is still 0 when it appears in the if block in the second 'Section'. When you set WallFactor in the get_int function, you create a local variable, that has nothing to do with the global one. It lives only in that function. The fact that the get_int function returns WallFactor doesn't effect the global variable with the same name. You have to set that global variable WallFactor to the return value of the get_int function:
WallFactor=get_int(prompt)

Another way is to declare in the get_func function that the WallFactor is a global variable:
def get_int(prompt):
    global WallFactor
    ...

In the last case the return statement would be unnecessary.
The same thing happens with the global variable WinDoorFactor. Its corresponding get_int function does not change its value. There for when it appears in the following if block its value is 0.


text:
Q: How to display percentage of progress completion in progress bar using fabric UI? I'm using fluent UI to display progress bar.
Link which I refered:
https://developer.microsoft.com/en-us/fluentui#/controls/web/progressindicator
I'm facing difficulty in displaying percentage in progress bar using react. Can someone suggest on this.
Thanks,

A: If all you want to show is the percentage number then all I did was to add the percentage to the <p> tag and used the percentage number used to increase the progress bar to display the percentage number.
Since the number increases from 0 to 1 as per the docs, what we can do is to multiply the output by 100 and take a Math.floor of that.
Codepen - Demo
const { ProgressIndicator, Fabric: FabricComponent, initializeIcons } = window.Fabric;

// Initialize icons in case this example uses them
initializeIcons();

const intervalDelay = 100;
const intervalIncrement = 0.01;

const ProgressIndicatorBasicExample: React.FunctionComponent = () => {
  const [percentComplete, setPercentComplete] = React.useState(0);

  React.useEffect(() => {
    const id = setInterval(() => {
      setPercentComplete((intervalIncrement + percentComplete) % 1);
    }, intervalDelay);
    return () => {
      clearInterval(id);
    };
  });

  return (
    <>
      <ProgressIndicator label="Example title" description="Example description"
      percentComplete={percentComplete} />
      <p>{Math.floor(percentComplete * 100)}%</p>
    </>
  );
};

const ProgressIndicatorBasicExampleWrapper = () => <FabricComponent><ProgressIndicatorBasicExample /></FabricComponent>;
ReactDOM.render(<ProgressIndicatorBasicExampleWrapper />, document.getElementById('content'))


text:
Q: Ruby: how to get parent method that redefined in children class How can i get Base's "hello" method from Up class in code below?
class Base
  def hello
    p 'hello from Base'
  end
end

class Up < Base
  def hello_orig
    # how to call hello from Base class?
  end

  def hello
    p 'hello from Up'
  end
end

u = Up.new
u.hello_orig # should return 'hello from Base'

A: You can use aliasing as well.
class Base
  def hello
    p 'hello from Base'
  end
end

class Up < Base
  alias hello_orig hello

  def hello
    p 'hello from Up'
  end
end

u = Up.new
u.hello_orig # should return 'hello from Base'

A: Try this,
class Base
  def hello
    p 'hello from Base'
  end

end

class Up < Base
  def hello_orig
    Base.instance_method(:hello).bind(self).call

  end

  def hello
    super()
    p 'hello from Up'
  end

end

u = Up.new
u.hello_orig # should return 'hello from Base' or
u.hello


text:
Q: RESTEasy and Wildfly returns 405 or 404 on requests I recently rebuilt my Maven WAR Project because the HTTP requests were received, but no dependencies were to be found in the lib folder.
I then moved all the files I had created (classes, web.xml, ...) from the old to the new project. Now all dependencies are loaded, but I always get "HTTP method POST is not supported by this URL" (status 405) as a response to POST requests (on GET I get 404 etc.).
In the meantime I've gone through many tutorials again to see if I've forgotten something, but I just can't find what my mistake is.
I use Wildfly, RESTEasy and Eclipse.
Below are a few files that could possibly contain my error
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_4_0.xsd">
</web-app>

jboss-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web xmlns="http://www.jboss.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee http://www.jboss.org/j2ee/schema/jboss-web_5_1.xsd">
    <context-root>/xyz</context-root>
</jboss-web>

MyApplication.java
package com.xyz.util.rest;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

import com.xyz.employee.rest.EmployeeRest;

@ApplicationPath("/rest")
public class MyApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(EmployeeRest.class);
        return classes;
    }
}

EmployeeRest.java
package com.xyz.employee.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.xyz.employee.EmployeeAndPassword;
import com.xyz.employee.service.EmployeeService;
import com.xyz.employee.service.dto.EmployeeDTO;
import com.xyz.servicelocator.ServiceLocator;

@Path("/employee")
public class EmployeeRest {
    EmployeeService emplServ = ServiceLocator.locateService(EmployeeService.class);

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("/create")
    public Response createEmployee(EmployeeAndPassword emplAndPwd) {

        return Response.ok(emplServ.createEmployee((EmployeeDTO) emplAndPwd, emplAndPwd.getPassword())).build();
    }
}

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</groupId>
    <artifactId>xyz</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>XYZ</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>12</maven.compiler.source>
        <maven.compiler.target>12</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.22.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian</groupId>
            <artifactId>arquillian-bom</artifactId>
            <version>1.6.0.Final</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.junit</groupId>
            <artifactId>arquillian-junit-container</artifactId>
            <version>1.6.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>3.17.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20200518</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-core</artifactId>
            <version>4.5.6.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>3.13.2.Final</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>8.0.1</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>xyz</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

I tried to send a request to this url via postman: http://localhost:8080/xyz/rest/employee/create

A: I've replaced RESTEasy and Wildfly with Jersey and Tomcat. Now it works without problems
But I don't know why RESTEasy and Wildfly didn't worked...

A: The following dependency will clash with wildfly:
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.4.22.Final</version>
</dependency>

Add the scope as provided to resolve the problem, or better remove it.


text:
Q: What is the difference Between Singleton object and sessionfactory singleton object As per my knowledge singleton Object is not thread safe and session Factory singleton object is thread safe.
How this possible, Please explain someone.

A: The singleton pattern is neither thread-safe nor not thread-safe per se. You have to take a look at your specific implementation. The major question is, does it manage state?
If so then you will make sure that no more than one thread is ever allowed to change the state at the same time. That is the same problem global variables are suffering from regarding thread-safety. But there are mechanisms to ensure this safety, one is called mutual exclusion. The event of two threads concurrently modifying the same variable is one the problematic events, there are more to be aware of. Like two threads sequentially modifying a variable, then the question is whos answer counts.
Mutually exclusive events in general and a specific explanation in the java context can be found here (Mutually exclusive events) and here (Oracle concurrency guide) respectively. Global variables are explained here. Stateless and stateful are also good terms to look at regarding concurrency, parallelism and thread-safety.
Back to your question: A factory usually doesn't introduce any state and though can being shared freely between several threads. Instances produced by the factory most probably are stateful and should only be shared between threads after having made them thread-safe.
Important Note:
But don't get me wrong here. Don't forget to always check the implementation of your singletons! In java you can introduce annotations to document your investigations and mark specific code elements as thread-safe. There exist packages wich already define commonly usable annotations to document such behavior, take a look at the apache org.apache.http.annotation. When you use an API it is a good idea to inspect the documentation for such hints.

A: Session factory object is also implemented using the singleton design pattern.
singleton design pattern can be made as thread safe.
and they have implemented singleton with thread safe for session factory.
when we implement singleton we should make sure whether we need thread safe or not and we should implement acordingly.
see the various implementation of singleton in my blog under design pattern
java guide


text:
Q: sqlcmd runs into error while parsing my .sql file I am invoking sqlcmd as follows:
sqlcmd -S SERVERNAME\SQLEXPRESS -i "C:\Documents and Settings\user\Desktop\data\bigDB.sql"

And I get an error while the script is executing:
Sqlcmd: Error: Syntax error at line 86626 near command '%' in file 'C:\Documents
 and Settings\user\Desktop\data\bigDB.sql'.

How do I tell sqlcmd to ignore the current record and keep running? I think i could edit bigDB.sql and include an :On Error Ignore directive at the top - but the bigDB.sql file is 5GB is size - i cant edit.
Or How could I go to the specific line and delete out the bad record? Thanks for helping.


text:
Q: Postgres plpgsql - Using a variable inside of a dynamic create statement Using Postgres pl/pgsql, I'm attempting to create a table using a dynamic EXECUTE command, such as:
 ...
 DECLARE
    tblVar varchar := "myTable";
 BEGIN
 EXECUTE 'CREATE TABLE $1 (
             foo integer NOT NULL,
             bar varchar NOT NULL)'
 USING _tblVar;
 ...

However, I continue to receive the error message

ERROR:  syntax error at or near "$1"

If I don't use the $1 token and, instead, write the string myTable it works just fine.
Is there a limitation on using dynamic statements for CREATE calls?

A: Yes, there is such limitation. You cannot use parameters for table/column names - that's because Postgres needs to be able to parse query on compiling the dynamic SQL statement. Parser must be able to identify used relations.
Quote from PL/pgSQL docs about dynamic SQL commands:

Note that parameter symbols can only be used for data values — if you
want to use dynamically determined table or column names, you must
insert them into the command string textually. For example, if the
preceding query needed to be done against a dynamically selected
table, you could do this:
EXECUTE 'SELECT count(*) FROM '
    || tabname::regclass
    || ' WHERE inserted_by = $1 AND inserted <= $2'
   INTO c
   USING checked_user, checked_date;

As noted in comments below, the cast method is not always feasible, especially for CREATE statements. Consider format function, for example:
EXECUTE format(
  'CREATE TABLE %I (%I %I, %I %I)',
  v_tabname,
  v_col1name, v_col1type,
  v_col2name, v_col2type);

Side note: probably this limitation applies to dynamic SQL in other DBMS, including Oracle: http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/dynamic.htm#CHDHGHIF

A: In addition to what @filiprem wrote, this is how you do it properly:
...
DECLARE
   tbl_var text := 'myTable';   -- I would not use mixed case names ..
BEGIN
EXECUTE '
CREATE TABLE ' || quote_ident(tbl_var) || '(
   foo integer NOT NULL,
   bar text NOT NULL)';
...

Use quote_ident() (or format()) to defend against SQL injection and syntax errors. It double-quotes identifiers with non-standard characters or reserved words.
I also replaced the double-quotes you had around the string value in your example with single-quotes.
See:

*

*SQL injection in Postgres functions vs prepared queries

*Insert text with single quotes in PostgreSQL

A: In the code above, you are using $1 which is an argument which you got as a parameter from the function. In this case, you can't use $1 inside the string. So, the code should be like this
EXECUTE 'CREATE TABLE ' || $1 || ' (
         foo integer NOT NULL,
         bar varchar NOT NULL)'

In here || this mark indicates that joining a string like + sign


text:
Q: lvalue required as left operand of assignment I get the following error: lvalue required as left operand of assignment
for this function code:
typedef struct {
  int nbIndividus;
  int nbVariables;
  distance_t *distancesReference;
  double **target;
  double *E;
  double *lag;
} functionData_t;

    double myfunc (unsigned n,const double *x, double *grad, void *my_func_data)
{
   int i,j,k,t,ind1,ind2,a,test_nb;
   double temp,sigma,eta,distanceCarre,sommeObj,distance,compteurDistance,somme,objectifFunction,Somme,*Array_val_E;
   int nbIndividus,nbVariables,NbDisplacement,nb_val_E;
   double **target;
   double *E;
   double *lag ;

   distance_t *distancesReference;
   functionData_t *functionData=(functionData_t *)my_func_data;

   nbIndividus=functionData->nbIndividus;
   nbVariables=functionData->nbVariables;
   target= functionData->target;
   E= functionData->E;
   lag=functionData->lag;
   distancesReference=functionData->distancesReference;
   sommeObj=0;
   somme=0;
   sigma=0.13;
   eta=0.5;
   nb_val_E=114814;
   compteurDistance=0;
   NbDisplacement=0;
  for(k=1;k<nbIndividus;k++){
   compteurDistance=compteurDistance+(nbIndividus-k);
  }

  for(i=0;i<compteurDistance;i++){
        ind1=distancesReference[i].i;
        ind2=distancesReference[i].j;
        distance=distancesReference[i].distance;
        Somme=0;
        for(k=0;k<nbVariables;k++) {
         temp=target[ind1][k]-target[ind2][k]+x[ind1*nbVariables+k]-x[ind2*nbVariables+k];
     Somme+=temp*temp;
        }
        distanceCarre=Somme;
        for(t=0;t<=nb_val_E;t++){
           Array_val_E[t]=fabs(E[t]-(distanceCarre/(4*sigma*sigma)));
        }
        index=min_array(Array_val_E,nb_val_E);
        sommeObj+=(distancesReference[i].distance)*(distancesReference[i].distance)+distanceCarre+2*sigma*sigma*nbVariables-2*sqrt(3.14)*(distancesReference[i].distance)*sigma*val_lag(index);
     }

    objectifFunction=sommeObj;

    return objectifFunction;

}

I think that the problem is in the vector E, but i cannot find the origin of this error. Can someone help me please to fix it ?
Thanks.

A: You forgot to declare index.
The reason for the apparently strange error message - "lvalue required..." as opposed to something like "'index' undeclared..." - is that there is a library function called "index" which you've happened to include a declaration of (most likely this one).
When you're not hiding that function with a variable declaration, you're attempting to assign to a function (which you can't, for obvious reasons).


text:
Q: Gravitational potential energy for more than two object When an object of mass $m_1$ is brought from infinity to an object of mass $m_2$ the gravitational potential energy of the system is
$-\frac{Gm_1m_2}{d}$.  Now if an object of mass $m_3$ is brought from infinity to this system, what will be the gravitational potential energy of the whole system? Is there any vector calculation?

A: For an arbitrary number of particles, just sum that expression, $-Gm_im_j/|\vec r_i-\vec r_j|$, over all pairs $i$, $j$ of particles. This is easy to see if you imagine bringing each particle successively into the potential of the particles already present, since the potentials of individual particles just add together.


text:
Q: How To Add New fxml to Controller I have 2 .fxml files (FXMLDocument.fxml/login.fxml) and one controller file (FXMLDocumentController). I want to remove FXMLDocument.fxml from the controller and add login.fxml to the contoller.
When I call the main method, I want get prompted with the login form instead of FXMLDocument.fxml.
Any idea what is happening?
PS: login.fxml is created using SceneBuilder.

A: You don't have to use the default FXML file generated by your IDE. Here is a basic controller that will use login.fxml:
public class LoginController {

    public LoginController(){
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("login.fxml"));
            fxmlLoader.setController(this);
            fxmlLoader.load();
        } catch (IOException exception) {
            System.out.println("Error loading content.");
            System.exit(0);
        }
    }

}

Note the line with FXMLLoader(getClass().getResource("login.fxml")). This is how you add an FXML file to a controller.


text:
Q: Trying to add an element before a dynamically built dropdown list This is my code:
<script language="JavaScript" type="text/javascript">
            (function($) {
            $(document).ready(function(){
                    var path = "http://shop.vodafone.co.uk",
                        phoneList = $('#phoneList');
                    $.getJSON("phones.json", function(data){
                            var option = $('option').attr('value', data);
                            var phones = [];
                            for(var phone in data) {
                                //phones.push("<option value='"+data[phone].value+"'>"+data[phone].name+"</option>");
                                phones.push(data[phone]);
                            }

                            //console.log(phones);
                            phones.sort(function(a, b){
                                var aName = a.name.toLowerCase(),
                                    bName = b.name.toLowerCase();
                                if(aName < bName) {
                                    return -1;
                                }
                                if(aName > bName){
                                    return 1;
                                };
                                return 0;
                            });
                            var select = $('<option value="Take your pick"></option>').val();
                            var htmlElements = [];
                            for(var i = 0; i<phones.length; i++) {
                                htmlElements.push("<option value='"+phones[i].value+"'>"+phones[i].name+"</option>");
                            }
                            //htmlElements.before(select);
                            $("#phoneList").before(select).html(htmlElements.join('\n'));
                            //val = $(this).find('option:selected').val(),

                    });
                    $('.phoneSelect').bind('change', function(){
                        var url = $("#phoneList option:selected").val();
                        window.location = path + url;
                    });
            });
            })(jQuery);
    </script>

And here's the HTML:
<div>
 <form class="phoneSelect" action="#">
 <select style="width: 200px" name="phoneMake" id="phoneList">
    <option selected="selected" value="Take your pick">Take your pick</option>
 </select>
</form>
</div>

The issue is I am trying to add the above element
    'Take your pick'
before the dynamically built dropdown list and all withing the same form element.
The dropdown list data is retrieved from a JSON file.
Can someone tell me where I am going wrong?

A: try to append the numbers while looping:
for(var i=0; i<phones.length; i++){
    $("#phoneList").append($("<option value='"+phones[i].value+"'>"+phones[i].name+"</option>"));
}


text:
Q: Read a physically partitioned data using wildcards I have a persisted dataframe on AWS S3 with the following structure:
s3://bucket/df/
|__ date=2020-02-19/
    |__ FILENAME01.json
    |__ FILENAME02.json
    |__ FILENAME03
    |__ ...
|__ date=2020-02-20/
    |__ FILENAME04.json
    |__ FILENAME05
    |__ ...
|__ ...

If I read this dataframe using the following syntax:
df = spark.read.json("s3://bucket/df)"

The file that doesn't have extensions will be part of my dataframe and this is not desirable. So, I would like to only consider the files with .json extension.
So I decided to read this dataframe filtering the files with suffix *.json. In a practical way, I tried the following:
df = spark.read.json("s3://bucket/df/date=*/*.json")

The spark.read.json worked, but the column date used to partition my dataframe wasn't present. Is there any way to retrieve only files that match to a specific suffix inside partition folders, without losing the partition column?

A: Spark can only discover partitions under the given input path. But here your path contains already the partition date. You can read this from the docs :

Starting from Spark 1.6.0, partition discovery only finds partitions
under the given paths by default. For the above example, if users pass
path/to/table/gender=male to either SparkSession.read.parquet or
SparkSession.read.load, gender will not be considered as a
partitioning column. If users need to specify the base path that
partition discovery should start with, they can set basePath in the
data source options. For example, when path/to/table/gender=male is
the path of the data and users set basePath to path/to/table/, gender
will be a partitioning column.

You can specify the basePath option :
df = spark.read.option("basePath", "s3://bucket/df/").json("s3://bucket/df/date=*/*.json")

Or alternatively, you can extract back the date partition from the input_file_name using regexp_extract function:
from pyspark.sql import functions as F

df = df.withColumn(
    "date",
    F.regexp_extract(F.input_file_name(), r".*/date=(\d{4}-\d{2}-\d{2})/.*", 1)
)


text:
Q: puppet master on CentOS 7 - Gone after reboot I deployed a Puppet Master and Puppet Agent on two different CentOS machines.
They both used to communicate via ssl but upon restart of Master server, things are gone.
Httpd's conf.d contains puppetmaster.conf, hence I need the httpd service to run.
When it worked, the https://name:8140 showed "The environment must be purely alphanumeric, not ''" meaning it was working.
I'm sure I ran
"$sudo chkconfig httpd on
Note: Forwarding request to 'systemctl enable httpd.service'."

to make this start on boot.
It used to error out on not having available sockets to listen to, but I solved it by killing the puppet process that was taking up the port.
Here's what I tried with no luck:
$sudo service httpd status
Redirecting to /bin/systemctl status  httpd.service
httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled)
   Active: active (running) since Mon 2015-03-30 12:39:07 PDT; 2min 13s ago
  Process: 4144 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=0/SUCCESS)
 Main PID: 4155 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           ├─4155 /usr/sbin/httpd -DFOREGROUND
           ├─4180 PassengerAgent watchdog
           ├─4186 PassengerAgent server
           ├─4192 PassengerAgent logger
           ├─4203 /usr/sbin/httpd -DFOREGROUND
           ├─4204 /usr/sbin/httpd -DFOREGROUND
           ├─4205 /usr/sbin/httpd -DFOREGROUND
           ├─4206 /usr/sbin/httpd -DFOREGROUND
           └─4207 /usr/sbin/httpd -DFOREGROUND

Mar 30 12:39:07 vaio systemd[1]: Started The Apache HTTP Server.
Mar 30 12:39:07 vaio python[4146]: SELinux is preventing /usr/local/share/gems/gems/passenger-5.0.5/buildout/support-binar...bility.

                                   *****  Plugin sys_resource (37.5 confidence) suggests   **********************...
Mar 30 12:40:49 vaio systemd[1]: Started The Apache HTTP Server.
Hint: Some lines were ellipsized, use -l to show in full.

$sudo service httpd start
Redirecting to /bin/systemctl start  httpd.service

(IPtable)
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 8140 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

(SELinux Status)
 sudo cat /etc/sysconfig/selinux

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=permissive
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

(HTTPD status -l)

sudo service httpd status -l
Redirecting to /bin/systemctl status  -l httpd.service
httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled)
   Active: active (running) since Mon 2015-03-30 12:39:07 PDT; 20min ago
 Main PID: 4155 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           ├─4155 /usr/sbin/httpd -DFOREGROUND
           ├─4180 PassengerAgent watchdog
           ├─4186 PassengerAgent server
           ├─4192 PassengerAgent logger
           ├─4203 /usr/sbin/httpd -DFOREGROUND
           ├─4204 /usr/sbin/httpd -DFOREGROUND
           ├─4205 /usr/sbin/httpd -DFOREGROUND
           ├─4206 /usr/sbin/httpd -DFOREGROUND
           └─4207 /usr/sbin/httpd -DFOREGROUND

Mar 30 12:39:07 vaio systemd[1]: Started The Apache HTTP Server.
Mar 30 12:39:07 vaio python[4146]: SELinux is preventing /usr/local/share/gems/gems/passenger-5.0.5/buildout/support-binaries/PassengerAgent from using the sys_resource capability.

                               *****  Plugin sys_resource (37.5 confidence) suggests   **********************

                               If you do not want processes to require capabilities to use up all the system resources on your system;
                               Then you need to diagnose why your system is running out of system resources and fix the problem.

                               According to /usr/include/linux/capability.h, sys_resource is required to:

                               /* Override resource limits. Set resource limits. */
                               /* Override quota limits. */
                               /* Override reserved space on ext2 filesystem */
                               /* Modify data journaling mode on ext3 filesystem (uses journaling
                                  resources) */
                               /* NOTE: ext2 honors fsuid when checking for resource overrides, so
                                  you can override using fsuid too */
                               /* Override size restrictions on IPC message queues */
                               /* Allow more than 64hz interrupts from the real-time clock */
                               /* Override max number of consoles on console allocation */
                               /* Override max number of keymaps */
                               /* Override resource limits. Set resource limits. */
                               /* Override quota limits. */
                               /* Override reserved space on ext2 filesystem */
                               /* Modify data journaling mode on ext3 filesystem (uses journaling
                                  resources) */
                               /* NOTE: ext2 honors fsuid when checking for resource overrides, so
                                  you can override using fsuid too */
                               /* Override size restrictions on IPC message queues */
                               /* Allow more than 64hz interrupts from the real-time clock */
                               /* Override max number of consoles on console allocation */
                               /* Override max number of keymaps */
                               /* Override resource limits. Set resource limits. */
                               /* Override quota limits. */
                               /* Override reserved space on ext2 filesystem */
                               /* Modify data journaling mode on ext3 filesystem (uses journaling
                                  resources) */
                               /* NOTE: ext2 honors fsuid when checking for resource overrides, so
                                  you can override using fsuid too */
                               /* Override size restrictions on IPC message queues */
                               /* Allow more than 64hz interrupts from the real-time clock */
                               /* Override max number of consoles on console allocation */
                               /* Override max number of keymaps */

                               Do
                               fix the cause of the SYS_RESOURCE on your system.

                               *****  Plugin catchall_boolean (30.1 confidence) suggests   ******************

                               If you want to allow httpd to run stickshift
                               Then you must tell SELinux about this by enabling the 'httpd_run_stickshift' boolean.
                               You can read 'None' man page for more details.
                               Do
                               setsebool -P httpd_run_stickshift 1

                               *****  Plugin catchall_boolean (30.1 confidence) suggests   ******************

                               If you want to allow httpd to setrlimit
                               Then you must tell SELinux about this by enabling the 'httpd_setrlimit' boolean.
                               You can read 'None' man page for more details.
                               Do
                               setsebool -P httpd_setrlimit 1

                               *****  Plugin catchall (4.20 confidence) suggests   **************************

                               If you believe that PassengerAgent should have the sys_resource capability by default.
                               Then you should report this as a bug.
                               You can generate a local policy module to allow this access.
                               Do
                               allow this access for now by executing:
                               # grep PassengerAgent /var/log/audit/audit.log | audit2allow -M mypol
                               # semodule -i mypol.pp

Mar 30 12:40:49 vaio systemd[1]: Started The Apache HTTP Server.
Mar 30 12:52:58 vaio systemd[1]: Started The Apache HTTP Server.

A: Trial and error show below steps bring Puppet Master back to life. Thanks to Shane Madden for guidance.
$ sudo service iptables restart
Redirecting to /bin/systemctl restart  iptables.service
$ sudo service httpd start
Redirecting to /bin/systemctl start  httpd.service
$ sudo chkconfig httpd on
Note: Forwarding request to 'systemctl enable httpd.service'.
$ sudo service httpd start
Redirecting to /bin/systemctl start  httpd.service
$ sudo setenforce permissive
$ sudo sed -i 's\=enforcing\=permissive\g' /etc/sysconfig/selinux
$ sudo getenforce

A: Make sure to have "-A INPUT -m state --state NEW -m tcp -p tcp --dport 8140 -j ACCEPT" in iptables.
Once you connect, it will say "The environment must be purely alphanumeric, not ''" which is NOT an error.


text:
Q: How to achieve a Heart-rate-monitor styled plot in Coreplot I'm using the Real Time Plot (in CorePlotGallery) to graph incoming ECG heart data. This works, but since it autoscrolls the X axis horizontally as new data arrives (which I don't want) I've modified the "-newData:" method in RealTimePlot.m with:
if (self.currentIndex >= kMaxDataPoints) self.currentIndex = 0;

This allows the plot to "chase" itself over & over on the graph. Great.
Problem: When the plot wraps back to the start, Coreplot connects the plot end point with the new start point, resulting in a horizontal plot line cutting through the entire graph, from the last point back to the first.
Q1: Is there a way I can get Coreplot to not connect these two data points?
Q2: Alternatively, is there another way of achieving a "heart rate monitor" styled plot in Coreplot with a real time data stream?

A: Add a dummy data point between the two where you want the break and give it a value of NAN or nil. You'll end up with one more data index than points you want displayed.
Alternatively, use two scatter plots to display the data. Add data points to one and remove them from the other and then switch when you get to the end.


text:
Q: Update a combo box based on another combo box's selection In VB for applications I have this code:
Private Sub cc_Change()

End Sub

Private Sub UserForm_Initialize()
    cc.AddItem "op1"
    cc.AddItem "op2"
    cc.AddItem "op3"
    cc.AddItem "op4"

End Sub

The above works.
I would like to further develop this so when you click "op1" you get associated options, this is the code I have so far;
Private Sub combo2_Change()
    If cc = "op1" Then
    Me.combo2.RowSourceType = "Value List"
    Me.combo2.RowSource = "a; b; c"
    Else
    Me.combo2.RowSourceType = "Value List"
    Me.combo2.RowSource = "default"
    End If
End Sub

I have only listed "op1" as it would be transferable. Please can you help me, when I select "op1" I don't get the values "a" "b" or "c"

A: If I got it correctly, you need to write the code for the event of changing the first combo box (cc) inside its change event. Try doing the following:
Private Sub cc_Change()
    If cc = "op1" Then
        Me.combo2.RowSourceType = "Value List"
        Me.combo2.RowSource = "a; b; c"
    Else
        Me.combo2.RowSourceType = "Value List"
        Me.combo2.RowSource = "default"
    End If
End Sub

A: Within the private sub of cc_Change()
Use this:
If cc = "op1" Then
        combo2.AddItem "a"
Else
        combo2.AddItem "default"
End If


text:
Q: Reading/Sending From/To a Console Application I'm using Delphi 2010, and I need to run a console application and automate the tasks that would normally require the user to enter information (for example a password).
So basically I need some way to pipe all the text and read the lines so I know when the application is read for some kind of input, then automatically have my program send the text that the other application needs.
The program I was trying to automate is a Cygwin port of OpenSSH, and I need to enter the password (which isn't displayed when typed) and then press enter.

A: You can try and get this library uZpRunConsoleApp.pas which contains a really nice class to work with console apps. It will also do what you want it to do, send and receive from a console app to your application.

A: you can send char by message to the Console window , there is an example :
Send To Console
note : it is`t exactly about your question , I made it for other purposes but it will be useful for you ...
good luck ...


text:
Q: Java position of the mouse on the screen I am making this GUI where you have icons that should always stay at the same position on the screen and I want to make them do something once I click on them.
In my case I've made this neat cancel symbol which I placed on the upper right corner of my lwjgl display - I've made this code here to enable clicking on it:
private void CloseIcon()
{
    if(Input.GetMousePosition().GetX() > 1175 && Input.GetMousePosition().GetX() < 1215 &&
       Input.GetMousePosition().GetY() > 685 && Input.GetMousePosition().GetY() < 715)
    {
        if(Input.GetMouse(0)) {
        System.out.println("closing porgram..");
        }
    }
}

Now there are two issues with this method and I was wondering If there's a better way to do it?
Issue 1: When I change the resolution of my display, or if I go to full screen, obviously the definition for x and y aren't the same anymore - what's a better way to define the location of the icon?
Issue 2: At the moment I have the icon object move together with the camera, like that it always stays at the same place on the screen - still is there a better way to position the object in openGL so it stays always at the same place no matter what the camera is doing?

A: Well, if you are using the lwjgl, you can define from the beginning your own resolution, and don't have to get heat up with that:
Display.setDisplayMode(new DisplayMode(width,height));
Display.create();

or for fullscreen
Display.setDisplayMode(displayMode);
Display.setFullscreen(true);
Display.create();


text:
Q: Please edit this script Tradingview keeps giving error for line 3 Compilation error Line 3: Could not find function or function reference 'indicator' //@version=5
indicator("Support Resistance Channels")
study("Support Resistance Channels", "sr_channels", overlay = true, max_bars_back = 501)
// Input parameters
prd = input(defval = 10, title="Pivot Period", minval = 4, maxval = 30, group = "Settings ", tooltip="Used while calculating Pivot Points, checks left&right bars")
ppsrc = input(defval = 'High/Low', title="Source", options = ['High/Low', 'Close/Open'], group = "Settings ", tooltip="Source for Pivot Points")
ChannelW = input(defval = 5, title = "Maximum Channel Width %", minval = 1, maxval = 8, group = "Settings ", tooltip="Calculated using Highest/Lowest levels in 300 bars")
minstrength = input(defval = 1, title = "Minimum Strength", minval = 1, group = "Settings ", tooltip = "Channel must contain at least 2 Pivot Points")
maxnumsr = input(defval = 6, title = "Maximum Number of S/R", minval = 1, maxval = 10, group = "Settings ", tooltip = "Maximum number of Support/Resistance Channels to Show") - 1
loopback = input(defval = 290, title = "Loopback Period", minval = 100, maxval = 400, group = "Settings ", tooltip="While calculating S/R levels it checks Pivots in Loopback Period")
res_col = input(defval = color.new(color.red, 75), title = "Resistance Color", group = "Colors ")
sup_col = input(defval = color.new(color.lime, 75), title = "Support Color", group = "Colors ")
inch_col = input(defval = color.new(color.gray, 75), title = "Color When Price in Channel", group = "Colors ")
showpp = input(defval = false, title = "Show Pivot Points", group = "Extras ⏶⏷")
showsrbroken = input(defval = false, title = "Show Broken Support/Resistance", group = "Extras ⏶⏷")
showthema1en = input(defval = false, title = "MA 1", inline = "ma1")
showthema1len = input(defval = 50, title = "", inline = "ma1")
showthema1type = input(defval = "SMA", title = "", options = ["SMA", "EMA"], inline = "ma1")
showthema2en = input(defval = false, title = "MA 2", inline = "ma2")
showthema2len = input(defval = 200, title = "", inline = "ma2")
showthema2type = input(defval = "SMA", title = "", options = ["SMA", "EMA"], inline = "ma2")
// Calculate moving
idk what to do trying fixing the code thought it was a spacing issue or copying but i am not sure

A: This works:
I've changed input()'s to suit v5 (input.int for example), and added a plot() for reference.

//@version=5
indicator("Support Resistance Channels", "sr_channels", overlay = true, max_bars_back = 501)

//Input parameters
prd = input.int(defval = 10, title="Pivot Period", minval = 4, maxval = 30, group = "Settings ", tooltip="Used while calculating Pivot Points, checks left&right bars")
ppsrc = input.string(defval = 'High/Low', title="Source", options = ['High/Low', 'Close/Open'], group = "Settings ", tooltip="Source for Pivot Points")
ChannelW = input.int(defval = 5, title = "Maximum Channel Width %", minval = 1, maxval = 8, group = "Settings ", tooltip="Calculated using Highest/Lowest levels in 300 bars")
minstrength = input.int(defval = 1, title = "Minimum Strength", minval = 1, group = "Settings ", tooltip = "Channel must contain at least 2 Pivot Points")
maxnumsr = input.int(defval = 6, title = "Maximum Number of S/R", minval = 1, maxval = 10, group = "Settings ", tooltip = "Maximum number of Support/Resistance Channels to Show") - 1
loopback = input.int(defval = 290, title = "Loopback Period", minval = 100, maxval = 400, group = "Settings ", tooltip="While calculating S/R levels it checks Pivots in Loopback Period")
res_col = input.color(defval = color.new(color.red, 75), title = "Resistance Color", group = "Colors ")
sup_col = input.color(defval = color.new(color.lime, 75), title = "Support Color", group = "Colors ")
inch_col = input.color(defval = color.new(color.gray, 75), title = "Color When Price in Channel", group = "Colors ")
showpp = input.bool(defval = false, title = "Show Pivot Points", group = "Extras ⏶⏷")
showsrbroken = input.bool(defval = false, title = "Show Broken Support/Resistance", group = "Extras ⏶⏷")
showthema1en = input.bool(defval = false, title = "MA 1", inline = "ma1")
showthema1len = input.int(defval = 50, title = "", inline = "ma1")
showthema1type = input.string(defval = "SMA", title = "", options = ["SMA", "EMA"], inline = "ma1")
showthema2en = input.bool(defval = false, title = "MA 2", inline = "ma2")
showthema2len = input.int(defval = 200, title = "", inline = "ma2")
showthema2type = input.string(defval = "SMA", title = "", options = ["SMA", "EMA"], inline = "ma2")

//I'VE INCLUDED A PLOT JUST FOR CLARITY AND REFERENCE - AMEND TO SUIT YOUR PREFERENCE
maPlot = ta.sma(close, showthema1len)
plot(maPlot)


text:
Q: Celery and mysql connections What is the appropriate way to handle mysql connections when multiple celery tasks read and write to the same database?
Pooling ? If so, is there support for it in mysqldb for python?
Thank you

A: I believe pooling is the right option. You can use SQLAlchemy ORM which has pooling support or  pooling can be supported by this package


text:
Q: Setting array to contain string values results in error I'm new to C++ and not totally sure what I am doing wrong. Here is my code. Simple enough
#include <iostream>
#include <fstream>

using namespace std;

const string WORD_FILE = ("/Users/matt/Desktop/C++/Hangman/Hangman/words.txt");
const int WORDS_USED = 20;

string fillArray(string words[]);

int main() {
    string words[WORDS_USED];

    fillArray(words);

}

string fillArray(string words){
    string word;
    ifstream inputStream;
    inputStream.open(WORD_FILE);
    while (int x=0 < WORDS_USED){
        inputStream >> word;
        words[x] = word;

    }
    return words;
}

When I run this, I get an error on the "words[x] = word;" line.
Assigning to 'value_type' (aka 'char') from incompatible type 'string'

I'm not sure what I'm doing wrong or why it is taking anything as a character

A: You just have a typo in your function definition:
string fillArray(string words){
    ...
}

words should be an array there, i.e. words[]. Your compiler should have warned you that the definition signature doesn't match the declaration earlier in the file.

A: There are some errors in your code.
You declared fillArray() as accepting an array of std::string objects as input, and returning a single std::string as output.  But, in your function definition, the input parameter is not declared as an array, it is a single std::string instead.  That is why you are getting the compiler error - you really are trying to assign a std::string read from the std:::ifstream to a single char.
Also, the syntax of your while loop is all wrong.  But even if it weren't, you are not incrementing x at all, so your loop would not break when it reached 20 words.  And you are not doing any error handling on the ifstream reading, so the loop would not break when it reaches EOF or encounters a reading error, either.
Try something more like this:
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

const string WORD_FILE = "/Users/matt/Desktop/C++/Hangman/Hangman/words.txt";
const int WORDS_USED = 20;

int fillArray(string words[]);

int main() {
    string words[WORDS_USED];
    fillArray(words);
    return 0;
}

int fillArray(string words[]) {
    ifstream inputStream(WORD_FILE);
    string word;
    int numWords = 0;
    while ((numWords < WORDS_USED) && (inputStream >> word)) {
        words[numWords] = word;
        ++numWords;
    }
    return numWords;
}


text:
Q: Проблема с базой данных и DataTable У меня есть база данных и в ней есть 1 запись у которой Login = test123-Login , и Password = test123-Login. Но когда я ввожу Логин test123-Login и пароль
test123-login (здесь l маленькая а в записи большая).
DataBaseHelper.cs
public static bool LoginExist(string login, string password)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection(connString))
            {
                connection.Open();
                string clearLogin = login.Trim();
                string clearPassword = password.Trim();
                DataTable dt = new DataTable();
                SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM [Table] WHERE Login=@clearLogin AND Password=@clearPassword", connection);
                cmd.Parameters.Add("clearLogin", SqlDbType.VarChar).Value = clearLogin;
                cmd.Parameters.Add("clearPassword", SqlDbType.VarChar).Value = clearPassword;
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(dt);
                int count = Convert.ToInt32(dt.Rows[0][0].ToString());
                return count == 0 ? false : true;
            }
        }
        catch { MessageBox.Show("Ошибка авторизации! Перезапустите приложение.", "Ошибка авторизации", MessageBoxButton.OK, MessageBoxImage.Error); return false; }
    }

И когда я ввожу неправильный пароль то мне все равно дает зайти в главное приложение. Как это исправить?
И кто может то подскажите правильно ли я все делаю? И как лучше сделать реализацию авторизации?

A: Ошибка в том, что не указана длина типа varchar:
cmd.Parameters.Add("clearLogin", SqlDbType.VarChar).Value = clearLogin;

Таким образом, длина равна 1.
Размер нужно указать тот же, который у вас в таблице.
cmd.Parameters.Add("clearLogin", SqlDbType.VarChar, 24).Value = clearLogin;

К тому же, возможно, стоит использовать nvarchar - это позволит использовать не только английские буквы в логине и пароле (если вас это устраивает).

Использование DataTable в данном случае совершенно излишне.
Кроме того, следует диспозить (освобождать) все используемые ресурсы.
Давайте перепишем код:
using (SqlConnection connection = new SqlConnection(connString))
{
    connection.Open();

    string clearLogin = login.Trim();
    string clearPassword = password.Trim();

    using (SqlCommand cmd = new SqlCommand(
        "SELECT COUNT(*) FROM [Table] WHERE Login=@clearLogin AND Password=@clearPassword",
        connection))
    {
        cmd.Parameters.Add("clearLogin", SqlDbType.VarChar, 24).Value = clearLogin;
        cmd.Parameters.Add("clearPassword", SqlDbType.VarChar, 24).Value = clearPassword;

        int count = (int)cmd.ExecuteScalar();
        return count != 0;
    }
}


text:
Q: I can't add the last Google Apps Email MX record because Zerigo DNS only allows 10 records. Will it matter? I am using Heroku for my site hosting, and Zerigo for DNS magagement. I'm trying to setup Google Apps email, but I can't add the last MX record (ASPMX5.GOOGLEMAIL.COM.) because I have hit my limit of 10 allowed total records on Zerigo. Will it matter if I don't add this last record?

A: No it won't.  Google Apps gives you that many MX servers for heavy redundancy in case of problems.  MX records have a server to send attempt to send mail to and a priority associated with it (IE which server are you in line to receive mail for this domain if the other isn't available).  You weren't able to add the lowest priority server to your DNS.  Normally no mail server would attempt to connect to it (aspmx5.googlemail.com) unless all the others were unavailable.  In an instance like that we'd probably have bigger problems to worry about :)

A: It's very unlikely that it will matter. Each DNS record is given a priority, so whenever an email server is resolving that domain name, it will go through each record, order by priority in ascending order, until it finds one that resolves.
Google's servers are very stable, so if they're to the point that 9 previous records are failing, chances are good that it's catastrophic and your email will be down regardless of DNS.
tl;dr: you're fine


text:
Q: Reading audit records in Oracle As a DBA, what is the best way to read the audit records on daily basis? Say, i'm the administrator and I would like to view the audit records made by the DBAs. I have enabled audit sys operatiosn to TRUE and and it creates records for the same but is there any easy readable format to clearly list out the changes made by the DBAs?

A: The audit records are written to the operating system's audit trail defined by the audit_file_dest parameter. You can change the format of to XML by changing the audit_trail parameter but the files will be still kept on the file system.
This due to security reasons since DBAs shouldn't be able to access those files if they are being audited.
You can play around with external tables or create a shell script for analyzing the files but there is no built in mechanism for analyzing the data.


text:
Q: How does checking if the empty string is in a word evaluate to true in python? This might be a very elementary question and I should know this but how does the following line evaluate to true?
>>> '' in 'spam'
True

Why/How is the empty string/character in a non-empty string?  I tried this in Idle for Python 2.7 and it's evaluating to true.  I found this from the link to Automate the Boring Stuff chapter 6

A: Because the in operator is to test membership, and by that notion, the empty set is a subset of all other sets. To be consistent in that regard, the in operator was deliberately designed to act accordingly.
5.9 Comparisons

The operators in and not in test for collection membership. x in s evaluates to true if x is a member of the collection s, and false otherwise. x not in s returns the negation of x in s. The collection membership test has traditionally been bound to sequences; an object is a member of a collection if the collection is a sequence and contains an element equal to that object. However, it make sense for many other object types to support membership tests without being a sequence. In particular, dictionaries (for keys) and sets support membership testing.
For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.
For the Unicode and string types, x in y is true if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Note, x and y need not be the same type; consequently, u'ab' in 'abc' will return True. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.


text:
Q: Loop over multiindex and get specific value -- Data cleaning o i really need to solve a particular Problem with Multi index Dataframe

| Doc_Number | Deliv_Number | Type  | Customer Name | Created_On | First_conf_deliv_date | Last_deliv_date | Goods Issue | Delivery_Group | Order_Quantity
| 134893847  | 1245678      | 2308  | ABC           |2019-03-04  | 2019-03-05            | 2019-03-22      | 2019-03-19  |      01        |   20
|            | 1245678      | 4567  | ABC           |2019-03-04  | 2019-03-05            | 2019-03-22      | 2019-03-19  |      01        |   20
|            | 3456789      | 4398  | ABC           |2020-03-04  | 2019-04-06            | 2019-04-16      | 2019-04-12  |      02        |   30
|2349586590  |....          | ...   | CDF
....

if you look in the table above, you can see a Doc_Number as First Index and the Deliv_Number column as Second Index.
The Problem is:
I need to clean the data for each Doc_Numbers in my Table where a specific Type (Type Column) in this case 2308 equals another row in the same Doc_Number (134893847) with same Delivery_Number ( both have 1245678) and with same Order_Quantity (both have 20), but different Type Number in this case 2308 and 4567.
--> When both rows cancel each other out on the same Doc_Number, Deliv_Number and Quantity, return me the Doc_Numbers else Not.
There are also cases where Type 2308 occurs multiple times in a Doc_Number so i have to find multiple rows which are equal to the row with the Type 2308.
Example: You have 5 rows with Type 2308 --> so you have to find 5 matching rows. if just 4 rows with a different Type and equal Doc_Number, Deliv_Number and Quantity are matching do not return the Doc_Number.
i hope it is understandable.
i thought about pulling out the rows with the Type 2308 for each Doc_Number. Then deleting it in the Table, so you dont match with the same column -->  then check each row in the same Doc_Number for matching values and if so --> return me the Doc_Number. Something like that.
i have tried different ways to solve the Problem, but nothing really worked.
Maybe some of you guys can help me out.


text:
Q: Migrating stats from Wordpress.com blog to self-hosted Wordpress.org blog I'm currently trying to migrate the wordpress.com stats over to a self-hosted wordpress.org blog for a client.  Migrating databases and everything else is absolutely no problem, I just haven't been able to find any definitive information on whether or not this is possible.  Could anyone point me in the right direction to getting this solved?

A: It's possible but requires help from an official WordPress support person (aka "Happiness Engineer") to do it:

As for stats, they can also be moved, but staff have to take care of that. Once you have Jetpack installed on the new WordPress.ORG install, post the relevant URLs in this forum thread and then add the "modlook" tag n the column on the right.

* Note: "WordPress.ORG" above really means "self-hosted" site. That's a common misnomer that was introduced earlier in the quoted thread.
So to do it from start to finish:

*

*Migrate your site to a self-hosted install as much as you can.

*Install the Jetpack plugin and connect it to a WordPress.com account. (I don't know if it helps if it's the one associated with your WordPress.com site. It can't hurt.)

*Open a new WordPress.com support thread. Tag it "modlook" and request that they move your stats to your new domain. Make sure to provide your old WordPress.com site and your new self-hosted domain.

Alternately, you can always use the paid "Guided Transfer" that also includes moving stats.


text:
Q: Binding activity to a running service in android I have a service S that starts at boot.
It has a contentobserver C that starts an intentservice X to do some processing.
The default activity A is started by the user.
I want to know if it's possible to bind A to the running service S without stopping it so that I can pass on a resultreceiver R to S that in turn has to be passed on to X.
I want to achieve this so that I can start X again, this time free from C, from the bound service S with R as a parcelable extra.
Via R, a progress dialog is updated in A whenever it's run.
Before trying my luck with resultreceivers, I was using notifications, the one from the support library.
But the problem was that I was building and showing them again for each iteration of a loop.
The alert sound was playing repeatedly for like 300 odd times and that was unpleasant.
Tried my luck with broadcasts but I had some bad experiences. So tossed them away.
Is there any other way around this problem?
My problem could be solved if there's a way to update the notification with building it again.
I'm using 4.1.1 build, API 16 in which setlatesteventinfo seems to be deprecated.
I am still open to go back to the idea of updating a running notification.
Or a different workaround.
Any help will be appreciated.
EDIT:
Using notifications is a way to implement this app in which there would be no need for the resultreceiver and ibinder interfaces.
I can't find the setlatesteventinfo in the API level 16. I'm trying to use the v4 support library. In my implementation, I build a new notification for every iteration of a loop. But I've not figured out a way to keep the sound alert for the first time only and not for the rest. Has anybody succeeded in properly updating a notification?

A:
I want to know if it's possible to bind A to the running service S without stopping it

That is certainly possible. As Hoan pointed out, you need to call bindService() from your activity. This article has some example code on how to do it.
As for the rest of your question, it seems like it could be broken down into several new questions. It's really hard to comprehend and answer all at once.

A: The android documentation on Bound Services says:

The third parameter is a flag indicating options for the binding. It should usually be BIND_AUTO_CREATE in order to create the service if its not already alive.

Still have to confirm that the onCreate() of service S is not called again though.


text:
Q: BlueJ how to get data from an array so that it can be compared with user input I'm currently messing around with BlueJ and trying to get objects to interact with each other and stuff. I have created an account and accountlist class. The accountlist allows you to add account objects which it then puts into an arraylist.
Removing these accounts from the array by index was easy enough with a for loop to get the position of each account, but now it should remove the Account with the account number specified as a parameter and I can't work out how to get the accountnumber from the array to compare it with the users input.
AccountList Class
/**
 * Creates an AccountList that will store customers accounts
 *
 * @author Ryan Conway
 * @version 12/11/2014
 */

import java.util.*;

public class AccountList
{

    private ArrayList < Account > accounts;

    /**
     * Create an AccountList that will contain accounts.
     */
    public AccountList()
    {

        accounts = new ArrayList < Account >();

    }

    /**
     * Add a account to this AccountList.
     */
    public void addAccount(Account newAccount)
    {
        accounts.add(newAccount);
    }

    /**
     * Return the number of accounts stored in this AccountList.
     */
    public int getNumberOfAccounts()
    {
        return accounts.size();
    }

    /**
     * prints out the number of accounts to the terminal.
     * for each loop used to get each account.
     */
    public void getAllAccounts()
    {
        for(Account account : accounts)
        {
            account.printAccountDetails();
        }

        System.out.println("Number of accounts: " + getNumberOfAccounts());
    }

    /**
     * Print out details of a account
     * @param accountEntry The entry in the list
     */
    public void getAccount(int accountEntry)
    {
        if(accountEntry < 0)
        {
            System.out.println("Negative entry :" + accountEntry);
        }
        else if(accountEntry < getNumberOfAccounts())
        {
            Account account = accounts.get(accountEntry);
            account.printAccountDetails();

        }
        else
        {
            System.out.println("No such entry :" + accountEntry);
        }
    }

    /**
     * removes a account from the list
     * @param accountEntry The entry in the list
     */
    public void removeAccount(int accountEntry)
    {
        if(accountEntry < 0)
        {
            System.out.println("Negative entry :" + accountEntry);
        }
        else if(accountEntry < getNumberOfAccounts())
        {
            accounts.remove(accountEntry);
        }
        else
        {
            System.out.println("No such entry :" + accountEntry);
        }
    }

    public boolean removeAccount(String accountNumber)
    {
        int index = 0;
        for(Account account : accounts)
        {
            if (accounts.equals(accountNumber))
                System.out.println("Found It!");
            index++;
        }
        return false;

    }

    public void printCollection()
    {
        System.out.println(accounts);
    }
}

Account Class
/**
 * Write a description of class Account here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Account
{
    private String firstName;
    private String lastName;
    private String accountNumber;
    private int pointsHeld;
    private Address address;

    /**
     * Constructor for objects of class Account.
     * The number of pointsHeld should be set to zero.
     *
     * @param firstName The Account Holder's first name
     * @param lastName The Account Holder's last name
     * @param accNumber The Account Holder's account number
     * @param street the account holder's street
     * @param town the account holder's town
     * @param postcode the account holder's postcode
     */
    public Account(String fName, String lName, String accNumber,
                   String street, String town, String postcode)
    {
        firstName = fName;
        lastName = lName;
        accountNumber = accNumber;
        pointsHeld = 0;
        address = new Address(street, town, postcode);
    }

    /**
     * Constructor for objects of class Account.
     * The number of pointsHeld should should be set to
     * the supplied value.
     *
     * @param fName The Account Holder's first name
     * @param lName The Account Holder's last name
     * @param acctNumber The account number
     * @param thePoints the pointsHeld awarded when account is initialised
     * @param street the account holder's street
     * @param town the account holder's town
     * @param postcode the account holder's postcode
     */
    public Account(String fName, String lName, String acctNumber, int points,
                   String street, String town, String postcode)
    {
        firstName = fName;
        lastName = lName;
        accountNumber = acctNumber;
        pointsHeld = points;
        address = new Address(street, town, postcode);
    }

    // accessors

    /**
     * Get the Account Holder's first name
     *
     * @return the Account Holder's first name
     */
    public String getFirstName()
    {
        return firstName;
    }

    /**
     * Get the Account Holder's last name
     *
     * @return the Account Holder's last name
     */
    public String getLastName()
    {
        return lastName;
    }

    /**
     * Get the Account Holder's account Number
     *
     * @return the Account Holder's account number
     */
    public String getAccountNumber()
    {
        return accountNumber;
    }

     /**
     * Get the number of points held
     *
     * @return the number of points held
     */
    public int getNoOfPoints()
    {
        return pointsHeld;
    }

    /**
     * Print out the Account Holder's details to the console window
     *
     */
    public void printAccountDetails()
    {
        System.out.println( firstName + " " + lastName
                           + "\n" + address.getFullAddress()
                           + "\nAccount Number: " + accountNumber
                           + "\nNumber of points: " + pointsHeld);
    }

    /**
     * Return the account holder's address
     *
     * @return the account holder's address
     */
    public String getAddress()
    {
        return address.getFullAddress();
    }

    // mutators

    /**
     * Change the first name
     *
     * @param fName the new first name
     *
     */
    public void setFirstName(String fName)
    {
        firstName = fName;
    }

    /**
     * Change the last name
     *
     * @param lName the new last name
     *
     */
    public void setLastName(String lName)
    {
        lastName = lName;
    }

    /**
     * Increase the number of points held by a given number
     * and output a esage to the console window giving
     * the revised number of points held.
     *
     * @param number of points to add to total
     */
    public void addPoints(int points)
    {
        pointsHeld = pointsHeld + points;
        System.out.println("Points now held: " + pointsHeld);
    }

    /**
     * Remove pointsHeld by a given number and output a
     * message to the console window giving the revised number
     * of points held as long as the number of points would
     * not fall below zero
     * - otherwise output message to console window instead.
     *
     * @param number of pointsHeld to remove total.
     *
     */
    public void removePoints (int points)
    {
        if ((pointsHeld - points) >=0)
        {
            pointsHeld = pointsHeld - points;
            System.out.println("Points now held: " + pointsHeld);
        }
        else
        {
            System.out.println("Transaction refused: "
                     + "Insufficient points available.");
        }
    }

    /**
     *  Change the account holder's address
     *
     *  @param street the street
     *  @param town the town
     *  @postcode the postcode
     */
    public void setAddress(String street, String town, String postcode)
    {
        address.setFullAddress(street, town, postcode);
    }

    /**
     * Print the account holder's address
     */
     public void printAddress()
     {
         address.printAddress();
     }
} // end class

http://i.imgur.com/dCwt9oK.jpg
thanks.

A: Try this:
public boolean removeAccount(String accountNumber)
{
    Iterator<Account> iterator = accounts.iterator();

    while (iterator.hasNext())
    {
         if (accountNumber.equals(iterator.next().getAccountNumber()))
         {
            System.out.println("Found It!");
            iterator.remove();
            return true;
         }
    }

    return false;
}

Removing an item from a list while you are looping through it is not a safe operation, but the Iterator class makes this possible. More information: Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop