问:
Unit testing using doctest in python
Define a function definition of 'isPalindrome' which checks if given number positive number is palindrome or not and return True and False correspondingly.

write a doctest which checks the function call 'isPalindrome(121)' returns True.

write a doctest which checks the function call 'isPalindrome(344)' returns False.

write a doctest which checks the function call 'isPalindrome(-121)' raises ValueError with an error message as 'x must be positive integer'.

write a doctest which checks the function call 'isPalindrome('hello')' raises TypeError with an error message as 'x must be an integer'.

I tried below but its giving answer as -

True
4
1
1
4
0

but the expected answer is

True
4
1
1
4
2

```<code>#!/bin/python3
import math
import os
import random
import re
import sys
import inspect

# Complete the isPalindrome function below.
def isPalindrome(x):
    # Write your doctests below.
    """
    >>> isPalindrome(121)
    True
    >>> isPalindrome(344)
    False
    >>> isPalindrome(-121)
    ValueError: x must be positive integer.
    >>> isPalindrome("hello")
    TypeError: x must be integer.
    """

    # Write the functionality below
    try:
        x = int(x)
        temp=x
        rev=0
        if(x>0):
            while(x>0):
                dig=x%10
                rev=rev*10+dig
                x=x//10
            if(temp==rev):
                return True
            else:
                return False
        elif(x<0):
            raise TypeError
        else:
            raise ValueError
    except ValueError:
        raise ValueError("x must be positive integer")
    except TypeError:
        raise TypeError("x must be an integer")

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    x = input()

    if x.isdigit():
        x = int(x)

    res = isPalindrome(x)

    doc = inspect.getdoc(isPalindrome)

    func_count = len(re.findall(r'isPalindrome', doc))
    true_count = len(re.findall(r'True', doc))
    false_count = len(re.findall(r'False', doc))
    pp_count = len(re.findall(r'>>>', doc))
    trace_count = len(re.findall(r'Traceback', doc))

    fptr.write(str(res)+'\n')
    fptr.write(str(func_count)+'\n')
    fptr.write(str(true_count)+'\n')
    fptr.write(str(false_count)+'\n')
    fptr.write(str(pp_count) + '\n')
    fptr.write(str(trace_count) + '\n')

    fptr.close()
</code>```

Please suggest

答:
Small Modification ---- Use below code

```<code>import math
import os
import random
import re
import sys
import inspect

def isPalindrome(x):
    """
    >>> isPalindrome(121)
    True
    >>> isPalindrome(344)
    False
    >>> isPalindrome(-121)
    Traceback (most recent call last):
    ValueError: x must be positive integer.
    >>> isPalindrome("hello")
    Traceback (most recent call last):
    TypeError: x must be integer.
    """
    try:
        x = int(x)
        temp=x
        rev=0
        if(x>0):
            while(x>0):
                dig=x%10
                rev=rev*10+dig
                x=x//10
            if(temp==rev):
                return True
            else:
                return False
        elif(x<0):
            raise TypeError
        else:
            raise ValueError
    except ValueError:
        raise ValueError("x must be positive integer")
    except TypeError:
        raise TypeError("x must be an integer")
</code>```

Title: Unit testing using doctest in python

Body:
Define a function definition of 'isPalindrome' which checks if given number positive number is palindrome or not and return True and False correspondingly.

write a doctest which checks the function call 'isPalindrome(121)' returns True.

write a doctest which checks the function call 'isPalindrome(344)' returns False.

write a doctest which checks the function call 'isPalindrome(-121)' raises ValueError with an error message as 'x must be positive integer'.

write a doctest which checks the function call 'isPalindrome('hello')' raises TypeError with an error message as 'x must be an integer'.

I tried below but its giving answer as -

True
4
1
1
4
0

but the expected answer is

True
4
1
1
4
2

#!/bin/python3
import math
import os
import random
import re
import sys
import inspect

# Complete the isPalindrome function below.
def isPalindrome(x):
    # Write your doctests below.
    """
    >>> isPalindrome(121)
    True
    >>> isPalindrome(344)
    False
    >>> isPalindrome(-121)
    ValueError: x must be positive integer.
    >>> isPalindrome("hello")
    TypeError: x must be integer.
    """

    # Write the functionality below
    try:
        x = int(x)
        temp=x
        rev=0
        if(x>0):
            while(x>0):
                dig=x%10
                rev=rev*10+dig
                x=x//10
            if(temp==rev):
                return True
            else:
                return False
        elif(x<0):
            raise TypeError
        else:
            raise ValueError
    except ValueError:
        raise ValueError("x must be positive integer")
    except TypeError:
        raise TypeError("x must be an integer")

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    x = input()

    if x.isdigit():
        x = int(x)

    res = isPalindrome(x)

    doc = inspect.getdoc(isPalindrome)

    func_count = len(re.findall(r'isPalindrome', doc))
    true_count = len(re.findall(r'True', doc))
    false_count = len(re.findall(r'False', doc))
    pp_count = len(re.findall(r'>>>', doc))
    trace_count = len(re.findall(r'Traceback', doc))

    fptr.write(str(res)+'\n')
    fptr.write(str(func_count)+'\n')
    fptr.write(str(true_count)+'\n')
    fptr.write(str(false_count)+'\n')
    fptr.write(str(pp_count) + '\n')
    fptr.write(str(trace_count) + '\n')

    fptr.close()

Please suggest

Body:
Small Modification ---- Use below code

import math
import os
import random
import re
import sys
import inspect

def isPalindrome(x):
    """
    >>> isPalindrome(121)
    True
    >>> isPalindrome(344)
    False
    >>> isPalindrome(-121)
    Traceback (most recent call last):
    ValueError: x must be positive integer.
    >>> isPalindrome("hello")
    Traceback (most recent call last):
    TypeError: x must be integer.
    """
    try:
        x = int(x)
        temp=x
        rev=0
        if(x>0):
            while(x>0):
                dig=x%10
                rev=rev*10+dig
                x=x//10
            if(temp==rev):
                return True
            else:
                return False
        elif(x<0):
            raise TypeError
        else:
            raise ValueError
    except ValueError:
        raise ValueError("x must be positive integer")
    except TypeError:
        raise TypeError("x must be an integer")


来源: stackexchange

问:
Flutter: Bottom sheet with TextField/TextFormField
In part of our application, I would like to have a simple form in BottomSheet like with the below code. unfortunately when i put into that, I get an error

The following assertion was thrown during performLayout(): An
InputDecorator, which is typically created by a TextField, cannot have
an unbounded width. This happens when the parent widget does not
provide a finite width constraint. For example, if the InputDecorator
is contained by a Row, then its width must be constrained. An Expanded
widget or a SizedBox can be used to constrain the width of the
InputDecorator or the TextField that contains it.
'package:flutter/src/material/input_decorator.dart': Failed assertion:
line 881 pos 7: 'layoutConstraints.maxWidth < double.infinity'

my implemented code:

```<code>  void _settingModalBottomSheet(context){
    showModalBottomSheet(
        context: context,
        elevation: 8.0,
        builder: (BuildContext bc){
          return Directionality(
            textDirection: TextDirection.rtl,
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minHeight: 250.0
              ),
              child: Container(
                padding: EdgeInsets.fromLTRB(0.0,10.0,0.0,10.0),
                child: new Wrap(
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Center(
                        child: Text(
                          'please fill this form',
                          style: TextStyle(
                            fontSize: 13.0,
                          ),
                        ),
                      ),
                    ),
                    Divider(),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Column(
                          children: <Widget>[
                            Text('item 1'),
                            Container(
                              child: TextField(),
                            )
                          ],
                        ),
                        Column(
                          children: <Widget>[
                            Text('item 2'),
                            Container(
                              child: TextField(),
                            )
                          ],
                        ),

                      ],
                    ),
                  ],
                ),
              ),
            ),
          );
        }
    );
  }
</code>```

答:
You will have to provide a specific width to the TextField, simply provide width in your Container or wrap your Column in  Expanded.

Solution 1

```<code>Container(
  width: 100, // do it in both Container
  child: TextField(),
),
</code>```

Solution 2

```<code>Row(
  mainAxisAlignment: MainAxisAlignment.center,
  crossAxisAlignment: CrossAxisAlignment.center,
  children: <Widget>[
    Expanded( // wrap your Column in Expanded
      child: Column(
        children: <Widget>[
          Text('item 1'),
          Container(child: TextField()),
        ],
      ),
    ),
    Expanded( // wrap your Column in Expanded
      child: Column(
        children: <Widget>[
          Text('item 2'),
          Container(child: TextField()),
        ],
      ),
    ),
  ],
),
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In part of our application, I would like to have a simple form in BottomSheet like with the below code. unfortunately when i put into that, I get an error

The following assertion was thrown during performLayout(): An
InputDecorator, which is typically created by a TextField, cannot have
an unbounded width. This happens when the parent widget does not
provide a finite width constraint. For example, if the InputDecorator
is contained by a Row, then its width must be constrained. An Expanded
widget or a SizedBox can be used to constrain the width of the
InputDecorator or the TextField that contains it.
'package:flutter/src/material/input_decorator.dart': Failed assertion:
line 881 pos 7: 'layoutConstraints.maxWidth < double.infinity'

my implemented code:

  void _settingModalBottomSheet(context){
    showModalBottomSheet(
        context: context,
        elevation: 8.0,
        builder: (BuildContext bc){
          return Directionality(
            textDirection: TextDirection.rtl,
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minHeight: 250.0
              ),
              child: Container(
                padding: EdgeInsets.fromLTRB(0.0,10.0,0.0,10.0),
                child: new Wrap(
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Center(
                        child: Text(
                          'please fill this form',
                          style: TextStyle(
                            fontSize: 13.0,
                          ),
                        ),
                      ),
                    ),
                    Divider(),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Column(
                          children: <Widget>[
                            Text('item 1'),
                            Container(
                              child: TextField(),
                            )
                          ],
                        ),
                        Column(
                          children: <Widget>[
                            Text('item 2'),
                            Container(
                              child: TextField(),
                            )
                          ],
                        ),

                      ],
                    ),
                  ],
                ),
              ),
            ),
          );
        }
    );
  }

Body:
You will have to provide a specific width to the TextField, simply provide width in your Container or wrap your Column in  Expanded.

Solution 1

Container(
  width: 100, // do it in both Container
  child: TextField(),
),

Solution 2

Row(
  mainAxisAlignment: MainAxisAlignment.center,
  crossAxisAlignment: CrossAxisAlignment.center,
  children: <Widget>[
    Expanded( // wrap your Column in Expanded
      child: Column(
        children: <Widget>[
          Text('item 1'),
          Container(child: TextField()),
        ],
      ),
    ),
    Expanded( // wrap your Column in Expanded
      child: Column(
        children: <Widget>[
          Text('item 2'),
          Container(child: TextField()),
        ],
      ),
    ),
  ],
),


问:
Generate a random token in ruby >= 2.5.1 / >= rails 5
I can see from here that has_secure_token can generate a random token for a new record in a (User) model. How can I simply generate a random token without needing to do it for a model? (i.e. suppose an app has no model(s) or to put it really simply, to run some (preferably very simple) method, and it should return a random string like pX27zsMN2ViQKta1bGfLmVJE

I have tried gems SecureRandom and digest as recommended in other answers, but neither seems to bundle install successfully (the SO answers were oldish so perhaps those gems are deprecated?) - I'm using ruby 2.5.1 and rails 5.2.3

My goal is simply to generate tokens to use as keys for an API, so I essentially just need randomly generated strings that are safe to use in urls, perhaps a method that I can specify the length of the token (but I'll take what I can get for now!)

答:
Just use SecureRandom. It's not a gem that you have to install. It's built into Ruby:

```<code>⇒ ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin18]
⇒ irb
2.5.1 :001 > require 'securerandom'
 => true
2.5.1 :002 > SecureRandom.hex(32)
 => "89d45edb28859a905672b707c8f7599f766d12074584ef48a997230dfc0e0998"
2.5.1 :003 > SecureRandom.base64(12)
 => "KaZbhQ7o7U/f9pMs"
2.5.1 :004 > SecureRandom.uuid
 => "ade17ef5-0943-4c70-b417-df7c96c198cd"
</code>```

Body:
Just use SecureRandom. It's not a gem that you have to install. It's built into Ruby:

⇒ ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin18]
⇒ irb
2.5.1 :001 > require 'securerandom'
 => true
2.5.1 :002 > SecureRandom.hex(32)
 => "89d45edb28859a905672b707c8f7599f766d12074584ef48a997230dfc0e0998"
2.5.1 :003 > SecureRandom.base64(12)
 => "KaZbhQ7o7U/f9pMs"
2.5.1 :004 > SecureRandom.uuid
 => "ade17ef5-0943-4c70-b417-df7c96c198cd"


问:
Find date upon which defined age in seconds is reached
I am attempting to write a program that

takes a certain number of seconds (say 1000000000), then

takes a given date (for example one's birthday) and

then determines when (at which given date) this age in number of seconds has been reached.

Certainly, the program should recognize if that age in number of seconds is in the past.
But even before building a check for this, the code runs into problems.

After receiving error message I tried changing parameter name from month to umonth in the input stage. That brought no difference.

```<code>from datetime import datetime

seconds = int(input("seconds: "))

year = int(input("year: "))
month = int(input("month: "))
day = int(input("day: "))

#Calculate time in seconds between now and the day of birth
date = (datetime(year=year, month=month, day=day) - datetime(seconds)).total_seconds()

print("You will be {} seconds old on {} old.".format(seconds, date))
</code>```

I am still dabbling with the datetime library.

I received a TypeError from python3.

"TypeError: Required argument 'month' (pos 2) not found"

Edit:

Following suggestions in the comments, I modified the code for using a new method, to convert a date into seconds.

```<code>from datetime import datetime

#seconds = int(input("seconds: "))
seconds = 1000000000

#year = int(input("year: "))
#month = int(input("month: "))
#day = int(input("day: "))
year = 1987
month = 9
day = 11

date = datetime.datetime(year,month,day)

#Calculate time in seconds between now and the day of birth
(date.total_seconds(datetime(year=year, month=month, day=day)) - seconds)

print("You will be {} seconds old on {} old.".format(seconds, date))
</code>```

That yields an AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

I am aware I dont know exactly how to use datetime library.
Working through the docs to understand.

But still, those things seem trivial to achieve.
Perhaps someone can explain.

The goal is, as before, to take a number of seconds and a date of birth.
And to see when, from the date of birth on, the number of seconds will be reached.

答:
```<code>AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
</code>```

You are receiving the above error because you already used import datetime. No need of writing datetime.datetime. You can directly use datetime(year, month, day).

Body:
I am attempting to write a program that

takes a certain number of seconds (say 1000000000), then

takes a given date (for example one's birthday) and

then determines when (at which given date) this age in number of seconds has been reached.

Certainly, the program should recognize if that age in number of seconds is in the past.
But even before building a check for this, the code runs into problems.

After receiving error message I tried changing parameter name from month to umonth in the input stage. That brought no difference.

from datetime import datetime

seconds = int(input("seconds: "))

year = int(input("year: "))
month = int(input("month: "))
day = int(input("day: "))

#Calculate time in seconds between now and the day of birth
date = (datetime(year=year, month=month, day=day) - datetime(seconds)).total_seconds()

print("You will be {} seconds old on {} old.".format(seconds, date))

I am still dabbling with the datetime library.

I received a TypeError from python3.

"TypeError: Required argument 'month' (pos 2) not found"

Edit:

Following suggestions in the comments, I modified the code for using a new method, to convert a date into seconds.

from datetime import datetime

#seconds = int(input("seconds: "))
seconds = 1000000000

#year = int(input("year: "))
#month = int(input("month: "))
#day = int(input("day: "))
year = 1987
month = 9
day = 11

date = datetime.datetime(year,month,day)

#Calculate time in seconds between now and the day of birth
(date.total_seconds(datetime(year=year, month=month, day=day)) - seconds)

print("You will be {} seconds old on {} old.".format(seconds, date))

That yields an AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

I am aware I dont know exactly how to use datetime library.
Working through the docs to understand.

But still, those things seem trivial to achieve.
Perhaps someone can explain.

The goal is, as before, to take a number of seconds and a date of birth.
And to see when, from the date of birth on, the number of seconds will be reached.

Body:
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

You are receiving the above error because you already used import datetime. No need of writing datetime.datetime. You can directly use datetime(year, month, day).


问:
How do I specify an absolute path?
I wrote this code, but I couldn't get the html. I don't know why. I want to know why this is when the route is not wrong.</p>

```<code><img id = "navLogo" src = "C:/Bitnami/wampstack-7.1.27-0/apache2/htdocs/TermProject/imgs/navLogo.jpg"></img>
</code>```

答:
For security reasons, websites may not request arbitrary files from your machine's filesystem.

Keep in mind that the way this works is the HTML is sent to the browser and then the browser sends a second request for the image.

In this case the browser would be trying to get the file off of your machine, (which may coincidentally be where the web server happens to be running), but if this site were live on the web and someone else accessed it, their browser would be trying to get this image from that user's machine, not from the website.

If the browser was allowed to serve files from your local filesystem, one could very easily create a site to grab files off of your machine and transmit them elsewhere, creating a MASSIVE security problem.

To fix this you should specify a path relative to the web server's root, which would probably mean:

```

<p>or maybe:</p>

<pre class="lang-html prettyprint-override"><code><img src="/TermProject/imgs/navLogo.jpg" />
</code>```

Note that behavior will be different if you're loading the HTML file from the filesystem (the location is file:…) vs. serving it from a web server (location is http://…). I'm assuming you're doing the former here based on the fact that your image is under an apache directory.

Title: How do I specify an absolute path?

Body:
For security reasons, websites may not request arbitrary files from your machine's filesystem.

Keep in mind that the way this works is the HTML is sent to the browser and then the browser sends a second request for the image.

In this case the browser would be trying to get the file off of your machine, (which may coincidentally be where the web server happens to be running), but if this site were live on the web and someone else accessed it, their browser would be trying to get this image from that user's machine, not from the website.

If the browser was allowed to serve files from your local filesystem, one could very easily create a site to grab files off of your machine and transmit them elsewhere, creating a MASSIVE security problem.

To fix this you should specify a path relative to the web server's root, which would probably mean:

<img src="/imgs/navLogo.jpg" />

or maybe:

<img src="/TermProject/imgs/navLogo.jpg" />

Note that behavior will be different if you're loading the HTML file from the filesystem (the location is file:…) vs. serving it from a web server (location is http://…). I'm assuming you're doing the former here based on the fact that your image is under an apache directory.


问:
How to make a list of tuples from several lists?
I have 3 lists:

```<code>a = [0, 1, 2]
b = [3, 4, 5]
c = [6, 7, 8]
</code>```

And I need to create a list of tuples from them.

The output should look like this:

```<code>[(0, 3, 6), (1, 4, 7), (2, 5, 8)]
</code>```

答:
You can do it like so:

list(zip(a, b, c))

Body:
I have 3 lists:

a = [0, 1, 2]
b = [3, 4, 5]
c = [6, 7, 8]

And I need to create a list of tuples from them.

The output should look like this:

[(0, 3, 6), (1, 4, 7), (2, 5, 8)]


答:
Just using zip only.

a = [0, 1, 2]
b = [3, 4, 5]
c = [6, 7, 8]

zipped = list(zip(a, b, c))
```

Title: How to make a list of tuples from several lists?


问:
I want to create the collectionView like it has in JIOtv App. This is something new, Answer not available on Internet
I am attaching the image of JIOtv App. Please help me. I am looking for same EPG

答: That is EPG data for tv you will never have one like but  HERE</p>


问:
How to mock a method call in JUnit when the method is inside a base class and the testing method class extends it?
I need to write unit test in JUnit for a method, the method is inside class A and class A extends Class B. My testing method methodA() calls another methodB() which is inside class B. So how should I mock this methodB() call so that when I call methodA() from my testCase, and when It calls methodB() it gets the mocked value and gets the test case passed?
Which class should I mock, classA or Class B?</p>

```<code>    ///logDaoImpl class extends BaseDaoImpl
    @Override
    public List<Log> LogAll(long fromIndex,long toIndex) {
    String query = "from Log ";
    QueryCondition qd = new QueryCondition();
    qd.setIgnoreCount(false);
    qd.addAndCondition("id", ">=" , "long", fromIndex);
    List<Log> result = findByCustomNamedQuery(query, qd);   //findByCustomNamedQuery method is from my extended class

   return result;
}

    public class BaseDaoImpl extends JpaDaoSupport implements BaseDao {

@PersistenceContext
EntityManager entityManager;

public List findByCustomNamedQuery(String query, QueryCondition qd) {

    if (qd.hasConditions()) {
        query += qd.getCondition() + qd.getOrderBy();
    }

    EntityManager em = getJpaTemplate().getEntityManagerFactory().createEntityManager();
    Query q = em.createQuery(query);
    String[] namedParams = StringUtils.substringsBetween(query, ":", " ");
    if (namedParams != null) {
        for (int i = 0; i < namedParams.length; i++) {
            q.setParameter(namedParams[i], qd.getParamValue(namedParams[i]));
        }
    }

    if (!qd.isIgnoreCount()) {
        q.setFirstResult(qd.start());
        q.setMaxResults(qd.count());
    }

    List result =  q.getResultList();
    em.close();
    return result;
}

//test class
  public void testLogAll() {

  List<Log>expL=new ArrayList<Log>();
    expL.add(Log);//added sample test log object from setup method
    String query = "from Log ";
    QueryCondition qd=new QueryCondition();
    qd.setIgnoreCount(false);
    qd.addAndCondition("id", ">=" , "long", 0L);
    LogDaoImpl obj=Mockito.spy(LogDaoImpl.class);
    when(obj.findByCustomNamedQuery(query,qd)).thenReturn(expL);
    List<UnbanLog> expResult = expL;
    List<UnbanLog> result = obj.LogAll(0L, 20L);
    assertEquals(expResult, result);
}
</code>```

答:
When ClassA extends ClassB, you have to spy ClassA, so some mehtods will be mocked, for the rest is called the original:</p>

```<code>@Test
public void methodATest() {
    ClassA obj = Mockito.spy(ClassA.class);
    Mockito.when(obj.methodB()).thenReturn(6);
    Assert.assertEquals(10, obj.methodA());

}
</code>```

Body:
I need to write unit test in JUnit for a method, the method is inside class A and class A extends Class B. My testing method methodA() calls another methodB() which is inside class B. So how should I mock this methodB() call so that when I call methodA() from my testCase, and when It calls methodB() it gets the mocked value and gets the test case passed?
Which class should I mock, classA or Class B?

    ///logDaoImpl class extends BaseDaoImpl
    @Override
    public List<Log> LogAll(long fromIndex,long toIndex) {
    String query = "from Log ";
    QueryCondition qd = new QueryCondition();
    qd.setIgnoreCount(false);
    qd.addAndCondition("id", ">=" , "long", fromIndex);
    List<Log> result = findByCustomNamedQuery(query, qd);   //findByCustomNamedQuery method is from my extended class

   return result;
}

    public class BaseDaoImpl extends JpaDaoSupport implements BaseDao {

@PersistenceContext
EntityManager entityManager;

public List findByCustomNamedQuery(String query, QueryCondition qd) {

    if (qd.hasConditions()) {
        query += qd.getCondition() + qd.getOrderBy();
    }

    EntityManager em = getJpaTemplate().getEntityManagerFactory().createEntityManager();
    Query q = em.createQuery(query);
    String[] namedParams = StringUtils.substringsBetween(query, ":", " ");
    if (namedParams != null) {
        for (int i = 0; i < namedParams.length; i++) {
            q.setParameter(namedParams[i], qd.getParamValue(namedParams[i]));
        }
    }

    if (!qd.isIgnoreCount()) {
        q.setFirstResult(qd.start());
        q.setMaxResults(qd.count());
    }

    List result =  q.getResultList();
    em.close();
    return result;
}

//test class
  public void testLogAll() {

  List<Log>expL=new ArrayList<Log>();
    expL.add(Log);//added sample test log object from setup method
    String query = "from Log ";
    QueryCondition qd=new QueryCondition();
    qd.setIgnoreCount(false);
    qd.addAndCondition("id", ">=" , "long", 0L);
    LogDaoImpl obj=Mockito.spy(LogDaoImpl.class);
    when(obj.findByCustomNamedQuery(query,qd)).thenReturn(expL);
    List<UnbanLog> expResult = expL;
    List<UnbanLog> result = obj.LogAll(0L, 20L);
    assertEquals(expResult, result);
}

Body:
When ClassA extends ClassB, you have to spy ClassA, so some mehtods will be mocked, for the rest is called the original:

@Test
public void methodATest() {
    ClassA obj = Mockito.spy(ClassA.class);
    Mockito.when(obj.methodB()).thenReturn(6);
    Assert.assertEquals(10, obj.methodA());

}


问:
JSONP works in jQuery but not in mootools
I'm trying to convert my code to Mootools (I like the coding paradigm better).

I am doing cross-domain AJAX where I own both domains (closed network).  I am just requesting simple JSON from my server.  I get these errors in Mootools (jQuery works):

Resource interpreted as Script but transferred with MIME type text/plain.
Uncaught SyntaxError: Unexpected token :

var url = http://localhost:3000/

Server:

```<code>var http = require('http'),
    json = {"hi" : false};

http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(json));
}).listen(3000, function() {
    console.log("Server on " + 3000);
});
</code>```

jQuery:

```<code>$.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    success: function (data) {
    }
});
</code>```

Mootools:

```<code>var myRequest = new Request.JSONP({
    url: url,
    onComplete: function (data) {
        alert(JSON.stringify(data));
    }
});
myRequest.send();
</code>```

I've tried adding these headers to no avail.:

```<code>'Accept': 'application/json',
'Content-Type': 'application/json'
</code>```

This seems to be a client-side thing and not a server-side thing since it works in jQuery.

答:
What does URL look like?  jQuery figures out it's a JSONP request by adding ?callback= or ?foo= to the url.  Request.JSONP instead uses an option callbackKey.

There's no method option for JSONP (in any library), since it's just injecting a script tag.

```<code>var myRequest = new Request.JSONP({
  url: url,
  callbackKey: 'callback'
  onComplete: function(data){}
}).send();
</code>```

I have a feeling, however, you aren't using JSONP, but rather XHR with JSON.  If that's the case, use Request.JSON, not Request.JSONP.

Edit

Since it sounds, from the comments on this answer, that you're not using JSONP, just do this:

```<code>new Request.JSON({
  url: url,
  method: 'get',
  onSuccess: function (data){
    console.log(data)
  }
}).send()
</code>```

Edit 2

To change the request headers just add them as an option:

```<code>new Request.JSON({
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  },
  url: url,
  method: 'get',
  onSuccess: function (data){
    console.log(data)
  }
}).send()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to convert my code to Mootools (I like the coding paradigm better).

I am doing cross-domain AJAX where I own both domains (closed network).  I am just requesting simple JSON from my server.  I get these errors in Mootools (jQuery works):

Resource interpreted as Script but transferred with MIME type text/plain.
Uncaught SyntaxError: Unexpected token :

var url = http://localhost:3000/

Server:

var http = require('http'),
    json = {"hi" : false};

http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(json));
}).listen(3000, function() {
    console.log("Server on " + 3000);
});

jQuery:

$.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    success: function (data) {
    }
});

Mootools:

var myRequest = new Request.JSONP({
    url: url,
    onComplete: function (data) {
        alert(JSON.stringify(data));
    }
});
myRequest.send();

I've tried adding these headers to no avail.:

'Accept': 'application/json',
'Content-Type': 'application/json'

This seems to be a client-side thing and not a server-side thing since it works in jQuery.

Body:
What does URL look like?  jQuery figures out it's a JSONP request by adding ?callback= or ?foo= to the url.  Request.JSONP instead uses an option callbackKey.

There's no method option for JSONP (in any library), since it's just injecting a script tag.

var myRequest = new Request.JSONP({
  url: url,
  callbackKey: 'callback'
  onComplete: function(data){}
}).send();

I have a feeling, however, you aren't using JSONP, but rather XHR with JSON.  If that's the case, use Request.JSON, not Request.JSONP.

Edit

Since it sounds, from the comments on this answer, that you're not using JSONP, just do this:

new Request.JSON({
  url: url,
  method: 'get',
  onSuccess: function (data){
    console.log(data)
  }
}).send()

Edit 2

To change the request headers just add them as an option:

new Request.JSON({
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  },
  url: url,
  method: 'get',
  onSuccess: function (data){
    console.log(data)
  }
}).send()


问:
How to select rows in google sheets by condition
I've been researching this for a couple of hours now and have had no luck.

I am trying to search for emails in my spreadsheet that contain "@google.com" and have them all selected so that I can copy them instead of going through them 1 by 1. There are around 90K so this would be a considerable undertaking.

This is the formula that I am currently using:

```<code>=QUERY(Data!A:A,"select A where(A =@google.com)")
</code>```

All of the data is in column A.

Hope I've just made a dumb error somewhere.

Thanks in advance :)

答:
Perhaps what you might try is:</p>

```<code>=QUERY(Data!A:A,"where A contains '@google.com'")
</code>```

Body:
I've been researching this for a couple of hours now and have had no luck.

I am trying to search for emails in my spreadsheet that contain "@google.com" and have them all selected so that I can copy them instead of going through them 1 by 1. There are around 90K so this would be a considerable undertaking.

This is the formula that I am currently using:

=QUERY(Data!A:A,"select A where(A =@google.com)")

All of the data is in column A.

Hope I've just made a dumb error somewhere.

Thanks in advance :)

Body:
Perhaps what you might try is:

=QUERY(Data!A:A,"where A contains '@google.com'")


问:
The background image for my website gets out of proportion when viewed in phones and other small screen sizes
I'm having issues with re-sizing my background image in CSS to fit other smaller screens than the intended screen size of my laptop

I have already tried 'background-size: contain' and 'background-repeat : no-repeat'. still, the background image blew out of proportion. I have a set of parameters for the image, which is 'height: 100vh;'

```<code>/* with this, only a fraction of image is seen in phone */

header {
    background - image: -webkit - linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - image: linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - size: cover;
    height: 100 vh;
    background - position: center;
    background - repeat: no - repeat;
    background - attachment: fixed;
}

/* with this a grey background appears in phone screens */
header {
    background - image: -webkit - linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - image: linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - size: contain;
    height: 100 vh;

    background - position: center;
    background - repeat: no - repeat;
    background - attachment: fixed;
}
</code>```

I expect the image to fit all screen sizes without zooming in and blurring, but the results always blew out of proportion.

答:
You must use media queries for make it responsive for mobile and other devices.I can not understand your code because you not give any html file in which you apply css properties but i suggest use media queries it help you for making you page responsive for every devices.
e.g:</p>

```<code>@media_queries{
max-width:100%;
min-width:100%
}
</code>```

Body:
I'm having issues with re-sizing my background image in CSS to fit other smaller screens than the intended screen size of my laptop

I have already tried 'background-size: contain' and 'background-repeat : no-repeat'. still, the background image blew out of proportion. I have a set of parameters for the image, which is 'height: 100vh;'

/* with this, only a fraction of image is seen in phone */

header {
    background - image: -webkit - linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - image: linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - size: cover;
    height: 100 vh;
    background - position: center;
    background - repeat: no - repeat;
    background - attachment: fixed;
}

/* with this a grey background appears in phone screens */
header {
    background - image: -webkit - linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - image: linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - size: contain;
    height: 100 vh;

    background - position: center;
    background - repeat: no - repeat;
    background - attachment: fixed;
}

I expect the image to fit all screen sizes without zooming in and blurring, but the results always blew out of proportion.

Body:
You must use media queries for make it responsive for mobile and other devices.I can not understand your code because you not give any html file in which you apply css properties but i suggest use media queries it help you for making you page responsive for every devices.
e.g:

@media_queries{
max-width:100%;
min-width:100%
}


问:
Uncaught TypeError: google.script.run.doSomething is not a function
I am trying to check if the input name is already in a Google Sheet. However, I am getting this error:

Uncaught TypeError: google.script.run.doSomething is not a function.

Here is my Index.html file.

```<code><!DOCTYPE html>
<html>

<head>
    <base target="_top">
    <meta charset="UTF-8">
</head>

<body>
    <input type="text" id="meetingTitle" value=""> // Getting value here
    <button onclick="checkName()">Check if available</button> //Calling function is is causing the error.
    <p id=nameVerification><i>Click the button above to check availability.</i></p>

    <script>
        function checkName() {
            var toPass = document.getElementById("meetingTitle").value;
            prompt("toPass " + toPass);
            google.script.run.doSomething();
        }

        function checkNameCS(checkNameSSReturn) {
            if (checkNameSSReturn == "") {
                document.getElementById('nameVerification').innerHTML = "Already in Use: Please try with another name."
                document.getElementById("meetingTitle").value = "";
            } else {
                document.getElementById("meetingTitle").value = checkNameSSReturn;
                document.getElementById('nameVerification').innerHTML = "Meeting name available. Procced."
            }

        }

        function doSomething () {
            var nameGiven = document.getElementById("meetingTitle").value;
            var nameExists = false;
            var nameVerified = false;
            var name = nameGiven.toLowerCase();
            name = strip(name);
            prompt("name " + name);

            var spreadsheetId = ''; //Sheet id entered
            var rangeName = 'Sheet1';
            var values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;
            if (!values) {} else {
                for (var row = 0; row < values.length; row++) {
                    if (name == values[row][0]) {
                        nameExists = true;
                    }
                }
            }

            if (nameExists) {
                checkNameCS("");
                prompt("name2 " + " ");
                return;
            }

            nameVerified = true;
            prompt("name2 " + name);
            checkNameCS(name);
            return;
        }

        function strip(str) {
             return str.replace(/^\s+|\s+$/g, '');
        }

    </script>
</body>

</html>
</code>```

I tried debuging it with prompts but with no success. It seems like the function do something is properly called. But the code stops working aftergoogle.script.run.doSomething();.

I have looked at the documentation for successhandlers but they dont solve the issue either.

答:
How about this modification?

Issue of your script:

doSomething() of google.script.run.doSomething() is required to be Google Apps Script.

In your script, doSomething() is put in HTML (index.html), and a method for using Google Apps Script is included. When google.script.run.doSomething() is run, doSomething() cannot be found at Google Apps Script (code.gs). By this, such error occurs. And if doSomething() is run at HTML side, also an error occurs at Sheets.Spreadsheets.Values.get(), because Sheets.Spreadsheets.Values.get() is the method of Advanced Google Services with Google Apps Script.

If you put it to Google Apps Script (code.gs), Javascript which is used at the script of doSomething() is required to be modified.

Modified script:

In this modification, your script was separated to Google Apps Script (code.gs) and HTML (index.html). var nameGiven = document.getElementById("meetingTitle").value; and checkNameCS(name); are used in index.html.

By the way, before you run this script, please enable Sheets API at Advanced Google Services.

Google Apps Script: code.gs

```<code>function strip(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

function doSomething (nameGiven) {
  var nameExists = false;
  var nameVerified = false;
  var name = nameGiven.toLowerCase();
  name = strip(name);

  var spreadsheetId = '###'; //Sheet id entered
  var rangeName = 'Sheet1';
  var values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;
  if (values) {
      for (var row = 0; row < values.length; row++) {
          if (name == values[row][0]) {
              nameExists = true;
          }
      }
  }

  if (nameExists) {
      return "";
  }

  nameVerified = true;
  return name;
}
</code>```

HTML: index.html

```<code><!DOCTYPE html>
<html>

<head>
    <base target="_top">
    <meta charset="UTF-8">
</head>

<body>
    <input type="text" id="meetingTitle" value="">
    <button onclick="checkName()">Check if available</button>
    <p id=nameVerification><i>Click the button above to check availability.</i></p>

    <script>
        function checkName() {
            var toPass = document.getElementById("meetingTitle").value;
            prompt("toPass " + toPass);
            var nameGiven = document.getElementById("meetingTitle").value; // Added
            google.script.run.withSuccessHandler(checkNameCS).doSomething(nameGiven); // Modified
        }

        function checkNameCS(checkNameSSReturn) {
          console.log(checkNameSSReturn)
            if (checkNameSSReturn == "") {
                document.getElementById('nameVerification').innerHTML = "Already in Use: Please try with another name."
                document.getElementById("meetingTitle").value = "";
            } else {
                document.getElementById("meetingTitle").value = checkNameSSReturn;
                document.getElementById('nameVerification').innerHTML = "Meeting name available. Procced."
            }
        }
    </script>
</body>

</html>
</code>```

Reference:

Class google.script.run

Body:
I am trying to check if the input name is already in a Google Sheet. However, I am getting this error:

Uncaught TypeError: google.script.run.doSomething is not a function.

Here is my Index.html file.

<!DOCTYPE html>

    <base target="_top">
    <meta charset="UTF-8">

    <input type="text" id="meetingTitle" value=""> // Getting value here
    <button onclick="checkName()">Check if available</button> //Calling function is is causing the error.

Click the button above to check availability.

I tried debuging it with prompts but with no success. It seems like the function do something is properly called. But the code stops working aftergoogle.script.run.doSomething();.

I have looked at the documentation for successhandlers but they dont solve the issue either.

Body:
How about this modification?

Issue of your script:

doSomething() of google.script.run.doSomething() is required to be Google Apps Script.

In your script, doSomething() is put in HTML (index.html), and a method for using Google Apps Script is included. When google.script.run.doSomething() is run, doSomething() cannot be found at Google Apps Script (code.gs). By this, such error occurs. And if doSomething() is run at HTML side, also an error occurs at Sheets.Spreadsheets.Values.get(), because Sheets.Spreadsheets.Values.get() is the method of Advanced Google Services with Google Apps Script.

If you put it to Google Apps Script (code.gs), Javascript which is used at the script of doSomething() is required to be modified.

Modified script:

In this modification, your script was separated to Google Apps Script (code.gs) and HTML (index.html). var nameGiven = document.getElementById("meetingTitle").value; and checkNameCS(name); are used in index.html.

By the way, before you run this script, please enable Sheets API at Advanced Google Services.

Google Apps Script: code.gs

function strip(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

function doSomething (nameGiven) {
  var nameExists = false;
  var nameVerified = false;
  var name = nameGiven.toLowerCase();
  name = strip(name);

  var spreadsheetId = '###'; //Sheet id entered
  var rangeName = 'Sheet1';
  var values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;
  if (values) {
      for (var row = 0; row < values.length; row++) {
          if (name == values[row][0]) {
              nameExists = true;
          }
      }
  }

  if (nameExists) {
      return "";
  }

  nameVerified = true;
  return name;
}

HTML: index.html

<!DOCTYPE html>
<html>

<head>
    <base target="_top">
    <meta charset="UTF-8">
</head>

<body>
    <input type="text" id="meetingTitle" value="">
    <button onclick="checkName()">Check if available</button>
    <p id=nameVerification><i>Click the button above to check availability.</i></p>

    <script>
        function checkName() {
            var toPass = document.getElementById("meetingTitle").value;
            prompt("toPass " + toPass);
            var nameGiven = document.getElementById("meetingTitle").value; // Added
            google.script.run.withSuccessHandler(checkNameCS).doSomething(nameGiven); // Modified
        }

        function checkNameCS(checkNameSSReturn) {
          console.log(checkNameSSReturn)
            if (checkNameSSReturn == "") {
                document.getElementById('nameVerification').innerHTML = "Already in Use: Please try with another name."
                document.getElementById("meetingTitle").value = "";
            } else {
                document.getElementById("meetingTitle").value = checkNameSSReturn;
                document.getElementById('nameVerification').innerHTML = "Meeting name available. Procced."
            }
        }
    </script>
</body>

</html>

Reference:

Class google.script.run


问:
How can I make a ring in JavaFX (fxml)
I need to make a ring in JavaFX using fxml.  It will be circling an item on an image beneath it.  I can make a circle, but it seems to be required to have a fill.  I can adjust the opacity, but that adjusts the opacity of both the fill and the circle.

I don't have image editing software at work (and I can't just install gimp) so I can't create an image and use an ImageView.  Paint won't let you save images without backgrounds.

It seems like such a simple task to create a circle without a fill.  Am I missing something?

Thanks

答:
Or, following the same idea as Mansueli, use this programmatically:</p>

```<code>circle.setFill(new Color(0,0,0,0));
</code>```

Title: How can I make a ring in JavaFX (fxml)

Body:
Or, following the same idea as Mansueli, use this programmatically:

circle.setFill(new Color(0,0,0,0));


问:
Android save state of listview with multipleChoice
I have a listview that contains some values with the multipleChoice enabled in my xml file.
I want to be able to save what has been checked by the user when the app is exited, then re-check what they have selected upon opening again. My code works for a radio group, but I can't seem to get it to work for this.

EDIT: Got this working by using some for loop trickery at the end.

答:
as @BGS wrote, SharedPreference would solve your problem.
Check out this post: MultiChoice Preference Widget for Android.

Here the values of the checkboxes are stored in a [special-separator]-separated string, and passed to the caller as a String array containing the selected values.

I'm using this approach, and it works great so far.


问:
how to get data from RESTful API using WIQL but it seems like not working
I can't figure out what is the problem with the code for a few days..
Can you guys have a look and say what I have done wrong?
Organizaiton name and project name are put correct in the code.

This is the error message shown on PowerShell ISE:

Invoke-RestMethod : Cannot send a content-body with this verb-type. At
  \Project\DevopTask.ps1:47 char:17
  + ... $response = Invoke-RestMethod -Uri $url -headers $headers -Method Get ...
  +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [Invoke-RestMethod], ProtocolViolationException
      + FullyQualifiedErrorId : System.Net.ProtocolViolationException,Microsoft.PowerShell.Commands.InvokeRestMet
  hodCommand

```<code>$collectionuri = $Env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI
$token = $Env:SYSTEM_ACCESSTOKEN # need to configure build to allow passing OAuth tokens

$basicAuth = "{0}:{1}" -f '', 'token~~fdsafdsa'
$basicAuth = [System.Text.Encoding]::UTF8.GetBytes(":$($basicAuth)")
$basicAuth = [System.Convert]::ToBase64String($basicAuth)
$headers = @{Authorization=("Basic {0}"-f $basicAuth)}

$WorkItemType = 'Recently updated'

$url = $collectionuri + 'https://dev.azure.com/{OrganizationName}/{ProjectName}/_apis/wit/queries/test/wiql?api-version=5.0'

$WIQL_query = "select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.IterationPath] from WorkItems where [System.TeamProject] = @project and [System.Id] in (@recentProjectActivity) and not [System.State] in ('Closed', 'Inactive', 'Completed') and [System.IterationPath] Under 'Sprint number two' order by [System.ChangedDate] desc"
$body = @{ query = $WIQL_query }
$bodyJson=@($body) | ConvertTo-Json

$response = Invoke-RestMethod -Uri $url -headers $headers -Method Get -ContentType "application/json" -Body $bodyJson

$workitems = $response.workItems
Write-Host "Found" $workitems.Count "work items of type:" $WorkItemType
</code>```

答:
You just need to change the -Method (in the Invoke-RestMethod) from Get to Post.

You try to get Work Items with Work Item Query Language, in this Rest API you need to pass the WIQL in the body so the -Method should be Post.

See the docs here.

Body:
I can't figure out what is the problem with the code for a few days..
Can you guys have a look and say what I have done wrong?
Organizaiton name and project name are put correct in the code.

This is the error message shown on PowerShell ISE:

Invoke-RestMethod : Cannot send a content-body with this verb-type. At
  \Project\DevopTask.ps1:47 char:17
  + ... $response = Invoke-RestMethod -Uri $url -headers $headers -Method Get ...
  +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [Invoke-RestMethod], ProtocolViolationException
      + FullyQualifiedErrorId : System.Net.ProtocolViolationException,Microsoft.PowerShell.Commands.InvokeRestMet
  hodCommand

$collectionuri = $Env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI
$token = $Env:SYSTEM_ACCESSTOKEN # need to configure build to allow passing OAuth tokens

$basicAuth = "{0}:{1}" -f '', 'token~~fdsafdsa'
$basicAuth = [System.Text.Encoding]::UTF8.GetBytes(":$($basicAuth)")
$basicAuth = [System.Convert]::ToBase64String($basicAuth)
$headers = @{Authorization=("Basic {0}"-f $basicAuth)}

$WorkItemType = 'Recently updated'

$url = $collectionuri + 'https://dev.azure.com/{OrganizationName}/{ProjectName}/_apis/wit/queries/test/wiql?api-version=5.0'

$WIQL_query = "select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.IterationPath] from WorkItems where [System.TeamProject] = @project and [System.Id] in (@recentProjectActivity) and not [System.State] in ('Closed', 'Inactive', 'Completed') and [System.IterationPath] Under 'Sprint number two' order by [System.ChangedDate] desc"
$body = @{ query = $WIQL_query }
$bodyJson=@($body) | ConvertTo-Json

$response = Invoke-RestMethod -Uri $url -headers $headers -Method Get -ContentType "application/json" -Body $bodyJson

$workitems = $response.workItems
Write-Host "Found" $workitems.Count "work items of type:" $WorkItemType


问:
How to extend a class when one of the optional argument is not a member variable and it is required?
Here is the code. We have a TabController (from sdk), I am extending this TabController class:

class TabController extends ChangeNotifier {
   int length;
   TabController({ int initialIndex = 0,
      @required this.length,
      @required TickerProvider vSync
   }):assert(length != null),
       assert(vSync != null);

} //end of TabController

class AppTabController extends TabController {

    AppTabController(int mInitialIndex,
       int mLength,
      TickerProvider mVsync):super(length: mLength, mVsync: vsync ){}

}
```

Now this AppTabController's constructor is giving syntax error. Seems like I can't extend TabController class because:

vsync is not a member variable of TabController

There are some assertions in TabController constructor itself due to which if the required args are not passed then it will crash.

These are the compile errors:

error: The named parameter vsync isn't defined

答:
this.length requires member variable.

@required requires assert

use : instead of =

make a class extended TickerProvider because it is abstract class. I made myTickerProvider as the example.

```<code>AppTabController appTabController = new AppTabController(mLength:10, mVsync:new myTickerProvider());

class TabController extends ChangeNotifier {
  int length;
  TabController({
    int initialIndex = 0,
    @required this.length,
    @required TickerProvider vSync
  }) : assert(length != null),
       assert(vSync != null);
} //end of TabController

class AppTabController extends TabController {

  AppTabController({int mInitialIndex,
      int mLength,
      TickerProvider mVsync}):super(length: mLength, vSync: mVsync);
}

class myTickerProvider extends TickerProvider{
  @override
  Ticker createTicker(onTick) {
    // TODO: implement createTicker
    return null;
  }
}
</code>```

Body:
Here is the code. We have a TabController (from sdk), I am extending this TabController class:

class TabController extends ChangeNotifier {
   int length;
   TabController({ int initialIndex = 0,
      @required this.length,
      @required TickerProvider vSync
   }):assert(length != null),
       assert(vSync != null);

} //end of TabController

class AppTabController extends TabController {

    AppTabController(int mInitialIndex,
       int mLength,
      TickerProvider mVsync):super(length: mLength, mVsync: vsync ){}

}

Now this AppTabController's constructor is giving syntax error. Seems like I can't extend TabController class because:

vsync is not a member variable of TabController

There are some assertions in TabController constructor itself due to which if the required args are not passed then it will crash.

These are the compile errors:

error: The named parameter vsync isn't defined

Body:
this.length requires member variable.

@required requires assert

use : instead of =

make a class extended TickerProvider because it is abstract class. I made myTickerProvider as the example.

AppTabController appTabController = new AppTabController(mLength:10, mVsync:new myTickerProvider());

class TabController extends ChangeNotifier {
  int length;
  TabController({
    int initialIndex = 0,
    @required this.length,
    @required TickerProvider vSync
  }) : assert(length != null),
       assert(vSync != null);
} //end of TabController

class AppTabController extends TabController {

  AppTabController({int mInitialIndex,
      int mLength,
      TickerProvider mVsync}):super(length: mLength, vSync: mVsync);
}

class myTickerProvider extends TickerProvider{
  @override
  Ticker createTicker(onTick) {
    // TODO: implement createTicker
    return null;
  }
}


问:
How to use custom alert in React Native?
I've created a custom alert as a component in React Native. I used Modal to create this custom alert. My problem is, how to use it? Instead of using Alert.alert in React Native, I want to display my own alert.

Here is my Custom Alert Modal.

```<code>import React, { Component } from 'react';
import { Text, View } from 'react-native';
import Modal from 'react-native-modal';

import styles from './style';
import Button from '../../components/Button';

export default class CustomAlert extends Component {

  renderModalContent = () => (
    <View style={styles.content}>
      <Text style={styles.contentTitle}>{this.props.title}</Text>
      <Text style={styles.contentInfo}>{this.props.content}</Text>
      <View style={styles.buttonContainer}>
        <Button
          color={this.props.buttonColor}
          text={this.props.buttonText}
          onPress={this.props.buttonOnPress}
        />
      </View>
    </View>
  );

  render() {
    return (
      <View style={styles.container}>
        <Modal
          isVisible={this.props.isVisible}
          backdropColor="#000000"
          backdropOpacity={0.9}
          animationIn="zoomInDown"
          animationOut="zoomOutUp"
          animationInTiming={600}
          animationOutTiming={600}
          backdropTransitionInTiming={600}
          backdropTransitionOutTiming={600}
        >
          {this.renderModalContent()}
        </Modal>
      </View>
    );
  }
}
</code>```

This is how I want to use it. I want to display this alert through a function. That means when function catches up with an error, I want to show my custom alert.

```<code>myFunction()
  .then(() => // do something)
  .catch(() => // show my custom alert);
</code>```

Can you help me please to solve this problem?

答:
set isVisible true in your catch block.</p>

```<code>myFunction()
 .then(() => // do something)
 .catch((e) => this.setState({ isVisible: true }))
</code>```

Body:
I've created a custom alert as a component in React Native. I used Modal to create this custom alert. My problem is, how to use it? Instead of using Alert.alert in React Native, I want to display my own alert.

Here is my Custom Alert Modal.

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import Modal from 'react-native-modal';

import styles from './style';
import Button from '../../components/Button';

export default class CustomAlert extends Component {

  renderModalContent = () => (
    <View style={styles.content}>
      <Text style={styles.contentTitle}>{this.props.title}</Text>
      <Text style={styles.contentInfo}>{this.props.content}</Text>
      <View style={styles.buttonContainer}>
        <Button
          color={this.props.buttonColor}
          text={this.props.buttonText}
          onPress={this.props.buttonOnPress}
        />
      </View>
    </View>
  );

  render() {
    return (
      <View style={styles.container}>
        <Modal
          isVisible={this.props.isVisible}
          backdropColor="#000000"
          backdropOpacity={0.9}
          animationIn="zoomInDown"
          animationOut="zoomOutUp"
          animationInTiming={600}
          animationOutTiming={600}
          backdropTransitionInTiming={600}
          backdropTransitionOutTiming={600}
        >
          {this.renderModalContent()}
        </Modal>
      </View>
    );
  }
}

This is how I want to use it. I want to display this alert through a function. That means when function catches up with an error, I want to show my custom alert.

myFunction()
  .then(() => // do something)
  .catch(() => // show my custom alert);

Can you help me please to solve this problem?

Body:
set isVisible true in your catch block.

myFunction()
 .then(() => // do something)
 .catch((e) => this.setState({ isVisible: true }))


问:
How to save images in a folder with for loop?
First, I have an issue with saving up every resized file with the same name to the same folder? Second, while running I can't understand if m t code works properly. Please, could you check if I am doing the resizing properly?Can't find a mistake in my code:</p>

```<code>import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
for image in images:
    with open(image,"rb") as file:
        img = Image.open(file)
        imgResult = img.resize((800,800), resample = Image.BILINEAR)
      imgResult.save('"C:/Users/marialavrovskaa/Desktop/Images/file_%d.jpg"', 'JPEG')
        print("All good")
</code>```

答:
If you want to give the images a name with a consecutive number than you've to concatenate the file name and a counter:

image_no = 1
for image in images:

    # [...]

    name = 'C:/Users/marialavrovskaa/Desktop/Images/file_' + str(image_no) + '.jpg'
    imgResult.save(name, 'JPEG')
    image_no += 1
```

<p>Since the format of the images is <em>PNG</em> and they should be stored as <code>JPEG</code>, the format has to be convert from <em>RGBA</em> to <em>RGB</em>, by <code>.convert('RGB')</code>. Note, storing a <code>RGBA</code> image to 'JPGE' would cause an error:</p>

<pre class="lang-py prettyprint-override"><code>import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
image_no = 1
for image in images:
    with open(image,"rb") as file:
        img = Image.open(file)
        imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')
        name = 'C:/Users/marialavrovskaa/Desktop/Images/file_' + str(image_no) + '.jpg'
        imgResult.save(name, 'JPEG')
        image_no += 1
        print("All good")
</code>```

By the way, if the file name should by kept and the image just should be stored to a file with a different extension, then then extension can be split form the file by .splitext:

```<code>import os
</code>```

imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')
name = os.path.splitext(image)[0] + '.jpg'
imgResult.save(name, 'JPEG')
```

<hr>

<p>If you wan to store the fiel to a different path, with a different extension, then you've to extract the fiel name from the path.</p>

<p>See <code>os.path</code>. Split the path from the file name and extension by <code>os.path.split(path)</code>, which returns a tuple of path and name.</p>

<p>e.g. </p>

<pre class="lang-py prettyprint-override"><code>>>> import os
>>> os.path.split('c:/mydir/myfile.ext')
('c:/mydir', 'myfile.ext')
</code>```

The split the file name and the extension by os.path.splitext(path):

>>> os.path.splitext('myfile.ext')
('myfile', '.ext')
```

<p>Applied to your code this means, where <code>file</code> is the path, name and extension of the source image file:</p>

<pre class="lang-py prettyprint-override"><code>import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
image_no = 1
for image in images:
    with open(image,"rb") as file:
        img = Image.open(file)
        imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')

        image_path_and_name = os.path.split(file)
        image_name_and_ext = os.path.splitext(image_path_and_name[1])
        name = image_name_and_ext[0] + '.png'
        file_path = os.path.join(path, name)

        imgResult.save(file_path , 'JPEG')
        image_no += 1
        print("All good")
</code>```

Body:
First, I have an issue with saving up every resized file with the same name to the same folder? Second, while running I can't understand if m t code works properly. Please, could you check if I am doing the resizing properly?Can't find a mistake in my code:

import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
for image in images:
    with open(image,"rb") as file:
        img = Image.open(file)
        imgResult = img.resize((800,800), resample = Image.BILINEAR)
      imgResult.save('"C:/Users/marialavrovskaa/Desktop/Images/file_%d.jpg"', 'JPEG')
        print("All good")

Body:
If you want to give the images a name with a consecutive number than you've to concatenate the file name and a counter:

image_no = 1
for image in images:

    # [...]

    name = 'C:/Users/marialavrovskaa/Desktop/Images/file_' + str(image_no) + '.jpg'
    imgResult.save(name, 'JPEG')
    image_no += 1

Since the format of the images is PNG and they should be stored as JPEG, the format has to be convert from RGBA to RGB, by .convert('RGB'). Note, storing a RGBA image to 'JPGE' would cause an error:

import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
image_no = 1
for image in images:
    with open(image,"rb") as file:
        img = Image.open(file)
        imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')
        name = 'C:/Users/marialavrovskaa/Desktop/Images/file_' + str(image_no) + '.jpg'
        imgResult.save(name, 'JPEG')
        image_no += 1
        print("All good")

By the way, if the file name should by kept and the image just should be stored to a file with a different extension, then then extension can be split form the file by .splitext:

import os

imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')
name = os.path.splitext(image)[0] + '.jpg'
imgResult.save(name, 'JPEG')

If you wan to store the fiel to a different path, with a different extension, then you've to extract the fiel name from the path.

See os.path. Split the path from the file name and extension by os.path.split(path), which returns a tuple of path and name.

e.g.

>>> import os
>>> os.path.split('c:/mydir/myfile.ext')
('c:/mydir', 'myfile.ext')

The split the file name and the extension by os.path.splitext(path):

>>> os.path.splitext('myfile.ext')
('myfile', '.ext')

Applied to your code this means, where file is the path, name and extension of the source image file:

import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
image_no = 1
for image in images:
    with open(image,"rb") as file:
        img = Image.open(file)
        imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')

        image_path_and_name = os.path.split(file)
        image_name_and_ext = os.path.splitext(image_path_and_name[1])
        name = image_name_and_ext[0] + '.png'
        file_path = os.path.join(path, name)

        imgResult.save(file_path , 'JPEG')
        image_no += 1
        print("All good")


问:
What is more efficient? Using pow to square or just multiply it with itself?
What of these two methods is in C more efficient? And how about:

```<code>pow(x,3)
</code>```

vs.

```<code>x*x*x // etc?
</code>```

答:
I have been busy with a similar problem, and I'm quite puzzled by the results. I was calculating x⁻³/² for Newtonian gravitation  in an n-bodies situation (acceleration undergone from another body of mass M situated at a distance vector d) : a = M G d*(d²)⁻³/² (where d² is the dot (scalar) product of d by itself) , and I thought calculating M*G*pow(d2, -1.5) would be simpler than M*G/d2/sqrt(d2)

The trick is that it is true for small systems, but as  systems grow in size, M*G/d2/sqrt(d2) becomes more efficient and I don't understand why the size of the system impacts this result, because repeating the operation on different data does not. It is as if there were possible optimizations as the system grow, but which are not possible with pow

Body:
What of these two methods is in C more efficient? And how about:

pow(x,3)

vs.

x*x*x // etc?


问:
Load More functionality using Spring JPA
I would like to enable a functionality of 'Loading more' in my website.
Since i'm fetching my data from remote DB using Spring JPA, I was wondering how would I implement such feature in Spring?

Basically, what I want to do, is to load only 100 records on the first REST call. And if the user clicks 'Load More', then I perform a new call for another 100 records from the last index I stopped (means records 101-200), and so on.

I can send start and end index via HTTP POST if needed. this is my repository:

```<code>@Repository
public interface IStatusRepository extends CrudRepository<StatusDAO,String> {

    List<StatusDAO> getStatusByIdAndFqhnIn(String id, List<String> filteredHostList);

}
</code>```

Do you have any suggestions?

答:
You can use Pageable or PagingAndSortingRepository<T, ID> to fulfill your requirements.
By having it extend PagingAndSortingRepository, we get findAll(Pageable pageable) and findAll(Sort sort) methods for paging and sorting.

Once we have our repository extending from PagingAndSortingRepository, we just need to:

Create or obtain a PageRequest object, which is an implementation of
the Pageable interface

Pass the PageRequest object as an argument to the repository method
we intend to use

Example:

```<code>public interface ProductRepository extends PagingAndSortingRepository<Product, Integer> {

    List<Product> findAllByPrice(double price, Pageable pageable);
}
</code>```

```<code>Pageable firstPageWithTwoElements = PageRequest.of(0, 2);

Pageable secondPageWithFiveElements = PageRequest.of(1, 5);
</code>```

```<code>Page<Product> allProducts = productRepository.findAll(firstPageWithTwoElements);

List<Product> allTenDollarProducts =
  productRepository.findAllByPrice(10, secondPageWithFiveElements);
</code>```

Paging and Sorting Doc Refer 1 Refer 2

Body:
I would like to enable a functionality of 'Loading more' in my website.
Since i'm fetching my data from remote DB using Spring JPA, I was wondering how would I implement such feature in Spring?

Basically, what I want to do, is to load only 100 records on the first REST call. And if the user clicks 'Load More', then I perform a new call for another 100 records from the last index I stopped (means records 101-200), and so on.

I can send start and end index via HTTP POST if needed. this is my repository:

@Repository
public interface IStatusRepository extends CrudRepository<StatusDAO,String> {

    List<StatusDAO> getStatusByIdAndFqhnIn(String id, List<String> filteredHostList);

}

Do you have any suggestions?

Body:
You can use Pageable or PagingAndSortingRepository<T, ID> to fulfill your requirements.
By having it extend PagingAndSortingRepository, we get findAll(Pageable pageable) and findAll(Sort sort) methods for paging and sorting.

Once we have our repository extending from PagingAndSortingRepository, we just need to:

Create or obtain a PageRequest object, which is an implementation of
the Pageable interface

Pass the PageRequest object as an argument to the repository method
we intend to use

Example:

public interface ProductRepository extends PagingAndSortingRepository<Product, Integer> {

    List<Product> findAllByPrice(double price, Pageable pageable);
}

Pageable firstPageWithTwoElements = PageRequest.of(0, 2);

Pageable secondPageWithFiveElements = PageRequest.of(1, 5);

Page<Product> allProducts = productRepository.findAll(firstPageWithTwoElements);

List<Product> allTenDollarProducts =
  productRepository.findAllByPrice(10, secondPageWithFiveElements);

Paging and Sorting Doc Refer 1 Refer 2


问:
Unity - Vertex light ignored by static objects (lightmapped)
Vertex lights work fine on dynamic objects, but the second I make them static and bake lightmaps they're ignored.

I've tried changing to different "lightmodes" within the shader, but none has worked. Lightmode "ForwardBase" seems to really mess up, even though I would assume its the one to use given its description on https://docs.unity3d.com/Manual/SL-PassTags.html

Any suggestions would be very appreciated :)

答:
My understanding of the question at hand

As I understand, when you bake a lightmap, the only light source that will change the light of the baked objects is a pixel light. But you would like to make it work with a vertex light.

I'm still not entirely sure whether you mean that the light simply won't bake into the baked map in the first place, or whether it cannot affect the light level of the object after it has been baked.

In any case, I did some searching.

Possible solution/explanation 1

When I searched I came across this tool and description.

https://assetstore.unity.com/packages/vfx/shaders/vertex-lit-shader-baked-shadows-realtime-light-75977

By default, using Unity’s built-in shader Mobile/VertexLit lighting
  works only as either baked or realtime but you cannot display a
  realtime light on a baked surface. This shader allows a baked surface
  to also receive realtime lighting.

Note that the tool is free.

Possible solution/explanation 2

I also came across this tutorial: https://catlikecoding.com/unity/tutorials/rendering/part-16/

Where the author writes

When lightmaps are used, Unity will never include vertex lights. Their
  keywords are mutually exclusive. So we don't need a variant with both
  VERTEXLIGHT_ON and LIGHTMAP_ON at the same time.

Lastly please note that these solutions seem to be developed at earlier versions of Unity. Newer solutions more appropriate may exist.

Hope this helps you.


问:
Why the transaction insert 2 values when fails the first one?
I have this Table:

```<code>TableAB
{
    IDTableA;
    IDTableB;
}
</code>```

I have one row in the table, (1,2). Now I want to insert some others values, and I want to do it in a transaction. I use this:

```<code>begin
insert into TableAB (IDTAbleA, IDTAbleB) VALUES(1,2);
insert into TableAB (IDTAbleA, IDTAbleB) VALUES(1,3);
insert into TableAB (IDTAbleA, IDTAbleB) VALUES(1,3);
commit
</code>```

I get an error of integrity in the first insert, but the second and third insert, insert the values in the table.

How I am using a transaction and fails the first one, why does it insert the other two rows? I thought inside a transaction, if somethings fails, all is aborted. Then in this case, which is the difference to use the transaction and don't use it?

Thanks.

答:
Try this:

```<code>SET XACT_ABORT ON
BEGIN TRANSACTION;

BEGIN TRY

    INSERT INTO TableAB(IDTAbleA,IDTAbleB)VALUES(1, 2);
    INSERT INTO TableAB(IDTAbleA,IDTAbleB)VALUES(1, 3);
    INSERT INTO TableAB(IDTAbleA,IDTAbleB)VALUES(1, 3);

    COMMIT TRANSACTION;
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
    BEGIN

        IF (XACT_STATE()) = -1
        BEGIN
            ROLLBACK TRANSACTION;
            THROW;
        END
        ELSE IF (XACT_STATE()) = 1
        BEGIN
            COMMIT TRANSACTION;
        END;

    END;

END CATCH;
</code>```

Read more:

XACT_ABORT: https://learn.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql?view=sql-server-2017

XACT_STATE(): https://learn.microsoft.com/en-us/sql/t-sql/functions/xact-state-transact-sql?view=sql-server-2017

@@TRANCOUNT: https://learn.microsoft.com/en-us/sql/t-sql/functions/trancount-transact-sql?view=sql-server-2017

Body:
I have this Table:

TableAB
{
    IDTableA;
    IDTableB;
}

I have one row in the table, (1,2). Now I want to insert some others values, and I want to do it in a transaction. I use this:

begin
insert into TableAB (IDTAbleA, IDTAbleB) VALUES(1,2);
insert into TableAB (IDTAbleA, IDTAbleB) VALUES(1,3);
insert into TableAB (IDTAbleA, IDTAbleB) VALUES(1,3);
commit

I get an error of integrity in the first insert, but the second and third insert, insert the values in the table.

How I am using a transaction and fails the first one, why does it insert the other two rows? I thought inside a transaction, if somethings fails, all is aborted. Then in this case, which is the difference to use the transaction and don't use it?

Thanks.

Body:
Try this:

SET XACT_ABORT ON
BEGIN TRANSACTION;

BEGIN TRY

    INSERT INTO TableAB(IDTAbleA,IDTAbleB)VALUES(1, 2);
    INSERT INTO TableAB(IDTAbleA,IDTAbleB)VALUES(1, 3);
    INSERT INTO TableAB(IDTAbleA,IDTAbleB)VALUES(1, 3);

    COMMIT TRANSACTION;
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
    BEGIN

        IF (XACT_STATE()) = -1
        BEGIN
            ROLLBACK TRANSACTION;
            THROW;
        END
        ELSE IF (XACT_STATE()) = 1
        BEGIN
            COMMIT TRANSACTION;
        END;

    END;

END CATCH;

Read more:

XACT_ABORT: https://learn.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql?view=sql-server-2017

XACT_STATE(): https://learn.microsoft.com/en-us/sql/t-sql/functions/xact-state-transact-sql?view=sql-server-2017

@@TRANCOUNT: https://learn.microsoft.com/en-us/sql/t-sql/functions/trancount-transact-sql?view=sql-server-2017


问:
PHP array sort with forced the first row
How to sort an array at PHP to force selected row as a first ?

My array is

```<code>array[]=array(id=>'a', content=>'lemon');
array[]=array(id=>'b', content=>'apple');
array[]=array(id=>'c', content=>'banana');
array[]=array(id=>'d', content=>'cherry');
</code>```

How to sort the array to force

```<code>array[]=array(id=>'b', content=>'apple');
</code>```

as a first row and doesn't matter the rest (apple is the key).

And in other example turn sort to get

```<code>array[]=array(id=>'d', content=>'cherry');
</code>```

as a first row and doesn't matter the rest (cherry is the key).

答:
There are 2 ways I can think of doing this.  The first is as Ultimater in the comments suggest to extract the matching row, then sort and then add the row back in...

```<code>$first = 'apple';
$array = [];
$array[]=array('id'=>'a', 'content'=>'lemon');
$array[]=array('id'=>'b', 'content'=>'apple');
$array[]=array('id'=>'c', 'content'=>'banana');
$array[]=array('id'=>'d', 'content'=>'chery');
$firstElement = array_search($first, array_column($array, "content"));
$row = $array[$firstElement];
unset($array[$firstElement]);
sort($array);
array_unshift($array, $row);
print_r($array);
</code>```

The second is to use usort and add specific clauses in that if the key matches the row you want first, then it will always force it to the first row...

```<code>$first = 'apple';
usort($array, function ($a, $b) use ($first){
    if ( $a['content'] == $first)   {
        return -1;
    }
    if ( $b['content'] == $first)   {
        return 1;
    }
    return $a <=> $b;
});
print_r($array);
</code>```

(I've used <=> in this which is PHP 7+, there are alternatives if you need to use PHP 5).

If as your comment suggests that there is no need to sort the rest of the data, then the first set of code minus the sort() should do.

Body:
How to sort an array at PHP to force selected row as a first ?

My array is

array[]=array(id=>'a', content=>'lemon');
array[]=array(id=>'b', content=>'apple');
array[]=array(id=>'c', content=>'banana');
array[]=array(id=>'d', content=>'cherry');

How to sort the array to force

array[]=array(id=>'b', content=>'apple');

as a first row and doesn't matter the rest (apple is the key).

And in other example turn sort to get

array[]=array(id=>'d', content=>'cherry');

as a first row and doesn't matter the rest (cherry is the key).

Body:
There are 2 ways I can think of doing this.  The first is as Ultimater in the comments suggest to extract the matching row, then sort and then add the row back in...

$first = 'apple';
$array = [];
$array[]=array('id'=>'a', 'content'=>'lemon');
$array[]=array('id'=>'b', 'content'=>'apple');
$array[]=array('id'=>'c', 'content'=>'banana');
$array[]=array('id'=>'d', 'content'=>'chery');
$firstElement = array_search($first, array_column($array, "content"));
$row = $array[$firstElement];
unset($array[$firstElement]);
sort($array);
array_unshift($array, $row);
print_r($array);

The second is to use usort and add specific clauses in that if the key matches the row you want first, then it will always force it to the first row...

$first = 'apple';
usort($array, function ($a, $b) use ($first){
    if ( $a['content'] == $first)   {
        return -1;
    }
    if ( $b['content'] == $first)   {
        return 1;
    }
    return $a <=> $b;
});
print_r($array);

(I've used <=> in this which is PHP 7+, there are alternatives if you need to use PHP 5).

If as your comment suggests that there is no need to sort the rest of the data, then the first set of code minus the sort() should do.


问:
Create a polygon clip path css and background in nativescript
Need to create a same that:

The polygon (creates with clip path css) and background. Need polygon with a circle on four corners.

答:
As given in the docs, you could use clippy to calculate clip-path and use it in your CSS.

```<code>.clip {
 clip-path: polygon(24% 29%, 63% 7%, 83% 79%, 33% 71%);
}
</code>```

Body:
As given in the docs, you could use clippy to calculate clip-path and use it in your CSS.

.clip {
 clip-path: polygon(24% 29%, 63% 7%, 83% 79%, 33% 71%);
}


问:
Stop a js function from loading on initial page load
I am trying to stop a JS function from loading every time a page is loaded, i wanted it to work only when a button is clicked. I have tried using onclick and .addEventListener.On using onclick, the output data displays before clicking the load data button and on using .addEventListener no data loads even on clicking the button. Any help would be appreciated, Thank you!</p>

```<code><html>
<head>
    <title> Monitoring</title>
</head>
<body>
<div id="output"></div>
<script src="./lib/mam.web.min.js"></script>
<script>

    const TRYTE_ALPHABET = 'SFRRJJVGGYJI';

    const asciiToTrytes = (input) => {
      let trytes = '';
      for (let i = 0; i < input.length; i++) {
        var dec = input[i].charCodeAt(0);
        trytes += TRYTE_ALPHABET[dec % 27];
        trytes += TRYTE_ALPHABET[(dec - dec % 27) / 27];
      }
      return trytes;
    };

    const trytesToAscii = (trytes) => {
      let ascii = '';
      for (let i = 0; i < trytes.length; i += 2) {
        ascii += String.fromCharCode(TRYTE_ALPHABET.indexOf(trytes[i]) + TRYTE_ALPHABET.indexOf(trytes[i + 1]) * 27);
      }
      return ascii;
    };
    const outputHtml = document.querySelector("#output");
          const mode = 'public'
      const provider = ''

      const mamExplorerLink = ``

      // Initialise MAM State
      let mamState = Mam.init(provider)

      // Publish to tangle
      const publish = async packet => {
//      alert("coming into publish");
        // Create MAM Payload - STRING OF TRYTES
        const trytes = asciiToTrytes(JSON.stringify(packet))
        const message = Mam.create(mamState, trytes)
//      alert("p2");
        // Save new mamState
        mamState = message.state
//      alert("p3");
        // Attach the payload
        await Mam.attach(message.payload, message.address, 3, 9)
//        alert("p4");
        outputHtml.innerHTML += `Published: ${packet}<br/>`;
//      alert(message.root);
        return message.root
      }

      const publishAll = async () => {
//    alert("Yes 1.3");
        const root = await publish('ALICE')

        return root
      }

      // Callback used to pass data out of the fetch
      const logData = data => outputHtml.innerHTML += `Fetched and parsed ${JSON.parse(trytesToAscii(data))}<br/>`;
 (async function GKpublishAll(){
     const root = await publishAll();
    //  alert(root);
     outputHtml.innerHTML += `${root}`;

    })();

  </script>
  <form>
  Publish message :
  <input type="submit" onclick="GKpublishAll()">
</form>
</body>

</html>
</code>```

答:
There are some unclear/uncertain/hidden parts of the code you posted. maybe you should start with a simplified version of it that shows the definitions and invocations.

for example, there is a function called logData you defined but never invoked/used. where should it be used, I didn't see any fetch here

@Ermir answer is the right answer for the question "why this piece of code works even without clicking the button?"

Body:
I am trying to stop a JS function from loading every time a page is loaded, i wanted it to work only when a button is clicked. I have tried using onclick and .addEventListener.On using onclick, the output data displays before clicking the load data button and on using .addEventListener no data loads even on clicking the button. Any help would be appreciated, Thank you!

    <title> Monitoring</title>

  <form>
  Publish message :
  <input type="submit" onclick="GKpublishAll()">
</form>


问:
Click event not triggering for every iteration of for loop
I want to automate this page to generate exam results. I want to generate exam results from one particular date to some other particular date. On clicking the submit button, the page generates another page in a new tab.

Manually clicking 10 times will generate 10 tabs. But see the following code:

```<code>for(let i=0;i<10;i++)
{
document.querySelector('#reg1').click();
console.log(`clicked ${i}th time`)
}
</code>```

I want to trigger a click 10 times and it should generate 10 tabs accordingly. But the problem is that the click works only works on the 10th iteration and spawns 1 tab only. Help me.
see

Edit:
@Jesse
See my utility full code:

```<code>var dateFrom=new Date('2017-01')
var dateTo=new Date('2019-01')
for(var i=dateFrom;i<dateTo;i.setMonth(i.getMonth()+1))
{
    // console.log(`${i.getFullYear()}-${i.getMonth()}`);
    // var dd=`${i.getFullYear()}-${i.getMonth()}`;
    var dd=new Date(i).toISOString().substr(0,7);
    console.log(dd);
    document.querySelector("input#picker.form-control").value=dd;
    var type='Supplementary'
    document.querySelector("select#result_type.form-control.form-email.selectoption").value=type;
    document.querySelector('#reg1').click();

}
</code>```

答: It's because you're using the same ID. Either switch to using a class or change the ID names so they aren't identical. </p>

Body:
I want to automate this page to generate exam results. I want to generate exam results from one particular date to some other particular date. On clicking the submit button, the page generates another page in a new tab.

Manually clicking 10 times will generate 10 tabs. But see the following code:

for(let i=0;i<10;i++)
{
document.querySelector('#reg1').click();
console.log(`clicked ${i}th time`)
}

I want to trigger a click 10 times and it should generate 10 tabs accordingly. But the problem is that the click works only works on the 10th iteration and spawns 1 tab only. Help me.
see

Edit:
@Jesse
See my utility full code:

var dateFrom=new Date('2017-01')
var dateTo=new Date('2019-01')
for(var i=dateFrom;i<dateTo;i.setMonth(i.getMonth()+1))
{
    // console.log(`${i.getFullYear()}-${i.getMonth()}`);
    // var dd=`${i.getFullYear()}-${i.getMonth()}`;
    var dd=new Date(i).toISOString().substr(0,7);
    console.log(dd);
    document.querySelector("input#picker.form-control").value=dd;
    var type='Supplementary'
    document.querySelector("select#result_type.form-control.form-email.selectoption").value=type;
    document.querySelector('#reg1').click();

}


问:
My Spring webflux flatMap, doOnNext, doFinally is not getting called for inner Mono?
I am absoluteltly new to reactor.
My flatMap, doOnNext, doFinally is not getting called for inner Mono.
I added the sample test and output of it which depicts the problem. It wont getting called even if I interchange getMeIntegerMono2 with getMeStringMono,
is there anything wrong i am doing ?

```<code>@Test
    public void prodBug() {
        System.out.println(Final());
    }

    String Final(){
        final String[] val = new String[1];
        System.out.println("1 - "+Thread.currentThread().getName());

        Mono<Integer> intMono =
                getMeIntegerMono("2")
                        .doOnNext(integer -> {
                            getMeIntegerMono2("21")
                                    .flatMap(s -> getMeStringMono(String.valueOf(s)));
                        });

        System.out.println("2 - "+Thread.currentThread().getName());

        intMono.subscribe(integer -> {
            val[0] =String.valueOf(integer);
        });
        System.out.println("3 - "+Thread.currentThread().getName());
        return val[0];
    }

    Mono<String> getMeStringMono(String val){
        System.out.println("String Mono - "+Thread.currentThread().getName());
        return Mono.just(val);
    }

    Mono<Integer> getMeIntegerMono(String val){
        System.out.println("Integer Mono - "+Thread.currentThread().getName());
        return Mono.just(Integer.parseInt(val));
    }

    Mono<Integer> getMeIntegerMono2(String val){
        System.out.println("Integer Mono2 - "+Thread.currentThread().getName());
        return Mono.just(Integer.parseInt(val));
    }
</code>```

the output is

```<code>1 - main
Integer Mono - main
2 - main
Integer Mono2 - main
3 - main
2
</code>```

Process finished with exit code 0

答:
There's a few issues with your code.

In Reactor, nothing happens until you subscribe. That is to say just creating a Mono doesn't do anything. In the function you pass to doOnNext, you create a Mono which is never subscribed to. Because of that, the function you pass to flatMap will never be invoked. Try to use flatMap instead of doOnNext (you will need to fiddle with the types a bit to get it to work).

One problem with the way you are testing this comes from the difference between "assembly time" and "execution time." In all of your getMe* methods, you immediately print something and then return a Mono. This actually is misleading when debugging because the printing will happen during assembly time, even if the returned Mono is never executed. You can perform the side effects at execution time instead using Mono.defer() or Mono.fromSupplier().

The technique of using an array to get around Java's restrictions on variables and lambdas is poor practice and while it may work in this case, you should get out of the habit as it's very fragile. To understand why, imagine that some Mono in your chain does an expensive operation in another thread. This means the function you pass to subscribe will be invoked after Final() has already returned.

Body:
I am absoluteltly new to reactor.
My flatMap, doOnNext, doFinally is not getting called for inner Mono.
I added the sample test and output of it which depicts the problem. It wont getting called even if I interchange getMeIntegerMono2 with getMeStringMono,
is there anything wrong i am doing ?

@Test
    public void prodBug() {
        System.out.println(Final());
    }

    String Final(){
        final String[] val = new String[1];
        System.out.println("1 - "+Thread.currentThread().getName());

        Mono<Integer> intMono =
                getMeIntegerMono("2")
                        .doOnNext(integer -> {
                            getMeIntegerMono2("21")
                                    .flatMap(s -> getMeStringMono(String.valueOf(s)));
                        });

        System.out.println("2 - "+Thread.currentThread().getName());

        intMono.subscribe(integer -> {
            val[0] =String.valueOf(integer);
        });
        System.out.println("3 - "+Thread.currentThread().getName());
        return val[0];
    }

    Mono<String> getMeStringMono(String val){
        System.out.println("String Mono - "+Thread.currentThread().getName());
        return Mono.just(val);
    }

    Mono<Integer> getMeIntegerMono(String val){
        System.out.println("Integer Mono - "+Thread.currentThread().getName());
        return Mono.just(Integer.parseInt(val));
    }

    Mono<Integer> getMeIntegerMono2(String val){
        System.out.println("Integer Mono2 - "+Thread.currentThread().getName());
        return Mono.just(Integer.parseInt(val));
    }

the output is

1 - main
Integer Mono - main
2 - main
Integer Mono2 - main
3 - main
2

Process finished with exit code 0


问:
How to activate automatic Whatsapp template from Facebook business manager?
I'm setting up a new connection between whatsapp and zendesk to support better Cust.service experience. The actual goal is to be able to sendout automated response through whatsapp that is triggered from salesforce, but I'm quite new to this and have limited knowledge about whatsapp API.

In our facebook business manager, I have created the Account API WhatsApp Business and also connected the phone number to the API whatsapp business, but the next step is confusing me, which I need to register the app using /v1/account node account. I dont understand this part.

further step is "Request a Registration Code"
Send the telephone number and vname certificate string encoded in your base64 to request the registration code. You can request to receive your code via SMS or voice call.

Use endpoint / v1 / account to request your registration code.

POST /v1/account

{
    "cc": "your-country-code",
    "phone_number": "your- phone-number-without-country-code",
    "method": "sms" | "voice",
    "cert": "your-verified-name-cert-in-base64",
    "pin": "your-existing-6-digit-pin" # required if two-factor verification is enabled
}

I expect to have whatsapp template that can be used by our registered phone number and set up auto response, then later we can create trigger in salesforce using something (which I still dont know)

答:
You also to need to share what kind of setup you're using for the WhatsApp Business API for us to help answer this question.
It seems you're on the technical steps at this point from their documentation. https://developers.facebook.com/docs/whatsapp/getting-started

You should first complete the setup (either on-premise or AWS setup) before moving to the registration step. If you have setup the containers locally, the docs recommend the Postman collection to start sending requests to the WhatsApp Business API container endpoints. https://developers.facebook.com/docs/whatsapp/guides/postman

Once you've completed the first step, you'll have a way to make API requests to the WhatsApp Business API web endpoint.

The registration step after that should be straightforward. https://developers.facebook.com/docs/whatsapp/api/account


问:
How to send multiple MIDI Events over USB on iOs with Xamarin?
I am using Core Midi to send MIDI Events over USB on a Xamarin iOs app,
I am based on this example
https://developer.xamarin.com/samples/monotouch/CoreMidiSample/

I want to modify the above example in order to send multiple NoteOn MIDI Events at the same time over USB, Unfortunately, It works only to send one NoteOn Midi Event at time,

Here is the modified part

```<code>void SendNote ()
        {
            for (int i = 0; i < Midi.DestinationCount; i++) {
                var endpoint = MidiEndpoint.GetDestination (i);
                // play note
                outputPort.Send (endpoint, new MidiPacket [] { new MidiPacket (0, new byte [] { 0x90, 60, 127 }) });
                outputPort.Send(endpoint, new MidiPacket[] { new MidiPacket(0, new byte[] { 0x90, 64, 127 }) });
                outputPort.Send(endpoint, new MidiPacket[] { new MidiPacket(0, new byte[] { 0x90, 68, 127 }) });
            }
        }
</code>```

It sound only one note sometimes, sometimes two notes,
I would expect to get the three notes to sound at the same time always,
How can I do that?

答:
See the page below on midi.org - basically you need to enable 'poly mode'.

Channel Mode Messages

Controller numbers 124 through 127 are used to select between Omni Mode On or Off, and to select between the Mono Mode or Poly Mode of operation.

When Poly mode is selected, incoming Note On messages are played polyphonically. This means that when multiple Note On messages are received, each note is assigned its own voice (subject to the number of voices available in the synthesizer). The result is that multiple notes are played at the same time.

https://www.midi.org/articles-old/about-midi-part-3-midi-messages

Hope that helps :)

Body:
I am using Core Midi to send MIDI Events over USB on a Xamarin iOs app,
I am based on this example
https://developer.xamarin.com/samples/monotouch/CoreMidiSample/

I want to modify the above example in order to send multiple NoteOn MIDI Events at the same time over USB, Unfortunately, It works only to send one NoteOn Midi Event at time,

Here is the modified part

void SendNote ()
        {
            for (int i = 0; i < Midi.DestinationCount; i++) {
                var endpoint = MidiEndpoint.GetDestination (i);
                // play note
                outputPort.Send (endpoint, new MidiPacket [] { new MidiPacket (0, new byte [] { 0x90, 60, 127 }) });
                outputPort.Send(endpoint, new MidiPacket[] { new MidiPacket(0, new byte[] { 0x90, 64, 127 }) });
                outputPort.Send(endpoint, new MidiPacket[] { new MidiPacket(0, new byte[] { 0x90, 68, 127 }) });
            }
        }

It sound only one note sometimes, sometimes two notes,
I would expect to get the three notes to sound at the same time always,
How can I do that?