问:
mysql performance question
Is a search through numbers (INT) faster than characters in an mySQL database?
Regards,
Thijs</p>

答:
If the INT and VARCHAR consumes the same amount of space the difference should be negligible, even though INT probably will come out on top.

Databases don't use black magic. They need to physically access data like everyone else. Table rows consume disk space. Reading 100 mb is faster than reading 200 mb. Always.

Therefore. this affects everything. Smaller rows means more rows per "block". More rows per block means more rows fetched per disk access. Fewer blocks in total means that a larger percentage of the rows will fit in various buffer caches.

Title: mysql performance question


来源: stackexchange

问:
Group duplicate column IDs in pandas dataframe
Now there are a lot of similar questions but most of them answer how to delete the duplicate columns. However, I want to know how can I make a list of tuples where each tuple contains the column names of duplicate columns. I am assuming that each column has a unique name. Just to further illustrate my question:

```<code>df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [2, 4, 2, 1, 9],
                   'C': [1, 2, 3, 4, 5],'D': [2, 4, 2, 1, 9],
                   'E': [3, 4, 2, 1, 2],'F': [1, 1, 1, 1, 1]},
                   index = ['a1', 'a2', 'a3', 'a4', 'a5'])
</code>```

then I want the output:

```<code>[('A', 'C'), ('B', 'D')]
</code>```

And if you are feeling great today then also extend the same question to rows. How to get a list of tuples where each tuple contains duplicate rows.

答:
Here's one more option using only comprehensions/built-ins:

```<code>filter(lambda x: len(x) > 1, list(set([tuple([x for x in df.columns if all(df[x] == df[y])]) for y in df.columns])))
</code>```

Result:

```<code>[('A', 'C'), ('B', 'D')]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Now there are a lot of similar questions but most of them answer how to delete the duplicate columns. However, I want to know how can I make a list of tuples where each tuple contains the column names of duplicate columns. I am assuming that each column has a unique name. Just to further illustrate my question:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [2, 4, 2, 1, 9],
                   'C': [1, 2, 3, 4, 5],'D': [2, 4, 2, 1, 9],
                   'E': [3, 4, 2, 1, 2],'F': [1, 1, 1, 1, 1]},
                   index = ['a1', 'a2', 'a3', 'a4', 'a5'])

then I want the output:

[('A', 'C'), ('B', 'D')]

And if you are feeling great today then also extend the same question to rows. How to get a list of tuples where each tuple contains duplicate rows.

Body:
Here's one more option using only comprehensions/built-ins:

filter(lambda x: len(x) > 1, list(set([tuple([x for x in df.columns if all(df[x] == df[y])]) for y in df.columns])))

Result:

[('A', 'C'), ('B', 'D')]


问:
Amazon S3 as like local files from php and html
I know there's SDK to handle s3 files like uploading and downloading, AND I know s3 files can be accessed by unique url.

HOWEVER,
I'd like to know that there's the best easiest way to access files from PHP script and html script like accessing to local files.

```<code>//Example for html -
<img src='/image/1.jpg'>
</code>```

for this case, I need to change all the url from '/image/1.jpg' to s3 urls.

```<code>//Example for php -
$file = 'assets/jquery.js';
echo '<script src='.$file.'></script>';
</code>```

The only way to access to s3 is that I have to change all local files access relative codes from local directory and file to s3 urls?

Changing all full or absolute file path to be s3 url is not a good way.
But is this only way to do so??

What about S3FU?
It's not recommended but works properly as other say.
Only reading files using S3FU and uploading SDK? what do you think?

答:
If you have S3 compatible bucket you can always use CloudBerry for keeping the same "folder structure"

Then only thing you need to do is to prepend all paths with proper domain.
Does it solve your problem?

Body:
I know there's SDK to handle s3 files like uploading and downloading, AND I know s3 files can be accessed by unique url.

HOWEVER,
I'd like to know that there's the best easiest way to access files from PHP script and html script like accessing to local files.

//Example for html -

for this case, I need to change all the url from '/image/1.jpg' to s3 urls.

//Example for php -
$file = 'assets/jquery.js';
echo '';

The only way to access to s3 is that I have to change all local files access relative codes from local directory and file to s3 urls?

Changing all full or absolute file path to be s3 url is not a good way.
But is this only way to do so??

What about S3FU?
It's not recommended but works properly as other say.
Only reading files using S3FU and uploading SDK? what do you think?


问:
Dedicate every element in a list to a variable
So let's say we have the lists a = [1,2,3,4] and s = ["q", "w", "e", "r"].
I want to dedicate every element in s a value in a, so that print(w) prints 2 and so on. You could write

```<code>for u in range(0, len(a)):
   s[u] = a[u]
</code>```

But here print(w) makes no sense and we get an error.

答:
The following solution does exactly what you have specified, using the built-in exec() function. However, you should never ever ever use it! It is hideously unsafe, and I am only posting it for completeness' sake. Use the solution after it instead.

```<code>for i in range(len(s)):
    exec(s[i] + "=" + str(a[i]))
</code>```

What you should do is use a dictionary:

```<code>myDictionary = dict(zip(s, a))
</code>```

What this does is it matches each element of the lists s and a into key-value pairs in a dictionary by their index (meaning that they are matched based on their order).

And then you can do:

```<code>>>> print(myDictionary["w"])
2
</code>```

Body:
So let's say we have the lists a = [1,2,3,4] and s = ["q", "w", "e", "r"].
I want to dedicate every element in s a value in a, so that print(w) prints 2 and so on. You could write

for u in range(0, len(a)):
   s[u] = a[u]

But here print(w) makes no sense and we get an error.

Body:
The following solution does exactly what you have specified, using the built-in exec() function. However, you should never ever ever use it! It is hideously unsafe, and I am only posting it for completeness' sake. Use the solution after it instead.

for i in range(len(s)):
    exec(s[i] + "=" + str(a[i]))

What you should do is use a dictionary:

myDictionary = dict(zip(s, a))

What this does is it matches each element of the lists s and a into key-value pairs in a dictionary by their index (meaning that they are matched based on their order).

And then you can do:

>>> print(myDictionary["w"])
2


问:
How do you create a table in python from a text file
i have been trying to create a table from a text file like this:

```<code>MemberID  Surname  Year joined  Membership status  Nights booked  Pointsbalance
Jim123    jimmy     2017        gold               10              15000
</code>```

and the text file is like this:

```<code>jim123,jimmy,2017,gold,10,15000
</code>```

how would i do this?
as simple as possible please

答:
If you're going to be using the data for any kind of analysis, try checking out Pandas. Check out this great (and detailed) post on how to achieve what you are trying to do:

https://chrisalbon.com/python/pandas_dataframe_importing_csv.html

This is the code you want (but check out that URL for the explanation):

```<code>df = pd.read_csv('../data/jimmy.csv', names=['MemberID', 'Surname', 'Membership status', 'Nights booked', 'Pointsbalance'])
</code>```

df

or

```<code>raw_data = {'MemberID': ['Jim123', 'Calamari123'],
        'Surname': ['jimmy', 'calamari'],
        'Membership status': ['gold', 'platinum'],
        'Nights booked': [10, 24],
        'Pointsbalance': ["15000", "94,000"]}
    df = pd.DataFrame(raw_data, columns = ['MemberID', 'Surname', 'Membership status', 'Nights booked', 'Pointsbalance'])
</code>```

Body:
i have been trying to create a table from a text file like this:

MemberID  Surname  Year joined  Membership status  Nights booked  Pointsbalance
Jim123    jimmy     2017        gold               10              15000

and the text file is like this:

jim123,jimmy,2017,gold,10,15000

how would i do this?
as simple as possible please

Body:
If you're going to be using the data for any kind of analysis, try checking out Pandas. Check out this great (and detailed) post on how to achieve what you are trying to do:

https://chrisalbon.com/python/pandas_dataframe_importing_csv.html

This is the code you want (but check out that URL for the explanation):

df = pd.read_csv('../data/jimmy.csv', names=['MemberID', 'Surname', 'Membership status', 'Nights booked', 'Pointsbalance'])

df

or

raw_data = {'MemberID': ['Jim123', 'Calamari123'],
        'Surname': ['jimmy', 'calamari'],
        'Membership status': ['gold', 'platinum'],
        'Nights booked': [10, 24],
        'Pointsbalance': ["15000", "94,000"]}
    df = pd.DataFrame(raw_data, columns = ['MemberID', 'Surname', 'Membership status', 'Nights booked', 'Pointsbalance'])


问:
Difference in std::map behavior between debug and release builds (Xcode 8.3, C++ 11, Cocos2d-x)
Running into an unexpected difference in behavior between a debug build built in Xcode 8.3.3, C++11, on the Cocos2d-x framework. I'm using the emplace() method to populate an std::map (_randomLetterChancesToAppear), which is correctly being built in debug, but appears not to be populated in release. This assertion is being tripped at a time when the two values are expected to be equal:

```<code>CC_ASSERT(outCellDetail._randomLetterChancesToAppear.size() == alphabetCount);
</code>```

When the assert trips in a release build, _randomLetterChancesToAppear doesn't appear to contain any data. (To test this, in case it's relevant, I created a duplicate Xcode scheme to my default mobile scheme, and changed the Run build configuration to release to allow me to test a release build with the IDE attached.)

Here's the offending method:

```<code>void GameDataController::PopulateIndividualCellChancesToAppear(CellDetail &outCellDetail, const rapidjson::Value &cellDetailObject, const GameDetail& constGameDetail) const
{
    cocostudio::DictionaryHelper* dicTool = cocostudio::DictionaryHelper::getInstance();
    CC_ASSERT(dicTool->checkObjectExist_json(cellDetailObject, "LetterChancesToAppear"));
    CCASSERT(constGameDetail._alphabet.length() > 0, "Zero-length alphabet!");

    const rapidjson::Value& letterChancesObject = dicTool->getSubDictionary_json(cellDetailObject, "LetterChancesToAppear");

    // iterate through each letter in this game detail's alphabet
    const int alphabetCount = static_cast<int>(constGameDetail._alphabet.length());
    std::vector<char> lettersNeedingChances;
    for (int i = 0; i < alphabetCount; ++i)
    {
        // if a given alphabet letter has a chance to appear, save it.
        const char alphabetChar = constGameDetail._alphabet.at(i);
        char letterChanceKey[1];
        sprintf(letterChanceKey, "%c", alphabetChar);
        if (dicTool->checkObjectExist_json(letterChancesObject, letterChanceKey))
        {
            const float ChanceToAppear = dicTool->getFloatValue_json(letterChancesObject, letterChanceKey);
            CC_ASSERT(!std::isnan(ChanceToAppear));
            CC_ASSERT(ChanceToAppear >= 0.0f);
            outCellDetail._randomLetterChancesToAppear.emplace(alphabetChar, !std::isnan(ChanceToAppear) ? ChanceToAppear : 0.0f);
        }
        else
        {
            // ... otherwise, store the letter in a list of letters without assigned chances.
            lettersNeedingChances.push_back(alphabetChar);
        }
    }

    // fill in missing chances to appear.
    if (lettersNeedingChances.size() > 0)
    {
        float defaultRemainingChance = 1.0f / static_cast<float>(alphabetCount);
        CC_ASSERT(!std::isnan(defaultRemainingChance));
        CC_ASSERT(defaultRemainingChance > FLT_EPSILON);
        for (const char remainingChar : lettersNeedingChances)
        {
            CCLOG("Character %c doesn't have a chance to appear specified. Using default %f", remainingChar, defaultRemainingChance);
            outCellDetail._randomLetterChancesToAppear.emplace(remainingChar, defaultRemainingChance);
        }
    }
    // vvvv THIS ASSERT IS FAILING IN RELEASE, BUT NOT IN DEBUG BUILD CONFIGURATIONS. vvvvv
    CC_ASSERT(outCellDetail._randomLetterChancesToAppear.size() == alphabetCount);

    // normalize chances to appear.
    float chanceTotal = 0.0f;
    for(auto iterator = outCellDetail._randomLetterChancesToAppear.begin();
        iterator != outCellDetail._randomLetterChancesToAppear.end();
        iterator++)
    {
        chanceTotal += iterator->second;
    }

    if (std::abs(chanceTotal - 1.0f) > FLT_EPSILON)
    {
        float adjustmentFactor = 1.0f / chanceTotal;
        float adjustedChanceTotal = 0.0f;
        for(auto iterator = outCellDetail._randomLetterChancesToAppear.begin();
            iterator != outCellDetail._randomLetterChancesToAppear.end();
            iterator++)
        {
            iterator->second = iterator->second * adjustmentFactor;
            adjustedChanceTotal += iterator->second;
        }
        CCASSERT(std::abs(adjustedChanceTotal - 1.0f) <= FLT_EPSILON, "adjustedChanceTotal != 1.0f");
    }
}
</code>```

Any thoughts on why this method might be behaving differently between the two build configurations?

答:
Credit goes to Igor Tandetnik for the answer.

```<code>    char letterChanceKey[1];
    sprintf(letterChanceKey, "%c", alphabetChar);
</code>```

did not leave enough room for the terminating NUL and caused a buffer overrun. Increasing the buffer size fixed the problem.

Thank you Igor!

Body:
Running into an unexpected difference in behavior between a debug build built in Xcode 8.3.3, C++11, on the Cocos2d-x framework. I'm using the emplace() method to populate an std::map (_randomLetterChancesToAppear), which is correctly being built in debug, but appears not to be populated in release. This assertion is being tripped at a time when the two values are expected to be equal:

CC_ASSERT(outCellDetail._randomLetterChancesToAppear.size() == alphabetCount);

When the assert trips in a release build, _randomLetterChancesToAppear doesn't appear to contain any data. (To test this, in case it's relevant, I created a duplicate Xcode scheme to my default mobile scheme, and changed the Run build configuration to release to allow me to test a release build with the IDE attached.)

Here's the offending method:

void GameDataController::PopulateIndividualCellChancesToAppear(CellDetail &outCellDetail, const rapidjson::Value &cellDetailObject, const GameDetail& constGameDetail) const
{
    cocostudio::DictionaryHelper* dicTool = cocostudio::DictionaryHelper::getInstance();
    CC_ASSERT(dicTool->checkObjectExist_json(cellDetailObject, "LetterChancesToAppear"));
    CCASSERT(constGameDetail._alphabet.length() > 0, "Zero-length alphabet!");

    const rapidjson::Value& letterChancesObject = dicTool->getSubDictionary_json(cellDetailObject, "LetterChancesToAppear");

    // iterate through each letter in this game detail's alphabet
    const int alphabetCount = static_cast<int>(constGameDetail._alphabet.length());
    std::vector<char> lettersNeedingChances;
    for (int i = 0; i < alphabetCount; ++i)
    {
        // if a given alphabet letter has a chance to appear, save it.
        const char alphabetChar = constGameDetail._alphabet.at(i);
        char letterChanceKey[1];
        sprintf(letterChanceKey, "%c", alphabetChar);
        if (dicTool->checkObjectExist_json(letterChancesObject, letterChanceKey))
        {
            const float ChanceToAppear = dicTool->getFloatValue_json(letterChancesObject, letterChanceKey);
            CC_ASSERT(!std::isnan(ChanceToAppear));
            CC_ASSERT(ChanceToAppear >= 0.0f);
            outCellDetail._randomLetterChancesToAppear.emplace(alphabetChar, !std::isnan(ChanceToAppear) ? ChanceToAppear : 0.0f);
        }
        else
        {
            // ... otherwise, store the letter in a list of letters without assigned chances.
            lettersNeedingChances.push_back(alphabetChar);
        }
    }

    // fill in missing chances to appear.
    if (lettersNeedingChances.size() > 0)
    {
        float defaultRemainingChance = 1.0f / static_cast<float>(alphabetCount);
        CC_ASSERT(!std::isnan(defaultRemainingChance));
        CC_ASSERT(defaultRemainingChance > FLT_EPSILON);
        for (const char remainingChar : lettersNeedingChances)
        {
            CCLOG("Character %c doesn't have a chance to appear specified. Using default %f", remainingChar, defaultRemainingChance);
            outCellDetail._randomLetterChancesToAppear.emplace(remainingChar, defaultRemainingChance);
        }
    }
    // vvvv THIS ASSERT IS FAILING IN RELEASE, BUT NOT IN DEBUG BUILD CONFIGURATIONS. vvvvv
    CC_ASSERT(outCellDetail._randomLetterChancesToAppear.size() == alphabetCount);

    // normalize chances to appear.
    float chanceTotal = 0.0f;
    for(auto iterator = outCellDetail._randomLetterChancesToAppear.begin();
        iterator != outCellDetail._randomLetterChancesToAppear.end();
        iterator++)
    {
        chanceTotal += iterator->second;
    }

    if (std::abs(chanceTotal - 1.0f) > FLT_EPSILON)
    {
        float adjustmentFactor = 1.0f / chanceTotal;
        float adjustedChanceTotal = 0.0f;
        for(auto iterator = outCellDetail._randomLetterChancesToAppear.begin();
            iterator != outCellDetail._randomLetterChancesToAppear.end();
            iterator++)
        {
            iterator->second = iterator->second * adjustmentFactor;
            adjustedChanceTotal += iterator->second;
        }
        CCASSERT(std::abs(adjustedChanceTotal - 1.0f) <= FLT_EPSILON, "adjustedChanceTotal != 1.0f");
    }
}

Any thoughts on why this method might be behaving differently between the two build configurations?

Body:
Credit goes to Igor Tandetnik for the answer.

    char letterChanceKey[1];
    sprintf(letterChanceKey, "%c", alphabetChar);

did not leave enough room for the terminating NUL and caused a buffer overrun. Increasing the buffer size fixed the problem.

Thank you Igor!


问:
Default method arguments don't work
Cython doesn't seem to recognize, that the sf::RenderTarget.clear() method can be called with different arguments and allows to call only the last declared variant in .pxd.

SFML's header file (source):

```<code>class RenderTarget {
    void clear(const Color& color = Color(0, 0, 0, 255));
}
</code>```

My Cython .pxd:

```<code>cdef extern from 'SFML/Graphics.hpp' namespace 'sf' nogil:
    cppclass CRenderTarget 'sf::RenderTarget':
        void clear()
        void clear(const CColor&)

    cppclass CRenderWindow 'sf::RenderWindow' (CWindow, CRenderTarget):
        ...
</code>```

My Cython wrapper:

```<code>cdef class RenderWindow(Window):
    cdef CWindow* c

    def __init__(self, ...):
        self.c = new CRenderWindow()
        ...

    def clear(self, Color color=None):
        if color is None:
            (<CRenderWindow*>self.c).clear()  # The error points here
        else:
            (<CRenderWindow*>self.c).clear(color.c[0])
</code>```

Compilation error: Call with wrong number of arguments (expected 1, got 0)

So I can call only whe .clear(color) variant and not the one with a default argument .clear(). What I'm doing wrong?

My implementation tries to follow what is explained here, but I can't get it to work.

答:
I have given aliases (C names) for methods in similar situations. In this case</p>

```<code>cdef extern from 'SFML/Graphics.hpp' namespace 'sf' nogil:
    cppclass CRenderTarget 'sf::RenderTarget':
        void clear0 "clear" ()
</code>```

Title: Default method arguments don't work

Body:
Cython doesn't seem to recognize, that the sf::RenderTarget.clear() method can be called with different arguments and allows to call only the last declared variant in .pxd.

SFML's header file (source):

class RenderTarget {
    void clear(const Color& color = Color(0, 0, 0, 255));
}

My Cython .pxd:

cdef extern from 'SFML/Graphics.hpp' namespace 'sf' nogil:
    cppclass CRenderTarget 'sf::RenderTarget':
        void clear()
        void clear(const CColor&)

    cppclass CRenderWindow 'sf::RenderWindow' (CWindow, CRenderTarget):
        ...

My Cython wrapper:

cdef class RenderWindow(Window):
    cdef CWindow* c

    def __init__(self, ...):
        self.c = new CRenderWindow()
        ...

    def clear(self, Color color=None):
        if color is None:
            (<CRenderWindow*>self.c).clear()  # The error points here
        else:
            (<CRenderWindow*>self.c).clear(color.c[0])

Compilation error: Call with wrong number of arguments (expected 1, got 0)

So I can call only whe .clear(color) variant and not the one with a default argument .clear(). What I'm doing wrong?

My implementation tries to follow what is explained here, but I can't get it to work.

Body:
I have given aliases (C names) for methods in similar situations. In this case

cdef extern from 'SFML/Graphics.hpp' namespace 'sf' nogil:
    cppclass CRenderTarget 'sf::RenderTarget':
        void clear0 "clear" ()


问:
Python: How to "redo" an iteration of a for loop?
I have this piece of code (for practice):

```<code>def choose_dice():
    while True:
        try:
            dice_quantity = int(input("How many dice would you like to use? "))
            dice_sides = []
            for current_dice in range(1, dice_quantity + 1):
                sides = int(input("How many sides on {} dice? ".format(str(current_dice) + ordinal(current_dice))))
                dice_sides.append([str(current_dice) + ordinal(current_dice) + " dice", sides])
#               print(dice_sides)
            return dice_sides
        except (TypeError, ValueError) as _:
            print("Oops, it seems you have entered a non integer ")
</code>```

Which prompts the user for a number and then for x in range(1, number) prompts the user to chose a number.

In the case of the user typing in a non integer or nothing whilst in the for loop, I want to return to the current iteration of the for loop instead of starting all over.

How can I elegantly achieve this?

i.e the current behavior is as such:

"How many dice would you like to use? 3

How many sides on 1st dice? 6

How many sides on 2nd dice? 0

How many sides on 3rd dice?

Oops, it seems you have entered a non integer

How many dice would you like to use? "

If a user doesn't enter anything, it gets caught in the exception and the whole process starts over. I want it to retry the current "How many sides on n'th dice?" instead of starting the loop from scratch

答:
try this:</p>

```<code>def choose_dice():
    while True:
        try:
            dice_quantity = int(input("How many dice would you like to use? "))
        except (TypeError, ValueError) as _:
            print("Oops, it seems you have entered a non integer ")

        dice_sides = []
        current_dice = 1
        while current_dice != dice_quantity + 1:
            try:
                sides = int(input("How many sides on {} dice? ".format(str(current_dice) + ordinal(current_dice))))
                dice_sides.append([str(current_dice) + ordinal(current_dice) + " dice", sides])
                current_dice += 1
            except (TypeError, ValueError, NameError) as _:
                print("Oops, it seems you have entered a non integer ")
        print(dice_sides)
        return dice_sides
</code>```

Body:
I have this piece of code (for practice):

def choose_dice():
    while True:
        try:
            dice_quantity = int(input("How many dice would you like to use? "))
            dice_sides = []
            for current_dice in range(1, dice_quantity + 1):
                sides = int(input("How many sides on {} dice? ".format(str(current_dice) + ordinal(current_dice))))
                dice_sides.append([str(current_dice) + ordinal(current_dice) + " dice", sides])
#               print(dice_sides)
            return dice_sides
        except (TypeError, ValueError) as _:
            print("Oops, it seems you have entered a non integer ")

Which prompts the user for a number and then for x in range(1, number) prompts the user to chose a number.

In the case of the user typing in a non integer or nothing whilst in the for loop, I want to return to the current iteration of the for loop instead of starting all over.

How can I elegantly achieve this?

i.e the current behavior is as such:

"How many dice would you like to use? 3

How many sides on 1st dice? 6

How many sides on 2nd dice? 0

How many sides on 3rd dice?

Oops, it seems you have entered a non integer

How many dice would you like to use? "

If a user doesn't enter anything, it gets caught in the exception and the whole process starts over. I want it to retry the current "How many sides on n'th dice?" instead of starting the loop from scratch

Body:
try this:

def choose_dice():
    while True:
        try:
            dice_quantity = int(input("How many dice would you like to use? "))
        except (TypeError, ValueError) as _:
            print("Oops, it seems you have entered a non integer ")

        dice_sides = []
        current_dice = 1
        while current_dice != dice_quantity + 1:
            try:
                sides = int(input("How many sides on {} dice? ".format(str(current_dice) + ordinal(current_dice))))
                dice_sides.append([str(current_dice) + ordinal(current_dice) + " dice", sides])
                current_dice += 1
            except (TypeError, ValueError, NameError) as _:
                print("Oops, it seems you have entered a non integer ")
        print(dice_sides)
        return dice_sides


问:
Changing camera in two different scenes in Unity
I have a mobile game, and this game have two different scenes. I want to do in first scene the camera should be vertical, and in second scene the camera should be horizontal. However, when I change the scene the camera always be vertical. How can I fix this.</p>

答:
You can attach a script to your cameras and use the following to change the screen orientation:

i.e. to set screen vertical

Screen.orientation = ScreenOrientation.Portrait;


问:
Why I am redirected to different plugin page url after activating any other plugins in wordpress?
Plese help me figure out this bug.

Problem:
I had installed a syntax highlighter plugin named "Enlighter". But it didn't work as I expected. So I went ahead and deactivated and deleted the plugin files.

Now the problem is that whenever I am trying to activate any other plugins it is redirecting me to the "enlighter" about page. Here's what my url looks when I try to activate any plugins: http://localhost/wp/wp-admin/admin.php?page=Enlighter-About

When I tried to activate TinyMCE Advanced Plugin it is redirected to the above-mentioned URL. You can read the error message in the screenshot attached. However, when I press the back button I can see the "TinyMCE" plugin activated.

I want to know how to fix the problem so that it is redirected to its relevant plugin page instead of enlighter's plugin page.

Thank you!

答:
Okay, So after sharing this problem with "englighter's" plugin developer on the WordPress forum he asked me to clear the browser cache and php op-code cache.

So I resolved this problem by clearing all the browser cache and then everything worked fine for me.

Here's our discussion thread on WordPress https://wordpress.org/support/topic/wrong-plugin-page-redirection-upon-activating-any-plugin/#post-9302622


问:
Center an item between two other items in autolayout (iOS)
I have 5 items on the top of my View Controller, and I am trying to space them evenly with autolayout.  For the left item (back button), I added a constraint to be 15px from the left border, and for the right item (camera), I added a constraint to be 15px from the right border. Then, I set up the center item (0:01) to align center x so it is in the middle.  Lastly, I selected "Reset to suggested constraints" for the ... and the flash item.

Upon looking at it in the iphone 5 and 4, it looks great.  As you can see, all the items are evenly divided:

So far, everything is going smoothly.  HOWEVER, when I test on the iphone6 and iphone6+, the "..." and the flash symbol are not centered between the < and the 0:01, as depicted:

How do you center an item between two neighboring items?  Aka, how to I center the "..." to be exactly in between the < and 0:01??  This simple task is taking me hours, and I don't understand why Xcode doesnt have a center between two neighbors.

Any help would be greatly appreciated!

答: Just to add: If you use UIImageView as container, then it is already transparent as you don't populate it with an image. Also, the top and bottom handles are easy to position</p>


问:
Register class-based task in
I am using Celery version 4.0.2.

Compared to previous versions of Celery, it seems that class-based tasks are not registered automatically (i.e. if you configured auto-discovery).

However, I do not even achieve registering a class-based task manually.

According to the Celery change log:

http://docs.celeryproject.org/en/latest/changelog.html#version-4-0-1

since version 4.0.1 it should be possible to register the task manually:

```<code>from celery import Celery, Task
app = Celery()

class CustomTask(Task):

    def run(self):
        return 'hello'

app.register_task(CustomTask())
</code>```

But this does not seem to work. Does anyone know how to achieve this?

I tried a few suggestions which are being discussed (apart from integrating a custom task loader mentioned in https://github.com/celery/celery/issues/3744):

Register Celery Class-based Task

https://github.com/celery/celery/issues/3615

https://github.com/celery/celery/issues/3744

答:
If You need shared_task decorator:

```<code>from celery import Task, shared_task

class CustomTask(Task):
    def process(self):
        return 'hello'

@shared_task(bind=True, base=CustomTask)
def custom(self):
    self.process()
</code>```

process is a custom name that starts task (decorator overrides run method)

bind=True binds function to a class instance

base=CustomTask sets a base class for a task

Title: Register class-based task in

Body:
I am using Celery version 4.0.2.

Compared to previous versions of Celery, it seems that class-based tasks are not registered automatically (i.e. if you configured auto-discovery).

However, I do not even achieve registering a class-based task manually.

According to the Celery change log:

http://docs.celeryproject.org/en/latest/changelog.html#version-4-0-1

since version 4.0.1 it should be possible to register the task manually:

from celery import Celery, Task
app = Celery()

class CustomTask(Task):

    def run(self):
        return 'hello'

app.register_task(CustomTask())

But this does not seem to work. Does anyone know how to achieve this?

I tried a few suggestions which are being discussed (apart from integrating a custom task loader mentioned in https://github.com/celery/celery/issues/3744):

Register Celery Class-based Task

https://github.com/celery/celery/issues/3615

https://github.com/celery/celery/issues/3744

Body:
If You need shared_task decorator:

from celery import Task, shared_task

class CustomTask(Task):
    def process(self):
        return 'hello'

@shared_task(bind=True, base=CustomTask)
def custom(self):
    self.process()

process is a custom name that starts task (decorator overrides run method)

bind=True binds function to a class instance

base=CustomTask sets a base class for a task


问:
Why new operator hangs my program?
I use Arduino but I think this is not Arduino related problem, but I do not understand something.
When I use the following code all works perfectly:

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

typedef struct strRec {
    int entry1;
    int entry2;
} Rec;

Rec tab[3] = {
    { 700, 7000 },
    { 300, 3000 },
    { 1000, 1000 },

};

Queue q(sizeof(Rec), 2, FIFO);  // Instantiate queue

void setup() {
    Serial.begin(19200);

    unsigned int i;

    for (i = 0 ; i < 3 ; i++)
    {
        Rec rec = tab[i];
        q.push(&rec);
    }

    for (i = 0 ; i < 5 ; i++)
    {
        Rec rec;
        if(q.pop(&rec)) {
        Serial.print(rec.entry1);
        Serial.print(" ");
        Serial.println(rec.entry2);
        }
        else {
            Serial.println("No records");
        }
    }

}
</code>```

But when I create an instance using new the program hangs after the operator: no operations performerd after it.

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

typedef struct strRec {
    int entry1;
    int entry2;
} Rec;

Rec tab[3] = {
    { 700, 7000 },
    { 300, 3000 },
    { 1000, 1000 },

};

Queue* q;

void setup() {
    Serial.begin(19200);

    q = new Queue(sizeof(Rec), 2, FIFO);

    unsigned int i;

    for (i = 0 ; i < 3 ; i++)
    {
        Rec rec = tab[i];
        q->push(&rec);
    }

    for (i = 0 ; i < 5 ; i++)
    {
        Rec rec;
        if(q->pop(&rec)) {
        Serial.print(rec.entry1);
        Serial.print(" ");
        Serial.println(rec.entry2);
        }
        else {
            Serial.println("No records");
        }
    }

}
</code>```

But if I do not call any method of Queue class but only create it the code below can be executed

```<code>Serial.println("some text before"); //this text can be printed
q = new Queue(sizeof(Rec), 2, FIFO);
Serial.println("some text after"); //this text can be printed too
</code>```

if I have method call here, the call hangs program right after the new, but not after method call

```<code>Serial.println("some text before"); //this text can be printed
q = new Queue(sizeof(Rec), 2, FIFO);
Serial.println("some text after"); //this text can not be printed and the program hangs here
Rec rec = tab[1];
q->push(&rec);
</code>```

I even tried to change push method to do nothing but the code hangs.
If I comment the string with free my code works normally, so the problem is here but I do not understad why

```<code>Queue::Queue(uint16_t size_rec, uint16_t nb_recs, QueueType type, bool overwrite)
{

    rec_nb = nb_recs;
    rec_sz = size_rec;
    impl = type;
    ovw = overwrite;

    if (queue)  { free(queue); }    // If I comment this string it works as I need
    queue = (uint8_t *) malloc(nb_recs * size_rec);

    clean();
}

Queue::~Queue()
{
  free(queue);
}

void Queue::clean(void)
{
    in = 0;
    out = 0;
    cnt = 0;
}
</code>```

Why it happens? What I do not understand?

Here is the Queue class

答:
There is this line in the constructor:

```<code>if (queue) { free(queue); } // Free existing data (if any)
</code>```

where queue is a data member. You are trying to free a garbage pointer value (that just happened to be non-zero) that you never initialized, thus invoking UB. Why do you believe this needed to be done at all?

Title: Why new operator hangs my program?

Body:
I use Arduino but I think this is not Arduino related problem, but I do not understand something.
When I use the following code all works perfectly:

#include <Queue.h>

typedef struct strRec {
    int entry1;
    int entry2;
} Rec;

Rec tab[3] = {
    { 700, 7000 },
    { 300, 3000 },
    { 1000, 1000 },

};

Queue q(sizeof(Rec), 2, FIFO);  // Instantiate queue

void setup() {
    Serial.begin(19200);

    unsigned int i;

    for (i = 0 ; i < 3 ; i++)
    {
        Rec rec = tab[i];
        q.push(&rec);
    }

    for (i = 0 ; i < 5 ; i++)
    {
        Rec rec;
        if(q.pop(&rec)) {
        Serial.print(rec.entry1);
        Serial.print(" ");
        Serial.println(rec.entry2);
        }
        else {
            Serial.println("No records");
        }
    }

}

But when I create an instance using new the program hangs after the operator: no operations performerd after it.

#include <Queue.h>

typedef struct strRec {
    int entry1;
    int entry2;
} Rec;

Rec tab[3] = {
    { 700, 7000 },
    { 300, 3000 },
    { 1000, 1000 },

};

Queue* q;

void setup() {
    Serial.begin(19200);

    q = new Queue(sizeof(Rec), 2, FIFO);

    unsigned int i;

    for (i = 0 ; i < 3 ; i++)
    {
        Rec rec = tab[i];
        q->push(&rec);
    }

    for (i = 0 ; i < 5 ; i++)
    {
        Rec rec;
        if(q->pop(&rec)) {
        Serial.print(rec.entry1);
        Serial.print(" ");
        Serial.println(rec.entry2);
        }
        else {
            Serial.println("No records");
        }
    }

}

But if I do not call any method of Queue class but only create it the code below can be executed

Serial.println("some text before"); //this text can be printed
q = new Queue(sizeof(Rec), 2, FIFO);
Serial.println("some text after"); //this text can be printed too

if I have method call here, the call hangs program right after the new, but not after method call

Serial.println("some text before"); //this text can be printed
q = new Queue(sizeof(Rec), 2, FIFO);
Serial.println("some text after"); //this text can not be printed and the program hangs here
Rec rec = tab[1];
q->push(&rec);

I even tried to change push method to do nothing but the code hangs.
If I comment the string with free my code works normally, so the problem is here but I do not understad why

Queue::Queue(uint16_t size_rec, uint16_t nb_recs, QueueType type, bool overwrite)
{

    rec_nb = nb_recs;
    rec_sz = size_rec;
    impl = type;
    ovw = overwrite;

    if (queue)  { free(queue); }    // If I comment this string it works as I need
    queue = (uint8_t *) malloc(nb_recs * size_rec);

    clean();
}

Queue::~Queue()
{
  free(queue);
}

void Queue::clean(void)
{
    in = 0;
    out = 0;
    cnt = 0;
}

Why it happens? What I do not understand?

Here is the Queue class

Body:
There is this line in the constructor:

if (queue) { free(queue); } // Free existing data (if any)

where queue is a data member. You are trying to free a garbage pointer value (that just happened to be non-zero) that you never initialized, thus invoking UB. Why do you believe this needed to be done at all?


问:
How can i make custom buttons to control the <embed>?
Im trying to play some sound(mp3) in my browser. Found <embed> but the default controllers (pause button, volume and timeslider) aint really pretty so what im wondering is how i could control it with some jquery buttons?

i would then hide the embed and call controls with jquery and the embed tags id.

Is this possible, and where could i find a overview of that?

答:
I agree with Fusion on that fact that HTML5 is probably the easiest way to go with the best result. However what are you going to do with the non-HTML5 compliant browsers? What about mobile?

My suggestion would be to use the HTML5 solution with compliant browsers, and a jQuery fall back solution for non-HTML5 browsers. That way the users with the most current technology get the best solution, but you don't leave everyone else behind.

jQuery has a wonderful ability to modify DOM so swapping out files in the tag would not be an issue. Check out this sound plugin ( http://plugins.jquery.com/project/sound_plugin ) and see if that fits your need.

ContentLicense: CC BY-SA 2.5


问:
Working with variable sized lists with Cython
I want to cythonise the python implementation of the Sutherland-Hogman algorithm. This algorithm updates a list of vertices according to pretty simple rules (being inside or outside an edge, etc.) but the details are not important. Here is the python version it accepts lists of vertices of polygons oriented clockwise. For instance those:

```<code>sP=[(50, 150),  (200, 50),  (350, 150), (350, 300), (250, 300), (200, 250), (150, 350),(100, 250), (100, 200)]
cP=[(100, 100), (300, 100), (300, 300), (100, 300)]
</code>```

and calculate their intersection:

```<code>inter=clip(sP, cP)
</code>```

Here is the code found on rosettacode and slightly modified to return an empty list if there is no intersection.

```<code>def clip(subjectPolygon, clipPolygon):
   def inside(p):
      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])

   def computeIntersection():
      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]
      dp = [ s[0] - e[0], s[1] - e[1] ]
      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
      n2 = s[0] * e[1] - s[1] * e[0]
      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]

   outputList = subjectPolygon
   cp1 = clipPolygon[-1]

   for clipVertex in clipPolygon:
      cp2 = clipVertex
      inputList = outputList
      outputList = []
      s = inputList[-1]

      for subjectVertex in inputList:
         e = subjectVertex
         if inside(e):
            if not inside(s):
               outputList.append(computeIntersection())
            outputList.append(e)
         elif inside(s):
            outputList.append(computeIntersection())
         s = e
      if len(outputList)<1:
          return []
      cp1 = cp2
   return(outputList)
</code>```

This function is excruciatingly slow for my applications so I tried to cythonize it using numpy. Here is my cython version. I had to define the two functions outside clip because I had error messages about buffer inputs.

cython1

```<code>cimport cython
import numpy as np
cimport numpy as np

def clip(np.ndarray[np.float32_t, ndim=2] subjectPolygon,np.ndarray[np.float32_t, ndim=2] clipPolygon):

    outputList = list(subjectPolygon)
    cdef np.ndarray[np.float32_t, ndim=1] cp1 = clipPolygon[-1,:]
    cdef np.ndarray[np.float32_t, ndim=1] cp2

    for i in xrange(clipPolygon.shape[0]):
       cp2 = clipPolygon[i]
       inputList = outputList
       outputList = []
       s = inputList[-1]

       for subjectVertex in inputList:
          e = subjectVertex
          if inside(e, cp1, cp2):
             if not inside(s, cp1, cp2):
                outputList.append(computeIntersection(cp1, cp2, e, s))
             outputList.append(e)
          elif inside(s, cp1, cp2):
             outputList.append(computeIntersection(cp1, cp2, e, s))
          s = e
       if len(outputList)<1:
         return []
       cp1 = cp2

    return(outputList)

def computeIntersection(np.ndarray[np.float32_t, ndim=1] cp1, np.ndarray[np.float32_t, ndim=1] cp2, np.ndarray[np.float32_t, ndim=1] e, np.ndarray[np.float32_t, ndim=1] s):
    cdef np.ndarray[np.float32_t, ndim=1] dc = cp1-cp2
    cdef np.ndarray[np.float32_t, ndim=1] dp = s-e
    cdef np.float32_t n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
    cdef np.float32_t n2 = s[0] * e[1] - s[1] * e[0]
    cdef np.float32_t n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
    cdef np.ndarray[np.float32_t, ndim=1] res=np.array([(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3], dtype=np.float32)
    return res

def inside(np.ndarray[np.float32_t, ndim=1] p, np.ndarray[np.float32_t, ndim=1] cp1, np.ndarray[np.float32_t, ndim=1] cp2):
    cdef bint b=(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])
    return b
</code>```

When I time the two versions I gained only a factor of two in speed-up I need at least 10 times that (or 100x !). Is there something to do ?
How does one deal with list with Cython ?

EDIT 1: I followed @DavidW's advice I allocate numpy arrays and trim them instead of using list and I am now using cdef functions, which are supposed to bring 10 times speed up, unfortunately I am seeing no speed-up at all !

cython2

```<code>cimport cython
import numpy as np
cimport numpy as np

@cython.boundscheck(False)
@cython.wraparound(False)
def clip(np.ndarray[np.float32_t, ndim=2] subjectPolygon,np.ndarray[np.float32_t, ndim=2] clipPolygon):
    return clip_in_c(subjectPolygon, clipPolygon)

@cython.boundscheck(False)
@cython.wraparound(False)
cdef np.ndarray[np.float32_t, ndim=2] clip_in_c(np.ndarray[np.float32_t, ndim=2] subjectPolygon,np.ndarray[np.float32_t, ndim=2] clipPolygon):

    cdef int cp_size=clipPolygon.shape[0]
    cdef int outputList_effective_size=subjectPolygon.shape[0]
    cdef int inputList_effective_size=outputList_effective_size
    #We allocate a fixed size array of size
    cdef int max_size_inter=outputList_effective_size*cp_size
    cdef int k=-1

    cdef np.ndarray[np.float32_t, ndim=2] outputList=np.empty((max_size_inter,2), dtype=np.float32)
    cdef np.ndarray[np.float32_t, ndim=2] inputList=np.empty((max_size_inter,2), dtype=np.float32)
    cdef np.ndarray[np.float32_t, ndim=1] cp1 = clipPolygon[cp_size-1,:]
    cdef np.ndarray[np.float32_t, ndim=1] cp2=np.empty((2,), dtype=np.float32)

    outputList[:outputList_effective_size]=subjectPolygon
    for i in xrange(cp_size):

        cp2 = clipPolygon[i]
        inputList[:outputList_effective_size] = outputList[:outputList_effective_size]
        inputList_effective_size=outputList_effective_size
        outputList_effective_size=0
        s = inputList[inputList_effective_size-1]

        for j in xrange(inputList_effective_size):
            e = inputList[j]
            if inside(e, cp1, cp2):
                if not inside(s, cp1, cp2):
                    k+=1
                    outputList[k]=computeIntersection(cp1, cp2, e, s)

                k+=1
                outputList[k]=e

            elif inside(s, cp1, cp2):
                k+=1
                outputList[k]=computeIntersection(cp1, cp2, e, s)

            s = e

        if k<0:
            return np.empty((0,0),dtype=np.float32)

        outputList_effective_size=k+1

        cp1 = cp2
        k=-1

    return outputList[:outputList_effective_size]

cdef np.ndarray[np.float32_t, ndim=1] computeIntersection(np.ndarray[np.float32_t, ndim=1] cp1, np.ndarray[np.float32_t, ndim=1] cp2, np.ndarray[np.float32_t, ndim=1] e, np.ndarray[np.float32_t, ndim=1] s):
    cdef np.ndarray[np.float32_t, ndim=1] dc = cp1-cp2
    cdef np.ndarray[np.float32_t, ndim=1] dp = s-e
    cdef np.float32_t n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
    cdef np.float32_t n2 = s[0] * e[1] - s[1] * e[0]
    cdef np.float32_t n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
    return np.array([(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3], dtype=np.float32)

cdef bint inside(np.ndarray[np.float32_t, ndim=1] p, np.ndarray[np.float32_t, ndim=1] cp1, np.ndarray[np.float32_t, ndim=1] cp2):
    return (cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])
</code>```

Here is the benchmarks:

```<code>import numpy as np
from cython1 import clip_cython1
from cython2 import clip_cython2
import time

sp=np.array([[50, 150],[200,50],[350,150],[250,300],[200,250],[150,350],[100,250],[100,200]],dtype=np.float32)
cp=np.array([[100,100],[300,100],[300,300],[100,300]],dtype=np.float32)

t1=time.time()
for i in xrange(120000):
    a=clip_cython1(sp, cp)
t2=time.time()
print (t2-t1)

t1=time.time()
for i in xrange(120000):
    a=clip_cython2(sp, cp)
t2=time.time()
print (t2-t1)
</code>```

39.45

44.12

The second one is even worse !

EDIT 2 The best answer coming from @Peter Taylor from CodeReview use the fact that each time you compute inside_s it is redundant because s=e and you already calculated inside_e (and to factorize dc and n1 out of the functions but it does not help much).

```<code>cimport cython
import numpy as np
cimport numpy as np

def clip(np.ndarray[np.float32_t, ndim=2] subjectPolygon,np.ndarray[np.float32_t, ndim=2] clipPolygon):

    outputList = list(subjectPolygon)
    cdef np.ndarray[np.float32_t, ndim=1] cp1 = clipPolygon[-1,:]
    cdef np.ndarray[np.float32_t, ndim=1] cp2
    cdef bint inside_e, inside_s
    cdef np.float32_t n1
    cdef np.ndarray[np.float32_t, ndim=1] dc
    cdef int i

    for i in range(clipPolygon.shape[0]):

       cp2 = clipPolygon[i]
       #intermediate
       n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
       dc=cp1-cp2
       inputList = outputList
       outputList = []
       s = inputList[-1]

       inside_s=inside(s, cp1, dc)
       for index, subjectVertex in enumerate(inputList):

           e = subjectVertex
           inside_e=inside(e, cp1, dc)
           if inside_e:

               if not inside_s:
                   outputList.append(computeIntersection(dc, n1, e, s))
               outputList.append(e)

           elif inside_s:
               outputList.append(computeIntersection(dc, n1, e, s))

           s = e
           inside_s=inside_e

       if len(outputList)<1:
           return []
       cp1 = cp2

    return(outputList)

cdef np.ndarray[np.float32_t, ndim=1] computeIntersection(np.ndarray[np.float32_t, ndim=1] dc, np.float32_t n1, np.ndarray[np.float32_t, ndim=1] e, np.ndarray[np.float32_t, ndim=1] s):
    cdef np.ndarray[np.float32_t, ndim=1] dp = s-e
    cdef np.float32_t n2 = s[0] * e[1] - s[1] * e[0]
    cdef np.float32_t n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
    return np.array([(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3], dtype=np.float32)

cdef bint inside(np.ndarray[np.float32_t, ndim=1] p, np.ndarray[np.float32_t, ndim=1] cp1, np.ndarray[np.float32_t, ndim=1] dc):
    return (-dc[0])*(p[1]-cp1[1]) > (-dc[1])*(p[0]-cp1[0])
</code>```

Mixing the two versions (only numpy arrays and @Peter Taylor's tricks works slightly worse). No idea why ? Possibly because we have to allocate a long list of size sP.shape[0]*cp.shape[0] ?

答:
After messing with your Cython code I figured it was way easier to find your library already implemented somewhere else, so check out the scikit-image version that is just several lines of Numpy code and the algo you're looking for from matplotlib:

```<code>import numpy as np
from matplotlib import path, transforms

def polygon_clip(rp, cp, r0, c0, r1, c1):
"""Clip a polygon to the given bounding box.

Parameters
----------
rp, cp : (N,) ndarray of double
    Row and column coordinates of the polygon.
(r0, c0), (r1, c1) : double
    Top-left and bottom-right coordinates of the bounding box.

Returns
-------
r_clipped, c_clipped : (M,) ndarray of double
    Coordinates of clipped polygon.

Notes
-----
This makes use of Sutherland-Hodgman clipping as implemented in
AGG 2.4 and exposed in Matplotlib.

"""
    poly = path.Path(np.vstack((rp, cp)).T, closed=True)
    clip_rect = transforms.Bbox([[r0, c0], [r1, c1]])
    poly_clipped = poly.clip_to_bbox(clip_rect).to_polygons()[0]

    # This should be fixed in matplotlib >1.5
    if np.all(poly_clipped[-1] == poly_clipped[-2]):
        poly_clipped = poly_clipped[:-1]

    return poly_clipped[:, 0], poly_clipped[:, 1]
</code>```

If nothing else the above should be way simpler to convert to Cython.

[UPDATE]
And from the other Cython answer profiling try this package which is already implementing polygon clipping from C++ into Python called https://pypi.python.org/pypi/pyclipper usage as such:

import pyclipper

subj = (
    ((180, 200), (260, 200), (260, 150), (180, 150)),
    ((215, 160), (230, 190), (200, 190))
)

clip = ((190, 210), (240, 210), (240, 130), (190, 130))

pc = pyclipper.Pyclipper()
pc.AddPath(clip, pyclipper.PT_CLIP, True)
pc.AddPaths(subj, pyclipper.PT_SUBJECT, True)

solution = pc.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)

The above is about the same speed as the fast Cython code answer on my terrible AMD work PC BTW 9us.

Body:
I want to cythonise the python implementation of the Sutherland-Hogman algorithm. This algorithm updates a list of vertices according to pretty simple rules (being inside or outside an edge, etc.) but the details are not important. Here is the python version it accepts lists of vertices of polygons oriented clockwise. For instance those:

sP=[(50, 150),  (200, 50),  (350, 150), (350, 300), (250, 300), (200, 250), (150, 350),(100, 250), (100, 200)]
cP=[(100, 100), (300, 100), (300, 300), (100, 300)]

and calculate their intersection:

inter=clip(sP, cP)

Here is the code found on rosettacode and slightly modified to return an empty list if there is no intersection.

def clip(subjectPolygon, clipPolygon):
   def inside(p):
      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])

   def computeIntersection():
      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]
      dp = [ s[0] - e[0], s[1] - e[1] ]
      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
      n2 = s[0] * e[1] - s[1] * e[0]
      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]

   outputList = subjectPolygon
   cp1 = clipPolygon[-1]

   for clipVertex in clipPolygon:
      cp2 = clipVertex
      inputList = outputList
      outputList = []
      s = inputList[-1]

      for subjectVertex in inputList:
         e = subjectVertex
         if inside(e):
            if not inside(s):
               outputList.append(computeIntersection())
            outputList.append(e)
         elif inside(s):
            outputList.append(computeIntersection())
         s = e
      if len(outputList)<1:
          return []
      cp1 = cp2
   return(outputList)

This function is excruciatingly slow for my applications so I tried to cythonize it using numpy. Here is my cython version. I had to define the two functions outside clip because I had error messages about buffer inputs.

cython1

cimport cython
import numpy as np
cimport numpy as np

def clip(np.ndarray[np.float32_t, ndim=2] subjectPolygon,np.ndarray[np.float32_t, ndim=2] clipPolygon):

    outputList = list(subjectPolygon)
    cdef np.ndarray[np.float32_t, ndim=1] cp1 = clipPolygon[-1,:]
    cdef np.ndarray[np.float32_t, ndim=1] cp2

    for i in xrange(clipPolygon.shape[0]):
       cp2 = clipPolygon[i]
       inputList = outputList
       outputList = []
       s = inputList[-1]

       for subjectVertex in inputList:
          e = subjectVertex
          if inside(e, cp1, cp2):
             if not inside(s, cp1, cp2):
                outputList.append(computeIntersection(cp1, cp2, e, s))
             outputList.append(e)
          elif inside(s, cp1, cp2):
             outputList.append(computeIntersection(cp1, cp2, e, s))
          s = e
       if len(outputList)<1:
         return []
       cp1 = cp2

    return(outputList)

def computeIntersection(np.ndarray[np.float32_t, ndim=1] cp1, np.ndarray[np.float32_t, ndim=1] cp2, np.ndarray[np.float32_t, ndim=1] e, np.ndarray[np.float32_t, ndim=1] s):
    cdef np.ndarray[np.float32_t, ndim=1] dc = cp1-cp2
    cdef np.ndarray[np.float32_t, ndim=1] dp = s-e
    cdef np.float32_t n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
    cdef np.float32_t n2 = s[0] * e[1] - s[1] * e[0]
    cdef np.float32_t n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
    cdef np.ndarray[np.float32_t, ndim=1] res=np.array([(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3], dtype=np.float32)
    return res

def inside(np.ndarray[np.float32_t, ndim=1] p, np.ndarray[np.float32_t, ndim=1] cp1, np.ndarray[np.float32_t, ndim=1] cp2):
    cdef bint b=(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])
    return b

When I time the two versions I gained only a factor of two in speed-up I need at least 10 times that (or 100x !). Is there something to do ?
How does one deal with list with Cython ?

EDIT 1: I followed @DavidW's advice I allocate numpy arrays and trim them instead of using list and I am now using cdef functions, which are supposed to bring 10 times speed up, unfortunately I am seeing no speed-up at all !

cython2

cimport cython
import numpy as np
cimport numpy as np

@cython.boundscheck(False)
@cython.wraparound(False)
def clip(np.ndarray[np.float32_t, ndim=2] subjectPolygon,np.ndarray[np.float32_t, ndim=2] clipPolygon):
    return clip_in_c(subjectPolygon, clipPolygon)

@cython.boundscheck(False)
@cython.wraparound(False)
cdef np.ndarray[np.float32_t, ndim=2] clip_in_c(np.ndarray[np.float32_t, ndim=2] subjectPolygon,np.ndarray[np.float32_t, ndim=2] clipPolygon):

    cdef int cp_size=clipPolygon.shape[0]
    cdef int outputList_effective_size=subjectPolygon.shape[0]
    cdef int inputList_effective_size=outputList_effective_size
    #We allocate a fixed size array of size
    cdef int max_size_inter=outputList_effective_size*cp_size
    cdef int k=-1

    cdef np.ndarray[np.float32_t, ndim=2] outputList=np.empty((max_size_inter,2), dtype=np.float32)
    cdef np.ndarray[np.float32_t, ndim=2] inputList=np.empty((max_size_inter,2), dtype=np.float32)
    cdef np.ndarray[np.float32_t, ndim=1] cp1 = clipPolygon[cp_size-1,:]
    cdef np.ndarray[np.float32_t, ndim=1] cp2=np.empty((2,), dtype=np.float32)

    outputList[:outputList_effective_size]=subjectPolygon
    for i in xrange(cp_size):

        cp2 = clipPolygon[i]
        inputList[:outputList_effective_size] = outputList[:outputList_effective_size]
        inputList_effective_size=outputList_effective_size
        outputList_effective_size=0
        s = inputList[inputList_effective_size-1]

        for j in xrange(inputList_effective_size):
            e = inputList[j]
            if inside(e, cp1, cp2):
                if not inside(s, cp1, cp2):
                    k+=1
                    outputList[k]=computeIntersection(cp1, cp2, e, s)

                k+=1
                outputList[k]=e

            elif inside(s, cp1, cp2):
                k+=1
                outputList[k]=computeIntersection(cp1, cp2, e, s)

            s = e

        if k<0:
            return np.empty((0,0),dtype=np.float32)

        outputList_effective_size=k+1

        cp1 = cp2
        k=-1

    return outputList[:outputList_effective_size]

cdef np.ndarray[np.float32_t, ndim=1] computeIntersection(np.ndarray[np.float32_t, ndim=1] cp1, np.ndarray[np.float32_t, ndim=1] cp2, np.ndarray[np.float32_t, ndim=1] e, np.ndarray[np.float32_t, ndim=1] s):
    cdef np.ndarray[np.float32_t, ndim=1] dc = cp1-cp2
    cdef np.ndarray[np.float32_t, ndim=1] dp = s-e
    cdef np.float32_t n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
    cdef np.float32_t n2 = s[0] * e[1] - s[1] * e[0]
    cdef np.float32_t n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
    return np.array([(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3], dtype=np.float32)

cdef bint inside(np.ndarray[np.float32_t, ndim=1] p, np.ndarray[np.float32_t, ndim=1] cp1, np.ndarray[np.float32_t, ndim=1] cp2):
    return (cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])

Here is the benchmarks:

import numpy as np
from cython1 import clip_cython1
from cython2 import clip_cython2
import time

sp=np.array([[50, 150],[200,50],[350,150],[250,300],[200,250],[150,350],[100,250],[100,200]],dtype=np.float32)
cp=np.array([[100,100],[300,100],[300,300],[100,300]],dtype=np.float32)

t1=time.time()
for i in xrange(120000):
    a=clip_cython1(sp, cp)
t2=time.time()
print (t2-t1)

t1=time.time()
for i in xrange(120000):
    a=clip_cython2(sp, cp)
t2=time.time()
print (t2-t1)

39.45

44.12

The second one is even worse !

EDIT 2 The best answer coming from @Peter Taylor from CodeReview use the fact that each time you compute inside_s it is redundant because s=e and you already calculated inside_e (and to factorize dc and n1 out of the functions but it does not help much).

cimport cython
import numpy as np
cimport numpy as np

def clip(np.ndarray[np.float32_t, ndim=2] subjectPolygon,np.ndarray[np.float32_t, ndim=2] clipPolygon):

    outputList = list(subjectPolygon)
    cdef np.ndarray[np.float32_t, ndim=1] cp1 = clipPolygon[-1,:]
    cdef np.ndarray[np.float32_t, ndim=1] cp2
    cdef bint inside_e, inside_s
    cdef np.float32_t n1
    cdef np.ndarray[np.float32_t, ndim=1] dc
    cdef int i

    for i in range(clipPolygon.shape[0]):

       cp2 = clipPolygon[i]
       #intermediate
       n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
       dc=cp1-cp2
       inputList = outputList
       outputList = []
       s = inputList[-1]

       inside_s=inside(s, cp1, dc)
       for index, subjectVertex in enumerate(inputList):

           e = subjectVertex
           inside_e=inside(e, cp1, dc)
           if inside_e:

               if not inside_s:
                   outputList.append(computeIntersection(dc, n1, e, s))
               outputList.append(e)

           elif inside_s:
               outputList.append(computeIntersection(dc, n1, e, s))

           s = e
           inside_s=inside_e

       if len(outputList)<1:
           return []
       cp1 = cp2

    return(outputList)

cdef np.ndarray[np.float32_t, ndim=1] computeIntersection(np.ndarray[np.float32_t, ndim=1] dc, np.float32_t n1, np.ndarray[np.float32_t, ndim=1] e, np.ndarray[np.float32_t, ndim=1] s):
    cdef np.ndarray[np.float32_t, ndim=1] dp = s-e
    cdef np.float32_t n2 = s[0] * e[1] - s[1] * e[0]
    cdef np.float32_t n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
    return np.array([(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3], dtype=np.float32)

cdef bint inside(np.ndarray[np.float32_t, ndim=1] p, np.ndarray[np.float32_t, ndim=1] cp1, np.ndarray[np.float32_t, ndim=1] dc):
    return (-dc[0])*(p[1]-cp1[1]) > (-dc[1])*(p[0]-cp1[0])

Mixing the two versions (only numpy arrays and @Peter Taylor's tricks works slightly worse). No idea why ? Possibly because we have to allocate a long list of size sP.shape[0]*cp.shape[0] ?

Body:
After messing with your Cython code I figured it was way easier to find your library already implemented somewhere else, so check out the scikit-image version that is just several lines of Numpy code and the algo you're looking for from matplotlib:

import numpy as np
from matplotlib import path, transforms

def polygon_clip(rp, cp, r0, c0, r1, c1):
"""Clip a polygon to the given bounding box.

Parameters
----------
rp, cp : (N,) ndarray of double
    Row and column coordinates of the polygon.
(r0, c0), (r1, c1) : double
    Top-left and bottom-right coordinates of the bounding box.

Returns
-------
r_clipped, c_clipped : (M,) ndarray of double
    Coordinates of clipped polygon.

Notes
-----
This makes use of Sutherland-Hodgman clipping as implemented in
AGG 2.4 and exposed in Matplotlib.

"""
    poly = path.Path(np.vstack((rp, cp)).T, closed=True)
    clip_rect = transforms.Bbox([[r0, c0], [r1, c1]])
    poly_clipped = poly.clip_to_bbox(clip_rect).to_polygons()[0]

    # This should be fixed in matplotlib >1.5
    if np.all(poly_clipped[-1] == poly_clipped[-2]):
        poly_clipped = poly_clipped[:-1]

    return poly_clipped[:, 0], poly_clipped[:, 1]

If nothing else the above should be way simpler to convert to Cython.

[UPDATE]
And from the other Cython answer profiling try this package which is already implementing polygon clipping from C++ into Python called https://pypi.python.org/pypi/pyclipper usage as such:

import pyclipper

subj = (
    ((180, 200), (260, 200), (260, 150), (180, 150)),
    ((215, 160), (230, 190), (200, 190))
)

clip = ((190, 210), (240, 210), (240, 130), (190, 130))

pc = pyclipper.Pyclipper()
pc.AddPath(clip, pyclipper.PT_CLIP, True)
pc.AddPaths(subj, pyclipper.PT_SUBJECT, True)

solution = pc.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)

The above is about the same speed as the fast Cython code answer on my terrible AMD work PC BTW 9us.


问:
c++: array size in new-expression must be constant
I am trying to declare a 2 dimensional array using a constant integer as the bounds, however this error still persists.

```<code>template <class Type>
matrixType<Type>::matrixType(){
    h = maxSize;
    w = maxSize;
    matrix = new Type[maxSize][maxSize];
    defaultFill();
}
</code>```

matrix is declared as:

```<code>Type* matrix;
</code>```

and maxSize is declared as:

```<code>const int maxSize = 4;
</code>```

答:
Briefly new operator has a following syntax: new typename [items_count]. new Type[maxSize][maxSize] expression tries to allocate array of maxSize of Type[maxSize] type and returns a pointer to Type[maxSize]. It is not possible to allocate multidimensional array with new. Using Type[maxSize] is illegal because maxSize is not known at compile time. If you want allocate a multidimensional array you should allocate an array of pointers to Type and then fill it with freshly allocated pointers to arrays of Type.

```<code>Type * * matrix = new Type *[maxSize];
for(size_t row = 0; maxSize != row; ++row)
{
    matrix[row] = new Type[maxSize];
}
</code>```

or as a single array

```<code>Type * matrix = new Type[maxSize * maxSize];
</code>```

Body:
I am trying to declare a 2 dimensional array using a constant integer as the bounds, however this error still persists.

template <class Type>
matrixType<Type>::matrixType(){
    h = maxSize;
    w = maxSize;
    matrix = new Type[maxSize][maxSize];
    defaultFill();
}

matrix is declared as:

Type* matrix;

and maxSize is declared as:

const int maxSize = 4;

Body:
Briefly new operator has a following syntax: new typename [items_count]. new Type[maxSize][maxSize] expression tries to allocate array of maxSize of Type[maxSize] type and returns a pointer to Type[maxSize]. It is not possible to allocate multidimensional array with new. Using Type[maxSize] is illegal because maxSize is not known at compile time. If you want allocate a multidimensional array you should allocate an array of pointers to Type and then fill it with freshly allocated pointers to arrays of Type.

Type * * matrix = new Type *[maxSize];
for(size_t row = 0; maxSize != row; ++row)
{
    matrix[row] = new Type[maxSize];
}

or as a single array

Type * matrix = new Type[maxSize * maxSize];


问:
How can I insert a Print button that prints a table
i have an asp.net mvc project. there is an index page with extension cshtml. and when i generated it shows to me on browser a page contain title, buttons, table and footer.
i want to add a button to print just the table not all the page.
i add in the layout:

<link id="ctl00_Link1" rel="stylesheet" href="themes/css/print.css" type="text/css" media="print">```
</div>
</div>
</p>

<p>and in the end of index page:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="line-btn ">
                <input type="submit" name="ctl00$Index" value="print" onclick="window.print();return false;" id="ctl00_MainContent_Button1" class="btn fl btn-print">

            </div></code>```

 but it still doesn't work and print all the index page!

答:
You can achieve what you want using following code. Add following in your index.cshtml page:

```<code><div class="line-btn">
    <input type="submit" value="print" onclick="PrintOnlyTable()" class="btn fl btn-print">
</div>

<script>
    function PrintOnlyTable() {
        var HTML = $("html");
        var cln = document.documentElement.innerHTML;
        HTML.html($("table"));
        window.print();
        document.documentElement.innerHTML = cln;
        return false;
    }
</script>
</code>```

Body:
i have an asp.net mvc project. there is an index page with extension cshtml. and when i generated it shows to me on browser a page contain title, buttons, table and footer.
i want to add a button to print just the table not all the page.
i add in the layout:

<link id="ctl00_Link1" rel="stylesheet" href="themes/css/print.css" type="text/css" media="print">

and in the end of index page:

                <input type="submit" name="ctl00$Index" value="print" onclick="window.print();return false;" id="ctl00_MainContent_Button1" class="btn fl btn-print">

 but it still doesn't work and print all the index page!

Body:
You can achieve what you want using following code. Add following in your index.cshtml page:

<div class="line-btn">
    <input type="submit" value="print" onclick="PrintOnlyTable()" class="btn fl btn-print">
</div>

<script>
    function PrintOnlyTable() {
        var HTML = $("html");
        var cln = document.documentElement.innerHTML;
        HTML.html($("table"));
        window.print();
        document.documentElement.innerHTML = cln;
        return false;
    }
</script>


问:
High fill rate, low impressions - a bug in adMob?
I have finally put some rewarded video ads in my trivia game.
Currently, I have around 1,000 active users a week with very low impressions.
I noticed my problem while testing my app again: it will deliver an ad very rarely to the users, I mean, once the user had seen an ad, it would take A LOT of time until he could see another one (when in most cases it will not show ad at all),
Even if he would close and open the app again.

VERY IMPORTANT:
1. I have a very high fill rate (96%) which might suggest that the problem is that the adMob SDK is not sending the requests all the time.
2. I have tested my adMod ad unit in the adMob rewarded video example app and it worked fine! The app showed me videos one after another with no delay!
3. I have Facebook sdk integrated in my app in the same activity where the rewarded videos show for a 'Share' button.

All these facts made me think that it might be my code that is causing all of this, but in the other hand, if my code was bad - why would the app show me videos at all?
In addition, my adMob code is taken from their website - stayed untouched except the app id and ad unit id.

Thanks, hope the problem is clear.

答:
High fill rate with low impression means that you request the ad and you receive it successfully, but the ad doesn't appear to the users.
it may be occur if the ads take long time to appear, so it appears after the user scrolls to another place or opens another screen.
it may also appear if the users countries have low internet connection strength.  </p>


问:
prevent a post back by assigning key function to enter key javascript
in the following code, I am using a jQuery call to prevent post back on an aspx page, that is calling Google maps for customer directions. When I use the enter key, instead of the "Directions" button. The page refreshes. I have included a bit of jQuery that should tie the keypress function to the button itself, but it is still causing post back.

My question is, can I prevent post back in this code by binding the keypress function to that button?

Edit 1: I still need to be able to allow the user to press the enter key to execute their search for directions.

jQuery:

```<code><script>
        var directionDisplay;
        var directionsService = new google.maps.DirectionsService();

        function initialize() {
            directionsDisplay = new google.maps.DirectionsRenderer();
            var mapOptions = {
                zoom: 10,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: new google.maps.LatLng(31.320574, -85.70925),
            };
            var map = new google.maps.Map(document.getElementById('map-canvas'),
                mapOptions);
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById('directions-panel'));

            var control = document.getElementById('control');
            control.style.display = 'block';
            map.controls[google.maps.ControlPosition.TOP].push(control);

            var image = '../images/flag.png';
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(31.239661, -85.499698),
                map: map,
                icon: image
            });
        }

        function calcRoute() {
            var start = document.getElementById('txtAddress1').value;
            var end = "business location";
            var request = {
                origin: start,
                destination: end,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                }
            });

            document.getElementById('map-canvas').style.display = 'inline-block';
        }
 $(document).ready(function () {
            $("form input").keypress(function (e) {
                if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                    $('input[type=button] .NavButton').click();
                    return true;
                }
            });
        });
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</code>```

Relevant HTML:

```<code><div id="control">
            <input type="text" id="txtAddress1" onchange="calcRoute()" value="" style="width: 300px; margin-top:40px; left:10px !important" />
            <input class="NavButton" type="button" value="Get Directions" onclick="calcRoute()" />
        </div>
</code>```

答:
return false not true ... or use e.preventDefault()

The default action of enter when there is a submit button in a form is to submit the form

When you return true the default action will continue but won't when you return false or use e.preventDefault()

Body:
in the following code, I am using a jQuery call to prevent post back on an aspx page, that is calling Google maps for customer directions. When I use the enter key, instead of the "Directions" button. The page refreshes. I have included a bit of jQuery that should tie the keypress function to the button itself, but it is still causing post back.

My question is, can I prevent post back in this code by binding the keypress function to that button?

Edit 1: I still need to be able to allow the user to press the enter key to execute their search for directions.

jQuery:

Relevant HTML:

            <input type="text" id="txtAddress1" onchange="calcRoute()" value="" style="width: 300px; margin-top:40px; left:10px !important" />
            <input class="NavButton" type="button" value="Get Directions" onclick="calcRoute()" />


问:
How to export data into excel from current search in Laravel?
I've problem with my project, I need to export my table from search data in Laravel, how I can do it sir?
There's my Controller and index.blade.php

Controller.php

```<code>public function downloadExcel(Request $request, $type)
{
    $data = TABLENAME::get()->toArray();
    return Excel::create('FILENAME', function($excel) use ($data) {
        $excel->sheet('mySheet', function($sheet) use ($data)
        {
            $sheet->fromArray($data);
        });
    })->download($type);
}

public function search(Request $request)
{
$query = Model_items::query();
            if(Input::has('name')) {
                $query->where('name', $getName);
            }
            if(Input::has('phone')) {
                $query->where('phone', $getPhone);
            }
            $dataList = $query->paginate(10);
return view('index', compact('dataList'));
}
</code>```

Index.blade.php

```<code>                <div class="col-md-4">
                            {!! Form::open(['method'=>'GET','url'=>'findData','role'=>'search'])  !!}
                            <div style="left: 120%" class="input-group custom-search-form">

                                <input id="cTah" name="cTah" type="checkbox" style="margin-bottom: 10px"/> Name
                                <input type="text" class="iTah" name="name" disabled="" style="float: right;"><br>

                                <input id="cKab" name="cKab" type="checkbox" style="margin-bottom: 10px"/> Phone
                                <input type="text" class="iKab" name="phone" disabled=""  style="float: right;"><br>

                                <br>
                                <span class="input-group-btn">
                                    <span class="input-group-btn">
                                        <button class="btn btn-default" type="submit" style="margin-left: 20px">
                                            <i class="fa fa-search"></i> Search
                                        </button>
                                     </span>
                                 </span>
                             </div>
                             {!! Form::close() !!}
                        </div>
                    </div>
                    <br/>
                    <table class="table table-bordered table-hover table-condensed tfix">
                        <thead align="center">
                        <tr>
                            <td><b>NAME</b></td>
                            <td><b>PHONE</b></td>
                            <td width="85px"></td>
                        </tr>
                        </thead>
                    @foreach($dataList as $key => $view)
                        <tr align="center">
                            <td>{{ $view->name }}</td>
                            <td>{{ $view->phone }}</td>
                        </tr>
                    @endforeach
                    </table>
                    {{ $dataList->appends(Request::except('page'))->links() }}
            <br/>
            <h3>Export File From Database:</h3>
            <div style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;">
                <a href="{{ route('pdfview',['download'=>'pdf']) }}"><button class="btn btn-danger btn-lg">Export PDF</button></a>
                <a href="{{ url('downloadExcel/xlsx') }}"><button class="btn btn-success btn-lg">Export Excel</button></a>
            </div>
            <br/>
</code>```

I use Maat to convert data into Excel, but this is export all data in TABLENAME, how to make this code can export my current data from search?

答:
Simple write your controller code look like</p>

```<code>if(Input::has('download')) {
    $query = Model_items::query();
    if(Input::has('name')) {
        $query->where('name', $getName);
    }
    if(Input::has('phone')) {
        $query->where('phone', $getPhone);
    }
    $dataList = $query->get();

    return Excel::create('FILENAME', function($excel) use ($dataList) {
        $excel->sheet('mySheet', function($sheet) use ($dataList)
        {
            $sheet->fromArray($dataList);
        });
    })->download($type);

} else {
    $query = Model_items::query();
    if(Input::has('name')) {
        $query->where('name', $getName);
    }
    if(Input::has('phone')) {
        $query->where('phone', $getPhone);
    }
    $dataList = $query->paginate(10);
}

return view('index', compact('dataList'));
</code>```

Body:
I've problem with my project, I need to export my table from search data in Laravel, how I can do it sir?
There's my Controller and index.blade.php

Controller.php

public function downloadExcel(Request $request, $type)
{
    $data = TABLENAME::get()->toArray();
    return Excel::create('FILENAME', function($excel) use ($data) {
        $excel->sheet('mySheet', function($sheet) use ($data)
        {
            $sheet->fromArray($data);
        });
    })->download($type);
}

public function search(Request $request)
{
$query = Model_items::query();
            if(Input::has('name')) {
                $query->where('name', $getName);
            }
            if(Input::has('phone')) {
                $query->where('phone', $getPhone);
            }
            $dataList = $query->paginate(10);
return view('index', compact('dataList'));
}

Index.blade.php

                            {!! Form::open(['method'=>'GET','url'=>'findData','role'=>'search'])  !!}

                                <input id="cTah" name="cTah" type="checkbox" style="margin-bottom: 10px"/> Name
                                <input type="text" class="iTah" name="name" disabled="" style="float: right;">

                                <input id="cKab" name="cKab" type="checkbox" style="margin-bottom: 10px"/> Phone
                                <input type="text" class="iKab" name="phone" disabled=""  style="float: right;">

                                        <button class="btn btn-default" type="submit" style="margin-left: 20px">
                                             Search
                                        </button>

                             {!! Form::close() !!}

                            NAME
                            PHONE

                    @foreach($dataList as $key => $view)

                            {{ $view->name }}
                            {{ $view->phone }}

                    @endforeach

                    {{ $dataList->appends(Request::except('page'))->links() }}

Export File From Database:

                'pdf']) }}"><button class="btn btn-danger btn-lg">Export PDF</button>
                <button class="btn btn-success btn-lg">Export Excel</button>

I use Maat to convert data into Excel, but this is export all data in TABLENAME, how to make this code can export my current data from search?

Body:
Simple write your controller code look like

if(Input::has('download')) {
    $query = Model_items::query();
    if(Input::has('name')) {
        $query->where('name', $getName);
    }
    if(Input::has('phone')) {
        $query->where('phone', $getPhone);
    }
    $dataList = $query->get();

    return Excel::create('FILENAME', function($excel) use ($dataList) {
        $excel->sheet('mySheet', function($sheet) use ($dataList)
        {
            $sheet->fromArray($dataList);
        });
    })->download($type);

} else {
    $query = Model_items::query();
    if(Input::has('name')) {
        $query->where('name', $getName);
    }
    if(Input::has('phone')) {
        $query->where('phone', $getPhone);
    }
    $dataList = $query->paginate(10);
}

return view('index', compact('dataList'));


问:
Can't apply css class to dynamic menu
The whole project can be found here Github.

I added a dynamic menu on my navigation bar placed in the header. For some reason I can't figure out how to link the dynamic menu with either a class or an ID defined in my style.css file.

For some reason, neither the 'menu_class' or the 'menu_id' seem to work.

Here the menu in the header.php file:

```<code><!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <!--Container of my link that are on the far right, they collapse with a small screen-->
    <ul class="nav navbar-nav navbar-right">
        <!--This code inject the dynamic menu inside thge av bar-->
        <!-- The Dynamic menu is managed in the admin section of word press-->
        <?php
            wp_nav_menu(
                array(
                    /*must have this link to function.php
                     *In function.php we defined this menu 'alphamenu'*/
                    'theme_location' => 'top-right-menu',
                    /*this line of code removes the default menu appearence*/
                    'container'      => false,
                    /*this line makes the menu with the same layout specified above
                     *(same as link 1 and 2)*/
                    'items_wrap'     => '%3$s',
                    /*CSS class applied to the menu*/
                    'menu_class'     => 'nav navbar-nav custom-head-foot',
                    'menu_id'        => 'custom-dynamic-menu'
                )
            );
        ?>
    </ul> <!--dynamic menu unordered list-->
</div> <!--dynamic menu div-->
</code>```

The function.php file:

```<code>/*Function to register a custom menu for the admin section
 *This resurces was taken from the wordpress codex*/
function custom_theme_setup() {

    /*Registered a custom primary navigation menu*/
    register_nav_menus (
        array( 'alphamenu', __( 'Primary Menu 123') )
    );

    /*Add theme support for title tag*/
    add_theme_support( 'title-tag' );
}
/*Hooking in the function "custom_theme_setup()" after the theme is setup
 *surce: wordpress plugin api hooks*/
add_action( 'after_setup_theme', 'custom_theme_setup');
</code>```

答: If the render method is screwed up you can always use .nav > div with or without pseudo-class like :nth-of-type(1) or there's second way: .nav:nth-child(1) as query for first child inside div.nav?

Title: Can't apply css class to dynamic menu

Body:
The whole project can be found here Github.

I added a dynamic menu on my navigation bar placed in the header. For some reason I can't figure out how to link the dynamic menu with either a class or an ID defined in my style.css file.

For some reason, neither the 'menu_class' or the 'menu_id' seem to work.

Here the menu in the header.php file:

        <?php
            wp_nav_menu(
                array(
                    /*must have this link to function.php
                     *In function.php we defined this menu 'alphamenu'*/
                    'theme_location' => 'top-right-menu',
                    /*this line of code removes the default menu appearence*/
                    'container'      => false,
                    /*this line makes the menu with the same layout specified above
                     *(same as link 1 and 2)*/
                    'items_wrap'     => '%3$s',
                    /*CSS class applied to the menu*/
                    'menu_class'     => 'nav navbar-nav custom-head-foot',
                    'menu_id'        => 'custom-dynamic-menu'
                )
            );
        ?>

The function.php file:

/*Function to register a custom menu for the admin section
 *This resurces was taken from the wordpress codex*/
function custom_theme_setup() {

    /*Registered a custom primary navigation menu*/
    register_nav_menus (
        array( 'alphamenu', __( 'Primary Menu 123') )
    );

    /*Add theme support for title tag*/
    add_theme_support( 'title-tag' );
}
/*Hooking in the function "custom_theme_setup()" after the theme is setup
 *surce: wordpress plugin api hooks*/
add_action( 'after_setup_theme', 'custom_theme_setup');


问:
Math optimization in C#
I've been profiling an application all day long and, having optimized a couple bits of code, I'm left with this on my todo list. It's the activation function for a neural network, which gets called over a 100 million times. According to dotTrace, it amounts to about 60% of the overall function time.

How would you optimize this?

```<code>public static float Sigmoid(double value) {
    return (float) (1.0 / (1.0 + Math.Pow(Math.E, -value)));
}
</code>```

答:
I've seen that a lot of people around here are trying to use approximation to make Sigmoid faster. However, it is important to know that Sigmoid can also be expressed using tanh, not only exp.
Calculating Sigmoid this way is around 5 times faster than with exponential, and by using this method you are not approximating anything, thus the original behaviour of Sigmoid is kept as-is.

```<code>    public static double Sigmoid(double value)
    {
        return 0.5d + 0.5d * Math.Tanh(value/2);
    }
</code>```

Of course, parellization would be the next step to performance improvement, but as far as the raw calculation is concerned, using Math.Tanh is faster than Math.Exp.

OwnerDisplayName: hb

Title: Math optimization in C#

Body:
I've been profiling an application all day long and, having optimized a couple bits of code, I'm left with this on my todo list. It's the activation function for a neural network, which gets called over a 100 million times. According to dotTrace, it amounts to about 60% of the overall function time.

How would you optimize this?

public static float Sigmoid(double value) {
    return (float) (1.0 / (1.0 + Math.Pow(Math.E, -value)));
}

LastEditorDisplayName: Jeff Atwood

Body:
I've seen that a lot of people around here are trying to use approximation to make Sigmoid faster. However, it is important to know that Sigmoid can also be expressed using tanh, not only exp.
Calculating Sigmoid this way is around 5 times faster than with exponential, and by using this method you are not approximating anything, thus the original behaviour of Sigmoid is kept as-is.

    public static double Sigmoid(double value)
    {
        return 0.5d + 0.5d * Math.Tanh(value/2);
    }

Of course, parellization would be the next step to performance improvement, but as far as the raw calculation is concerned, using Math.Tanh is faster than Math.Exp.


问:
How to center a hitbox inside rotating triangle sprite?
I'm having problems plotting hitboxes in the center of rotating triangle sprites. When I spawn the triangles, I set the collision rectangle like this:

```<code>bullet.collisionRect.width = flashingTriangleSprite.getWidth() - 20;
bullet.collisionRect.height = flashingTriangleSprite.getHeight() - 14;
bullet.scale = 0.287f;
</code>```

Updating is done as follows:

```<code>bullet.position.y += bullet.velocity.y;

// center collision rect over triangle sprite
bullet.collisionRect.x =
  bullet.position.x + ((flashingTriangleSprite.getWidth() / 2) - bullet.collisionRect.getWidth() / 2);
bullet.collisionRect.y =
  bullet.position.y + ((flashingTriangleSprite.getHeight() / 2) - bullet.collisionRect.getHeight() / 2);

if (bullet.scale < 1)
{
  bullet.scale += 0.011f;
}

if (bullet.driftDirection == Globals.Direction.LEFT)
{
  bullet.rotation -= 3.804f;
  bullet.position.x -= bullet.velocity.x;
}
else // drift right
{
  bullet.rotation += 3.804f;
  bullet.position.x += bullet.velocity.x;
}
</code>```

This is the result: http://imgur.com/rIvIT8K

As you can see, the hitboxes are not centered. In fact, the hitboxes seem to change position within the triangle sprites depending on the rotation of the triangle sprite. Any ideas what I'm doing wrong?

答:
When determining your hitbox centre position you are targeting the centre of the triangle sprite (a square), but that is not the perfect centre of the drawn triangle.

Therefore your hitbox is always closer to one of the vertices of the triangle (depending on the rotation). Also, your hitboxes are never rotated with the triangle, instead they always appear to be standing vertically.

To place the hitbox in the middle of the triangle you should aim for 1/3 of the height of the sprite (if the triangle has one side flat at the bottom in the base sprite image) and when you are updating the sprite, attempt to update the hitbox rotation to match the sprite rotation.

You could also try making a more accurate triangle hitbox using the PolygonShape, but that's up to you.

Body:
I'm having problems plotting hitboxes in the center of rotating triangle sprites. When I spawn the triangles, I set the collision rectangle like this:

bullet.collisionRect.width = flashingTriangleSprite.getWidth() - 20;
bullet.collisionRect.height = flashingTriangleSprite.getHeight() - 14;
bullet.scale = 0.287f;

Updating is done as follows:

bullet.position.y += bullet.velocity.y;

// center collision rect over triangle sprite
bullet.collisionRect.x =
  bullet.position.x + ((flashingTriangleSprite.getWidth() / 2) - bullet.collisionRect.getWidth() / 2);
bullet.collisionRect.y =
  bullet.position.y + ((flashingTriangleSprite.getHeight() / 2) - bullet.collisionRect.getHeight() / 2);

if (bullet.scale < 1)
{
  bullet.scale += 0.011f;
}

if (bullet.driftDirection == Globals.Direction.LEFT)
{
  bullet.rotation -= 3.804f;
  bullet.position.x -= bullet.velocity.x;
}
else // drift right
{
  bullet.rotation += 3.804f;
  bullet.position.x += bullet.velocity.x;
}

This is the result: http://imgur.com/rIvIT8K

As you can see, the hitboxes are not centered. In fact, the hitboxes seem to change position within the triangle sprites depending on the rotation of the triangle sprite. Any ideas what I'm doing wrong?


问:
Refresh the method after item add or delete from SQL database
As in the title, I am developing an application using C# and WPF which acts as a client on many computers and handling a data using SQL within a company. I want it to refresh the views of the items on all computers using this application when one person adds or deletes something from the server's db. I know I might need to use SQL triggers, but I am kind of confused where to start.

just this type of idea:

```<code>private void Timer_Tick(object sender, EventArgs e)
    {
        if (trigger1.triggered == true)
          {
            RefreshView();
            trigger1.triggered == false;
          }
    }
</code>```

答:
SQL Triggers occur when something happens in the database, and allow you to do things like delete related rows in tables without a foreign key to maintain data integrity.  I don't think that they will be of any benefit here because they are intended to do things within the database rather than externally.

The problem with your request and your proposed way of doing it is that it could cause a lot of network traffic.  If you don't have a problem with that, one way would be to use a timestamp.  When the record changes, save the new timestamp in the database.

Now, in your timer on each machine, check to see if the timestamp has changed since the last time you checked. If it has, reload the data.  If not, continue running.

There will be lots of things to think about with this proposition, though.  For example, what if the data on your screen has changed but not been saved when someone else changes it?  Do you lose your changes? Do you list  the changes and ask what to do?  Are you actually entitled to make those changes or does it require administrator approval?

It would be more normal when using Optimistic Locking (last record written is the correct one) to check for a clash at save time rather than polling for the changes.  That way network traffic is reduced but you are told if the record has changed since you loaded it and given the available options on how to proceed.

In the case of lists of records, the simple way to avoid huge network traffic is a simple Refresh button to reload the list.

This article may give you some ideas on ensuring data integrity in multi-user environments: https://www.codeproject.com/Articles/1178358/What-You-See-Is-What-You-Update

I hope that this gives you some food for thought.

Body:
As in the title, I am developing an application using C# and WPF which acts as a client on many computers and handling a data using SQL within a company. I want it to refresh the views of the items on all computers using this application when one person adds or deletes something from the server's db. I know I might need to use SQL triggers, but I am kind of confused where to start.

just this type of idea:

private void Timer_Tick(object sender, EventArgs e)
    {
        if (trigger1.triggered == true)
          {
            RefreshView();
            trigger1.triggered == false;
          }
    }


问:
Concatenate text in VBA Excel with certain paramaters
What method would be best if I had the following.

3 checkboxes that if selected will populate 3 cells A1, A2 & A3. I need code that will check the 3 cells for data and create a singular string of info.  I can use this with formula but need VBA to do the following to the cells as per below.

So my end result will be "cell1" (if only 1 checkbox is selected) or "cell1 & cell2" (if 2 checkboxes are selected) but if all 3 are selected I want the string to read "cell1, cell2 & cell3". There will only ever be 3 cells in this section.

I want the Concatenate Text to then go into a single cell. AA13 where it can be copied at a later stage.

I have another scenario where I have 6 checkboxes and I need the same thing as above, the 6 checkboxes populate 6 cells B1:B6. but, I need some code that makes sure a minimum of 2 check box's are selected. I can't work out how to get VBA to check for the number of tick boxes and report an error if it doesn't meet the criteria of 2 minimum.

I will have an active x button to run the code as per above to concatenate but when a check box is selected the cell will auto populate with the string i need.

Help would be much appreciated. I'm struggling to find code online to help me for these two scenarios

答:
Consider:</p>

```<code>Sub konkat()
    Dim N As Long
    With Application.WorksheetFunction
        N = .CountA(Range("A1:A3"))
        Select Case N
            Case 0
                Exit Sub
            Case 1
                Range("AA13").Value = Range("A1") & Range("A2") & Range("A3")
            Case 2
                Range("AA13").Value = .TextJoin(" & ", True, Range("A1:A3"))
            Case 3
                Range("AA13").Value = Range("A1").Value & " , " & Range("A2").Value & " & " & Range("A3").Value
        End Select
    End With
End Sub
</code>```

Body:
Consider:

Sub konkat()
    Dim N As Long
    With Application.WorksheetFunction
        N = .CountA(Range("A1:A3"))
        Select Case N
            Case 0
                Exit Sub
            Case 1
                Range("AA13").Value = Range("A1") & Range("A2") & Range("A3")
            Case 2
                Range("AA13").Value = .TextJoin(" & ", True, Range("A1:A3"))
            Case 3
                Range("AA13").Value = Range("A1").Value & " , " & Range("A2").Value & " & " & Range("A3").Value
        End Select
    End With
End Sub


问:
odoo issue tracking doesn't show up after installation / Version 10
I've installed the module Issue Tracking on my Odoo 10.0-20170705 (Community Edition).
There isn't any change at the menus or settings. I can't find the module. The App-overview says, it is installed.</p>

答: I did found the cause. I wasn't logged in as an administrator</p>