问:
How can I get millisecond resolution (or better) time in HTML5?
I'm making HTML5 canvas application. For animation, I need high resolution clock time. How can I get this? It should be millisecond level resolution at minimum.</p>

答:
AFAIK, this isn't part of HTML5 but JavaScript. And you can't do this reliably since it depends on the browser implementation. For example, in IE (8 and 6), the smallest resolution you can have is 15 milliseconds.

Update

Apologies - I just noticed you asked how to actually get the time, use Date.getTime(). This will give you the time in milliseconds since 1st Jan, 1970 but my caveat from above still stands - you'll get a value in milliseconds but you cannot be sure of the accuracy and so you shouldn't depend on this for anything time critical.

References:

http://www.quackit.com/javascript/javascript_date_and_time_functions.cfm

http://www.w3schools.com/jsref/jsref_obj_date.asp

Is there any way to get current time in nanoseconds using JavaScript?


来源: stackexchange

问:
Update ellipse position interactive matplotlib figure jupyter notebook
I managed to generate an interactive matplotlib figure that changes the position of an ellipse using some ipywidget slider.

However the plot is displayed in a new window, I could not find a working solution with the plot in the notebook.

I could generate other interactive figures within a jupyter notebook, like line plots, but with the ellipse, no way..

```<code>%matplotlib
from matplotlib import patches
import matplotlib.pyplot as plt
from ipywidgets import interact

fig = plt.figure()
ax = fig.add_subplot(111)

ellipse = patches.Ellipse((0,0), width=50, height=25, angle=15)
ax.add_patch(ellipse)

ax.set_xlim(-100, 100)
ax.set_ylim(-100, 100)

@interact
def update(xcenter=(-50,50), ycenter=(-50,50)):
    ellipse.set_center((xcenter, ycenter))
    #fig.canvas.draw()
    plt.plot()
</code>```

答: Using % matplotlib notebook fixed the issue in most cases.

ContentLicense: CC BY-SA 4.0

Body:
I managed to generate an interactive matplotlib figure that changes the position of an ellipse using some ipywidget slider.

However the plot is displayed in a new window, I could not find a working solution with the plot in the notebook.

I could generate other interactive figures within a jupyter notebook, like line plots, but with the ellipse, no way..

%matplotlib
from matplotlib import patches
import matplotlib.pyplot as plt
from ipywidgets import interact

fig = plt.figure()
ax = fig.add_subplot(111)

ellipse = patches.Ellipse((0,0), width=50, height=25, angle=15)
ax.add_patch(ellipse)

ax.set_xlim(-100, 100)
ax.set_ylim(-100, 100)

@interact
def update(xcenter=(-50,50), ycenter=(-50,50)):
    ellipse.set_center((xcenter, ycenter))
    #fig.canvas.draw()
    plt.plot()


问:
My code returns a JSONDecodeError but the only thing in the file is {}
Please read to the bottom before answering.

My code loads the JSON from a file called reference.json. Then it adds different object to file, then dumps it back to the file. But when it does that return this error:

```<code>Ignoring exception in command import:
Traceback (most recent call last):
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 120, in attach_command
    self.dump_json(json_content, new_file, new_channel, message=message)
  File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 61, in dump_json
    reference_content = json.load(reference_file)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

JSON file:

```<code>{}
</code>```

Coding Snippet:

```<code>    def dump_json(self, json_content, new_file, channel, message=None):
        if new_file:
            reference_file = open("json/reference.json", "w+")

            reference_content = json.load(reference_file)

            reference_content[str(channel.name)] = {}
            reference_content[str(channel.name)]["guild_id"] = int(channel.guild.id)
            reference_content[str(channel.name)]["channel_id"] = int(channel.id)
            reference_content[str(channel.name)]["message_id"] = int(message.id)

            json.dump(reference_content, reference_file, indent=4)

        file = open(f"json/{channel.name}.json", "w")

        json.dump(json_content, file, indent=4)
</code>```

Full Code:

```<code>from discord.ext import commands
from os import path
import utils
import discord
import json

class ImportTestSuite(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    async def get_json_content(self, ctx):
        attachments = ctx.message.attachments

        if len(attachments) == 0:
            embed = discord.Embed(description="You need to provide 1 JSON attachment",
                                  timestamp=ctx.message.created_at,
                                  colour=discord.colour.Colour.red())

            embed = utils.add_promotion_footer(embed)

            await ctx.send(embed=embed)

            return None

        attachment = attachments[0]

        if attachment.filename.split(".")[1] != "json":
            embed = discord.Embed(description="You must attach a `.json` file",
                                  timestamp=ctx.message.created_at,
                                  colour=discord.colour.Colour.red())

            embed = utils.add_promotion_footer(embed)

            await ctx.send(embed=embed)

            return None

        attachment_content = await attachment.read()

        try:
            json_content = json.loads(attachment_content)
        except json.JSONDecodeError:
            embed = discord.Embed(description="You must attach valid JSON.\nUse "
                                              "https://jsonformatter.curiousconcept.com/ or an alternative to"
                                              " validate JSON",
                                  timestamp=ctx.message.created_at,
                                  colour=discord.colour.Colour.red())

            embed = utils.add_promotion_footer(embed)

            await ctx.send(embed=embed)

            return None

        return json_content

    def dump_json(self, json_content, new_file, channel, message=None):
        if new_file:
            print(message)
            print(channel.id)
            reference_file = open("json/reference.json", "w+")

            reference_content = json.load(reference_file)

            reference_content[str(channel.name)] = {}
            reference_content[str(channel.name)]["guild_id"] = int(channel.guild.id)
            reference_content[str(channel.name)]["channel_id"] = int(channel.id)
            reference_content[str(channel.name)]["message_id"] = int(message.id)

            json.dump(reference_content, reference_file, indent=4)

        file = open(f"json/{channel.name}.json", "w")

        json.dump(json_content, file, indent=4)

    async def setup_new_channel(self, ctx, channel):
        new_channel = await channel.category.create_text_channel(channel.name,
                                                                 overwrites=channel.overwrites,
                                                                 position=channel.position,
                                                                 topic=channel.topic,
                                                                 nsfw=channel.is_nsfw())

        await channel.delete()

        embed = discord.Embed(description="React with ✅ to start the test",
                              timestamp=ctx.message.created_at,
                              colour=discord.colour.Colour.green())

        embed = utils.add_promotion_footer(embed)

        message = await new_channel.send(embed=embed)

        await message.add_reaction("✅")

        return message, new_channel

    def check_if_new_file(self, channel):
        new_file = False

        if not path.exists(f"json/{channel.name}.json"):
            new_file = True

        return new_file

    @commands.command(name="import")
    async def attach_command(self, ctx, channel: discord.TextChannel = None):
        if channel is None:
            channel = ctx.message.channel

        json_content = await self.get_json_content(ctx)

        if json_content is None:
            return

        new_file = self.check_if_new_file(channel)

        if new_file:
            message, new_channel = await self.setup_new_channel(ctx, channel)

            self.dump_json(json_content, new_file, new_channel, message=message)
        else:
            await ctx.message.delete()

            self.dump_json(json_content, new_file, channel)

def setup(bot):
    bot.add_cog(ImportTestSuite(bot))
</code>```

I have tried different modes and checked if the data is correct, all that is good.

Thanks in advance

答:
The cause is given in this other SO post: Confused by python file mode "w+".
but not closing as duplicate because is may not be evident at first sight.

The error stack trace gives the line in your code that raises the error:

```<code>File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 61, in dump_json
reference_content = json.load(reference_file)
</code>```

Just before, we can find:

```<code>reference_file = open("json/reference.json", "w+")
</code>```

As explained in the referenced post, w+ mode truncates the file to 0 length, and json does not read your initialized data but an empty file and finds nothing since char 0, hence the error message.

Body:
Please read to the bottom before answering.

My code loads the JSON from a file called reference.json. Then it adds different object to file, then dumps it back to the file. But when it does that return this error:

Ignoring exception in command import:
Traceback (most recent call last):
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 120, in attach_command
    self.dump_json(json_content, new_file, new_channel, message=message)
  File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 61, in dump_json
    reference_content = json.load(reference_file)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)

JSON file:

{}

Coding Snippet:

    def dump_json(self, json_content, new_file, channel, message=None):
        if new_file:
            reference_file = open("json/reference.json", "w+")

            reference_content = json.load(reference_file)

            reference_content[str(channel.name)] = {}
            reference_content[str(channel.name)]["guild_id"] = int(channel.guild.id)
            reference_content[str(channel.name)]["channel_id"] = int(channel.id)
            reference_content[str(channel.name)]["message_id"] = int(message.id)

            json.dump(reference_content, reference_file, indent=4)

        file = open(f"json/{channel.name}.json", "w")

        json.dump(json_content, file, indent=4)

Full Code:

from discord.ext import commands
from os import path
import utils
import discord
import json

class ImportTestSuite(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    async def get_json_content(self, ctx):
        attachments = ctx.message.attachments

        if len(attachments) == 0:
            embed = discord.Embed(description="You need to provide 1 JSON attachment",
                                  timestamp=ctx.message.created_at,
                                  colour=discord.colour.Colour.red())

            embed = utils.add_promotion_footer(embed)

            await ctx.send(embed=embed)

            return None

        attachment = attachments[0]

        if attachment.filename.split(".")[1] != "json":
            embed = discord.Embed(description="You must attach a `.json` file",
                                  timestamp=ctx.message.created_at,
                                  colour=discord.colour.Colour.red())

            embed = utils.add_promotion_footer(embed)

            await ctx.send(embed=embed)

            return None

        attachment_content = await attachment.read()

        try:
            json_content = json.loads(attachment_content)
        except json.JSONDecodeError:
            embed = discord.Embed(description="You must attach valid JSON.\nUse "
                                              "https://jsonformatter.curiousconcept.com/ or an alternative to"
                                              " validate JSON",
                                  timestamp=ctx.message.created_at,
                                  colour=discord.colour.Colour.red())

            embed = utils.add_promotion_footer(embed)

            await ctx.send(embed=embed)

            return None

        return json_content

    def dump_json(self, json_content, new_file, channel, message=None):
        if new_file:
            print(message)
            print(channel.id)
            reference_file = open("json/reference.json", "w+")

            reference_content = json.load(reference_file)

            reference_content[str(channel.name)] = {}
            reference_content[str(channel.name)]["guild_id"] = int(channel.guild.id)
            reference_content[str(channel.name)]["channel_id"] = int(channel.id)
            reference_content[str(channel.name)]["message_id"] = int(message.id)

            json.dump(reference_content, reference_file, indent=4)

        file = open(f"json/{channel.name}.json", "w")

        json.dump(json_content, file, indent=4)

    async def setup_new_channel(self, ctx, channel):
        new_channel = await channel.category.create_text_channel(channel.name,
                                                                 overwrites=channel.overwrites,
                                                                 position=channel.position,
                                                                 topic=channel.topic,
                                                                 nsfw=channel.is_nsfw())

        await channel.delete()

        embed = discord.Embed(description="React with ✅ to start the test",
                              timestamp=ctx.message.created_at,
                              colour=discord.colour.Colour.green())

        embed = utils.add_promotion_footer(embed)

        message = await new_channel.send(embed=embed)

        await message.add_reaction("✅")

        return message, new_channel

    def check_if_new_file(self, channel):
        new_file = False

        if not path.exists(f"json/{channel.name}.json"):
            new_file = True

        return new_file

    @commands.command(name="import")
    async def attach_command(self, ctx, channel: discord.TextChannel = None):
        if channel is None:
            channel = ctx.message.channel

        json_content = await self.get_json_content(ctx)

        if json_content is None:
            return

        new_file = self.check_if_new_file(channel)

        if new_file:
            message, new_channel = await self.setup_new_channel(ctx, channel)

            self.dump_json(json_content, new_file, new_channel, message=message)
        else:
            await ctx.message.delete()

            self.dump_json(json_content, new_file, channel)

def setup(bot):
    bot.add_cog(ImportTestSuite(bot))

I have tried different modes and checked if the data is correct, all that is good.

Thanks in advance

Body:
The cause is given in this other SO post: Confused by python file mode "w+".
but not closing as duplicate because is may not be evident at first sight.

The error stack trace gives the line in your code that raises the error:

File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 61, in dump_json
reference_content = json.load(reference_file)

Just before, we can find:

reference_file = open("json/reference.json", "w+")

As explained in the referenced post, w+ mode truncates the file to 0 length, and json does not read your initialized data but an empty file and finds nothing since char 0, hence the error message.


问:
How to specify signature expressly in Alloy?
I'm learning Alloy modeling language, and I saw this code.

```<code>sig Person {
  partner: Person
}

fact partnerProperties {
  partner = ~partner
  no p: Person | p in p.partner
}
</code>```

This code express "Person's partner relation is mutual".

I can understand above code, but I think how to express partner is relation that wrote in Person expressly.
Because of readability.

I want to write like this.

```<code>fact partnerProperties {
  Person.partner = ~Person.partner
  no p: Person | p in p.partner
}
</code>```

I'm grad to help me.

答:
You could write a quantification as follows :

```<code>sig Person {
  partner: Person
}

fact partnerProperties {
  all p1,p2:Person| p1.partner=p2 implies p2.partner=p1
  no p: Person | p in p.partner
}

run{}
</code>```

Note that in that case persons can only have one partner each.
This model allows pluralism:

```<code>sig Person {
  partner: some Person
}

fact partnerProperties {
  all p1,p2:Person| p2 in p1.partner  implies p1 in p2.partner
  no p: Person | p in p.partner
}

run{} for 5
</code>```

Body:
I'm learning Alloy modeling language, and I saw this code.

sig Person {
  partner: Person
}

fact partnerProperties {
  partner = ~partner
  no p: Person | p in p.partner
}

This code express "Person's partner relation is mutual".

I can understand above code, but I think how to express partner is relation that wrote in Person expressly.
Because of readability.

I want to write like this.

fact partnerProperties {
  Person.partner = ~Person.partner
  no p: Person | p in p.partner
}

I'm grad to help me.

Body:
You could write a quantification as follows :

sig Person {
  partner: Person
}

fact partnerProperties {
  all p1,p2:Person| p1.partner=p2 implies p2.partner=p1
  no p: Person | p in p.partner
}

run{}

Note that in that case persons can only have one partner each.
This model allows pluralism:

sig Person {
  partner: some Person
}

fact partnerProperties {
  all p1,p2:Person| p2 in p1.partner  implies p1 in p2.partner
  no p: Person | p in p.partner
}

run{} for 5


问:
I am revising a Hotel Reservation System in Our School and my problem is i'm having a hard time showing the output of my prices
```<code><?php
$sql = "SELECT * from tblpv where refID = :refID";
$query = $dbh->prepare($sql);
$query->bindParam(':refID', $refID, PDO::PARAM_STR);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$norooms = 0;
$extrabed = 0;

foreach ($results as $result) {
  $norooms += $result->norooms;
  $extrabed += $result->extrabed;
}
</code>```

This is my html form not complete only example

```<code>    <li>Number of Rooms: <b><?php echo $norooms ?></b></li>
    <li>Number of Extra Bed: <b><?php echo $extrabed ?></b></li>
</code>```

I still can't have my answers shown. I want to know why and how.

The Website
The Database

EDIT 1
My result from the first answer.

1

2

3

4

5

6

7

8

9

10

11

This is what i did, is it right? There's no changes at all sorry i think i lack of logical thinking.

and this is the result of Number of rooms and Number of extra bed

this is what i got

答:
Please try this and tell us the output:</p>

```<code>$refID = '7425901624';

$sql = "SELECT SUM(extrabed) as extrabed, COUNT(id) as norooms from tblpv where refID = :refID";
$query = $dbh->prepare($sql);
$query->bindParam(':refID', $refID);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);

echo "Result: "; print_r( $results ); echo "<br />";
echo "Extrabed: " . $results['extrabed'] . "<br />";
echo "Norooms: " . $results['norooms'] . "<br />";
</code>```

Body:
<?php
$sql = "SELECT * from tblpv where refID = :refID";
$query = $dbh->prepare($sql);
$query->bindParam(':refID', $refID, PDO::PARAM_STR);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$norooms = 0;
$extrabed = 0;

foreach ($results as $result) {
  $norooms += $result->norooms;
  $extrabed += $result->extrabed;
}

This is my html form not complete only example

Number of Rooms: <?php echo $norooms ?>

Number of Extra Bed: <?php echo $extrabed ?>

I still can't have my answers shown. I want to know why and how.

The Website
The Database

EDIT 1
My result from the first answer.

1

2

3

4

5

6

7

8

9

10

11

This is what i did, is it right? There's no changes at all sorry i think i lack of logical thinking.

and this is the result of Number of rooms and Number of extra bed

this is what i got

Body:
Please try this and tell us the output:

$refID = '7425901624';

$sql = "SELECT SUM(extrabed) as extrabed, COUNT(id) as norooms from tblpv where refID = :refID";
$query = $dbh->prepare($sql);
$query->bindParam(':refID', $refID);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);

echo "Result: "; print_r( $results ); echo "<br />";
echo "Extrabed: " . $results['extrabed'] . "<br />";
echo "Norooms: " . $results['norooms'] . "<br />";


问:
How to set a class Name as a method's parameter?
I would like to send a class name as a parameter of method. I would like to use(execute) it like that.

```<code>orderDao.getTheMostFrequentType(EmployeeOrder.class);
</code>```

I have this code

```<code>@Override
public String getTheMostFrequentType(Class<T> orderClass){
    String tableName = orderClass.getAnnotation(Table.class).name();
    String sqlQuery = "SELECT STATS_MODE(signed_by_id) FROM " + tableName;
    String result = (String)getSessionFactory().getCurrentSession().createSQLQuery(sqlQuery).uniqueResult();
    return result;
}
</code>```

But it executing attempts gives me:

```<code>getTheMostFrequentType("org.apache.poi.ss.formula.functions.T") method cannot be applied in "java.lang.entities.EmployeeOrder"
</code>```

May be there is another classes should i import instead of apache.poi. But which one? What i do wrong?

答:
If you are using T in a method of class level, you must define it first in class / method definition, unless "T" is unknown.

```<code>public class MainClass<T> extends Parent
{...}
</code>```

or

```<code>public <T> String getTheMostFrequentType(Class<T> orderClass)
{...}
</code>```

Another option is not define specific type of T with mark "?"
in your case i think it's better solution

TIP: Better to not make code complex with generic if it's not really
  needed.

like that:

```<code>public String getTheMostFrequentType(Class<?> orderClass)
{...}
</code>```

Body:
I would like to send a class name as a parameter of method. I would like to use(execute) it like that.

orderDao.getTheMostFrequentType(EmployeeOrder.class);

I have this code

@Override
public String getTheMostFrequentType(Class<T> orderClass){
    String tableName = orderClass.getAnnotation(Table.class).name();
    String sqlQuery = "SELECT STATS_MODE(signed_by_id) FROM " + tableName;
    String result = (String)getSessionFactory().getCurrentSession().createSQLQuery(sqlQuery).uniqueResult();
    return result;
}

But it executing attempts gives me:

getTheMostFrequentType("org.apache.poi.ss.formula.functions.T") method cannot be applied in "java.lang.entities.EmployeeOrder"

May be there is another classes should i import instead of apache.poi. But which one? What i do wrong?

Body:
If you are using T in a method of class level, you must define it first in class / method definition, unless "T" is unknown.

public class MainClass<T> extends Parent
{...}

or

public <T> String getTheMostFrequentType(Class<T> orderClass)
{...}

Another option is not define specific type of T with mark "?"
in your case i think it's better solution

TIP: Better to not make code complex with generic if it's not really
  needed.

like that:

public String getTheMostFrequentType(Class<?> orderClass)
{...}


问:
Navigating between two fragments on backpress
I am having trouble going back to previous fragment on backpress from current fragment.
I have Two fragments and i navigate to second fragment on click and when i try to click back from the second fragment, i want to go back to the previous fragment but instead the app exits on backpress. below is the code i am using..

Fragment1 calling second fragment

```<code>    UserFragment frag = new UserFragment()
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        frag.setArguments(bundle);
        transaction.addToBackStack("UserActivity");
             transaction.replace(android.R.id.content, frag, "UserActivity").addToBackStack(null);
transaction.commit();
</code>```

In second Fragment i have implemented an interface OnBackpress and over riding the below method

```<code>@Override
public void onBackPressed() {

    if (getFragmentManager().getBackStackEntryCount() != 0) {
        if(getFragmentManager().findFragmentByTag("UserActivity") != null){
            Log.e("UserActivity",getFragmentManager().findFragmentByTag("UserActivity").toString());
            getFragmentManager().popBackStack();
        };
    }

}
</code>```

But on back press the app exits. Instead i want to go back to previous fragment. What mistake am i doing? please help. thanks

答:
First, you need to add your fragments to the backstack:

```<code>public static void addFragment(FragmentManager fragmentManager, Fragment fragment, int id){
    fragmentManager.beginTransaction().add(id, fragment).addToBackStack(null).commit();
}
</code>```

Then you need to override the onBackPressed, which is a method gets called whenever a user clicks the back button:

```<code>@Override
public void onBackPressed() {
    super.onBackPressed();
    if(getSupportFragmentManager().getBackStackEntryCount() == 0){
        button.setVisibility(View.VISIBLE);
    }
}
</code>```

Body:
I am having trouble going back to previous fragment on backpress from current fragment.
I have Two fragments and i navigate to second fragment on click and when i try to click back from the second fragment, i want to go back to the previous fragment but instead the app exits on backpress. below is the code i am using..

Fragment1 calling second fragment

    UserFragment frag = new UserFragment()
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        frag.setArguments(bundle);
        transaction.addToBackStack("UserActivity");
             transaction.replace(android.R.id.content, frag, "UserActivity").addToBackStack(null);
transaction.commit();

In second Fragment i have implemented an interface OnBackpress and over riding the below method

@Override
public void onBackPressed() {

    if (getFragmentManager().getBackStackEntryCount() != 0) {
        if(getFragmentManager().findFragmentByTag("UserActivity") != null){
            Log.e("UserActivity",getFragmentManager().findFragmentByTag("UserActivity").toString());
            getFragmentManager().popBackStack();
        };
    }

}

But on back press the app exits. Instead i want to go back to previous fragment. What mistake am i doing? please help. thanks

Body:
First, you need to add your fragments to the backstack:

public static void addFragment(FragmentManager fragmentManager, Fragment fragment, int id){
    fragmentManager.beginTransaction().add(id, fragment).addToBackStack(null).commit();
}

Then you need to override the onBackPressed, which is a method gets called whenever a user clicks the back button:

@Override
public void onBackPressed() {
    super.onBackPressed();
    if(getSupportFragmentManager().getBackStackEntryCount() == 0){
        button.setVisibility(View.VISIBLE);
    }
}


问:
bitwise join two if's into one
I have this,

```<code>public enum Condition : uint // bitwise
{
    None = 0,
    NewLine = 1,
    Space = 2
}

Rule.Condition someCondition = Rule.Condition.Space | Rule.Condition.NewLine;
</code>```

I'd like to convert this,

```<code>if ((Rule.Condition.Space & condition) == Rule.Condition.Space) return true;
if ((Rule.Condition.NewLine & condition) == Rule.Condition.NewLine) return true;
</code>```

Into something like,

```<code>if((someCondition & condition) == someCondition) return true;
</code>```

But it isn't working.  What am I forgetting?

答:
someCondition has two bits set, one for Rule.Condition.Space and one for Rule.Condition.NewLine. someCondition & condition will have one bit set if condition is Space or NewLine, and be 0 otherwise.

You should test if the bitwise operation returns 0 instead of checking for equality with someCondition

```<code>if ((someCondition & condition) != 0) return true
</code>```

ContentLicense: CC BY-SA 3.0

Title: bitwise join two if's into one

Body:
I have this,

public enum Condition : uint // bitwise
{
    None = 0,
    NewLine = 1,
    Space = 2
}

Rule.Condition someCondition = Rule.Condition.Space | Rule.Condition.NewLine;

I'd like to convert this,

if ((Rule.Condition.Space & condition) == Rule.Condition.Space) return true;
if ((Rule.Condition.NewLine & condition) == Rule.Condition.NewLine) return true;

Into something like,

if((someCondition & condition) == someCondition) return true;

But it isn't working.  What am I forgetting?

Body:
someCondition has two bits set, one for Rule.Condition.Space and one for Rule.Condition.NewLine. someCondition & condition will have one bit set if condition is Space or NewLine, and be 0 otherwise.

You should test if the bitwise operation returns 0 instead of checking for equality with someCondition

if ((someCondition & condition) != 0) return true


问:
Spring boot actuator 2 metrics from custom function
I am in the spring-boot-actuator world mow...

How can I add my own metrics coming from a custom function from my @Service class?

I would expect to have something like

```<code>meterRegistry.registerNewGauge(
    "animals_count",
    "cats",
    animalCounterService::countCatsFromDatabase
);
</code>```

currently i can only find easy metrics like

```<code>meterRegistry.counter("animals_count").increment();
</code>```

but that doesn't help much when I have to aggregate things like database entries. I need a more flexible one.
I also found something like MeterBinder.bindTo but that didn't worked. No error, nothing in metrics.
I am searching now for months without any success.

thanks

答:
I'm assuming you're using Micrometer for metrics, right?

If so, you can create a gauge and bind it to any object that provides a method that returns double like this:

```<code>@Service
public class MyService {
...
   public double calculateValueForGauge() {...}
}

MyService service = ...// get from spring
MeterRegistry registry = ... // get from spring

// here is how you can create a gauge and bind it to an arbitrary method of your service
Gauge.builder("some.name.goes.here, service, (service) -> service.calculateValueForGauge())
          .register(registry);
</code>```

For example you can place the code of gauge registration to the listener that will be called when the application context is started:

```<code>@EventListener
public void onApplicationStarted(ApplicationReadyEvent event) {
  // register gauges here
}
</code>```

Body:
I am in the spring-boot-actuator world mow...

How can I add my own metrics coming from a custom function from my @Service class?

I would expect to have something like

meterRegistry.registerNewGauge(
    "animals_count",
    "cats",
    animalCounterService::countCatsFromDatabase
);

currently i can only find easy metrics like

meterRegistry.counter("animals_count").increment();

but that doesn't help much when I have to aggregate things like database entries. I need a more flexible one.
I also found something like MeterBinder.bindTo but that didn't worked. No error, nothing in metrics.
I am searching now for months without any success.

thanks

Body:
I'm assuming you're using Micrometer for metrics, right?

If so, you can create a gauge and bind it to any object that provides a method that returns double like this:

@Service
public class MyService {
...
   public double calculateValueForGauge() {...}
}

MyService service = ...// get from spring
MeterRegistry registry = ... // get from spring

// here is how you can create a gauge and bind it to an arbitrary method of your service
Gauge.builder("some.name.goes.here, service, (service) -> service.calculateValueForGauge())
          .register(registry);

For example you can place the code of gauge registration to the listener that will be called when the application context is started:

@EventListener
public void onApplicationStarted(ApplicationReadyEvent event) {
  // register gauges here
}


问:
Numpy: Elegant solution to calculating output matrix of function with indefinite number of variables
I have been searching all weekend for a more elegant (read: no manual for-loop programming) solution to the following problem:

Lets assume we have a custom function f() with an indefinite number of inputs. For simplicity, let us start with two:

```<code>def f(x,y):
    return x + y
</code>```

Now I pass an array with the correct number of variables to this function:

```<code>x = np.array([x0, x1, x2, ..., xn])
y = np.array([y0, y1, y2, ..., yn])
</code>```

The answer I look for is:

```<code>z = np.array([[x0 + y0, x0 + y1, x0 + y2, ..., x0 + yn],
              [x1 + y0, x1 + y1, x1 + y2, ..., x1 + yn],
              [x2 + y0, x2 + y1, x2 + y2, ..., x2 + yn],
              ...])
</code>```

So, in summary, I am looking for a function, that I can pass another custom function to, which then calculates all possible combinations, without me having to program a ridiculous number of for-loops.

Please help me, hive mind!

Edit 1: the custom function may be of arbitrary complexity. From my real world problem, this is one example:

```<code>def f(x, y):
    return 1 - (x/2)**y*binom(y, y/2)
</code>```

Edit 2: the accepted answer works as intended. The answer of Dishin H Goyani linking to stackoverflow.com/a/32742943/6075699 produces the same result using a different path.

Thanks everyone! Stackoverflow rules!

答:
It seems like you're looking for an application of the dot product:

```<code>In [1]: a = np.array([1, 2, 3, 4, 5, 6, 7])
In [2]: b = np.array([1, 2, 3, 4, 5, 6, 7])
In [3]: np.dot(np.matrix(a).T, np.matrix(b))
Out[3]:
 matrix([[ 1,  2,  3,  4,  5,  6,  7],
         [ 2,  4,  6,  8, 10, 12, 14],
         [ 3,  6,  9, 12, 15, 18, 21],
         [ 4,  8, 12, 16, 20, 24, 28],
         [ 5, 10, 15, 20, 25, 30, 35],
         [ 6, 12, 18, 24, 30, 36, 42],
         [ 7, 14, 21, 28, 35, 42, 49]])
</code>```

This only works, if you convert your array into something that has 2 dimensions (like the matrix object) of which one is a singleton dimension. Then transpose one of them and the dot product can give you exactly what you need.

Body:
I have been searching all weekend for a more elegant (read: no manual for-loop programming) solution to the following problem:

Lets assume we have a custom function f() with an indefinite number of inputs. For simplicity, let us start with two:

def f(x,y):
    return x + y

Now I pass an array with the correct number of variables to this function:

x = np.array([x0, x1, x2, ..., xn])
y = np.array([y0, y1, y2, ..., yn])

The answer I look for is:

z = np.array([[x0 + y0, x0 + y1, x0 + y2, ..., x0 + yn],
              [x1 + y0, x1 + y1, x1 + y2, ..., x1 + yn],
              [x2 + y0, x2 + y1, x2 + y2, ..., x2 + yn],
              ...])

So, in summary, I am looking for a function, that I can pass another custom function to, which then calculates all possible combinations, without me having to program a ridiculous number of for-loops.

Please help me, hive mind!

Edit 1: the custom function may be of arbitrary complexity. From my real world problem, this is one example:

def f(x, y):
    return 1 - (x/2)**y*binom(y, y/2)

Edit 2: the accepted answer works as intended. The answer of Dishin H Goyani linking to stackoverflow.com/a/32742943/6075699 produces the same result using a different path.

Thanks everyone! Stackoverflow rules!

Body:
It seems like you're looking for an application of the dot product:

In [1]: a = np.array([1, 2, 3, 4, 5, 6, 7])
In [2]: b = np.array([1, 2, 3, 4, 5, 6, 7])
In [3]: np.dot(np.matrix(a).T, np.matrix(b))
Out[3]:
 matrix([[ 1,  2,  3,  4,  5,  6,  7],
         [ 2,  4,  6,  8, 10, 12, 14],
         [ 3,  6,  9, 12, 15, 18, 21],
         [ 4,  8, 12, 16, 20, 24, 28],
         [ 5, 10, 15, 20, 25, 30, 35],
         [ 6, 12, 18, 24, 30, 36, 42],
         [ 7, 14, 21, 28, 35, 42, 49]])

This only works, if you convert your array into something that has 2 dimensions (like the matrix object) of which one is a singleton dimension. Then transpose one of them and the dot product can give you exactly what you need.


问:
suggestion about implement sms app in MEAN stack
Im using third parties sms service provider it cost more to my services so im interested create my own sms gateway app in MEAN stack technologies. i was searched lot of things but could not get proper information about implementation SMS app  so anyone suggest to implement</p>

答: You can use Twilio for this. You send them the message and the number via a REST API call and you get notified of its status by webhooks.</p>


问:
How do I make a file of specific size in c++?
How do i make a dummy file?

I'm using Visual C++ for a form and I need it to make a dummy file.
I know how to use things like fstream to write to files but how can I do it so that I know the exact size of the resulting file?

I already tried fstuil but that's a CMD command (yes i know you can use system()) whereas i want pure c++.

答:
Try this (creates a 1MB file):</p>

```<code>#include <fstream>

int main()
{
    std::ofstream ofs("foo.bar", std::ios::binary | std::ios::out);
    ofs.seekp((1024*1024) - 1);
    ofs.write("", 1);
}
</code>```

Body:
Try this (creates a 1MB file):

#include <fstream>

int main()
{
    std::ofstream ofs("foo.bar", std::ios::binary | std::ios::out);
    ofs.seekp((1024*1024) - 1);
    ofs.write("", 1);
}


问:
Python - How do I do conditional counting of rows based on various columns?
I want to create a Python dataframe that counts the number of times that the types C or P occur for each date in each sample. C and P are subsets of F meaning that whenever Type is equal to F, I can count the number of rows with the same Sample value and the same Date value.

I cannot hardcode the conditions as the actual data set is much larger than the sample. This means that I need to base my conditions on the values in the data set where Type is equal to F.

Here is a sample of my data set, df_Data (the actual one being much larger):

Sample | Type | Date | Strike

      A      | F | 1 Jun 2020 |

      A | C | 1 Jun 2020 | 5

      A | P | 1 Jun 2020 | 2.5

      A | F | 1 Dec 2020 |

      A | P | 1 Dec 2020 | 3

      A | P | 1 Dec 2020 | 3.5

      A | P | 1 Dec 2020 | 4

      B | F | 1 Jun 2020 |

      B | C | 1 Jun 2020 | 2.5

      B | C | 1 Jun 2020 | 3

      B | C | 1 Jun 2020 | 4

      B | F | 1 Dec 2020 |

      B | C | 1 Dec 2020 | 2

      B | C | 1 Dec 2020 | 4

      B | P | 1 Dec 2020 | 2

      B | P | 1 Dec 2020 | 4

The corresponding output is a new dataframe like this one:

Sample | Type | Date | Count

=======================

```<code>A | F | 1 Jun 2020 |2
A | F | 1 Dec 2020 |3
B | F | 1 Jun 2020 |3
B | F | 1 Dec 2020 |4
</code>```

In Excel I would have used the CountIfs-function:

IF Type = "F" then countifs(Sample-column, Sample-value, Date-column, Date-value, Type-column, "<> F")

Please help (apologies for the poor table formatting).

答:
I suggest to following code:

```<code>import pandas as pd
df = pd.read_csv('sample.csv')
df['Type']=df['Type'].apply(lambda x: 'F' if x == 'P' or 'C' else '')
adf = df.groupby(['Sample', 'Type', 'Dat`enter code here`e'],as_index=False).agg({'Strike':['count']})
</code>```

This code reads sample.csv into a dataframe. Then, you perform a lambda-query on the column Type.  The final result is in adf.

Body:
I want to create a Python dataframe that counts the number of times that the types C or P occur for each date in each sample. C and P are subsets of F meaning that whenever Type is equal to F, I can count the number of rows with the same Sample value and the same Date value.

I cannot hardcode the conditions as the actual data set is much larger than the sample. This means that I need to base my conditions on the values in the data set where Type is equal to F.

Here is a sample of my data set, df_Data (the actual one being much larger):

Sample | Type | Date | Strike

      A      | F | 1 Jun 2020 |

      A | C | 1 Jun 2020 | 5

      A | P | 1 Jun 2020 | 2.5

      A | F | 1 Dec 2020 |

      A | P | 1 Dec 2020 | 3

      A | P | 1 Dec 2020 | 3.5

      A | P | 1 Dec 2020 | 4

      B | F | 1 Jun 2020 |

      B | C | 1 Jun 2020 | 2.5

      B | C | 1 Jun 2020 | 3

      B | C | 1 Jun 2020 | 4

      B | F | 1 Dec 2020 |

      B | C | 1 Dec 2020 | 2

      B | C | 1 Dec 2020 | 4

      B | P | 1 Dec 2020 | 2

      B | P | 1 Dec 2020 | 4

The corresponding output is a new dataframe like this one:

Sample | Type | Date | Count

=======================

A | F | 1 Jun 2020 |2
A | F | 1 Dec 2020 |3
B | F | 1 Jun 2020 |3
B | F | 1 Dec 2020 |4

In Excel I would have used the CountIfs-function:

IF Type = "F" then countifs(Sample-column, Sample-value, Date-column, Date-value, Type-column, "<> F")

Please help (apologies for the poor table formatting).

Body:
I suggest to following code:

import pandas as pd
df = pd.read_csv('sample.csv')
df['Type']=df['Type'].apply(lambda x: 'F' if x == 'P' or 'C' else '')
adf = df.groupby(['Sample', 'Type', 'Dat`enter code here`e'],as_index=False).agg({'Strike':['count']})

This code reads sample.csv into a dataframe. Then, you perform a lambda-query on the column Type.  The final result is in adf.


问:
Error while inserting date column into oracle database using odbc package in R
we are using odbc connection to connect target database (oracle database) and we need to insert a dataframe into target database. We are using dbBind() to insert data frame into database. Please find the sample data and code mentioned below.

```<code>Dataframe: Inputdata
  column1    column2    column3      date_column  column4
  <chr>      <chr>      <chr>        <chr>         <chr>
1 1111       6          fff          2015-11-01    MCA
2 2222       1          aaa          2006-12-02    NA
3 3333       2          bbb          2007-10-03    NA
4 4444       3          ccc          2008-01-04    NA
5 555        4          ddd          2007-11-05    NA
6 6666       5          eee          2010-11-06    BCH

R script :
Target1Conn<-dbConnect(odbc::odbc(), dsn = "TARGETDB", uid = "username", pwd = "password")
insert <- dbSendQuery(Target1Conn, paste0('insert into ', outputTableName, '(column1,column2,column3,date_column,column4) values(?,?,?,?,?)'))
dbBind(insert, list(InputData$column1,InputData$column2,InputData$column3,InputData$date_column,InputData$column4))"

Error:
Error in result_bind(res@ptr, as.list(params), batch_rows) :
  nanodbc/nanodbc.cpp:1617: 00000: [Oracle][ODBC][Ora]ORA-01861: literal does not match format string
</code>```

My DataFrame has 1.3 million records and with the above approach after inserting 1024 records, the script is getting failed with error mentioned above.

if we ignore date column and insert data , we are able to insert data into database without any issues. Please let us know if any other solution is present.

答:
Try

```<code>library(tidyverse)
library(lubridate)

df <- df %>%
    mutate(date_column = ymd(date_column))
</code>```

and then run your code again.

Body:
we are using odbc connection to connect target database (oracle database) and we need to insert a dataframe into target database. We are using dbBind() to insert data frame into database. Please find the sample data and code mentioned below.

Dataframe: Inputdata
  column1    column2    column3      date_column  column4
  <chr>      <chr>      <chr>        <chr>         <chr>
1 1111       6          fff          2015-11-01    MCA
2 2222       1          aaa          2006-12-02    NA
3 3333       2          bbb          2007-10-03    NA
4 4444       3          ccc          2008-01-04    NA
5 555        4          ddd          2007-11-05    NA
6 6666       5          eee          2010-11-06    BCH

R script :
Target1Conn<-dbConnect(odbc::odbc(), dsn = "TARGETDB", uid = "username", pwd = "password")
insert <- dbSendQuery(Target1Conn, paste0('insert into ', outputTableName, '(column1,column2,column3,date_column,column4) values(?,?,?,?,?)'))
dbBind(insert, list(InputData$column1,InputData$column2,InputData$column3,InputData$date_column,InputData$column4))"

Error:
Error in result_bind(res@ptr, as.list(params), batch_rows) :
  nanodbc/nanodbc.cpp:1617: 00000: [Oracle][ODBC][Ora]ORA-01861: literal does not match format string

My DataFrame has 1.3 million records and with the above approach after inserting 1024 records, the script is getting failed with error mentioned above.

if we ignore date column and insert data , we are able to insert data into database without any issues. Please let us know if any other solution is present.

Body:
Try

library(tidyverse)
library(lubridate)

df <- df %>%
    mutate(date_column = ymd(date_column))

and then run your code again.


问:
Create a table in excel sheet and add rows in table with SQL in loop
In excel vba ,I am running SQL in a for loop and I want the result of SQL in loop to be added as a table in my excel worksheet.
the example code snippet is given below. So the below code just checks user activity between 2 dates. I need this data to be presented in form of table with excel vba.</p>

```<code>    Sub activity_count

    Dim x as date
    Dim start_date as date
    Dim End_date as date
    Dim rsResult as object
    Dim strSql as string

    for x=start_date to end_date

    Set rsResult =CreateObject("ADODB.Recordset")

    strSQL="select logdate, username, activity_count from table where logdate='"&start_date
    strSQL= strSQL & "'"
    strSQL=strSQL & ";"

    Call Logon
    rsResult.Open strSQL, Conn

    'with your help ,I need the code to write this data in same excel sheet in the form of table.

    rsResult.close
    Set rsResult=nothing
    Set Conn=nothing
    strSQL=""

    start_date=DateAdd("d",1,start_date)

    next
end sub
</code>```

答:
Since this is part of a bigger report routine, create the db connection at the start of the script, pass it as a parameter to all other parts that need it then disconnect at the end. Not sure why you want to retrieve the records one date at a time when the BETWEEN function does it in one statement. For example

    Option Explicit
    Sub bigreport()

       Dim conn As ADODB.Connection
       Call Logon  ' establish the connection conn

       ' create activity table
       ' db connection, start_date, end_date , results sheet, table position
       Call activity_count(conn, "01/01/2020", "01/02/2020", "Sheet3", "B2")

       conn.Close
       Set conn = Nothing

    End Sub

    Sub activity_count(conn As ADODB.Connection, start_date As Date, end_date As Date, _
                        sheet_name As String, table_posn As String)

        Dim cmd As ADODB.Command, strSQL As String

        ' query
        strSQL = " SELECT logdate, username, activity_count " & _
                 " FROM Table_1 " & _
                 " WHERE logdate BETWEEN ? AND ? " & _
                 " ORDER BY logdate, username "

        ' parameters
        Dim p1 As String, p2 As String
        p1 = Format(start_date, "yyyy-mm-dd")
        p2 = Format(end_date, "yyyy-mm-dd")
        'Debug.Print p1, p2

        Set cmd = New ADODB.Command
        With cmd
            .ActiveConnection = conn
            .CommandText = strSQL
            .CommandType = 1 'adCmdText
            .Parameters.Append .CreateParameter("P1", adVArChar, 1, 10, p1) '
            .Parameters.Append .CreateParameter("P2", adVArChar, 1, 10, p2) ' adParamInput = 1
        End With

        'run query
        Dim rsResult As ADODB.Recordset
        Set rsResult = cmd.Execute

        ' create table
        Dim wb As Workbook, ws As Worksheet
        Set wb = ThisWorkbook
        Set ws = wb.Sheets(sheet_name)
        ws.Cells.Clear
        With ws.Range(table_posn)
            .Value = Array("Log Date", "User Name", "Activity Count")
            .Offset(1, 0).CopyFromRecordset rsResult
            ws.ListObjects.Add xlSrcRange, .CurrentRegion, , xlYes
            .AutoFilter
            .EntireColumn.HorizontalAlignment = xlCenter
            .Offset(0, 2).EntireColumn.HorizontalAlignment = xlCenter
        End With

        ' end
        MsgBox rsResult.RecordCount & " records written to " & sheet_name, vbInformation, "Finished"
        rsResult.Close
        Set rsResult = Nothing

    End Sub
```

Body:
In excel vba ,I am running SQL in a for loop and I want the result of SQL in loop to be added as a table in my excel worksheet.
the example code snippet is given below. So the below code just checks user activity between 2 dates. I need this data to be presented in form of table with excel vba.

    Sub activity_count

    Dim x as date
    Dim start_date as date
    Dim End_date as date
    Dim rsResult as object
    Dim strSql as string

    for x=start_date to end_date

    Set rsResult =CreateObject("ADODB.Recordset")

    strSQL="select logdate, username, activity_count from table where logdate='"&start_date
    strSQL= strSQL & "'"
    strSQL=strSQL & ";"

    Call Logon
    rsResult.Open strSQL, Conn

    'with your help ,I need the code to write this data in same excel sheet in the form of table.

    rsResult.close
    Set rsResult=nothing
    Set Conn=nothing
    strSQL=""

    start_date=DateAdd("d",1,start_date)

    next
end sub


问:
Redirecting after form submission with user input in the URL
I need to have a form that when filled out will create a variable and then goto a url with that variable in the url.

Something like this (but that works) :)

```<code><form action="?????" method="?????">

Number: <input type="text" name="url1" value=""><br>

<input type="submit" name="submit" value="Goto URL">
</form>
</code>```

When the submit is pressed I need it to goto http://somewhere.com?url=VALUEHERE

Any ideas?

答:
Use method="GET" to place the variables in the url:

```<code><form action="http://somewhere.com/" method="GET">
    Number: <input type="text" name="url" value="" /><br />

    <input type="submit" name="submit" value="Goto URL" />
</form>
</code>```

Posting this form will go to http://somewhere.com/?url=USER_INPUT_URL

Body:
I need to have a form that when filled out will create a variable and then goto a url with that variable in the url.

Something like this (but that works) :)

<form action="?????" method="?????">

Number: <input type="text" name="url1" value="">

<input type="submit" name="submit" value="Goto URL">
</form>

When the submit is pressed I need it to goto http://somewhere.com?url=VALUEHERE

Any ideas?

Body:
Use method="GET" to place the variables in the url:

<form action="http://somewhere.com/" method="GET">
    Number: <input type="text" name="url" value="" /><br />

    <input type="submit" name="submit" value="Goto URL" />
</form>

Posting this form will go to http://somewhere.com/?url=USER_INPUT_URL


问:
Nested components in Angular CLI not accessible after first level
I'm new in Angular CLI and I'm trying to make my first web based on an older one I've made.
Until now, I'm able to nest and show components inside the root component, but from that point onwards I can't refer to any component in the HTML.

Here's my code:

index.html

```<code><!doctype html>
  <html lang="es">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Testing Angular</title>
      <base href="/">
      <link rel="icon" type="image/x-icon" href="favicon.ico">
    </head>
    <body>
      <app-root></app-root>
    </body>
  </html>
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { FirstComponent } from './first/first.component';

@NgModule({
  declarations: [AppComponent, FirstComponent],
  imports: [BrowserModule, AppRoutingModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ["./app.component.css"]
})

export class AppComponent {}
</code>```

app.component.html

```<code><section id="container">
  <app-first></app-first>
</section>

<router-outlet></router-outlet>
</code>```

first.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SecondComponent } from './second/second.component';

@NgModule({
  declarations: [SecondComponent],
  imports: [CommonModule]
})
export class FirstModule { }
</code>```

first.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ["./first.component.css"]
})

export class FirstComponent {}
</code>```

first.component.html

```<code><div id="first">
  <app-second></app-second> <!-- This gives an error: it doesn't know whats Second Component -->
</div>
</code>```

second.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [CommonModule],
  declarations: []
})
export class SecondModule { }
</code>```

second.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ["./second.component.css"]
})

export class SecondComponent {}
</code>```

second.component.html

```<code><div id="second">
  <span>I'm second component!</span>
</div>
</code>```

The <app-second></app-second> reference gives an error. In Visual Studio Code is not even in the list of suggestions.

答:
You have to include your modules somewhere, angular don't know anything about your SecondComponent, add FirstModule or SecondModule to your AppModule.
Take a look at Angular docs to get more strategies https://angular.io/docs

```<code>  imports: [BrowserModule, AppRoutingModule, FirstModule],
</code>```

Modify your FirstModule with adding exports with components which you want to share for others modules.

```<code>exports: [SecondComponent]
</code>```

Body:
I'm new in Angular CLI and I'm trying to make my first web based on an older one I've made.
Until now, I'm able to nest and show components inside the root component, but from that point onwards I can't refer to any component in the HTML.

Here's my code:

index.html

<!doctype html>

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Testing Angular</title>
      <base href="/">
      <link rel="icon" type="image/x-icon" href="favicon.ico">

      <app-root></app-root>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { FirstComponent } from './first/first.component';

@NgModule({
  declarations: [AppComponent, FirstComponent],
  imports: [BrowserModule, AppRoutingModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ["./app.component.css"]
})

export class AppComponent {}

app.component.html

  <app-first></app-first>

<router-outlet></router-outlet>

first.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SecondComponent } from './second/second.component';

@NgModule({
  declarations: [SecondComponent],
  imports: [CommonModule]
})
export class FirstModule { }

first.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ["./first.component.css"]
})

export class FirstComponent {}

first.component.html

  <app-second></app-second>

second.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [CommonModule],
  declarations: []
})
export class SecondModule { }

second.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ["./second.component.css"]
})

export class SecondComponent {}

second.component.html

  I'm second component!

The <app-second></app-second> reference gives an error. In Visual Studio Code is not even in the list of suggestions.

Body:
You have to include your modules somewhere, angular don't know anything about your SecondComponent, add FirstModule or SecondModule to your AppModule.
Take a look at Angular docs to get more strategies https://angular.io/docs

  imports: [BrowserModule, AppRoutingModule, FirstModule],

Modify your FirstModule with adding exports with components which you want to share for others modules.

exports: [SecondComponent]


问:
Filter array using multiple keys
I'm trying to render grid with multiple toggling filters. I'm Using react hooks.

This is data array:

```<code>const items = [
    {
        name: 'hotel1',
        type: 'hotel'
    },
    {
        name: 'bar1',
        type: 'bar'
    },{
        name: 'entertainment1',
         type: 'entertainment'
    },{
        name: 'equipment1',
        type: 'equipment'
    },
    {
        name: 'shop1',
        type: 'shop'
    }
]

    const initialFilters = [
        {
            id: 1,
            active: false,
            type: 'bar'
        },
        {
            id: 2,
            active: false,
            type: 'shop'
        },
        {
            id: 3,
            active: false,
            type: 'hotel'
        },
        {
            id: 4,
            active: false,
            type: 'entertainment'
        },
        {
            id: 5,
            active: false,
            type: 'equipment'
        },
    ];

const [data, setData] = useState(items);
const [filterItems, setFilteredItems] = useState(initialFilters);

</code>```

currently I'm filtering with single key that is passed

```<code>const mainFilter = (key) => {
 setData(items.filter(x => x.type === key));
}
</code>```

and filter buttons with grid item names are rendered:

```<code>return (
    <div>
        <ul>
            {filterItems.map(x =>
                <li key={x.type}><a
                    className={x.active == true ? 'active' : ''}
                    onClick={() => mainFilter(x.type)}>
                    {x.type}
                </a></li>
            )}
        </ul>
     <div>{data.map(item => <div>{item.name}</div>}</div>
    </div>
)
</code>```

I need to get the functionality where when pressed for example shop filter, it should only leave items with type shop. if you press bar filter, it should only leave items with bar an shop and it should work all the way to all 5 filters.
if none are selected, it should show full array.

I've tried converting logic from this:

https://gist.github.com/jherax/f11d669ba286f21b7a2dcff69621eb72#file-filterplainarray-js

but no luck yet

答:
You can store the selected keys and then sort by checking if they are included:

const mainFilter = (keys) => {
 setData(items.filter(x => keys.includes(x.type)));
}
```

This implementation would need a change in your onClick function - instead of calling a function with the key you'll need to store the keys.

Title: Filter array using multiple keys

Body:
I'm trying to render grid with multiple toggling filters. I'm Using react hooks.

This is data array:

const items = [
    {
        name: 'hotel1',
        type: 'hotel'
    },
    {
        name: 'bar1',
        type: 'bar'
    },{
        name: 'entertainment1',
         type: 'entertainment'
    },{
        name: 'equipment1',
        type: 'equipment'
    },
    {
        name: 'shop1',
        type: 'shop'
    }
]

    const initialFilters = [
        {
            id: 1,
            active: false,
            type: 'bar'
        },
        {
            id: 2,
            active: false,
            type: 'shop'
        },
        {
            id: 3,
            active: false,
            type: 'hotel'
        },
        {
            id: 4,
            active: false,
            type: 'entertainment'
        },
        {
            id: 5,
            active: false,
            type: 'equipment'
        },
    ];

const [data, setData] = useState(items);
const [filterItems, setFilteredItems] = useState(initialFilters);

currently I'm filtering with single key that is passed

const mainFilter = (key) => {
 setData(items.filter(x => x.type === key));
}

and filter buttons with grid item names are rendered:

return (

            {filterItems.map(x =>

 mainFilter(x.type)}>
                    {x.type}

            )}

{data.map(item =>
{item.name}
}

)

I need to get the functionality where when pressed for example shop filter, it should only leave items with type shop. if you press bar filter, it should only leave items with bar an shop and it should work all the way to all 5 filters.
if none are selected, it should show full array.

I've tried converting logic from this:

https://gist.github.com/jherax/f11d669ba286f21b7a2dcff69621eb72#file-filterplainarray-js

but no luck yet

Body:
You can store the selected keys and then sort by checking if they are included:

const mainFilter = (keys) => {
 setData(items.filter(x => keys.includes(x.type)));
}

This implementation would need a change in your onClick function - instead of calling a function with the key you'll need to store the keys.


问:
Make ScrollView - Items use a percentage size of the whole screen
My current scrollview items have the problem, that I need to set a fixed height and width for them in order to show up properly on different devices.

Every scrollview item should use 1/6 of the screen height in order to fit for different screen sizes... but how do we achieve this without making the scrollview unscrollable ?

My current attempt...

```<code> <ScrollView style={{backgroundColor: 'blue'}} contentContainerStyle={{flexGrow: 1}}>

    { /* Renders the header */}
    <Header text={Constants.header} screen="Drills&Games"/>

     <BoxView></BoxView>
     <BoxView></BoxView>
     <BoxView></BoxView>
     <BoxView></BoxView>
     <BoxView></BoxView>

  </ScrollView>

export default class BoxView extends Component{

    render(){

        return(

            <View style={{backgroundColor: 'red', flex: 0.25}}>

            </View>
        );
    }
}
</code>```

Renders a scrollview with 5 BoxView-Items... The problem here is... the box views do scale correctly, each one uses 0.25 flex, but the list is not scrollable anymore.

So how do we pass a percentage/flex height to the items with keeping the scrollview scrollable ?

答:
On react native I recommend using Dimensions on setting dynamic height.

for getting the 1/6 of the screen I would do is

```<code>{ height: Dimensions.get("screen").height * 0.16 }
</code>```

Body:
My current scrollview items have the problem, that I need to set a fixed height and width for them in order to show up properly on different devices.

Every scrollview item should use 1/6 of the screen height in order to fit for different screen sizes... but how do we achieve this without making the scrollview unscrollable ?

My current attempt...

 <ScrollView style={{backgroundColor: 'blue'}} contentContainerStyle={{flexGrow: 1}}>

    { /* Renders the header */}

     <BoxView></BoxView>
     <BoxView></BoxView>
     <BoxView></BoxView>
     <BoxView></BoxView>
     <BoxView></BoxView>

  </ScrollView>

export default class BoxView extends Component{

    render(){

        return(

            <View style={{backgroundColor: 'red', flex: 0.25}}>

            </View>
        );
    }
}

Renders a scrollview with 5 BoxView-Items... The problem here is... the box views do scale correctly, each one uses 0.25 flex, but the list is not scrollable anymore.

So how do we pass a percentage/flex height to the items with keeping the scrollview scrollable ?

Body:
On react native I recommend using Dimensions on setting dynamic height.

for getting the 1/6 of the screen I would do is

{ height: Dimensions.get("screen").height * 0.16 }


问:
Can I use a hosted build agent to build a VS 2019 project that targets both netcore 2.1 and 3.1?
I had a VS 2017 project that targeted netcore 2.1. This was built and deployed using a YAML build pipeline on the hosted vs 2017 agent.

We needed to support netcore 3.1 as well as 2.1 so I updated the project to VS 2019 and changed it to multi-target both netcore 2.1 and 3.1. This builds fine on my dev machine but (obviously) failed on the existing build pipeline that uses the vs 2017 image.

Based on the documentation I have update the build pipeline to use the 'windows-2019' vm image.

However, this gives me the following error message:

```<code>The framework 'Microsoft.NETCore.App', version '2.1.0' was not found.
</code>```

I'd rather not create and maintain a build server internally for this so is it possible on a hosted agent?

答:
This turns out to have been caused by the test projects still targeting netcore 2.1.

Our build pipeline runs tests (using the vstest task) on both x86 and x64 and it was only the x86 tests that were failing.

After we updated the test projects to netcore 3.1, it worked as expected and the tests passed.

Body:
I had a VS 2017 project that targeted netcore 2.1. This was built and deployed using a YAML build pipeline on the hosted vs 2017 agent.

We needed to support netcore 3.1 as well as 2.1 so I updated the project to VS 2019 and changed it to multi-target both netcore 2.1 and 3.1. This builds fine on my dev machine but (obviously) failed on the existing build pipeline that uses the vs 2017 image.

Based on the documentation I have update the build pipeline to use the 'windows-2019' vm image.

However, this gives me the following error message:

The framework 'Microsoft.NETCore.App', version '2.1.0' was not found.

I'd rather not create and maintain a build server internally for this so is it possible on a hosted agent?


问:
Conditional exclusion of file from compilation in maven project
What the easiest/right way to conditionally exclude a java file from compilation in a maven project?

I would like to be able to set a 'boolean' properties in the pom.xml:

```<code><properties>
    <IncludeMayBe>true</IncludeMayBe>
</properties>

...

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <excludes>
            ????

        </excludes>
    </configuration>
</plugin>
</code>```

Is there a way to fiddle something with the compiler plugin? Or should I go for profiles? I feel like creating a profile is overkill, but may be this is the only solution...

EDIT:

We have established that profiles are the solution. For conditional activation from within the pom.xml, one can use the following:

```<code><profiles>
  <profile>
    <activation>
      <property>
        <IncludeMayBe>true</IncludeMayBe>
      </property>
    </activation>
    ...
  </profile>
</profiles>
</code>```

答:
You cannot do this using the compiler plugin (see below).

But even if you could, it doesn't feel right.  It would mean that the files in a artifact JAR file would depend on command line switches and/or environmental settings, and that makes it harder for other folks to reproduce builds.

My gut feeling is that you'd be better of modularizing your maven project and using profiles to determine what modules get built.

I had a look at the source code of the compiler plugin mojo, and it looks like there's no way to configure source include / exclude filters.  At some point, someone has implemented filters, but the relevant Map objects are private and there is no way to populate them, and hence no way to use this functionality.

The code is here: http://svn.apache.org/viewvc/maven/plugins/tags/maven-compiler-plugin-2.3.2/src/main/java/org/apache/maven/plugin/

I guess you could hack your own version of the plugin ... but it seems like a bad idea.

Body:
What the easiest/right way to conditionally exclude a java file from compilation in a maven project?

I would like to be able to set a 'boolean' properties in the pom.xml:

<properties>
    <IncludeMayBe>true</IncludeMayBe>
</properties>

...

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <excludes>
            ????

        </excludes>
    </configuration>
</plugin>

Is there a way to fiddle something with the compiler plugin? Or should I go for profiles? I feel like creating a profile is overkill, but may be this is the only solution...

EDIT:

We have established that profiles are the solution. For conditional activation from within the pom.xml, one can use the following:

<profiles>
  <profile>
    <activation>
      <property>
        <IncludeMayBe>true</IncludeMayBe>
      </property>
    </activation>
    ...
  </profile>
</profiles>


问:
How to apply hashing SHA256 on Django LDAP login?
I'm using LDAP authentication in Django, as shown below and also using password hashers.

```<code>from django_auth_ldap.config import PosixGroupType, LDAPSearch
import ldap

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

# We use a dedicated user to bind to the LDAP server and execute the server.
AUTH_LDAP_SERVER_URI = "ldap://xx.xx.xx.xx:389"
AUTH_LDAP_BIND_DN = "xxxxx@xxxx.com"
AUTH_LDAP_BIND_PASSWORD = "xxxxx"
AUTH_LDAP_CONNECTION_OPTIONS = {
    ldap.OPT_DEBUG_LEVEL: 1,
    ldap.OPT_REFERRALS: 0,
}

# sAMAccountName is mostly used for Micrsoft Active Directory
# objectCategory    CN=Person,CN=Schema,CN=Configuration,DC=corp,DC=xxxx,DC=com
# (cn=%(user)s)
AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=corp,DC=xxxxx,DC=com",
                                    ldap.SCOPE_SUBTREE,
                                    "(&(objectClass=user)(sAMAccountName=%(user)s))")

AUTH_LDAP_USER_ATTR_MAP = {
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail"
}
</code>```

But, my credential is transmitting in a plain text.

From Fiddler:

Password stored in DB:

```<code>!Qoc6uEP5h0lOXIeqmSov1HWOL8eY4fmlpJ1Z3q
</code>```

How to apply hashing SHA256?

Note: Site was deployed on Apache2.4, Windows server 2008 r2.

答:
If you need hash you password try this:</p>

```<code>import hashlib
HashedPassword =hashlib.sha1('PASSWORD'.encode('UTF-8'))
</code>```

Body:
I'm using LDAP authentication in Django, as shown below and also using password hashers.

from django_auth_ldap.config import PosixGroupType, LDAPSearch
import ldap

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

# We use a dedicated user to bind to the LDAP server and execute the server.
AUTH_LDAP_SERVER_URI = "ldap://xx.xx.xx.xx:389"
AUTH_LDAP_BIND_DN = "xxxxx@xxxx.com"
AUTH_LDAP_BIND_PASSWORD = "xxxxx"
AUTH_LDAP_CONNECTION_OPTIONS = {
    ldap.OPT_DEBUG_LEVEL: 1,
    ldap.OPT_REFERRALS: 0,
}

# sAMAccountName is mostly used for Micrsoft Active Directory
# objectCategory    CN=Person,CN=Schema,CN=Configuration,DC=corp,DC=xxxx,DC=com
# (cn=%(user)s)
AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=corp,DC=xxxxx,DC=com",
                                    ldap.SCOPE_SUBTREE,
                                    "(&(objectClass=user)(sAMAccountName=%(user)s))")

AUTH_LDAP_USER_ATTR_MAP = {
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail"
}

But, my credential is transmitting in a plain text.

From Fiddler:

Password stored in DB:

!Qoc6uEP5h0lOXIeqmSov1HWOL8eY4fmlpJ1Z3q

How to apply hashing SHA256?

Note: Site was deployed on Apache2.4, Windows server 2008 r2.

Body:
If you need hash you password try this:

import hashlib
HashedPassword =hashlib.sha1('PASSWORD'.encode('UTF-8'))


问:
How to set a class Name as a method's parameter?
I would like to send a class name as a parameter of method. I would like to use(execute) it like that.

```<code>orderDao.getTheMostFrequentType(EmployeeOrder.class);
</code>```

I have this code

```<code>@Override
public String getTheMostFrequentType(Class<T> orderClass){
    String tableName = orderClass.getAnnotation(Table.class).name();
    String sqlQuery = "SELECT STATS_MODE(signed_by_id) FROM " + tableName;
    String result = (String)getSessionFactory().getCurrentSession().createSQLQuery(sqlQuery).uniqueResult();
    return result;
}
</code>```

But it executing attempts gives me:

```<code>getTheMostFrequentType("org.apache.poi.ss.formula.functions.T") method cannot be applied in "java.lang.entities.EmployeeOrder"
</code>```

May be there is another classes should i import instead of apache.poi. But which one? What i do wrong?

答:
As suggested in the comments, the problem was caused by not declaring a type parameter T but importing an actual type T.

The problem was solved by replacing Class<T> with Class<?>.

Body:
I would like to send a class name as a parameter of method. I would like to use(execute) it like that.

orderDao.getTheMostFrequentType(EmployeeOrder.class);

I have this code

@Override
public String getTheMostFrequentType(Class<T> orderClass){
    String tableName = orderClass.getAnnotation(Table.class).name();
    String sqlQuery = "SELECT STATS_MODE(signed_by_id) FROM " + tableName;
    String result = (String)getSessionFactory().getCurrentSession().createSQLQuery(sqlQuery).uniqueResult();
    return result;
}

But it executing attempts gives me:

getTheMostFrequentType("org.apache.poi.ss.formula.functions.T") method cannot be applied in "java.lang.entities.EmployeeOrder"

May be there is another classes should i import instead of apache.poi. But which one? What i do wrong?


问:
404 Not Found, but route exist in Laravel 5.4
I'm using PhpStorm. I can run and open the index.php, but when I want to press submit button (post sign in), its display 404 not found.

Web server Apache 2.4 running on Windows 10.

This is my home

This is my route

答:
Update 2020

There are many case happened above, I've once more case I met a long time but I still forget and sometimes I dont know why. This is some url patterns is the same, example abc.com/c/{get_an_id} and abc.com/c/get_text. You can change order but only first can run, 404 for the second url.


问:
Fuzzy match in a column in a dataframe in python
I have a column that has strings. I want to do a fuzzy match and mark those which have an 80% match in a column next to it. I can do it with the following code on a smaller dataset but my original dataset is too big for this to work efficiently. Is there a better way to do this? This is what I have done.</p>

```<code>import pandas as pd

l = [[1,'a','b','c','help pls'],[2,'a','c','c','yooo'],[3,'a','c','c','you will not pass'],[4,'a','b','b','You shall not pass'],[5,'a','c','c','You shall not pass!']]
df = pd.DataFrame(l,columns = ['Serial No','one','two','three','four'])

df['yes/no 2'] = ""

for i in range(0, df.shape[0]):
    for j in range(0, df.shape[0]):
        if (i != j):
            if (fuzz.token_sort_ratio(df.iloc[i,df.shape[1]-2],df.iloc[j,df.shape[1]-2]) > 80):
                df.iloc[i,df.shape[1]-1] = "yes"
</code>```

答:
```<code>import pandas as pd
from fuzzywuzzy import fuzz

l = [[1,'a','b','c','help pls'],[2,'a','c','c','yooo'],[3,'a','c','c','you will not pass'],[4,'a','b','b','You shall not pass'],[5,'a','c','c','You shall not pass!']]
df = pd.DataFrame(l,columns = ['Serial No','one','two','three','four'])

def match(row):
    thresh = 80
    return fuzz.token_sort_ratio(row["two"],row["three"])>thresh

df["Yes/No"] = df.apply(match,axis=1)
print(df)

   Serial No one two three                 four  Yes/No
0          1   a   b     c             help pls   False
1          2   a   c     c                 yooo    True
2          3   a   c     c    you will not pass    True
3          4   a   b     b   You shall not pass    True
4          5   a   c     c  You shall not pass!    True
</code>```

Body:
I have a column that has strings. I want to do a fuzzy match and mark those which have an 80% match in a column next to it. I can do it with the following code on a smaller dataset but my original dataset is too big for this to work efficiently. Is there a better way to do this? This is what I have done.

import pandas as pd

l = [[1,'a','b','c','help pls'],[2,'a','c','c','yooo'],[3,'a','c','c','you will not pass'],[4,'a','b','b','You shall not pass'],[5,'a','c','c','You shall not pass!']]
df = pd.DataFrame(l,columns = ['Serial No','one','two','three','four'])

df['yes/no 2'] = ""

for i in range(0, df.shape[0]):
    for j in range(0, df.shape[0]):
        if (i != j):
            if (fuzz.token_sort_ratio(df.iloc[i,df.shape[1]-2],df.iloc[j,df.shape[1]-2]) > 80):
                df.iloc[i,df.shape[1]-1] = "yes"


问:
How can you get an Android user's email address?
I have android.permission.READ_OWNER_DATA but I can't find any reliable code that would explain how can I read email address of device's owner. How can I do this?

答:
please add this permission in your manifest file.

```<code><uses-permission android:name="android.permission.GET_ACCOUNTS" />
</code>```

Add this function in your MainActivity.java

    public void getAccounts() {
        StringBuilder emailAccounts = new StringBuilder();

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.GET_ACCOUNTS)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.GET_ACCOUNTS}, 1);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.GET_ACCOUNTS}, 1);
            }
        }
        else {
            List<String> accountList = new ArrayList<String>();
            Pattern gmailPattern = Patterns.EMAIL_ADDRESS;
            Account[] accounts = AccountManager.get(this).getAccounts();
            for (Account account : accounts) {
                if (gmailPattern.matcher(account.name).matches()) {
                    emailAccounts.append(flag + ". " + "" + account.name + "
" +
                            "---------" + "---------
"); ;
                }
            }
            deviceDetails.setText(Html.fromHtml(emailAccounts+""));
        }
    }```

now call this function in your onCreate() method like this.

getAccounts();

Body:
please add this permission in your manifest file.

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

Add this function in your MainActivity.java

    public void getAccounts() {
        StringBuilder emailAccounts = new StringBuilder();

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.GET_ACCOUNTS)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.GET_ACCOUNTS}, 1);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.GET_ACCOUNTS}, 1);
            }
        }
        else {
            List<String> accountList = new ArrayList<String>();
            Pattern gmailPattern = Patterns.EMAIL_ADDRESS;
            Account[] accounts = AccountManager.get(this).getAccounts();
            for (Account account : accounts) {
                if (gmailPattern.matcher(account.name).matches()) {
                    emailAccounts.append(flag + ". " + "<b>" + account.name + "<br>" +
                            "---------" + "---------<br>"); ;
                }
            }
            deviceDetails.setText(Html.fromHtml(emailAccounts+""));
        }
    }

now call this function in your onCreate() method like this.

getAccounts();


问:
Arduino C++ Declare array of objects with parameters in constructor
I only want to declare an array of objects of class control with size of 5. The contents of the specific objects will be filled afterwards.

```<code>class control {
  public:
    control(char* controlName) {
    name = controlName;
  }

  private:
  char* name;
};

void setup() {
  control humidityControl("humidityControl");
  // Problem: Declare an array controlArray with the size of 5 and the name "controlArray"
  control controlArray[5]("controlArray"); // Error: no matching function for call to 'control::control()'
  control controlArray("controlArray")[5]; // Error: expected ',' or ';' before '[' token
}

void loop() {

}
</code>```

I'm using C++ on my Arduino. I'd appreciate every tipp how to fix this. Thanks!

答:
Your problem is that you're mixing the declaration of an array (the square brackets) with a call to the constructor. This SO answer clarifies it: https://stackoverflow.com/a/1598409/2881667.

What you want to do is this:

```<code>void setup() {
  control controlArray[5] = {"controlArray", "controlArray", "controlArray", "controlArray", "controlArray"};
}
</code>```

Notice how you have to include the argument to the constructor 5 times. To avoid that, you have two options:

Use a default constructor:

```<code>control(char* controlName = "controlArray");
</code>```

Might work for you, but only if you plan on initializing all arrays with the same value.

If using gcc, you can use its extension to initialize it like this:

```<code>control controlArray[5] = {[0 ... 4] = "controlArray"};
</code>```

But this will only work with gcc, so not so good for portability.

Also, unrelated to your question - I think you probably meant to copy the string, and not store the pointer in your class, so you should use something like strncpy in the constructor, instead of just assigning to name, and you'll have to preallocate storage for name in that case (either declare it as a char array, like char name[255];, allocate space for it in the constructor, or use std::string to make it all easier).

Body:
I only want to declare an array of objects of class control with size of 5. The contents of the specific objects will be filled afterwards.

class control {
  public:
    control(char* controlName) {
    name = controlName;
  }

  private:
  char* name;
};

void setup() {
  control humidityControl("humidityControl");
  // Problem: Declare an array controlArray with the size of 5 and the name "controlArray"
  control controlArray[5]("controlArray"); // Error: no matching function for call to 'control::control()'
  control controlArray("controlArray")[5]; // Error: expected ',' or ';' before '[' token
}

void loop() {

}

I'm using C++ on my Arduino. I'd appreciate every tipp how to fix this. Thanks!

Body:
Your problem is that you're mixing the declaration of an array (the square brackets) with a call to the constructor. This SO answer clarifies it: https://stackoverflow.com/a/1598409/2881667.

What you want to do is this:

void setup() {
  control controlArray[5] = {"controlArray", "controlArray", "controlArray", "controlArray", "controlArray"};
}

Notice how you have to include the argument to the constructor 5 times. To avoid that, you have two options:

Use a default constructor:

control(char* controlName = "controlArray");

Might work for you, but only if you plan on initializing all arrays with the same value.

If using gcc, you can use its extension to initialize it like this:

control controlArray[5] = {[0 ... 4] = "controlArray"};

But this will only work with gcc, so not so good for portability.

Also, unrelated to your question - I think you probably meant to copy the string, and not store the pointer in your class, so you should use something like strncpy in the constructor, instead of just assigning to name, and you'll have to preallocate storage for name in that case (either declare it as a char array, like char name[255];, allocate space for it in the constructor, or use std::string to make it all easier).


问:
Web scraping: update data like in Chrome?
All the articles about web scraping in Python I came across quoted BeautifulSoup and Selenium as the main tools to use to retrieve HTML and JavaScript content from a webpage.

However, I have not found a way to automatically update the data received from this same webpage without the need to send it a new request.

Is it impossible to do in Python what you would do with Google Chrome, that is, simply opening a webpage and looking at it being automatically updated by the host itself?

答: Yes, it is possible. For example, you can download elements of the DOM tree in a loop if the content is dynamically modified using JavaScript. You can also call your own JavaScript to perform a specific action. Alternatively, you can even write and upload your own browser plugin. In general, in selenium you can control the browser to a large extent, just like a normal user, without the need to refresh the page again.</p>


问:
Disable designer in Visual Studio?
I'm using Visual C# Express to write Windows Form applications, and call me old school, but I don't like the designer. It is a nuisance and pollutes my project with lots of unwanted files, as well as unwanted monkey-generated source code.

Please tell me there's a way to turn it off completely.

答:
Add a [System.ComponentModel.DesignerCategory("")] attribute before a UI class to avoid designer activation on double-click.

Note that including System.ComponentModel at the top of the file and then just adding the attribute as [DesignerCategory("")] will not work (at least not in Visual Studio 2010/2013). You must use the full, namespace-qualified attribute type name.

OwnerDisplayName: I. J. Kennedy

Title: Disable designer in Visual Studio?

OwnerDisplayName: Andrew


问:
htaccess file with ubuntu and WordPress
I set the following "htaccess" file code on WordPress folder

```<code># BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPresssss
</code>```

but when typing some URL the 404 pages are not showing properly and I don't get the custom 404 error page. example
https://healthguruwealth.com/fgdfdgf

答:
By default, WordPress doesn't create custom 404 pages. You can create a new 404 templates. Please follow the instruction as per the link below:
https://codex.wordpress.org/Creating_an_Error_404_Page

Or, you can create through plugins like ithemes security

Title: htaccess file with ubuntu and WordPress

Body:
I set the following "htaccess" file code on WordPress folder

# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPresssss

but when typing some URL the 404 pages are not showing properly and I don't get the custom 404 error page. example
https://healthguruwealth.com/fgdfdgf


问:
How do I save an html form post to two databases? Rabbitmq vs Redis pub/sub?
I have a Flask microservice that needs to save a form post to both AWS DynamoDB (thru boto3) and to Elastic Search DB (running on EC2). I first considered writing a Python AsyncIO server to implement a broker/Observer pattern but it looked like re-inventing what Rabbitmq/Redis PubSub already does. However, I couldn't find straight forward documentation (both doc sites) and therefore, I am looking for an example of this common pattern. Any pointers would be helpful and I will appreciate your help.

Thanks,

答: Looks like you are using AWS already, so why not use SNS. You can create a form_post_topic with two subscribers (DynamoDB and ElasticSearch) and you send messages to that topic.


问:
Can't add .so file to Android Studio 3.5.3 using jniLibs
I'm trying to add a .so file to a new Android project. I'm using Android Studio 3.5.3. I've done what was recommended here and here ; so I created folders (jniLibs/arm64-v8a, etc) in src/main and added this to app/build.gradle:

```<code>sourceSets {
    main {
        jniLibs.srcDirs = ['src/main/jniLibs']
    }
}
</code>```

I placed the libhl.so file in /app/src/main/jniLibs/arm64-v8a (yes, 64-bit should be ok). The project will compile just fine, but on execution it will show the following error in logcat:

```<code>02-17 10:25:31.719 3691-3691/com.example.bmdtest03 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.bmdtest03, PID: 3691
    java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.example.bmdtest03-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.bmdtest03-2/lib/x86_64, /vendor/lib64, /system/lib64]]] couldn't find "libhl.so"
        at java.lang.Runtime.loadLibrary(Runtime.java:366)
        at java.lang.System.loadLibrary(System.java:989)
        at com.example.bmdtest03.MainActivity.<clinit>(MainActivity.java:14)
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at java.lang.Class.newInstance(Class.java:1572)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
</code>```

Conclusion: the file is there, the source is updated in build.gradle, what am I missing?

答:
You can manually  generate  the .so file with NDK . Then you can add the lib.so file in your jni folder.

Add the NDK path to your local.properties.

Refer this page :  https://developer.android.com/studio/projects/gradle-external-native-builds

If its not works. You can create javah then you can access it.
Link  to make javah :  https://developer.android.com/training/articles/perf-jni

Body:
I'm trying to add a .so file to a new Android project. I'm using Android Studio 3.5.3. I've done what was recommended here and here ; so I created folders (jniLibs/arm64-v8a, etc) in src/main and added this to app/build.gradle:

sourceSets {
    main {
        jniLibs.srcDirs = ['src/main/jniLibs']
    }
}

I placed the libhl.so file in /app/src/main/jniLibs/arm64-v8a (yes, 64-bit should be ok). The project will compile just fine, but on execution it will show the following error in logcat:

02-17 10:25:31.719 3691-3691/com.example.bmdtest03 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.bmdtest03, PID: 3691
    java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.example.bmdtest03-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.bmdtest03-2/lib/x86_64, /vendor/lib64, /system/lib64]]] couldn't find "libhl.so"
        at java.lang.Runtime.loadLibrary(Runtime.java:366)
        at java.lang.System.loadLibrary(System.java:989)
        at com.example.bmdtest03.MainActivity.<clinit>(MainActivity.java:14)
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at java.lang.Class.newInstance(Class.java:1572)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Conclusion: the file is there, the source is updated in build.gradle, what am I missing?


问:
laravel show multiple data in datatables
I work with laravel spatie permission package and need to show user role for each user in datatables lists. now I  add datatables addColumn method:

```<code>$items = Admin::orderBy('id','DESC');

return DataTables::of($items)
    ->addColumn('role',function(Admin $admin){

        foreach($admin->getRoleNames() as $v){
            return $v;
        }

    })
    ->toJson();
</code>```

this code work and show role name for each user but If user have a two role name(multiple roles) My code not work and show only first role name. ie: for user test I have two roles name: moderator and editor But i see only moderator.

How to can i show multiple roles name for each user in datatables list?!

答:
```<code>public function roles()
{
    return $this->hasMany('App\Role');
}
</code>```

```<code>public function user()
{
    return $this->belongsTo('App\User');
}
</code>```

I think that you should add these methods to your user Model and the second one to your role Model

Body:
I work with laravel spatie permission package and need to show user role for each user in datatables lists. now I  add datatables addColumn method:

$items = Admin::orderBy('id','DESC');

return DataTables::of($items)
    ->addColumn('role',function(Admin $admin){

        foreach($admin->getRoleNames() as $v){
            return $v;
        }

    })
    ->toJson();

this code work and show role name for each user but If user have a two role name(multiple roles) My code not work and show only first role name. ie: for user test I have two roles name: moderator and editor But i see only moderator.

How to can i show multiple roles name for each user in datatables list?!

Body:
public function roles()
{
    return $this->hasMany('App\Role');
}

public function user()
{
    return $this->belongsTo('App\User');
}

I think that you should add these methods to your user Model and the second one to your role Model


问:
How country targeting works in Google Play Console?
I've read through Google Play Console support: https://support.google.com/googleplay/android-developer/answer/7550024?hl=en# and I'm still not sure if I can do the following:

I have a 1.0 version in Production released to all countries

I have a 2.0 version in Beta released to all countries

I want to release 2.0 to production but to all countries excepting USA. However, I want to keep USA users to be able to download 1.0

I'm not sure about the 1.0 Production release to be available in the USA.

Thanks

答: What you're looking for is a staged rollout: https://support.google.com/googleplay/android-developer/answer/6346149 (see section "Release a staged roll-out to specific countries")</p>