问:
Prime number code error 10001's prime (python)
I have made a program to find primes, but when I try to get the 10001st prime it isn't correct. I can't figure out why.

I haven't really tried much because I have no idea what to try.

```<code>import math
startingPrimes = [2,3, 5, 7, 11, 13, 17, 19]
for times in range (2):
    primeList = []
    numbersToBeTested = 0
    for _ in range (startingPrimes[len(startingPrimes)-1]**2):
        primeList.append(_ + 2)
    print ()
    numbersToBeTested = startingPrimes[len(startingPrimes)-1]**2
    print (numbersToBeTested)
    divisor = 0
    term = 0
    dividend = 0
    position = 0

    while divisor < math.sqrt(len(primeList)):
        term = 0
        divisor = startingPrimes[position]
        dividend = primeList[position]
        while term + 1 < len(primeList):

            term = term + 1
            if primeList[term] % divisor == 0:
                if primeList[term] != divisor:
                    primeList.remove(primeList[term])
        position = position + 1
    startingPrimes = primeList

for termOfList in range (len(primeList)):
    print (primeList[termOfList])
print ("How many primes: " + str(len(primeList)))
print ("10001st prime: " + str(primeList[10000]))
</code>```

It gives me 90373 which is wrong!
Please help!

答:
There are a number of issues with your code:

It generates primes that aren't prime, e.g. 99973 = 257 * 389

It's nearly impossible to figure how it decides when it's found sufficient primes.

It has bizarre expressions that seem to make no sense, eg.:

```<code>   for times in range (2):
       primeList = []
</code>```

This appears to run the code twice!  But it changes the result!
   Where's the code comment!

And there's this:

```<code>while divisor < math.sqrt(len(primeList)):
</code>```

The square root of the number of primes you found so far is a limit when searching for your next prime?

Problematic programs tend to be underwritten or overwritten -- this is an example of an overwritten program.  You can solve this problem with a dozen lines of Python, of no more than roughly 30 characters each, in a fraction of a second.  Your program requires more than twice that many lines, some twice that length, and takes nearly a minute to come up short on the answer.

My advice is to start over and keep it simple:

You don't need startingPrimes = [2,3, 5, 7, 11, 13, 17, 19].  Just initializing primeList = [2] is sufficient to avoid testing even numbers and focus on odd divisors.

You don't need math.sqrt(), simply test if if divisor * divisor > number: and all the divisors you need are in primeList.

The only modification operation you really need to do on primeList is append().

Somewhere there should be an explicit test for completion, eg.:

```<code>while len(primeList) < n:  # where n = 10001
</code>```

Body:
I have made a program to find primes, but when I try to get the 10001st prime it isn't correct. I can't figure out why.

I haven't really tried much because I have no idea what to try.

import math
startingPrimes = [2,3, 5, 7, 11, 13, 17, 19]
for times in range (2):
    primeList = []
    numbersToBeTested = 0
    for _ in range (startingPrimes[len(startingPrimes)-1]**2):
        primeList.append(_ + 2)
    print ()
    numbersToBeTested = startingPrimes[len(startingPrimes)-1]**2
    print (numbersToBeTested)
    divisor = 0
    term = 0
    dividend = 0
    position = 0

    while divisor < math.sqrt(len(primeList)):
        term = 0
        divisor = startingPrimes[position]
        dividend = primeList[position]
        while term + 1 < len(primeList):

            term = term + 1
            if primeList[term] % divisor == 0:
                if primeList[term] != divisor:
                    primeList.remove(primeList[term])
        position = position + 1
    startingPrimes = primeList

for termOfList in range (len(primeList)):
    print (primeList[termOfList])
print ("How many primes: " + str(len(primeList)))
print ("10001st prime: " + str(primeList[10000]))

It gives me 90373 which is wrong!
Please help!

Body:
There are a number of issues with your code:

It generates primes that aren't prime, e.g. 99973 = 257 * 389

It's nearly impossible to figure how it decides when it's found sufficient primes.

It has bizarre expressions that seem to make no sense, eg.:

   for times in range (2):
       primeList = []

This appears to run the code twice!  But it changes the result!
   Where's the code comment!

And there's this:

while divisor < math.sqrt(len(primeList)):

The square root of the number of primes you found so far is a limit when searching for your next prime?

Problematic programs tend to be underwritten or overwritten -- this is an example of an overwritten program.  You can solve this problem with a dozen lines of Python, of no more than roughly 30 characters each, in a fraction of a second.  Your program requires more than twice that many lines, some twice that length, and takes nearly a minute to come up short on the answer.

My advice is to start over and keep it simple:

You don't need startingPrimes = [2,3, 5, 7, 11, 13, 17, 19].  Just initializing primeList = [2] is sufficient to avoid testing even numbers and focus on odd divisors.

You don't need math.sqrt(), simply test if if divisor * divisor > number: and all the divisors you need are in primeList.

The only modification operation you really need to do on primeList is append().

Somewhere there should be an explicit test for completion, eg.:

while len(primeList) < n:  # where n = 10001


来源: stackexchange

问:
AWS security optionsn
I am currently building a instance request form for AWS services (EC2, RDS etc) and   I am being asked to add a security portion in the request form where we can select the type of security applicable for the instance be it a publicly accessible instance or a back-end instance.

I would like to kindly ask for help in determining the possible security options for aws instances. I have no other resources being new to the department within work thus this post (recently moved from service delivery to infra)

Here is the security section of the form. please see the link:

https://i.stack.imgur.com/Zi6Mj.png

Thank you for all the help.

答:
Below are some items you may want to consider putting on the request form:

Will this instance be internet facing or not?

Who will need access to this system? How will they need to access it?

Does the instance require encryption? Will PHI/PII data be stored on this instance?

Does the request need approval from other departments or management?

Will on-premise or data center resources need access to the instance (think VPN tunnels, etc, to create connections to the resources)

Will additional logging be needed for the system?

What applications will be required to be installed on the system?

How long with the instance be needed, or date to terminate the instance when no longer needed?

I hope this helps.

ContentLicense: CC BY-SA 4.0

Title: AWS security optionsn


问:
How do I update/upgrade pip itself from inside my virtual environment?
I'm able to update pip-managed packages, but how do I update pip itself? According to pip --version, I currently have pip 1.1 installed in my virtualenv and I want to update to the latest version.

What's the command for that? Do I need to use distribute or is there a native pip or virtualenv command? I've already tried pip update and pip update pip with no success.

答:
I was in a similar situation and wanted to update urllib3 package.
What worked for me was:</p>

```<code>pip3 install --upgrade --force-reinstall --ignore-installed urllib3==1.25.3
</code>```

Body:
I was in a similar situation and wanted to update urllib3 package.
What worked for me was:

pip3 install --upgrade --force-reinstall --ignore-installed urllib3==1.25.3


问:
Count word frequency of all words in a file
I have a text file, from which I have removed symbols and stop words.

I have also tokenized it (broken it into a list of all words) in case operations are easier with a list.

I would like to create a .csv file with frequencies of all words (long format) in descending order. How could I go about it?

I have thought about looping through the list thus:

```<code>longData = pandas.DataFrame([], index=[], columns=['Frequency'])
for word in tokenizedFile:
    if word in longData.index:
         longData.loc[word]=longData.loc[word]+1
    else:
         wordFrame = pandas.DataFrame([1], index=[word])
         longData.append(wordFrame)
</code>```

but that seems pretty inefficient and wasteful.

答:
Counter would be good here:</p>

```<code>    from collections import Counter
    c = Counter(tokenizedFile)
    longData = pd.DataFrame(c.values(), index = c.keys(), columns=['Frequency'])
</code>```

Body:
I have a text file, from which I have removed symbols and stop words.

I have also tokenized it (broken it into a list of all words) in case operations are easier with a list.

I would like to create a .csv file with frequencies of all words (long format) in descending order. How could I go about it?

I have thought about looping through the list thus:

longData = pandas.DataFrame([], index=[], columns=['Frequency'])
for word in tokenizedFile:
    if word in longData.index:
         longData.loc[word]=longData.loc[word]+1
    else:
         wordFrame = pandas.DataFrame([1], index=[word])
         longData.append(wordFrame)

but that seems pretty inefficient and wasteful.

Body:
Counter would be good here:

    from collections import Counter
    c = Counter(tokenizedFile)
    longData = pd.DataFrame(c.values(), index = c.keys(), columns=['Frequency'])


问:
how do I see if two values are not equal in APL?
Writing an APL function- how do I check to see if two values are not equal?
I tried like this:

```<code> :If (rowValue ≠ columnValue)
</code>```

but that gives me a LengthError.
Thank you!

答:
You're looking for ≢ rather than ≠.

≢ (full documentation) checks if the the left argument is different from the right argument in any way (rank, shape or content). It returns a single scalar 0 (false) only if the arrays are identical, else 1 (true).

≠ (full documentation) compares each atomic element in the left argument to the corresponding atomic element in the right argument. It pervades all structure, returning one Boolean per atomic element. If the arguments do not have compatible shapes, an error is signalled.

Body:
Writing an APL function- how do I check to see if two values are not equal?
I tried like this:

 :If (rowValue ≠ columnValue)

but that gives me a LengthError.
Thank you!


问:
How to move all elements that are zero to the end of an array?
Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.

Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.

NOT allowed to use any temporary arrays or objects. Also not allowed to use any Array.prototype or Object.prototype methods.So no array.push or splice() is allowed.

I tried this:

```<code>function removeZeros(nums) {

   for(let i = nums.length - 1; i >= 0 ; i--){
    if(nums[i] === 0){
      nums.splice(i, 1);
      nums.push(0);
    }
   }
   return nums;
}
</code>```

input:

```<code>[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]
</code>```

Expected:

```<code>[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]
</code>```

Actual:

```<code>[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]
</code>```

Result is coming as correct but I need to do it without array.push() or array.splice()

答:
```<code>function pushZeros(arr) {
  let count = 0;
  for (let i = 0; i < arr.length; i++) {
      if (arr[i] !== 0) arr[count++] = arr[i];
  }
  while (count < arr.length) arr[count++] = 0;

  return arr;
}
</code>```

Basically I am looping through all elements of array, picking nonzero element as I loop and storing it from 0th position in same array.  After I am done looping, count will be equal to total nonzero elements in array.  Rest all can be then initialized to zero.

Body:
Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.

Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.

NOT allowed to use any temporary arrays or objects. Also not allowed to use any Array.prototype or Object.prototype methods.So no array.push or splice() is allowed.

I tried this:

function removeZeros(nums) {

   for(let i = nums.length - 1; i >= 0 ; i--){
    if(nums[i] === 0){
      nums.splice(i, 1);
      nums.push(0);
    }
   }
   return nums;
}

input:

[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

Expected:

[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

Actual:

[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

Result is coming as correct but I need to do it without array.push() or array.splice()

Body:
function pushZeros(arr) {
  let count = 0;
  for (let i = 0; i < arr.length; i++) {
      if (arr[i] !== 0) arr[count++] = arr[i];
  }
  while (count < arr.length) arr[count++] = 0;

  return arr;
}

Basically I am looping through all elements of array, picking nonzero element as I loop and storing it from 0th position in same array.  After I am done looping, count will be equal to total nonzero elements in array.  Rest all can be then initialized to zero.


问:
Show 3 different values of the same column and same table in the same row in results
I use SQL Server 2014 for my project. I have three tables:

```<code>Table A:
Column: id
Table B:
Column: id, id_of_Table_A
Table C:
Column: id, id_of_Table_B, category

The relationship between A and B is one to many
The relationship between B and C is one to many
</code>```

In Table C, there are 10 category values for the category column, but I am interested only in three categories (cat1, cat2, cat3). I hope to query and produce the following results for the three categories:

```<code>id_of_Table_A, category, category, category
</code>```

I have the following statement:

```<code>select a.id, c.category from Table_C c
join Table_B b on b.id = c.id_of_Table_B
join Table_A a on a.id = b.id_of_Table_A
where c.category = 'cat1' and a.id in (1, 2, 3)
</code>```

But this statement only lists

```<code>id_of_Table_A, cat1
</code>```

which contains only cat1 of a given id_of_Table_A. I hope to have something like:

```<code>1, cat1, cat2, cat3
</code>```

if cat1, cat2, and cat3 exists in Table C for the given id 1 in Table A.

If a single statement is unable to produce the desired results, then a stored procedure is okay.

Update

In the following example results,

```<code>1, cat1, cat2, cat3
</code>```

cat1, cat2, cat3 must come from three different records in Table B. Suppose we have these tables and rows:

```<code>Table A: 1,2
Table B: (1,1), (2,1), (3,1), (4,2), (5,2), (6,2)
Table c: (1,1,'cat3'), (2,2,'cat1'), (3,3,'cat2'), (4,4,'cat1'), (5,5,'cat4'), (6,6,'cat2')
</code>```

Then the expected results should be:

```<code>1, cat1, cat2, cat3
</code>```

Basically, the relationships of the tables form a tree. I hope to find the root  (Table A) with leaves being cat1, cat2, and cat3 on non-overlapping paths from the root.

答:
You can combine all categories for id_of_b in a single xml value and then show categories in columns. Something like this.

```<code>declare @a table(id int)
declare @b table(id int,id_of_a int)
declare @c table(id int,id_of_b int,category varchar(50))
insert @a values(1),(2)
insert @b values(1,1),(2,1),(3,2)
insert @c values(1,1,'cat1'),(2,1,'cat2'),(3,1,'cat3'),(4,2,'cat4')
;with cte as(
  select a.id,
    cast((select category from @c c where c.id_of_b = b.id for xml auto,root,type) as xml) xcat
  from @a a inner join @b b on a.id = b.id_of_a
)
select id,
  t.v.value('c[1]/@category','varchar(50)') cat1,
  t.v.value('c[2]/@category','varchar(50)') cat2,
  t.v.value('c[3]/@category','varchar(50)') cat3
from cte
cross apply xcat.nodes('root') t(v)
</code>```

Updated answer for updated question

```<code>declare @a table(id int)
declare @b table(id int,id_of_a int)
declare @c table(id int,id_of_b int,category varchar(50))
insert @a values(1),(2)
insert @b values (1,1), (2,1), (3,1), (4,2), (5,2), (6,2)
insert @c values (1,1,'cat3'), (2,2,'cat1'), (3,3,'cat2'), (4,4,'cat1'), (5,5,'cat4'), (6,6,'cat2')

;with cte as(
  select a.id,
    cast((select category from @c c inner join @b b on c.id_of_b = b.id
       where b.id_of_a=a.id
       for xml auto,root,type) as xml) xcat
  from @a a
)
select id,
  t.v.value('c[1]/@category','varchar(50)') cat1,
  t.v.value('c[2]/@category','varchar(50)') cat2,
  t.v.value('c[3]/@category','varchar(50)') cat3
from cte
cross apply xcat.nodes('root') t(v)
</code>```

Body:
I use SQL Server 2014 for my project. I have three tables:

Table A:
Column: id
Table B:
Column: id, id_of_Table_A
Table C:
Column: id, id_of_Table_B, category

The relationship between A and B is one to many
The relationship between B and C is one to many

In Table C, there are 10 category values for the category column, but I am interested only in three categories (cat1, cat2, cat3). I hope to query and produce the following results for the three categories:

id_of_Table_A, category, category, category

I have the following statement:

select a.id, c.category from Table_C c
join Table_B b on b.id = c.id_of_Table_B
join Table_A a on a.id = b.id_of_Table_A
where c.category = 'cat1' and a.id in (1, 2, 3)

But this statement only lists

id_of_Table_A, cat1

which contains only cat1 of a given id_of_Table_A. I hope to have something like:

1, cat1, cat2, cat3

if cat1, cat2, and cat3 exists in Table C for the given id 1 in Table A.

If a single statement is unable to produce the desired results, then a stored procedure is okay.

Update

In the following example results,

1, cat1, cat2, cat3

cat1, cat2, cat3 must come from three different records in Table B. Suppose we have these tables and rows:

Table A: 1,2
Table B: (1,1), (2,1), (3,1), (4,2), (5,2), (6,2)
Table c: (1,1,'cat3'), (2,2,'cat1'), (3,3,'cat2'), (4,4,'cat1'), (5,5,'cat4'), (6,6,'cat2')

Then the expected results should be:

1, cat1, cat2, cat3

Basically, the relationships of the tables form a tree. I hope to find the root  (Table A) with leaves being cat1, cat2, and cat3 on non-overlapping paths from the root.

Body:
You can combine all categories for id_of_b in a single xml value and then show categories in columns. Something like this.

declare @a table(id int)
declare @b table(id int,id_of_a int)
declare @c table(id int,id_of_b int,category varchar(50))
insert @a values(1),(2)
insert @b values(1,1),(2,1),(3,2)
insert @c values(1,1,'cat1'),(2,1,'cat2'),(3,1,'cat3'),(4,2,'cat4')
;with cte as(
  select a.id,
    cast((select category from @c c where c.id_of_b = b.id for xml auto,root,type) as xml) xcat
  from @a a inner join @b b on a.id = b.id_of_a
)
select id,
  t.v.value('c[1]/@category','varchar(50)') cat1,
  t.v.value('c[2]/@category','varchar(50)') cat2,
  t.v.value('c[3]/@category','varchar(50)') cat3
from cte
cross apply xcat.nodes('root') t(v)

Updated answer for updated question

declare @a table(id int)
declare @b table(id int,id_of_a int)
declare @c table(id int,id_of_b int,category varchar(50))
insert @a values(1),(2)
insert @b values (1,1), (2,1), (3,1), (4,2), (5,2), (6,2)
insert @c values (1,1,'cat3'), (2,2,'cat1'), (3,3,'cat2'), (4,4,'cat1'), (5,5,'cat4'), (6,6,'cat2')

;with cte as(
  select a.id,
    cast((select category from @c c inner join @b b on c.id_of_b = b.id
       where b.id_of_a=a.id
       for xml auto,root,type) as xml) xcat
  from @a a
)
select id,
  t.v.value('c[1]/@category','varchar(50)') cat1,
  t.v.value('c[2]/@category','varchar(50)') cat2,
  t.v.value('c[3]/@category','varchar(50)') cat3
from cte
cross apply xcat.nodes('root') t(v)


问:
Creating a method in a Class which takes dummy arguments
I am kind of new to object oriented programming and want to explore it more. I have a dictionary here  "a" which has certain key value pairs. So what I would like to do is build a method which goes through this dictionary and takes only the values which have their values as True

I tried creating a class which takes in the values, i have the logic for checking the values in the dict but dont understand how to proceed with creating a method out of it

a = {"A": True, "B": False, "C": True}

```<code>class Check:

    def __init__(self, country, A, B):
         self.country = country
         self.A = A
         self.B = B

    def countrycheck(self):

        Result = {}
        for i in self.country:
            if self.country[i] == True:
                Result.update({i: True})

        return Result
</code>```

I get results but not cannot formulate what I actually want. I want it to run something like this:

```<code>trial = Check(a, b, c)
</code>```

So running this should give me a dict = {"A": True, "C": True}.
a is where I check for the country values from the dict and I also want the b and c arguments to be there. I tried using them but it gives me this error - "b is not defined"

答:
function init(), is always executed when the class is being initiated.

Use the init() function to assign values to object properties, or other operations that are necessary to do when the object is being created. in your case A,B in  def __init__(self, country, A, B): doesnt have sense

Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

Object Methods:

Objects can also contain methods. Methods in objects are functions that belongs to the object.

If you want to use the method (or attribute) of a class outside the definition of that class you will do it like:

```<code>trial = Check(a)

trial.countrycheck()
</code>```

Example:

```<code>class A(object):
    def foo(self):
        print ('Foo')

    def bar(self, argument):
        print ('Bar ', argument)

a = A()
a.foo() #prints 'Foo'
a.bar('Arg!') #prints 'Bar Arg!'
</code>```

your code should look like:

```<code>class Check:
    def __init__(self, country):
         self.country = country

    def countrycheck(self):

        Result = {}
        for i in self.country:
            if self.country[i] == True:
                Result.update({i: True})

        return Result

a = {"A": True, "B": False, "C": True}

trial = Check(a)

print (trial.countrycheck())
</code>```

output:

```<code>{'A': True, 'C': True}
</code>```

Body:
I am kind of new to object oriented programming and want to explore it more. I have a dictionary here  "a" which has certain key value pairs. So what I would like to do is build a method which goes through this dictionary and takes only the values which have their values as True

I tried creating a class which takes in the values, i have the logic for checking the values in the dict but dont understand how to proceed with creating a method out of it

a = {"A": True, "B": False, "C": True}

class Check:

    def __init__(self, country, A, B):
         self.country = country
         self.A = A
         self.B = B

    def countrycheck(self):

        Result = {}
        for i in self.country:
            if self.country[i] == True:
                Result.update({i: True})

        return Result

I get results but not cannot formulate what I actually want. I want it to run something like this:

trial = Check(a, b, c)

So running this should give me a dict = {"A": True, "C": True}.
a is where I check for the country values from the dict and I also want the b and c arguments to be there. I tried using them but it gives me this error - "b is not defined"

Body:
function init(), is always executed when the class is being initiated.

Use the init() function to assign values to object properties, or other operations that are necessary to do when the object is being created. in your case A,B in  def __init__(self, country, A, B): doesnt have sense

Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

Object Methods:

Objects can also contain methods. Methods in objects are functions that belongs to the object.

If you want to use the method (or attribute) of a class outside the definition of that class you will do it like:

trial = Check(a)

trial.countrycheck()

Example:

class A(object):
    def foo(self):
        print ('Foo')

    def bar(self, argument):
        print ('Bar ', argument)

a = A()
a.foo() #prints 'Foo'
a.bar('Arg!') #prints 'Bar Arg!'

your code should look like:

class Check:
    def __init__(self, country):
         self.country = country

    def countrycheck(self):

        Result = {}
        for i in self.country:
            if self.country[i] == True:
                Result.update({i: True})

        return Result

a = {"A": True, "B": False, "C": True}

trial = Check(a)

print (trial.countrycheck())

output:

{'A': True, 'C': True}


问:
Batch countdown timer that doesn't clear rest of output?
I am trying to create a batch timer that doesn't clear the output above it.

I have a timer function created, but am looking to improve it so that I can still view the output above it without having lines on lines of a countdown in the output. My current function is:

```<code>@echo off
echo KEEP THIS OUTPUT
CALL :timer 10
rem Do more things...
EXIT

:Timer
set time=%~1

:loop
cls

echo Countdown - [%time%]

set /a time=%time%-1
if %time%==0 goto timesup

ping localhost -n 2 > nul
goto loop

:timesup
echo Timer completed!!
EXIT /B 0
</code>```

Currently, the timer clears the screen, but I would like to make it so that the output above this timer stays.

For example, at 10 seconds, the output should be:

```<code>KEEP THIS OUTPUT
Countdown - [10]
</code>```

And then the output should change to:

```<code>KEEP THIS OUTPUT
Countdown - [9]
</code>```

The output should NOT be:

```<code>KEEP THIS OUTPUT
Countdown - [10]
Countdown - [9]
</code>```

and should NOT be:

```<code>Countdown - [9]
</code>```

Is there any way to do this?

答:
It can be done with special characters, carriage return or backspace.

A carriage return moves the cursor back to the beginning of the line.

But to be on the same line as the Countdown text, you can't use the echo command, as it always appends an linefeed.

Instead I use the set /p command to avoid this.

```<code>@Echo off
setlocal EnableDelayedExpansion
for /F %%# in ('copy /Z "%~dpf0" NUL') do set "CR=%%#"

for /L %%n in (10 -1 0) do (
    <nul set /p ".=Countdown[%%n] !CR!"
    ping localhost -n 2 > nul
)
</code>```

Body:
I am trying to create a batch timer that doesn't clear the output above it.

I have a timer function created, but am looking to improve it so that I can still view the output above it without having lines on lines of a countdown in the output. My current function is:

@echo off
echo KEEP THIS OUTPUT
CALL :timer 10
rem Do more things...
EXIT

:Timer
set time=%~1

:loop
cls

echo Countdown - [%time%]

set /a time=%time%-1
if %time%==0 goto timesup

ping localhost -n 2 > nul
goto loop

:timesup
echo Timer completed!!
EXIT /B 0

Currently, the timer clears the screen, but I would like to make it so that the output above this timer stays.

For example, at 10 seconds, the output should be:

KEEP THIS OUTPUT
Countdown - [10]

And then the output should change to:

KEEP THIS OUTPUT
Countdown - [9]

The output should NOT be:

KEEP THIS OUTPUT
Countdown - [10]
Countdown - [9]

and should NOT be:

Countdown - [9]

Is there any way to do this?

Body:
It can be done with special characters, carriage return or backspace.

A carriage return moves the cursor back to the beginning of the line.

But to be on the same line as the Countdown text, you can't use the echo command, as it always appends an linefeed.

Instead I use the set /p command to avoid this.

@Echo off
setlocal EnableDelayedExpansion
for /F %%# in ('copy /Z "%~dpf0" NUL') do set "CR=%%#"

for /L %%n in (10 -1 0) do (
    <nul set /p ".=Countdown[%%n] !CR!"
    ping localhost -n 2 > nul
)


问:
How to plot a grid of images and their categories
I am trying to create a plot similar to this.

I have several pictures, each of which I have two lists for (both lists with 5 elements).

I want to plot the image with the two lists to its right. Since there are several pictures to do this for, it would be nice if it could be done in a tile/grid format.

My data looks like:

```<code>class0[i] = ['example0', 'example1', .., 'example4']
class1[i] = ['example0', 'example1', .., 'example4']
</code>```

答:
Here is a suggestion using a grid of axes that can be pretty much any shape, and a table for pretty alignment of the class labels.

```<code>class0 = [['class0_{:d}'.format(i+1) for i in range(5)] for _ in range(10)]
class1 = [['class1_{:d}'.format(i+1) for i in range(5)] for _ in range(10)]

nrows, ncols = 5,2
fig, axs = plt.subplots(nrows, ncols*2, figsize=(2*ncols*2,2*nrows))
for img_ax,txt_ax,curr_class0,curr_class1 in zip(axs.flat[0::2], axs.flat[1::2], class0, class1):
    img_ax.imshow(np.random.random(size=(5,5)))

    text = [[c,d] for c,d in zip(curr_class0,curr_class1)]
    txt_ax.table(cellText=text, loc='center', edges='open')
    txt_ax.set_axis_off()
</code>```

Body:
I am trying to create a plot similar to this.

I have several pictures, each of which I have two lists for (both lists with 5 elements).

I want to plot the image with the two lists to its right. Since there are several pictures to do this for, it would be nice if it could be done in a tile/grid format.

My data looks like:

class0[i] = ['example0', 'example1', .., 'example4']
class1[i] = ['example0', 'example1', .., 'example4']

Body:
Here is a suggestion using a grid of axes that can be pretty much any shape, and a table for pretty alignment of the class labels.

class0 = [['class0_{:d}'.format(i+1) for i in range(5)] for _ in range(10)]
class1 = [['class1_{:d}'.format(i+1) for i in range(5)] for _ in range(10)]

nrows, ncols = 5,2
fig, axs = plt.subplots(nrows, ncols*2, figsize=(2*ncols*2,2*nrows))
for img_ax,txt_ax,curr_class0,curr_class1 in zip(axs.flat[0::2], axs.flat[1::2], class0, class1):
    img_ax.imshow(np.random.random(size=(5,5)))

    text = [[c,d] for c,d in zip(curr_class0,curr_class1)]
    txt_ax.table(cellText=text, loc='center', edges='open')
    txt_ax.set_axis_off()


问:
Typescript type check not working with Array filter
I am using Array.filter and instanceof to get all the objects of a certain type out of a more generic array.

```<code> let cars:Car[] = this.gameObjects.filter(go => go instanceof Car)
</code>```

This works! But the typescript compiler doesn't agree that the returned types are all of the Car type.

Type 'GameObject[]' is not assignable to type 'Car[]'

On the Typescript GitHub this issue is considered solved by adding an interface for array.filter. That doesn't work for me, it still gives the same error. You can try it out by pasting this code in the typescript playground:

```<code>interface Array<T> {
    filter<U extends T>(pred: (a: T) => a is U): U[];
}

class Car {
    drive() {

    }
}
class GameObject {

}

let gameObjects:GameObject[] = [new Car(), new Car()]

let cars:Car[] = gameObjects.filter((go) => go instanceof Car)
</code>```

Am I missing something here? How can I filter an array by type and get back an array of the correct type?

答:
To change the return type on filter function you must use a Type Guard Function like the following. You also don't need to extend the Array type because that's already defined on TypeScript.</p>

```<code>class GameObject {

}

class Car {
    drive() {

    }
}

let isCar = (obj: any): obj is Car => {
    return obj instanceof Car;
}

let gameObjects: GameObject[] = [new Car(), new Car()]

let cars: Car[] = gameObjects.filter(isCar)
</code>```

Body:
I am using Array.filter and instanceof to get all the objects of a certain type out of a more generic array.

 let cars:Car[] = this.gameObjects.filter(go => go instanceof Car)

This works! But the typescript compiler doesn't agree that the returned types are all of the Car type.

Type 'GameObject[]' is not assignable to type 'Car[]'

On the Typescript GitHub this issue is considered solved by adding an interface for array.filter. That doesn't work for me, it still gives the same error. You can try it out by pasting this code in the typescript playground:

interface Array<T> {
    filter(pred: (a: T) => a is U): U[];
}

class Car {
    drive() {

    }
}
class GameObject {

}

let gameObjects:GameObject[] = [new Car(), new Car()]

let cars:Car[] = gameObjects.filter((go) => go instanceof Car)

Am I missing something here? How can I filter an array by type and get back an array of the correct type?

Body:
To change the return type on filter function you must use a Type Guard Function like the following. You also don't need to extend the Array type because that's already defined on TypeScript.

class GameObject {

}

class Car {
    drive() {

    }
}

let isCar = (obj: any): obj is Car => {
    return obj instanceof Car;
}

let gameObjects: GameObject[] = [new Car(), new Car()]

let cars: Car[] = gameObjects.filter(isCar)


问:
Saving list data in python
I am wondering how I can save whatever I added to a list when I close a python file. For example, in this "my contact" program that I wrote below, if I add information about 'Jane Doe', what could I do so that next time I open up the same file, Jane Doe still exists.  </p>

```<code>def main():
    myBook = Book([{"name": 'John Doe', "phone": '123-456-7890', "address": '1000 Constitution Ave'}])
class Book:
    def __init__(self, peoples):
        self.peoples = peoples
        self.main_menu()
    def main_menu(self):
        print('Main Menu')
        print('1. Display Contact Names')
        print('2. Search For Contacts')
        print('3. Edit Contact')
        print('4. New Contact')
        print('5. Remove Contact')
        print('6. Exit')
        self.selection = input('Enter a # form the menu: ')
        if (self.selection == "1"):
            self.display_names()
        if (self.selection == "2"):
            self.search()
        if (self.selection == "3"):
            self.edit()
        if (self.selection == "4"):
            self.new()
        if (self.selection == "5"):
            self.delete()
        if (self.selection == "6"):
            self.end()
    def display_names(self):
        for people in self.peoples:
                print("Name: " + people["name"])
        self.main_menu()
    def search(self):
        searchname = input('What is the name of your contact: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                print("Name: " + self.peoples[index]["name"])
                print("Address: " + self.peoples[index]["address"])
                print("Phone: " + self.peoples[index]["phone"])
        self.main_menu()
    def edit(self):
        searchname = input('What is the name of the contact that you want to edit: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)
                name = input('What is your name: ')
                address = input('What is your address: ')
                phone = input('What is your phone number: ')
                self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def new(self):
        name = input('What is your name: ')
        address = input('What is your address: ')
        phone = input('What is your phone number: ')
        self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def delete(self):
        searchname = input('What is the name of the contact that you want to delete: ')
        for index in reversed(range(len(self.peoples))):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)

            print(searchname, 'has been removed')
        self.main_menu()
    def end(self):
        print('Thank you for using the contact book, have a nice day')
        print('Copyright Carson147 2019©, All Rights Reserved')

main()
</code>```

答:
There are innumerable kinds of serialization options, but a time-tested favorite is JSON. JavaScript Object Notation looks like:

```<code>[
    "this",
    "is",
    "a",
    "list",
    "of",
    "strings",
    "with",
    "a",
    {
        "dictionary": "of",
        "values": 4,
        "an": "example"
    },
    "can strings be single-quoted?",
    false,
    "can objects nest?",
    {
        "I": {
            "Think": {
                "They": "can"
            }
        }
    }
]
</code>```

JSON is widely used, and the Python stdlib has a method of converting objects to and from JSON in the json package.

>>> import json
>>> data = ['a', 'list', 'full', 'of', 'entries']
>>> json.dumps(data)  # dumps will dump to string
["a", "list", "full", "of", "entries"]
```

<p>You can then save your Book data to json before the program shuts down, and read from json after it starts up.</p>

<pre class="lang-py prettyprint-override"><code># at the top
import json
from pathlib import Path

# at the bottom of your program:
if __name__ == '__main__':
    persistence = Path('book.json')
    if persistence.exists():
        with persistence.open() as f:
            data = json.load(f)
    else:
        data = [{"name": 'John Doe', "phone": '123-456-7890', "address": '1000 Constitution Ave'}]

    book = Book(data)
    with persistence.open('w') as f:
        json.dump(f, indent=4)
</code>```

Title: Saving list data in python

Body:
I am wondering how I can save whatever I added to a list when I close a python file. For example, in this "my contact" program that I wrote below, if I add information about 'Jane Doe', what could I do so that next time I open up the same file, Jane Doe still exists.

def main():
    myBook = Book([{"name": 'John Doe', "phone": '123-456-7890', "address": '1000 Constitution Ave'}])
class Book:
    def __init__(self, peoples):
        self.peoples = peoples
        self.main_menu()
    def main_menu(self):
        print('Main Menu')
        print('1. Display Contact Names')
        print('2. Search For Contacts')
        print('3. Edit Contact')
        print('4. New Contact')
        print('5. Remove Contact')
        print('6. Exit')
        self.selection = input('Enter a # form the menu: ')
        if (self.selection == "1"):
            self.display_names()
        if (self.selection == "2"):
            self.search()
        if (self.selection == "3"):
            self.edit()
        if (self.selection == "4"):
            self.new()
        if (self.selection == "5"):
            self.delete()
        if (self.selection == "6"):
            self.end()
    def display_names(self):
        for people in self.peoples:
                print("Name: " + people["name"])
        self.main_menu()
    def search(self):
        searchname = input('What is the name of your contact: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                print("Name: " + self.peoples[index]["name"])
                print("Address: " + self.peoples[index]["address"])
                print("Phone: " + self.peoples[index]["phone"])
        self.main_menu()
    def edit(self):
        searchname = input('What is the name of the contact that you want to edit: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)
                name = input('What is your name: ')
                address = input('What is your address: ')
                phone = input('What is your phone number: ')
                self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def new(self):
        name = input('What is your name: ')
        address = input('What is your address: ')
        phone = input('What is your phone number: ')
        self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def delete(self):
        searchname = input('What is the name of the contact that you want to delete: ')
        for index in reversed(range(len(self.peoples))):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)

            print(searchname, 'has been removed')
        self.main_menu()
    def end(self):
        print('Thank you for using the contact book, have a nice day')
        print('Copyright Carson147 2019©, All Rights Reserved')

main()

Body:
There are innumerable kinds of serialization options, but a time-tested favorite is JSON. JavaScript Object Notation looks like:

[
    "this",
    "is",
    "a",
    "list",
    "of",
    "strings",
    "with",
    "a",
    {
        "dictionary": "of",
        "values": 4,
        "an": "example"
    },
    "can strings be single-quoted?",
    false,
    "can objects nest?",
    {
        "I": {
            "Think": {
                "They": "can"
            }
        }
    }
]

JSON is widely used, and the Python stdlib has a method of converting objects to and from JSON in the json package.

>>> import json
>>> data = ['a', 'list', 'full', 'of', 'entries']
>>> json.dumps(data)  # dumps will dump to string
["a", "list", "full", "of", "entries"]

You can then save your Book data to json before the program shuts down, and read from json after it starts up.

# at the top
import json
from pathlib import Path

# at the bottom of your program:
if __name__ == '__main__':
    persistence = Path('book.json')
    if persistence.exists():
        with persistence.open() as f:
            data = json.load(f)
    else:
        data = [{"name": 'John Doe', "phone": '123-456-7890', "address": '1000 Constitution Ave'}]

    book = Book(data)
    with persistence.open('w') as f:
        json.dump(f, indent=4)


问:
Android Studio wireless ADB error (10061)
It seems that wireless ADB has more and more issues each time I update Android Studio. Using 2.1.1, I'm now unable to connect to my tablet using the command:

```<code>adb connect <ip addr>
</code>```

It results in the error:

```<code>unable to connect to <ip addr>:5555: cannot connect to <ip addr>:5555: No connection could be made because the target machine actively refused it. (10061)
</code>```

This happens directly after approving the connection in the dialog box on the tablet. Before today I was forced to do an adb kill-server prior to attempting to connect to the tablet but now that doesn't even help.

答: I had the same issue. It was working perfectly for a month, and then one day it stopped working. I tried all the solutions above, but to no avail. Then, I noticed that for some reason, the IP address of my phone had changed, ending with the number 1 instead of 0. So I connected to the new address with 1 as the last digit in the address and now it works again. Weird.</p>

ContentLicense: CC BY-SA 3.0

Body:
It seems that wireless ADB has more and more issues each time I update Android Studio. Using 2.1.1, I'm now unable to connect to my tablet using the command:

adb connect <ip addr>

It results in the error:

unable to connect to <ip addr>:5555: cannot connect to <ip addr>:5555: No connection could be made because the target machine actively refused it. (10061)

This happens directly after approving the connection in the dialog box on the tablet. Before today I was forced to do an adb kill-server prior to attempting to connect to the tablet but now that doesn't even help.


问:
selenium checkbox click not working in python
https://agent.loadbook.in/#/login
When I go to the signup form, the form has a checkbox as I agree with the condition. It's an Input tag checkbox. when I select the tag by id and when I perform click or send_key of submitting its showing checkbox not clickable.

below all Method are not work

```<code>driver.find_element_by_xpath('//div[@class="switch__container"]//input').click()

driver.find_element_by_xpath('//div[@class="switch__container"]//input').send_keys(Keys.ENTER)

driver.find_element_by_xpath('//div[@class="switch__container"]//input').submit()

driver.find_element_by_xpath('//div[@class="switch__container"]//input').send_keys("after")

driver.find_element_by_xpath('//div[@class="switch__container"]//label').click()

driver = webdriver.Chrome(options=chrome_options)
driver.get("https://agent.loadbook.in/#/login")

driver.find_element_by_partial_link_text("Create an account").click()
</code>```

try:

```<code>driver.find_element_by_xpath('//div[@class="switch__container"]//input').click()
# driver.find_element("name","username").send_keys("test")
# driver.find_element("name","email").send_keys("test@test.com")
# driver.find_element("name","phone").send_keys("99999999")
# driver.find_element("name","password").send_keys("12345")
</code>```

except NoSuchElementException as exception:
      print("not found")

selenium.common.exceptions.ElementNotVisibleException: Message:
  element not interactable

答:
To click() on the checkbox asociated with text as I agree to the Terms and Conditions and Privacy Policy you have to induce WebDriverWait for the element to be clickable and you can use the following solution:

Code Block:

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
# options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get("https://agent.loadbook.in/#/login")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Create an account"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label[for='switch-shadow']"))).click()
</code>```

Browser Snapshot:

Body:
https://agent.loadbook.in/#/login
When I go to the signup form, the form has a checkbox as I agree with the condition. It's an Input tag checkbox. when I select the tag by id and when I perform click or send_key of submitting its showing checkbox not clickable.

below all Method are not work

driver.find_element_by_xpath('//div[@class="switch__container"]//input').click()

driver.find_element_by_xpath('//div[@class="switch__container"]//input').send_keys(Keys.ENTER)

driver.find_element_by_xpath('//div[@class="switch__container"]//input').submit()

driver.find_element_by_xpath('//div[@class="switch__container"]//input').send_keys("after")

driver.find_element_by_xpath('//div[@class="switch__container"]//label').click()

driver = webdriver.Chrome(options=chrome_options)
driver.get("https://agent.loadbook.in/#/login")

driver.find_element_by_partial_link_text("Create an account").click()

try:

driver.find_element_by_xpath('//div[@class="switch__container"]//input').click()
# driver.find_element("name","username").send_keys("test")
# driver.find_element("name","email").send_keys("test@test.com")
# driver.find_element("name","phone").send_keys("99999999")
# driver.find_element("name","password").send_keys("12345")

except NoSuchElementException as exception:
      print("not found")

selenium.common.exceptions.ElementNotVisibleException: Message:
  element not interactable

Body:
To click() on the checkbox asociated with text as I agree to the Terms and Conditions and Privacy Policy you have to induce WebDriverWait for the element to be clickable and you can use the following solution:

Code Block:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
# options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get("https://agent.loadbook.in/#/login")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Create an account"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label[for='switch-shadow']"))).click()

Browser Snapshot:


问:
Run matlab code on javascript
I have a simple matlab code. It loads a file and draws a graph using datas in this file. I want that when I press a html button, the graph is drew.I read some recommendations on web/blogs. Have to I use com server?

EDIT

My app is not a web app yet. I run it local pc, it is just a htm file.I use google chrome for now.

答:
One way to do so would be for you to generate the C++ code out of Matlab code using Matlab coder, then there are a few way ways to run C/C++ codes in the browser, see below links:

Running C in A Browser and Native client

It is worthwhile to mention that it might not be the best idea and you might face many fundamental issues since you are practically converting Matlab code two times to different programming languages. Currently, there are many issues with Google Native Client, including the fact that you can not run it on every browser, other services are essentially better than the google native client.

Finally, if you have a simple code I would recommend you to rewrite it in JS instead of going throw all the trouble.

Title: Run matlab code on javascript


问:
Insert a row into a dataframe at index i
I need your help on a pandas problem :

I am currently extracting data via APIs that contain gaps in their ranks.

However I need to take into account these on the dataset by replacing them with an average value.

Then I need to insert a row in my dataframe to fill the dataframe.

Illustration :

Here's what my problem looks like :

```<code>   rank timestamp value
0    1     21:50  3450
1    4     21:40  3442
2    5     21:41  5964
3    6     14:27  5258
4    7     13:10  3001
5    8     14:02  2782
</code>```

ranks 2 and 3 are missing

So,hHere's what I'm trying to get :

```<code>   rank timestamp value
0    1     21:50  3450
1    2      NaN   avg
2    3      NaN   avg
3    4     21:40  3442
4    5     21:41  5964
5    6     14:27  5258
6    7     13:10  3001
7    8     14:02  2782
</code>```

I know approximately how to deal with columns, but I have no idea how to deal with rows.

Do you have an idea ?

I have already tried to use "append" but I struggle then to reindex my dataframe :/

答:
You can use reindex to add missing ranks and fillna to fill missing values.</p>

```<code>df = df.set_index('rank').reindex(np.arange(df['rank'].min(), df['rank'].max()+1)).reset_index()
df['value'] = df['value'].fillna(df['value'].mean()).round()

    rank    timestamp   value
0   1       21:50       3450
1   2       NaN         3982
2   3       NaN         3982
3   4       21:40       3442
4   5       21:41       5964
5   6       14:27       5258
6   7       13:10       3001
7   8       14:02       2782
</code>```

Body:
I need your help on a pandas problem :

I am currently extracting data via APIs that contain gaps in their ranks.

However I need to take into account these on the dataset by replacing them with an average value.

Then I need to insert a row in my dataframe to fill the dataframe.

Illustration :

Here's what my problem looks like :

   rank timestamp value
0    1     21:50  3450
1    4     21:40  3442
2    5     21:41  5964
3    6     14:27  5258
4    7     13:10  3001
5    8     14:02  2782

ranks 2 and 3 are missing

So,hHere's what I'm trying to get :

   rank timestamp value
0    1     21:50  3450
1    2      NaN   avg
2    3      NaN   avg
3    4     21:40  3442
4    5     21:41  5964
5    6     14:27  5258
6    7     13:10  3001
7    8     14:02  2782

I know approximately how to deal with columns, but I have no idea how to deal with rows.

Do you have an idea ?

I have already tried to use "append" but I struggle then to reindex my dataframe :/

Body:
You can use reindex to add missing ranks and fillna to fill missing values.

df = df.set_index('rank').reindex(np.arange(df['rank'].min(), df['rank'].max()+1)).reset_index()
df['value'] = df['value'].fillna(df['value'].mean()).round()

    rank    timestamp   value
0   1       21:50       3450
1   2       NaN         3982
2   3       NaN         3982
3   4       21:40       3442
4   5       21:41       5964
5   6       14:27       5258
6   7       13:10       3001
7   8       14:02       2782


问:
Df.mean returns imaginary numbers
I have a dataframe with around 50 columns and around 3000 rows. Most cells are empty but not all of them. I am trying to add a new row at the end of the dataframe, with the mean value of each column and I need it to ignore the empty cells.

I am using df.mean(axis=0), which somehows turns all values of the dataframe into imaginary numbers. All values stay the same but a +0j is added. I have no Idea why.

Turbine.loc['Mean_Values'] = Turbine.mean(axis=0)
```

I couldnt find a solution for this, is it because of the empty cells?

答: some cells had information about directions (north, west...) in them, which were interpreted as imaginary numbers.</p>

Title: Df.mean returns imaginary numbers

Body:
I have a dataframe with around 50 columns and around 3000 rows. Most cells are empty but not all of them. I am trying to add a new row at the end of the dataframe, with the mean value of each column and I need it to ignore the empty cells.

I am using df.mean(axis=0), which somehows turns all values of the dataframe into imaginary numbers. All values stay the same but a +0j is added. I have no Idea why.

Turbine.loc['Mean_Values'] = Turbine.mean(axis=0)

I couldnt find a solution for this, is it because of the empty cells?


问:
Why do I get 404 error on RESTEasy (wildfly) after deploy?
I have created simple 3 files in Java, and used mvn clean package wildfly:deploy command to run it. It all deployed successfully (at least thats what is written in console). However, when I go to

http://localhost:8080/lab-rest-api/library/book

I get 404 error. My project is located in module lab-rest-api (its just a part of a project, other modules are for web consume - ejb, ear etc)

I did web service and simple web consuming and it worked out fine. However, REST API is not working.

Here is my pom.xml:

```<code> <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxrs</artifactId>
        <version>3.6.3.Final</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>3.6.3.Final</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxb-provider</artifactId>
        <version>3.6.3.Final</version>
        <scope>provided</scope>
    </dependency>
</code>```

My extend Application:

```<code>@ApplicationPath("/")
public class RESTMain extends Application {
    public RESTMain() {
        System.out.println("whatever");
    }

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

And my service:

```<code>@Path("/library")
@Consumes({"application/json"})
@Produces({"application/json"})
public class ServicesInterface {

    Book booky = new Book();

    @GET
    @Path("/book/{title}")
    public Book getBook(@PathParam("title") String title){
        return booky;
    }

    @PUT
    @Path("/book/{title}")
    public Book addBook(@PathParam("title") String title, @QueryParam("author") String author){
        return booky;
    }

    @POST
    @Path("/book/{title}")
    public Book updateBook(@PathParam("title") String title, String author){
        return booky;
    }

    @DELETE
    @Path("/book/{title}")
    public Book removeBook(@PathParam("title") String title){
        return booky;
    }

}
</code>```

"Book" is a simple class with 2 Strings (author and title) and getters and setters for it.

答:
You seems didn't implement the Get for \book. You only implemented \book\{title}

for your current implementation, try \book\{meaningful title in your database}

Body:
I have created simple 3 files in Java, and used mvn clean package wildfly:deploy command to run it. It all deployed successfully (at least thats what is written in console). However, when I go to

http://localhost:8080/lab-rest-api/library/book

I get 404 error. My project is located in module lab-rest-api (its just a part of a project, other modules are for web consume - ejb, ear etc)

I did web service and simple web consuming and it worked out fine. However, REST API is not working.

Here is my pom.xml:

 <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxrs</artifactId>
        <version>3.6.3.Final</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>3.6.3.Final</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxb-provider</artifactId>
        <version>3.6.3.Final</version>
        <scope>provided</scope>
    </dependency>

My extend Application:

@ApplicationPath("/")
public class RESTMain extends Application {
    public RESTMain() {
        System.out.println("whatever");
    }

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

And my service:

@Path("/library")
@Consumes({"application/json"})
@Produces({"application/json"})
public class ServicesInterface {

    Book booky = new Book();

    @GET
    @Path("/book/{title}")
    public Book getBook(@PathParam("title") String title){
        return booky;
    }

    @PUT
    @Path("/book/{title}")
    public Book addBook(@PathParam("title") String title, @QueryParam("author") String author){
        return booky;
    }

    @POST
    @Path("/book/{title}")
    public Book updateBook(@PathParam("title") String title, String author){
        return booky;
    }

    @DELETE
    @Path("/book/{title}")
    public Book removeBook(@PathParam("title") String title){
        return booky;
    }

}

"Book" is a simple class with 2 Strings (author and title) and getters and setters for it.


问:
Can I in a @RabbitConsumer find out if any messages are prefetched for this consumer
I need to know if there are more messages comming for this consumer.

Right now I count the messages on the queue. But that give me only what is left on the queue and not what has been prefetched.

```<code>@RabbitListener(queues = QUEUENAME)
    public void recieve(Message message, Channel channel) throws IOException {
   long messagesOnQueue = channel.messageCount(QUEUENAME);
   if(messagesOnQueue>1) {
     //add message to list
   }
   else {
      //save the list
   }
}
</code>```

It would be really great If there was a way to tell if messages was prefetched for this consumer. Is that possible? If I can get that count then I dont care if there are messages on the queue as well.

After recieving suggestions from Gary I have changed the implementation to this, and it works.
When manually acknowledging a message it has to be done on the same channel as you get the message. But you can save a reference to it in case you need it in another thread.
In your spring boot application.yml add this

```<code>spring:
  rabbitmq:
    listener:
      direct:
        prefetch: 200
      simple:
        prefetch: 200
        acknowledgeMode: MANUAL
</code>```

Code from the consumer.

```<code>//The list we build and save in one transaction
    private Set<PayloadDto> unhandledPayloads = new HashSet<>();
    private long latestTag = 0L;
    private Channel latestChannel;

    @RabbitListener(queues = QUEUE_NAME, id = "consumerId")
    public void recieve(Message message, Channel channel) throws IOException {
        PayloadDto payloadDto = parse(message.getBody());

        unhandledPayloads.add(payloadDto);
        latestTag = message.getMessageProperties().getDeliveryTag();
        latestChannel = channel;
        if (unhandledPayloads.size() > UNHANDLED_PAYLOADS_LIMIT) {
            service.createOrUpdate(unhandledPayloads);
            queue.clear();
            channel.basicAck(latestTag, true);
        }
    }

    @EventListener(condition = "event.listenerId == 'consumerId'")
    public void onApplicationEvent(ListenerContainerIdleEvent event) {
        if(!queue.isEmpty()) {
            service.createOrUpdate(unhandledPayloads);
            queue.clear();
            latestChannel.basicAck(latestTag, true);
        }

    }
</code>```

The reason we are trying to build up a list before saving it is to be able to do batch insert to make it run faster.

答: Not currently, but it wouldn't be hard to add a feature. Open a github issue to request it. However, I am not sure how useful it would be. If there are still messages in the queue, consuming a prefetched will fetch another.</p>

Body:
I need to know if there are more messages comming for this consumer.

Right now I count the messages on the queue. But that give me only what is left on the queue and not what has been prefetched.

@RabbitListener(queues = QUEUENAME)
    public void recieve(Message message, Channel channel) throws IOException {
   long messagesOnQueue = channel.messageCount(QUEUENAME);
   if(messagesOnQueue>1) {
     //add message to list
   }
   else {
      //save the list
   }
}

It would be really great If there was a way to tell if messages was prefetched for this consumer. Is that possible? If I can get that count then I dont care if there are messages on the queue as well.

After recieving suggestions from Gary I have changed the implementation to this, and it works.
When manually acknowledging a message it has to be done on the same channel as you get the message. But you can save a reference to it in case you need it in another thread.
In your spring boot application.yml add this

spring:
  rabbitmq:
    listener:
      direct:
        prefetch: 200
      simple:
        prefetch: 200
        acknowledgeMode: MANUAL

Code from the consumer.

//The list we build and save in one transaction
    private Set<PayloadDto> unhandledPayloads = new HashSet<>();
    private long latestTag = 0L;
    private Channel latestChannel;

    @RabbitListener(queues = QUEUE_NAME, id = "consumerId")
    public void recieve(Message message, Channel channel) throws IOException {
        PayloadDto payloadDto = parse(message.getBody());

        unhandledPayloads.add(payloadDto);
        latestTag = message.getMessageProperties().getDeliveryTag();
        latestChannel = channel;
        if (unhandledPayloads.size() > UNHANDLED_PAYLOADS_LIMIT) {
            service.createOrUpdate(unhandledPayloads);
            queue.clear();
            channel.basicAck(latestTag, true);
        }
    }

    @EventListener(condition = "event.listenerId == 'consumerId'")
    public void onApplicationEvent(ListenerContainerIdleEvent event) {
        if(!queue.isEmpty()) {
            service.createOrUpdate(unhandledPayloads);
            queue.clear();
            latestChannel.basicAck(latestTag, true);
        }

    }

The reason we are trying to build up a list before saving it is to be able to do batch insert to make it run faster.


问:
ASP.NET MVC Forms authentication against external web service
I am trying to write an ASP.NET MVC application which is a frontend to our CRM which has a SOAP web service. I would like the user to log in to my web application using their CRM username and password, and then authenticate against CRM, make web service calls on the pages etc.

I started to look at using Forms Authentication and implementing a custom membership provider - I can implement all the methods I need to like ValidateUser(), but the problem I have is that after logging in to the CRM web service you are given a token which has to be passed with every subsequent web service call, and I am not sure where I can store this.

So my questions are:

is Forms Authentication the way to go here, or is it going to be more straightforward to handle all of the authentication myself and store the token in Session.

If Forms Authentication is the way to go, where and how should I store additional information like this. It seems likes using Forms Authentication but then ramming a load of additional information (which is related to authentication) into a cookie or session outside this would be a bit of a mess?

Any advice would be appreciated

答:
You can store the authentication token in the userData part of the forms authentication cookie. This way it will be available on each request.

So for example once you verify the credentials of a user you could query the web service to obtain the token and manually create and emit the forms authentication cookie:

```<code>[HttpPost]
public ActionResult LogOn(string username, string password)
{
    // TODO: verify username/password, obtain token, ...
    // and if everything is OK generate the authentication cookie like this:

    var authTicket = new FormsAuthenticationTicket(
        2,
        username,
        DateTime.Now,
        DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
        false,
        "some token that will be used to access the web service and that you have fetched"
    );
    var authCookie = new HttpCookie(
        FormsAuthentication.FormsCookieName,
        FormsAuthentication.Encrypt(authTicket)
    )
    {
        HttpOnly = true
    };
    Response.AppendCookie(authCookie);

    // ... redirect
}
</code>```

Then you could write a custom authorize attribute which will read this information and set a custom generic identity:

```<code>[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthenticated = base.AuthorizeCore(httpContext);
        if (isAuthenticated)
        {
            string cookieName = FormsAuthentication.FormsCookieName;
            if (!httpContext.User.Identity.IsAuthenticated ||
                httpContext.Request.Cookies == null ||
                httpContext.Request.Cookies[cookieName] == null)
            {
                return false;
            }

            var authCookie = httpContext.Request.Cookies[cookieName];
            var authTicket = FormsAuthentication.Decrypt(authCookie.Value);

            // This is where you can read the userData part of the authentication
            // cookie and fetch the token
            string webServiceToken = authTicket.UserData;

            IPrincipal userPrincipal = ... create some custom implementation
                                           and store the web service token as property

            // Inject the custom principal in the HttpContext
            httpContext.User = userPrincipal;
        }
        return isAuthenticated;
    }
}
</code>```

Finally decorate your controllers/actions that require authentication with this attribute:

```<code>[MyAuthorize]
public ActionResult Foo()
{
    // HttpContext.User will represent the custom principal you created
    // and it will contain the web service token that you could use to
    // query the remote service
    ...
}
</code>```

Body:
You can store the authentication token in the userData part of the forms authentication cookie. This way it will be available on each request.

So for example once you verify the credentials of a user you could query the web service to obtain the token and manually create and emit the forms authentication cookie:

[HttpPost]
public ActionResult LogOn(string username, string password)
{
    // TODO: verify username/password, obtain token, ...
    // and if everything is OK generate the authentication cookie like this:

    var authTicket = new FormsAuthenticationTicket(
        2,
        username,
        DateTime.Now,
        DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
        false,
        "some token that will be used to access the web service and that you have fetched"
    );
    var authCookie = new HttpCookie(
        FormsAuthentication.FormsCookieName,
        FormsAuthentication.Encrypt(authTicket)
    )
    {
        HttpOnly = true
    };
    Response.AppendCookie(authCookie);

    // ... redirect
}

Then you could write a custom authorize attribute which will read this information and set a custom generic identity:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthenticated = base.AuthorizeCore(httpContext);
        if (isAuthenticated)
        {
            string cookieName = FormsAuthentication.FormsCookieName;
            if (!httpContext.User.Identity.IsAuthenticated ||
                httpContext.Request.Cookies == null ||
                httpContext.Request.Cookies[cookieName] == null)
            {
                return false;
            }

            var authCookie = httpContext.Request.Cookies[cookieName];
            var authTicket = FormsAuthentication.Decrypt(authCookie.Value);

            // This is where you can read the userData part of the authentication
            // cookie and fetch the token
            string webServiceToken = authTicket.UserData;

            IPrincipal userPrincipal = ... create some custom implementation
                                           and store the web service token as property

            // Inject the custom principal in the HttpContext
            httpContext.User = userPrincipal;
        }
        return isAuthenticated;
    }
}

Finally decorate your controllers/actions that require authentication with this attribute:

[MyAuthorize]
public ActionResult Foo()
{
    // HttpContext.User will represent the custom principal you created
    // and it will contain the web service token that you could use to
    // query the remote service
    ...
}


问:
Is a bat file an application?
I'm trying to get my head around a DLL load library problem. The Windows Dynamic-Link Library Search Order is supposed to be

```<code>Memory
Known DLL's
Application Directory
System Directory
...etc,
</code>```

as discussed at https://learn.microsoft.com/en-us/windows/desktop/dlls/dynamic-link-library-search-order and at many other places.

When I run a Windows Executable (Desktop Application) from a Batch file, does it inherit the 'application' folder from the Batch File?  (Because I'm running out of other explanations)

答:
Nope, you can't consider a batch file an application at all.
It's more like a script, as it needs to be run through an actual application/executable program (like the DOS runtime, or CMD on Windows)

You can setup environment variables much like in old DOS times (if you need to define a Paths variable) through sysdm.cpl, but I'm not sure that would help for DLL searching

Title: Is a bat file an application?

Body:
I'm trying to get my head around a DLL load library problem. The Windows Dynamic-Link Library Search Order is supposed to be

Memory
Known DLL's
Application Directory
System Directory
...etc,

as discussed at https://learn.microsoft.com/en-us/windows/desktop/dlls/dynamic-link-library-search-order and at many other places.

When I run a Windows Executable (Desktop Application) from a Batch file, does it inherit the 'application' folder from the Batch File?  (Because I'm running out of other explanations)


问:
OpenSSL not creating a key file from a RSA private key
I'm following this guide in order to set up Continuous Integration for my Salesforce development. It says to create a RSA private key and from this create a key file and after that generate a certificate. But I get some errors and cant find my answer online.

image of commands

As seen in the image I tried openssl genrsa -des3 -passout pass:x -out server.pass.key 2048 and get the following error.

Generating RSA private key, 2048 bit long modulus (2 primes)
....+++++
.......................+++++
e is 65537 (0x010001)
484:error:28078065:UI routines:UI_set_result_ex:result too small:crypto/ui/ui_lib.c:903:You must type in 4 to 1023 characters
484:error:28078065:UI routines:UI_set_result_ex:result too small:crypto/ui/ui_lib.c:903:You must type in 4 to 1023 characters
484:error:0906906F:PEM routines:PEM_ASN1_write_bio:read key:crypto/pem/pem_lib.c:357:

I figured 2048 was a to big number (dont know why) so I used openssl genrsa -des3 -passout pass:x -out server.pass.key 1023 and it worked with the following as result.

Generating RSA private key, 1023 bit long modulus (2 primes)
................................................+++++
.......................+++++
e is 65537 (0x010001)

When trying to create a key from the RSA private key with this command openssl rsa -passin pass:x -in server.pass.key -out server.key I got another error saying it is unable to load the private key. This was the output.

unable to load Private Key
20536:error:28078065:UI routines:UI_set_result_ex:result too small:crypto/ui/ui_lib.c:903:You must type in 4 to 1023 characters
20536:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:crypto/evp/evp_enc.c:570:
20536:error:0906A065:PEM routines:PEM_do_header:bad decrypt:crypto/pem/pem_lib.c:461:

This is the file that was created:

```<code>Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,647BC276259FFAB6

UZaGpWtLuxhhU5bFNpYMcbb2pZcmPccQOfyLeJ555oECpv7sd2qNaZn1dQOZaahy
nGDLZdOtHZ6rKZD2jZ99HcxDS9sdys9JRNHXo4fzEJb3q7Qo+rMwFyiL1NVVmkUL
+ib9FifiFdKB+WCza18dAQEGaMA0af7InrMo86wBlP1Qn6oU4kvaxG2JY1zqu1BG
NBVUyQB1NEhzeEYs4acXWT7mSW+blkofzycGlQ24eaBP/SMtP+qACPsJ2aL6vc8j
ofK7GT6vmL1TYebHD4fBTNuTVFNSZx1WkZNBUwAW9LSnxfBXE62bVoqxlaXuFBJW
+xUZ/Y8V3Hnlz5n7nsXieMN7xMMfelt11yFH3qOSvZYao+8XfsQMDSIeTtEaqVhc
veBfL9UGkM0ePgEN8Ewdxau9clDbPBphfi0UIJfS+MJKixmykTIYepBU2HIjHjdZ
co2nOIb7DgIsTKzf3Lec5PPmZRXMAGa1cPq1qLLnga6BA/pz9UMtkKuzJX7q+OoI
pcp1WRTN6Pwavm7mrdGmaiU/VHVGuC4KKdIquQ7iIlsy4s/YD5bVzWxVpAFDsyZ7
IRGI0Ac+0+1h2jm3XctYGFRm6FueOg2XuDHgF3E0W9XrZ1rMTLP27N8gSw4AIFi9
Nu035TlvADkR5EJUZq6YQrne7Yp7cS8yEuZ/eJfWDgKJ6MuHHky5iVOZivyQkL1X
FYNi4NF6QHImZdQUJ0n+on8xlG501ZpCrjCMk/GoY/VdgMWZz90Ri6x1f8TdVk5O
UY6CuBsMcWUV6WwIBeVV0oiAlyBb7JsmevHXfU77ep4=
-----END RSA PRIVATE KEY-----```
```

答:
The password is too short for the version of openssl you are using. It appears to require at least 4 characters. Try this instead:

```<code>openssl genrsa -des3 -passout pass:xxxx -out server.pass.key 2048
</code>```

Of course that is not a good password, but if it works, that will confirm the cause of the error message you received. On decryption, use the longer password, too:

```<code>openssl rsa -passin pass:xxxx -in server.pass.key -out server.key
</code>```

Body:
I'm following this guide in order to set up Continuous Integration for my Salesforce development. It says to create a RSA private key and from this create a key file and after that generate a certificate. But I get some errors and cant find my answer online.

image of commands

As seen in the image I tried openssl genrsa -des3 -passout pass:x -out server.pass.key 2048 and get the following error.

Generating RSA private key, 2048 bit long modulus (2 primes)
....+++++
.......................+++++
e is 65537 (0x010001)
484:error:28078065:UI routines:UI_set_result_ex:result too small:crypto/ui/ui_lib.c:903:You must type in 4 to 1023 characters
484:error:28078065:UI routines:UI_set_result_ex:result too small:crypto/ui/ui_lib.c:903:You must type in 4 to 1023 characters
484:error:0906906F:PEM routines:PEM_ASN1_write_bio:read key:crypto/pem/pem_lib.c:357:

I figured 2048 was a to big number (dont know why) so I used openssl genrsa -des3 -passout pass:x -out server.pass.key 1023 and it worked with the following as result.

Generating RSA private key, 1023 bit long modulus (2 primes)
................................................+++++
.......................+++++
e is 65537 (0x010001)

When trying to create a key from the RSA private key with this command openssl rsa -passin pass:x -in server.pass.key -out server.key I got another error saying it is unable to load the private key. This was the output.

unable to load Private Key
20536:error:28078065:UI routines:UI_set_result_ex:result too small:crypto/ui/ui_lib.c:903:You must type in 4 to 1023 characters
20536:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:crypto/evp/evp_enc.c:570:
20536:error:0906A065:PEM routines:PEM_do_header:bad decrypt:crypto/pem/pem_lib.c:461:

This is the file that was created:

Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,647BC276259FFAB6

UZaGpWtLuxhhU5bFNpYMcbb2pZcmPccQOfyLeJ555oECpv7sd2qNaZn1dQOZaahy
nGDLZdOtHZ6rKZD2jZ99HcxDS9sdys9JRNHXo4fzEJb3q7Qo+rMwFyiL1NVVmkUL
+ib9FifiFdKB+WCza18dAQEGaMA0af7InrMo86wBlP1Qn6oU4kvaxG2JY1zqu1BG
NBVUyQB1NEhzeEYs4acXWT7mSW+blkofzycGlQ24eaBP/SMtP+qACPsJ2aL6vc8j
ofK7GT6vmL1TYebHD4fBTNuTVFNSZx1WkZNBUwAW9LSnxfBXE62bVoqxlaXuFBJW
+xUZ/Y8V3Hnlz5n7nsXieMN7xMMfelt11yFH3qOSvZYao+8XfsQMDSIeTtEaqVhc
veBfL9UGkM0ePgEN8Ewdxau9clDbPBphfi0UIJfS+MJKixmykTIYepBU2HIjHjdZ
co2nOIb7DgIsTKzf3Lec5PPmZRXMAGa1cPq1qLLnga6BA/pz9UMtkKuzJX7q+OoI
pcp1WRTN6Pwavm7mrdGmaiU/VHVGuC4KKdIquQ7iIlsy4s/YD5bVzWxVpAFDsyZ7
IRGI0Ac+0+1h2jm3XctYGFRm6FueOg2XuDHgF3E0W9XrZ1rMTLP27N8gSw4AIFi9
Nu035TlvADkR5EJUZq6YQrne7Yp7cS8yEuZ/eJfWDgKJ6MuHHky5iVOZivyQkL1X
FYNi4NF6QHImZdQUJ0n+on8xlG501ZpCrjCMk/GoY/VdgMWZz90Ri6x1f8TdVk5O
UY6CuBsMcWUV6WwIBeVV0oiAlyBb7JsmevHXfU77ep4=
-----END RSA PRIVATE KEY-----```

Body:
The password is too short for the version of openssl you are using. It appears to require at least 4 characters. Try this instead:

openssl genrsa -des3 -passout pass:xxxx -out server.pass.key 2048

Of course that is not a good password, but if it works, that will confirm the cause of the error message you received. On decryption, use the longer password, too:

openssl rsa -passin pass:xxxx -in server.pass.key -out server.key


问:
Yii2 console: How to disable color output in command via command line?
I like to have colors in output of my Yii2 console commands but in a special scenario I'm using it in a terminal that doesn't support colors and it looks all weird. Isn't there a command line option I can disable colors with?</p>

答:
You can use --color switch:

```<code>./yii my-command --color=0
</code>```

Body:
You can use --color switch:

./yii my-command --color=0


问:
Mongo query Limit not showing in operation
I`m using MongoDB.Driver for .NET to query Mongo(Version 3.0.11).  This is my code to query a field  and limit the query to 200 documents.

```<code>BsonDocument bson = new BsonDocument();
bson.Add("Field", "Value");
BsonDocumentFilterDefinition<ResultClass> filter      = new BsonDocumentFilterDefinition<ResultClass>(bson);
FindOptions                               queryOptions    = new FindOptions() { BatchSize = 200 };
List<ResultClass> result = new List<ResultClass>();
result.AddRange(myCollection.Find<ResultClass>(filter, queryOptions).Limit(200).ToList());
</code>```

My issue is that when I check the database`s current operations, the operation query field shows only :

{ Field : "Value" }

Which is different from the query using "AsQueryable" below:

```<code>List<ResultClass> result = myCollection.AsQueryable<ResultClass>().Where(t => t.Field == "Value").Take(200)
</code>```

Query operation using "AsQueryable"

{ aggregate: "CollectionName", pipeline: [ { $match: { Field:
  "Value" } }, { $limit: 200 } ], cursor: {} }

Why can't I see the limit in the query using Find?Is the limit being handled in the client side instead of the server?
I need to limit this in the server side but I can't use the second query because the field searched needs to be a string which can't be done using AsQueryable.

答:
Using limit in the first piece of code executes the limit on a cursor object, which is still serverside until you actually request the document by invoking ToList(). At which point only 200 documents will go over the wire to your application.

It looks like the AsQueryable is executing an aggregation pipeline which will show up in currentOp, but both are essentially the same.

I'm not sure if there is a performance impact for either one though

Body:
I`m using MongoDB.Driver for .NET to query Mongo(Version 3.0.11).  This is my code to query a field  and limit the query to 200 documents.

BsonDocument bson = new BsonDocument();
bson.Add("Field", "Value");
BsonDocumentFilterDefinition<ResultClass> filter      = new BsonDocumentFilterDefinition<ResultClass>(bson);
FindOptions                               queryOptions    = new FindOptions() { BatchSize = 200 };
List<ResultClass> result = new List<ResultClass>();
result.AddRange(myCollection.Find<ResultClass>(filter, queryOptions).Limit(200).ToList());

My issue is that when I check the database`s current operations, the operation query field shows only :

{ Field : "Value" }

Which is different from the query using "AsQueryable" below:

List<ResultClass> result = myCollection.AsQueryable<ResultClass>().Where(t => t.Field == "Value").Take(200)

Query operation using "AsQueryable"

{ aggregate: "CollectionName", pipeline: [ { $match: { Field:
  "Value" } }, { $limit: 200 } ], cursor: {} }

Why can't I see the limit in the query using Find?Is the limit being handled in the client side instead of the server?
I need to limit this in the server side but I can't use the second query because the field searched needs to be a string which can't be done using AsQueryable.


问:
Match capture group to given pattern in pandas column
I have a DataFrame 'tdf' with a column "Cars" where the values are 4 letters and then 1-6 numbers.

```<code>Cars
JAXT450678
KYXS 56746
LMOP01456
...
</code>```

I have compiled the regex to match it:

 r'(?=[a-zA-Z]{4}\s*\d{1,6}\b)([a-zA-Z]{4})(\s?\d+)'

What I want to do is strip the whitespace out and then make sure that if there are less than 6 digits in the second group, insert 0's starting at the second group until a count of 6 is reached, such that the result is:

```<code>Cars
JAXT450678
KYXS056746
LMOP001456
...
</code>```

Any help is appreciated. I have tried playing around with .replace and .sub and can get it to replace the entire match, but I don't know how to reference the group and have it dynamically match.

tdf = tdf.replace(r'(?=[a-zA-Z]{4}\s*\d{1,6}\b)([a-zA-Z]{4})(\s?\d+)','000000', regex = True)

答:
Not quite a one-liner, but you can avoid apply:

```<code>s = df.Cars.str.slice(4).str.strip().str.zfill(6)
df.Cars.str.slice(0,4) + s
</code>```

Output:

```<code>0    JAXT450678
1    KYXS056746
2    LMOP001456
Name: Cars, dtype: object
</code>```

Body:
I have a DataFrame 'tdf' with a column "Cars" where the values are 4 letters and then 1-6 numbers.

Cars
JAXT450678
KYXS 56746
LMOP01456
...

I have compiled the regex to match it:

 r'(?=[a-zA-Z]{4}\s*\d{1,6}\b)([a-zA-Z]{4})(\s?\d+)'

What I want to do is strip the whitespace out and then make sure that if there are less than 6 digits in the second group, insert 0's starting at the second group until a count of 6 is reached, such that the result is:

Cars
JAXT450678
KYXS056746
LMOP001456
...

Any help is appreciated. I have tried playing around with .replace and .sub and can get it to replace the entire match, but I don't know how to reference the group and have it dynamically match.

tdf = tdf.replace(r'(?=[a-zA-Z]{4}\s*\d{1,6}\b)([a-zA-Z]{4})(\s?\d+)','000000', regex = True)

Body:
Not quite a one-liner, but you can avoid apply:

s = df.Cars.str.slice(4).str.strip().str.zfill(6)
df.Cars.str.slice(0,4) + s

Output:

0    JAXT450678
1    KYXS056746
2    LMOP001456
Name: Cars, dtype: object


问:
Modify scheduler timing dynamically based on the condition used with spring-boot @Scheduled annotation
I have a scheduler, which triggers at a fixed delay of 5secs. I am planning to have more than one schedulers, but for now, let's stick to just one scheduler.

Requirement: Based on business condition scheduler's fixedDelay should be changed (e.g, default fixedDelay is 5secs, but it can be 6, 8, 10secs, based on condition).

In order to achieve this, I am trying to modify the fixedDelay. But it's not working for me.

Interface, with delay methods

```<code>public abstract class DynamicSchedule{
        /**
         * Delays scheduler
         * @param milliseconds - the time to delay scheduler.
         */
        abstract void delay(Long milliseconds);

        /**
         * Decreases delay period
         * @param milliseconds - the time to decrease delay period.
         */
        abstract void decreaseDelayInterval(Long milliseconds);

        /**
         * Increases delay period
         * @param milliseconds - the time to increase dela period
        */
        abstract void increaseDelayInterval(Long milliseconds);
}
</code>```

Implementating Trigger interface that is located at org.springframework.scheduling in the spring-context project.

```<code>import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

public class CustomDynamicSchedule extends DynamicSchedule implements Trigger {

    private TaskScheduler taskScheduler;
    private ScheduledFuture<?> schedulerFuture;

    /**
     * milliseconds
     */
    private long delayInterval;

    public CustomDynamicSchedule(TaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
    }

    @Override
    public void increaseDelayInterval(Long delay) {
        if (schedulerFuture != null) {
            schedulerFuture.cancel(true);
        }
        this.delayInterval += delay;
        schedulerFuture = taskScheduler.schedule(() -> { }, this);
    }

    @Override
    public void decreaseDelayInterval(Long delay) {
        if (schedulerFuture != null) {
            schedulerFuture.cancel(true);
        }
        this.delayInterval += delay;
        schedulerFuture = taskScheduler.schedule(() -> { }, this);
    }

    @Override
    public void delay(Long delay) {
        if (schedulerFuture != null) {
            schedulerFuture.cancel(true);
        }
        this.delayInterval = delay;
        schedulerFuture = taskScheduler.schedule(() -> { }, this);
    }

    @Override
    public Date nextExecutionTime(TriggerContext triggerContext) {
        Date lastTime = triggerContext.lastActualExecutionTime();
        return (lastTime == null) ? new Date() : new Date(lastTime.getTime() + delayInterval);
    }
}
</code>```

configuration:

```<code>@Configuration
public class DynamicSchedulerConfig {
    @Bean
    public CustomDynamicSchedule getDinamicScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.initialize();
        return  new CustomDynamicSchedule(threadPoolTaskScheduler);
    }
}
</code>```

Test class, to test the usage.

```<code>@EnableScheduling
@Component
public class TestSchedulerComponent {

    @Autowired
    private CustomDynamicSchedule dynamicSchedule;

    @Scheduled(fixedDelay = 5000)
    public void testMethod() {
        dynamicSchedule.delay(1000l);
        dynamicSchedule.increaseDelayInterval(9000l);
        dynamicSchedule.decreaseDelayInterval(5000l);
    }

}
</code>```

I have tried to use https://stackoverflow.com/a/51333059/4770397 but this code is not working for me.

Scheduler is running at fixedDelay, there is no change in that.

答:
Using @Scheduled will only allow to use static schedules. You can use properties to make the schedule configruable like this

```<code>@Scheduled(cron = "${yourConfiguration.cronExpression}")

// or

@Scheduled(fixedDelayString = "${yourConfiguration.fixedDelay}")
</code>```

However the resulting schedule will be fixed once your spring context is initialized (the application is started).

To get fine grained control over a scheduled execution you need implement a custom Trigger - similar to what you already did. Together with the to be executed task, this trigger can be registered by implementing SchedulingConfigurer in your @Configuration class using ScheduledTaskRegistrar.addTriggerTask:

```<code>@Configuration
@EnableScheduling
public class AppConfig implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskScheduler());
        taskRegistrar.addTriggerTask(() -> myTask().work(), myTrigger());
    }

    @Bean(destroyMethod="shutdown")
    public Executor taskScheduler() {
        return Executors.newScheduledThreadPool(42);
    }

    @Bean
    public CustomDynamicSchedule myTrigger() {
        new CustomDynamicSchedule();
    }

    @Bean
    public MyTask myTask() {
        return new MyTask();
    }
}
</code>```

But don't do any registration of a task in the CustomDynamicSchedule just use it to compute the next execution time:

```<code>public class CustomDynamicSchedule extends DynamicSchedule implements Trigger {

    private long delayInterval;

    @Override
    public synchronized void increaseDelayInterval(Long delay) {
        this.delayInterval += delay;
    }

    @Override
    public synchronized void decreaseDelayInterval(Long delay) {
        this.delayInterval += delay;
    }

    @Override
    public synchronized void delay(Long delay) {
        this.delayInterval = delay;
    }

    @Override
    public Date nextExecutionTime(TriggerContext triggerContext) {
        Date lastTime = triggerContext.lastActualExecutionTime();
        return (lastTime == null) ? new Date() : new Date(lastTime.getTime() + delayInterval);
    }
}
</code>```

But remember to make CustomDynamicSchedule thread safe as it will be created as singleton by spring and might be accessed by multiple threads in parallel.

Body:
I have a scheduler, which triggers at a fixed delay of 5secs. I am planning to have more than one schedulers, but for now, let's stick to just one scheduler.

Requirement: Based on business condition scheduler's fixedDelay should be changed (e.g, default fixedDelay is 5secs, but it can be 6, 8, 10secs, based on condition).

In order to achieve this, I am trying to modify the fixedDelay. But it's not working for me.

Interface, with delay methods

public abstract class DynamicSchedule{
        /**
         * Delays scheduler
         * @param milliseconds - the time to delay scheduler.
         */
        abstract void delay(Long milliseconds);

        /**
         * Decreases delay period
         * @param milliseconds - the time to decrease delay period.
         */
        abstract void decreaseDelayInterval(Long milliseconds);

        /**
         * Increases delay period
         * @param milliseconds - the time to increase dela period
        */
        abstract void increaseDelayInterval(Long milliseconds);
}

Implementating Trigger interface that is located at org.springframework.scheduling in the spring-context project.

import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

public class CustomDynamicSchedule extends DynamicSchedule implements Trigger {

    private TaskScheduler taskScheduler;
    private ScheduledFuture<?> schedulerFuture;

    /**
     * milliseconds
     */
    private long delayInterval;

    public CustomDynamicSchedule(TaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
    }

    @Override
    public void increaseDelayInterval(Long delay) {
        if (schedulerFuture != null) {
            schedulerFuture.cancel(true);
        }
        this.delayInterval += delay;
        schedulerFuture = taskScheduler.schedule(() -> { }, this);
    }

    @Override
    public void decreaseDelayInterval(Long delay) {
        if (schedulerFuture != null) {
            schedulerFuture.cancel(true);
        }
        this.delayInterval += delay;
        schedulerFuture = taskScheduler.schedule(() -> { }, this);
    }

    @Override
    public void delay(Long delay) {
        if (schedulerFuture != null) {
            schedulerFuture.cancel(true);
        }
        this.delayInterval = delay;
        schedulerFuture = taskScheduler.schedule(() -> { }, this);
    }

    @Override
    public Date nextExecutionTime(TriggerContext triggerContext) {
        Date lastTime = triggerContext.lastActualExecutionTime();
        return (lastTime == null) ? new Date() : new Date(lastTime.getTime() + delayInterval);
    }
}

configuration:

@Configuration
public class DynamicSchedulerConfig {
    @Bean
    public CustomDynamicSchedule getDinamicScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.initialize();
        return  new CustomDynamicSchedule(threadPoolTaskScheduler);
    }
}

Test class, to test the usage.

@EnableScheduling
@Component
public class TestSchedulerComponent {

    @Autowired
    private CustomDynamicSchedule dynamicSchedule;

    @Scheduled(fixedDelay = 5000)
    public void testMethod() {
        dynamicSchedule.delay(1000l);
        dynamicSchedule.increaseDelayInterval(9000l);
        dynamicSchedule.decreaseDelayInterval(5000l);
    }

}

I have tried to use https://stackoverflow.com/a/51333059/4770397 but this code is not working for me.

Scheduler is running at fixedDelay, there is no change in that.

Body:
Using @Scheduled will only allow to use static schedules. You can use properties to make the schedule configruable like this

@Scheduled(cron = "${yourConfiguration.cronExpression}")

// or

@Scheduled(fixedDelayString = "${yourConfiguration.fixedDelay}")

However the resulting schedule will be fixed once your spring context is initialized (the application is started).

To get fine grained control over a scheduled execution you need implement a custom Trigger - similar to what you already did. Together with the to be executed task, this trigger can be registered by implementing SchedulingConfigurer in your @Configuration class using ScheduledTaskRegistrar.addTriggerTask:

@Configuration
@EnableScheduling
public class AppConfig implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskScheduler());
        taskRegistrar.addTriggerTask(() -> myTask().work(), myTrigger());
    }

    @Bean(destroyMethod="shutdown")
    public Executor taskScheduler() {
        return Executors.newScheduledThreadPool(42);
    }

    @Bean
    public CustomDynamicSchedule myTrigger() {
        new CustomDynamicSchedule();
    }

    @Bean
    public MyTask myTask() {
        return new MyTask();
    }
}

But don't do any registration of a task in the CustomDynamicSchedule just use it to compute the next execution time:

public class CustomDynamicSchedule extends DynamicSchedule implements Trigger {

    private long delayInterval;

    @Override
    public synchronized void increaseDelayInterval(Long delay) {
        this.delayInterval += delay;
    }

    @Override
    public synchronized void decreaseDelayInterval(Long delay) {
        this.delayInterval += delay;
    }

    @Override
    public synchronized void delay(Long delay) {
        this.delayInterval = delay;
    }

    @Override
    public Date nextExecutionTime(TriggerContext triggerContext) {
        Date lastTime = triggerContext.lastActualExecutionTime();
        return (lastTime == null) ? new Date() : new Date(lastTime.getTime() + delayInterval);
    }
}

But remember to make CustomDynamicSchedule thread safe as it will be created as singleton by spring and might be accessed by multiple threads in parallel.


问:
Dealing with SVN keyword expansion with git-svn
I recently asked about keyword expansion in Git and I'm willing to accept the design not to really support this idea in Git.

For better or worse, the project I'm working on at the moment requires SVN keyword expansion like this:

```<code>svn propset svn:keywords "Id" expl3.dtx
</code>```

to keep this string up-to-date:

```<code>$Id: expl3.dtx 803 2008-09-11 14:01:58Z will $
</code>```

But I would quite like to use Git to do my version control. Unfortunately, git-svn doesn't support this, according to the docs:

"We ignore all SVN properties except svn:executable"

But it doesn't seem too tricky to have this keyword stuff emulated by a couple of pre/post commit hooks. Am I the first person to want this? Does anyone have some code to do this?

答:
Here is a sample project containing the configuration and filter code needed for adding RCS keyword support to a git project:

https://github.com/turon/git-rcs-keywords

It's not as simple to setup as one would like, but it seems to work.  It uses a smudge/clean filter pair written in perl (similar to what emk's answer described), and yes, it will touch all files with the extensions set in .gitattributes, generally slowing things down a bit.

OwnerDisplayName: Will Robertson

Body:
I recently asked about keyword expansion in Git and I'm willing to accept the design not to really support this idea in Git.

For better or worse, the project I'm working on at the moment requires SVN keyword expansion like this:

svn propset svn:keywords "Id" expl3.dtx

to keep this string up-to-date:

$Id: expl3.dtx 803 2008-09-11 14:01:58Z will $

But I would quite like to use Git to do my version control. Unfortunately, git-svn doesn't support this, according to the docs:

"We ignore all SVN properties except svn:executable"

But it doesn't seem too tricky to have this keyword stuff emulated by a couple of pre/post commit hooks. Am I the first person to want this? Does anyone have some code to do this?

LastEditorDisplayName: Will Robertson