问:
Rhino: how to make Rhino evaluate a RegEx expression on a Java String?
I have trouble calling .replace(searchValue, newValue) on Java String objects from Rhino when searchValue is a RegEx expression. This works otherwise fine when searchValue is not a RegEx expression, or when the method is called on a String which was initiated from within JavaScript.

Example:

Sample Java object and a method that returns a string

```<code>public class MyTestObject {
    public String returnStringValue() {
        return " This is a string with spaces ";
    }
}
</code>```

Set up of Rhino, creation of the Java object

```<code>import java.io.FileNotFoundException;
import javax.script.*;

public class TestRhino{

    public static void main(String[] args) throws FileNotFoundException, ScriptException, NoSuchMethodException {
        // Create my Java Object
        MyTestObject testObject = new MyTestObject();

        // Initiate the JavaScript engine
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        Compilable compEngine = (Compilable)engine;

        // evaluate my JavaScript file; add my Java object to it
        engine.eval(new java.io.FileReader("MyJavaScriptFile.js"));
        engine.put("testObject", testObject); // this adds my Java Object to Rhino

        // Invoke my javaScript function
        Invocable inv = (Invocable) engine;
        Object returnVal = inv.invokeFunction("testFunction");

        // print out the result
        System.out.println(returnVal); // should print "ThisisaString" to the console
    }
}
</code>```

My JavaScript function (this code cannot be modified in any way).

```<code>function testFunction() {
    let myString = testObject.returnStringValue();
    return myString.replace(/\s/g,"");  // Error!
}
</code>```

This throws an error The choice of Java constructor replace matching JavaScript argument types (function,string) is ambiguous; candidate constructors are: class java.lang.String replace(java.lang.CharSequence,java.lang.CharSequence).

However, when my JavaScript function is modified as follows, Rhino returns the expected value, and no error is thrown.

```<code>function testFunction() {
    let myString = testObject.returnStringValue();
    return myString.replace("T", "P"); //  Phis is a string with spaces
}
</code>```

The following JavaScript function also works when it is called with Rhino.

```<code>function testFunction() {
    return " This is a string with spaces ".replace(/\s/g,""); // Thisisastringwithspaces
}
</code>```

I'm looking for a way to make the above works without modifying the JavaScript code. I can only modify the Java code.

Note: this works well with Nashorn (default JavaScript engine from Java1.8 onwards), however I have to use Rhino (default javaScript engine until Java 1.7).

答:
My guess is that the Java code calls

```<code>replace(null, null);
</code>```

method in the String class and thus does not know, if it should execute -

```<code>replace(char oldChar, char newChar);
</code>```

or

```<code>replace(CharSequence target, CharSequence replacement);
</code>```

Cast the arguments in the Java call to:

```<code>replace((CharSequence) null, (CharSequence) null);
</code>```

Body:
I have trouble calling .replace(searchValue, newValue) on Java String objects from Rhino when searchValue is a RegEx expression. This works otherwise fine when searchValue is not a RegEx expression, or when the method is called on a String which was initiated from within JavaScript.

Example:

Sample Java object and a method that returns a string

public class MyTestObject {
    public String returnStringValue() {
        return " This is a string with spaces ";
    }
}

Set up of Rhino, creation of the Java object

import java.io.FileNotFoundException;
import javax.script.*;

public class TestRhino{

    public static void main(String[] args) throws FileNotFoundException, ScriptException, NoSuchMethodException {
        // Create my Java Object
        MyTestObject testObject = new MyTestObject();

        // Initiate the JavaScript engine
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        Compilable compEngine = (Compilable)engine;

        // evaluate my JavaScript file; add my Java object to it
        engine.eval(new java.io.FileReader("MyJavaScriptFile.js"));
        engine.put("testObject", testObject); // this adds my Java Object to Rhino

        // Invoke my javaScript function
        Invocable inv = (Invocable) engine;
        Object returnVal = inv.invokeFunction("testFunction");

        // print out the result
        System.out.println(returnVal); // should print "ThisisaString" to the console
    }
}

My JavaScript function (this code cannot be modified in any way).

function testFunction() {
    let myString = testObject.returnStringValue();
    return myString.replace(/\s/g,"");  // Error!
}

This throws an error The choice of Java constructor replace matching JavaScript argument types (function,string) is ambiguous; candidate constructors are: class java.lang.String replace(java.lang.CharSequence,java.lang.CharSequence).

However, when my JavaScript function is modified as follows, Rhino returns the expected value, and no error is thrown.

function testFunction() {
    let myString = testObject.returnStringValue();
    return myString.replace("T", "P"); //  Phis is a string with spaces
}

The following JavaScript function also works when it is called with Rhino.

function testFunction() {
    return " This is a string with spaces ".replace(/\s/g,""); // Thisisastringwithspaces
}

I'm looking for a way to make the above works without modifying the JavaScript code. I can only modify the Java code.

Note: this works well with Nashorn (default JavaScript engine from Java1.8 onwards), however I have to use Rhino (default javaScript engine until Java 1.7).

Body:
My guess is that the Java code calls

replace(null, null);

method in the String class and thus does not know, if it should execute -

replace(char oldChar, char newChar);

or

replace(CharSequence target, CharSequence replacement);

Cast the arguments in the Java call to:

replace((CharSequence) null, (CharSequence) null);


来源: stackexchange

问:
The incorrect pictures are being removed
When I click the Delete Selected button, the wrong picture is being deleted. Most of the times it deleted the picture on the right of a selected picture. Other times, for example when everything is selected, it only deletes a single picture.

I don't know what's going on. Here's a picture to illustrate what happens:

Here is the code for both user controls I'm using: HorizontalPictureScroller and SelectablePicture.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.ComponentModel.Design.Serialization;

namespace WinformsPlayground
{
    public partial class HorizontalPictureScroller : UserControl
    {
        public HorizontalPictureScroller()
        {
            InitializeComponent();
            Pictures = new ObservableCollection<SelectablePicture>();
            Pictures.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Pictures_CollectionChanged);
        }

        #region "Properties"
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public ObservableCollection<SelectablePicture> Pictures { get; set; }
        private int PositionControlX = 0;
        #endregion

        #region "Methods"
        private void RedrawPictures()
        {
            PositionControlX = 0;

            foreach (var picture in Pictures)
            {
                picture.Location = new Point(PositionControlX + panelPicturesWrapper.AutoScrollPosition.X, 0);
                PositionControlX += 130;
                panelPicturesWrapper.Controls.Add(picture);
            }
        }

        public void AddPicture(SelectablePicture picture)
        {
            Pictures.Add(picture);
        }

        public void RemovePicture(SelectablePicture picture)
        {
            Pictures.Remove(picture);
        }

        public void MovePictureLeft(int index)
        {
            SelectablePicture tmpPicture = Pictures[index];
            Pictures[index] = Pictures[index - 1];
            Pictures[index - 1] = tmpPicture;
        }

        public void MovePictureRight(int index)
        {
            SelectablePicture tmpPicture = Pictures[index];
            Pictures[index] = Pictures[index + 1];
            Pictures[index + 1] = tmpPicture;
        }

        public void SelectAllImages()
        {
            foreach (var picture in panelPicturesWrapper.Controls)
            {
                ((SelectablePicture)picture).SelectPicture();
            }
        }

        public void DeselectAllImages()
        {
            foreach (var picture in panelPicturesWrapper.Controls)
            {
                ((SelectablePicture)picture).DeselectPicture();
            }
        }

        public void DeleteSelectedImages()
        {
            foreach (var picture in panelPicturesWrapper.Controls)
            {
                if (((SelectablePicture)picture).IsSelected())
                {
                    this.RemovePicture((SelectablePicture)picture);
                }
            }
        }
        #endregion

        #region "Events"
        void Pictures_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            RedrawPictures();
        }
        #endregion

    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization;

namespace WinformsPlayground
{
    public partial class SelectablePicture : UserControl
    {
        public SelectablePicture()
        {
            InitializeComponent();
            panel1.BackgroundImageLayout = ImageLayout.Zoom;
        }

        public SelectablePicture(Image image)
        {
            InitializeComponent();
            panel1.BackgroundImage = image;
            panel1.BackgroundImageLayout = ImageLayout.Zoom;
        }

        #region "Properties"
        public Image Image()
        {
            return panel1.BackgroundImage;
        }

        public bool IsSelected()
        {
            return chkSelected.Checked;
        }
        #endregion

        #region "Methods"
        public void ToggleCheckBox()
        {
            chkSelected.Checked = chkSelected.Checked ? false : true;
        }

        public void VisuallySelect()
        {
            this.BackColor = Color.FromArgb(51, 153, 255);
        }

        public void VisuallyDeselect()
        {
            //If none of the controls inside the usercontrol have focus, set this control to white.
            if (!this.Focused && !this.panel1.Focused && !this.chkSelected.Focused)
            {
                this.BackColor = Color.White;
            }
        }

        public void SelectPicture()
        {
            this.chkSelected.Checked = true;
        }

        public void DeselectPicture()
        {
            this.chkSelected.Checked = false;
        }
        #endregion

        #region "Events"
        private void panel1_Click(object sender, EventArgs e)
        {
            VisuallySelect();
            ToggleCheckBox();
            panel1.Focus();
        }

        private void chkSelected_Click(object sender, EventArgs e)
        {
            VisuallySelect();
            ToggleCheckBox();
            chkSelected.Focus();
        }

        private void SelectablePicture_Click(object sender, EventArgs e)
        {
            VisuallySelect();
            ToggleCheckBox();
            this.Focus();
        }

        private void panel1_Leave(object sender, EventArgs e)
        {
            VisuallyDeselect();
        }

        private void chkSelected_Leave(object sender, EventArgs e)
        {
            VisuallyDeselect();
        }

        private void SelectablePicture_Leave(object sender, EventArgs e)
        {
            VisuallyDeselect();
        }
        #endregion
    }
}
</code>```

The code is simple enough. I've used breakpoints and I can confirm that the HorizontalPictureScroller.DeleteSelectedImages() method is correctly iterating through selected pictures. I'm not sure what else I could do to see what's going on. I'm stumped!

Any ideas? Maybe the .Remove() method that comes with the ObservableCollection type doesn't work as I thought it did.

答:
Every time the Pictures collection changes, you're calling RedrawPictures. That adds all of the pictures again, but doesn't clear anything... so you'll be trying to add a control to panelPicturesWrapper.Controls when it already contains that control. That sounds like a bad idea to me.

Further, you're iterating over the Controls collection while changing it, which is generally a bad idea.

I suggest you change your removal code to something like this:

```<code>public void DeleteSelectedImages()
{
    var picturesToRemove = panelPicturesWrapper.Controls
                                               .Cast<SelectablePicture>();
                                               .Where(p => p.IsSelected())
                                               .ToList();

    foreach (var picture in picturesToRemove)
    {
        RemovePicture(picture);
    }
}
</code>```

OwnerDisplayName: delete

ContentLicense: CC BY-SA 2.5

Body:
When I click the Delete Selected button, the wrong picture is being deleted. Most of the times it deleted the picture on the right of a selected picture. Other times, for example when everything is selected, it only deletes a single picture.

I don't know what's going on. Here's a picture to illustrate what happens:

Here is the code for both user controls I'm using: HorizontalPictureScroller and SelectablePicture.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.ComponentModel.Design.Serialization;

namespace WinformsPlayground
{
    public partial class HorizontalPictureScroller : UserControl
    {
        public HorizontalPictureScroller()
        {
            InitializeComponent();
            Pictures = new ObservableCollection<SelectablePicture>();
            Pictures.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Pictures_CollectionChanged);
        }

        #region "Properties"
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public ObservableCollection<SelectablePicture> Pictures { get; set; }
        private int PositionControlX = 0;
        #endregion

        #region "Methods"
        private void RedrawPictures()
        {
            PositionControlX = 0;

            foreach (var picture in Pictures)
            {
                picture.Location = new Point(PositionControlX + panelPicturesWrapper.AutoScrollPosition.X, 0);
                PositionControlX += 130;
                panelPicturesWrapper.Controls.Add(picture);
            }
        }

        public void AddPicture(SelectablePicture picture)
        {
            Pictures.Add(picture);
        }

        public void RemovePicture(SelectablePicture picture)
        {
            Pictures.Remove(picture);
        }

        public void MovePictureLeft(int index)
        {
            SelectablePicture tmpPicture = Pictures[index];
            Pictures[index] = Pictures[index - 1];
            Pictures[index - 1] = tmpPicture;
        }

        public void MovePictureRight(int index)
        {
            SelectablePicture tmpPicture = Pictures[index];
            Pictures[index] = Pictures[index + 1];
            Pictures[index + 1] = tmpPicture;
        }

        public void SelectAllImages()
        {
            foreach (var picture in panelPicturesWrapper.Controls)
            {
                ((SelectablePicture)picture).SelectPicture();
            }
        }

        public void DeselectAllImages()
        {
            foreach (var picture in panelPicturesWrapper.Controls)
            {
                ((SelectablePicture)picture).DeselectPicture();
            }
        }

        public void DeleteSelectedImages()
        {
            foreach (var picture in panelPicturesWrapper.Controls)
            {
                if (((SelectablePicture)picture).IsSelected())
                {
                    this.RemovePicture((SelectablePicture)picture);
                }
            }
        }
        #endregion

        #region "Events"
        void Pictures_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            RedrawPictures();
        }
        #endregion

    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization;

namespace WinformsPlayground
{
    public partial class SelectablePicture : UserControl
    {
        public SelectablePicture()
        {
            InitializeComponent();
            panel1.BackgroundImageLayout = ImageLayout.Zoom;
        }

        public SelectablePicture(Image image)
        {
            InitializeComponent();
            panel1.BackgroundImage = image;
            panel1.BackgroundImageLayout = ImageLayout.Zoom;
        }

        #region "Properties"
        public Image Image()
        {
            return panel1.BackgroundImage;
        }

        public bool IsSelected()
        {
            return chkSelected.Checked;
        }
        #endregion

        #region "Methods"
        public void ToggleCheckBox()
        {
            chkSelected.Checked = chkSelected.Checked ? false : true;
        }

        public void VisuallySelect()
        {
            this.BackColor = Color.FromArgb(51, 153, 255);
        }

        public void VisuallyDeselect()
        {
            //If none of the controls inside the usercontrol have focus, set this control to white.
            if (!this.Focused && !this.panel1.Focused && !this.chkSelected.Focused)
            {
                this.BackColor = Color.White;
            }
        }

        public void SelectPicture()
        {
            this.chkSelected.Checked = true;
        }

        public void DeselectPicture()
        {
            this.chkSelected.Checked = false;
        }
        #endregion

        #region "Events"
        private void panel1_Click(object sender, EventArgs e)
        {
            VisuallySelect();
            ToggleCheckBox();
            panel1.Focus();
        }

        private void chkSelected_Click(object sender, EventArgs e)
        {
            VisuallySelect();
            ToggleCheckBox();
            chkSelected.Focus();
        }

        private void SelectablePicture_Click(object sender, EventArgs e)
        {
            VisuallySelect();
            ToggleCheckBox();
            this.Focus();
        }

        private void panel1_Leave(object sender, EventArgs e)
        {
            VisuallyDeselect();
        }

        private void chkSelected_Leave(object sender, EventArgs e)
        {
            VisuallyDeselect();
        }

        private void SelectablePicture_Leave(object sender, EventArgs e)
        {
            VisuallyDeselect();
        }
        #endregion
    }
}

The code is simple enough. I've used breakpoints and I can confirm that the HorizontalPictureScroller.DeleteSelectedImages() method is correctly iterating through selected pictures. I'm not sure what else I could do to see what's going on. I'm stumped!

Any ideas? Maybe the .Remove() method that comes with the ObservableCollection type doesn't work as I thought it did.

Body:
Every time the Pictures collection changes, you're calling RedrawPictures. That adds all of the pictures again, but doesn't clear anything... so you'll be trying to add a control to panelPicturesWrapper.Controls when it already contains that control. That sounds like a bad idea to me.

Further, you're iterating over the Controls collection while changing it, which is generally a bad idea.

I suggest you change your removal code to something like this:

public void DeleteSelectedImages()
{
    var picturesToRemove = panelPicturesWrapper.Controls
                                               .Cast<SelectablePicture>();
                                               .Where(p => p.IsSelected())
                                               .ToList();

    foreach (var picture in picturesToRemove)
    {
        RemovePicture(picture);
    }
}


问:
How to avoid READPAST lock warnings using NServiceBus
Scenario

I've written a stress test that sends a 100 GenerateFile commands to the Bus.
I know the process has worked, because all 100 files have been created as expected.

Symptoms

In the Service logs however I find these warnings:

Warn | NServiceBus.Transport.SQLServer.ExpiredMessagesPurger | Purging
  expired messages from table [dbo].[TransportTable] failed after purging 0
  messages.

And

Warn | NServiceBus.Transport.SQLServer.MessagePump | Purging
  expired messages from table [dbo].[TransportTable] failed with exception:
  System.Data.SqlClient.SqlException (0x80131904): You can only specify
  the READPAST lock in the READ COMMITTED or REPEATABLE READ isolation
  levels.

Clarification: This occurs on the NServiceBus transport table, not a functional table of my own.

What I want

In the spirit of keeping the logs as clean as possible, I'd like to avoid the above warnings.

So

What is happening?

I've found this link, but the root cause is still not clear to me.

and

How can I avoid these warnings?

答:
David Boike from Particular Software here.

Are you specifying a different transaction isolation level? You should be using READ COMMITTED. We actually have an open issue to only support read committed.

The READPAST hint is critical because if you have multiple endpoint instances processing messages from the same queue (i.e. table) then when it encounters a locked row, you don't want to hang waiting for that row to become available, because another instance is dealing with it. Instead you want to just skip over and look at the next row.

It looks like this warning is coming from the process that removes messages that have expired from use of a [TimeToBeReceived] attribute. You don't want that process getting hung up over locked rows either.

ContentLicense: CC BY-SA 3.0


问:
Why must I click twice to open and close my menu
Hello I got a situation which I do not understand quite well. I have the following setup:

 $(document).ready(function(){
  $('.menuBtn').on('click touch', function () {
  $(this).toggleClass('act');
   if($(this).hasClass('act')) {
    $('.mobileMenu').addClass('act');
    //$('body').addClass('positionfixed');
   }
   else {
    $('.mobileMenu').removeClass('act');
    //$('body').removeClass('positionfixed');
   }
 });
   });```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .mobile-menu-button{
  display:block;
  position:fixed;
  top:20px;
  left:20px;
  z-index:99;
    background-color:#19b698;
    padding:5px 10px;
    color:#fff;
    font-family: Open Sans;
    font-weight:bold;
 }
 .mobile-menu-button i{
  font-size:26px;
  background-color:#00adee;
  padding:5px 10px;
  color:#fff;
 }
.mobileMenu {
  background-color: #fff !important;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  height: 100vh;
  width: 100vw;
  display: block;
  text-align: center;
  opacity: 0;
  -webkit-transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  -webkit-transform: scale(0);
     transform: scale(0);
  overflow:hidden;
 }
 .mobileMenu img{
  max-width:90%;
  margin:0 auto;
  margin-top:20px;
  margin-bottom:10px;
  border-bottom:1px dotted #717274;
  padding-bottom:20px;
 }
 .mobileMenu.act {
  opacity: 1;
  -webkit-transform: scale(1);
     transform: scale(1);
 }
 .mobileMenu.act ul li {
  opacity: 1;
  -webkit-transform: translateX(0);
     transform: translateX(0);
  display:block !important;
 }
 .mobileMenu ul {
  display: block;
  vertical-align: middle;
 }
 .mobileMenu li {
  padding: 10px 0 !important;
  -webkit-transition: all 400ms 510ms;
  transition: all 400ms 510ms;
  opacity: 0;
 }
 .mobileMenu li:nth-child(odd) {
   -webkit-transform: translateX(30%);
     transform: translateX(30%);
 }
 .mobileMenu li:nth-child(even) {
   -webkit-transform: translateX(-30%);
     transform: translateX(-30%);
 }
 .mobileMenu li:last-child {
   -webkit-transform: none;
     transform: none;
 }
 .mobileMenu a {
   color: #00adee !important;
   display: inline-block;
   font-size: 18px;
 }
 .mobileMenu a.suBtn {
   color: #fff;
 }</code>```

Open

  Close

Home

Testimonials

Contact

```

Why should I press two times on the open / close button to open / close the menu?

Anyone any idea / fix?

答:
You should use below jQuery code instead of using yours::

```<code>$(document).ready(function(){
  $('.menuBtn').on('click touch', function () {
    $(this).toggleClass('act');
    if(!$('.mobileMenu').hasClass('act')) {
      $('.mobileMenu').addClass('act');
      //$('body').addClass('positionfixed');
    }
    else {
      $('.mobileMenu').removeClass('act');
      //$('body').removeClass('positionfixed');
    }
  });
});
</code>```

Working URL:: https://jsfiddle.net/Lxz9v34L/2/

Body:
Hello I got a situation which I do not understand quite well. I have the following setup:

 $(document).ready(function(){
  $('.menuBtn').on('click touch', function () {
  $(this).toggleClass('act');
   if($(this).hasClass('act')) {
    $('.mobileMenu').addClass('act');
    //$('body').addClass('positionfixed');
   }
   else {
    $('.mobileMenu').removeClass('act');
    //$('body').removeClass('positionfixed');
   }
 });
   });

 .mobile-menu-button{
  display:block;
  position:fixed;
  top:20px;
  left:20px;
  z-index:99;
    background-color:#19b698;
    padding:5px 10px;
    color:#fff;
    font-family: Open Sans;
    font-weight:bold;
 }
 .mobile-menu-button i{
  font-size:26px;
  background-color:#00adee;
  padding:5px 10px;
  color:#fff;
 }
.mobileMenu {
  background-color: #fff !important;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  height: 100vh;
  width: 100vw;
  display: block;
  text-align: center;
  opacity: 0;
  -webkit-transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  -webkit-transform: scale(0);
     transform: scale(0);
  overflow:hidden;
 }
 .mobileMenu img{
  max-width:90%;
  margin:0 auto;
  margin-top:20px;
  margin-bottom:10px;
  border-bottom:1px dotted #717274;
  padding-bottom:20px;
 }
 .mobileMenu.act {
  opacity: 1;
  -webkit-transform: scale(1);
     transform: scale(1);
 }
 .mobileMenu.act ul li {
  opacity: 1;
  -webkit-transform: translateX(0);
     transform: translateX(0);
  display:block !important;
 }
 .mobileMenu ul {
  display: block;
  vertical-align: middle;
 }
 .mobileMenu li {
  padding: 10px 0 !important;
  -webkit-transition: all 400ms 510ms;
  transition: all 400ms 510ms;
  opacity: 0;
 }
 .mobileMenu li:nth-child(odd) {
   -webkit-transform: translateX(30%);
     transform: translateX(30%);
 }
 .mobileMenu li:nth-child(even) {
   -webkit-transform: translateX(-30%);
     transform: translateX(-30%);
 }
 .mobileMenu li:last-child {
   -webkit-transform: none;
     transform: none;
 }
 .mobileMenu a {
   color: #00adee !important;
   display: inline-block;
   font-size: 18px;
 }
 .mobileMenu a.suBtn {
   color: #fff;
 }

Open

  Close

Home

Testimonials

Contact

Why should I press two times on the open / close button to open / close the menu?

Anyone any idea / fix?

Body:
You should use below jQuery code instead of using yours::

$(document).ready(function(){
  $('.menuBtn').on('click touch', function () {
    $(this).toggleClass('act');
    if(!$('.mobileMenu').hasClass('act')) {
      $('.mobileMenu').addClass('act');
      //$('body').addClass('positionfixed');
    }
    else {
      $('.mobileMenu').removeClass('act');
      //$('body').removeClass('positionfixed');
    }
  });
});

Working URL:: https://jsfiddle.net/Lxz9v34L/2/


问:
How can I write an excel formula to return a value from a range based on the contents of a cell?
How can I write an Excel formula which will check if a cell contains a word listed in a separate range, and then return the single, individual word from the specified range?

The formula must specify the cell and the range, rather than cramming the values into the formula itself.

Example:

For example, the formula is being written in cell B1 and references the cell A1. The cell A1 contains the text "uk car insurance". The range is located from cells C1 to cell C10 (C1:C10). In this range 10 countries are listed, one per cell cascading downwards (e.g: C1="uk", C2="usa", C3="france" etc).

Based on this example, the formula in B1 should pull back the value "uk" from the range of cells (C1:C10) as the cell in A1 contains the text "uk car insurance" which contains "uk". The text of "uk" is also stored in cell C1, so that's what should be pulled back into B1.

A formula like this (moving away from our example now) wouldn't work for my purposes:

```<code>=IF(COUNTIF(L5:L47,"FALSE"),"Portfolios Mismatched","Portfolios Matched")
</code>```

My range of countries in column C may become vast and thus any formula which attempts to list the values within itself (instead of referring to a range) is not scalable.

答:
Use INDEX and AGGREGATE:

```<code>=INDEX(C:C,AGGREGATE(15,6,ROW($C$1:INDEX(C:C,MATCH("zzz",C:C)))/(ISNUMBER(SEARCH(" " & $C$1:INDEX(C:C,MATCH("zzz",C:C)) & " "," " & A1 & " "))),1))
</code>```

The $C$1:INDEX(C:C,MATCH("zzz",C:C)) sets the range, it is dynamic.  It will set the range to only those with values and change as values are added or removed from the reference list.

The SEARCH will search for matches.  The " " & and & " " make sure we are looking for the entire word,  So we do not get false positives on things like eric and erica.

The Aggregate will find the first row in which a word if found in the reference cell.

Index returns that word as the answer.

Body:
How can I write an Excel formula which will check if a cell contains a word listed in a separate range, and then return the single, individual word from the specified range?

The formula must specify the cell and the range, rather than cramming the values into the formula itself.

Example:

For example, the formula is being written in cell B1 and references the cell A1. The cell A1 contains the text "uk car insurance". The range is located from cells C1 to cell C10 (C1:C10). In this range 10 countries are listed, one per cell cascading downwards (e.g: C1="uk", C2="usa", C3="france" etc).

Based on this example, the formula in B1 should pull back the value "uk" from the range of cells (C1:C10) as the cell in A1 contains the text "uk car insurance" which contains "uk". The text of "uk" is also stored in cell C1, so that's what should be pulled back into B1.

A formula like this (moving away from our example now) wouldn't work for my purposes:

=IF(COUNTIF(L5:L47,"FALSE"),"Portfolios Mismatched","Portfolios Matched")

My range of countries in column C may become vast and thus any formula which attempts to list the values within itself (instead of referring to a range) is not scalable.

Body:
Use INDEX and AGGREGATE:

=INDEX(C:C,AGGREGATE(15,6,ROW($C$1:INDEX(C:C,MATCH("zzz",C:C)))/(ISNUMBER(SEARCH(" " & $C$1:INDEX(C:C,MATCH("zzz",C:C)) & " "," " & A1 & " "))),1))

The $C$1:INDEX(C:C,MATCH("zzz",C:C)) sets the range, it is dynamic.  It will set the range to only those with values and change as values are added or removed from the reference list.

The SEARCH will search for matches.  The " " & and & " " make sure we are looking for the entire word,  So we do not get false positives on things like eric and erica.

The Aggregate will find the first row in which a word if found in the reference cell.

Index returns that word as the answer.


问:
Accessing variables in layout.phtml in zf2
I have simple application in zf2, I have menu in layout which is for each page of application. e.g., provinces/index.phtml, districts/index.phtml, cities/index.phtml etc.

Menu is:

```<code>            <li class="start active ">
                <a href="admin">
                    <i class="fa fa-home"></i>
                    <span class="title">
                        Dashboard
                    </span>
                    <span class="selected">
                    </span>
                </a>
            </li>
            <li>
                <a href="provinces">
                    <i class="fa fa-globe"></i>
                    <span class="title">
                        Provinces
                    </span>
                </a>
            </li>
            <li>
                <a href="districts">
                    <i class="fa fa-map-marker"></i>
                    <span class="title">
                        Districts
                    </span>
                </a>
            </li>
            <li>
                <a href="cities">
                    <i class="fa fa-tint"></i>
                    <span class="title">
                        Cities
                    </span>
                </a>
            </li>
</code>```

I have code:

```<code><div class="page-content-wrapper">
    <?php echo $this->content; ?> <!--this print contents of index.phtml -->
</div>
</code>```

which access each page in the same layout.

Now I want to make menu dynamically, i.e., when provinces is selected then provinces should highlighted, if districts is selected then districts in menu should be highlighted.

I tried the logic like below:
In provinces/index.phtml I write the code $selected_page="provinces", in districts/index.phtml I write the code $selected_page="districts" etc

Then in menu in layout:

I write   class="start active"  >

same is for districts and provinces etc.

But here variable $selected_page can not accessed, because

```<code><?php echo $this->content; ?>
</code>```

can only print and display content of index.phtml, and variable is not passed to layout.
So how should I do this? how should I pass variable $current_page to layout, or show me other logic about it.

Thanks in advance:

screenshot is given below with Dashboard highlighted:

答:
If you want to pass variable from controller/action (for example provincesAction()) to view. Use layout() controller plugin:

```<code>public function provincesAction()
{
    $this->layout()->setVariable('foo', 'bar');
    return new ViewModel([]);
}
</code>```

In layout.phtml

```<code>// html code
<?php echo $this->foo; ?> // It will display "bar"
// more html code
</code>```

But for your example. I would suggest you to use navigation() view helper. Read more on https://framework.zend.com/manual/2.4/en/modules/zend.navigation.view.helper.menu.html. This plugin is made just for such things like you need.

Body:
I have simple application in zf2, I have menu in layout which is for each page of application. e.g., provinces/index.phtml, districts/index.phtml, cities/index.phtml etc.

Menu is:

                        Dashboard

                        Provinces

                        Districts

                        Cities

I have code:

    <?php echo $this->content; ?>

which access each page in the same layout.

Now I want to make menu dynamically, i.e., when provinces is selected then provinces should highlighted, if districts is selected then districts in menu should be highlighted.

I tried the logic like below:
In provinces/index.phtml I write the code $selected_page="provinces", in districts/index.phtml I write the code $selected_page="districts" etc

Then in menu in layout:

I write   class="start active"  >

same is for districts and provinces etc.

But here variable $selected_page can not accessed, because

<?php echo $this->content; ?>

can only print and display content of index.phtml, and variable is not passed to layout.
So how should I do this? how should I pass variable $current_page to layout, or show me other logic about it.

Thanks in advance:

screenshot is given below with Dashboard highlighted:

Body:
If you want to pass variable from controller/action (for example provincesAction()) to view. Use layout() controller plugin:

public function provincesAction()
{
    $this->layout()->setVariable('foo', 'bar');
    return new ViewModel([]);
}

In layout.phtml

// html code
<?php echo $this->foo; ?> // It will display "bar"
// more html code

But for your example. I would suggest you to use navigation() view helper. Read more on https://framework.zend.com/manual/2.4/en/modules/zend.navigation.view.helper.menu.html. This plugin is made just for such things like you need.


问:
What is the fastest way to open a form from a form?
What is the fast and effective way to open Form2 from Form1?

I work in WinCE (limited memory and CPU power) so this becomes important.

答: Depending on your requirements, you might trick your users to see a splash screen when your application loads. During this time, you instantiate important forms in the background. This approach should give you a few extra seconds that most users don't think of as "being slow". Users usually accept that an app starts slower if it works reasonably fast afterwards.</p>

OwnerDisplayName: Gold

LastEditorDisplayName: Rich B

OwnerDisplayName: Sergiu Damian


问:
How to make HTTP POST on website that uses asp.net?
I'm using Python library requests for this, but I can't seem to be able to log in to this website.
The url is https://www.bet365affiliates.com/ui/pages/affiliates/, and I've been trying post requests to https://www.bet365affiliates.com/Members/CMSitePages/SiteLogin.aspx?lng=1 with the data of "ctl00$MasterHeaderPlaceHolder$ctl00$passwordTextbox", "ctl00$MasterHeaderPlaceHolder$ctl00$userNameTextbox", etc, but I never seem to be able to get logged in.

Could someone more experienced check the page's source code and tell me what am I am missing here?

答:
The solution could be this: Please Take attention, you could do it without selenium. If you want to do without it, firstly you should get the main affiliate page, and from the response data you could fetch all the required information (which I gather by xpaths). I just didn't have enough time to write it in fully requests.

To gather the informations from response data you could use XML tree library. With the same XPATH method, you could easily find all the requested informations.

```<code>import requests
from selenium import webdriver

Password = 'YOURPASS'
Username = 'YOURUSERNAME'

browser = webdriver.Chrome(os.getcwd()+"/"+"Chromedriver.exe")
browser.get('https://www.bet365affiliates.com/ui/pages/affiliates/Affiliates.aspx')
VIEWSTATE=browser.find_element_by_xpath('//*[@id="__VIEWSTATE"]')
SESSIONID=browser.find_element_by_xpath('//*[@id="CMSessionId"]')
PREVPAG=browser.find_element_by_xpath('//*[@id="__PREVIOUSPAGE"]')
EVENTVALIDATION=browser.find_element_by_xpath('//* [@id="__EVENTVALIDATION"]')
cookies = browser.get_cookies()

session = requests.session()
for cookie in cookies:
    print cookie['name']
    print cookie['value']
    session.cookies.set(cookie['name'], cookie['value'])

payload = {'ctl00_AjaxScriptManager_HiddenField':'',
           '__EVENTTARGET':'ctl00$MasterHeaderPlaceHolder$ctl00$goButton',
           '__EVENTARGUMENT':'',
           '__VIEWSTATE':VIEWSTATE,
           '__PREVIOUSPAGE':PREVPAG,
           '__EVENTVALIDATION':EVENTVALIDATION,
           'txtPassword':Username,
           'txtUserName':Password,
           'CMSessionId':SESSIONID,
           'returnURL':'/ui/pages/affiliates/Affiliates.aspx',
           'ctl00$MasterHeaderPlaceHolder$ctl00$userNameTextbox':Username,
           'ctl00$MasterHeaderPlaceHolder$ctl00$passwordTextbox':Password,
           'ctl00$MasterHeaderPlaceHolder$ctl00$tempPasswordTextbox':'Password'}

session.post('https://www.bet365affiliates.com/Members/CMSitePages/SiteLogin.aspx?lng=1',data=payload)
</code>```

Body:
The solution could be this: Please Take attention, you could do it without selenium. If you want to do without it, firstly you should get the main affiliate page, and from the response data you could fetch all the required information (which I gather by xpaths). I just didn't have enough time to write it in fully requests.

To gather the informations from response data you could use XML tree library. With the same XPATH method, you could easily find all the requested informations.

import requests
from selenium import webdriver

Password = 'YOURPASS'
Username = 'YOURUSERNAME'

browser = webdriver.Chrome(os.getcwd()+"/"+"Chromedriver.exe")
browser.get('https://www.bet365affiliates.com/ui/pages/affiliates/Affiliates.aspx')
VIEWSTATE=browser.find_element_by_xpath('//*[@id="__VIEWSTATE"]')
SESSIONID=browser.find_element_by_xpath('//*[@id="CMSessionId"]')
PREVPAG=browser.find_element_by_xpath('//*[@id="__PREVIOUSPAGE"]')
EVENTVALIDATION=browser.find_element_by_xpath('//* [@id="__EVENTVALIDATION"]')
cookies = browser.get_cookies()

session = requests.session()
for cookie in cookies:
    print cookie['name']
    print cookie['value']
    session.cookies.set(cookie['name'], cookie['value'])

payload = {'ctl00_AjaxScriptManager_HiddenField':'',
           '__EVENTTARGET':'ctl00$MasterHeaderPlaceHolder$ctl00$goButton',
           '__EVENTARGUMENT':'',
           '__VIEWSTATE':VIEWSTATE,
           '__PREVIOUSPAGE':PREVPAG,
           '__EVENTVALIDATION':EVENTVALIDATION,
           'txtPassword':Username,
           'txtUserName':Password,
           'CMSessionId':SESSIONID,
           'returnURL':'/ui/pages/affiliates/Affiliates.aspx',
           'ctl00$MasterHeaderPlaceHolder$ctl00$userNameTextbox':Username,
           'ctl00$MasterHeaderPlaceHolder$ctl00$passwordTextbox':Password,
           'ctl00$MasterHeaderPlaceHolder$ctl00$tempPasswordTextbox':'Password'}

session.post('https://www.bet365affiliates.com/Members/CMSitePages/SiteLogin.aspx?lng=1',data=payload)


问:
Excel not capturing SUMIFS where condition is Text/Boolean
I have a sample data set with TRUE/FALSE values:

```<code>COLA   | COLB  | COLC
------ | ----- | -----
ABCD   | 1234  | TRUE
BCDE   | 2345  | FALSE
ABCD   | 3456  | TRUE
</code>```

The formula which I'm attempting is =SUMIFS(COLB,COLC,"TRUE",COLA,"ABCD"), which is returning 0 instead of 4690.

If I instead use Boolean denotation instead of Text =SUMIFS(COLB,COLC,TRUE,COLA,"ABCD"), it still returns a 0.

Oddly enough, if I go back to the cells in COLC and double click + enter on the values, the contents get centered and then the formula starts working correctly:

```<code>COLA   | COLB  | COLC
------ | ----- | -----
ABCD   | 1234  |  TRUE
BCDE   | 2345  | FALSE
ABCD   | 3456  |  TRUE
</code>```

However, I don't want to do this because the data is being imported via a macro and the sheet shouldn't be touched.

How can I fix the formula to capture the text as it is currently in COLC?

答:
SUMIFS is interpreting the TRUE in the criteria argument as Boolean.  Your data is being imported as a text string.

You can force SUMIFs to view TRUE as a string by adding a wild card:

```<code>=SUMIFS(COLB,COLA,"ABCD",COLC,"*TRUE")
</code>```

Obviously, not ideal, as it will count any string that ends with TRUE, but should work given your example.

An alternative, not dependent on wild cards is:

```<code>=SUMPRODUCT((COLA="ABCD")*(COLC="TRUE")*COLB)
</code>```

If you need to be able to count TRUE whether it might be BOOLEAN or TEXT, try one of these:

```<code>=SUM(SUMIFS(COLB,COLA,"ABCD",COLC,{"*TRUE",TRUE}))
=SUMPRODUCT((COLA="ABCD")*(COLC={"TRUE",TRUE})*COLB)
</code>```

Body:
I have a sample data set with TRUE/FALSE values:

COLA   | COLB  | COLC
------ | ----- | -----
ABCD   | 1234  | TRUE
BCDE   | 2345  | FALSE
ABCD   | 3456  | TRUE

The formula which I'm attempting is =SUMIFS(COLB,COLC,"TRUE",COLA,"ABCD"), which is returning 0 instead of 4690.

If I instead use Boolean denotation instead of Text =SUMIFS(COLB,COLC,TRUE,COLA,"ABCD"), it still returns a 0.

Oddly enough, if I go back to the cells in COLC and double click + enter on the values, the contents get centered and then the formula starts working correctly:

COLA   | COLB  | COLC
------ | ----- | -----
ABCD   | 1234  |  TRUE
BCDE   | 2345  | FALSE
ABCD   | 3456  |  TRUE

However, I don't want to do this because the data is being imported via a macro and the sheet shouldn't be touched.

How can I fix the formula to capture the text as it is currently in COLC?

Body:
SUMIFS is interpreting the TRUE in the criteria argument as Boolean.  Your data is being imported as a text string.

You can force SUMIFs to view TRUE as a string by adding a wild card:

=SUMIFS(COLB,COLA,"ABCD",COLC,"*TRUE")

Obviously, not ideal, as it will count any string that ends with TRUE, but should work given your example.

An alternative, not dependent on wild cards is:

=SUMPRODUCT((COLA="ABCD")*(COLC="TRUE")*COLB)

If you need to be able to count TRUE whether it might be BOOLEAN or TEXT, try one of these:

=SUM(SUMIFS(COLB,COLA,"ABCD",COLC,{"*TRUE",TRUE}))
=SUMPRODUCT((COLA="ABCD")*(COLC={"TRUE",TRUE})*COLB)


问:
POJO from JSON through Gson
How I can convert it to POJO? I have a little troubles with "langs": {}. Is the Langs a Java object with a random quantity of variables?

Need for GsonFactory / Retrofit 2. Regards.

```<code>{
    "dirs": [
        "ru-en",
        "ru-pl",
        "ru-hu",
      ...
    ],
   "langs": {
        "ru": "russian",
        "en": "english",
        "pl": "polish",
     ...
   }

}
</code>```

答:
Try this:</p>

```<code>public class Example {

    @NonNull
    @SerializedName("dirs")
    public List<String> dirs;

    @NonNull
    @SerializedName("langs")
    public Map<String, String> langs;

}
</code>```

Title: POJO from JSON through Gson

Body:
How I can convert it to POJO? I have a little troubles with "langs": {}. Is the Langs a Java object with a random quantity of variables?

Need for GsonFactory / Retrofit 2. Regards.

{
    "dirs": [
        "ru-en",
        "ru-pl",
        "ru-hu",
      ...
    ],
   "langs": {
        "ru": "russian",
        "en": "english",
        "pl": "polish",
     ...
   }

}

Body:
Try this:

public class Example {

    @NonNull
    @SerializedName("dirs")
    public List<String> dirs;

    @NonNull
    @SerializedName("langs")
    public Map<String, String> langs;

}


问:
Last character of php string in php
In C the last character of a string is always '\0' Is it same for PHP as well? If not, then what's the last character of a string in PHP?</p>

答:
I think its should be worked

```<code>  $lastChar = substr($string, -1);
</code>```

Title: Last character of php string in php

Body:
I think its should be worked

  $lastChar = substr($string, -1);


问:
Google material design in dynamic page
So, I am using infinite scroll (http://infiniteajaxscroll.com/docs/getting-started.html).

However when the main content is inside of "mdl-js-layout" the infinite scroll function does not work (shown below)

So, if I remove the mdl-js-layout in the most outer div, then infinite scroll works otherwise it does not work.

```<code><div class="mdl-layout mdl-js-layout mdl-layout--fixed-header mdl-layout--fixed-drawer">
<header class="mdl-layout__header">
    Head
</head>
<main class="mdl-layout__content">
    <div class="rfp_hide" id="rhm_post_show">
        <?php
        if ( get_query_var('paged') ) {
            $paged = get_query_var('paged');
        } elseif ( get_query_var('page') ) {
            $paged = get_query_var('page');
        } else {
            $paged = 1;
        }
        $args = array(
            'paged'=>$paged,
            'posts_per_page' => 5,
            'orderby' => 'date',
            'order' => 'DESC'
            );
        $loop = new WP_Query( $args );
        global $post, $paged;
        while ( $loop->have_posts() ) : $loop->the_post();
        ?>
        <div class="rhm_post_container">
            Post
        </div>
        <?php endwhile; ?>
        <?php wp_reset_postdata(); ?>
    </div>
    <nav id="rh_nav_below">
        <ul>
            <li class="rh_nav_previous"><?php previous_posts_link( '« PREV', $loop->max_num_pages) ?></li>
            <li class="rh_nav_next"><?php next_posts_link( 'NEXT »', $loop->max_num_pages) ?></li>
        </ul>
    </nav>
</main>
</div>

<script>
var container = document.querySelector('#rhm_post_show');
var msnry = new Masonry( container, {
  // options
  itemSelector: '.rhm_post_container',
  gutter: 10
});

var ias = $.ias({
  container:  '#rhm_post_show',
  item:       '.rhm_post_container',
  pagination: '#rh_nav_below',
  next:       '.rh_nav_next a',
  delay: 100
});

ias.on('render', function(items) {
  $(items).css({ opacity: 0 });
});

ias.on('rendered', function(items) {
  msnry.appended(items);
});

 ias.extension(new IASSpinnerExtension());
 ias.extension(new IASNoneLeftExtension({html: '<div class="ias-noneleft" style="text-align:center"><p><em>You reached the end!</em></p></div>'}));
 </script>
</code>```

I asked the developer and got the following response:(https://github.com/google/material-design-lite/issues/1584#issuecomment-139060676)

MDL is targeting static content for now, so use-cases with infinite scroll are not supported by us right now. However, there are people who have made MDL work with dynamic sites and you can probably get valuable help by heading over to StackOverflow and using the material-design-lite tag.

Does anyone what I should try?

Thanks!

答:
I also had some issues with dynamic websites and mdl.

On their website I found the following paragraph about dynamic websites, which helped in my case:
https://getmdl.io/started/index.html#dynamic

Material Design Lite will automatically register and render all elements marked with MDL classes upon page load. However in the case where you are creating DOM elements dynamically you need to register new elements using the upgradeElement function.

They also provide an example, how to use the function.

Title: Google material design in dynamic page

Body:
So, I am using infinite scroll (http://infiniteajaxscroll.com/docs/getting-started.html).

However when the main content is inside of "mdl-js-layout" the infinite scroll function does not work (shown below)

So, if I remove the mdl-js-layout in the most outer div, then infinite scroll works otherwise it does not work.

    Head

        <?php
        if ( get_query_var('paged') ) {
            $paged = get_query_var('paged');
        } elseif ( get_query_var('page') ) {
            $paged = get_query_var('page');
        } else {
            $paged = 1;
        }
        $args = array(
            'paged'=>$paged,
            'posts_per_page' => 5,
            'orderby' => 'date',
            'order' => 'DESC'
            );
        $loop = new WP_Query( $args );
        global $post, $paged;
        while ( $loop->have_posts() ) : $loop->the_post();
        ?>

            Post

        <?php endwhile; ?>
        <?php wp_reset_postdata(); ?>

<?php previous_posts_link( '« PREV', $loop->max_num_pages) ?>

<?php next_posts_link( 'NEXT »', $loop->max_num_pages) ?>

I asked the developer and got the following response:(https://github.com/google/material-design-lite/issues/1584#issuecomment-139060676)

MDL is targeting static content for now, so use-cases with infinite scroll are not supported by us right now. However, there are people who have made MDL work with dynamic sites and you can probably get valuable help by heading over to StackOverflow and using the material-design-lite tag.

Does anyone what I should try?

Thanks!


问:
secure or encrypt smarty plugins
I am working on CMS system using smarty. The one cms system could support multiple websites with multiple websites, multiple templates, multiple plugins and components...

Client can register and create his website using pre existing templates and choose components to display them on that template.

My Question is that How i can make those component secure or encrypted. so if client take his site away from the server to another server, he won't able to use those module, components etc. or atleast these would expire after certain time..

I am going to create these components using smarty plugins.

Is there any solution in php, smarty ?

答:
Instead of trying to secure the file itself, you may just make those templates private :

Set up the include_path of your php environment to a private folder, thus, your application can use the files in this folder, templates included.
Your users however can't retrieve the files easily.

Title: secure or encrypt smarty plugins


问:
Android - deleting items from ListView but not from Database
So I have a small problem, my code deletes ListView row from ListView but every time I kill the app and then reopen it the "deleted" rows populate the ListView again.

Here's the code for delete method in DatabaseHelper class:

```<code> public void obrisiTrening(int id){
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(DBKonstante.TABLE_NAME, DBKonstante.KEY_ID + "=?", new String[]{String.valueOf(id)});
        db.close();
</code>```

And here's what my code for deleting ListView row and record from database:

```<code>  rec_WorkoutItemsList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {

            final Dialog dialog = new Dialog(MainActivity.this);
            dialog.setContentView(R.layout.dialog_delete);

            final TextView tvDialogDelete = (TextView) dialog.findViewById(R.id.tvDialogDelete);

            tvDialogDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final DBPodatci infoData = dbPodatci.get(i);
                    dba = new DBHandler(MainActivity.this);
                    int position = dbPodatci.indexOf(infoData);
                    dbPodatci.remove(position);

                    DBPodatci podatki = new DBPodatci();
                    final int idToDelete = podatki.getItemId();

                    dba.obrisiTrening(idToDelete);
                    dba = new DBHandler(MainActivity.this);
                    dba.obrisiTrening(i);

                    rec_WorkoutItemsList.setAdapter(vjezbaAdapter);
                    vjezbaAdapter.notifyDataSetChanged();
                    dialog.dismiss();

                }
            });
            dialog.show();

            return false;
        }
    });
</code>```

DB PODATCI

```<code>public class DBPodatci {
    public String odabraneVjezbe, recordDate;
    public int itemId;

    public String getOdabraneVjezbe() {
        return odabraneVjezbe;
    }

    public void setOdabraneVjezbe(String odabraneVjezbe) {
        this.odabraneVjezbe = odabraneVjezbe;
    }

    public String getRecordDate() {
        return recordDate;
    }

    public void setRecordDate(String recordDate) {

    this.recordDate = recordDate;
}

public int getItemId() {
    return itemId;
}

public void setItemId(int itemId) {
    this.itemId = itemId;
}
</code>```

}

答:
Not sure what this is trying to do.

```<code>dba.obrisiTrening(idToDelete);
dba = new DBHandler(MainActivity.this);
dba.obrisiTrening(i);
</code>```

You only need this

```<code>   final TextView tvDialogDelete = (TextView) dialog.findViewById(R.id.tvDialogDelete);

    final DBHandler dba = new DBHandler(MainActivity.this);

        tvDialogDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final DBPodatci infoData = dbPodatci.get(i);
                final int idToDelete = infoData.getItemId();

                dbPodatci.remove(i);
                dba.obrisiTrening(idToDelete);

                vjezbaAdapter.notifyDataSetChanged();
                dialog.dismiss();
</code>```

And note: you shouldnt be using an Arraylist & ArrayAdapter here... You are using a database, so CursorAdapter is what you want

Body:
So I have a small problem, my code deletes ListView row from ListView but every time I kill the app and then reopen it the "deleted" rows populate the ListView again.

Here's the code for delete method in DatabaseHelper class:

 public void obrisiTrening(int id){
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(DBKonstante.TABLE_NAME, DBKonstante.KEY_ID + "=?", new String[]{String.valueOf(id)});
        db.close();

And here's what my code for deleting ListView row and record from database:

  rec_WorkoutItemsList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {

            final Dialog dialog = new Dialog(MainActivity.this);
            dialog.setContentView(R.layout.dialog_delete);

            final TextView tvDialogDelete = (TextView) dialog.findViewById(R.id.tvDialogDelete);

            tvDialogDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final DBPodatci infoData = dbPodatci.get(i);
                    dba = new DBHandler(MainActivity.this);
                    int position = dbPodatci.indexOf(infoData);
                    dbPodatci.remove(position);

                    DBPodatci podatki = new DBPodatci();
                    final int idToDelete = podatki.getItemId();

                    dba.obrisiTrening(idToDelete);
                    dba = new DBHandler(MainActivity.this);
                    dba.obrisiTrening(i);

                    rec_WorkoutItemsList.setAdapter(vjezbaAdapter);
                    vjezbaAdapter.notifyDataSetChanged();
                    dialog.dismiss();

                }
            });
            dialog.show();

            return false;
        }
    });

DB PODATCI

public class DBPodatci {
    public String odabraneVjezbe, recordDate;
    public int itemId;

    public String getOdabraneVjezbe() {
        return odabraneVjezbe;
    }

    public void setOdabraneVjezbe(String odabraneVjezbe) {
        this.odabraneVjezbe = odabraneVjezbe;
    }

    public String getRecordDate() {
        return recordDate;
    }

    public void setRecordDate(String recordDate) {

    this.recordDate = recordDate;
}

public int getItemId() {
    return itemId;
}

public void setItemId(int itemId) {
    this.itemId = itemId;
}

}

Body:
Not sure what this is trying to do.

dba.obrisiTrening(idToDelete);
dba = new DBHandler(MainActivity.this);
dba.obrisiTrening(i);

You only need this

   final TextView tvDialogDelete = (TextView) dialog.findViewById(R.id.tvDialogDelete);

    final DBHandler dba = new DBHandler(MainActivity.this);

        tvDialogDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final DBPodatci infoData = dbPodatci.get(i);
                final int idToDelete = infoData.getItemId();

                dbPodatci.remove(i);
                dba.obrisiTrening(idToDelete);

                vjezbaAdapter.notifyDataSetChanged();
                dialog.dismiss();

And note: you shouldnt be using an Arraylist & ArrayAdapter here... You are using a database, so CursorAdapter is what you want


问:
How to set start time and end time in fullcalendar from input textboxes using jquery timepicker
In my modal I have two input textbox startTime and endTime using jquery timepicker

I'm able to stick the event in the right date selected from the jquery ui calendar but How can I get the values from Start Time and End Time then set those values in event of fullcalendar?

I know how to get the values in those input e.g. $('#startTime').val() but stacked in there to set it as the start Time for the fullcalendar.

Below is my code:

```<code>  function setTimeValues(x,y)
{
    var startHour = parseInt( $('#startTime').val());
    var endHour = parseInt($('#endTime').val());

    //x = moment(x)
    //            .set({ hour: parseInt(_startHour), minute: parseInt(_startMinutes), date: parseInt(_day), month: parseInt(_month), year: parseInt(_year) })
    //            .toDate();

    // y = moment(y)
    //           .set({ hour: parseInt(_endHour), minute: parseInt(_endMinute), date: parseInt(_day), month: parseInt(_month), year: parseInt(_year) })
    //           .toDate();

    $("#calendar").fullCalendar('renderEvent',
    {
        title: $('#CustomerFullName :selected').text(),
        description: $('#description').val(),
        start: x,
        end: y,
        allDay: false
    },

        true)
</code>```

Thanks!

答:
Try to format date as following yyyy-mm-dd then the time picker as following:

```<code>$(document).ready(function(){
    //init
    $('#startTime').timepicker({ timeFormat: 'H:i' });
    $('#endTime').timepicker({ timeFormat: 'H:i' });
});
</code>```

then at start & end variables use:

```<code>start: x + "T" + startHour + ":00",
end: y + "T" + endHour + ":00",
</code>```

And don't forget to remove parseInt from start & end hour because all you need is the formatted text

Body:
In my modal I have two input textbox startTime and endTime using jquery timepicker

I'm able to stick the event in the right date selected from the jquery ui calendar but How can I get the values from Start Time and End Time then set those values in event of fullcalendar?

I know how to get the values in those input e.g. $('#startTime').val() but stacked in there to set it as the start Time for the fullcalendar.

Below is my code:

  function setTimeValues(x,y)
{
    var startHour = parseInt( $('#startTime').val());
    var endHour = parseInt($('#endTime').val());

    //x = moment(x)
    //            .set({ hour: parseInt(_startHour), minute: parseInt(_startMinutes), date: parseInt(_day), month: parseInt(_month), year: parseInt(_year) })
    //            .toDate();

    // y = moment(y)
    //           .set({ hour: parseInt(_endHour), minute: parseInt(_endMinute), date: parseInt(_day), month: parseInt(_month), year: parseInt(_year) })
    //           .toDate();

    $("#calendar").fullCalendar('renderEvent',
    {
        title: $('#CustomerFullName :selected').text(),
        description: $('#description').val(),
        start: x,
        end: y,
        allDay: false
    },

        true)

Thanks!

Body:
Try to format date as following yyyy-mm-dd then the time picker as following:

$(document).ready(function(){
    //init
    $('#startTime').timepicker({ timeFormat: 'H:i' });
    $('#endTime').timepicker({ timeFormat: 'H:i' });
});

then at start & end variables use:

start: x + "T" + startHour + ":00",
end: y + "T" + endHour + ":00",

And don't forget to remove parseInt from start & end hour because all you need is the formatted text


问:
Test zoom levels of page on browsers in selenium webdriver
To zoom in webpage on browser I searched solution and used following ways but I am receiving either an error or no zoom effect. Can someone please help me to identify where is the mistake or what's wrong with the code. Browser I am using is Chrome.

First method:

```<code>element = driver.findElement(By.tagName("html"));
element.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));
</code>```

Error received on this: Exception in thread "main"
  org.openqa.selenium.WebDriverException: unknown error: cannot focus
  element

To solve above error I tried:

```<code>element = driver.findElement(By.tagname("html"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.click();
actions.sendKeys(Keys.CONTROL, Keys.ADD);
actions.build().perform();
</code>```

Error received: unknown error: Failed to execute 'getComputedStyle' on
  'Window': parameter 1 is not of type 'Element'.

Also I tried to replace element html with body but zoom not worked

Third way:

```<code>JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.body.style.zoom='80%'");
</code>```

答:
Here is what you need:

```<code>new Actions(driver)
     .sendKeys(Keys.Control).sendKeys(Keys.Add)
     .perform();
</code>```

At list this works for me on C#.

Body:
To zoom in webpage on browser I searched solution and used following ways but I am receiving either an error or no zoom effect. Can someone please help me to identify where is the mistake or what's wrong with the code. Browser I am using is Chrome.

First method:

element = driver.findElement(By.tagName("html"));
element.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));

Error received on this: Exception in thread "main"
  org.openqa.selenium.WebDriverException: unknown error: cannot focus
  element

To solve above error I tried:

element = driver.findElement(By.tagname("html"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.click();
actions.sendKeys(Keys.CONTROL, Keys.ADD);
actions.build().perform();

Error received: unknown error: Failed to execute 'getComputedStyle' on
  'Window': parameter 1 is not of type 'Element'.

Also I tried to replace element html with body but zoom not worked

Third way:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.body.style.zoom='80%'");

Body:
Here is what you need:

new Actions(driver)
     .sendKeys(Keys.Control).sendKeys(Keys.Add)
     .perform();

At list this works for me on C#.


问:
Static member type or nothing in Julia
Just trying to get my head around Julia and came across the need where a type member should be of a particular type or it can also be nothing. So, I tried the following:

```<code>using NIfTI  # Julia package for reading NIfTI medical images

type RR
    source::Union(NIfTI.NIVolume, nothing)
end
</code>```

However, when I try to initialize this object, I get:

ERROR: LoadError: LoadError: MethodError: no method matching
  Union(::Type{NIfTI.NIVolume}, ::Void)

The reason I want to do this is that there is no good default way to initialize the NIVolume object and it seems a good idea to leave it uninitialized till needed.

答:
Julia's type system can also express the concept that an expression cannot produce any value – e.g. if it throws an error or is part of a basic block that cannot execute (dead code). The type of an expression that can never produce a value is the empty union type, Union{}: a union of zero types, of which no values are instances. This is distinct from the type of nothing – since nothing is a normal (but uninteresting) value, so it cannot be an instance of Union{}.

http://docs.julialang.org/en/release-0.4/manual/faq/#nothingness-and-missing-values

Title: Static member type or nothing in Julia

Body:
Just trying to get my head around Julia and came across the need where a type member should be of a particular type or it can also be nothing. So, I tried the following:

using NIfTI  # Julia package for reading NIfTI medical images

type RR
    source::Union(NIfTI.NIVolume, nothing)
end

However, when I try to initialize this object, I get:

ERROR: LoadError: LoadError: MethodError: no method matching
  Union(::Type{NIfTI.NIVolume}, ::Void)

The reason I want to do this is that there is no good default way to initialize the NIVolume object and it seems a good idea to leave it uninitialized till needed.


问:
Storing User Input in a List and writing a loop to find a valid value from that list
New to coding...
i am a student and have been tasked with writing a code that asks the user to input a series of values that will i will store in a list and then to ask to input a value (continue this until user types done) and then to check to determine if it is found in the list of valid values.

I'm assuming this could be done with a while true loop to accomplish the input until 'done' is typed and i'm assuming a search using 'if' and 'in' would accomplish the second part.

I am struggling finding a while true using the list of input. i am using an integer input. what am i comparing the condition to if to continue the loop?

Any help is appreciated! The code below is what i wrote i test if i could store input in a list but the while true is where i'm struggling with what to compare.

```<code>while True:
    if list_of_inputs
list_of_inputs = input("Write numbers: ").split()
list_of_inputs = list(map(int , list_of_inputs))
print (list_of_inputs)
</code>```

答:
Python 3.x

```<code>list_of_inputs = list()
while True:
    var = input("Enter Number or type 'done' to exit :")
    if var.lower() == 'done':
        print(" Your inputs are: ",list_of_inputs)
        exit()
    else:
        list_of_inputs.append(int(var))
</code>```

Make sure indentation is proper in python codes.

Body:
New to coding...
i am a student and have been tasked with writing a code that asks the user to input a series of values that will i will store in a list and then to ask to input a value (continue this until user types done) and then to check to determine if it is found in the list of valid values.

I'm assuming this could be done with a while true loop to accomplish the input until 'done' is typed and i'm assuming a search using 'if' and 'in' would accomplish the second part.

I am struggling finding a while true using the list of input. i am using an integer input. what am i comparing the condition to if to continue the loop?

Any help is appreciated! The code below is what i wrote i test if i could store input in a list but the while true is where i'm struggling with what to compare.

while True:
    if list_of_inputs
list_of_inputs = input("Write numbers: ").split()
list_of_inputs = list(map(int , list_of_inputs))
print (list_of_inputs)

Body:
Python 3.x

list_of_inputs = list()
while True:
    var = input("Enter Number or type 'done' to exit :")
    if var.lower() == 'done':
        print(" Your inputs are: ",list_of_inputs)
        exit()
    else:
        list_of_inputs.append(int(var))

Make sure indentation is proper in python codes.


问:
Select all for checkbox does not work
```<code>  <div class="col-6 col-md-3">
  <p class="orange OldStandard"> Menu Filters</p>
  <input type="button" class="check" value="Select All"/>
  <input type="button" class="uncheck" value= "Unselect All"/>
  <br>
        <input type="checkbox" id="vegan" checked/> <label for="vegan">Vegan</label>
        <br/>
        <input type="checkbox" id="vegetarian" checked/> <label for="vegetarian">Vegetarian</label>
        <br/>
        <input type="checkbox" id="pescetarian" checked/> <label for="pescetarian">Pescetarian</label>
         <br/>
        <input type="checkbox" id="dairy-free" checked/> <label for="dairy-free">Dairy-free</label>
         <br/>
        <input type="checkbox" id="egg-free" checked/> <label for="egg-free">Egg-free</label>
         <br/>
        <input type="checkbox" id="fish-free" checked/> <label for="fish-free">Fish-free</label>
         <br/>
        <input type="checkbox" id="shellfish" checked/> <label for="shellfish">Shellfish-free</label>
          <br/>
        <input type="checkbox" id="tree" checked/> <label for="tree">Tree nut-free</label>
          <br/>
        <input type="checkbox" id="peanut" checked/> <label for="peanut">Peanut-free</label>
          <br/>
        <input type="checkbox" id="soy" checked/> <label for="soy">Soy-free</label>
          <br/>
        <input type="checkbox" id="total-fat" checked/> <label for="total-fat">Low Total Fat</label>
          <br/>
        <input type="checkbox" id="saturated-fat" checked/> <label for="saturated-fat">Low Saturated Fat</label>
          <br/>
        <input type="checkbox" id="cholesterol" checked/> <label for="cholesterol">Low Cholesterol</label>
          <br/>
        <input type="checkbox" id="sodium" checked/> <label for="sodium">Low Sodium</label>
          <br/>
        <input type="checkbox" id="protein" checked/> <label for="protein">Protein >25g</label>
          <br/>
        <input type="checkbox" id="calories" checked/> <label for="calories">Calories  <450 calories</label>
  <br>

  </div>
<script src="http://code.jquery.com/jquery.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script>
$(document).ready(function() {
    $('.check').click(function (){
        $('input[type="checkbox"]').attr("checked", "checked");
    });
    $('.uncheck').click(function (){
        $('input:checkbox').removeAttr('checked');
    });
});
</script>
</code>```

This is my code, it contains many food selections, now they are all preselected when you first enter the page, and you have an option to unselect or select all, my unselect works perfectly fine, but my select all does not work at all, I tried different ways for example the one above and :
$('input:checkbox').attr("checked", "checked"); but it still didnt work. Could anyone help?

答:
To fix the issue use prop('checked', true) instead of attr(), and prop('checked', false) instead of removeAttr():

$('.check').click(function() {
  $('input[type="checkbox"]').prop("checked", true);
});

$('.uncheck').click(function() {
  $('input:checkbox').prop("checked", false);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="col-6 col-md-3">
  <p class="orange OldStandard"> Menu Filters</p>
  <input type="button" class="check" value="Select All" />
  <input type="button" class="uncheck" value="Unselect All" /><br>

  <input type="checkbox" id="vegan" checked/> <label for="vegan">Vegan</label><br/>
  <input type="checkbox" id="vegetarian" checked/> <label for="vegetarian">Vegetarian</label><br/>
  <input type="checkbox" id="pescetarian" checked/> <label for="pescetarian">Pescetarian</label><br/>
  <input type="checkbox" id="dairy-free" checked/> <label for="dairy-free">Dairy-free</label><br/>
  <input type="checkbox" id="egg-free" checked/> <label for="egg-free">Egg-free</label><br/>
  <input type="checkbox" id="fish-free" checked/> <label for="fish-free">Fish-free</label><br/>
  <input type="checkbox" id="shellfish" checked/> <label for="shellfish">Shellfish-free</label><br/>
  <input type="checkbox" id="tree" checked/> <label for="tree">Tree nut-free</label><br/>
  <input type="checkbox" id="peanut" checked/> <label for="peanut">Peanut-free</label><br/>
  <input type="checkbox" id="soy" checked/> <label for="soy">Soy-free</label><br/>
  <input type="checkbox" id="total-fat" checked/> <label for="total-fat">Low Total Fat</label><br/>
  <input type="checkbox" id="saturated-fat" checked/> <label for="saturated-fat">Low Saturated Fat</label><br/>
  <input type="checkbox" id="cholesterol" checked/> <label for="cholesterol">Low Cholesterol</label><br/>
  <input type="checkbox" id="sodium" checked/> <label for="sodium">Low Sodium</label><br/>
  <input type="checkbox" id="protein" checked/> <label for="protein">Protein >25g</label><br/>
  <input type="checkbox" id="calories" checked/> <label for="calories">Calories  < 450 calories</label><br>
</div></code>```

Also note that you should use the HTML character entity for <, <, so that it doesn't interfere with your HTML.

Title: Select all for checkbox does not work

Body:
 Menu Filters

  <input type="button" class="check" value="Select All"/>
  <input type="button" class="uncheck" value= "Unselect All"/>

        <input type="checkbox" id="vegan" checked/> Vegan

        <input type="checkbox" id="vegetarian" checked/> Vegetarian

        <input type="checkbox" id="pescetarian" checked/> Pescetarian

        <input type="checkbox" id="dairy-free" checked/> Dairy-free

        <input type="checkbox" id="egg-free" checked/> Egg-free

        <input type="checkbox" id="fish-free" checked/> Fish-free

        <input type="checkbox" id="shellfish" checked/> Shellfish-free

        <input type="checkbox" id="tree" checked/> Tree nut-free

        <input type="checkbox" id="peanut" checked/> Peanut-free

        <input type="checkbox" id="soy" checked/> Soy-free

        <input type="checkbox" id="total-fat" checked/> Low Total Fat

        <input type="checkbox" id="saturated-fat" checked/> Low Saturated Fat

        <input type="checkbox" id="cholesterol" checked/> Low Cholesterol

        <input type="checkbox" id="sodium" checked/> Low Sodium

        <input type="checkbox" id="protein" checked/> Protein >25g

        <input type="checkbox" id="calories" checked/> Calories  <450 calories

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

This is my code, it contains many food selections, now they are all preselected when you first enter the page, and you have an option to unselect or select all, my unselect works perfectly fine, but my select all does not work at all, I tried different ways for example the one above and :
$('input:checkbox').attr("checked", "checked"); but it still didnt work. Could anyone help?

Body:
To fix the issue use prop('checked', true) instead of attr(), and prop('checked', false) instead of removeAttr():

$('.check').click(function() {
  $('input[type="checkbox"]').prop("checked", true);
});

$('.uncheck').click(function() {
  $('input:checkbox').prop("checked", false);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="col-6 col-md-3">
  <p class="orange OldStandard"> Menu Filters</p>
  <input type="button" class="check" value="Select All" />
  <input type="button" class="uncheck" value="Unselect All" /><br>

  <input type="checkbox" id="vegan" checked/> <label for="vegan">Vegan</label><br/>
  <input type="checkbox" id="vegetarian" checked/> <label for="vegetarian">Vegetarian</label><br/>
  <input type="checkbox" id="pescetarian" checked/> <label for="pescetarian">Pescetarian</label><br/>
  <input type="checkbox" id="dairy-free" checked/> <label for="dairy-free">Dairy-free</label><br/>
  <input type="checkbox" id="egg-free" checked/> <label for="egg-free">Egg-free</label><br/>
  <input type="checkbox" id="fish-free" checked/> <label for="fish-free">Fish-free</label><br/>
  <input type="checkbox" id="shellfish" checked/> <label for="shellfish">Shellfish-free</label><br/>
  <input type="checkbox" id="tree" checked/> <label for="tree">Tree nut-free</label><br/>
  <input type="checkbox" id="peanut" checked/> <label for="peanut">Peanut-free</label><br/>
  <input type="checkbox" id="soy" checked/> <label for="soy">Soy-free</label><br/>
  <input type="checkbox" id="total-fat" checked/> <label for="total-fat">Low Total Fat</label><br/>
  <input type="checkbox" id="saturated-fat" checked/> <label for="saturated-fat">Low Saturated Fat</label><br/>
  <input type="checkbox" id="cholesterol" checked/> <label for="cholesterol">Low Cholesterol</label><br/>
  <input type="checkbox" id="sodium" checked/> <label for="sodium">Low Sodium</label><br/>
  <input type="checkbox" id="protein" checked/> <label for="protein">Protein >25g</label><br/>
  <input type="checkbox" id="calories" checked/> <label for="calories">Calories  &lt; 450 calories</label><br>
</div>

Also note that you should use the HTML character entity for <, &lt;, so that it doesn't interfere with your HTML.


答:
May I offer a solution where you have a single button controlling the display of the menu instead of two buttons?

Main changes were to increase the z-index of .mobile-menu-button so it's always on top of your menu and to check in the text value of the button and decide whether to open or close it. You could also check if the menu has .act on it instead of checking the text of the button; tomayto, tomahto.

$( document ).ready( function () {

  var $mobileMenu = $( '.mobileMenu' );

  $('.menuBtn').on( 'click touch', function () {

    var $this = $( this ),
        isOpen = 'Close' === $this.text();

    $this.text( isOpen ? 'Open' : 'Close' );
    $mobileMenu.toggleClass( 'act', !isOpen );

  } );

} );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.mobile-menu-button {
  display: block;
  position: fixed;
  top: 20px;
  left: 20px;
  z-index: 105;
  background-color: #19b698;
  padding: 5px 10px;
  color: #fff;
  font-family: Open Sans;
  font-weight: bold;
  cursor: pointer;
}

.mobile-menu-button i {
  font-size: 26px;
  background-color: #00adee;
  padding: 5px 10px;
  color: #fff;
}

.mobileMenu {
  background-color: #fff !important;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  height: 100vh;
  width: 100vw;
  display: block;
  text-align: center;
  opacity: 0;
  -webkit-transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  -webkit-transform: scale(0);
  transform: scale(0);
  overflow: hidden;
}

.mobileMenu img {
  max-width: 90%;
  margin: 0 auto;
  margin-top: 20px;
  margin-bottom: 10px;
  border-bottom: 1px dotted #717274;
  padding-bottom: 20px;
}

.mobileMenu.act {
  opacity: 1;
  -webkit-transform: scale(1);
  transform: scale(1);
}

.mobileMenu.act ul li {
  opacity: 1;
  -webkit-transform: translateX(0);
  transform: translateX(0);
  display: block !important;
}

.mobileMenu ul {
  display: block;
  list-style: none;
}

.mobileMenu li {
  padding: 10px 0 !important;
  -webkit-transition: all 400ms 510ms;
  transition: all 400ms 510ms;
  opacity: 0;
}

.mobileMenu li:nth-child(odd) {
  -webkit-transform: translateX(30%);
  transform: translateX(30%);
}

.mobileMenu li:nth-child(even) {
  -webkit-transform: translateX(-30%);
  transform: translateX(-30%);
}

.mobileMenu li:last-child {
  -webkit-transform: none;
  transform: none;
}

.mobileMenu a {
  color: #00adee !important;
  display: inline-block;
  font-size: 18px;
}

.mobileMenu a.suBtn {
  color: #fff;
}</code>```

Open

Home

Testimonials

Contact

```

I also added list-style: none; to .mobileMenu ul as I noticed some bullet points. I'm assuming you didn't want those.

Why Two Clicks?

As far as why you had to click twice, you were using toggleClass() on two different buttons to open/close the menu. The first button (Open) would get .act added and the menu would show. Now we're seeing the second button (Close) which doesn't have .act yet, so you click it and toggleClass() adds .act to it (instead of removing .act from the first button (Open) like you might have been expecting). Since a button needs .act on it to hide the menu, you now need to click the second button (Close) a second time to for toggelClass() to remove .act and hide the menu. Now the first button (Open) is shown, which still has .act. But clicking it removes .act, thus necessitating one more click to add .act back to the button and now the menu can be show because the button has .act.

It's more simple to use a single button.

Title: Why must I click twice to open and close my menu

Body:
Hello I got a situation which I do not understand quite well. I have the following setup:

 $(document).ready(function(){
  $('.menuBtn').on('click touch', function () {
  $(this).toggleClass('act');
   if($(this).hasClass('act')) {
    $('.mobileMenu').addClass('act');
    //$('body').addClass('positionfixed');
   }
   else {
    $('.mobileMenu').removeClass('act');
    //$('body').removeClass('positionfixed');
   }
 });
   });

 .mobile-menu-button{
  display:block;
  position:fixed;
  top:20px;
  left:20px;
  z-index:99;
    background-color:#19b698;
    padding:5px 10px;
    color:#fff;
    font-family: Open Sans;
    font-weight:bold;
 }
 .mobile-menu-button i{
  font-size:26px;
  background-color:#00adee;
  padding:5px 10px;
  color:#fff;
 }
.mobileMenu {
  background-color: #fff !important;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  height: 100vh;
  width: 100vw;
  display: block;
  text-align: center;
  opacity: 0;
  -webkit-transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  -webkit-transform: scale(0);
     transform: scale(0);
  overflow:hidden;
 }
 .mobileMenu img{
  max-width:90%;
  margin:0 auto;
  margin-top:20px;
  margin-bottom:10px;
  border-bottom:1px dotted #717274;
  padding-bottom:20px;
 }
 .mobileMenu.act {
  opacity: 1;
  -webkit-transform: scale(1);
     transform: scale(1);
 }
 .mobileMenu.act ul li {
  opacity: 1;
  -webkit-transform: translateX(0);
     transform: translateX(0);
  display:block !important;
 }
 .mobileMenu ul {
  display: block;
  vertical-align: middle;
 }
 .mobileMenu li {
  padding: 10px 0 !important;
  -webkit-transition: all 400ms 510ms;
  transition: all 400ms 510ms;
  opacity: 0;
 }
 .mobileMenu li:nth-child(odd) {
   -webkit-transform: translateX(30%);
     transform: translateX(30%);
 }
 .mobileMenu li:nth-child(even) {
   -webkit-transform: translateX(-30%);
     transform: translateX(-30%);
 }
 .mobileMenu li:last-child {
   -webkit-transform: none;
     transform: none;
 }
 .mobileMenu a {
   color: #00adee !important;
   display: inline-block;
   font-size: 18px;
 }
 .mobileMenu a.suBtn {
   color: #fff;
 }

Open

  Close

Home

Testimonials

Contact

Why should I press two times on the open / close button to open / close the menu?

Anyone any idea / fix?

Body:
May I offer a solution where you have a single button controlling the display of the menu instead of two buttons?

Main changes were to increase the z-index of .mobile-menu-button so it's always on top of your menu and to check in the text value of the button and decide whether to open or close it. You could also check if the menu has .act on it instead of checking the text of the button; tomayto, tomahto.

$( document ).ready( function () {

  var $mobileMenu = $( '.mobileMenu' );

  $('.menuBtn').on( 'click touch', function () {

    var $this = $( this ),
        isOpen = 'Close' === $this.text();

    $this.text( isOpen ? 'Open' : 'Close' );
    $mobileMenu.toggleClass( 'act', !isOpen );

  } );

} );

.mobile-menu-button {
  display: block;
  position: fixed;
  top: 20px;
  left: 20px;
  z-index: 105;
  background-color: #19b698;
  padding: 5px 10px;
  color: #fff;
  font-family: Open Sans;
  font-weight: bold;
  cursor: pointer;
}

.mobile-menu-button i {
  font-size: 26px;
  background-color: #00adee;
  padding: 5px 10px;
  color: #fff;
}

.mobileMenu {
  background-color: #fff !important;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  height: 100vh;
  width: 100vw;
  display: block;
  text-align: center;
  opacity: 0;
  -webkit-transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  transition: all 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  -webkit-transform: scale(0);
  transform: scale(0);
  overflow: hidden;
}

.mobileMenu img {
  max-width: 90%;
  margin: 0 auto;
  margin-top: 20px;
  margin-bottom: 10px;
  border-bottom: 1px dotted #717274;
  padding-bottom: 20px;
}

.mobileMenu.act {
  opacity: 1;
  -webkit-transform: scale(1);
  transform: scale(1);
}

.mobileMenu.act ul li {
  opacity: 1;
  -webkit-transform: translateX(0);
  transform: translateX(0);
  display: block !important;
}

.mobileMenu ul {
  display: block;
  list-style: none;
}

.mobileMenu li {
  padding: 10px 0 !important;
  -webkit-transition: all 400ms 510ms;
  transition: all 400ms 510ms;
  opacity: 0;
}

.mobileMenu li:nth-child(odd) {
  -webkit-transform: translateX(30%);
  transform: translateX(30%);
}

.mobileMenu li:nth-child(even) {
  -webkit-transform: translateX(-30%);
  transform: translateX(-30%);
}

.mobileMenu li:last-child {
  -webkit-transform: none;
  transform: none;
}

.mobileMenu a {
  color: #00adee !important;
  display: inline-block;
  font-size: 18px;
}

.mobileMenu a.suBtn {
  color: #fff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="mobile-menu-button menuBtn">Open</span>
<nav class="mobileMenu">
  <ul>
    <li><a href="index.html">Home</a></li>
    <li><a href="testimonials.html">Testimonials</a></li>
    <li><a href="contact.html">Contact</a></li>
  </ul>
</nav>

I also added list-style: none; to .mobileMenu ul as I noticed some bullet points. I'm assuming you didn't want those.

Why Two Clicks?

As far as why you had to click twice, you were using toggleClass() on two different buttons to open/close the menu. The first button (Open) would get .act added and the menu would show. Now we're seeing the second button (Close) which doesn't have .act yet, so you click it and toggleClass() adds .act to it (instead of removing .act from the first button (Open) like you might have been expecting). Since a button needs .act on it to hide the menu, you now need to click the second button (Close) a second time to for toggelClass() to remove .act and hide the menu. Now the first button (Open) is shown, which still has .act. But clicking it removes .act, thus necessitating one more click to add .act back to the button and now the menu can be show because the button has .act.

It's more simple to use a single button.