问:
Python - "KeyError : System.Object" - Pyadomd - Querying a SSAS Data Source
Working on a project where I am trying to query a SSAS data source we have at work through Python. The connection is presently within Excel files, but I am trying to reverse engineer the process with Python to automate part of the analysis I do on a day to day... I use the pyadomd library to connect to the data source, here`s my code:

```<code>clr.AddReference(r"C:\Program Files (x86)\Microsoft  Office\root\vfs\ProgramFilesX86\Microsoft.NET\ADOMD.NET\130\Microsoft.AnalysisServices.AdomdClient.dll")
clr.AddReference('Microsoft.AnalysisServices.AdomdClient')
from Microsoft.AnalysisServices.AdomdClient import AdomdConnection , AdomdDataAdapter
from sys import path
path.append('C:\Program Files (x86)\Microsoft Office\root\vfs\ProgramFilesX86\Microsoft.NET\ADOMD.NET\130\Microsoft.AnalysisServices.AdomdClient.dll')
import pyadomd
from pyadomd import Pyadomd
from pyadomd._type_code import adomd_type_map, convert

constr= "connection string"

with Pyadomd(constr) as conn:
    with conn.cursor().execute(query) as cur:
        print(cur.fetchall())
</code>```

Which works (in part), seemingly I am able to connect to the SSAS data source. Say I do conn = Pyadomd(constr), it returns no error (no more as it did before). The issue is when I try to execute the query with the cursor it returns an error saying:

```<code>  File "C:\Users\User\Anaconda3\lib\site-packages\pyadomd\pyadomd.py", line 71, in execute
    adomd_type_map[self._reader.GetFieldType(i).ToString()].type_name

KeyError: 'System.Object'
</code>```

By doing a bit of research, I found that KeyError meant that the code was trying to access a key within a dictionary in which that key isn't present. By digging through my variables and going through the code, I realized that the line:

```<code> from pyadomd._type_code import adomd_type_map
</code>```

Created this dictionary of keys:values:
See dictionary here

Containing these keys: System.Boolean, System.DateTime, System.Decimal, System.Double, System.Int64, System.String. I figured that the "KeyError: System.Object" was referring to that dictionary. My issue is how can I import this System.Object key to that dictionary? From which library/module/IronPython Clr reference can I get it from?

What I tried:

```<code>clr.AddReference("System.Object")
</code>```

Gave me error message saying "Unable to find assembly 'System.Object'. at Python.Runtime.CLRModule.AddReference(String name)"

I also tried:

```<code>from System import Object #no error but didn't work
from System import System.Object #error saying invalid syntax
</code>```

I think it has to do with some clr.AddReference IronPython thing that I am missing, but I've been looking everywhere and can't find it.

Thanks!

答:
Glad that the newer version solved the problem.

A few comments to the code snippet above. It can be done a bit more concise
Pyadomd will import the necessary classes from the AdomdClient, which means that the following lines can be left out.

```<code>clr.AddReference(r"C:\Program Files (x86)\MicrosoftOffice\root\vfs\ProgramFilesX86\Microsoft.NET\ADOMD.NET\130\Microsoft.AnalysisServices.AdomdClient.dll")
clr.AddReference('Microsoft.AnalysisServices.AdomdClient')
from Microsoft.AnalysisServices.AdomdClient import AdomdConnection , AdomdDataAdapter
</code>```

Your code will then look like this:

```<code>import pandas as pd
from sys import path
path.append(r'C:\Program Files (x86)\MicrosoftOffice\root\vfs\ProgramFilesX86\Microsoft.NET\ADOMD.NET\130')

from pyadomd import Pyadomd

constr= "constring"
query = "query"

with Pyadomd(constr) as con:
    with con.cursor().execute(query) as cur:
        DF = pd.DataFrame(cur.fetchone(), columns = [i.name for i in cur.description])
</code>```

The most important thing is to add the AdomdClient.dll to your path before importing the pyadomd package.

Furthermore, the package is mainly meant to be used with CPython version 3.6 and 3.7.

Body:
Working on a project where I am trying to query a SSAS data source we have at work through Python. The connection is presently within Excel files, but I am trying to reverse engineer the process with Python to automate part of the analysis I do on a day to day... I use the pyadomd library to connect to the data source, here`s my code:

clr.AddReference(r"C:\Program Files (x86)\Microsoft  Office\root\vfs\ProgramFilesX86\Microsoft.NET\ADOMD.NET\130\Microsoft.AnalysisServices.AdomdClient.dll")
clr.AddReference('Microsoft.AnalysisServices.AdomdClient')
from Microsoft.AnalysisServices.AdomdClient import AdomdConnection , AdomdDataAdapter
from sys import path
path.append('C:\Program Files (x86)\Microsoft Office\root\vfs\ProgramFilesX86\Microsoft.NET\ADOMD.NET\130\Microsoft.AnalysisServices.AdomdClient.dll')
import pyadomd
from pyadomd import Pyadomd
from pyadomd._type_code import adomd_type_map, convert

constr= "connection string"

with Pyadomd(constr) as conn:
    with conn.cursor().execute(query) as cur:
        print(cur.fetchall())

Which works (in part), seemingly I am able to connect to the SSAS data source. Say I do conn = Pyadomd(constr), it returns no error (no more as it did before). The issue is when I try to execute the query with the cursor it returns an error saying:

  File "C:\Users\User\Anaconda3\lib\site-packages\pyadomd\pyadomd.py", line 71, in execute
    adomd_type_map[self._reader.GetFieldType(i).ToString()].type_name

KeyError: 'System.Object'

By doing a bit of research, I found that KeyError meant that the code was trying to access a key within a dictionary in which that key isn't present. By digging through my variables and going through the code, I realized that the line:

 from pyadomd._type_code import adomd_type_map

Created this dictionary of keys:values:
See dictionary here

Containing these keys: System.Boolean, System.DateTime, System.Decimal, System.Double, System.Int64, System.String. I figured that the "KeyError: System.Object" was referring to that dictionary. My issue is how can I import this System.Object key to that dictionary? From which library/module/IronPython Clr reference can I get it from?

What I tried:

clr.AddReference("System.Object")

Gave me error message saying "Unable to find assembly 'System.Object'. at Python.Runtime.CLRModule.AddReference(String name)"

I also tried:

from System import Object #no error but didn't work
from System import System.Object #error saying invalid syntax

I think it has to do with some clr.AddReference IronPython thing that I am missing, but I've been looking everywhere and can't find it.

Thanks!

Body:
Glad that the newer version solved the problem.

A few comments to the code snippet above. It can be done a bit more concise
Pyadomd will import the necessary classes from the AdomdClient, which means that the following lines can be left out.

clr.AddReference(r"C:\Program Files (x86)\MicrosoftOffice\root\vfs\ProgramFilesX86\Microsoft.NET\ADOMD.NET\130\Microsoft.AnalysisServices.AdomdClient.dll")
clr.AddReference('Microsoft.AnalysisServices.AdomdClient')
from Microsoft.AnalysisServices.AdomdClient import AdomdConnection , AdomdDataAdapter

Your code will then look like this:

import pandas as pd
from sys import path
path.append(r'C:\Program Files (x86)\MicrosoftOffice\root\vfs\ProgramFilesX86\Microsoft.NET\ADOMD.NET\130')

from pyadomd import Pyadomd

constr= "constring"
query = "query"

with Pyadomd(constr) as con:
    with con.cursor().execute(query) as cur:
        DF = pd.DataFrame(cur.fetchone(), columns = [i.name for i in cur.description])

The most important thing is to add the AdomdClient.dll to your path before importing the pyadomd package.

Furthermore, the package is mainly meant to be used with CPython version 3.6 and 3.7.


来源: stackexchange

问:
Reading individual numbers from text file in ncurses
I've got a text file filled with numbers with no spaces between them, with the same number of digits in each row (it's actually an ASCII image). I need to read each individual digit (0-9) into a two-dimensional array in ncurses that I will later print into a window in order to reproduce the ASCII image. "scanw" isn't working for me, but neither is getch(). How can I make this work?

Here's the relevant section of code:

```<code>int aboutArray[LINES][COLS];

FILE *myFile;
myFile = fopen("sample.txt", "r");
if (myFile == NULL) {
    wprintw(aboutWin, "Failure to open file");
    return(1);
}

//read file into array
for (i = 0; i < LINES; i++) {
    for (j = 0; j < COLS; j++) {
        scanw(myFile, "%1d", &aboutArray[i][j]);
    }
}
fclose(myFile);

for (i = 0; i < LINES; i++) {
    for (j = 0; j < COLS; j++) {
        wprintw(aboutWin, 0, 0, "%1d", aboutArray[i][j]);
    }
}
</code>```

答:
scanw doesn't read from a FILE; it reads from a WINDOW.

Use fscanf.

ContentLicense: CC BY-SA 4.0

Body:
I've got a text file filled with numbers with no spaces between them, with the same number of digits in each row (it's actually an ASCII image). I need to read each individual digit (0-9) into a two-dimensional array in ncurses that I will later print into a window in order to reproduce the ASCII image. "scanw" isn't working for me, but neither is getch(). How can I make this work?

Here's the relevant section of code:

int aboutArray[LINES][COLS];

FILE *myFile;
myFile = fopen("sample.txt", "r");
if (myFile == NULL) {
    wprintw(aboutWin, "Failure to open file");
    return(1);
}

//read file into array
for (i = 0; i < LINES; i++) {
    for (j = 0; j < COLS; j++) {
        scanw(myFile, "%1d", &aboutArray[i][j]);
    }
}
fclose(myFile);

for (i = 0; i < LINES; i++) {
    for (j = 0; j < COLS; j++) {
        wprintw(aboutWin, 0, 0, "%1d", aboutArray[i][j]);
    }
}


问:
How to correctly download files using ftplib so line breaks are added for windows
I have been using a very simple batch file to download millions of files from a UNIX ftp server for years

```<code>login
passwd
ascii
prompt n
cd to the right directory
get some_file
get another_file
cd to the next directory
repeat the pattern
</code>```

The nice thing about this was that it was simple and all the files arrived with Window's line breaks so the files were ready to use with my existing programs.  Because of some changes in my router I had to write a Python script to pull the files - my first version of the script is very simple - but it works

```<code>for key in key_filings:
   for filing in key_filings[key]:
        remote_directory = '/foo/bar/' + key + '/' + filing['key_number']
        ftp.cwd(remote_directory)
        text_file = filing['txt']
        ftp.retrlines('RETR '+ text_file, open(save_dir + text_file,'w').writelines)
        hdr_file = filing['hdr']
        ftp.retrlines('RETR ' + hdr_file, open(save_dir + hdr_file,'w').writelines)
</code>```

However, the files do not have any apparent line breaks.  The files are stored in a unix system.  Before when I downloaded the files using the Windows CMD shell the line breaks were just there.  I have tried sending the ASCII command but as expected that did not have any effect.

It is critical that I be able to have access to the line breaks that existed originally as some of my code processing is line based.

答:
It is so weird why the CRLF is being stripped out. I was trying it on a IBM iSeries DB2. Ended up doing this to avoid I/O to the disk file for each line read. </p>

```<code>lines = []
ftp.retrlines('RETR ' + remote_file, lambda d:lines.append(d+'\n'))
f=open(yourfile,'w')
f.writelines(lines)
f.close()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been using a very simple batch file to download millions of files from a UNIX ftp server for years

login
passwd
ascii
prompt n
cd to the right directory
get some_file
get another_file
cd to the next directory
repeat the pattern

The nice thing about this was that it was simple and all the files arrived with Window's line breaks so the files were ready to use with my existing programs.  Because of some changes in my router I had to write a Python script to pull the files - my first version of the script is very simple - but it works

for key in key_filings:
   for filing in key_filings[key]:
        remote_directory = '/foo/bar/' + key + '/' + filing['key_number']
        ftp.cwd(remote_directory)
        text_file = filing['txt']
        ftp.retrlines('RETR '+ text_file, open(save_dir + text_file,'w').writelines)
        hdr_file = filing['hdr']
        ftp.retrlines('RETR ' + hdr_file, open(save_dir + hdr_file,'w').writelines)

However, the files do not have any apparent line breaks.  The files are stored in a unix system.  Before when I downloaded the files using the Windows CMD shell the line breaks were just there.  I have tried sending the ASCII command but as expected that did not have any effect.

It is critical that I be able to have access to the line breaks that existed originally as some of my code processing is line based.

Body:
It is so weird why the CRLF is being stripped out. I was trying it on a IBM iSeries DB2. Ended up doing this to avoid I/O to the disk file for each line read.

lines = []
ftp.retrlines('RETR ' + remote_file, lambda d:lines.append(d+'\n'))
f=open(yourfile,'w')
f.writelines(lines)
f.close()


问:
Creating a new column in a specific place in Pandas
I would like to create a new column in Python and place in a specific position. For instance, let "example" be the following dataframe:

```<code>import pandas as pd

example = pd.DataFrame({
            'name': ['alice','bob','charlie'],
            'age': [25,26,27],
            'job': ['manager','clerk','policeman'],
            'gender': ['female','male','male'],
            'nationality': ['french','german','american']
        })
</code>```

I would like to create a new column to contain the values of the column "age":

```<code>example['age_times_two']= example['age'] *2
</code>```

Yet, this code creates a column at the end of the dataframe. I would like to place it as the third column, or, in other words, the column right next to the column "age". How could this be done:

a) By setting an absolute place to the new column (e.g. third position)?

b) By setting a relative place for the new column (e.g. right to the column "age")?

答:
You can use df.insert here.

```<code>example.insert(2,'age_times_two',example['age']*2)
example
      name  age  age_times_two        job  gender nationality
0    alice   25             50    manager  female      french
1      bob   26             52      clerk    male      german
2  charlie   27             54  policeman    male    american
</code>```

Body:
I would like to create a new column in Python and place in a specific position. For instance, let "example" be the following dataframe:

import pandas as pd

example = pd.DataFrame({
            'name': ['alice','bob','charlie'],
            'age': [25,26,27],
            'job': ['manager','clerk','policeman'],
            'gender': ['female','male','male'],
            'nationality': ['french','german','american']
        })

I would like to create a new column to contain the values of the column "age":

example['age_times_two']= example['age'] *2

Yet, this code creates a column at the end of the dataframe. I would like to place it as the third column, or, in other words, the column right next to the column "age". How could this be done:

a) By setting an absolute place to the new column (e.g. third position)?

b) By setting a relative place for the new column (e.g. right to the column "age")?

Body:
You can use df.insert here.

example.insert(2,'age_times_two',example['age']*2)
example
      name  age  age_times_two        job  gender nationality
0    alice   25             50    manager  female      french
1      bob   26             52      clerk    male      german
2  charlie   27             54  policeman    male    american


问:
HTML5 Canvas drawing is layering a new path over the existing path at each new point. Why?
This is hard to explain so I created a JS Fiddle to show what is going on: http://jsfiddle.net/dGdxS/ - (Webkit only) Just mouse over the canvas to draw - you may need to click around

I noticed the performance of the canvas was not what I expected, and when I set the line alpha I think I see why.

It looks like every new point I add to the drawing it is layering a completely new line over the previous line. The stroke alpha is set to 1%, and when you draw the older areas of the stroke begin to darken as the layers build up.

I assume I am doing something wrong. Do I need to clear the canvas before drawing to it at each new point?

答:
Because you never call ctx.closePath();, so it will redraw the entire path from the beginning each time.

So you really want something similar to this:

http://jsfiddle.net/dGdxS/7/


问:
High availability in Erlang?
What are typical ways to achieve high availability in Erlang?

Let's assume some gen_server registered as a ?MODULE locally. Given N indepent and interconnected by defuaul Erlang nodes, each running an instance of that gen_server, how to 1) ensure that no request is lost due to failure of some participating node (as long as at least one of them is online), 2) loadbalance them in order to avoid overload of some nodes while others hang waiting for new messages? As far as I know, there exists no built-in loadbalancer: no pg2 nor newer pg is sufficient (still might be a good basement for further work in this direction).

I bet that's a common problem and well-established battle-tested "Erlangish" solutions do exist. What are them?

答:
I think that for 1) to have only-once guarantee you need some kind of distributed transaction algorithm because connections might fail and you don't know the state of the request in the remote node: Is the remote node dead? is it alive and just disconnected because a network failure? how far into the request processing did it go before the failure?

You should check mnesia, it's deeply integrated with Erlang.

If you relax the requirements for 1) (for instance if the requests are idempotent. you only care for at-least-once or the failures are not common), it may suffice with monitoring the remote gen_server and just replaying the request if the connection to the remote server is lost for whatever reason.

For 2 we use haproxy or nginx webserver in a least-conn fashion in front of the nodes, although I believe that you mean 'inside' Erlang. In that case I'd do the following to have a local ETS with the load info:

Have a MODULE sidekick that broadcasts the local MODULE's mailbox size (or other metric) periodically to other sidekicks in the cluster.

If the sidekick receives this broadcast, it writes the origin node and size into an ETS or just saves them internally and stores the least-busy for the time being in an ETS

If the sidekick notices that a remote node disconnects, it updates the ETS

Regarding OTP23's pg, don't discard it so easily. By the doc Process Groups implement strong eventual consistency. you may have overloaded servers leave the process group temporarily and they will eventually stop receiving requests. You can have several servers by node with a low trigger to leave the group for a more uniform distribution.

Title: High availability in Erlang?


问:
Background misbehaving in mobile browsers
I'm making a modest portfolio and everything goes well but when I access the website from mobile browser (all of them) and scroll down the sections the backgrounds seems to be constantly resizing. This behaviour won't happen in desktop nor desktop browsers inspector. I tested it in mobile with google chrome, opera and firefox with the same result. I provide a screenshot showing the glitch:

I have a background placed in the body tag, and over it a class puts a translucid blue background. I think this might be it but I don't know for sure. Some code that might be relevant since the whole code is too long:

Background placed in body:

```<code>* {
    padding   : 0;
    margin    : 0;
    box-sizing: border-box;
}

html {
    font-size      : 10px;
    overflow-x     : hidden;
    scroll-behavior: smooth;
    font-size      : 10px;
}

body {
    background-image     : $background-img;
    background-size      : cover;
    background-position  : center;
    background-repeat    : no-repeat;
    background-attachment: fixed;
    min-height           : 100vh;
    height               : auto;
}
</code>```

Every section puts another layer over it:

```<code>    .section {
        width          : auto;
        height         : auto;
        min-height     : 100vh;
        display        : flex;
        justify-content: center;
        align-items    : center;
        color          : white;
        background-color: #17223bc9;
    }
</code>```

Here's the site: https://cromadev.com

Thanks in advance.

答:
Viewport units don't work well on mobile browsers since the address bar/overall GUI of many mobile browsers resize as you scroll down, hence changing the size of the window.

Percentage units are more widely supported, so mobile browsers might render them in a more reliable way. Based on the code you provided, you can try them out by adding the following styles to your CSS (remove the vh styles, too):

html {
  height: 100%
}

body {
  min-height: 100%;
}
```

You might have to experiment with switching height and min-height to get everything fully working for your specific use case.

You could also take a look at this GitHub project which aims to help fix some of these issues: https://github.com/rodneyrehm/viewport-units-buggyfill -- but I would recommend you try out the percentages first.

Body:
I'm making a modest portfolio and everything goes well but when I access the website from mobile browser (all of them) and scroll down the sections the backgrounds seems to be constantly resizing. This behaviour won't happen in desktop nor desktop browsers inspector. I tested it in mobile with google chrome, opera and firefox with the same result. I provide a screenshot showing the glitch:

I have a background placed in the body tag, and over it a class puts a translucid blue background. I think this might be it but I don't know for sure. Some code that might be relevant since the whole code is too long:

Background placed in body:

* {
    padding   : 0;
    margin    : 0;
    box-sizing: border-box;
}

html {
    font-size      : 10px;
    overflow-x     : hidden;
    scroll-behavior: smooth;
    font-size      : 10px;
}

body {
    background-image     : $background-img;
    background-size      : cover;
    background-position  : center;
    background-repeat    : no-repeat;
    background-attachment: fixed;
    min-height           : 100vh;
    height               : auto;
}

Every section puts another layer over it:

    .section {
        width          : auto;
        height         : auto;
        min-height     : 100vh;
        display        : flex;
        justify-content: center;
        align-items    : center;
        color          : white;
        background-color: #17223bc9;
    }

Here's the site: https://cromadev.com

Thanks in advance.

Body:
Viewport units don't work well on mobile browsers since the address bar/overall GUI of many mobile browsers resize as you scroll down, hence changing the size of the window.

Percentage units are more widely supported, so mobile browsers might render them in a more reliable way. Based on the code you provided, you can try them out by adding the following styles to your CSS (remove the vh styles, too):

html {
  height: 100%
}

body {
  min-height: 100%;
}

You might have to experiment with switching height and min-height to get everything fully working for your specific use case.

You could also take a look at this GitHub project which aims to help fix some of these issues: https://github.com/rodneyrehm/viewport-units-buggyfill -- but I would recommend you try out the percentages first.


问:
Dynamic Selection of Slicer for Character Values
So, I have a Power BI report where I have a slicer with values such as :

```<code>202005
202004
202003
202002
202001
Pacing
</code>```

Every month, the data gets added and the category is incremented by 1. i.e in June, I'll have 202006 as well.

I have a report where I want the data to be filtered by last 3 months and Pacing.

i.e in May, default selection should be 202004, 202003, 202002, Pacing

in June, default selection should be 202005,202004,202003, Pacing

In other words, I want default selection of: max month-1, max month -2, max month -3 and pacing.

Currently, I am manually making the selection and saving the report and then publishing it again. But to do so, I have to refresh data every time to get updated values of the month and it has increased my file size to a great extent because the data is imported in my report. I believe that my report can crash anytime if I continue this.

答:
While you can't yet directly set slicer defaults, there are some workarounds.

However, relative date filtering or Top N filtering on a slicer might help:

If you don't need all the old data, you can keep your file size from continuing to grow by filtering the dates in the query editor before they are loaded to the model.

Body:
So, I have a Power BI report where I have a slicer with values such as :

202005
202004
202003
202002
202001
Pacing

Every month, the data gets added and the category is incremented by 1. i.e in June, I'll have 202006 as well.

I have a report where I want the data to be filtered by last 3 months and Pacing.

i.e in May, default selection should be 202004, 202003, 202002, Pacing

in June, default selection should be 202005,202004,202003, Pacing

In other words, I want default selection of: max month-1, max month -2, max month -3 and pacing.

Currently, I am manually making the selection and saving the report and then publishing it again. But to do so, I have to refresh data every time to get updated values of the month and it has increased my file size to a great extent because the data is imported in my report. I believe that my report can crash anytime if I continue this.


问:
Why can't I override my interface methods?
Let's say I have an interface as follows.

```<code>interface CardHolder : IEnumerable<Card>
{
    /// <summary> ...
    void PutCard(Card card);

    /// <summary> ...
    void PutCards(Card[] card);

    /// Some more methods...
}
</code>```

I implement it as follows.

```<code>public class ArrayCardHolder : CardHolder
{
    private Card[] _cards;
    private int _size = 0;

    public ArrayCardHolder(int capacity)
    {
        _cards = new Card[capacity];
    }

    public void PutCard(Card card)
    {
        if (IsFull())
            throw new Exception("This CardHolder is full. Capacity: " + Capacity());

        _cards[_size++] = card;
    }

    public void PutCards(Card[] cards)
    {
        if (_size + cards.Length > _cards.Length)
            throw new Exception("Adding the Cards would exceed this CardHolder its capacity. Capacity: " + Capacity());

        for (int index = 0; index < cards.Length; index++)
            _cards[_size++] = cards[index];
    }
    public IEnumerator<Card> GetEnumerator()
    {
        for (int index = 0; index < _size; index++)
            yield return _cards[index];
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }

    ///More methods.

}
</code>```

Why can I not use the override keyword in my ArrayCardHolder
(e.g. public void override PutCard(Card card) { ///implementation } to indicate that the method implements (i.e. overrides) the interface? In that case, the project will refuse to build.

Why does it work however when overriding ToString()? And why doesn't it work when implementing CompareTo(T t) from IComparable<T>?

What should I use instead? I'm worried that the documentation from the interface will not apply to my implementing methods. Such is the case in Java when the @Override annotation is used.

答:
As mentioned abundantly, override applies to virtual and abstract method implementations, not interface method implementations.

The annoying thing about all of this is that there is no way to generate warnings when a method that used to implement an interface method becomes orphaned.

Interestingly, java tooling has an option to allow @override on interface methods, so that errors/warnings will be generated when an interface method becomes orphaned.

The question, from a language implementation point of view would be whether an override of a interfacement method would be virtual or not. I suppose "override virtual" would be an option. Or "override abstract".

https://github.com/dotnet/csharplang/issues/3510

So technically, the answer to WHY is not "because you can't", but something deeper and more sinister; namely: because the C# language spec is wrong. Just saying. :-P

Body:
Let's say I have an interface as follows.

interface CardHolder : IEnumerable<Card>
{
    ///  ...
    void PutCard(Card card);

    ///  ...
    void PutCards(Card[] card);

    /// Some more methods...
}

I implement it as follows.

public class ArrayCardHolder : CardHolder
{
    private Card[] _cards;
    private int _size = 0;

    public ArrayCardHolder(int capacity)
    {
        _cards = new Card[capacity];
    }

    public void PutCard(Card card)
    {
        if (IsFull())
            throw new Exception("This CardHolder is full. Capacity: " + Capacity());

        _cards[_size++] = card;
    }

    public void PutCards(Card[] cards)
    {
        if (_size + cards.Length > _cards.Length)
            throw new Exception("Adding the Cards would exceed this CardHolder its capacity. Capacity: " + Capacity());

        for (int index = 0; index < cards.Length; index++)
            _cards[_size++] = cards[index];
    }
    public IEnumerator<Card> GetEnumerator()
    {
        for (int index = 0; index < _size; index++)
            yield return _cards[index];
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }

    ///More methods.

}

Why can I not use the override keyword in my ArrayCardHolder
(e.g. public void override PutCard(Card card) { ///implementation } to indicate that the method implements (i.e. overrides) the interface? In that case, the project will refuse to build.

Why does it work however when overriding ToString()? And why doesn't it work when implementing CompareTo(T t) from IComparable<T>?

What should I use instead? I'm worried that the documentation from the interface will not apply to my implementing methods. Such is the case in Java when the @Override annotation is used.


答:
Assuming that you have the script on the same directory as your CSV files (and all the CSV files have the same format XXXX-MM-DD.csv where the dates are monotonically increasing) and that you had made the script executable with (chmod +x script.py) the following script.py should work:

```<code>#!/usr/bin/env python3

import os
import sys
import pandas as pd

filepath = "/path/to/csvfiles/" #[TODO] change to the path where the csv files are located.

try:
    first_file = sys.argv[1]
    second_file = sys.argv[2]
except:
    print("An error occurred. Enter two file names separated by a space in the format of YYYY-MM-D1 YYYY-MM-D2")
    sys.exit(1)

csv_files = [csv_file for csv_file in os.listdir(filepath) if csv_file.endswith('.csv')]
ordered_files = sorted(csv_files)

try:
    index_first_file = ordered_files.index(first_file)
    index_second_file = ordered_files.index(second_file)
except:
     print("One of the csv files was not found in the current directory.")
     sys.exit(1)

df_list = [pd.read_csv(ordered_files[i]) for i in range(index_first_file, index_second_file+1)]

print(df_list)

</code>```

In order to use it simply run e.g. ./script.py 2020-03-01.csv 2020-03-02.csv

Title: Only load files with date range from command line pandas dataframe

Body:
I have file names with the date, I would like to fetch range of files from directory and put them into pandas dataframe, DO NOT WANT TO LOAD ALL OF THE FILES

020-03-01.csv   2020-03-23.csv  2020-04-14.csv  2020-05-06.csv
2020-03-02.csv  2020-03-24.csv  2020-04-15.csv  2020-05-07.csv
2020-03-03.csv  2020-03-25.csv  2020-04-16.csv  2020-05-08.csv
2020-03-04.csv  2020-03-26.csv  2020-04-17.csv  2020-05-10.csv
2020-03-05.csv  2020-03-27.csv  2020-04-19.csv  2020-05-11.csv
2020-03-06.csv  2020-03-29.csv  2020-04-20.csv  2020-05-12.csv
2020-03-08.csv  2020-03-30.csv  2020-04-21.csv  2020-05-13.csv
2020-03-09.csv  2020-03-31.csv  2020-04-22.csv  2020-05-14.csv
2020-03-10.csv  2020-04-01.csv  2020-04-23.csv  2020-05-15.csv
2020-03-11.csv

I would like to fetch only file which are in range given as start date and end date and take the start date as sys.argv[1] and end date sys.argv[2]
i.e nameofthescript 2020-03-01 2020-03-20

Body:
Assuming that you have the script on the same directory as your CSV files (and all the CSV files have the same format XXXX-MM-DD.csv where the dates are monotonically increasing) and that you had made the script executable with (chmod +x script.py) the following script.py should work:

#!/usr/bin/env python3

import os
import sys
import pandas as pd

filepath = "/path/to/csvfiles/" #[TODO] change to the path where the csv files are located.

try:
    first_file = sys.argv[1]
    second_file = sys.argv[2]
except:
    print("An error occurred. Enter two file names separated by a space in the format of YYYY-MM-D1 YYYY-MM-D2")
    sys.exit(1)

csv_files = [csv_file for csv_file in os.listdir(filepath) if csv_file.endswith('.csv')]
ordered_files = sorted(csv_files)

try:
    index_first_file = ordered_files.index(first_file)
    index_second_file = ordered_files.index(second_file)
except:
     print("One of the csv files was not found in the current directory.")
     sys.exit(1)

df_list = [pd.read_csv(ordered_files[i]) for i in range(index_first_file, index_second_file+1)]

print(df_list)

In order to use it simply run e.g. ./script.py 2020-03-01.csv 2020-03-02.csv


问:
Check if there are higher values in 2 columns (C&D) on other sheet based on cell value in column B & autopopulate result
Link to Google Sheet Sample

In column E on sheet 'Calc', I want to check if there's a person in sheet 'Data' who has the same A value, but a higher value on B and C. Eventually I want to Return 'No' if not, return 'yes' if yes. If there's a person with the same A value who has a higher value on B but not on C (or vice versa) return 'maybe' with the name of the person(s). Autopopulate E with the returned value.

The values in columns B, C and D in 'Calc' are dynamic and will change based on other calculations. The B, C and D values in 'Data' are static. The length of both columns can differ.

Some examples:

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B71, C75. No-one else has A89 and higher values on both B or C.

Return 'Yes'.

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B60, C55. No-one else has A89 and higher values on both B or C.

Return 'No'.

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B71, C55. No-one else has A89 and higher values on both B or C.

Return 'Maybe: Person A'.

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B71, C55. Person B in sheet 'Data' has the values of A89, B55, C71. Person A has the highest value on B compared to the people in sheet 'Data' with A89 but a C lower than that of Name 1 in sheet 'Calc'. Person B has the highest value on C compared to the people in sheet 'Data' with A89 but a B lower than the of Name 1 in sheet 'Calc'.
Return 'Maybe: Person A, Person B'.

I've tried to make a start by just getting the highest values in sheet 'Calc' by combining =ARRAYFORMULA with MAX, but I get either a 'different number' array error or everything is just compared to B3.

Error:

```<code>=ARRAYFORMULA(IF(ISBLANK($A3:$A);;$B3&":"&MAX((Data!$B3:$B=$B3)*Data!$C3:$C)&":"&MAX((Data!$B3:$B=$B3)*Data!$D3:$D)))
</code>```

Only calculated with B3:

```<code>=ARRAYFORMULA(IF(ISBLANK($A3:$A);;$B3&":"&MAX((Data!$B3:$B=$B3)*Data!$C3:$C)&":"&MAX((Data!$B3:$B=$B3)*Data!$D3:$D)))
</code>```

Edit: I've removed the open-ended ranges which at least removed the error I got, but it still doesn't return the desired numbers (it returns either zero or the highest numbers belonging to the first entry, B3). I've updated the sheet accordingly.

```<code>=ARRAYFORMULA(IF(ISBLANK($A3:$A999);;$B$3:$B$999&":"&MAX((Data!$B3:$B999=$B$3:$B$999)*Data!$C3:$C999)&":"&MAX((Data!$B3:$B999=$B$3:$B$999)*Data!$D3:$D999)))
</code>```

答:
Your issue is that your two tabs are of different size AND you have open ranges.

Your Calc tab is 1002 rows, while Data is 2001 rows.

You have 2 alternatives

Solution 1

Add just one more row in your Data tab or delete one from your Calc tab.

Solution 2

Use closed ranges as in

```<code>=ARRAYFORMULA(IF(ISBLANK($A3:$A888);;$B3:$B888&":"&MAX((Data!$B3:$B888=$B3:$B888)*Data!$C3:$C888)&":"&MAX((Data!$B3:$B888=$B3:$B888)*Data!$D3:$D888)))
</code>```

In either case, make sure your ranges have the same amount of rows.

Body:
Link to Google Sheet Sample

In column E on sheet 'Calc', I want to check if there's a person in sheet 'Data' who has the same A value, but a higher value on B and C. Eventually I want to Return 'No' if not, return 'yes' if yes. If there's a person with the same A value who has a higher value on B but not on C (or vice versa) return 'maybe' with the name of the person(s). Autopopulate E with the returned value.

The values in columns B, C and D in 'Calc' are dynamic and will change based on other calculations. The B, C and D values in 'Data' are static. The length of both columns can differ.

Some examples:

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B71, C75. No-one else has A89 and higher values on both B or C.

Return 'Yes'.

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B60, C55. No-one else has A89 and higher values on both B or C.

Return 'No'.

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B71, C55. No-one else has A89 and higher values on both B or C.

Return 'Maybe: Person A'.

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B71, C55. Person B in sheet 'Data' has the values of A89, B55, C71. Person A has the highest value on B compared to the people in sheet 'Data' with A89 but a C lower than that of Name 1 in sheet 'Calc'. Person B has the highest value on C compared to the people in sheet 'Data' with A89 but a B lower than the of Name 1 in sheet 'Calc'.
Return 'Maybe: Person A, Person B'.

I've tried to make a start by just getting the highest values in sheet 'Calc' by combining =ARRAYFORMULA with MAX, but I get either a 'different number' array error or everything is just compared to B3.

Error:

=ARRAYFORMULA(IF(ISBLANK($A3:$A);;$B3&":"&MAX((Data!$B3:$B=$B3)*Data!$C3:$C)&":"&MAX((Data!$B3:$B=$B3)*Data!$D3:$D)))

Only calculated with B3:

=ARRAYFORMULA(IF(ISBLANK($A3:$A);;$B3&":"&MAX((Data!$B3:$B=$B3)*Data!$C3:$C)&":"&MAX((Data!$B3:$B=$B3)*Data!$D3:$D)))

Edit: I've removed the open-ended ranges which at least removed the error I got, but it still doesn't return the desired numbers (it returns either zero or the highest numbers belonging to the first entry, B3). I've updated the sheet accordingly.

=ARRAYFORMULA(IF(ISBLANK($A3:$A999);;$B$3:$B$999&":"&MAX((Data!$B3:$B999=$B$3:$B$999)*Data!$C3:$C999)&":"&MAX((Data!$B3:$B999=$B$3:$B$999)*Data!$D3:$D999)))

Body:
Your issue is that your two tabs are of different size AND you have open ranges.

Your Calc tab is 1002 rows, while Data is 2001 rows.

You have 2 alternatives

Solution 1

Add just one more row in your Data tab or delete one from your Calc tab.

Solution 2

Use closed ranges as in

=ARRAYFORMULA(IF(ISBLANK($A3:$A888);;$B3:$B888&":"&MAX((Data!$B3:$B888=$B3:$B888)*Data!$C3:$C888)&":"&MAX((Data!$B3:$B888=$B3:$B888)*Data!$D3:$D888)))

In either case, make sure your ranges have the same amount of rows.


问:
From date to tuple Python
I have like input: 12/12/2019
and I want this output: (12,12,2019)
I tried this code but it doesn't work because they consider "/" as a division :

```<code>date= 12/12/2019
date=str(date).split("/")
print(tuple(date))
</code>```

答:
Though your code should work. I also have one more easier code

```<code>print(tuple(map(int, "12/12/2019".split("/"))))
</code>```

the output is as desired

```<code>('12', '12', '2019')
</code>```

Title: From date to tuple Python

Body:
I have like input: 12/12/2019
and I want this output: (12,12,2019)
I tried this code but it doesn't work because they consider "/" as a division :

date= 12/12/2019
date=str(date).split("/")
print(tuple(date))

Body:
Though your code should work. I also have one more easier code

print(tuple(map(int, "12/12/2019".split("/"))))

the output is as desired

('12', '12', '2019')


问:
Why string str = new string("abc") doesn't pass compiler?
Given public String(char*) why we cannot use the following statement?

```<code>string str = new string("aaa");
</code>```

Error   1

The best overloaded method match for
  'string.String(char*)' has some
  invalid
  arguments C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  26  ConsoleApplication2

Error   2

Argument 1: cannot convert from
  'string' to
  'char*'   C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  37  ConsoleApplication2

答:
You are attempting to call a constructor with a string as a parameter.

The compiler is telling you there is no string constructor with a single string as a param.

Body:
Given public String(char*) why we cannot use the following statement?

string str = new string("aaa");

Error   1

The best overloaded method match for
  'string.String(char*)' has some
  invalid
  arguments C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  26  ConsoleApplication2

Error   2

Argument 1: cannot convert from
  'string' to
  'char*'   C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  37  ConsoleApplication2


问:
Table in bootstrap navigation bar
from where the extra 'green' portion came from?

This is my nav bar
The green portion

How can i get rid of this?

Note: When I put normal text here, I get it nicely formatted vertically center, but when using table it doesn't.

Here is my html structures.

```<code><li class="nav-item">
    <table class="table table-sm table-condensed table-borderless">
        <tbody class="user-logout">
        <tr>
            <td class="text-light">Farhad Hossain</td>
            <td rowspan="2">
                <a href="{{ url_for('dashboard') }}">
                    <img src="{{ url_for('static', filename='profile_pics/'+current_user.trainer.picture) }}"
                         width="56" height="56" class="rounded-circle" alt="">
                </a>
            </td>
        </tr>
        <tr>
            <td><a class="text-decoration-none text-warning" href="{{ url_for('logout') }}">Logout</a></td>
        </tr>
        </tbody>
    </table>
</li>
</code>```

Any hope?

答: I suppose the default styling for bootstrap tables contains plenty of margin underneath, that is visible here. You could try to override that by setting margin-bottom: 0 !important (there is a similar question out here addressing this), but generally, as a learning curve thing, I don't think you should be using a table for these purposes. A table is for showing data, as an actual table, not for aligning things, but well, we all have learnt HTML and CSS first by using tables and this works too, unless you need to shift the order of these things or make it responsive.

Title: Table in bootstrap navigation bar

Body:
from where the extra 'green' portion came from?

This is my nav bar
The green portion

How can i get rid of this?

Note: When I put normal text here, I get it nicely formatted vertically center, but when using table it doesn't.

Here is my html structures.

            Farhad Hossain

            Logout

Any hope?


问:
Does gradle.properties have access to environment variables
I looked around and could not find any way of accessing environment variables in my gradle.properties.

What I can do: In my build.gradle I can access environment variables like this System.getenv("MY_VAR"). I would like to do the same in my gradle.properties.

Example of what I want to do: In my gradle.properties replace build.foo=bar with build.foo=System.getenv("BAR")

So far all my attempts to access environment variables from gradle.properties have failed.

Any insight into the matter would be great, thanks!

答:
Not all environment variables are visible to gradle. If you can name them with the special prefix ORG_GRADLE_PROJECT_ these will be available. You can read about it here

ORG_GRADLE_PROJECT_foo can be accessed as foo within gradle.


问:
how to write dice rolling game project. this is my first project
did i write correct code

```<code>no1 = 1
no2 = 6
enter code here
dice = input("enter number: "):
no1 = int(input("enter number one: "))
no2 = int(input("enter number two: "))
    print("you have enter "+str(no1))
    print("you have enter "+str(no2))

if dice == "5":
    print("you want to roll again")
elif dice == "6":
    print("roll dice automatically")
</code>```

check that you have not incorrectly formatted all of your question as code

答:
help on this one
Alice, Bob and Carol have agreed to pool their Halloween candy and split it evenly among themselves. For the sake of their friendship, any candies left over will be smashed. For example, if they collectively bring home 91 candies, they'll take 30 each and smash 1.

Write an arithmetic expression below to calculate how many candies they must smash for a given haul.

Body:
did i write correct code

no1 = 1
no2 = 6
enter code here
dice = input("enter number: "):
no1 = int(input("enter number one: "))
no2 = int(input("enter number two: "))
    print("you have enter "+str(no1))
    print("you have enter "+str(no2))

if dice == "5":
    print("you want to roll again")
elif dice == "6":
    print("roll dice automatically")

check that you have not incorrectly formatted all of your question as code


问:
Remove specific section of string
Hi I have a file that contains several thousand file paths that I am looking to move to Wazhu. Problem is I need directories so what I have looks like
>/apples/oranges/test.ex< What I need is >/apples/oranges<
Not sure if Regex or just using str.replace() is better. As each line is different I would need to find the last / and remove it as well as everything up to <

Hopefully that makes sense.

答:
You don’t need regex to do this. You can simply use:
os.path.split

```<code>import os
head, tail = os.path.split("/apples/oranges/test.ex")
print(head)
Output: /apples/oranges
</code>```

I was stuck with the same issue, the above method solved it!

Title: Remove specific section of string

Body:
You don’t need regex to do this. You can simply use:
os.path.split

import os
head, tail = os.path.split("/apples/oranges/test.ex")
print(head)
Output: /apples/oranges

I was stuck with the same issue, the above method solved it!


问:
How to manage custom number formatting in power BI?
How can I do custom number formatting in a Power Bi visual?

I don't want to show all value as million. I want to put thousand for 1-day value, and million for 1-week value and year for 1-year value.

答:
Power BI charts follow the principles of good data visualisation. That includes a scale that is relevant to the data with labels that relate to the scale.

In the visualisation, the differences for the values less than 1M are not discernible. The label with the 0M supports that approach, although it doesn't look great. But that happens when you have a chart with very large AND very small values. Power BI only supports one display unit and you selected Millions.

You may want to consider using a different visual for the data. Not all visuals to be shown as charts. If you want to show the exact numbers, then a simple table might be a better approach. In a sorted list of numbers, the digits in a number act very much like a horizontal bar.

Or split the chart in two and show one chart for values above 1M and another for values below 1M.

Or use Thousands as display units instead of Millions.


问:
How to get a list data that are in global environment into a list
I am working on a list of .csv data which I have read in and keep the variables that i need for study. During this process, I have build multiple data set with name xxx_101(PY_101, vB_101_FG_101, etc.) which store in global environment. Now I want to put every new data set with ending _101 into a list. Is it a clever way to build that list other than type them in one by one? Once I read them in to a list, I would like to rename the each list with their original data name. Is there a easy way to do that? </p>

<p>I could do it one by one, but just feel there should be a better way to do. Thanks. </p>

答:
We can use mget with ls and specify the pattern with "_101" as the end ($) of the object name.  It would get the values of all those objects into a list

```<code>lst1 <- mget(ls(pattern = "_101$"))
</code>```

Body:
I am working on a list of .csv data which I have read in and keep the variables that i need for study. During this process, I have build multiple data set with name xxx_101(PY_101, vB_101_FG_101, etc.) which store in global environment. Now I want to put every new data set with ending _101 into a list. Is it a clever way to build that list other than type them in one by one? Once I read them in to a list, I would like to rename the each list with their original data name. Is there a easy way to do that?

I could do it one by one, but just feel there should be a better way to do. Thanks.

Body:
We can use mget with ls and specify the pattern with "_101" as the end ($) of the object name.  It would get the values of all those objects into a list

lst1 <- mget(ls(pattern = "_101$"))


问:
Dyanmically create Hyperlinks to all files in a folder using MVC 3
I have a controller that returns a list of files in a directory using DirectoryInfo.GetFiles()

```<code>public ActionResult Index()
        {
            DirectoryInfo vidDir = null;
            FileInfo[] files = null;

            string dirPath = @"/Content/Videos";
            vidDir = new DirectoryInfo(Server.MapPath(dirPath));
            files = vidDir.GetFiles();

            return View(files);
        }
</code>```

In my view I enumerate the files with the following code:

```<code><ul>  @foreach (var file in Model) {
                  <li>
                   @file
                  </li>
            }
                  </ul>
</code>```

What I would like to do is foreach (var file in Model) { create a hyperlink to file }

I was able to hard code a link using @html.actionlink

```<code> @Html.ActionLink("Test Link", "file1.txt", "Content/Videos");
</code>```

When I put in @file for the first two parameters, I get an error that says:

'System.Web.Mvc.HtmlHelper'
  has no applicable method named
  'ActionLink' but appears to have an
  extension method by that name"

How can I use @html.Actionlink to create a hyperlink to all the files passed into the view?

答:
These seem to be a direct link to those files. If so</p>

```<code><a href="@Url.Content(string.Concat("Content/Videos/", @file))">@file</a>
</code>```

Body:
I have a controller that returns a list of files in a directory using DirectoryInfo.GetFiles()

public ActionResult Index()
        {
            DirectoryInfo vidDir = null;
            FileInfo[] files = null;

            string dirPath = @"/Content/Videos";
            vidDir = new DirectoryInfo(Server.MapPath(dirPath));
            files = vidDir.GetFiles();

            return View(files);
        }

In my view I enumerate the files with the following code:

  @foreach (var file in Model) {

                   @file

            }

What I would like to do is foreach (var file in Model) { create a hyperlink to file }

I was able to hard code a link using @html.actionlink

 @Html.ActionLink("Test Link", "file1.txt", "Content/Videos");

When I put in @file for the first two parameters, I get an error that says:

'System.Web.Mvc.HtmlHelper'
  has no applicable method named
  'ActionLink' but appears to have an
  extension method by that name"

How can I use @html.Actionlink to create a hyperlink to all the files passed into the view?

Body:
These seem to be a direct link to those files. If so

<a href="@Url.Content(string.Concat("Content/Videos/", @file))">@file</a>


问:
How to center columns in DT package? R
```<code>datatable(head(iris))

</code>```

How can I center my columns so they're right underneath my column names?

答:
You can use the columnDefs argument argument under options.  Set className to dt-center to center columns and use targets to set which columns you'd like to center, for example as a range, 0:4 (starts at zero), or _all for all of them.

```<code>library(DT)
datatable(head(iris),
          options = list(columnDefs =
                           list(list(className = 'dt-center',
                                     targets = "_all"))))
</code>```

Title: How to center columns in DT package? R

Body:
datatable(head(iris))

How can I center my columns so they're right underneath my column names?

Body:
You can use the columnDefs argument argument under options.  Set className to dt-center to center columns and use targets to set which columns you'd like to center, for example as a range, 0:4 (starts at zero), or _all for all of them.

library(DT)
datatable(head(iris),
          options = list(columnDefs =
                           list(list(className = 'dt-center',
                                     targets = "_all"))))


问:
Fullscreen Google map in bootstrap 4 large modal not show
I add a google map in a large modal using bootstrap 4.
when modal show, Map is work but when i click fullscreen button, the modal and map not display just blank. My head was broken thinking this. How to fix it?

Before:

(source: image.ibb.co)

After:

My javascript code:

```<code>$(document).ready(function() {
var marker, i;
var markers=[];
function load_map(){
  if (typeof google === 'object' && typeof google.maps === 'object') {

    var myLatLng = new google.maps.LatLng(<?=$row->lat?>,<?=$row->lon?>);

    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 20,
      center: myLatLng,
      fullscreenControl: true,
      scaleControl:true,
      streetViewControl:true,
      mapTypeId: google.maps.MapTypeId.HYBRID
    });

    infowindow = new google.maps.InfoWindow();

    //set markers
    var locations=<?=json_encode($kordinat)?>;
    for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        animation: google.maps.Animation.DROP,
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map,
        icon: {
          url:base_url+'assets/base/images/marker_black.png'
        }
      });
      markers.push(marker);
    }
    //target marker
    marker = new google.maps.Marker({
        animation: google.maps.Animation.DROP,
        position: myLatLng,
        map: map
    });
    markers.push(marker);

    var markerCluster = new MarkerClusterer(map, markers,{imagePath: base_url+'assets/base/images/m'});
    map.setCenter(myLatLng);

  }else{
  $('#show-map').slideDown();
  $('#map').slideUp();
     alert('Tidak dapat memuat peta ! Periksa koneksi internet !');
  }
}

$('#show-map').click(function(){
    $(this).slideUp();
    $('#map').slideDown();
    setTimeout(function(){load_map()}, 1000);
});});
</code>```

My HTML code:

```<code><div class="modal fade modal-3d-slit show" id="modal-detail" aria-labelledby="exampleModalPrimary" role="dialog" tabindex="-1"><div class="modal-dialog modal-lg">
<div class="modal-content">
  <div class="modal-header">
      <div class="ribbon ribbon-corner ribbon-info ribbon-reverse">
        <a href="#" data-dismiss="modal">
          <span class="ribbon-inner"><i class="icon md-close" aria-hidden="true"></i></span>
        </a>
      </div>
      <h4 class="modal-title"><span class="icon md-account-circle"</span>Detail Izin</h4>
    </div>
  <div class="modal-body"><style type="text/css">li.list-group-item:hover{background: #eeeeee}</style>
    <div class="nav-tabs-animate nav-tabs-inverse nav-tabs-horizontal" data-plugin="tabs"><ul class="nav nav-tabs" role="tablist">
          <li class="nav-item" role="presentation"><a class="nav-link" data-toggle="tab" href="#tab-pemohon" aria-expanded="false">Pemohon</a></li>
            <li class="nav-item" role="presentation"><a class="nav-link active" data-toggle="tab" href="#tab-izin" aria-expanded="true">Izin</a></li>
          <li class="nav-item" role="presentation"><a class="nav-link" data-toggle="tab" href="#tab-persyaratan" aria-expanded="false">Persyaratan</a></li>
          <li class="nav-item" role="presentation"><a class="nav-link" data-toggle="tab" href="#tab-tindakan" aria-expanded="false">Riwayat Tindakan</a></li>
        </ul>

        <div class="tab-content">
            <div class="tab-pane animation-scale-up mt-10 active" id="tab-izin" role="tabpanel" aria-expanded="true">
              <table class="table table-hover"></table>
              <button type="button" class="btn btn-primary waves-effect waves-classic btn-block btn-lg" id="show-map"><i class="icon md-map"></i> Tampilkan Peta</button>

              <div id="map" style="height: 400px; width: 100%;"></div>

          </div>
        </div>
    </div>
  </div>
</div>
</code>```

答:
I'm doing something similar (not a Google Map, but Esri's JS-mapping library) with Bootstrap - have the map in a modal, but take up as much real estate as possible. I know that JS maps are really finicky - you have to have some way for the browser to set at least one dimension in pixels unless you're going 100% for both dimensions. (At least, that's the way it used to be when I first started with JS Maps.) I suspect that might be what's happening but I'm also guessing when you click full screen, the map no longer knows it's supposed to be inside that modal content.

Anyway, I'm using an iframe (id="mapiFrame") within the modal-body div, and the following CSS gets me really close to what I want:

```<code>#mapiFrame {
  height: calc(80vh - 5px);
  width: calc(90vw - 5px);
}

.modal-dialog {
  max-width: none;
  max-height: none;
  margin: 2px;
  padding: 2px;
}
</code>```

Body:
I add a google map in a large modal using bootstrap 4.
when modal show, Map is work but when i click fullscreen button, the modal and map not display just blank. My head was broken thinking this. How to fix it?

Before:

(source: image.ibb.co)

After:

My javascript code:

$(document).ready(function() {
var marker, i;
var markers=[];
function load_map(){
  if (typeof google === 'object' && typeof google.maps === 'object') {

    var myLatLng = new google.maps.LatLng(<?=$row->lat?>,<?=$row->lon?>);

    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 20,
      center: myLatLng,
      fullscreenControl: true,
      scaleControl:true,
      streetViewControl:true,
      mapTypeId: google.maps.MapTypeId.HYBRID
    });

    infowindow = new google.maps.InfoWindow();

    //set markers
    var locations=<?=json_encode($kordinat)?>;
    for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        animation: google.maps.Animation.DROP,
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map,
        icon: {
          url:base_url+'assets/base/images/marker_black.png'
        }
      });
      markers.push(marker);
    }
    //target marker
    marker = new google.maps.Marker({
        animation: google.maps.Animation.DROP,
        position: myLatLng,
        map: map
    });
    markers.push(marker);

    var markerCluster = new MarkerClusterer(map, markers,{imagePath: base_url+'assets/base/images/m'});
    map.setCenter(myLatLng);

  }else{
  $('#show-map').slideDown();
  $('#map').slideUp();
     alert('Tidak dapat memuat peta ! Periksa koneksi internet !');
  }
}

$('#show-map').click(function(){
    $(this).slideUp();
    $('#map').slideDown();
    setTimeout(function(){load_map()}, 1000);
});});

My HTML code:

<span class="icon md-account-circle"Detail Izin

Pemohon

Izin

Persyaratan

Riwayat Tindakan

              <button type="button" class="btn btn-primary waves-effect waves-classic btn-block btn-lg" id="show-map"> Tampilkan Peta</button>

Body:
I'm doing something similar (not a Google Map, but Esri's JS-mapping library) with Bootstrap - have the map in a modal, but take up as much real estate as possible. I know that JS maps are really finicky - you have to have some way for the browser to set at least one dimension in pixels unless you're going 100% for both dimensions. (At least, that's the way it used to be when I first started with JS Maps.) I suspect that might be what's happening but I'm also guessing when you click full screen, the map no longer knows it's supposed to be inside that modal content.

Anyway, I'm using an iframe (id="mapiFrame") within the modal-body div, and the following CSS gets me really close to what I want:

#mapiFrame {
  height: calc(80vh - 5px);
  width: calc(90vw - 5px);
}

.modal-dialog {
  max-width: none;
  max-height: none;
  margin: 2px;
  padding: 2px;
}


问:
Difference in handling onClicks with functions REACT
What is the difference between these two lines:

```<code><button onClick={() => this.updateTodoToShow("all")}>all</button>
</code>```

and

```<code><button onClick = {this.deleteCompleted}>delete completed</button>
</code>```

Why is one called with an arrow function and not the other? When is it appropriate to do each of these? Here is the full code for those two functions:

```<code>deleteCompleted = () => {
          this.setState({
              todos: this.state.todos.filter(todo => !todo.complete)
          });
      };

updateTodoToShow = s => {
        this.setState({
          todoToShow: s
        });
      };
</code>```

答:
The first uses an anonymous arrow function in order to pass a value other than the event to the function updateTodoToShow.

The second apparently does not need to pass anything besides the click event which is the default argument (in fact, it doesn't appear to use the event either), so it only passes the function reference to this.deleteCompleted.

If no extra parameter is needed for the event handler, passing only the function reference is better. Creating an unnecessary inline function is pointless, like in the following:

onClick={(e) => this.handler(e)}
```

<p>Is functionally equivalent to below, there is just no unnecessary in-between function:</p>

<pre class="lang-js prettyprint-override"><code>onClick={this.handler}
</code>```

The main thing to understand here is that both methods are passing onClick a function reference. The first is passing a reference to the inline function, the second is passing a reference to the deleteCompleted function.

It is appropriate to use the inline function only when you need to add extra arguments to the handler. Another common usecase would be passing an id or other identifier when creating buttons in a loop.

Body:
What is the difference between these two lines:

<button onClick={() => this.updateTodoToShow("all")}>all</button>

and

<button onClick = {this.deleteCompleted}>delete completed</button>

Why is one called with an arrow function and not the other? When is it appropriate to do each of these? Here is the full code for those two functions:

deleteCompleted = () => {
          this.setState({
              todos: this.state.todos.filter(todo => !todo.complete)
          });
      };

updateTodoToShow = s => {
        this.setState({
          todoToShow: s
        });
      };

Body:
The first uses an anonymous arrow function in order to pass a value other than the event to the function updateTodoToShow.

The second apparently does not need to pass anything besides the click event which is the default argument (in fact, it doesn't appear to use the event either), so it only passes the function reference to this.deleteCompleted.

If no extra parameter is needed for the event handler, passing only the function reference is better. Creating an unnecessary inline function is pointless, like in the following:

onClick={(e) => this.handler(e)}

Is functionally equivalent to below, there is just no unnecessary in-between function:

onClick={this.handler}

The main thing to understand here is that both methods are passing onClick a function reference. The first is passing a reference to the inline function, the second is passing a reference to the deleteCompleted function.

It is appropriate to use the inline function only when you need to add extra arguments to the handler. Another common usecase would be passing an id or other identifier when creating buttons in a loop.


问:
Cron parser and validation in python
I am currently running a django web app in python where I store cron entries entered by the user into a database. I was wondering if there are any python libraries/packages that will validate these entries before I store them into the database. By validate I mean correct syntax as well as the correct range (ex: month cannot be 15). Does anyone have any suggestions? Thanks!</p>

答:
Since the accepted answer is quite old, the same library has a croniter.is_valid() method now. From docs:

```<code>>>> croniter.is_valid('0 0 1 * *')  # True
>>> croniter.is_valid('0 wrong_value 1 * *')  # False
</code>```

Title: Cron parser and validation in python

Body:
Since the accepted answer is quite old, the same library has a croniter.is_valid() method now. From docs:

>>> croniter.is_valid('0 0 1 * *')  # True
>>> croniter.is_valid('0 wrong_value 1 * *')  # False


问:
Creating a new column in a specific place in Pandas
I would like to create a new column in Python and place in a specific position. For instance, let "example" be the following dataframe:

```<code>import pandas as pd

example = pd.DataFrame({
            'name': ['alice','bob','charlie'],
            'age': [25,26,27],
            'job': ['manager','clerk','policeman'],
            'gender': ['female','male','male'],
            'nationality': ['french','german','american']
        })
</code>```

I would like to create a new column to contain the values of the column "age":

```<code>example['age_times_two']= example['age'] *2
</code>```

Yet, this code creates a column at the end of the dataframe. I would like to place it as the third column, or, in other words, the column right next to the column "age". How could this be done:

a) By setting an absolute place to the new column (e.g. third position)?

b) By setting a relative place for the new column (e.g. right to the column "age")?

答:
Another way to do it:

```<code>example['age_times_two']= example['age'] *2

cols = example.columns.tolist()

cols = cols[:2]+cols[-1:]+cols[2:-1]

example = example[cols]

print(example)
</code>```

.

```<code>      name  age  age_times_two        job  gender nationality
0    alice   25             50    manager  female      french
1      bob   26             52      clerk    male      german
2  charlie   27             54  policeman    male    american
</code>```

Body:
I would like to create a new column in Python and place in a specific position. For instance, let "example" be the following dataframe:

import pandas as pd

example = pd.DataFrame({
            'name': ['alice','bob','charlie'],
            'age': [25,26,27],
            'job': ['manager','clerk','policeman'],
            'gender': ['female','male','male'],
            'nationality': ['french','german','american']
        })

I would like to create a new column to contain the values of the column "age":

example['age_times_two']= example['age'] *2

Yet, this code creates a column at the end of the dataframe. I would like to place it as the third column, or, in other words, the column right next to the column "age". How could this be done:

a) By setting an absolute place to the new column (e.g. third position)?

b) By setting a relative place for the new column (e.g. right to the column "age")?

Body:
Another way to do it:

example['age_times_two']= example['age'] *2

cols = example.columns.tolist()

cols = cols[:2]+cols[-1:]+cols[2:-1]

example = example[cols]

print(example)

.

      name  age  age_times_two        job  gender nationality
0    alice   25             50    manager  female      french
1      bob   26             52      clerk    male      german
2  charlie   27             54  policeman    male    american


问:
I am trying to add a UILabel exactly like I already have but keep getting this error
I am trying to add a label to my calculator where it shows the tip amount but I keep getting

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

I just want it to display the tip amount as well. I copied it exact for the other UILabel.

```<code>
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var PriceTxt: UITextField!
    @IBOutlet weak var Tip: UITextField!
    @IBOutlet weak var totalFinal: UILabel!
    @IBOutlet weak var TipAmount: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        totalFinal.text = ""
        TipAmount.text = ""
    }

    @IBAction func Calcualte(_ sender: Any) {
        if  PriceTxt.text! == "" || Tip.text! == ""
        {
            totalFinal.text = "Input the Numbers"
            TipAmount.text = ""
        }

        else {
        let price = Double(PriceTxt.text!)!
        let tipPer = Double(Tip.text!)!
        let TipMult =  price * (tipPer/100)
        let TipFinal = Double((round(100*TipMult)/100) + price)
        totalFinal.text = "$\(TipFinal)"
        TipAmount.text = "$\(TipMult)"
    }

}
}
</code>```

答:
It will show you the problem in your code.. please always try to avoid force cast</p>

```<code>class ViewController: UIViewController {

    @IBOutlet weak var PriceTxt: UITextField!
    @IBOutlet weak var Tip: UITextField!
    @IBOutlet weak var totalFinal: UILabel!
    @IBOutlet weak var TipAmount: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        totalFinal.text = ""
        TipAmount.text = ""
    }

    @IBAction func Calcualte(_ sender: Any) {
        if let getPrice = PriceTxt.text , let getTip = Tip.text
        {
            if getPrice.isEmpty || getTip.isEmpty {
                totalFinal.text = "Input the Numbers"
                TipAmount.text = ""
            }
            else {

                let price = Double(getPrice)!
                let tipPer = Double(getTip)!
                let TipMult =  price * (tipPer/100)
                let TipFinal = Double((round(100*TipMult)/100) + price)
                totalFinal.text = "$\(TipFinal)"
                TipAmount.text = "$\(TipMult)"
            }
        } else {
            print("either PriceTxt or Tip is nil")
        }
    }
}
</code>```

Body:
I am trying to add a label to my calculator where it shows the tip amount but I keep getting

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

I just want it to display the tip amount as well. I copied it exact for the other UILabel.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var PriceTxt: UITextField!
    @IBOutlet weak var Tip: UITextField!
    @IBOutlet weak var totalFinal: UILabel!
    @IBOutlet weak var TipAmount: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        totalFinal.text = ""
        TipAmount.text = ""
    }

    @IBAction func Calcualte(_ sender: Any) {
        if  PriceTxt.text! == "" || Tip.text! == ""
        {
            totalFinal.text = "Input the Numbers"
            TipAmount.text = ""
        }

        else {
        let price = Double(PriceTxt.text!)!
        let tipPer = Double(Tip.text!)!
        let TipMult =  price * (tipPer/100)
        let TipFinal = Double((round(100*TipMult)/100) + price)
        totalFinal.text = "$\(TipFinal)"
        TipAmount.text = "$\(TipMult)"
    }

}
}

Body:
It will show you the problem in your code.. please always try to avoid force cast

class ViewController: UIViewController {

    @IBOutlet weak var PriceTxt: UITextField!
    @IBOutlet weak var Tip: UITextField!
    @IBOutlet weak var totalFinal: UILabel!
    @IBOutlet weak var TipAmount: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        totalFinal.text = ""
        TipAmount.text = ""
    }

    @IBAction func Calcualte(_ sender: Any) {
        if let getPrice = PriceTxt.text , let getTip = Tip.text
        {
            if getPrice.isEmpty || getTip.isEmpty {
                totalFinal.text = "Input the Numbers"
                TipAmount.text = ""
            }
            else {

                let price = Double(getPrice)!
                let tipPer = Double(getTip)!
                let TipMult =  price * (tipPer/100)
                let TipFinal = Double((round(100*TipMult)/100) + price)
                totalFinal.text = "$\(TipFinal)"
                TipAmount.text = "$\(TipMult)"
            }
        } else {
            print("either PriceTxt or Tip is nil")
        }
    }
}


问:
How do I get my intent to call my fulfilment on DialogFlow?
I must be missing something because my intent is never calling my fulfillment script.

I created an intent, let's say it is called xyz. It is simple, just has some phrases it can be called by.

I created the JavaScript under fulfillment, and it has a function called abc() that should be called. I also added:

```<code>intentMap.set('xyz', abc);
</code>```

But my fulfillment is never called when I test the phrases of xyz, I just get Sorry, project name isn't responding right now. Please try again soon.

I don't even see the logs on the first lines of my script there.

The first few lines look like this:

```<code>exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
</code>```

So I'm assuming that means I should be seeing those console.log lines but I don't see them. Does that mean that I have neglected to link my intent with my fulfillment? How do I do that?

Edit: Here is the screenshot of the intent:

This is the code:

```<code>// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';

const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');
const { Card, Suggestion } = require('dialogflow-fulfillment');

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to my agent!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }
  function testIntent(agent) {
    const conv = agent.conv();
    agent.tell('this is a test');
  }
  // // Uncomment and edit to make your own intent handler
  // // uncomment `intentMap.set('your intent name here', yourFunctionHandler);`
  // // below to get this function to be run when a Dialogflow intent is matched
  // function yourFunctionHandler(agent) {
  //   agent.add(`This message is from Dialogflow's Cloud Functions for Firebase editor!`);
  //   agent.add(new Card({
  //       title: `Title: this is a card title`,
  //       imageUrl: 'https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png',
  //       text: `This is the body text of a card.  You can even use line\n  breaks and emoji! `,
  //       buttonText: 'This is a button',
  //       buttonUrl: 'https://assistant.google.com/'
  //     })
  //   );
  //   agent.add(new Suggestion(`Quick Reply`));
  //   agent.add(new Suggestion(`Suggestion`));
  //   agent.setContext({ name: 'weather', lifespan: 2, parameters: { city: 'Rome' }});
  // }

  // // Uncomment and edit to make your own Google Assistant intent handler
  // // uncomment `intentMap.set('your intent name here', googleAssistantHandler);`
  // // below to get this function to be run when a Dialogflow intent is matched
  // function googleAssistantHandler(agent) {
  //   let conv = agent.conv(); // Get Actions on Google library conv instance
  //   conv.ask('Hello from the Actions on Google client library!') // Use Actions on Google library
  //   agent.add(conv); // Add Actions on Google library responses to your agent's response
  // }
  // // See https://github.com/dialogflow/fulfillment-actions-library-nodejs
  // // for a complete Dialogflow fulfillment library Actions on Google client library v2 integration sample

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('test intent', testIntent);
  // intentMap.set('your intent name here', yourFunctionHandler);
  // intentMap.set('your intent name here', googleAssistantHandler);
  agent.handleRequest(intentMap);
});
</code>```

答:
The issue is that your testIntent() handler function is calling agent.tell(), which isn't a valid method.

I suspect you meant to call agent.add()

Body:
I must be missing something because my intent is never calling my fulfillment script.

I created an intent, let's say it is called xyz. It is simple, just has some phrases it can be called by.

I created the JavaScript under fulfillment, and it has a function called abc() that should be called. I also added:

intentMap.set('xyz', abc);

But my fulfillment is never called when I test the phrases of xyz, I just get Sorry, project name isn't responding right now. Please try again soon.

I don't even see the logs on the first lines of my script there.

The first few lines look like this:

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

So I'm assuming that means I should be seeing those console.log lines but I don't see them. Does that mean that I have neglected to link my intent with my fulfillment? How do I do that?

Edit: Here is the screenshot of the intent:

This is the code:

// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';

const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');
const { Card, Suggestion } = require('dialogflow-fulfillment');

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to my agent!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }
  function testIntent(agent) {
    const conv = agent.conv();
    agent.tell('this is a test');
  }
  // // Uncomment and edit to make your own intent handler
  // // uncomment `intentMap.set('your intent name here', yourFunctionHandler);`
  // // below to get this function to be run when a Dialogflow intent is matched
  // function yourFunctionHandler(agent) {
  //   agent.add(`This message is from Dialogflow's Cloud Functions for Firebase editor!`);
  //   agent.add(new Card({
  //       title: `Title: this is a card title`,
  //       imageUrl: 'https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png',
  //       text: `This is the body text of a card.  You can even use line\n  breaks and emoji! `,
  //       buttonText: 'This is a button',
  //       buttonUrl: 'https://assistant.google.com/'
  //     })
  //   );
  //   agent.add(new Suggestion(`Quick Reply`));
  //   agent.add(new Suggestion(`Suggestion`));
  //   agent.setContext({ name: 'weather', lifespan: 2, parameters: { city: 'Rome' }});
  // }

  // // Uncomment and edit to make your own Google Assistant intent handler
  // // uncomment `intentMap.set('your intent name here', googleAssistantHandler);`
  // // below to get this function to be run when a Dialogflow intent is matched
  // function googleAssistantHandler(agent) {
  //   let conv = agent.conv(); // Get Actions on Google library conv instance
  //   conv.ask('Hello from the Actions on Google client library!') // Use Actions on Google library
  //   agent.add(conv); // Add Actions on Google library responses to your agent's response
  // }
  // // See https://github.com/dialogflow/fulfillment-actions-library-nodejs
  // // for a complete Dialogflow fulfillment library Actions on Google client library v2 integration sample

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('test intent', testIntent);
  // intentMap.set('your intent name here', yourFunctionHandler);
  // intentMap.set('your intent name here', googleAssistantHandler);
  agent.handleRequest(intentMap);
});


问:
Is there a way to use inspect element to select an element in Electron?
I'm looking to utilize the "Select an element in the page to inspect it" Ctrl + Shift + C utility in Chromium's developer tools in order to allow a user to select an element on an Electron application.

For example, a page or file should be loaded. Then, upon calling a function, the user should be presented with the ability to select an element as if they had opened their developer tools and pressed the inspect element button. Clicking on an element to inspect it should result in a function being called with the inspected element, without opening the developer tools. The intention is that this is a built in way to select elements on a page without the need for re-writing code to allow for this style of point, highlight, and click selection system.

The intended usage is as follows

const {app, BrowserWindow} = require('electron');

app.on('ready', function() {
    let window = new BrowserWindow();
    window.loadURL('https://stackoverflow.com/');

    // This should trigger the inspect element tool
    window.getElementFromInspector(function(element) {
        // This should be called after an element is selected with the inspect element tool
    });
});
```

It's not expected that window should necessarily contain a .getElementFromInspector(callback: function) method. However, the solution should be functionally similar to the proposed usage. (Even if it requires loading external JavaScript into the page, just was trying to avoid it if at all possible)

Doing some looking in Electon's API documentation gave light to the contents.inspectElement(x, y) method. This sounds as if it would allow for an element to be selected for inspection from an x,y position on the page, but mentions nothing of accessing the now inspected element remotely. I would also imagine this results in opening the developer tools if not already open, which is something that can hopefully be avoided.

EDIT: From what I've seen, I don't believe it is going to be <s>possible</s> easy to use the inspect element selector without having the developer tools open. Because of this, answers that require the developer tools to be open will be accepted, but it is preferred that the developer tools need not be open.

答:
This accomplishes the inspect on hover over in the same way the inspect element utility does, but does not highlight the element. It also requires the developer tools to be shown to work.

```<code>// main.js
const electron = require('electron');
const path = require('path');

electron.app.on('ready', function() {
  let window = new electron.BrowserWindow({
    webPreferences: {
      preload: path.join(__dirname, 'inspector.js')
    }
  });

  window.webContents.openDevTools();

  electron.ipcMain.addListener('mouse', function(event, e) {
    event.returnValue = null;
    window.webContents.inspectElement(e.x, e.y);
  });

  window.loadURL('https://stackoverflow.com/');
});
</code>```

```<code>// inspector.js
window.onload = function() {
  let {ipcRenderer} = require('electron');

  document.onmousemove = e => ipcRenderer.sendSync('mouse', { x: e.clientX, y: e.clientY });
};
</code>```

This doesn't do exactly what I had wanted, nor does it do it in the manor I had intended, but it is the closest I've been able to get to solving this problem.

Body:
I'm looking to utilize the "Select an element in the page to inspect it" Ctrl + Shift + C utility in Chromium's developer tools in order to allow a user to select an element on an Electron application.

For example, a page or file should be loaded. Then, upon calling a function, the user should be presented with the ability to select an element as if they had opened their developer tools and pressed the inspect element button. Clicking on an element to inspect it should result in a function being called with the inspected element, without opening the developer tools. The intention is that this is a built in way to select elements on a page without the need for re-writing code to allow for this style of point, highlight, and click selection system.

The intended usage is as follows

const {app, BrowserWindow} = require('electron');

app.on('ready', function() {
    let window = new BrowserWindow();
    window.loadURL('https://stackoverflow.com/');

    // This should trigger the inspect element tool
    window.getElementFromInspector(function(element) {
        // This should be called after an element is selected with the inspect element tool
    });
});

It's not expected that window should necessarily contain a .getElementFromInspector(callback: function) method. However, the solution should be functionally similar to the proposed usage. (Even if it requires loading external JavaScript into the page, just was trying to avoid it if at all possible)

Doing some looking in Electon's API documentation gave light to the contents.inspectElement(x, y) method. This sounds as if it would allow for an element to be selected for inspection from an x,y position on the page, but mentions nothing of accessing the now inspected element remotely. I would also imagine this results in opening the developer tools if not already open, which is something that can hopefully be avoided.

EDIT: From what I've seen, I don't believe it is going to be <s>possible</s> easy to use the inspect element selector without having the developer tools open. Because of this, answers that require the developer tools to be open will be accepted, but it is preferred that the developer tools need not be open.

Body:
This accomplishes the inspect on hover over in the same way the inspect element utility does, but does not highlight the element. It also requires the developer tools to be shown to work.

// main.js
const electron = require('electron');
const path = require('path');

electron.app.on('ready', function() {
  let window = new electron.BrowserWindow({
    webPreferences: {
      preload: path.join(__dirname, 'inspector.js')
    }
  });

  window.webContents.openDevTools();

  electron.ipcMain.addListener('mouse', function(event, e) {
    event.returnValue = null;
    window.webContents.inspectElement(e.x, e.y);
  });

  window.loadURL('https://stackoverflow.com/');
});

// inspector.js
window.onload = function() {
  let {ipcRenderer} = require('electron');

  document.onmousemove = e => ipcRenderer.sendSync('mouse', { x: e.clientX, y: e.clientY });
};

This doesn't do exactly what I had wanted, nor does it do it in the manor I had intended, but it is the closest I've been able to get to solving this problem.


问:
Why Are My Cell's Images Being Pixelated?
I am using an iPhone 4 with retina display.

I have a 60x60 png that was downsized from a 500x500 png that I am using as the cell's imageView.

For some reason, the image looks a bit pixelated and blurry, basically not up to retina display standards.

What am I doing wrong?

I am using cell.imageView.image = [UIImage imageNamed:@"picture.png"];

答:
Try using a a 60x60 png as a source. It will likely resolve your bluriness problems and will additionaly be cheaper on memory usage.

I have also experienced resized images to be blurry and the likes. I could imagine that this has something todo with the images being shrunken down at runtime, though I'm not sure about that.

Also remember that it's recommended to provide two versions of your imagefile:

One for normal resolutions (iPhone 3G, 3GS ...): picture.png for your case: 30x30px

One for the retina display (iPhone 4): picture@2x.png for your case: 60x60px.


问:
How to print a list more nicely?
This is similar to How to print a list in Python “nicely”, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.

```<code>foolist = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf',
    'pdcurses-devel',     'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel',
    'qgis1.1', 'php_mapscript']

evenNicerPrint(foolist)
</code>```

Desired result:

```<code>exiv2-devel       msvcrt
mingw-libs        gdal-grass
tcltk-demos       iconv
fcgi              qgis-devel
netcdf            qgis1.1
pdcurses-devel    php_mapscript
</code>```

thanks!

答:
For Python >=3.6, slight update to @JoshuaZastrow's answer using f-strings and adding clear method to adjust columns

```<code>cols = 5
[print(f'{key:20}', end='\t') if (idx + 1) % cols else print(f'{key}') for idx, key in enumerate(list_variable)]
</code>```

or

```<code>cols = 5
for idx, key in enumerate(list_variable):
    if (idx + 1) % cols:
        print(f'{key:20}', end='\t')
    else:
        print(f'{key}')
</code>```

Title: How to print a list more nicely?

Body:
This is similar to How to print a list in Python “nicely”, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.

foolist = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf',
    'pdcurses-devel',     'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel',
    'qgis1.1', 'php_mapscript']

evenNicerPrint(foolist)

Desired result:

exiv2-devel       msvcrt
mingw-libs        gdal-grass
tcltk-demos       iconv
fcgi              qgis-devel
netcdf            qgis1.1
pdcurses-devel    php_mapscript

thanks!

Body:
For Python >=3.6, slight update to @JoshuaZastrow's answer using f-strings and adding clear method to adjust columns

cols = 5
[print(f'{key:20}', end='\t') if (idx + 1) % cols else print(f'{key}') for idx, key in enumerate(list_variable)]

or

cols = 5
for idx, key in enumerate(list_variable):
    if (idx + 1) % cols:
        print(f'{key:20}', end='\t')
    else:
        print(f'{key}')


问:
VBA dynamic variable value
There is no dumb questions, only dumb people asking questions. I might fall in that category right now.

I want to achieve the following :

```<code>Sub test
Dim lastcolumn as long
lastcolumn = Range("A1").End(xlToRight).Column
DebugPrint lastcolumn '=5
'Add 2 columns between first and last col
DebugPrint lastcolumn '=7
End Sub
</code>```

right now I need to do as follow :

```<code>Sub test
Dim lastcolumn as long
lastcolumn = Range("A1").End(xlToRight).Column
DebugPrint lastcolumn '=5
'Add 2 columns between first and last col
lastcolumn = Range("A1").End(xlToRight).Column
DebugPrint lastcolumn '=7
End Sub
</code>```

So I end up with

lastcolumn = Range("A1").End(xlToRight).Column

all over the place

What's the correct way to do that?

答:
What about something like this ? Is it bad ? Might not be performant

```<code>'Option Explicit

Public Enum DynamicVar
    lastcolumn
    lastrow
End Enum

Public Function MyVar(name As DynamicVar) As Variant

If name = lastcolumn Then
    MyVar = Cells(1, Columns.Count).End(xlToLeft).Column
    Exit Function

ElseIf name = lastrow Then
    MyVar = Cells(Rows.Count, 1).End(xlUp).Row
    Exit Function

End If

End Function

Sub test()
Cells(MyVar(lastrow), MyVar(lastcolumn)).value = "Wathever"
End Sub'
</code>```

Edit : Maybe this is a bit better

```<code>Public Function MyVar(name As DynamicVar) As Variant

Select Case name

    Case lastcolumn
        MyVar = Cells(1, Columns.Count).End(xlToLeft).Column

    Case lastrow
        MyVar = Cells(Rows.Count, 1).End(xlUp).Row

End Select

End Function
</code>```

Title: VBA dynamic variable value

Body:
There is no dumb questions, only dumb people asking questions. I might fall in that category right now.

I want to achieve the following :

Sub test
Dim lastcolumn as long
lastcolumn = Range("A1").End(xlToRight).Column
DebugPrint lastcolumn '=5
'Add 2 columns between first and last col
DebugPrint lastcolumn '=7
End Sub

right now I need to do as follow :

Sub test
Dim lastcolumn as long
lastcolumn = Range("A1").End(xlToRight).Column
DebugPrint lastcolumn '=5
'Add 2 columns between first and last col
lastcolumn = Range("A1").End(xlToRight).Column
DebugPrint lastcolumn '=7
End Sub

So I end up with

lastcolumn = Range("A1").End(xlToRight).Column

all over the place

What's the correct way to do that?

Body:
What about something like this ? Is it bad ? Might not be performant

'Option Explicit

Public Enum DynamicVar
    lastcolumn
    lastrow
End Enum

Public Function MyVar(name As DynamicVar) As Variant

If name = lastcolumn Then
    MyVar = Cells(1, Columns.Count).End(xlToLeft).Column
    Exit Function

ElseIf name = lastrow Then
    MyVar = Cells(Rows.Count, 1).End(xlUp).Row
    Exit Function

End If

End Function

Sub test()
Cells(MyVar(lastrow), MyVar(lastcolumn)).value = "Wathever"
End Sub'

Edit : Maybe this is a bit better

Public Function MyVar(name As DynamicVar) As Variant

Select Case name

    Case lastcolumn
        MyVar = Cells(1, Columns.Count).End(xlToLeft).Column

    Case lastrow
        MyVar = Cells(Rows.Count, 1).End(xlUp).Row

End Select

End Function


问:
How to make responsive React bootstrap cards that are vertically aligned?
I have a card component:

   <Card className="m-5 border-0 shadow" style={styles.card}>
      <Row>
        <Col>
          <Card.Img src={props.image} style={styles.cardImage}/>
        </Col>
        <Col>
          <Card.Body>
            <Card.Title as="h1">
              {props.title}
            </Card.Title>
            <Card.Text as="h4" style={styles.cardText}>
              {props.description}
            </Card.Text>
          </Card.Body>
          {
            props.link &&
            <Button style={styles.button} href={props.url}>Read More</Button>
          }
        </Col>
      </Row>
    </Card>```
</div>
</div>
</p>

<p>The card is wrapped in a fluid <code><Container></code> and <code><CardGroup></code> component from <code>react-bootstrap</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><Container fluid className="text-center">
  <CardGroup className="m-5 d-block">
    <Card />
  </CardGroup>
</Container></code>```

On desktop device it looks like this:

But it looks like this on mobile device:

Here are the styles:

const styles = {
  card: {
    backgroundColor: '#B7E0F2',
    borderRadius: 55,
    padding: '3rem'
  },
  cardImage: {
    height: '100%',
    objectFit: 'cover',
    borderRadius: 55
  }
};```

Does anyone know how to fix this? Thanks.

答:
Try this one

```<code>                    <Card.Columns>

                                <Card >
                                <Card.Body>
                                <Card.Title style={{textAlign:"center"}}>title</Card.Title>
                                <Card.Text style={{textAlign:"left"}}>
                                    description
                                </Card.Text>
                                </Card.Body>
                                <Card.Footer>
                                <Card.Text style={{textAlign:"right"}}>Link</Card.Text>
                                </Card.Footer>
                                </Card>

                    </Card.Columns>
</code>```

For more details check out this Link

Body:
I have a card component:

   <Card className="m-5 border-0 shadow" style={styles.card}>
      <Row>
        <Col>
          <Card.Img src={props.image} style={styles.cardImage}/>
        </Col>
        <Col>
          <Card.Body>
            <Card.Title as="h1">
              {props.title}
            </Card.Title>
            <Card.Text as="h4" style={styles.cardText}>
              {props.description}
            </Card.Text>
          </Card.Body>
          {
            props.link &&
            <Button style={styles.button} href={props.url}>Read More</Button>
          }
        </Col>
      </Row>
    </Card>

The card is wrapped in a fluid <Container> and <CardGroup> component from react-bootstrap:

<Container fluid className="text-center">
  <CardGroup className="m-5 d-block">
    <Card />
  </CardGroup>
</Container>

On desktop device it looks like this:

But it looks like this on mobile device:

Here are the styles:

const styles = {
  card: {
    backgroundColor: '#B7E0F2',
    borderRadius: 55,
    padding: '3rem'
  },
  cardImage: {
    height: '100%',
    objectFit: 'cover',
    borderRadius: 55
  }
};

Does anyone know how to fix this? Thanks.

Body:
Try this one

                    <Card.Columns>

                                <Card >
                                <Card.Body>
                                <Card.Title style={{textAlign:"center"}}>title</Card.Title>
                                <Card.Text style={{textAlign:"left"}}>
                                    description
                                </Card.Text>
                                </Card.Body>
                                <Card.Footer>
                                <Card.Text style={{textAlign:"right"}}>Link</Card.Text>
                                </Card.Footer>
                                </Card>

                    </Card.Columns>

For more details check out this Link