答:
Given your code,

```<code>list myListWierd;
myListWierd.sortAppend(2);
myListWierd.sortAppend(4);
myListWierd.sortAppend(5);
myListWierd.show();
</code>```

shows

```<code>2
5
</code>```

so the sortAppend does not work.

The trouble is around updating either the tail, since  operator + relies on using the tail.

I could sort the code out for you and make it work; indeed Andreas' answer does this. But for now, notice you have assumed a function works, but I found a case it doesn't work for by looking at the moving parts - a list we created, that we then try to re-create in a different order. As a general rule, try all the parts in a function that goes wrong, one at a time, maybe as a unit test.

Rather than fixing this, for now, let's make a couple of suggestions.

First, the destructor does nothing, other than walk pointers (using empty which uses head and not tail - so head needs setting as said before)

```<code>~list() { while (!empty()) { (*this)--; } }
</code>```

If you don't want leaks you need to give this more thought.

Next,

```<code>list& operator+(list&, list&)
</code>```

creates a pointer and returns its contents. This is a BAD IDEA. NEVER DO THIS.

For now, change the signature to

```<code>list operator+(list&, list&);
</code>```

and just return a list:

```<code>list operator+(list& X, list& Y) {
    list* tempListArr[2] = { &X, &Y };
    list tempList;//copy it over to the calling vode otherwise DANGER
    for (const list* i : tempListArr)
    {
        element* tempHead = (i->inf).head;
        while (tempHead != nullptr) {
            tempList.sortAppend(tempHead->value);
            std::cout << "Adding " << tempHead->value << '\n';
            tempHead = tempHead->next;
        }
        tempList.show();
        std::cout << "--\n";
    }
    return tempList;
}
</code>```

Title: List implementation does not sum lists correctly

Body:
Given your code,

list myListWierd;
myListWierd.sortAppend(2);
myListWierd.sortAppend(4);
myListWierd.sortAppend(5);
myListWierd.show();

shows

2
5

so the sortAppend does not work.

The trouble is around updating either the tail, since  operator + relies on using the tail.

I could sort the code out for you and make it work; indeed Andreas' answer does this. But for now, notice you have assumed a function works, but I found a case it doesn't work for by looking at the moving parts - a list we created, that we then try to re-create in a different order. As a general rule, try all the parts in a function that goes wrong, one at a time, maybe as a unit test.

Rather than fixing this, for now, let's make a couple of suggestions.

First, the destructor does nothing, other than walk pointers (using empty which uses head and not tail - so head needs setting as said before)

~list() { while (!empty()) { (*this)--; } }

If you don't want leaks you need to give this more thought.

Next,

list& operator+(list&, list&)

creates a pointer and returns its contents. This is a BAD IDEA. NEVER DO THIS.

For now, change the signature to

list operator+(list&, list&);

and just return a list:

list operator+(list& X, list& Y) {
    list* tempListArr[2] = { &X, &Y };
    list tempList;//copy it over to the calling vode otherwise DANGER
    for (const list* i : tempListArr)
    {
        element* tempHead = (i->inf).head;
        while (tempHead != nullptr) {
            tempList.sortAppend(tempHead->value);
            std::cout << "Adding " << tempHead->value << '\n';
            tempHead = tempHead->next;
        }
        tempList.show();
        std::cout << "--\n";
    }
    return tempList;
}


来源: stackexchange

问:
Git workflow for small web team
I know there are already many questions here on this topic, but I've had trouble finding exactly what I need.

We're a small team of developers currently using SVN but soon to be making a switch to Git.  We are used to checking in changes and pushing to the live website throughout the day but currently lack any formal testing procedures, which is something we'd like to add.  The way I'm used to doing this with SVN is:

develop in a personal test environment

check in your changes

send the current repository files to a global (production-like) testing webserver, and test

send the current repository files to the live webservers

This obviously can create some problems, especially if communication is not good.  I've experienced times when untested changes have gone live and that's something we'd definitely like to avoid.

What I'm envisioning is a master Git repository that holds the tested code that is running on the live servers.  Then have a clone of that repository that is used to test revisions.  I'd like to have a script that is responsible for pulling changes from the requesting developer, putting them in a branch on the test repository, and running some automated tests to make sure nothing major is broken.  When that all checks out, that branch can be merged and pushed up to the master and out to the live servers.

I'd like to hear any comments about this possible workflow and any suggestions for improvement or how to do it differently.  Also, any specifics on how to set this up would also be appreciated.  Thanks!

EDIT: I've used the above method for a while now and it's worked out pretty well.

答:
Do you really need a separate repository? Your live code is only a single branch; you can use other branches for "deploy candidates" under testing.

You don't necessarily need a script to pull the changes - developers could just push them to a separate branch, then invoke a script to test that branch.

ContentLicense: CC BY-SA 3.0

Title: Git workflow for small web team

ContentLicense: CC BY-SA 2.5


问:
Splitting a list based on another list that contains the indexes that must be filtered
The problem is the following:

I have list of 91 ordered values each representing 1 of 2 possible trials: Pumpindex

I have another list (actually a pandas df) which has 2 columns, one called Left and the other Right. These columns contain the order in which left and right trials came in the first list. (i.e. column Left : 0,1,3,4,6,8... // column Right : 2,5,7,9....)

What i want to do next is split the first list based on their index if its index # is in either the left or Right column lists.

This is the most simple solution i came up with but alas it does not work and only filters out the first 46 left trials regardless of the number in the second list. It only sees that there 46 left trials and takes the first 46 trials from the first list.

```<code> df1 = pd.read_csv("LeftRightrat1.csv")
 df1.columns = ['Left', 'Right']
 Pumpindex = [somelist]
 Leftypump = [x for x in Pumpindex if Pumpindex.index(x) in df1['Left']]
</code>```

What i think i m doing here is: Add x to the list if the index of x is found in the series df1['Left']. So if the numbers 0,1,3,4,6,8 are in the df1[left] then my list would select only the values in Pumpindex that are indexed as 0,1,3,4,6,8. Unfortunately it only gives me 0,1,2,3,4,5...

Where did I go wrong?

答:
If the dataframe contains the indices for the split, why not try</p>

```<code>left = [Pumpindex[x] for x in df1.Left]
right = [Pumpindex[x] for x in df1.Right]
</code>```

Body:
The problem is the following:

I have list of 91 ordered values each representing 1 of 2 possible trials: Pumpindex

I have another list (actually a pandas df) which has 2 columns, one called Left and the other Right. These columns contain the order in which left and right trials came in the first list. (i.e. column Left : 0,1,3,4,6,8... // column Right : 2,5,7,9....)

What i want to do next is split the first list based on their index if its index # is in either the left or Right column lists.

This is the most simple solution i came up with but alas it does not work and only filters out the first 46 left trials regardless of the number in the second list. It only sees that there 46 left trials and takes the first 46 trials from the first list.

 df1 = pd.read_csv("LeftRightrat1.csv")
 df1.columns = ['Left', 'Right']
 Pumpindex = [somelist]
 Leftypump = [x for x in Pumpindex if Pumpindex.index(x) in df1['Left']]

What i think i m doing here is: Add x to the list if the index of x is found in the series df1['Left']. So if the numbers 0,1,3,4,6,8 are in the df1[left] then my list would select only the values in Pumpindex that are indexed as 0,1,3,4,6,8. Unfortunately it only gives me 0,1,2,3,4,5...

Where did I go wrong?

Body:
If the dataframe contains the indices for the split, why not try

left = [Pumpindex[x] for x in df1.Left]
right = [Pumpindex[x] for x in df1.Right]


问:
.htaccess rewrite url get?
```<code>/watch.php?id=1

/watch/1/seo-url-827372
</code>```

and

```<code>/category.php?id=1

/category/1/seo-url-734774
</code>```

I have a server that supports .htaccees how can I implement these rules with rewrite .htaccess

答:
Your usecase is a bit more than just .htaccess - yes, it's possible to do it only with .htaccess but it's stretching it - you would have to write redirects from the top to the bottom URLs(meaning write the hard coded URLs in .htaccess - possible, but not recomended).

More common use case would be to have the seo-url-827372 also in the original URL (something like /watch.php?id=1&url=seo-url-827372) and then use .htaccess to rewrite it.

Have a look here for a nice, detailed explanation (with examples).

Title: .htaccess rewrite url get?

Body:
/watch.php?id=1

/watch/1/seo-url-827372

and

/category.php?id=1

/category/1/seo-url-734774

I have a server that supports .htaccees how can I implement these rules with rewrite .htaccess


问:
Code not functioning with larger lists
I am coding for a problem on project euler. Problem 50 https://projecteuler.net/problem=50

The problem is my code works fine with small lists, specifically a list of primes under a few thousand, however, it fails to work with a list of primes under 1 million (with is around the 80000th prime) which is an issue in getting the answer.

There are two main problems:

It is horrendously slow with larger lists such roughly greater than 20000  (10 - 20mins)

It does not produce the correct answer

Even if the logic is correct and finishes running the answer is incorrect, is this a memory issue? I would like to know why my code only works with smaller data and how to improve my efficiency

Also, if I am asking a bad question let me know.

```<code>def primes(n):

   sieve = [True] * n
    for i in range(3,int(n**0.5) + 1, 2):
        if sieve[i]:
            sieve[i * i :: 2 * i] = [False] * int((n - i * i - 1)/(2 * i) + 1)
    return [2] + [i for i in range(3, n, 2) if sieve[i]]

primes = primes(1000)
start = 0
answer = 0
x = 0
count = y = 2

while len(primes[x:y - 1]) < len(primes):
    summed = sum(primes[x:y])
    length = len(primes[x:y])
    if summed in primes and length > start:
        start = length
        answer = summed
    x += 1
    y += 1
    if y - 1 == len(primes):
        count += 1
        x = 0
        y = count

print(start)
print(answer)
</code>```

答:
As noted in comments, there are a few unneccessary linear complexities in your code, e.g. for determining the number of elements in the current sum, or whether the number is in the list of primes. If you eliminate those, your algorithm becomes much faster.

```<code>p_set = set(primes)  # use a set for lookup
summed = None
while y - 1 - x < len(primes):
    # instead of getting the sublist and the sum, just update the last sum
    summed = sum(primes[x:y]) if summed is None else summed - primes[x-1] + primes[y-1]
    length = y - x  # no need for creating the sublist
    if summed in p_set and length > start:  # lookup in set
        start = length
        answer = summed
        print(start, answer)
    x += 1
    y += 1
    if y - 1 == len(primes):
        count += 1
        x = 0
        y = count
        summed = None  # reset sum
</code>```

But depending on your computer this might still take more than a minute. This is because you first test all the sums of two primes, then all the sums of three primes, etc., by shifting both x and y before increasing the difference between the two.

If, instead, you turn this around, and first look at sums of many small primes, instead of sums of a few large primes, you will quickly find the result -- starting at the third prime!

```<code>max_ = res = 0
for i in range(len(primes)):
    sum_ = primes[i]
    for k in range(i+1, len(primes)):
        sum_ += primes[k]
        if sum_ in p_set and k - (i - 1) > max_:
            max_, res = k - (i - 1), sum_
            print(max_, res, i, k)
        if sum_ > MAX:
            break
</code>```

Title: Code not functioning with larger lists

Body:
I am coding for a problem on project euler. Problem 50 https://projecteuler.net/problem=50

The problem is my code works fine with small lists, specifically a list of primes under a few thousand, however, it fails to work with a list of primes under 1 million (with is around the 80000th prime) which is an issue in getting the answer.

There are two main problems:

It is horrendously slow with larger lists such roughly greater than 20000  (10 - 20mins)

It does not produce the correct answer

Even if the logic is correct and finishes running the answer is incorrect, is this a memory issue? I would like to know why my code only works with smaller data and how to improve my efficiency

Also, if I am asking a bad question let me know.

def primes(n):

   sieve = [True] * n
    for i in range(3,int(n**0.5) + 1, 2):
        if sieve[i]:
            sieve[i * i :: 2 * i] = [False] * int((n - i * i - 1)/(2 * i) + 1)
    return [2] + [i for i in range(3, n, 2) if sieve[i]]

primes = primes(1000)
start = 0
answer = 0
x = 0
count = y = 2

while len(primes[x:y - 1]) < len(primes):
    summed = sum(primes[x:y])
    length = len(primes[x:y])
    if summed in primes and length > start:
        start = length
        answer = summed
    x += 1
    y += 1
    if y - 1 == len(primes):
        count += 1
        x = 0
        y = count

print(start)
print(answer)

Body:
As noted in comments, there are a few unneccessary linear complexities in your code, e.g. for determining the number of elements in the current sum, or whether the number is in the list of primes. If you eliminate those, your algorithm becomes much faster.

p_set = set(primes)  # use a set for lookup
summed = None
while y - 1 - x < len(primes):
    # instead of getting the sublist and the sum, just update the last sum
    summed = sum(primes[x:y]) if summed is None else summed - primes[x-1] + primes[y-1]
    length = y - x  # no need for creating the sublist
    if summed in p_set and length > start:  # lookup in set
        start = length
        answer = summed
        print(start, answer)
    x += 1
    y += 1
    if y - 1 == len(primes):
        count += 1
        x = 0
        y = count
        summed = None  # reset sum

But depending on your computer this might still take more than a minute. This is because you first test all the sums of two primes, then all the sums of three primes, etc., by shifting both x and y before increasing the difference between the two.

If, instead, you turn this around, and first look at sums of many small primes, instead of sums of a few large primes, you will quickly find the result -- starting at the third prime!

max_ = res = 0
for i in range(len(primes)):
    sum_ = primes[i]
    for k in range(i+1, len(primes)):
        sum_ += primes[k]
        if sum_ in p_set and k - (i - 1) > max_:
            max_, res = k - (i - 1), sum_
            print(max_, res, i, k)
        if sum_ > MAX:
            break


问:
Scrapy Crawling 0 pages
New to python and scrapy, whats wrong with the code? I can retrieve the data from scrapy shell but why cannot retrieve in scrapy crawl?

EDIT: I have put the log at below, could you help me check what problem it is?

Problem SOLVED:

This link is incorrect ?price=2-2/

Should be ?price=2-2

quotes.spider.py

```<code>import scrapy
from tutorial.items import TutorialItem

class QuotesSpider(scrapy.Spider):
     name = "quotes"

def start_requests(self):
    urls = [
        'http://www.testing.com.my/?price=2-2/',
    ]
    for url in urls:
        yield scrapy.Request(url=url, callback=self.parse)

def parse(self, response):
    titles = response.xpath('//a[contains(@class, "c-product-card__img-placeholder-inner")]/@href')
    return titles.extract()
</code>```

items.py

```<code>from scrapy.item import Item, Field

class TutorialItem(Item):
    link = Field()
</code>```

Log

```<code>2017-07-05 16:26:52 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: tutorial
)
2017-07-05 16:26:52 [scrapy.utils.log] INFO: Overridden settings: {'BOT_NAME': '
tutorial', 'NEWSPIDER_MODULE': 'tutorial.spiders', 'ROBOTSTXT_OBEY': True, 'SPID
ER_MODULES': ['tutorial.spiders']}
2017-07-05 16:26:52 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.logstats.LogStats']
2017-07-05 16:26:52 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-07-05 16:26:52 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-07-05 16:26:52 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2017-07-05 16:26:52 [scrapy.core.engine] INFO: Spider opened
2017-07-05 16:26:52 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pag
es/min), scraped 0 items (at 0 items/min)
2017-07-05 16:26:52 [scrapy.extensions.telnet] DEBUG: Telnet console listening o
n 127.0.0.1:6023
2017-07-05 16:26:55 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://www.la
zada.com.my/robots.txt> (referer: None)
2017-07-05 16:26:55 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://www.la
zada.com.my/shop-power-banks2/?price=2-2/> (referer: None)
2017-07-05 16:26:55 [scrapy.core.engine] INFO: Closing spider (finished)
2017-07-05 16:26:55 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 596,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
 'downloader/response_bytes': 55953,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 2,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 7, 5, 8, 26, 55, 942385),
 'log_count/DEBUG': 3,
 'log_count/INFO': 7,
 'response_received_count': 2,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2017, 7, 5, 8, 26, 52, 624796)}
2017-07-05 16:26:55 [scrapy.core.engine] INFO: Spider closed (finished)
</code>```

答:
If you want to extract the link for each article, i'd propose something like :

```<code>response.css("a.c-product-card::attr(href)")
</code>```

instead of :

```<code>response.xpath('//a[contains(@class, "c-product-card__img-placeholder-inner")]/@href')
</code>```

Title: Scrapy Crawling 0 pages

Body:
New to python and scrapy, whats wrong with the code? I can retrieve the data from scrapy shell but why cannot retrieve in scrapy crawl?

EDIT: I have put the log at below, could you help me check what problem it is?

Problem SOLVED:

This link is incorrect ?price=2-2/

Should be ?price=2-2

quotes.spider.py

import scrapy
from tutorial.items import TutorialItem

class QuotesSpider(scrapy.Spider):
     name = "quotes"

def start_requests(self):
    urls = [
        'http://www.testing.com.my/?price=2-2/',
    ]
    for url in urls:
        yield scrapy.Request(url=url, callback=self.parse)

def parse(self, response):
    titles = response.xpath('//a[contains(@class, "c-product-card__img-placeholder-inner")]/@href')
    return titles.extract()

items.py

from scrapy.item import Item, Field

class TutorialItem(Item):
    link = Field()

Log

2017-07-05 16:26:52 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: tutorial
)
2017-07-05 16:26:52 [scrapy.utils.log] INFO: Overridden settings: {'BOT_NAME': '
tutorial', 'NEWSPIDER_MODULE': 'tutorial.spiders', 'ROBOTSTXT_OBEY': True, 'SPID
ER_MODULES': ['tutorial.spiders']}
2017-07-05 16:26:52 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.logstats.LogStats']
2017-07-05 16:26:52 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-07-05 16:26:52 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-07-05 16:26:52 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2017-07-05 16:26:52 [scrapy.core.engine] INFO: Spider opened
2017-07-05 16:26:52 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pag
es/min), scraped 0 items (at 0 items/min)
2017-07-05 16:26:52 [scrapy.extensions.telnet] DEBUG: Telnet console listening o
n 127.0.0.1:6023
2017-07-05 16:26:55 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://www.la
zada.com.my/robots.txt> (referer: None)
2017-07-05 16:26:55 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://www.la
zada.com.my/shop-power-banks2/?price=2-2/> (referer: None)
2017-07-05 16:26:55 [scrapy.core.engine] INFO: Closing spider (finished)
2017-07-05 16:26:55 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 596,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
 'downloader/response_bytes': 55953,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 2,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 7, 5, 8, 26, 55, 942385),
 'log_count/DEBUG': 3,
 'log_count/INFO': 7,
 'response_received_count': 2,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2017, 7, 5, 8, 26, 52, 624796)}
2017-07-05 16:26:55 [scrapy.core.engine] INFO: Spider closed (finished)

Body:
If you want to extract the link for each article, i'd propose something like :

response.css("a.c-product-card::attr(href)")

instead of :

response.xpath('//a[contains(@class, "c-product-card__img-placeholder-inner")]/@href')


问:
Best way to represent constraints on values in Scala?
What is the best way to express that, say, an Int field or parameter should never be negative?

The first thing that comes to mind is an annotation on the type, like case class Foo(x: Int @NotNegative). But I'd have to invent my own annotation, and there wouldn't be any sort of compile-time checking or anything.

Is there a better way?

答: Contracts and invariants are not supported by Scala at this time.</p>


问:
How can i get dynamic form field values in angular?
Below i have added dynamic form add and delete after submit i want to get all the form values .how can i do this ?? anyone help me out move forward

this is my jsfiddle link

http://jsfiddle.net/rnnb32rm/1438/

below i added my cod

var app = angular.module('angularjs-starter', []);

  app.controller('MainCtrl', function($scope) {

  $scope.choices = [{id: 'choice1'}];

  $scope.addNewChoice = function() {
    var newItemNo = $scope.choices.length+1;
    $scope.choices.push({'id':'choice'+newItemNo});
  };

  $scope.removeChoice = function() {
    var lastItem = $scope.choices.length-1;
    $scope.choices.splice(lastItem);
  };
  $scope.OnSave = function() {
    console.log('sjs');
  };

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>fieldset{
    background: #FCFCFC;
    padding: 16px;
    border: 1px solid #D5D5D5;
}
.addfields{
    margin: 10px 0;
}

#choicesDisplay {
    padding: 10px;
    background: rgb(227, 250, 227);
    border: 1px solid rgb(171, 239, 171);
    color: rgb(9, 56, 9);
}
.remove{
    background: #C76868;
    color: #FFF;
    font-weight: bold;
    font-size: 21px;
    border: 0;
    cursor: pointer;
    display: inline-block;
    padding: 4px 9px;
    vertical-align: top;
    line-height: 100%;
}
input[type="text"],
select{
    padding:5px;
}</code>```

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

    <button class="addfields" ng-click="addNewChoice()">Add fields</button>

    name
    <input type="text" ng-model="name" name="" placeholder="Add name">

    email
    <input type="text" ng-model="email" name="" placeholder="Add emalil">

    <fieldset data-ng-repeat="choice in choices">

        Add Question

        <input type="text" ng-model="choice.name" name="" placeholder="Add Question">

        Question order
        <input type="text" ng-model="choice.order" name="" placeholder="Add Question order">

        <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
    </fieldset>

    <button type="submit" class="btn btn-primary" ng-click="OnSave()">Submit</button>

        {{ choices }}

```
</div>
</div>
</p>

<p>my expected result :</p>

```{

    "name": "test",
    "email": "asdf@gmail.com",
    "questions": [
        {
            "question": "Which of the following is the most important characteristic for a supervisor?",
            "questionorder": "1",

        },
        {
            "question": "Which of the following is the most important characteristic for a supervisor?",
            "questionorder": "2",

        }
    ]
}
```

答:
```<code>//html
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
<button class="addfields" ng-click="addNewChoice()">Add fields</button><br>
                <label class="control-label col-sm-2">name</label>
                      <input type="text" ng-model="form.name" name="" placeholder="Add name"><br><br>
                <label class="control-label col-sm-2">email</label>
                      <input type="text" ng-model="form.email" name="" placeholder="Add emalil"><br><br>
   <fieldset  data-ng-repeat="choice in choices">

       <label class="control-label col-sm-2">Add Question</label>

                      <input type="text" ng-model="choice.name" name="" placeholder="Add Question"><br><br>

       <label class="control-label col-sm-2">Question order</label>
        <input type="text" ng-model="choice.order" name="" placeholder="Add Question order">

      <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
   </fieldset><br><br>

                <button type="submit" class="btn btn-primary"  ng-click="OnSave(form, choices)">Submit</button><br><br><br>

   <div id="choicesDisplay" ng-repeat="obj in formData">
      {{ obj }}
   </div>
</div>

//js

var app = angular.module('angularjs-starter', []);

  app.controller('MainCtrl', function($scope) {

  $scope.choices = [{id: 'choice1'}];

  $scope.addNewChoice = function() {
    var newItemNo = $scope.choices.length+1;
    $scope.choices.push({'id':'choice'+newItemNo});
  };

  $scope.removeChoice = function() {
    var lastItem = $scope.choices.length-1;
    $scope.choices.splice(lastItem);
  };
  $scope.OnSave = function(form, choice) {
        $scope.formData = [];
      $scope.formData.push ({
        name: form.name,
        email: form.email,
        questions: choice
      });
      console.log($scope.formData);
  };

});
</code>```

Body:
Below i have added dynamic form add and delete after submit i want to get all the form values .how can i do this ?? anyone help me out move forward

this is my jsfiddle link

http://jsfiddle.net/rnnb32rm/1438/

below i added my cod

var app = angular.module('angularjs-starter', []);

  app.controller('MainCtrl', function($scope) {

  $scope.choices = [{id: 'choice1'}];

  $scope.addNewChoice = function() {
    var newItemNo = $scope.choices.length+1;
    $scope.choices.push({'id':'choice'+newItemNo});
  };

  $scope.removeChoice = function() {
    var lastItem = $scope.choices.length-1;
    $scope.choices.splice(lastItem);
  };
  $scope.OnSave = function() {
    console.log('sjs');
  };

});

fieldset{
    background: #FCFCFC;
    padding: 16px;
    border: 1px solid #D5D5D5;
}
.addfields{
    margin: 10px 0;
}

#choicesDisplay {
    padding: 10px;
    background: rgb(227, 250, 227);
    border: 1px solid rgb(171, 239, 171);
    color: rgb(9, 56, 9);
}
.remove{
    background: #C76868;
    color: #FFF;
    font-weight: bold;
    font-size: 21px;
    border: 0;
    cursor: pointer;
    display: inline-block;
    padding: 4px 9px;
    vertical-align: top;
    line-height: 100%;
}
input[type="text"],
select{
    padding:5px;
}

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

    <button class="addfields" ng-click="addNewChoice()">Add fields</button>

    name
    <input type="text" ng-model="name" name="" placeholder="Add name">

    email
    <input type="text" ng-model="email" name="" placeholder="Add emalil">

    <fieldset data-ng-repeat="choice in choices">

        Add Question

        <input type="text" ng-model="choice.name" name="" placeholder="Add Question">

        Question order
        <input type="text" ng-model="choice.order" name="" placeholder="Add Question order">

        <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
    </fieldset>

    <button type="submit" class="btn btn-primary" ng-click="OnSave()">Submit</button>

        {{ choices }}

my expected result :

{

    "name": "test",
    "email": "asdf@gmail.com",
    "questions": [
        {
            "question": "Which of the following is the most important characteristic for a supervisor?",
            "questionorder": "1",

        },
        {
            "question": "Which of the following is the most important characteristic for a supervisor?",
            "questionorder": "2",

        }
    ]
}


问:
How to automate a django functions when a certain condition is met by a django model's field
My problem is, how do I make a Django function run automatically when a certain condition is met by a Django model field. Google decided not to be collaborative on this. Say for example, I have the following model:

```<code>class Check(models.Model):

    name = models.CharField(max_length=100, blank=True)
    interval = models.DurationField(default=td(hours=1))
    last_run = models.DateTimeField(null=True, blank=True)

    def run_function(self):
        return HttpResponse("....")
</code>```

I have a model named Check which has fields for name, the intervals which I expect a function to be run and the last time the function was run. I need to call the function each time after the specific interval. What is the simplest way to write a function that will be called or will call another function after the interval passes?

I am currently learning Django and I got stuck on this.

答: If you want periodic task to be run under Django you can give a look to http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html</p>

Body:
My problem is, how do I make a Django function run automatically when a certain condition is met by a Django model field. Google decided not to be collaborative on this. Say for example, I have the following model:

class Check(models.Model):

    name = models.CharField(max_length=100, blank=True)
    interval = models.DurationField(default=td(hours=1))
    last_run = models.DateTimeField(null=True, blank=True)

    def run_function(self):
        return HttpResponse("....")

I have a model named Check which has fields for name, the intervals which I expect a function to be run and the last time the function was run. I need to call the function each time after the specific interval. What is the simplest way to write a function that will be called or will call another function after the interval passes?

I am currently learning Django and I got stuck on this.


问:
BeautifulSoup get element inside list except one
I want to get all link value inside a list except one of them.
This is my list:

```<code>    <ul>
<li>
  <a class="link" href="consept link 1">
      <svg class="consept" preserveAspectRatio="xMinYMin meet" viewBox="0 0 22 22"><use xlink:href="link"></use></svg>
    <h2>Consept title 1</h2>
</a></li>
<li>
  <a class="link" href="consept link 2">
      <svg class="consept" preserveAspectRatio="xMinYMin meet" viewBox="0 0 22 22"><use xlink:href="link"></use></svg>
    <h2>Consept title 2</h2>
</a></li>
<li>
  <a class="link" href="consept link 3">
      <svg class="consept" preserveAspectRatio="xMinYMin meet" viewBox="0 0 22 22"><use xlink:href="link"></use></svg>
    <h2>Consept title 3</h2>
</a></li>
<li>
  <a class="link" href="video link">
      <svg class="video" preserveAspectRatio="xMinYMin meet" viewBox="0 0 22 22"><use xlink:href="link"></use></svg>
    <h2>video title</h2>
</a></li>
</ul>
</code>```

I want to get link address of parent <svg class="consept"> I mean the a tag but not svg with class video.

expected result:

```<code>consept link 1
consept link 2
consept link 3
</code>```

答:
This worked thanks to a friend.</p>

```<code>def _get_all_links(self):
      consepts = self.section_bs4.select('consept')
      for video_index, post in enumerate(consepts):
          consept_url = post.find_parent('a')['href']
</code>```

Body:
I want to get all link value inside a list except one of them.
This is my list:

      <svg class="consept" preserveAspectRatio="xMinYMin meet" viewBox="0 0 22 22"><use xlink:href="link"></use></svg>

Consept title 1

      <svg class="consept" preserveAspectRatio="xMinYMin meet" viewBox="0 0 22 22"><use xlink:href="link"></use></svg>

Consept title 2

      <svg class="consept" preserveAspectRatio="xMinYMin meet" viewBox="0 0 22 22"><use xlink:href="link"></use></svg>

Consept title 3

      <svg class="video" preserveAspectRatio="xMinYMin meet" viewBox="0 0 22 22"><use xlink:href="link"></use></svg>

video title

I want to get link address of parent <svg class="consept"> I mean the a tag but not svg with class video.

expected result:

consept link 1
consept link 2
consept link 3

Body:
This worked thanks to a friend.

def _get_all_links(self):
      consepts = self.section_bs4.select('consept')
      for video_index, post in enumerate(consepts):
          consept_url = post.find_parent('a')['href']


问:
Change the color of the button by using html color codes
I want to change the color of the button when it is pressed in windows form app and I want to use the color codes. Is there a way to make button color #C0C0C0 ??

答:
```<code>This may help you..
<script>
function changeCol(btnid){
    document.getElementById(btnid).style.backgroundColor = "#ff00F0";
}
</script>
<input type = "button" id = "btn" value="$alt1" onClick="changeCol('btn')">
</code>```


问:
android comparing dates I couldn't compare two dates...I referred many tutorials
I am using the datepicker dialog and am trying to compare the  current date  with the date specified in the dialog.
if the date is before the current date I wish to display invalid date.

Both current date and date entered are in same format. but I am getting error. when printing in console both current date and entered date are coming the the same format

```<code>if(date1.before(currDate))
{
     Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
}
</code>```

result:

current date 5/7/2017

picked date 5-7-2017

答:
Try this</p>

```<code>        String strCurrDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
        String strAnotherDate = "05/03/2017";
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

        try {
            Date currDate = formatter.parse(strCurrDate);
            Date anotherDate = formatter.parse(strAnotherDate);
            if (currDate.before(anotherDate)) {
                Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
</code>```

Body:
I am using the datepicker dialog and am trying to compare the  current date  with the date specified in the dialog.
if the date is before the current date I wish to display invalid date.

Both current date and date entered are in same format. but I am getting error. when printing in console both current date and entered date are coming the the same format

if(date1.before(currDate))
{
     Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
}

result:

current date 5/7/2017

picked date 5-7-2017

Body:
Try this

        String strCurrDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
        String strAnotherDate = "05/03/2017";
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

        try {
            Date currDate = formatter.parse(strCurrDate);
            Date anotherDate = formatter.parse(strAnotherDate);
            if (currDate.before(anotherDate)) {
                Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }


问:
Exporting an oracle table dynamically to a flat file
I am trying to build a C++ program using occi libraries that will take a select statement or a table name as an input and turn it into a delimited file. However, looking at the documentation, I can't find a way to export all columns of a query result into a file. Almost all examples I found were along the following lines

```<code>string query = "SELECT col1 FROM table1";

stmt = con->createStatement(query);
res = stmt->executeQuery();

while (res->next())
{
    outfile<<res->getInt(1)<<endl;
}
</code>```

What i want to do is: Do a select * and then export the full row to the file in one go without specifying the type for each column, but I haven't been able to find something that does this.

I know that row-by-row exports are not really efficient for large sets, but I want to make this work before optimizing it.

Does anyone have any ideas around how to do this efficiently?

答:
I don't think that you will find something like this "in the box" while using OCCI.

However using STL you can push to a stringstream the result of every iteration and when the rs->next() is NULL you can append the stringstream in the file.

Body:
I am trying to build a C++ program using occi libraries that will take a select statement or a table name as an input and turn it into a delimited file. However, looking at the documentation, I can't find a way to export all columns of a query result into a file. Almost all examples I found were along the following lines

string query = "SELECT col1 FROM table1";

stmt = con->createStatement(query);
res = stmt->executeQuery();

while (res->next())
{
    outfile<<res->getInt(1)<<endl;
}

What i want to do is: Do a select * and then export the full row to the file in one go without specifying the type for each column, but I haven't been able to find something that does this.

I know that row-by-row exports are not really efficient for large sets, but I want to make this work before optimizing it.

Does anyone have any ideas around how to do this efficiently?


问:
How to hide all li except first two in one list, and third and fourth in another?
could you please tell me how to hide all li expect first two li ? in secnd case I want to hide all li expect show 3 and 4 li on buttn click
here is my code

https://jsbin.com/damolibule/edit?html,js,output

```<code>$(function() {
  $('#id_show12').click(function() {
    $('.show12').not(":nth-child(2)").css("display", "none");
  })

  $('#id_show34').click(function() {
    $('.show34').not(":nth-child(5)").css("display", "none");
  })
})
</code>```

Expected output: when first button click it shows 1 and 2 only. If user clicks on second button it show 3 and 4.

答:
To show only the first two li you can use :gt(1) to get all the following li, then hide() them,

To show only the third and fourth li you can use not() in combination with :eq(2) and :eq(3) to hide() the unrequired ones. Try this:

$('#id_show12').click(function() {
  $('.show12 li:gt(1)').hide();
})
$('#id_show34').click(function() {
  $('.show34 li').not(':eq(2), :eq(3)').hide();
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="show12">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
</div>
<div class="show34">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
</div>

<button id="id_show12">show only one/two</button>
<button id="id_show34">show only three/four</button></code>```

Body:
could you please tell me how to hide all li expect first two li ? in secnd case I want to hide all li expect show 3 and 4 li on buttn click
here is my code

https://jsbin.com/damolibule/edit?html,js,output

$(function() {
  $('#id_show12').click(function() {
    $('.show12').not(":nth-child(2)").css("display", "none");
  })

  $('#id_show34').click(function() {
    $('.show34').not(":nth-child(5)").css("display", "none");
  })
})

Expected output: when first button click it shows 1 and 2 only. If user clicks on second button it show 3 and 4.

Body:
To show only the first two li you can use :gt(1) to get all the following li, then hide() them,

To show only the third and fourth li you can use not() in combination with :eq(2) and :eq(3) to hide() the unrequired ones. Try this:

$('#id_show12').click(function() {
  $('.show12 li:gt(1)').hide();
})
$('#id_show34').click(function() {
  $('.show34 li').not(':eq(2), :eq(3)').hide();
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="show12">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
</div>
<div class="show34">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
</div>

<button id="id_show12">show only one/two</button>
<button id="id_show34">show only three/four</button>

ContentLicense: CC BY-SA 4.0


问:
MVC5 can't find controller in same folder as default
I have a routing problem. I have 3 controllers in the same folder.

```<code>/pages/defaultcontroller
/pages/datacontroller
/pages/infocontroller
</code>```

All controllers have a Index action, and there are index.cshtml views in the views folder(s). The system can find the default controller but it cant find the others.

E.g. http://servername/pages/default works fine but http://servername/pages/data doesn't work and http://servername/pages/info doesn't work

The error is

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /pages/info

I have this route, configured

```<code>context.MapRoute(
    "pages_default",
    "pages/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional }
);
</code>```

The only oddity is that this is an mvc portion added to an existing web-forms project as part of application migration development to mvc.

I am newish to mvc and enjoying it so far :)

Any ideas ?

UPDATE

I tried adding extra routing, still the same problem

```<code>        context.MapRoute(
            "pages_data",
            "pages/data/{action}/{id}",
            new { controller = "data", action = "Index", id = UrlParameter.Optional }
        );

        context.MapRoute(
            "pages_info",
            "pages/info/{action}/{id}",
            new { controller = "info", action = "Index", id = UrlParameter.Optional }
        );

        context.MapRoute(
            "pages_default",
            "pages/{controller}/{action}/{id}",
            new { controller = "default", action = "Index", id = UrlParameter.Optional }
        );
</code>```

UPDATE(2)

Output from route debugger (top of question)

答:
Should your route be:

```<code>context.MapRoute(
    "pages_default",
    "pages/{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
</code>```

You don't have a controller param defined in the defaults.

Body:
I have a routing problem. I have 3 controllers in the same folder.

/pages/defaultcontroller
/pages/datacontroller
/pages/infocontroller

All controllers have a Index action, and there are index.cshtml views in the views folder(s). The system can find the default controller but it cant find the others.

E.g. http://servername/pages/default works fine but http://servername/pages/data doesn't work and http://servername/pages/info doesn't work

The error is

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /pages/info

I have this route, configured

context.MapRoute(
    "pages_default",
    "pages/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional }
);

The only oddity is that this is an mvc portion added to an existing web-forms project as part of application migration development to mvc.

I am newish to mvc and enjoying it so far :)

Any ideas ?

UPDATE

I tried adding extra routing, still the same problem

        context.MapRoute(
            "pages_data",
            "pages/data/{action}/{id}",
            new { controller = "data", action = "Index", id = UrlParameter.Optional }
        );

        context.MapRoute(
            "pages_info",
            "pages/info/{action}/{id}",
            new { controller = "info", action = "Index", id = UrlParameter.Optional }
        );

        context.MapRoute(
            "pages_default",
            "pages/{controller}/{action}/{id}",
            new { controller = "default", action = "Index", id = UrlParameter.Optional }
        );

UPDATE(2)

Output from route debugger (top of question)

Body:
Should your route be:

context.MapRoute(
    "pages_default",
    "pages/{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

You don't have a controller param defined in the defaults.


问:
Extract content in paragraph Tags
I have following html in string and i have to extract the content only in Paragraph tags  any ideas??

link is http://www.public-domain-content.com/books/Coming_Race/C1P1.shtml

I have tried

```<code>  const string HTML_TAG_PATTERN = "<[^>]+.*?>";
    static string StripHTML(string inputString)
            {
                return Regex.Replace(inputString, HTML_TAG_PATTERN, string.Empty);
            }
</code>```

it removes all html tags but i dont want to remove all the tags because this is the way how i can get content like paragraph by tags

secondly it makes line breaks to \n in text and and applying replace("\n","") dose not helps
one problem is that when i apply

```<code>int UrlStart = e.Result.IndexOf("<p>"), urlEnd = e.Result.IndexOf("<p> </p></td>\r" );
     string paragraph = e.Result.Substring(UrlStart, urlEnd);
     extractedContent.Text = paragraph.Replace(Environment.NewLine, "");
</code>```

	\r this appears at the end of paragraph but urlEnd dose not makes sure only paragraph is shown

the string extracted is shown in visual studio is like this

this page is downloaded by Webclient
End of HTMLpage

```<code>We will provide ourselves with ropes of\rsuitable length and strength- and- pardon me- you must not\rdrink more to-night.  our hands and feet must be steady and\rfirm tomorrow.\"\r<p> </p>     </td>\r    </tr>\r\r    <tr>\r     <td height=\"25\" width=\"10%\">\r     \r     </td><td height=\"25\" width=\"80%\" align=\"center\">\r       <font color=\"#FFFFFF\">\r       <font size=\"4\">1</font>  \r       </font></td>\r     <td height=\"25\" width=\"10%\" align=\"right\"><a href=\"C2P1.shtml\">Next</a></td>\r    </tr>\r   </table>\r  </center>\r</div>\r<p align=\"center\"><a href=\"index.shtml\"><b>The Coming Race -by- Edward Bulwer Lytton</b></a></p>\r<P><B><center><A HREF=\"http://www.public-domain-content.com/encyclopedia.shtml\">Encyclopedia</a> - <A HREF=\"http://www.public-domain-content.com/books.shtml\">Books</a> - <A HREF=\"http://www.public-domain-content.com/religion.shtml\">Religion<a/> - <A HREF=\"http://www.public-domain-content.com/links2.shtml\">Links</a> - <A HREF=\"http://www.public-domain-content.com/\">Home</a> - <A HREF=\"http://www.webmaster-headquarters.com/mb/\">Message Boards</a></B><BR>This <a HREF=\"http://www.wikipedia.org/\">Wikipedia</a> content is licensed under the <a href=\"http://www.gnu.org/copyleft/fdl.html\">GNU Fr
</code>```

答:
Don't use regular expressions to parse HTML. Use the HTML Agility Pack (or something similar) instead.

A quick example, but you could do something like this:

```<code>HtmlDocument document = new HtmlDocument();
document.Load("your_file_here.htm");
foreach(HtmlNode paragraph in document.DocumentElement.SelectNodes("//p"))
{
    // do something with the paragraph node here
    string content = paragraph.InnerText; // or something similar
}
</code>```

Title: Extract content in paragraph Tags

Body:
I have following html in string and i have to extract the content only in Paragraph tags  any ideas??

link is http://www.public-domain-content.com/books/Coming_Race/C1P1.shtml

I have tried

  const string HTML_TAG_PATTERN = "<[^>]+.*?>";
    static string StripHTML(string inputString)
            {
                return Regex.Replace(inputString, HTML_TAG_PATTERN, string.Empty);
            }

it removes all html tags but i dont want to remove all the tags because this is the way how i can get content like paragraph by tags

secondly it makes line breaks to \n in text and and applying replace("\n","") dose not helps
one problem is that when i apply

int UrlStart = e.Result.IndexOf("
"), urlEnd = e.Result.IndexOf("

	\r" );
     string paragraph = e.Result.Substring(UrlStart, urlEnd);
     extractedContent.Text = paragraph.Replace(Environment.NewLine, "");

	\r this appears at the end of paragraph but urlEnd dose not makes sure only paragraph is shown

the string extracted is shown in visual studio is like this

this page is downloaded by Webclient
End of HTMLpage

We will provide ourselves with ropes of\rsuitable length and strength- and- pardon me- you must not\rdrink more to-night.  our hands and feet must be steady and\rfirm tomorrow.\"\r

     	\r
\r\r
\r     \r     \r     	\r       \r       1  \r       	\r     Next	\r
\r
\r  \r
\r
The Coming Race -by- Edward Bulwer Lytton
\r
Encyclopedia - Books - Religion - Links - Home - Message Boards
This Wikipedia content is licensed under the GNU Fr

Body:
Don't use regular expressions to parse HTML. Use the HTML Agility Pack (or something similar) instead.

A quick example, but you could do something like this:

HtmlDocument document = new HtmlDocument();
document.Load("your_file_here.htm");
foreach(HtmlNode paragraph in document.DocumentElement.SelectNodes("//p"))
{
    // do something with the paragraph node here
    string content = paragraph.InnerText; // or something similar
}


问:
Submitting Informatica Workflows Parallely through PMCMD command
How do I submit Informatica workflows to run at the same time..?

We developed a file having all the PMCMD commands for every workflow. We intend to call this file in the script that will eventually hit Workflow manager for the execution of Infa Workflows. The problem we are facing is, the workflows are running sequentially. There is no dependency between any of the workflows and can be run in parallel.

Im already using as below:

./pmcmd startworkflow -sv intg_ser -d Domain_name -u user -p welcome123 -usd Native -f SDE_ORAR1213_Adaptor -rin intg_ser SDE_ORA_InventoryLotDimension &

(followed by next pmcmd command)

'&' used to run the workflows in background.

Is there any way to do apart from using '&' , since i do not want to run the w/f in background. Any info of how Scheduling tools like DAC achieved this parallelism, we wanted to implement the same functionality without using any scheduling tool.

If not, can I achieve this through unix scripting itself? If so please provide me the steps.

Any Java related suggestions also accepted.

Thanks in Advance!

答:
u can create a master-workflow in which u can call workflows at same time giving same trigger function and they will run parallel over monitor also.

also for performance u can use clock to run after desire time or from when workflow was triggered.


问:
What happened to the Unity Test Runner options?
Take a look at this screenshot (from this site):

Now look at a screenshot from my own copy of Unity (Personal).

As you can see, a lot appears to be missing. Does anybody know why? Is this a Pro-only thing? I can't find any reference to it.

答:
The screenshot above is an older version of Test Tools. UnityTestTools was an open soruce project, deployed as a Package in the Asset Store. You had to import the asset from Asset Store to use this feature up to Unity 5.5. This is a deprecated project and is not supported anymore from Unity 5.6 (valid until Unity 5.5).

The Unity Technologies apparently liked it so they included the Test Tool as an official feature from Unity 5.6, and renamed it Test Runner. When you create projects you have the Test Runner included by default, which can be accessed from the tab [Window - Test Runner].

A few major changes I've noticed are:

AssertComponent no longer exists

No Scene-Based-Test out of the box as it used to be. Although Unity Forum suggests it should be easy to implement such tests yourself with PlayMode I feel like there are not enough ducumentation and examples for beginners.


问:
Python using regex to extract parts of a string in pandas column
I've got a pandas df column called 'Raw' for which the format is inconsistent. The strings it contains look like that:

```<code>'(1T XXX, Europe)'
'(2T YYYY, Latin America)'
'(3T ZZ/ZZZZ, Europe)'
'(4T XXX XXX, Africa)'
</code>```

The only thing consistent in the strings in 'Raw' is that they start with a digit, includes a comma in the middle followed by a whitespace, and they contain parentheses as well.

Now, I'd like to create two extra columns (Model and Region) in my dataframe:

'Model' would contain the beginning of the string, i.e. everything between the first parenthesis and the comma

'Region' would contain the end of the string, i.e. everything between the whitespace after the comma and the final parenthesis

How do I do that using regex?

答:
```<code>import re

s = '(3T ZZ/ZZZZ, Europe)'
m=re.search(r'\((.*), (.*)\)',s)
print(m.groups())
</code>```

Body:
I've got a pandas df column called 'Raw' for which the format is inconsistent. The strings it contains look like that:

'(1T XXX, Europe)'
'(2T YYYY, Latin America)'
'(3T ZZ/ZZZZ, Europe)'
'(4T XXX XXX, Africa)'

The only thing consistent in the strings in 'Raw' is that they start with a digit, includes a comma in the middle followed by a whitespace, and they contain parentheses as well.

Now, I'd like to create two extra columns (Model and Region) in my dataframe:

'Model' would contain the beginning of the string, i.e. everything between the first parenthesis and the comma

'Region' would contain the end of the string, i.e. everything between the whitespace after the comma and the final parenthesis

How do I do that using regex?


问:
Max difference between two adjacent values in an array, C
I want to find the max difference between two adjacent values in an array.For instance, for array int tab[6] = {1,2,8,4,5,6}; the maximum difference is 6, because of the difference between 8 and 2. Remaining differences are equal to 1. So, the result of my program should be 6. However, my program prints 1 and I do not know where's the problem:

```<code>#include <stdio.h>

int main(int argc, char **argv)
{
    int n = 6;
    int tab[6] = {1,2,8,4,5,6};
    int diff = tab[1] - tab[0], maxdiff = diff, i;

    for(i=2; i<n-1; i++)
    {
        if(diff > maxdiff)
            maxdiff = diff;

        diff = tab[i] - tab[i-1];
    }

    printf("%d\n", diff);

    return 0;
}
</code>```

答:
Well, you keep the information about the maximum difference into maxdiff but you always print diff which is the difference between the one before the last pair of numbers (in this example 1).

i should goes up to < n otherwise you don't take into account the last pair.

I would clean up the code a bit and check for the n<=1 corner case.

I guess that you are interested in the absolute difference among values. You either use abs or make sure the subtraction gives you a non-negative result by changing the order of the operands accordingly. (abs is easier)

Here it is  my suggestion:

```<code>int main(int argc, char **argv) {
  const int n = 6;
  int tab[n] = {1, 2, 8, 4, 5, 26};
  if (n <= 1)
    return 0; //or whatever you have to do in this corner case
  else {
    int maxdiff = INT_MIN;
    for (int i = 1; i < n; i++)
      maxdiff = max(maxdiff, abs(tab[i] - tab[i - 1]));

    printf("%d\n", maxdiff);
  }
  return 0;
}
</code>```

Body:
I want to find the max difference between two adjacent values in an array.For instance, for array int tab[6] = {1,2,8,4,5,6}; the maximum difference is 6, because of the difference between 8 and 2. Remaining differences are equal to 1. So, the result of my program should be 6. However, my program prints 1 and I do not know where's the problem:

#include <stdio.h>

int main(int argc, char **argv)
{
    int n = 6;
    int tab[6] = {1,2,8,4,5,6};
    int diff = tab[1] - tab[0], maxdiff = diff, i;

    for(i=2; i<n-1; i++)
    {
        if(diff > maxdiff)
            maxdiff = diff;

        diff = tab[i] - tab[i-1];
    }

    printf("%d\n", diff);

    return 0;
}

Body:
Well, you keep the information about the maximum difference into maxdiff but you always print diff which is the difference between the one before the last pair of numbers (in this example 1).

i should goes up to < n otherwise you don't take into account the last pair.

I would clean up the code a bit and check for the n<=1 corner case.

I guess that you are interested in the absolute difference among values. You either use abs or make sure the subtraction gives you a non-negative result by changing the order of the operands accordingly. (abs is easier)

Here it is  my suggestion:

int main(int argc, char **argv) {
  const int n = 6;
  int tab[n] = {1, 2, 8, 4, 5, 26};
  if (n <= 1)
    return 0; //or whatever you have to do in this corner case
  else {
    int maxdiff = INT_MIN;
    for (int i = 1; i < n; i++)
      maxdiff = max(maxdiff, abs(tab[i] - tab[i - 1]));

    printf("%d\n", maxdiff);
  }
  return 0;
}


问:
Android: How to set both staticHeaders and dynamic Headers in same service call? Is this possible?
I have got a scenario like need to pass one header as parameter

```<code>@GET("mobile/userProfile")
Observable<ProfileDetail> getImageUrlDetail(@Header("contentType") String contentType,
                                              @Query("pictureName") String fileName);
</code>```

and also I need to set Authorization and X-API key.

So I have created a custom Intercepter and adding Authorization and X-API key in this interceptor.

But only one header is working either static or dynamic header. Both headers should be set into OkHttpClient. Otherwise, I will receive 400 bad request.

```<code>OkHttpClient okHttpClient = new okhttp3.OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS) // 30 seconds Connection Timeout
                .readTimeout(60, TimeUnit.SECONDS) // 60 seconds Read Timeout
                .addInterceptor(interceptor)
                .addInterceptor(logging)
                .build();
</code>```

the weird scenario is If add my custom interceptor first and then logging interceptor. It gives custom interceptor's HEADERS in logcat.
If I switch the lines,
                .addInterceptor(logging)
                .addInterceptor(interceptor)
Then I'm getting @Header in logcat, which is passing as param.

I want to set both headers to API call get 200 response.

Suggestion and solutions are most welcome.
Thanks

答:
There's a couple of things about your code and question. Let me try and help you with all of them the best I can.

First

the weird scenario is If add my custom interceptor first and then logging interceptor. It gives custom interceptor's HEADERS in logcat. If I switch the lines, .addInterceptor(logging) .addInterceptor(interceptor) Then I'm getting @Header in logcat, which is passing as param.

If I get it right then that's 100% expected and it's how it works. Interceptors work like a chain, so when you do

```<code>.addInterceptor(interceptor)
.addInterceptor(logging)
</code>```

Then it will run first interceptor, which I guess adds the api key and then it will run the logging interceptor, which will log all the headers added so far to the request. The @Header is added by retrofit, not by OkHttp, so it should be there even if you don't have any interceptor and it will be there before the okhttp interceptors get a chance to kick in.

If you switch it around:

```<code>.addInterceptor(logging)
.addInterceptor(interceptor)
</code>```

Then you'll log first - no api key header has been added yet - and then you add the api key header. That's why in log cat you don't see your api key header added if you do it like that, but you do see the @Header. As a rule of thumb, always put the logging last in the chain.

In both scenarios, both headers should be added to the final request regardless of the order of the interceptors. If this is not the case, then there's something else on the way messing up the headers.

Now onto the static vs. dynamic headers. To my best of knowledge these should work pretty well together. The thing I'm guessing it's not working is the fact you have @Header("contentType") - notice how you've wrote contentType? It should be content-type if I understand this standard correctly. So it should work if you change it to @Header("Content-Type").

Hope this helps

Body:
I have got a scenario like need to pass one header as parameter

@GET("mobile/userProfile")
Observable<ProfileDetail> getImageUrlDetail(@Header("contentType") String contentType,
                                              @Query("pictureName") String fileName);

and also I need to set Authorization and X-API key.

So I have created a custom Intercepter and adding Authorization and X-API key in this interceptor.

But only one header is working either static or dynamic header. Both headers should be set into OkHttpClient. Otherwise, I will receive 400 bad request.

OkHttpClient okHttpClient = new okhttp3.OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS) // 30 seconds Connection Timeout
                .readTimeout(60, TimeUnit.SECONDS) // 60 seconds Read Timeout
                .addInterceptor(interceptor)
                .addInterceptor(logging)
                .build();

the weird scenario is If add my custom interceptor first and then logging interceptor. It gives custom interceptor's HEADERS in logcat.
If I switch the lines,
                .addInterceptor(logging)
                .addInterceptor(interceptor)
Then I'm getting @Header in logcat, which is passing as param.

I want to set both headers to API call get 200 response.

Suggestion and solutions are most welcome.
Thanks

Body:
There's a couple of things about your code and question. Let me try and help you with all of them the best I can.

First

the weird scenario is If add my custom interceptor first and then logging interceptor. It gives custom interceptor's HEADERS in logcat. If I switch the lines, .addInterceptor(logging) .addInterceptor(interceptor) Then I'm getting @Header in logcat, which is passing as param.

If I get it right then that's 100% expected and it's how it works. Interceptors work like a chain, so when you do

.addInterceptor(interceptor)
.addInterceptor(logging)

Then it will run first interceptor, which I guess adds the api key and then it will run the logging interceptor, which will log all the headers added so far to the request. The @Header is added by retrofit, not by OkHttp, so it should be there even if you don't have any interceptor and it will be there before the okhttp interceptors get a chance to kick in.

If you switch it around:

.addInterceptor(logging)
.addInterceptor(interceptor)

Then you'll log first - no api key header has been added yet - and then you add the api key header. That's why in log cat you don't see your api key header added if you do it like that, but you do see the @Header. As a rule of thumb, always put the logging last in the chain.

In both scenarios, both headers should be added to the final request regardless of the order of the interceptors. If this is not the case, then there's something else on the way messing up the headers.

Now onto the static vs. dynamic headers. To my best of knowledge these should work pretty well together. The thing I'm guessing it's not working is the fact you have @Header("contentType") - notice how you've wrote contentType? It should be content-type if I understand this standard correctly. So it should work if you change it to @Header("Content-Type").

Hope this helps


问:
Is there are way to change value inside of AlertDialog.Builder?(Android)
I'm new to android.
Can I change the value inside of AlertDialog.Builder?</p>

```<code>int changeThisDataToOne = 0;

    new AlertDialog.Builder(view.getContext())
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Are you sure?")
            .setMessage("Do you want to delete this note?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            changeThisDataToOne = 1;
                           //error : Variable 'changeThisDataToOne' is accessed
                           //from within inner class, needs to be declared final
                        }
                    }
            )
            .setNegativeButton("No", null)
            .show();
}
</code>```

答:
change changeThisDataToOne to final int[],

```<code>final int[] changeThisDataToOne = {0};
</code>```

then its value can be changed as

```<code>changeThisDataToOne[0] = 1;
</code>```

or make changeThisDataToOne as field variable.

Body:
I'm new to android.
Can I change the value inside of AlertDialog.Builder?

int changeThisDataToOne = 0;

    new AlertDialog.Builder(view.getContext())
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Are you sure?")
            .setMessage("Do you want to delete this note?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            changeThisDataToOne = 1;
                           //error : Variable 'changeThisDataToOne' is accessed
                           //from within inner class, needs to be declared final
                        }
                    }
            )
            .setNegativeButton("No", null)
            .show();
}

Body:
change changeThisDataToOne to final int[],

final int[] changeThisDataToOne = {0};

then its value can be changed as

changeThisDataToOne[0] = 1;

or make changeThisDataToOne as field variable.


问:
Libgdx - Rotate an object using its movement
I'm trying to implement an autorotation method for a SpriteAnimation class (trying to port SpriteAnimation).

Everything is working, the sprite draws correctly (it uses the correct animations) it just doesn't rotate properly if at all, normally it seems to point to the origin (0, 0) only after its target matches its position while I want its rotation to update as it moves, i've tried both degrees and radians, neither of which work. It should be rotating to match the current direction it's going. I've been struggling with this for about a week now, but still have not gotten the desired result.

Full Code Here

Relevant code:

From SpriteAnimation

```<code>// The x position of the sprite's upper left corner pixel.
public int getX() { return (int)position.x; }
public void setX(int value)
{
    prevPosition.x = position.x;
    position.x = value;
    updateRotation();
}

// The y position of the sprite's upper left corner pixel.
public int getY() { return (int)position.y; }
public void setY(int value)
{
    prevPosition.y = position.y;
    position.y = value;
    updateRotation();
}

void updateRotation()
{
    if (rotateByPosition)
    {
        Vector2 rotationVector = new Vector2(position.x - prevPosition.x, position.y - prevPosition.y);
        rotationRad = rotationVector.angle();
        rotationDeg = rotationRad * MathUtils.radiansToDegrees;
    }
}

public void MoveBy(int x, int y)
{
    prevPosition = new Vector2(position);
    position.x += x;
    position.y += y;
    updateRotation();
}

public void Update(float deltaTime)
{
    // Don't do anything if the sprite is not animating
    if (animating)
    {
        // If there is not a currently active animation
        if (getCurrentFrameAnimation() == null)
        {
            // Make sure we have an animation associated with this sprite
            if (animations.size() > 0)
            {
                // Set the active animation to the first animation
                // associated with this sprite
                String[] sKeys = new String[animations.size()];
                int index = 0;
                for (Entry<String, FrameAnimation> mapEntry : animations.entrySet()) {
                    sKeys[index] = mapEntry.getKey();
                    index++;
                }
                setCurrentAnimation(sKeys[0]);
            }
            else
            {
                return;
            }
        }

        // Run the Animation's update method
        getCurrentFrameAnimation().Update(deltaTime);

        // Check to see if there is a "follow-up" animation named for this animation
        if (getCurrentFrameAnimation().getNextAnimation() != null && !getCurrentFrameAnimation().getNextAnimation().isEmpty())
        {
            // If there is, see if the currently playing animation has
            // completed a full animation loop
            if (getCurrentFrameAnimation().getPlayCount() > 0)
            {
                // If it has, set up the next animation
                setCurrentAnimation(getCurrentFrameAnimation().getNextAnimation());
            }
        }
    }
}

public void Draw(SpriteBatch spriteBatch, int xOffset, int yOffset)
{
    updateRotation();   // Calling this while testing to make sure that it is being called
    spriteBatch.draw(getCurrentTextureRegion(), getPosition().x + xOffset - center.x, getPosition().y + yOffset - center.y, center.x, center.y, getCurrentFrameAnimation().getFrameWidth(), getCurrentFrameAnimation().getFrameHeight(), 1.0f, 1.0f, rotationRad);
}
</code>```

TestScreen class

```<code>package com.darkstudio.darkisle.screens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.darkstudio.darkisle.DarkIsle;
import com.delib.engine.sprite.MobileSprite;

/**
 * Created by DarkEnder on 2017/06/27.
 */

public class TestScreen implements Screen {
    final DarkIsle game;
    OrthographicCamera camera;
    Texture tankTexture;

    MobileSprite mouseTank;

    public TestScreen(final DarkIsle game)
    {
        this.game = game;

        camera = new OrthographicCamera();
        configureCamera();

        tankTexture = new Texture(Gdx.files.internal("MulticolorTanks.png"));

        mouseTank = new MobileSprite(tankTexture, 32, 32);
        mouseTank.getSprite().AddAnimation("red", 0, 32, 32, 32, 8, 0.1f);
        mouseTank.getSprite().AddAnimation("purple", 0, 128, 32, 32, 8, 0.1f, "red");
        mouseTank.getSprite().AddAnimation("yellow", 0, 64, 32, 32, 8, 0.1f);
        mouseTank.getSprite().setAutoRotate(true);
        mouseTank.setPosition(new Vector2(100, 100));
        mouseTank.setTarget(new Vector2(mouseTank.getPosition()));
        mouseTank.setIsPathing(true);
        mouseTank.setEndPathAnimation("yellow");
        mouseTank.setLoopPath(false);
        mouseTank.setSpeed(2);
    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

        update();

        game.batch.begin();

        mouseTank.draw(game.batch);

        game.batch.end();
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {

    }

    private void configureCamera()
    {
        Vector3 camPos = new Vector3(camera.position);

        float size = 800;
        float cameraWidth = 0;
        float cameraHeight = 0;

        if (Gdx.graphics.getHeight() < Gdx.graphics.getWidth())
        {
            cameraWidth = size;
            cameraHeight = size * Gdx.graphics.getHeight() / Gdx.graphics.getWidth();
        }
        else
        {
            cameraWidth = size * Gdx.graphics.getWidth() / Gdx.graphics.getHeight();
            cameraHeight = size;
        }

        camera.setToOrtho(true, cameraWidth, cameraHeight);
        camera.position.set(camPos.x + camera.viewportWidth / 2f, camPos.y + camera.viewportHeight / 2f, 0);
    }

    private void update() {
        int xTouch = Gdx.input.getX(0);
        int yTouch = Gdx.input.getY(0);
        mouseTank.setTarget(xTouch, yTouch);
        mouseTank.update(Gdx.graphics.getDeltaTime());
    }
}
</code>```

Edit: Just saying now that I've already tried using atan2 in MathUtils and it gave the same results.

The MobileSprite update method

```<code>public void update(float deltaTime)
{
    if (active && movingTowardsTarget)
    {
        if ((target != null))
        {
            // Get a vector pointing from the current location of the sprite
            // to the destination.
            Vector2 Delta = new Vector2(target.x - sprite.getX(), target.y - sprite.getY());

            if (Delta.len() > getSpeed())
            {
                Delta.nor();
                Delta.scl(getSpeed());
                getPosition().add(Delta);
            }
            else
            {
                if (target == sprite.getPosition())
                {
                    if (pathing)
                    {
                        if (queuePath.size() > 0)
                        {
                            target = queuePath.remove();
                            if (loopPath)
                            {
                                queuePath.remove(target);
                            }
                        }
                        else
                        {
                            if (!(endPathAnimation == null))
                            {
                                if (!(getSprite().getCurrentAnimation() == endPathAnimation))
                                {
                                    getSprite().setCurrentAnimation(endPathAnimation);
                                }
                            }

                            if (deactivateAtEndOfPath)
                            {
                                setIsActive(false);
                            }

                            if (hideAtEndOfPath)
                            {
                                setIsVisible(false);
                            }
                        }
                    }
                }
                else
                {
                    sprite.setPosition(target);
                }
            }
        }
    }
    if (active)
        sprite.Update(deltaTime);
}
</code>```

答:
To get the radians angle:

```<code>void updateRotation()
{
    if (rotateByPosition)
    {
        Vector2 rotationVector = new Vector2(position.x - prevPosition.x, position.y - prevPosition.y);
        rotationRad = rotationVector.angleRad();
        rotationDeg = rotationRad * MathUtils.radiansToDegrees;
    }
}
</code>```

and the draw method needs a degrees angle:

```<code>spriteBatch.draw(
            getCurrentTextureRegion(),
            getPosition().x + xOffset - center.x,
            getPosition().y + yOffset - center.y,
            center.x, center.y,
            getCurrentFrameAnimation().getFrameWidth(), getCurrentFrameAnimation().getFrameHeight(),
            1.0f, 1.0f,
            rotationDeg
    );
</code>```

The screen mouse position is from the upper left corner the renderer needs from the bottom left corner:

```<code>int xTouch = Gdx.input.getX(0);
int yTouch = Gdx.graphics.getHeight() - Gdx.input.getY(0);
</code>```

Body:
I'm trying to implement an autorotation method for a SpriteAnimation class (trying to port SpriteAnimation).

Everything is working, the sprite draws correctly (it uses the correct animations) it just doesn't rotate properly if at all, normally it seems to point to the origin (0, 0) only after its target matches its position while I want its rotation to update as it moves, i've tried both degrees and radians, neither of which work. It should be rotating to match the current direction it's going. I've been struggling with this for about a week now, but still have not gotten the desired result.

Full Code Here

Relevant code:

From SpriteAnimation

// The x position of the sprite's upper left corner pixel.
public int getX() { return (int)position.x; }
public void setX(int value)
{
    prevPosition.x = position.x;
    position.x = value;
    updateRotation();
}

// The y position of the sprite's upper left corner pixel.
public int getY() { return (int)position.y; }
public void setY(int value)
{
    prevPosition.y = position.y;
    position.y = value;
    updateRotation();
}

void updateRotation()
{
    if (rotateByPosition)
    {
        Vector2 rotationVector = new Vector2(position.x - prevPosition.x, position.y - prevPosition.y);
        rotationRad = rotationVector.angle();
        rotationDeg = rotationRad * MathUtils.radiansToDegrees;
    }
}

public void MoveBy(int x, int y)
{
    prevPosition = new Vector2(position);
    position.x += x;
    position.y += y;
    updateRotation();
}

public void Update(float deltaTime)
{
    // Don't do anything if the sprite is not animating
    if (animating)
    {
        // If there is not a currently active animation
        if (getCurrentFrameAnimation() == null)
        {
            // Make sure we have an animation associated with this sprite
            if (animations.size() > 0)
            {
                // Set the active animation to the first animation
                // associated with this sprite
                String[] sKeys = new String[animations.size()];
                int index = 0;
                for (Entry<String, FrameAnimation> mapEntry : animations.entrySet()) {
                    sKeys[index] = mapEntry.getKey();
                    index++;
                }
                setCurrentAnimation(sKeys[0]);
            }
            else
            {
                return;
            }
        }

        // Run the Animation's update method
        getCurrentFrameAnimation().Update(deltaTime);

        // Check to see if there is a "follow-up" animation named for this animation
        if (getCurrentFrameAnimation().getNextAnimation() != null && !getCurrentFrameAnimation().getNextAnimation().isEmpty())
        {
            // If there is, see if the currently playing animation has
            // completed a full animation loop
            if (getCurrentFrameAnimation().getPlayCount() > 0)
            {
                // If it has, set up the next animation
                setCurrentAnimation(getCurrentFrameAnimation().getNextAnimation());
            }
        }
    }
}

public void Draw(SpriteBatch spriteBatch, int xOffset, int yOffset)
{
    updateRotation();   // Calling this while testing to make sure that it is being called
    spriteBatch.draw(getCurrentTextureRegion(), getPosition().x + xOffset - center.x, getPosition().y + yOffset - center.y, center.x, center.y, getCurrentFrameAnimation().getFrameWidth(), getCurrentFrameAnimation().getFrameHeight(), 1.0f, 1.0f, rotationRad);
}

TestScreen class

package com.darkstudio.darkisle.screens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.darkstudio.darkisle.DarkIsle;
import com.delib.engine.sprite.MobileSprite;

/**
 * Created by DarkEnder on 2017/06/27.
 */

public class TestScreen implements Screen {
    final DarkIsle game;
    OrthographicCamera camera;
    Texture tankTexture;

    MobileSprite mouseTank;

    public TestScreen(final DarkIsle game)
    {
        this.game = game;

        camera = new OrthographicCamera();
        configureCamera();

        tankTexture = new Texture(Gdx.files.internal("MulticolorTanks.png"));

        mouseTank = new MobileSprite(tankTexture, 32, 32);
        mouseTank.getSprite().AddAnimation("red", 0, 32, 32, 32, 8, 0.1f);
        mouseTank.getSprite().AddAnimation("purple", 0, 128, 32, 32, 8, 0.1f, "red");
        mouseTank.getSprite().AddAnimation("yellow", 0, 64, 32, 32, 8, 0.1f);
        mouseTank.getSprite().setAutoRotate(true);
        mouseTank.setPosition(new Vector2(100, 100));
        mouseTank.setTarget(new Vector2(mouseTank.getPosition()));
        mouseTank.setIsPathing(true);
        mouseTank.setEndPathAnimation("yellow");
        mouseTank.setLoopPath(false);
        mouseTank.setSpeed(2);
    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

        update();

        game.batch.begin();

        mouseTank.draw(game.batch);

        game.batch.end();
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {

    }

    private void configureCamera()
    {
        Vector3 camPos = new Vector3(camera.position);

        float size = 800;
        float cameraWidth = 0;
        float cameraHeight = 0;

        if (Gdx.graphics.getHeight() < Gdx.graphics.getWidth())
        {
            cameraWidth = size;
            cameraHeight = size * Gdx.graphics.getHeight() / Gdx.graphics.getWidth();
        }
        else
        {
            cameraWidth = size * Gdx.graphics.getWidth() / Gdx.graphics.getHeight();
            cameraHeight = size;
        }

        camera.setToOrtho(true, cameraWidth, cameraHeight);
        camera.position.set(camPos.x + camera.viewportWidth / 2f, camPos.y + camera.viewportHeight / 2f, 0);
    }

    private void update() {
        int xTouch = Gdx.input.getX(0);
        int yTouch = Gdx.input.getY(0);
        mouseTank.setTarget(xTouch, yTouch);
        mouseTank.update(Gdx.graphics.getDeltaTime());
    }
}

Edit: Just saying now that I've already tried using atan2 in MathUtils and it gave the same results.

The MobileSprite update method

public void update(float deltaTime)
{
    if (active && movingTowardsTarget)
    {
        if ((target != null))
        {
            // Get a vector pointing from the current location of the sprite
            // to the destination.
            Vector2 Delta = new Vector2(target.x - sprite.getX(), target.y - sprite.getY());

            if (Delta.len() > getSpeed())
            {
                Delta.nor();
                Delta.scl(getSpeed());
                getPosition().add(Delta);
            }
            else
            {
                if (target == sprite.getPosition())
                {
                    if (pathing)
                    {
                        if (queuePath.size() > 0)
                        {
                            target = queuePath.remove();
                            if (loopPath)
                            {
                                queuePath.remove(target);
                            }
                        }
                        else
                        {
                            if (!(endPathAnimation == null))
                            {
                                if (!(getSprite().getCurrentAnimation() == endPathAnimation))
                                {
                                    getSprite().setCurrentAnimation(endPathAnimation);
                                }
                            }

                            if (deactivateAtEndOfPath)
                            {
                                setIsActive(false);
                            }

                            if (hideAtEndOfPath)
                            {
                                setIsVisible(false);
                            }
                        }
                    }
                }
                else
                {
                    sprite.setPosition(target);
                }
            }
        }
    }
    if (active)
        sprite.Update(deltaTime);
}

Body:
To get the radians angle:

void updateRotation()
{
    if (rotateByPosition)
    {
        Vector2 rotationVector = new Vector2(position.x - prevPosition.x, position.y - prevPosition.y);
        rotationRad = rotationVector.angleRad();
        rotationDeg = rotationRad * MathUtils.radiansToDegrees;
    }
}

and the draw method needs a degrees angle:

spriteBatch.draw(
            getCurrentTextureRegion(),
            getPosition().x + xOffset - center.x,
            getPosition().y + yOffset - center.y,
            center.x, center.y,
            getCurrentFrameAnimation().getFrameWidth(), getCurrentFrameAnimation().getFrameHeight(),
            1.0f, 1.0f,
            rotationDeg
    );

The screen mouse position is from the upper left corner the renderer needs from the bottom left corner:

int xTouch = Gdx.input.getX(0);
int yTouch = Gdx.graphics.getHeight() - Gdx.input.getY(0);


问:
<input type="hidden"> does not send values to REST
My project's logic is this.

I have an HTML form with a <select multiple> inside that contains a list of String

With an Angular.js function I fill a event-dialog-controller.js variable with selected String

I take that variable called vm.usernames and I set it as value of an <input type="hidden">

I call a REST service with form's data using Spring

Spring automatically converts the input in an object of Event class

What I see in the end is that object

My issue is that the field that should get the vm.usernames value is empty in my REST. I checked up if vm.usernames is correct when I call the form (using console.log(vm.usernames)), it's correct.

How could I fix this problem?

HTML code:

```<code><div class="form-group">
    <label for="field_attendeestoparse">{{vm.usernames}}</label>
    <select class="form-control" multiple ng-model="vm.attendeesToParse" ng-change="vm.selectUsernames(vm.attendeesToParse)"
                    ng-options="customUser as customUser.username for customUser in vm.customusers | orderBy:'id' ">
    </select>
    <input class="form-control" type="hidden" name="attendees" id="field_attendees" ng-model="vm.event.attendees" ng-value="vm.usernames" />

</div>
</code>```

I don't paste here my Angular function because I am sure that it does what it has to do.

A little note. If I use an <input type="text"> with the same attributes as <input type="hidden"> and I insert values from keyboard, it works perfectly. I don't know why that hidden does not send that value.

All the other Event's fields work perfectly.

I know I am missing something, please help me!

答:
I finally solved the problem. It's a pleasure to share the solution, maybe it should be helpful for someone.

I created a new <input type="text" disabled>, with Angular.js' function I fill it with selected options and then I send the form.
In other words, when I click on options they are automatically set as values in input text.

It works really fine, maybe it's not the best semantic solution but it solves the problem and works, so I think to use this version of code.

HTML code:

```<code><div class="form-group">
    <label for="field_attendees">Attendees</label>
    <select class="form-control" multiple ng-model="vm.attendeesToParse" ng-change="vm.selectUsernames(vm.attendeesToParse)"
                    ng-options="customUser as customUser.username for customUser in vm.customusers | orderBy:'id' ">
    </select>
    </br>
    <input disabled type="text" class="form-control" name="attendees" ng-model="vm.event.attendees" id="field_attendees" />
</div>
</code>```

angular.js controller:

```<code>$scope.usernames = '';
    vm.selectUsernames = function(model) {
        $scope.usernames = "";
        for (var i = 0; i < model.length; i++) {
            $scope.usernames += model[i].username + " ";
        }
        vm.event.attendees = $scope.usernames;
};
</code>```

Body:
My project's logic is this.

I have an HTML form with a <select multiple> inside that contains a list of String

With an Angular.js function I fill a event-dialog-controller.js variable with selected String

I take that variable called vm.usernames and I set it as value of an <input type="hidden">

I call a REST service with form's data using Spring

Spring automatically converts the input in an object of Event class

What I see in the end is that object

My issue is that the field that should get the vm.usernames value is empty in my REST. I checked up if vm.usernames is correct when I call the form (using console.log(vm.usernames)), it's correct.

How could I fix this problem?

HTML code:

    {{vm.usernames}}
    <select class="form-control" multiple ng-model="vm.attendeesToParse" ng-change="vm.selectUsernames(vm.attendeesToParse)"
                    ng-options="customUser as customUser.username for customUser in vm.customusers | orderBy:'id' ">
    </select>
    <input class="form-control" type="hidden" name="attendees" id="field_attendees" ng-model="vm.event.attendees" ng-value="vm.usernames" />

I don't paste here my Angular function because I am sure that it does what it has to do.

A little note. If I use an <input type="text"> with the same attributes as <input type="hidden"> and I insert values from keyboard, it works perfectly. I don't know why that hidden does not send that value.

All the other Event's fields work perfectly.

I know I am missing something, please help me!

Body:
I finally solved the problem. It's a pleasure to share the solution, maybe it should be helpful for someone.

I created a new <input type="text" disabled>, with Angular.js' function I fill it with selected options and then I send the form.
In other words, when I click on options they are automatically set as values in input text.

It works really fine, maybe it's not the best semantic solution but it solves the problem and works, so I think to use this version of code.

HTML code:

<div class="form-group">
    <label for="field_attendees">Attendees</label>
    <select class="form-control" multiple ng-model="vm.attendeesToParse" ng-change="vm.selectUsernames(vm.attendeesToParse)"
                    ng-options="customUser as customUser.username for customUser in vm.customusers | orderBy:'id' ">
    </select>
    </br>
    <input disabled type="text" class="form-control" name="attendees" ng-model="vm.event.attendees" id="field_attendees" />
</div>

angular.js controller:

$scope.usernames = '';
    vm.selectUsernames = function(model) {
        $scope.usernames = "";
        for (var i = 0; i < model.length; i++) {
            $scope.usernames += model[i].username + " ";
        }
        vm.event.attendees = $scope.usernames;
};