Q: Zend storing data in session I'm new in Zend and php. For a project, i need to gather 3 ajax Zend Forms together. I know i need to use session to do that but i can't find any information about how to do that. Can someone help me ?
EDIT :
    public function formResAction(){

        $form = new Front_Form_ResPhone();
        $bdd_Reservation = new Front_Model_DbTable_Reservation();

        if($this->getRequest()->isPost()){
            if($form->isValid($this->getRequest()->getPost())){
                // Données non valides

                $session = new Zend_Session_Namespace('forms');
                $formData = $form->getValues();
                $session->form1 = $formData;
                print_r ($session->form1);

                echo $this->view->bloc11Fid($formData);
                exit;
            }
            else{
                // Données non valides
//              echo "non valide";
            }
        }
        else{
            // Appel en GET
//              echo "GET";
        }
        echo $form;
        exit;

}

    public function formFidAction(){

            $form = new Front_Form_FidForm();
            $bdd_Reservation = new Front_Model_DbTable_Reservation();

        if($this->getRequest()->isPost()){
            if($form->isValid($this->getRequest()->getPost())){
                // Données non valides

                $session = new Zend_Session_Namespace('forms');
                $formData = $form->getValues();
                $session->form2 = $formData;
                print_r ($session->form2);

                echo $this->view->bloc11Fid2($formData);
                exit;
            }
            else{
                // Données non valides
//              echo "non valide";
            }
        }
        else{
            // Appel en GET
//              echo "GET";
        }
        echo $form;
        exit;

}

    public function formFid2Action(){

            $form = new Front_Form_FidForm2();
            $bdd_Reservation = new Front_Model_DbTable_Reservation();

        if($this->getRequest()->isPost()){
            if($form->isValid($this->getRequest()->getPost())){
                // Données non valides

                $session = new Zend_Session_Namespace('forms');
                $formData = $form->getValues();
                $session->form3 = $formData;
                print_r ($session->form3);

                echo $this->view->bloc11Res($formData);

                exit;
            }
            else{
                // Données non valides
//              echo "non valide";
            }
        }
        else{
            // Appel en GET
//              echo "GET";
        }
        echo $form;
        exit;

}

public function resFormAction(){

        $form = new Front_Form_ResForm();
        $bdd_Reservation = new Front_Model_DbTable_Reservation();

        if($this->getRequest()->isPost()){
            if($form->isValid($this->getRequest()->getPost())){
                // Données non valides

                $session = new Zend_Session_Namespace('forms');
                $formData = $form->getValues();
                $session->form4 = $formData;
                print_r ($session);

                $bdd_Reservation->insert($forms);

                echo $this->view->bloc11Fel($formData);
                exit;

                exit;
            }
            else{
                // Données non valides
//              echo "non valide";
            }
        }
        else{
            // Appel en GET
//              echo "GET";
        }
        echo $form;
        exit;
}

A: Check this:
//create a session namespace
$session = new Zend_Session_Namespace('myapp');

$session->somevar = 'somevalue';

echo $session->somevar; //somevalue

Zend_Session_Namespace has magic getter and setter.
So, if a attribute of the session object is not set, it will be NULL by default.
http://framework.zend.com/manual/1.12/en/zend.session.basic_usage.html


Q: Directx Texture interface to existing memory I'm writing a rendering app that communicates with an image processor as a sort of virtual camera, and I'm trying to figure out the fastest way to write the texture data from one process to the awaiting image buffer in the other.
Theoretically I think it should be possible with 1 DirectX copy from VRAM directly to the area of memory I want it in, but I can't figure out how to specify a region of memory for a texture to occupy, and thus must perform an additional memcpy.  DX9 or DX11 solutions would be welcome.
So far, the docs here: http://msdn.microsoft.com/en-us/library/windows/desktop/bb174363(v=vs.85).aspx have held the most promise.

"In Windows Vista CreateTexture can create a texture from a system memory pointer allowing the application more flexibility over the use, allocation and deletion of the system memory"

I'm running on Windows 7 with the June 2010 Directx SDK, However, whenever I try and use the function in the way it specifies, I the function fails with an invalid arguments error code.  Here is the call I tried as a test:
    static char s_TextureBuffer[640*480*4]; //larger than needed
    void* p = (void*)s_TextureBuffer;
    HRESULT res = g_D3D9Device->CreateTexture(640,480,1,0, D3DFORMAT::D3DFMT_L8, D3DPOOL::D3DPOOL_SYSTEMMEM, &g_ReadTexture, (void**)p);

I tried with several different texture formats, but with no luck. I've begun looking into DX11 solutions, it's going slowly since I'm used to DX9. Thanks!


Q: Python detect 'key up' event from the terminal I'm trying to write a python program to emulate a musical instrument. While the button is pressed down the note plays, when you take your finger off the button the sound automatically stops:
while buttonUp:
  noteSilent()

  if buttonDown:
     notePlay()

From what I understand the two main ways of doing this are with pygame and through curses. Pygame seems simpler but it seems to be aimed at making graphical apps whereas I'm quite content running this program purely from the command line. I've been trying to get it to work with curses but it's not really having the desired effect. This is what I currently have:
        while key != ord('q'):
        key = stdscr.getch()
        curses.echo()
        stdscr.addch(20, 25, key)
        stdscr.refresh()

        NoteSilent(2)

        if key == ord('a'):
            print "hello"
            NotePlay(2)

This doesn't seem to have the desired effect and so any advice on how to tackle this would be much appreciated.

A: curses doesn't provide separate events for key presses and releases, so you'd probably be better off with pygame if you want it to work that way.
(Weird quasi-exception: ncurses and PDCurses can provide separate press and release events for mouse buttons, if you wanted to go that way. This isn't quite standard curses, and I don't know if the Python interface supports it.)


Q: ol3 geometryFunction interaction.Draw add GPS point In a project i'm developing we are using the ol.interaction.Draw functionality to draw geometry. The geometryFunction we are using to add a GPS point to the geometry (linestring or polygon). This is accomplished by setting a boolean to add this GPS point. This boolean is set by a button some were in the HTML.
Al works well but the sketch isn't updated untill we move the cursor over the map again. Is there a way to trigger the geometryFunction without moving the cursor over the map?
// Interaction
        $scope.interactions.draw = new ol.interaction.Draw({
            source: $scope.vector.getSource(),
            type: (function () {
                var type = 'Point';
                if ($scope.layer.TypeName == 'LineStyle')
                    type = 'LineString';
                if ($scope.layer.TypeName == 'PolygonStyle')
                    type = 'Polygon';
                return type;
            })(),
            geometryFunction: function (coordinates, geometry) {

                if (!_.isUndefined(geometry)) {
                    // Is move to GPS position selected?
                    if ($scope.moveToGpsPosition_) {
                        // GPS position
                        var pos = _geolocation.geolocation.getPosition();
                        // Line
                        if ($scope.layer.TypeName == 'LineStyle')
                            coordinates.splice(coordinates.length - 1, 0, pos);
                        // Polygon
                        if ($scope.layer.TypeName == 'PolygonStyle')
                            coordinates[0].splice(coordinates.length - 2, 0, pos);
                        // Stop move to GPS position
                        $scope.moveToGpsPosition_ = false;
                    }
                    geometry.setCoordinates(coordinates);
                } else {

                    // Detect geometry type
                    if ($scope.layer.TypeName == 'PointStyle')
                        geometry = new ol.geom.Point(coordinates);
                    if ($scope.layer.TypeName == 'LineStyle')
                        geometry = new ol.geom.LineString(coordinates);
                    if ($scope.layer.TypeName == 'PolygonStyle')
                        geometry = new ol.geom.Polygon(coordinates);
                }
                return geometry;
            }
        });

A: I'm having a difficult time replicating your problem but I suspect you can solve it by added one of the following after your geometry.setCoordinates(coordinates); line:
map.updateSize();
or
map.render();


Q: tomcat to send SSL client certificate I am trying to do a https rest API call with a SSL certificate(PFX file) which have a password. I tested the connection from my desktop with SOAP UI and it is working fine.
I have a web application which is running on tomcat and I need my tomcat to send this certificate for all the http/https call which it will make.
I am not a tomcat person so i am stuck with this now.
I can find in online about how to set up a keystore & server.xml so that my web app can use Client Authentication against things connecting to it, not for when it needs to connect out to some other server(outgoing call).
my tomcat version is : 9.0.22
connector settings on my server.xml file


Q: Error messages on Java code that has me make 2 calculator objects and perform operations on them Here's the main Java file:
   class Main {
  public static void main(String[] args) {
   Calculator One = new Calculator(100,50,"Addition");
   One.calculateNums();
   One.showResults();
   Calculator Two = new Calculator(100,50,"Subtraction");
   Two.changeNumOne("200");
   Two.calculateNums();
   Two.showResults();

  }
}

And here's the calculator java code:
public class Calculator {
  // instance variables - first number, second number, operation
  private int firstNum;
  private int secondNum;
  private String operation;

  // static field to keep track of number of Calculator objects
  public static int Calculatorobjects = 0;
  // default constructor
  public Calculator(){
    int firstNum = 0;
    int secondNum = 0;
    operation = "Addition";
  }
  // initializing constructor
  public Calculator(int firstNum, int secondNum, int NumOperation){
    NumOne = firstNum;
    NumTwo = secondNum;
    NumOperation = operation;
  }
  // getters for all 3 instance variables
  public int one(){
    return firstNum;
  }
  public int two(){
    return secondNum;
  }
  public String three(){
    return operation;
  }
  // setters to be able to change any of the 3 instance variables after creating them
  public void changeNumOne(int NewNumOne){
    firstNum = NewNumOne;
  }
  public void changeNumOne(int NewNumTwo){
    SecondNum = NewNumTwo;
  }
  public void changeNumOne(String NewNumOperation){
    operation = NewNumOperation;
  }
  // instance method to perform operation
  public void calculateNums(int result){
    if(operation == "Addition"){
      result = firstNum + secondNum;
    }
    if(operation == "Subtraction"){
      result = firstNum - secondNum;
    }
  }
  // instance method to display results
  public void showResults(){
    System.out.println(firstNum + " " +  operation + " " + secondNum + " = " + result);
  }
}

I'm getting the following error messages:
exit status 1
Calculator.java:35: error: method changeNumOne(int) is already defined in class Calculator
  public void changeNumOne(int NewNumTwo){
              ^
Calculator.java:36: error: cannot find symbol
    SecondNum = NewNumTwo;
    ^
  symbol:   variable SecondNum
  location: class Calculator
Calculator.java:52: error: cannot find symbol
    System.out.println(firstNum + " " +  operation + " " + secondNum + " = " + result);
                                                                               ^
  symbol:   variable result
  location: class Calculator
Main.java:4: error: method calculateNums in class Calculator cannot be applied to given types;
   One.calculateNums();
      ^
  required: int
  found: no arguments
  reason: actual and formal argument lists differ in length
Main.java:8: error: method calculateNums in class Calculator cannot be applied to given types;
   Two.calculateNums();
      ^
  required: int
  found: no arguments
  reason: actual and formal argument lists differ in length
5 errors

I've tried a bunch of random things while trying to fix it and all of them have either done nothing or made even more errors. I'm an amateur at Java so I definitely did a lot of things wrong but if someone could point them out and send the right code that would be great.

A: 1.) At least you need to fix:
public void changeNumOne(int NewNumOne){
    firstNum = NewNumOne;
}

// Error: Same name as above
public void changeNumOne(int NewNumTwo){
    // Error: Capital SecondName
    SecondNum = NewNumTwo;
}

To:
public void changeNumOne(int firstNum){
    this.firstNum = firstNum;
}

public void changeNumTwo(int secondNum){
    this.secondNum = secondNum;
}

2.) And here you would like to print result, but your class does not have such a variable (also check, if your function calculateNums makes sense):
public void showResults(){
    System.out.println(firstNum + " " +  operation + " " + secondNum + " = " + result);
}

3.) This should also fail:
public Calculator(int firstNum, int secondNum, int NumOperation){
    NumOne = firstNum;
    NumTwo = secondNum;
    NumOperation = operation;
}

Should be:
public Calculator(int firstNum, int secondNum, string operation){
    this.firstNum = firstNum;
    this.secondNum = secondNum;
    this.operation = operation;
}

4.) Here you do not assign the values:
public Calculator(){
    int firstNum = 0;
    int secondNum = 0;
    operation = "Addition";
}

Should be:
public Calculator(){
    this.firstNum = 0;
    this.secondNum = 0;
    this.operation = "Addition";
}

Overall:
There might be other errors.
You need to check all your variables names. They are quite inconsistent. Though, read your error messages carefully and try to understand them for the future.

A: There are many errors. I solved with this code, acting with Calculator class. I commented on the code where there were errors.
class Calculator {
// instance variables - first number, second number, operation
private int firstNum;
private int secondNum;
private int result;   //I declare the result variable so I can print it
private String operation;

// static field to keep track of number of Calculator objects
public static int Calculatorobjects = 0;
// default constructor
public Calculator(){
    this.firstNum = 0;    //useless because uninitialized int are already 0
    this.secondNum = 0;     //same
    this.operation = "Addition";
}
// initializing constructor
public Calculator(int firstNum, int secondNum, String NumOperation){   //NumOperation is a String, not an int
    this.firstNum = firstNum;    //I'm setting the global variables as the local variables that you pass to the constructor
    this.secondNum = secondNum;
    this.operation = NumOperation;
}
// getters for all 3 instance variables
public int one(){
    return firstNum;
}
public int two(){
    return secondNum;
}
public String three(){
    return operation;
}
// setters to be able to change any of the 3 instance variables after creating them
public void changeNumOne(int NewNumOne){
    firstNum = NewNumOne;
}
public void changeNumTwo(int NewNumTwo){.   //changed method name
    secondNum = NewNumTwo;
}
public void changeNumOne(String NewNumOperation){
    operation = NewNumOperation;
}
// instance method to perform operation
public void calculateNums(){
    if(operation.equals("Addition")){     //equals is used to compare strings
        result = firstNum + secondNum;
    }
    if(operation.equals("Subtraction")){
        result = firstNum - secondNum;
    }
}
// instance method to display results
public void showResults(){
    System.out.println(firstNum + " " +  operation + " " + secondNum + " = " + result);
}


Q: Navigation Bar Title Font Size I need to change the size of the Navigation Bar title text for one view controller in my iPhone app. I'm using iOS5, and tried the following code:
if ([self.tabBarItem respondsToSelector:@selector(setTitleTextAttributes:)]) {
    NSLog(@"*** Support method(iOS 5): setTitleTextAttributes:");
    [self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                [UIFont fontWithName:@"AmericanTypewriter" size:20.0f], UITextAttributeFont,
                                                [UIColor blackColor], UITextAttributeTextColor,
                                                [UIColor grayColor], UITextAttributeTextShadowColor,
                                                [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)], UITextAttributeTextShadowOffset,
                                                nil]];
}

However this only applies to the tabBarItem.

A: Swift 2.0:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        UINavigationBar.appearance().titleTextAttributes = [
            NSFontAttributeName: UIFont(name: "DINNextLTW04-Regular", size: 20)!
        ]

        return true
    }

Or
 override func viewDidLoad() {
  super.viewDidLoad()

  self.navigationController?.navigationBarHidden =  false
  self.title = "SAMPLE"

//Set Color
  let attributes: AnyObject = [ NSForegroundColorAttributeName: UIColor.redColor()]
  self.navigationController!.navigationBar.titleTextAttributes = attributes as? [String : AnyObject]

//Set Font Size
  self.navigationController!.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Arial", size: 37.0)!];

 }

A: You got it already,but you can also use following attributes methods.
For Color,
NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor RedColor],UITextAttributeTextColor, nil];

self.navigationController.navigationBar.titleTextAttributes = attributes;

For Size,
NSDictionary *size = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Arial" size:17.0],UITextAttributeFont, nil];

self.navigationController.navigationBar.titleTextAttributes = size;

Thanks.
For iOS 7 and above
For Size:
NSDictionary *size = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Arial" size:17.0],NSFontAttributeName, nil];

self.navigationController.navigationBar.titleTextAttributes = size;

A: You need to grab the navigation bar property and the use @property(nonatomic, copy) NSDictionary *titleTextAttributes.
For further info see UINavigationBar Class Reference and Customizing UINavigationBar section.
To understand better your question: What type of controller do you have?
EDIT
[self.navigationController.navigationBar setTitleTextAttributes:...];

if you access the navigationController within a pushed controller.
[navigationController.navigationBar setTitleTextAttributes:...];

if navigationController is your current UINavigationController. This could be used when for example if you have the following code:
UINavigationController* navigationController = ...;
[navigationController.navigationBar setTitleTextAttributes:...];

A: Since iOS7, I always do like following:
[[UINavigationBar appearance] setTitleTextAttributes:
    [NSDictionary dictionaryWithObjectsAndKeys:
        [UIFont fontWithName:@"Helvetica-Bold" size:18.0],NSFontAttributeName,
        nil]];

The Keyword UITextAttributeFont has been depressed from iOS7, you'd supposed to replace with
NSFontAttributeName.
You can use
[self.navigationController.navigationBar setTitleTextAttributes:]to set someone navigationController's appearence, while [UINavigationBar appearance] setTitleTextAttributes:] works for your whole App directly.(Of course you need to put it in a property position.)

A: My example
guard let sansLightFont = UIFont(name: "OpenSans", size: 20) else { return }
navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName : sansLightFont]


Q: Set of bytes, what are the values of a and b program Project1;
var
  a,b:set of byte;
  c:set of byte;
  i:integer;

begin
  a:=[3];
  b:=[2];
  c:=(a+b)*(a-b);
  FOR i:= 0 TO 5 DO
    IF i IN c THEN write(i:2);
  readln;
end.

Can someone please explain to me what is going on in this code. I know that c=3 but dont understand how, what are the values of a and b ? Tried writeln(a,b);  but gives me an error ...

A: Ok, I'll explain what you probably could find out by debugging, or by simply reading a textbook on Pascal as well:
The line:
c := (a+b)*(a-b);

does the following:
a + b is the union of the two sets, i.e. all elements that are
      in a or in b or in both, so here, that is [2, 3];
a - b is the difference of the two sets, i.e. it is a minus the
      elements of a that happen to be in b too. In this case, no
      common elements to be removed, so the result is the same as a,
      i.e. [3]
x * y is the intersection of the two sets, i.e. elements that are in
      x as well as in y (i.e. a set with the elements both have in common).

Say, x := a + b; y := a - b;, then it can be disected as:
x := a + b; // [3] + [2] --> [2, 3]
y := a - b; // [3] - [2] --> [3]
c := x * y; // [2, 3] * [3] --> [3]


Q: Silverstripe migration, index and other pages not found. Why? I recently migrated a silverstripe website from a server with apache2 to a new server with nginx. I followed these instructions: http://doc.silverstripe.org/framework/en/installation/nginx . I am using php5-fpm with tcp port (127.0.0.1:9000).
The problem is that i am facing "file not found." as soon as i try to reach the website from the browser.
I would appreciate any help.
Thanks.

A: *

*Which SilverStripe version?

*Is there anything in the logs (both nginx and PHP)?

My slightly tuned nginx configuration for SilverStripe 3 looks like this: https://gist.github.com/xeraa/eab6bc9914e4b75009b8 — this might get you started


Q: Running Code View (assembly debugger) on Win7 x64 I am using Win7 x64.
In my class, we use Win XP x32 and write program in standard MS-DOS editor, and debug our programs with Code View.
But my problem is that I can't set it up home, because I can't run Code View on x64.
I two solutions. One is to change my OS to winXP x32 or install Virtual Machine and use winXP x32 on it.
Is there maybe some other emulator/program that can do same as Code View ? any good tutorials about that?

A: Late answer but hopefully someone will find it useful.
One way to run it is to download DOSBox, it is an emulator of old-timer DOS. Since you are mentioning Code View, I am guessing that you are using MASM as well so short instructions how to run it would be as follows:

*

*Run DOSBox

*In the console, write something like 'mount D C:/masm' where 'masm' is a folder where you have stored your compiler and Code View (cv.exe)

*Next is command 'D:' which will make you inside your 'masm' folder

*Compile it - 'masm myfile.asm'

*Link it - 'link myfile'

*Finally, debug in the Code View 'cv myfile.exe'


Q: VBA refresh form I have a simple progress bar. I want to fill it when I make iteration through my loop, but I only see my form with 0 and 100 progress value, so it doesn't refresh during the loop. How can I achieve the runtime refreshment? Thank you!
Sub test()
UserForm1.Show (False)
DoEvents

For i = 1 To 700
    For j = 1 To 5000
        UserForm1.Label1.Caption = 100 * i / 700 & "% Completed"
        UserForm1.Bar.Width = 200 * i / 700 '200 - width of the bar
    Next j
Next i

End Sub

A: You just have the DoEvents in the wrong place. Try it like this.
Sub test()
UserForm1.Show vbModeless

For i = 1 To 700
    For j = 1 To 5000
        UserForm1.Label1.Caption = 100 * i / 700 & "% Completed"
        UserForm1.Bar.Width = 200 * i / 700 '200 - width of the bar
        DoEvents
    Next
Next

End Sub


Q: Why are we seeing parquet write errors after switching to EMRFS consistent view? we have a large ETL process running on an EMR cluster that reads and writes large number of parquet files to into S3 buckets
Here is the code:
a = spark.read.parquet(path1)
a.registerTempTable('a')
b = spark.read.parquet(path2)
b.registerTempTable('b')
c = spark.read.parquet(path3)
c.registerTempTable('c')

sql = '''
select
a.col1,
a.col2,
b.col1,
b.col2,
c.col1,
c.col2,
a.dt
from
a
join
b
on
a.dt = b.dt
join
c
on
a.dt = c.dt
''''

df_out = spark.sql(sql)

df_out.repartition('dt').write.parquet( path_out, partitionBy='dt', mode='overwrite')

We recently had to switch to transient clusters and thus had to start using consistent view. I am positing our ERMFS site setup below:
{
"fs.s3.enableServerSideEncryption": "true",
"fs.s3.consistent": "false",
"fs.s3.consistent.retryPeriodSeconds": "10",
"fs.s3.serverSideEncryption.kms.keyId": "xxxxxx",
"fs.s3.consistent.retryCount": "5",
"fs.s3.consistent.metadata.tableName": "xxxxx",
"fs.s3.consistent.throwExceptionOnInconsistency": "true"
}

Running the same code wit the same spark configuration - that works on the permanent cluster - on the transient cluster with consistent view enabled results in an error.
...
19/02/25 23:01:23 DEBUG S3NativeFileSystem: getFileStatus could not find key 'xxxxxREDACTEDxxxx'
19/02/25 23:01:23 DEBUG S3NativeFileSystem: Delete called for 'xxxxxREDACTEDxxxx' but file does not exist, so returning false
19/02/25 23:01:23 DEBUG DFSClient: DFSClient writeChunk allocating new packet seqno=465, src=/var/log/spark/apps/application_1551126537652_0003.inprogress, packetSize=65016, chunksPerPacket=126, bytesCurBlock=25074688
19/02/25 23:01:23 DEBUG DFSClient: DFSClient flush(): bytesCurBlock=25081892 lastFlushOffset=25075161 createNewBlock=false
19/02/25 23:01:23 DEBUG DFSClient: Queued packet 465
19/02/25 23:01:23 DEBUG DFSClient: Waiting for ack for: 465
19/02/25 23:01:23 DEBUG DFSClient: DataStreamer block BP-75703405-10.13.32.237-1551126523840:blk_1073741876_1052 sending packet packet seqno: 465 offsetInBlock: 25074688 lastPacketInBlock: false lastByteOffsetInBlock: 25081892
19/02/25 23:01:23 DEBUG DFSClient: DFSClient seqno: 465 reply: SUCCESS downstreamAckTimeNanos: 0 flag: 0
Traceback (most recent call last):
File "xxxxxREDACTEDxxxx", line 112, in <module>
main()
File "xxxxxREDACTEDxxxx", line xxxxxREDACTEDxxxx, in main
xxxxxREDACTEDxxxx
File "xxxxxREDACTEDxxxx", line 70, in main
partitionBy='dt', mode='overwrite')
File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/readwriter.py", line 691, in parquet
File "/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__
File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 63, in deco
File "/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o232.parquet.
: org.apache.spark.SparkException: Job aborted.
at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply$mcV$sp(FileFormatWriter.scala:215)
at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:173)
at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:173)
at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:65)
at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:173)

I suspect that the error is due to the setup of EMRFS but I was not able to find any EMRFS setting that would work. The only thing that results in this error not being thrown while I am running the code above is increasing the number of node to double the normal number. The error also isn't thrown if I decrease the amount of data.
Changing the output commuter and spark speculation does not help either.
Thanks a lot. I will be great full for any ideas / suggestions.

A: "fs.s3.consistent": "false" should be true for emrfs consistent view to work


Q: Shidoku solver matlab code I'm trying to write a Shidoku  ( smaller and easier 4x4 variant of Sudoku) solver code in MATLAB.
I have found some soduko solver (9x9) but i could't revise them to be suitable for my problem. For example:
% Solving Sudoku Using Recursive Backtracking

function X = sudoku(X)
% SUDOKU  Solve Sudoku using recursive backtracking.
%   sudoku(X), expects a 9-by-9 array X.
 % Fill in all “singletons”.
 % C is a cell array of candidate vectors for each cell.
 % s is the first cell, if any, with one candidate.
 % e is the first cell, if any, with no candidates.
 [C,s,e] = candidates(X);
 while ~isempty(s) && isempty(e)
    X(s) = C{s};
    [C,s,e] = candidates(X);
 end
 % Return for impossible puzzles.
 if ~isempty(e)
    return
 end
 % Recursive backtracking.
  if any(X(:) == 0)
    Y = X;
    z = find(X(:) == 0,1);    % The first unfilled cell.
    for r = [C{z}]            % Iterate over candidates.
       X = Y;
       X(z) = r;              % Insert a tentative value.
       X = sudoku(X);         % Recursive call.
       if all(X(:) > 0)       % Found a solution.
          return
       end
     end
   end
% ------------------------------
   function [C,s,e] = candidates(X)
      C = cell(9,9);
      tri = @(k) 3*ceil(k/3-1) + (1:3);
      for j = 1:9
         for i = 1:9
            if X(i,j)==0
               z = 1:9;
               z(nonzeros(X(i,:))) = 0;
               z(nonzeros(X(:,j))) = 0;
               z(nonzeros(X(tri(i),tri(j)))) = 0;
               C{i,j} = nonzeros(z)';
            end
         end
      end
 L = cellfun(@length,C);   % Number of candidates.
 s = find(X==0 & L==1,1);
 e = find(X==0 & L==0,1);
 end % candidates
end % sudoku

Any help will be helpful.

A: Just reduce the problem dimensionality from 3 to 2 (I know now that it is said "9x9" instead of "3x3", but the important dimensional number for the puzzle is N=3):
    % SHIDOKU  Solve Shidoku using recursive backtracking.
    %   shidoku(X), expects a 4-by-4 array X.
    function X = shidoku(X)

            [C,s,e] = candidates(X);
            while ~isempty(s) && isempty(e)
                    X(s) = C{s};
                    [C,s,e] = candidates(X);
            end;

            if ~isempty(e)
                    return
            end;

            if any(X(:) == 0)
                    Y = X;
                    z = find(X(:) == 0,1);

                    for r = [C{z}]
                            X = Y;
                            X(z) = r;
                            X = shidoku(X);
                            if all(X(:) > 0)
                                    return;
                            end;
                    end;
            end;

            % ------------------------------
            function [C,s,e] = candidates(X)
                    C = cell(4,4);
                    bi = @(k) 2*ceil(k/2-1) + (1:2);
                    for j = 1:4
                            for i = 1:4
                                    if X(i,j)==0
                                            z = 1:4;
                                            z(nonzeros(X(i,:))) = 0;
                                            z(nonzeros(X(:,j))) = 0;
                                            z(nonzeros(X(bi(i),bi(j)))) = 0;
                                            C{i,j} = transpose(nonzeros(z));
                                    end;
                            end;
                    end;

                    L = cellfun(@length,C);   % Number of candidates.
                    s = find(X==0 & L==1,1);
                    e = find(X==0 & L==0,1);
             end % candidates

    end % shidoku


Q: printing a div using jQuery How do I just print the article on my web page using jQuery, article is inside a div
window.print() will print the entire window.
So little confused with that...!

A: Don't use jQuery ... use css and media=print.  Here is an article for reference, and here.
Basically, create a new stylesheet for what you want to show when you print, and set the media to print:
<link rel="stylesheet" type"text/css" href="print.css" media="print">

A: You could probably put the content in an iframe and call print() on that window.
A quick google gave me http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=449 which mentions you must focus() before you print(). Note that that page is a few years old.
Also see How do I print an IFrame from javascript in Safari/Chrome.

A: Styling html for printing is commonly achieved using a different style sheet, e.g. in your head element:
<head>
    ...

    <link rel="stylesheet" type="text/css" media="screen" href="style.css">
    <link rel="stylesheet" type="text/css" media="print" href="print.css">
    ...

</head>

The style sheet style.css is used to style your html on screen, while print.css is used to style your html for print. By providing the appropriate styling in print.css you can easily show or hide html elements to achieve the output you are looking for.


Q: Keras LSTM + TensorFlow and a number sequence (improve loss) first of all, I'm running with the following setup:

*

*Running on windows 10

*Python 3.6.2

*TensorFlow 1.8.0

*Keras 2.1.6

I'm trying to predict, or at least guesstimate the following number sequence:
https://codepen.io/anon/pen/RJRPPx (limited to 20,000 for testing), the full sequence contains about one million records.
And here is the code (run.py)
import lstm
import time
import matplotlib.pyplot as plt

def plot_results(predicted_data, true_data):
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(true_data, label='True Data')
    plt.plot(predicted_data, label='Prediction')
    plt.legend()
    plt.show()

def plot_results_multiple(predicted_data, true_data, prediction_len):
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(true_data, label='True Data')
    #Pad the list of predictions to shift it in the graph to it's correct start
    for i, data in enumerate(predicted_data):
        padding = [None for p in range(i * prediction_len)]
        plt.plot(padding + data, label='Prediction')
        plt.legend()
    plt.show()

#Main Run Thread
if __name__=='__main__':
    global_start_time = time.time()
    epochs  = 10
    seq_len = 50

    print('> Loading data... ')

    X_train, y_train, X_test, y_test = lstm.load_data('dice_amplified/primeros_20_mil.csv', seq_len, True)

    print('> Data Loaded. Compiling...')

    model = lstm.build_model([1, 50, 100, 1])

    model.fit(
        X_train,
        y_train,
        batch_size = 512,
        nb_epoch=epochs,
        validation_split=0.05)

    predictions = lstm.predict_sequences_multiple(model, X_test, seq_len, 50)
    #predicted = lstm.predict_sequence_full(model, X_test, seq_len)
    #predicted = lstm.predict_point_by_point(model, X_test)

    print('Training duration (s) : ', time.time() - global_start_time)
    plot_results_multiple(predictions, y_test, 50)

I have tried to:

*

*increase and decrease epochs.

*increase and decrease batch size.

*amplify the data.

The following plot represents:

*

*epochs  = 10

*batch_size = 512

*validation_split = 0.05

As well, as far as I understand, the loss should be decreasing with more epochs? Which doesn't seem to be happening!
Using TensorFlow backend.
> Loading data...
> Data Loaded. Compiling...
> Compilation Time :  0.03000473976135254
Train on 17056 samples, validate on 898 samples
Epoch 1/10
17056/17056 [==============================] - 31s 2ms/step - loss: 29927.0164 - val_loss: 289.8873
Epoch 2/10
17056/17056 [==============================] - 29s 2ms/step - loss: 29920.3513 - val_loss: 290.1069
Epoch 3/10
17056/17056 [==============================] - 29s 2ms/step - loss: 29920.4602 - val_loss: 292.7868
Epoch 4/10
17056/17056 [==============================] - 27s 2ms/step - loss: 29915.0955 - val_loss: 286.7317
Epoch 5/10
17056/17056 [==============================] - 26s 2ms/step - loss: 29913.6961 - val_loss: 298.7889
Epoch 6/10
17056/17056 [==============================] - 26s 2ms/step - loss: 29920.2068 - val_loss: 287.5138
Epoch 7/10
17056/17056 [==============================] - 28s 2ms/step - loss: 29914.0650 - val_loss: 295.2230
Epoch 8/10
17056/17056 [==============================] - 25s 1ms/step - loss: 29912.8860 - val_loss: 295.0592
Epoch 9/10
17056/17056 [==============================] - 28s 2ms/step - loss: 29907.4067 - val_loss: 286.9338
Epoch 10/10
17056/17056 [==============================] - 46s 3ms/step - loss: 29914.6869 - val_loss: 289.3236

Any recommendations? How could I improve it? Thanks!
Lstm.py contents:
import os
import time
import warnings
import numpy as np
from numpy import newaxis
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' #Hide messy TensorFlow warnings
warnings.filterwarnings("ignore") #Hide messy Numpy warnings

def load_data(filename, seq_len, normalise_window):
    f = open(filename, 'rb').read()
    data = f.decode().split('\n')

    sequence_length = seq_len + 1
    result = []
    for index in range(len(data) - sequence_length):
        result.append(data[index: index + sequence_length])

    if normalise_window:
        result = normalise_windows(result)

    result = np.array(result)

    row = round(0.9 * result.shape[0])
    train = result[:int(row), :]
    np.random.shuffle(train)
    x_train = train[:, :-1]
    y_train = train[:, -1]
    x_test = result[int(row):, :-1]
    y_test = result[int(row):, -1]

    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))

    return [x_train, y_train, x_test, y_test]

def normalise_windows(window_data):
    normalised_data = []
    for window in window_data:
        normalised_window = [((float(p) / float(window[0])) - 1) for p in window]
        normalised_data.append(normalised_window)
    return normalised_data

def build_model(layers):
    model = Sequential()

    model.add(LSTM(
        input_shape=(layers[1], layers[0]),
        output_dim=layers[1],
        return_sequences=True))
    model.add(Dropout(0.2))

    model.add(LSTM(
        layers[2],
        return_sequences=False))
    model.add(Dropout(0.2))

    model.add(Dense(
        output_dim=layers[3]))
    model.add(Activation("linear"))

    start = time.time()
    model.compile(loss="mse", optimizer="rmsprop")
    print("> Compilation Time : ", time.time() - start)
    return model

def predict_point_by_point(model, data):
    #Predict each timestep given the last sequence of true data, in effect only predicting 1 step ahead each time
    predicted = model.predict(data)
    predicted = np.reshape(predicted, (predicted.size,))
    return predicted

def predict_sequence_full(model, data, window_size):
    #Shift the window by 1 new prediction each time, re-run predictions on new window
    curr_frame = data[0]
    predicted = []
    for i in range(len(data)):
        predicted.append(model.predict(curr_frame[newaxis,:,:])[0,0])
        curr_frame = curr_frame[1:]
        curr_frame = np.insert(curr_frame, [window_size-1], predicted[-1], axis=0)
    return predicted

def predict_sequences_multiple(model, data, window_size, prediction_len):
    #Predict sequence of 50 steps before shifting prediction run forward by 50 steps
    prediction_seqs = []
    for i in range(int(len(data)/prediction_len)):
        curr_frame = data[i*prediction_len]
        predicted = []
        for j in range(prediction_len):
            predicted.append(model.predict(curr_frame[newaxis,:,:])[0,0])
            curr_frame = curr_frame[1:]
            curr_frame = np.insert(curr_frame, [window_size-1], predicted[-1], axis=0)
        prediction_seqs.append(predicted)
    return prediction_seqs

Addendum:
At nuric suggestion I modified the model as following:
def build_model(layers):
    model = Sequential()
    model.add(LSTM(input_shape=(layers[1], layers[0]), output_dim=layers[1], return_sequences=True))
    model.add(Dropout(0.2))
    model.add(LSTM(layers[2], return_sequences=False))
    model.add(Dropout(0.2))
    model.add(Dense(output_dim=layers[3]))
    model.add(Activation("linear"))
    model.add(Dense(64, input_dim=50, activation='relu'))
    model.add(Dense(32, activation='relu'))
    model.add(Dense(1))
    start = time.time()
    model.compile(loss="mse", optimizer="rmsprop")
    print("> Compilation Time : ", time.time() - start)
    return model

Still a bit lost on this one...

A: Even though you normalise the input, you don't normalise the output. The LSTM by default has a tanh output which means you will have a limited feature space, ie the dense layer won't be able to regress to large numbers.
You have a fixed length numerical input (50,), directly pass that to Dense layers with relu activation and will perform better on regression tasks, something simple like:
model = Sequential()
model.add(Dense(64, input_dim=50, activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(1))

For regression it is also preferable to use l2 regularizers instead of Dropout because you are not really feature extracting for classification etc.


Q: angular2 / RxJS - how to retry from inside subscribe() this is my code:
this._api.getCompanies().subscribe(
    res => this.companies = JSON.parse(res),
    exception => {if(this._api.responseErrorProcess(exception)) { // in case this retured TRUE then I need to retry() } }
)

in case an exception happened, it will be sent to a function in the API then return true if the problem is fixed (like token refreshed for example) and it just needs to retry again after its fixed
I could not figure out how to make it retry.

A: In your .getCompanies() call right after the .map add a .retryWhen:
.retryWhen((errors) => {
    return errors.scan((errorCount, err) => errorCount + 1, 0)
                 .takeWhile((errorCount) => errorCount < 2);
});

In this example, the observable completes after 2 failures (errorCount < 2).

A: You mean something like this?
this._api.getCompanies().subscribe(this.updateCompanies.bind(this))

updateCompanies(companies, exception) {
    companies => this.companies = JSON.parse(companies),
    exception => {
        if(this._api.responseErrorProcess(exception)) {
            // in case this retured TRUE then I need to retry()
            this.updateCompanies(companies, exception)
        }
    }
}


Q: generic casting from object-boxed type Why does this work:
decimal dec = new Decimal(33);
double dd = (double) dec;
Console.WriteLine(dd);

But not this:
decimal dec = new Decimal(33);
object o = (object)dec;
double dd = (double) o;
Console.WriteLine(dd);

The second example throws:

System.InvalidCastException: Specified cast is not valid.

This question comes from a situation where I have a generic method
public T GetValue(string q)

That gets values from a datasource. The types of these values are unknown, but the method assumes that it can cast the value to T. Sometimes the value will be object{decimal} and T will be double, in which case the InvalidCastException will be thrown. But in principle this should not be an issue since the value is a decimal (albeit boxed by an object) which can be cast to double.
How do I handle this generically?

A: The latter doesn't work because the decimal value is boxed into an object. That means to get the value back you have to unbox first using the same syntax of casting, so you have to do it in 2 steps like this:
double dd = (double) (decimal) o;

Note that the first (decimal) is unboxing, the (double) is casting.

A: This can be done with Convert.ChangeType:
class Program
{
    static void Main(string[] args)
    {
        decimal dec = new Decimal(33);
        object o = (object)dec;
        double dd = GetValue<double>(o);
        Console.WriteLine(dd);
    }

    static T GetValue<T>(object val)
    {
        return (T)Convert.ChangeType(val, typeof(T));
    }
}

The reason your code doesn't work has been well explained by others on this post.

A: You can only cast boxed value types back to the exact type that was boxed in. It doesn't matter if there is an implicit or explicit conversion from the boxed type to the one you are casting to -- you still have to cast to the boxed type (in order to unbox) and then take it from there.
In the example, this means two consecutive casts:
double dd = (double) (decimal) o;

Or, using the Convert methods:
double dd = Convert.ToDouble(o);

Of course this won't do for your real use case because you cannot immediately go from a generic type parameter to ToDouble. But as long as the target type is IConvertible, you can do this:
double dd = (double)Convert.ChangeType(o, typeof(double));

where the generic type parameter T can be substituted for double.


Q: extracting words from a sentence using indexOf and substring and storing them in an array in java Here is what I have so far for this part of my program;
String text = JOptionPane.showInputDialog("enter a sentence");

String newWord = "";
char space = '_';
int count = 0;

for(int i = 0; i < text.length(); i++)
{
  int found = text.indexOf(space, i);

  int start = found + 1; // start location of substring after a space
  int end = text.indexOf(space, start); // end of word
  count = end + 1;
}
  while(count < text.length())
  {

newWord[count] = text.substring(start, end);

  count++;

}

System.out.println(newWord[count]);

A: to split a sentence, use String's .split() method
String [] splitter = text.split(" ");

this will break the sentence based on spaces. Then you can do whatever you need to the array

A: String text = JOptionPane.showInputDialog("Enter a sentence");
int count = 0;
char space = ' ';

int index = 0;
do
{
   ++ count;
   ++ index;
   index = text.indexOf(space, index);
}
while (index != -1);

    String[] array = new String[count];
    index = 0;
    int endIndex = 0;
    for(int i = 0; i < count; i++)
    {
      endIndex = text.indexOf(space, index);

      if(endIndex == -1)
     {
       array[i] = text.substring(index);
     }else{
       array[i] = text.substring(index, endIndex);
     }

     index = endIndex + 1;
    }
    for(String s : array)
    {
      System.out.println(s);
    }


Q: IBM MQ transmission queue exclusive lock I have a WebSphere MQ Queue Manager with transmission queue defined and I'm using API to get some information about the queue. When trying to inquire the queue (using .NET interface, but I believe this is not important here), I always receive an exception with reason 2042: MQRC_OBJECT_IN_USE - according to the documentation, this means that there's an exclusive lock at the queue. By some further investigation I can see that the process holding the lock is runmqchl - part of MQ Server.

*

*Is the exclusive lock typical for transmission queues?

*Or this means that there's something wrong with the queue or the transmission?

*Even better, maybe there is a way to do some inquiries (read-only) to that locked queue (i.e. to get its depth or browse the messages) using API?

A: The SDR or SVR channel will always open the transmission queue for exclusive use.  If the .Net client is getting an error because of this then it is asking for input rights as well as inquire.  You can verify this by using WMQ Explorer to inquire on the queue and you will see that it has no problem getting queue attributes, depths, etc.  So open for inquire but not browse or get and you should be fine.


Q: React change state of one component from another I need to change the state of my sidebar component from another component.
My code:
Sidebar.tsx >
const SideBar: React.FC = () => {

    const [open, setOpen] = useState<boolean>(false);

    function switchSidebar() {
       setOpen(!open);
    }

    const bar = useMemo(() => <Menu open={open} sidebar={true} />, [open])

        return (
           <>
              <SidebarButton />
              { bar }
           </>

}

SidebarButton.tsx >
export const SidebarButton:React.FC = () => {
  return(
        <svg xmlns="http://www.w3.org/2000/svg" onMouseDown={/* ? */}>
            <path stroke="currentColor" strokeWidth={3} d="M0 1.5h28M0 10.5h28M8 19.5h20"/>
        </svg>
 )
}

Menu.tsx >
const Menu: React.FC = ({sidebar, open, data = HeaderData}) => {
       return (
         <ul>
            <SidebarButton />
            { /* Other things to render */ }
         </ul>
       )
}

How you can see I need a method to change the state that is contained in Sidebar from SidebarButton.

A: You can pass the setOpen function as a prop to the SidebarButton component and then simply call the setOpen function to change the value.
<SidebarButton setOpen={setOpen} />

If you would like to also call it from the menu component then you may need to move the declaration of open to a higher component that is common between Sidebar and Menu since props can only be passed downwards.


Q: How to animate (resize) a Linear layout loaded into listview on item click in android Hi i need to animate (resize height and width) a linear layout added into a Listview through adapter in android.

A: I'm not entirely sure as to what you want to do here. If im correct what your looking for is an expanded listview. You can achieve this using the following library it takes two layouts one for the listview item and the second the layout which needs to be expanded when the listview item is clicked
https://github.com/tjerkw/Android-SlideExpandableListView


Q: How to translate whole words into morse-code with a dictionary? I'm writing a program that translates normal text to Morse code and I've written the core program that translates single letters to Morse code I still can't figure out how to translate whole words and text.
more clarification:
 i can translate single letters but i cant translate whole words
Here's the code:
from tkinter import *

#key down function
def click():
    entered_text=textentry.get() #this wil collect the text from the text entry box
    outpout.delete(0.0, END)
    try:
        definition = my_dictionary[entered_text]
    except:
        definition= "sorry an error occured"
    outpout.insert(END, definition)

#### main
window = Tk()
window.title("THIS IS A SIMPLE TITLE")
window.configure(background="yellow")

#create label
Label (window,text="Enter a text here.", bg="YELLOW", fg="BLACK", font="arial 30 bold italic" ) .grid(row=1, column=0, sticky=W)

#create a text entry box
textentry= Entry(window, width=20, bg="WHITE")
textentry.grid(row=2, column=0, sticky=W)

#add a submit button
Button(window, text="SUBMIT", width=6, command=click) .grid(row=3 ,column=0, sticky=W)

#create another label
Label (window,text="THE ENCRYPTED TEXT IS:", bg="YELLOW", fg="BLACK", font="arial 10 bold" ) .grid(row=4, column=0, sticky=W)

#create a text box
outpout = Text(window, width=75, height=6, wrap=WORD, bg="WHITE")
outpout.grid(row=5, column=0, columnspan=2, sticky=W)

#the dictionary
my_dictionary = {
    "A" : ".-",
    "B" : "-...",
    "C" : "-.-.",
    "D" : "-..",
    "E" : ".",
    "F" : "..-.",
    "G" : "--.",
    "H" : "....",
    "I" : "..",
    "J" : ".---",
    "K" : "-.-",
    "L" : ".-..",
    "M" : "--",
    "N" : "-.",
    "O" : "---",
    "P" : ".--.",
    "Q" : "--.-",
    "R" : ".-.",
    "S" : "...",
    "T" : "-",
    "U" : "..-",
    "V" : "...-",
    "W" : ".--",
    "X" : "-..-",
    "Y" : "-.--",
    "Z" : "--..",
    " " : "/"
    }
#run the main loop
window.mainloop()

A: I think the issue is that you are trying to use the entire text as the key to the dictionary. So, if the text "A" is entered into the text input then it works as "A" is a key in my_dictionary. If the text "AS" is entered into the text box, this will fail as there is no key "AS" in my_dictionary.
What you will want to do, therefore, is loop over each of the characters in the entered string and add the Morse value of that letter to your definition string. You will also want to make sure that the letter is uppercase (unless it is guaranteed that the input will be upper case). This is done using the string .upper() method in the following example. Something like the following should do what you want.
definition = str()  # Create a blank string to add the Morse code to

# Go through each letter and add the Morse definition of the letter to definition
for letter in entered_text:
    definition += my_dict[letter.upper()]  # The upper makes sure the letter is a capital so that there will be a match in my_dict


Q: Does Flask trim  items? Within Flask and using Jinja2, I'm calling a datalist but for some reason any option with a space is trimmed so "tomato sauce" becomes "tomato". Is this something Flask is doing or have I messed up the templating?
<!-- HOMEPAGE -->
<form type="text" id="homeForm" class="centered" method="post" onsubmit="return false;">
        {{ form.hidden_tag() }}
        <input type="text" id="homeInput" autocomplete=off list="topps" placeholder="Input here">
        <datalist id="topps">
            {% for top in topps %}
            <option value={{ top }}>
            {% endfor %}
        </datalist>
        <button type="submit" id="homeSubmit">Submit</button>
</form>

# ROUTES.PY #
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    form = ToppingsForm()
    topps = ["tomato sauce", "chilli flakes","something else"]
    return render_template('index.html', title='Home', form=form, topps=topps)

A: Your problem is here:
<option value={{ top }}>

add quotes outside of {{top}}
<option value="{{ top }}" />


Q: ProxySQL between master/slave replication on flaky connection I have two MySQL servers with master/slave replication between them. The connection between them is ADSL. It is not reliable at all. I decided to add another ADSL connection from another ISP with its own IP address.
The problem is that when when one ADSL connection goes down, the other one is useless because the slave is using the first connection's IP address which is down now.
I want to know if is it possible to put a proxysql node between and give its IP to the slave.
Is it possible for proxysql to do fail-over connection handling for the same node? Proxysql must choose the second IP address when the first one is not available.

A: ADSL is generally not a fixed IP, which means that the server does not recognize it.
As I understand it, you want to balance the load.
Analyzing your doubt. I leave my case study.
1 - How each server is separate.
Place a fixed IPv4 from there, create a fixed DNS and point to the corresponding fixed IP. Also place a domain and add the DNS configuration. If you have IPv6 (AAA), add it for even more answers. And prioritize cryptography.
If you need a secure proxy, use CloudFlaure to manage your settings. It helps the configuration become more practical.
2 - Pointing the DNS to fixed IP, create NS for both servers.
example: ns1.server.com //// ns2.server.com
I recommend creating 4 NS for each server.
3 - The same procedure is used on the slave. but do not use ns, switch to another silga, for example: (tl1.server.com).
This facilitates orientation.
So, for each server.
An IPv4
An Ipv6
Four NS
Two DNS
Therefore, when the first server goes down, the other server takes over. Be on IPV4 or IPV6. And the DNS and the DNS are congested or are not recognized for some reason, promptly the other takes over. So, without loss.
If there is a problem with your hosting, create IP or domains. Due to fees.
There are some free ones and, that work 90%, cloudflare itself has this service.
If I was able to understand your demand, I recommend the services later.
It works for me.
Submit questions and follow the case.

A: My Idea.
You use dynamic dns to know always, which IP Address is valid, to reach the site with the spotty connection.
A fail over Router like the one in the comment, has the advantage, that it always knows which connection is the better one, and actualizes the dyndns serverip.
For the rest, i would see that both sites build a vpn. Most router can be VPN server as also client and with the dynamic Ip, establishing the connection is no problems, as long any connection actually work. For your replication it is the same network, with a fixed ip.
If you have already a ssl server,all is the same, only you need to bridge the port, so that packet will enter the network.
For all that, you should get some help, because the are many points that can be tweaked, to fit the situation on side.


Q: Aframe + Meteor - Add a conditional custom component to an entity <a-gltf-model id='playerone' {{#if myplayer playerone}}entitymove{{/if}} src="#myMixBun"> </a-gltf-model>

Using Aframe in Meteor, I want to add the custom component “entitymove” if the value of myplayer is “playerone”.
The value of {{myplayer}} is “playerone” in main.html, so the variable is set correctly. But I get the Meteor error “A template tag of type BLOCKOPEN is not allowed here”.
If “entitymove” was a “class”, for instance,  I think I could solve this with the following:
<a-gltf-model id='playerone' class={{#if myplayer playerone}}entitymove{{/if}}  src="#myMixBun"> </a-gltf-model>

But since it’s a component, I am at a loss as to how to fix the syntax.

A: Assuming that this uses Meteor-Blaze templates you need to include the conditionals for DOM element attributes inside quotes/double quotes:
<a-gltf-model id='playerone' class="{{#if myplayer playerone}}entitymove{{/if}}"  src="#myMixBun"> </a-gltf-model>

Readings:
http://blazejs.org/guide/spacebars.html

A: SOLVED
This is my original, which doesn’t work.
In main.js:
player = "player not active";

Template.hello.helpers(
  counter() {......

// if player one
player = "playerone";
// if player two
player = "playertwo";

return { myplayer: player };
  }

In main.html:
// This statement works
{{counter.myplayer}}....

<a-gltf-model id='playerone' class="{{#if counter.myplayer playerone}}entitymove{{/if}}"  src="#myMixBun"> </a-gltf-model>

<a-gltf-model id='playertwo' class="{{#if counter.myplayer playertwo}}entitymove{{/if}}"  src="#myMixBun"> </a-gltf-model>

I think there are 2 problems with this:
1) spacebars doesn’t seem to like the if statement with a comparison?:
{{#if counter.myplayer playertwo}}

It only allows true or false if statements?, such as:
{{#if counter.player1}}

2) My aframe custom component isn’t actually a class, so I can’t put the meteor #if statement inside the  entity.
I changed the code to the following and it now works:
Changed main.js to:
playerone ="";
playertwo ="";

// if player one
     playerone = "true";
    playertwo = "";

// if player two
     playerone = "";
    playertwo = "true";
 return { player1: playerone, player2: playertwo};
  }

Changed main.html to:
// These statements work
{{#if counter.player1}}player1 is true{{/if}}
{{#if counter.player2}}player2 is true{{/if}}....

{{#if counter.player1}}
 <a-gltf-model id='playerone' entitymove   src="#myMixBun" ></a-gltf-model>
 <a-gltf-model id='playertwo'   src="#myMixBun" ></a-gltf-model>
 {{/if}}

  {{#if counter.player2}}
 <a-gltf-model id='playerone'  src="#myMixBun" ></a-gltf-model>
 <a-gltf-model id='playertwo' entitymove   src="#myMixBun" ></a-gltf-model>
 {{/if}}


Q: count frequency group by pandas I am trying to add a new column to a data below, in which columns Algorithm1,2 & 3 are derived from Text column. I want to count each element in the 3 columns and create new column to only have elements which have count > 1
df = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'],
                     'Algorithm1': ['AX','AB','AAB'],
                     'Algorithm2' : ['BX','AAX','AB'],
                     'Algorithm3' : ['AX','AB','AAX']})

This is how the final output should look like with columns values AB, AX & AAX as they have frequency > 1
df2 = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'],
                     'Algorithm1': ['AX','AB','AAB'],
                     'Algorithm2' : ['BX','AAX','AB'],
                     'Algorithm3' : ['AX','AB','AAX'],
                   'Majority': ['AB','AX','AAX']})

A: IIUC count values in Algorithm columns and filter if greater like 1:
df = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'],
                     'Algorithm1': ['AX','AB','AAB'],
                     'Algorithm2' : ['BX','AAX','AB'],
                     'Algorithm3' : ['AX','AB','AAX']})
s = df.filter(like='Algorithm').stack().value_counts()
m = s.gt(1)
print (s)
AB     3
AX     2
AAX    2
AAB    1
BX     1
dtype: int64

df['new'] = pd.Series(s.index[m])[:m.sum()]
print (df)
        T Algorithm1 Algorithm2 Algorithm3  new
0  AAABBX         AX         BX         AX   AB
1  AAABBX         AB        AAX         AB   AX
2  AAABBX        AAB         AB        AAX  AAX

If number of values is greater like length of DataFrame:
df = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'],
                     'Algorithm1': ['AX','AB','AAB'],
                     'Algorithm2' : ['AAX','AAX','AB'],
                     'Algorithm3' : ['AX','AB','AAB']})

s = df.filter(like='Algorithm').stack().value_counts()
m = s.gt(1)
print (s)
AB     3
AAB    2
AX     2
AAX    2
dtype: int64

df['new'] = pd.Series(s.index[m])[:m.sum()]
print (df)
        T Algorithm1 Algorithm2 Algorithm3  new
0  AAABBX         AX        AAX         AX   AB
1  AAABBX         AB        AAX         AB  AAB
2  AAABBX        AAB         AB        AAB   AX

If number of values is less like length of DataFrame:
df = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'],
                     'Algorithm1': ['AX','AB','AX'],
                     'Algorithm2' : ['AA','AAX','AB'],
                     'Algorithm3' : ['AX','AB','AX']})

s = df.filter(like='Algorithm').stack().value_counts()
m = s.gt(1)
print (s)
AX     4
AB     3
AAX    1
AA     1
dtype: int64

df['new'] = pd.Series(s.index[m])[:m.sum()]
print (df)
        T Algorithm1 Algorithm2 Algorithm3  new
0  AAABBX         AX         AA         AX   AX
1  AAABBX         AB        AAX         AB   AB
2  AAABBX         AX         AB         AX  NaN


Q: how to strip a txt file of multiple things? I am creating a function which reads data of a txt file, the text file is set up as one sentence per line. I have 6 requirements to strip the file of to make it usable later on in my program:
 1. Make everything lowercase
 2. Split the line into words
 3. Remove all punctuation, such as “,”, “.”, “!”, etc.
 4. Remove apostrophes and hyphens, e.g. transform “can’t” into “cant” and
 “first-born” into “firstborn”
 5. Remove the words that are not all alphabetic characters (do not remove
 “can’t” because you have transformed it to “cant”, similarly for
 “firstborn”).
 6. Remove the words with less than 2 characters, like “a”.

Here's what I have so far...
def read_data(fp):
    file_dict={}
    fp=fp.lower
    fp=fp.strip(string.punctuation)
    lines=fp.readlines()

I am a little stuck, so how do I strip this file of these 6 items?

A: This can be accomplished via a series of regex checks and then a loop to remove all items with less than 2 characters:
Code
import re

with open("text.txt", "r") as fi:
    lowerFile = re.sub("[^\w ]", "", fi.read().lower())
    lowerFile = re.sub("(^| )[^ ]*[^a-z ][^ ]*(?=$| )", "", lowerFile)
    words = [word for word in lowerFile.split() if len(word) >= 2]
    print(words)

Input
I li6ke to swim, dance, and Run r8un88.

Output
['to', 'swim', 'dance', 'and', 'run']


Q: Use imagemin in Cloud Functions for Firebase I've got a cloud function for Firebase that triggers on a storage bucket write:
exports.convertToWebP = functions.storage.object().onChange(async event => {
    const path = event.data.name;
    const [pictureSlug, fileName] = path.split('/');
    const [fileSlug, fileType] = fileName.split('.');

    // Download the file
    const tmpFilePath = `/tmp/${fileSlug}.${fileType}`;

    const file = bucket.file(path);
    await file.download({ destination: tmpFilePath });

    await imagemin(
          [`tmp/${fileSlug}.${fileType}`],
          '/tmp',
          { use: [ imageminWebp({quality: 50})] });

    const destination = `${pictureSlug}.webp`;
    await bucket.upload(tmpFilePath, { destination });

The issue I'm having is that when I call the .download method on the storage object, it goes to the /tmp/ folder, but I can't for the life of me figure out how to get imagemin to grab the file.
It could have something to do with the way I'm constructing the path, or it could be something else like Cloud Functions not supporting imagemin.
The reason I'm doing this to being with is because the local instance of ImageMagick doesn't support webp.
Also: This file is a .ts file and I'm using the typescript compiler to create a js file of it. It compiles to an ES5 version.

A: In this bit of code:
await imagemin(
      [`tmp/${fileSlug}.${fileType}`],
      '/tmp',
      { use: [ imageminWebp({quality: 50})] });

It looks like you're building a different string to the tmp file than you did when you built tmpFilePath.  It's missing the leading slash.  Any reason why you wouldn't use this instead?
await imagemin(
      [tmpFilePath],
      '/tmp',
      { use: [ imageminWebp({quality: 50})] });


Q: chart.js / angular-chart line outside style issue I have a strange issue with angular-chart.js (which use chart.js).
If I set and block the min and max values for yAxis,  when the line goes out of the limits the style is strange. Do you have an idea about what occurs ?

Here is the configuration for each 3 chart :
    ChartJsProvider.setOptions({
    responsive: true,
    animation: false,
    pointDot: false,
    colours: [{ // blue
        fillColor: 'rgba(0,0,0,0)',
        strokeColor: 'rgba(51,87,205,1)',
        pointColor: 'rgba(51,87,205,1)',
        pointStrokeColor: 'rgba(51,87,205,1)',
        pointHighlightFill: 'rgba(0,0,0,0)',
        bezierCurve: true,
        pointHitDetectionRadius: 20,
        datasetStroke: false,
    }, { // blue
        fillColor: 'rgba(0,0,0,0)',
        strokeColor: '#FB3333',
        pointColor: '#FB3333',
        pointStrokeColor: '#FB3333',
        pointHighlightFill: 'rgba(0,0,0,0)',
    }],
    maintainAspectRatio: false,
    showXLabels: 10,
    showTooltips: true,
    multiTooltipTemplate: function(label) {

        return label.datasetLabel + " : " + label.value.toFixed(1);
    }

});

And for each chart I applied an other configuration :
    $scope.optionsG1 = {
    scaleStartValue: -2,
    scaleStepWidth: 1,
    scaleOverride: true,
    scaleSteps: 4
};

Thanks for your help

A: Set bezierCurve: false for the charts where you are having this problem.


Q: Get Current Path of Page in Middleman Layout File Is it possible to retrieve the current path of a page in a middleman file?  For instance, if I have a layout file layout.erb with something like the following:
<%= page.path %>
<%= yield %>

and a test file index.html:
Testing

then when Middleman rendered the page I would get something like:
/index.html
Testing

A: Middleman also provides the current_page variable.  current_page.path is the source path of this resource (relative to the source directory, without template extensions) and current_page.url is the path without the directory index (so foo/index.html becomes just foo).
<%= current_page.path %>
# -> index.html

<%= current_page.url %>
# -> /

Details from Middleman's Middleman::Sitemap::Resource rubydoc.
http://rubydoc.info/github/middleman/middleman/Middleman/Sitemap/Resource

A: The solution is:
<%= request.path %>


Q: Calculate average value between two cell phone recharges I have a cell phone recharge table which is as below.
In that at UserId,Date level I have particular user's Balance amount, the amount which he consumed at a particular day for voice communication and amount that was consumed for data (internet) usage.
Whenever the user recharges his account the Balance increases.
So I want a query which could help me to find the average Voice and Data amount/balance between two recharges for each user.
Recharge Table
+--------+-----------+---------+-------+------+
| Userid |   Date    | Balance | Voice | Data |
+--------+-----------+---------+-------+------+
|      1 | 4/5/2018  |     100 |    10 |   15 |  //Recharge of 100
|      1 | 4/6/2018  |      75 |     5 |   10 |
|      1 | 4/7/2018  |      60 |    10 |   10 |
|      1 | 4/8/2018  |      90 |    10 |   20 | //Recharge of 50
|      1 | 4/9/2018  |      60 |    10 |   20 |
|      1 | 4/10/2018 |      50 |    20 |   30 |// Recharge of 20
|      2 | 4/1/2018  |     200 |    50 |   40 |// Recharge of 200
|      2 | 4/2/2018  |     110 |    20 |   20 |
|      2 | 4/3/2018  |      70 |    20 |   10 |
|      2 | 4/4/2018  |      55 |    10 |   40 |// Recharge of 15
|      2 | 4/5/2018  |      5  |    2  |   2  |
+--------+-----------+---------+-------+------+

In the above table
A given day's Balance = Previous Day's (Balance - SUM(Voice + Data))
As you can see for UserId 1 100 gets reduced to 75 (100 - (10 + 15)).
But in the third row(Date = 4/8/2018) he recharges by an amount of 50 due to which his balance becomes 90 instead of 40.
So I want to find the average Voice and Data column between 100 and 90 for UserId = 1
Below is the output I want
+--------+-------------+-----------+----------+
| UserID | RechageDate | Avg_Voice | Avg_Data |
+--------+-------------+-----------+----------+
|      1 | 4/8/2018    |      8.33 |    11.66 |
|      1 | 4/10/2018   |        10 |       20 |
|      2 | 4/4/2018    |      27.5 |       25 |
+--------+-------------+-----------+----------+

I know the question is difficult to understand but I have tried my best to explain it.
Please feel free to ask in case of any ambiguity.

A: I have Added two new column to determine the recharge information:
I think you have recharge information in another table, if you can put that information like i did this query will work.
DECLARE @tbl table(
    Userid int,
    Date    datetime,
    Balance int,
    Voice int,
    Data int,
    Recharge int,
    RechargeSN int
)

INSERT INTO @tbl(    Userid,    [Date],    Balance,    Voice,    Data,Recharge,RechargeSN) VALUES(1,'4/5/2018'  ,     100 ,    10 ,   15,100,3)
INSERT INTO @tbl(    Userid,    [Date],    Balance,    Voice,    Data,Recharge,RechargeSN) VALUES(1,'4/6/2018'  ,      75 ,     5 ,   10,0,3)
INSERT INTO @tbl(    Userid,    [Date],    Balance,    Voice,    Data,Recharge,RechargeSN) VALUES(1,'4/7/2018'  ,      60 ,    10 ,   10,0,3)
INSERT INTO @tbl(    Userid,    [Date],    Balance,    Voice,    Data,Recharge,RechargeSN) VALUES(1,'4/8/2018'  ,      90 ,    10 ,   20,50,2)
INSERT INTO @tbl(    Userid,    [Date],    Balance,    Voice,    Data,Recharge,RechargeSN) VALUES(1,'4/9/2018'  ,      60 ,    10 ,   20,0,2)
INSERT INTO @tbl(    Userid,    [Date],    Balance,    Voice,    Data,Recharge,RechargeSN) VALUES(1,'4/10/2018' ,      50 ,    20 ,   30,20,1)

INSERT INTO @tbl(    Userid,    [Date],    Balance,    Voice,    Data,Recharge,RechargeSN) VALUES(2,'4/1/2018'  ,     200 ,    50 ,   40,200,2)
INSERT INTO @tbl(    Userid,    [Date],    Balance,    Voice,    Data,Recharge,RechargeSN) VALUES(2,'4/2/2018'  ,     110 ,    20 ,   20,0,2)
INSERT INTO @tbl(    Userid,    [Date],    Balance,    Voice,    Data,Recharge,RechargeSN) VALUES(2,'4/3/2018'  ,      70 ,    20 ,   10,0,2)
INSERT INTO @tbl(    Userid,    [Date],    Balance,    Voice,    Data,Recharge,RechargeSN) VALUES(2,'4/4/2018'  ,      55 ,    10 ,   40,15,1)
INSERT INTO @tbl(    Userid,    [Date],    Balance,    Voice,    Data,Recharge,RechargeSN) VALUES(2,'4/5/2018'  ,      5  ,    2  ,   2,0,1)

--SELECT * FROM @tbl t

SELECT userid, RechageDate  = max(date), Avg_Voice = (cast(SUM(voice) AS numeric) / Count(voice))  , Avg_Data = cast(SUM(Data) AS numeric) / Count(Data) *1.00
--, t.RechargeSN
FROM @tbl t
GROUP BY t.Userid, t.RechargeSN
ORDER BY t.Userid

A: Since you haven't posted any attempt to solve this, but have shown an understanding of the data, I assume you just need to be given a broad strategy to begin following, and you can handle the coding from there.
Using LAG() partitioned by UserID, you can join each row to the previous row.  You already have stated that you understand that  (Balance - SUM(Voice + Data)), so in any CASE where that is not true, then you know that you have found a row where a recharge was done.
You can create an artificial column (eg HasRecharge) in a CTE that uses a CASE expression to test this and return 1 for the rows that have a recharge, and 0 for the rows that don't.
Then you can do a 2nd CTE where you SELECT from the first CTE WHERE HasRecharge=1 and WHERE there EXISTS() a previous row that also HasRecharge=1.  And calculate two additional columns:
A SUM of Voice + Data between this recharge and the last recharge (again using LAG() but this time WHERE HasRecharge=1)
A COUNT of rows between this recharge and the last.
Your final SELECT from the 2nd CTE would get the average simply by dividing the SUM column by the COUNT column.

A: This problem becomes simpler when you have a flat table containing the day's charge, and the previous day's charge. Note that this will only work if your data set  has a contiguous range of dates.
The following queries will need to be edited of course:
Select
 currentday.Date,
 currentday.user,
 currentday.balance - prevday.balance - (currentday.voice+currentday.data) as charge,
 currentDay.voice,
 currentDay.data,
 --The above column will tell you what the difference
 --is between the expected balance, and should
 --resolve to the charge for the day
 GETDATE() as nextCharge
 --leave this empty, use GETDATE() to force it to be a datetime
into ##ChargeTable
from [RechargeTable] currentday
 left join [RechargeTable] prevday
   on DATEADD(d,1,prevday.Date) = currentday.Date
      AND prevday.user = currentday.user

Now, we know when the user has charged. The charge column will be positive.
Select
 user,
 date
into ##uniquedates
from ##charge
where charge>0

Now that we have the dates, we need to go back to the first temp table and update it with the next dates. (not sure on the syntax on aliasing updates).
update ##ChargeTable up
set
nextCharge = (
    select
     date
    from ##uniquedates
    where up.user == user AND date > up.date
)

Now we can do some sub selects back on the table to get the data we need.
select
 user,
 (select
       avg(voice)
      from ##ChargeTable
      where user = ct.user
       and date>=ct.date
       and date<=ct.nextCharge) as AvgVoice,
 (select
       avg(data)
      from ##ChargeTable
      where user = ct.user
       and date>=ct.date
       and date<=ct.nextCharge) as AvgData
from ##ChargeTable ct
where nextCharge is not null and charge>0


Q: How to detect a scroll / wheel event only once in a certain period of time? Let's say I have a scroll/wheel event like this:
container.addEventListener("wheel", (e) => {
  const isScrollingDown = Math.sign(e.wheelDeltaY);

  // call some function once, don't listen for wheel event anymore
  // then listen for event again when done
}

Based on deltaY, I detect whether a user is scrolling down, or up. How would I call a function only once when I detect this (which is immediatly), remove the event listener, and then listen for it again when my function is complete?
I can't remove the event listener from inside my event listener right?
Thanks in advance.

A: You can use removeEventListener() function. documentation
example:
let wheelHandler = function(e) {
    toggleListener(wheelHandler, false)
    const isScrollingDown = Math.sign(e.wheelDeltaY);
    // call some function once, don't listen for wheel event anymore
    // then listen for event again when done
    toggleListener(wheelHandler, true)
};
let toggleListener = function(listener, add) {
    if (add) {
        container.addEventListener("wheel", wheelHandler)
    } else {
        container.removeEventListener("wheel", wheelHandler)
    }
}
toggleListener(wheelHandler, true);

A: wait 1 second after first wheel:

    function handleWheel(e){
          console.log(Math.random())
          document.getElementById("container").removeEventListener("wheel", handleWheel)

          setTimeout(()=>{
            document.getElementById("container").addEventListener("wheel", handleWheel);
          },1000); // return event after 1 second
    }

    document.getElementById("container").addEventListener("wheel", handleWheel)

wheel

A: you can define loading variable and check each time before run function
var loading = false
container.addEventListener("wheel", (e) => {
  const isScrollingDown = Math.sign(e.wheelDeltaY);

  if(!loading){
      loading = true;
     // call some function once, don't listen for wheel event anymore
     // then listen for event again when done
     // after done
     loading = false
  }
}


Q: insert in select in MySQL with JDBC I would like to have a value from a row inserted into an other row here is my code:
static void addVipMonth(String name) throws SQLException
{
    Connection conn = (Connection) DriverManager.getConnection(url, user, pass);
    PreparedStatement queryStatement = (PreparedStatement) conn.prepareStatement("INSERT INTO vips(memberId, gotten, expires) " +
            "VALUES (SELECT name FROM members WHERE id = ?, NOW(), DATEADD(month, 1, NOW()))"); //Put your query in the quotes
    queryStatement.setString(1, name);
    queryStatement.executeUpdate(); //Executes the query
    queryStatement.close(); //Closes the query
    conn.close(); //Closes the connection
}

This code is not valid. How do I correct it?

A:
I get an error 17:28:46 [SEVERE] com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MyS QL server version for the right syntax to use near ' NOW(), DATE_ADD( now(), INT ERVAL 1 MONTH )' at line 1 –  sanchixx

It was due to error in SELECT .. statement.
Modified statement is:
INSERT INTO vips( memberId, gotten, expires )
   SELECT name, NOW(), DATE_ADD( now(), INTERVAL 1 MONTH )
    FROM members WHERE id = ?

*

*You don't require VALUES key word when inserting with a select.

*You used a wrong DATEADD function syntax. Correct syntax is Date_add( date_expr_or_col, INTERVAL number unit_on_interval).

You can try your insert statement as corrected below:
INSERT INTO vips( memberId, gotten, expires )
   SELECT name FROM members
     WHERE id = ?, NOW(), DATE_ADD( now(), INTERVAL 1 MONTH )

Refer to:

*

*INSERT ... SELECT Syntax

*DATE_ADD(date,INTERVAL expr unit)


Q: Movable parameters in std::thread constructor (Visual C++ 2012) I run into problem with rvalue references in MSVC 2012.
#include <thread>
#include <string>
#include <future>

void foo(std::promise<std::string> &&prms) { /* some code */ }

int main() {
  std::promise<std::string> prms;
  // std::future<std::string> ftr = prms.get_future();
  std::thread th(&foo, std::move(prms));

  // some other code
}

Compiler says: error C2664: 'void (std::promise<_Ty> &&)' : cannot convert parameter 1 from 'std::promise<_Ty>' to 'std::promise<_Ty> &&'
Is there my mistake (then how to fix it) or compiler issue (then I'd like to know origin of such behaviour)?

A: This is a known issue in the Visual C++ 2012 implementation of std::thread.  See the following bug on Microsoft Connect:

std::thread constructor doesn't handle movable object

The response to that bug states:

We attempted to fix this during VC11's development, but it exploded horribly and we had to revert the change. As it turns out, std::thread can't be powered by bind(), because thread needs to move its arguments, and bind() is forbidden from doing so (since bound functors should be repeatedly invokable, without their bound arguments being moved-from). So we'll need to reimplement std::thread's ctor to avoid using bind().


Q: TFS access issue when check in files I have a problem in TFS.
Actually, last time when we are working on ROM (my project name). We (john & me ) both had created a controller with same
name ROController.cs and we noticed this problem (same files Confilct), when we are checking files to TFS.
So, i deleted my file , and let john to check in his file.
Now ,the problem is that when i try to get lastest or even
access that ROController and its View. i got errors like

"you do not have permissoin to access this file."

also in the team explorer , my file is shown as deleted, user name (me)
These are the files properly defining the error status.

This is the Error Shown


Q: Node Outside of openshift cluster can't access pods inside cluster Note I have three nodes (A, B, C) whose ips are 172.18.143.115, 172.18.143.117, 172.18.143.124.
A and B are a openshift cluster using ovs-sdn as its network pulgin, pod network is 10.130.0.0/16, service ip range is 172.30.0.0/16. there is a pod P(10.130.3.249:8002) in node B, and a corresponding
service S(172.30.148.77:8002).
I can curl S in node A or B, but can't do it in node C
So I add a route like if dst_ip is P then goto node A or B.
Then strange things happen, if the route points to B, I can curl S, otherwise if
the route points to A, I can't curl S.
Through tcpdump, i find pod P return a TCP ACK packet to node C through its veth,
then this packet is output to tun0 according to flows in OVS, according to route it should be send by ens192(network interface) since its dst_ip is node C, but i can't catch it on ens192 with tcpdump, it seems like that this packet is droped. Why did this happen?

A: Traffic is only routed within the cluster by default, so if the application on C is not part of the cluster, then ingress and egress won't be possible between the A/B nodes and C. This is all controlled by application's service configuration.
To route ingress and egress traffic from/to outside the cluster, you'll need to configure the service of your application. One of the easier ways to do this is to use the type LoadBalancer service.
You can also use the type NodePort service, which will expose the service on a mapped port in the range of 30000 - 32767 across all nodes.
Lastly, you can assign an External IP to the service to allow outside traffic into the cluster.
Hope this helps!


Q: How to perform a Join using Icriteria nhibernate I am developing an application in MVC3 using nhibernate to fire queries on database.
I have Two Models.
HobbyMasters
HObbyDetail
HobbyMaster class Contains:
HobbyId
and other details

HobbyDetail Class Contains:
HobbyDetaild
HobbyMasters hobbymaster
other detals

Now i want to perform a jon between two tables using Icrteria:
ICriteria criteria = session.CreateCriteria<HobbyDetail>()
                    .CreateAlias("HobbyMasters", "HobbyMasters")
                    .Add(Restrictions.EqProperty("HobbyMasters.HobbyId", "HobbyDetail.hobbymaster.HobbyId"));

Also this:
 HobbyDetail = session.CreateCriteria(typeof(HobbyDetail))
               .CreateAlias("HobbyMasters", "HobbyMasters", NHibernate.SqlCommand.JoinType.InnerJoin)
              .Add(Restrictions.EqProperty("HobbyMasters.hobbymaster.HobbyId", "HobbyDetail.HobbyId"))

But i get an error saying Couldnot Resolve Property HobbyMaster of HobbyDetail Class
Please Help me

A: You can use QueryOver, it's a wrapper on ICriteria with Lambda Expressions:
session.QueryOver<HobbyDetail>()
  .Fetch(hobbyDetail => hobbyDetail.HobbyMasters).Eager
  .TransformUsing(Transformers.DistinctRootEntity)
  .List();


Q: How to extend the context object of a GraphQL call? I'm having the following GraphQL server call in a standard module:
export default () => {
    return graphqlHTTP({
        schema: schema,
        graphiql: true,
        pretty: true,
        formatError: error => ({
            message: error.message,
            locations: error.locations,
            stack: error.stack,
            path: error.path
        })
    });
};

That is used together with passport:
app.use(
    "/graphql",
    passport.authenticate("jwt", { session: false }),
    appGraphQL()
);

Everything is working file. Passport extends my req to get a logged user object that is used on my GraphQL calls to queries or mutations:
...
    resolve(source, args, context) {
        console.log("CURRENT USER OBJECT")
        console.log(context.user)
...

All fine.
Now I need to extend my context to add some custom resolvers, so my first try is:
export default () => {
    return graphqlHTTP({
        schema: schema,
        graphiql: true,
        pretty: true,
        context: resolvers,
        formatError: error => ({
            message: error.message,
            locations: error.locations,
            stack: error.stack,
            path: error.path
        })
    });
};

As GraphQL docs says, this overrides the original req context and my context.user on queries and mutations stops working.
How can I properly extend the current context to add some more fields, instead of overriding it? Another unsuccessfull try:
export default (req) => {
    return graphqlHTTP({
        schema: schema,
        graphiql: true,
        pretty: true,
        context: {
            user: req.user,
            resolvers: resolvers
        },
        formatError: error => ({
            message: error.message,
            locations: error.locations,
            stack: error.stack,
            path: error.path
        })
    });
};

This approach is not working... I'm getting the following error:
  user: req.user,
                ^

TypeError: Cannot read property 'user' of undefined

[edit]
My latest try is from my example on Apollo Docs:
export default () => {
    return graphqlHTTP({
        schema: schema,
        graphiql: true,
        pretty: true,
        context: ({ req }) => ({
            user: req.user
        }),
        formatError: error => ({
            message: error.message,
            locations: error.locations,
            stack: error.stack,
            path: error.path
        })
    });
};

Now my context is a function in my resolver:
console.log(context)
console.log(context.user)

Returns:
[Function: context]
undefined

Getting crazy with this simple thing...

A: Assuming you're using express-graphql, graphqlHTTP is a function that takes some configuration parameters and returns an express middleware function. Normally, it's used like this:
app.use(
  '/graphql',
  graphqlHTTP({ ... })
)

However, instead of an object, graphqlHTTP can also take a function that returns an object as shown in the docs.
app.use(
  '/graphql',
  graphqlHTTP((req, res, graphQLParams) => {
    return { ... }
  })
)

In this way, you can utilize the req, res or graphQLParams parameters inside your configuration object.
app.use(
  '/graphql',
  graphqlHTTP((req, res, graphQLParams) => {
    return {
      schema,
      // other options
      context: {
        user: req.user,
        // whatever else you want
      }
    }
  })
)


Q: Dataframe from complex data structure Say I need to have data stored as follows:
[[[{}][{}]]]

or a list of lists of two lists of dictionaries
where:
{}: dictionaries containing data from individual frames observing an event. (There are two observers/stations, hence two dictionaries.)
[{}][{}]: two lists of all the individual frames related to a single event, one from each observer/station.
[[{}][{}]]: list of all events on a single night of observation.
[[[{}][{}]]]: list of all nights.
Hopefully that's clear. What I want to do is create two pandas dataframes where all dictionaries from station_1 are stored in one, and all dictionaries from station_2 are stored in the other.
My current method is as follows (where data is the above data structure):
for night in range(len(data)):

    station_1 = pd.DataFrame(data[night][0])
    station_2 = pd.DataFrame(data[night][1])

    all_station_1.append(station_1)
    all_station_2.append(station_2)

all_station_1 = pd.concat(all_station_1)
all_station_2 = pd.concat(all_station_2)

My understanding though is that the for loop must be horribly inefficient since I will be scaling the application of this script way up from my sample dataset this cost could easily become unmanageable.
So, any advice for a smarter way of proceeding would be appreciated! I feel like pandas is so user friendly there's gotta be an efficient way of dealing with any kind of data structure but I haven't been able to find it on my own yet. Thanks!

A: I don't think you can really avoid using a loop here, unless you want to invoke jq via sh. See this answer
Anyways, using your full sample, I managed to parse it into a multiindexed dataframe, which I assume is what you want.
import datetime
import re
import json

data=None
with open('datasample.txt', 'r') as f:
    data=f.readlines()
# There's only one line
data=data[0]

# Replace single quotes to double quotes: I did that in the .txt file itself, you could do it using re

# Fix the datetime problem
cleaned_data = re.sub(r'(datetime.datetime\(.*?\))', lambda x: '"'+ str(eval(x.group(0)).isoformat())+'"', data)

Now that the string from the file is valid json, we can load it:
json_data = json.loads(cleaned_data)

And we can process it into a dataframe:
# List to store the dfs before concat
all_ = []
for n, night in enumerate(json_data):
    for s, station in enumerate(night):
        events = pd.DataFrame(station)
        # Set index to the event number
        events = events.set_index('###')
        # Prepend night number and station number to index
        events.index = pd.MultiIndex.from_tuples([(n, s, x) for x in events.index])
        all_.append(events)

df_all = pd.concat(all_)
# Rename the index levels
df_all.index.names = ['Night','Station','Event']
# Convert to datetime
df_all.DateTime = pd.to_datetime(df_all.DateTime)
df_all

(Truncated) Result:


Q: How to Lock Cell based on the value of the another cell and perform data validation I am very new to VBA code. Now I was assigned to make a task that validate the data in an excel sheets.
For Example in my Column A, I have a drop down menu that enable the user to make a selection between "Yes" or "No" only.

*

*If user selected "Yes", cells in Column B and Column C will be marked as Mandatory and cannot be blank. I want to put a validation error on this.
**Example 1: If A1 and A30 == YES**

*

*B1 and C1, B30 and C30 are mandatory

*Will fill a color to the mandatory cells and remove the fill color when     the cells have value already

*Throw a validation error when these cells are blank and if exceeds
the number of characters required.
Example 2: If A99 == NO

*B99 will be locked and the user will not be allowed to enter a data
on this cell. Possible that we can add a cell value as "NA" to avoid
confusion
I was able to capture this using the data validation and conditional formatting. However, I cannot perform the locked functionality since as per research, I need a VBA code for this one.

A: Something like this should work.
Put it into the code module for the sheet you want to apply it to.
Private Sub worksheet_change(ByVal target As Range)

    ''''' CHECK IF THE CHANGED CELL IS IN RANGE A1:A99 (OR ANY OTHER RANGE YOU DEFINE)
    If Not Intersect(target, Range("A1:A99")) Is Nothing Then

        ''''' UNPROTECT THE SHEET
        ActiveSheet.Unprotect

        ''''' IF THE CELL CHANGED IS NOW 'YES'
        If target = "Yes" Then

            ''''' WE DEFINE HOW MANY COLUMNS TO MOVE ACROSS FROM THE CELL THAT CHANGED AND DO THE ACTIONS IN THE CODE BELOW
            ''''' SO IN THIS EXAMPLE WE'RE MOVING ACROSS 1 CELL TO B1 AND THEN 2 CELLS TO C1
            ''''' SO TO GET TO AA1 AND AB2 WE'D DO i = 26 to 27
            ''''' IF WE WANTED TO ACCESS AA1 ALL THE WAY THROUGH TO AZ1 WE'D DO i = 26 to 51
            For i = 1 To 2

                ''''' MOVE ACROSS i NUMBER OF CELLS FROM THE CELL THAT CHANGED
                With target.Offset(0, i)

                    ''''' UNLOCK THE CELL
                    .Locked = False

                    '''''SET THE CONDITIONAL FORMATTING
                    .FormatConditions.Add Type:=xlExpression, Formula1:="=ISBLANK(" & target.Offset(0, i).Address & ")"
                    With .FormatConditions(.FormatConditions.Count)
                        .SetFirstPriority
                        .Interior.ColorIndex = 37
                    End With

                End With

            ''''' INCREASE i BY 1 AND LOOP TO AFFECT THE NEXT CELL
            Next i

        ''''' IF THE CELL CHANGED IS NOW 'NO'
        ElseIf target = "No" Then

            ''''' WE DEFINE HOW MANY COLUMNS TO MOVE ACROSS FROM THE CELL THAT CHANGED AND DO THE ACTIONS IN THE CODE BELOW
            For i = 1 To 2

                ''''' MOVE ACROSS i NUMBER OF CELLS FROM THE CELL THAT CHANGED
                With target.Offset(0, i)

                    ''''' SET THE CELL VALUE TO BLANK
                    .Value = ""

                    ''''' LOCK THE CELL
                    .Locked = True

                    ''''' REMOVE THE CONDITIONAL FORMATTING
                    .FormatConditions.Delete

                        ''''' ADD NEW CONDITIONAL FORMATTING HERE IF REQUIRED

                End With

            ''''' INCREASE i BY 1 AND LOOP TO AFFECT THE NEXT CELL
            Next i

        End If

        '''''PROTECT THE SHEET
        ActiveSheet.Protect

    End If

End Sub

Be sure to set locked to false in your A column where the drop down lists are or users won't be able to change the drop down value while the sheet is locked.


Q: Coding a guessing game in Jython Environment for Students ( JES ) I am trying to code a guessing game in JES using the pseudo code below:
Generate a random  single digit number
Have the user guess the number
If the user does not guess correctly give them a clue – indicate whether the number is even or odd and ask the user to guess again.
If the user does not guess correctly,  give another clue – indicate whether the number is a multiple of 3 and ask the user to guess again.
If the user does not guess correctly, give another clue – indicate whether the number is less than or greater than 5 and ask the user to guess again.
If the user does not guess correctly,
display a box indicating the correct answer and the number of guesses the user made.
If the user has guessed correctly, display a box indicating their guess is correct and how many guesses were required
Show the amount of time the user played the guessing game.
There are so many conditions I have no clue how to have the program ask each question, analyze the answer, and if the condition isn't met, to move on to the next one. When I run this code, it is just stuck in the loop of asking the user to guess and does not move through the if statements to give the user hints if they are incorrect.
Below is my current code which obviously is incorrect. I am also aware there may be indenting issues in this post.
from random import *
from time import *

def main():
  a= randrange( 0, 11 )
  start= clock()
  numberOfGuesses= 0
  userGuess= requestInteger( " Please guess a single digit number " )

  while userGuess != a:
    userGuess= requestInteger( " Please guess a single digit number " )
    if userGuess % 2 == 0:
      showInformation( " Incorrect! Please try again. Hint: The number is          even " )
    if userGuess % 2 != 0:
      showInformation( " Incorrect! Please try again. Hint: The number is odd " )
    if userGuess % 3 != 0:
      showInformation( " Incorrect! Please try again. Hint: The number is not a multiple of 3 " )
    if userGuess > 5:
      showInformation( " Incorrect! Please try again. Hint: The number is greater than 5 " )
    if userGuess < 5:
      showInformation( " Incorrect! Please try again. Hint: The number is greater than 5 " )
    else:
      showInformation( " Correct " )

REVISED AND WORKING CODE
from random import*
from time import*

def main ():
  a= randrange( 0, 10 )
  start= clock()
  numberOfGuesses= 0
  userGuess= requestNumber( " Please guess a single digit number " )
  end= clock()
  elapsedTime= end - start

  if userGuess != a and userGuess % 2 == 0:
    showInformation( " Incorrect! Please try again. Hint: The number is even " )
    userGuess= requestNumber( " Please guess a single digit number " )
    numberOfGuesses= numberOfGuesses + 1
  elif userGuess != a and a % 2 != 0:
      showInformation( " Incorrect! Please try again. Hint: The number is odd " )
      userGuess= requestNumber( " Please guess a single digit number " )
      numberOfGuesses= numberOfGuesses + 1

  if userGuess != a and a % 3 != 0:
    showInformation( " Incorrect! Please try again. Hint: The number IS NOT a multiple of 3 " )
    userGuess= requestNumber( " Please guess a single digit number " )
    numberOfGuesses= numberOfGuesses + 1

  if userGuess != a and a > 5:
    showInformation( " Incorrect! Please try again. Hint: The number is greater than 5 " )
    userGuess= requestNumber( " Please guess a single digit number " )
    numberOfGuesses= numberOfGuesses + 1
  if userGuess != a and a  < 5:
    showInformation( " Incorrect! Please try again. Hint: The number is less than 5 " )
    userGuess= requestNumber( " Please guess a single digit number " )
    numberOfGuesses= numberOfGuesses + 1
  if userGuess == a:
    showInformation( " Correct! " )
    showInformation( " The correct answer was" + " " + str(a) + " It took you " + str(elapsedTime) + " " + " seconds to complete this game " )
  elif userGuess != a :
    showInformation( " Incorrect! " + " " + " The correct answer was" + " " + str(a) + " It took you " + str(elapsedTime) + " " + " seconds to complete this game " )

A: its stuck in the loop because user cant guess the same num that randnum genertes
"while userguess !=a  " it'll never be true