问:
How to find all the strings in an application's memory
I'm trying to find all the strings in a java application's memory. (Like process hacker does). However, when I use process hacker, I get strings that my program can't detect.

Also, I'm pretty sure I'm looping through this one character at a time, is there a way I can fix this, while preventing ReadProccessMemory from returning fragments of strings? (I.e. if the memory is like oiuwlkmeMyStinglkjalkwj I want to make sure MyString doesn't get split up, into two different strings (like oiuwlkmeMySti and nglkjalkwj)

Here's my code so far:

```<code>        const int PROCESS_WM_READ = 0x0010;//?
    [DllImport("kernel32.dll")]
    public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);

    [DllImport("kernel32.dll")]
    public static extern bool ReadProcessMemory(int hProcess,
      Int64 lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead);

    static void Main(string[] args)
    {
        //doMemorySharp();
        //Console.ReadLine();
        //return;

        Process process = Process.GetProcessesByName("javaw")[0];
        IntPtr processHandle = OpenProcess(PROCESS_WM_READ, false, process.Id);
        IntPtr startOffset = process.MainModule.BaseAddress;
        IntPtr endOffset = IntPtr.Add(startOffset, process.MainModule.ModuleMemorySize);
        int bytesRead = 0;
        byte[] buffer = new byte[48];

        for (int i = 0 ; i < process.MainModule.ModuleMemorySize; i++)
        {
            bytesRead = 0;
            buffer = new byte[48];
            if (!ReadProcessMemory((int)processHandle, IntPtr.Add(startOffset, i).ToInt64(), buffer, buffer.Length, ref bytesRead))
            {
                Console.WriteLine("false");
            }

            string s = Encoding.Default.GetString(buffer);
            if (s.Contains("MyString"))
            {
                Console.WriteLine("Yay!");
            }
            Console.WriteLine(s);
            Console.WriteLine(fromByteArray(buffer));
            Console.ReadLine();
        }
        Console.WriteLine("Finished");
        Console.WriteLine("Memory:" + process.MainModule.ModuleMemorySize.ToString());
        Console.ReadLine();
    }
</code>```

答:
Actually, the first thing you should do in to increase the buffer size to make your scanner healthier and faster. This will not prevent the problem from happening, but it's still helpful:

```<code>byte[] buffer = new byte[4096];
</code>```

If the processes are not too big (on the point of view of memory consumption) you could dump their whole memory with a single ReadProcessMemory call and then perform a fast binary scan on the dump.

Another way is to keep on scanning their memory by chunks as you are already doing and, as soon as you spot a piece of text that partially matches the beginning your string:

revert back the current offset to the beginning of that piece of text

read the small memory area between OffsetBegin and OffsetBegin + TargetStringLength

check if the content of your buffer matches the target string

Body:
I'm trying to find all the strings in a java application's memory. (Like process hacker does). However, when I use process hacker, I get strings that my program can't detect.

Also, I'm pretty sure I'm looping through this one character at a time, is there a way I can fix this, while preventing ReadProccessMemory from returning fragments of strings? (I.e. if the memory is like oiuwlkmeMyStinglkjalkwj I want to make sure MyString doesn't get split up, into two different strings (like oiuwlkmeMySti and nglkjalkwj)

Here's my code so far:

        const int PROCESS_WM_READ = 0x0010;//?
    [DllImport("kernel32.dll")]
    public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);

    [DllImport("kernel32.dll")]
    public static extern bool ReadProcessMemory(int hProcess,
      Int64 lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead);

    static void Main(string[] args)
    {
        //doMemorySharp();
        //Console.ReadLine();
        //return;

        Process process = Process.GetProcessesByName("javaw")[0];
        IntPtr processHandle = OpenProcess(PROCESS_WM_READ, false, process.Id);
        IntPtr startOffset = process.MainModule.BaseAddress;
        IntPtr endOffset = IntPtr.Add(startOffset, process.MainModule.ModuleMemorySize);
        int bytesRead = 0;
        byte[] buffer = new byte[48];

        for (int i = 0 ; i < process.MainModule.ModuleMemorySize; i++)
        {
            bytesRead = 0;
            buffer = new byte[48];
            if (!ReadProcessMemory((int)processHandle, IntPtr.Add(startOffset, i).ToInt64(), buffer, buffer.Length, ref bytesRead))
            {
                Console.WriteLine("false");
            }

            string s = Encoding.Default.GetString(buffer);
            if (s.Contains("MyString"))
            {
                Console.WriteLine("Yay!");
            }
            Console.WriteLine(s);
            Console.WriteLine(fromByteArray(buffer));
            Console.ReadLine();
        }
        Console.WriteLine("Finished");
        Console.WriteLine("Memory:" + process.MainModule.ModuleMemorySize.ToString());
        Console.ReadLine();
    }

Body:
Actually, the first thing you should do in to increase the buffer size to make your scanner healthier and faster. This will not prevent the problem from happening, but it's still helpful:

byte[] buffer = new byte[4096];

If the processes are not too big (on the point of view of memory consumption) you could dump their whole memory with a single ReadProcessMemory call and then perform a fast binary scan on the dump.

Another way is to keep on scanning their memory by chunks as you are already doing and, as soon as you spot a piece of text that partially matches the beginning your string:

revert back the current offset to the beginning of that piece of text

read the small memory area between OffsetBegin and OffsetBegin + TargetStringLength

check if the content of your buffer matches the target string


来源: stackexchange

问:
How to count in multiple columns a variable
I am working on a Crystal Report and cannot figure out a way to do this in Crystal or MSSQL

I have a table with usernames that get recorded when an activity is completed in a web app like below

```<code>UID Approved    Denied  Moved   Pended
1   Tom         null    null    Bill
2   null        null    Bill    null
3   Bill        null    Tom     null
4   null        Tom     null    null
5   Tom         null    Bill    Bill
6   null        Bill    Bill    null
7   Tom         null    null    Bill
</code>```

I need to produce a productivity report like below

```<code>        Approved    Denied  Moved   Pended
Tom     3           1       1       0
Bill    1           1       3       3
</code>```

I am not sure how to group the counts by the names that are in the data?

答:
I think this simple query will do the trick to get the result you want.</p>

```<code>SELECT Approved as Names, count(Approved) as Approved,
   (SELECT count(Denied)
    FROM tableName AS j2
    WHERE j1.Approved = j2.Denied) AS Denied,
    (SELECT count(Moved)
    FROM tableName AS j2
    WHERE j1.Approved = j2.Moved) AS Moved,
    (SELECT count(Pended)
    FROM tableName AS j2
    WHERE j1.Approved = j2.Pended) AS Pended
FROM tableName AS j1
GROUP BY Approved
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working on a Crystal Report and cannot figure out a way to do this in Crystal or MSSQL

I have a table with usernames that get recorded when an activity is completed in a web app like below

UID Approved    Denied  Moved   Pended
1   Tom         null    null    Bill
2   null        null    Bill    null
3   Bill        null    Tom     null
4   null        Tom     null    null
5   Tom         null    Bill    Bill
6   null        Bill    Bill    null
7   Tom         null    null    Bill

I need to produce a productivity report like below

        Approved    Denied  Moved   Pended
Tom     3           1       1       0
Bill    1           1       3       3

I am not sure how to group the counts by the names that are in the data?

Body:
I think this simple query will do the trick to get the result you want.

SELECT Approved as Names, count(Approved) as Approved,
   (SELECT count(Denied)
    FROM tableName AS j2
    WHERE j1.Approved = j2.Denied) AS Denied,
    (SELECT count(Moved)
    FROM tableName AS j2
    WHERE j1.Approved = j2.Moved) AS Moved,
    (SELECT count(Pended)
    FROM tableName AS j2
    WHERE j1.Approved = j2.Pended) AS Pended
FROM tableName AS j1
GROUP BY Approved


问:
NULLIF vs IFNULL
Could you explain to me what is the difference between the sql-functions "NULLIF" and "IFNULL"?</p>

答:
```<code>IFNULL(value-to-test, action-if-tested-as-null )

#equivalent case expression:
CASE WHEN value-to-test IS NULL THEN action-if-tested-as-null ELSE value-to-test END
</code>```

IFNULL directs the query to output the second parameter if the first paramenetr happens to be NULL, otherwise it outputs the first parameter. IFNULL is a MySQL only function name, the SQL standard alternative is COALESCE

```<code>NULLIF(value-to-compare-a, value-to-compare-b )

#equivalent case expression:
CASE WHEN value-to-compare-a = value-to-compare-b THEN null ELSE value-to-compare-a END
</code>```

NULLIF compares 2 values. If BOTH values are the SAME then it returns NULL otherwise it returns the first parameter.

Personally I always prefer to use COALESCE instead of IFNULL.

Title: NULLIF vs IFNULL

Body:
IFNULL(value-to-test, action-if-tested-as-null )

#equivalent case expression:
CASE WHEN value-to-test IS NULL THEN action-if-tested-as-null ELSE value-to-test END

IFNULL directs the query to output the second parameter if the first paramenetr happens to be NULL, otherwise it outputs the first parameter. IFNULL is a MySQL only function name, the SQL standard alternative is COALESCE

NULLIF(value-to-compare-a, value-to-compare-b )

#equivalent case expression:
CASE WHEN value-to-compare-a = value-to-compare-b THEN null ELSE value-to-compare-a END

NULLIF compares 2 values. If BOTH values are the SAME then it returns NULL otherwise it returns the first parameter.

Personally I always prefer to use COALESCE instead of IFNULL.


问:
How to align image flush with text
I'm trying to place icon next to text using span but the images are not flush with the text that is beside them. They are moved up. I'm wondering if anyone knows why it is displayed this way and how to fix it. Thanks you.

```<code><div class="search" id="search">
  <input type="search" placeholder="What can we help you find today?"><span>
  <img src="search.png" width="20" height="20"></span>
</div>

<div class="customer" id="customer">
  <div class="My Account">
    <p>My Account<span><img src="user.png" width="23" height="23"></span>
    </p>
  </div>
  <div class="cart">
    <span>Cart |</span><span>0</span><span>items</span><span>
    <img src="cart.png" width="23" height="auto"></span>
  </div>
</div>
</code>```

答:
Because the default vertical alignment for inline elements is baseline. Set the alignment on your images to middle> Also be sure to remove any white space in your code that would be between those elements as browsers are sensitive to it:

```<code>img {
  vertical-align: middle;
}
</code>```

img {
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="search" id="search">
  <input type="search" placeholder="What can we help you find today?"><span><img src="search.png" width="20" height="20"></span>
</div>

<div class="customer" id="customer">
  <div class="My Account">
    <p>My Account<span><img src="user.png" width="23" height="23"></span>
    </p>
  </div>
  <div class="cart">
    <span>Cart |</span><span>0</span><span>items</span><span><img src="cart.png" width="23" height="auto"></span>
  </div>
</div></code>```

Title: How to align image flush with text

Body:
I'm trying to place icon next to text using span but the images are not flush with the text that is beside them. They are moved up. I'm wondering if anyone knows why it is displayed this way and how to fix it. Thanks you.

  <input type="search" placeholder="What can we help you find today?">

My Account

    Cart |0items

Body:
Because the default vertical alignment for inline elements is baseline. Set the alignment on your images to middle> Also be sure to remove any white space in your code that would be between those elements as browsers are sensitive to it:

img {
  vertical-align: middle;
}

img {
  vertical-align: middle;
}

<div class="search" id="search">
  <input type="search" placeholder="What can we help you find today?"><span><img src="search.png" width="20" height="20"></span>
</div>

<div class="customer" id="customer">
  <div class="My Account">
    <p>My Account<span><img src="user.png" width="23" height="23"></span>
    </p>
  </div>
  <div class="cart">
    <span>Cart |</span><span>0</span><span>items</span><span><img src="cart.png" width="23" height="auto"></span>
  </div>
</div>


问:
Pandas Resample on Date Columns
I have a dataframe with dates as columns. I'd like to average the values from daily to a monthly level. I've tried with Time Grouper and Resample, but it doesn't like the columns names are strings and I can seem to figure out how to make columns into something like a DatetimeIndex.

My starting dataframe:

```<code>import pandas as pd

df = pd.DataFrame(data=[[1,2,3,4],[5,6,7,8]],
                  columns=['2013-01-01', '2013-01-02', '2013-02-03', '2013-02-04'],
                  index=['A', 'B'])
</code>```

Desired Output:

```<code>   2013-01-01  2013-02-01
A         1.5         3.5
B         5.6         7.5
</code>```

答:
You can using resample

```<code>df.columns = pd.to_datetime(df.columns)
df.T.resample('M').mean().T
Out[409]:
   2013-01-31  2013-02-28
A         1.5         3.5
B         5.5         7.5
</code>```

Or groupby one

```<code>axis=1
df.groupby(pd.to_datetime(df.columns).to_period('M'),1).mean()
Out[412]:
   2013-01  2013-02
A      1.5      3.5
B      5.5      7.5
</code>```

Title: Pandas Resample on Date Columns

Body:
I have a dataframe with dates as columns. I'd like to average the values from daily to a monthly level. I've tried with Time Grouper and Resample, but it doesn't like the columns names are strings and I can seem to figure out how to make columns into something like a DatetimeIndex.

My starting dataframe:

import pandas as pd

df = pd.DataFrame(data=[[1,2,3,4],[5,6,7,8]],
                  columns=['2013-01-01', '2013-01-02', '2013-02-03', '2013-02-04'],
                  index=['A', 'B'])

Desired Output:

   2013-01-01  2013-02-01
A         1.5         3.5
B         5.6         7.5

Body:
You can using resample

df.columns = pd.to_datetime(df.columns)
df.T.resample('M').mean().T
Out[409]:
   2013-01-31  2013-02-28
A         1.5         3.5
B         5.5         7.5

Or groupby one

axis=1
df.groupby(pd.to_datetime(df.columns).to_period('M'),1).mean()
Out[412]:
   2013-01  2013-02
A      1.5      3.5
B      5.5      7.5


问:
How to parallelize a Data-Driven unit test in Visual Studio 2010?
I know regular MS-Test unit tests can be parallelized on a multi-core machine (with caveats of course) by specifying parallelTestCount attribute in the .testresults file in the test solution. Like this,

```<code><Execution parallelTestCount="1">
    <TestTypeSpecific />
    <AgentRule name="Execution Agents"></AgentRule>
</Execution>
</code>```

More at MSDN: Executing Unit Tests in parallel on a multi-CPU/core machine

However, I have a data-driven test, something like this, this is just one test, but the input comes in from a csv and runs 1000s of records through the same test.

```<code>[DeploymentItem("InputDataRows.csv"), Timeout(37800000), DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\InputDataRow.csv", "InputDataRow#csv", DataAccessMethod.Sequential)]
[TestMethod]
public void RunProcessing()
{
    int userId = Convert.ToInt32(TestContext.DataRow[0].ToString());
    int connId = Convert.ToInt32(TestContext.DataRow[1].ToString());
    string xml = TestHelper.GetDataFromDb(userId, connId);
    a = doStuffA(xml);
    b = doStuffB(xml);
    Assert.IsTrue(a == b);
}
</code>```

Because this is a slow process, I am looking at parallelizing this unit test.

The Sequential enum on the attribute is just the way it accesses data, the other option is Random, which is still serial and not parallel.

答:
This might seem a bit complex, but hear me out.
There is a limitation in MSTest that you cannot actually run data-driven tests in parallel.
What I have done in the past to get around this is to create a "custom tool" in visual studio.

https://msdn.microsoft.com/en-us/library/bb166508.aspx

OR

https://msdn.microsoft.com/en-us/library/bb166817.aspx

The custom tool that we created did the following:

Split out the csv into multiple csv files with only one row each.

Generate an individual test for each of the newly generated csvs.

When these tests were generated, we put specific test attributes on them, so we could specify to only run the tests with that attribute.

This sounds kind of over the top, but if you do a good job building the custom tool, it's actually a very smooth process.

ContentLicense: CC BY-SA 4.0

Body:
I know regular MS-Test unit tests can be parallelized on a multi-core machine (with caveats of course) by specifying parallelTestCount attribute in the .testresults file in the test solution. Like this,

<Execution parallelTestCount="1">
    <TestTypeSpecific />
    <AgentRule name="Execution Agents"></AgentRule>
</Execution>

More at MSDN: Executing Unit Tests in parallel on a multi-CPU/core machine

However, I have a data-driven test, something like this, this is just one test, but the input comes in from a csv and runs 1000s of records through the same test.

[DeploymentItem("InputDataRows.csv"), Timeout(37800000), DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\InputDataRow.csv", "InputDataRow#csv", DataAccessMethod.Sequential)]
[TestMethod]
public void RunProcessing()
{
    int userId = Convert.ToInt32(TestContext.DataRow[0].ToString());
    int connId = Convert.ToInt32(TestContext.DataRow[1].ToString());
    string xml = TestHelper.GetDataFromDb(userId, connId);
    a = doStuffA(xml);
    b = doStuffB(xml);
    Assert.IsTrue(a == b);
}

Because this is a slow process, I am looking at parallelizing this unit test.

The Sequential enum on the attribute is just the way it accesses data, the other option is Random, which is still serial and not parallel.


问:
MapStruct QualifiedByName with multiple parameters
I have come across a situation where my mapping method has 3 parameters, and all the three are being used in deriving one of the properties of the target type.

I have created a default mapping method in the interface keeping the logic for deriving the property, now for calling this method, I could use an expression = "java( /*method call here*/ )" in the @Mapping annotation.

Is there any way to do this with any of the mapstruct annotation like @qualifiedByName, I tried commenting the annotation having expression property and used qualifiedByName, but it doesn't work :

```<code>@Mapper
public interface OneMapper {

    @Mapping(target="id", source="one.id")
    //@Mapping(target="qualified",expression = "java( checkQualified (one, projId, code) )")
    @Mapping(target="qualified",qualifiedByName="checkQualifiedNamed")
    OneDto createOne (One one, Integer projId, Integer val, String code);

    @Named("checkQualifiedNamed")
    default Boolean checkQualified (One one, Integer projId, Integer val, String code) {
        if(one.getProjectId() == projId && one.getVal() == val && one.getCode().equalsIgnoreCase(code)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
</code>```

答:
Currently MapStruct does not support mapping methods with multiple source properties.

However, in your case you can use the @Context from 1.2.0. From what I understand the projId and the code are there just as helper of the mapping, and they are not used to map target properties from.

So you can do something like (It should work in theory):

```<code>@Mapper
public interface OneMapper {

    @Mapping(target="id", source="one.id")
    @Mapping(target="qualified", qualifiedByName="checkQualifiedNamed")
    OneDto createOne (One one, @Context Integer projId, @Context String code);

    @Named("checkQualifiedNamed")
    default Boolean checkQualified (One one, @Context Integer projId, @Context String code) {
        if(one.getProjectId() == projId && one.getCode().equalsIgnoreCase(code)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
</code>```

Another alternative would be to extract all those properties into a separate class and pass that along (this would allow for multiple parameters of the same type).

The class would look like:

```<code>public class Filter {

    private final Integer projId;
    private final Integer val;
    private final String code;

    public Filter (Integer projId, Integer val, String code) {
        this.projId = projId;
        this.val = val;
        this.code = code;
    }

    //getters
}
</code>```

Your mapper will then look like:

```<code>@Mapper
public interface OneMapper {

    @Mapping(target="id", source="one.id")
    @Mapping(target="qualified", qualifiedByName="checkQualifiedNamed")
    OneDto createOne (One one, @Context Filter filter);

    @Named("checkQualifiedNamed")
    default Boolean checkQualified (One one, @Context Filter filter) {
        if(one.getProjectId() == filter.getProjId() && one.getVal() == filter.getVal() && one.getCode().equalsIgnoreCase(filter.getCode())) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
</code>```

You can then call the mapper like: mapper.createOne(one, new Filter(projId, val, code));

Body:
I have come across a situation where my mapping method has 3 parameters, and all the three are being used in deriving one of the properties of the target type.

I have created a default mapping method in the interface keeping the logic for deriving the property, now for calling this method, I could use an expression = "java( /*method call here*/ )" in the @Mapping annotation.

Is there any way to do this with any of the mapstruct annotation like @qualifiedByName, I tried commenting the annotation having expression property and used qualifiedByName, but it doesn't work :

@Mapper
public interface OneMapper {

    @Mapping(target="id", source="one.id")
    //@Mapping(target="qualified",expression = "java( checkQualified (one, projId, code) )")
    @Mapping(target="qualified",qualifiedByName="checkQualifiedNamed")
    OneDto createOne (One one, Integer projId, Integer val, String code);

    @Named("checkQualifiedNamed")
    default Boolean checkQualified (One one, Integer projId, Integer val, String code) {
        if(one.getProjectId() == projId && one.getVal() == val && one.getCode().equalsIgnoreCase(code)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}

Body:
Currently MapStruct does not support mapping methods with multiple source properties.

However, in your case you can use the @Context from 1.2.0. From what I understand the projId and the code are there just as helper of the mapping, and they are not used to map target properties from.

So you can do something like (It should work in theory):

@Mapper
public interface OneMapper {

    @Mapping(target="id", source="one.id")
    @Mapping(target="qualified", qualifiedByName="checkQualifiedNamed")
    OneDto createOne (One one, @Context Integer projId, @Context String code);

    @Named("checkQualifiedNamed")
    default Boolean checkQualified (One one, @Context Integer projId, @Context String code) {
        if(one.getProjectId() == projId && one.getCode().equalsIgnoreCase(code)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}

Another alternative would be to extract all those properties into a separate class and pass that along (this would allow for multiple parameters of the same type).

The class would look like:

public class Filter {

    private final Integer projId;
    private final Integer val;
    private final String code;

    public Filter (Integer projId, Integer val, String code) {
        this.projId = projId;
        this.val = val;
        this.code = code;
    }

    //getters
}

Your mapper will then look like:

@Mapper
public interface OneMapper {

    @Mapping(target="id", source="one.id")
    @Mapping(target="qualified", qualifiedByName="checkQualifiedNamed")
    OneDto createOne (One one, @Context Filter filter);

    @Named("checkQualifiedNamed")
    default Boolean checkQualified (One one, @Context Filter filter) {
        if(one.getProjectId() == filter.getProjId() && one.getVal() == filter.getVal() && one.getCode().equalsIgnoreCase(filter.getCode())) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}

You can then call the mapper like: mapper.createOne(one, new Filter(projId, val, code));


问:
Python sending data to a MySQL DB
I have a script running, updating certain values in a DB once a second.
At the start of the script I first connect to the DB:

```<code>conn = pymysql.connect(host= "server",
               user="user",
               passwd="pw",
               db="db",
               charset='utf8')
x = conn.cursor()
</code>```

I leave the connection open for the running time of the script (around 30min)

With this code I update certain values once every second:

```<code>query = "UPDATE missionFilesDelDro SET landLat = '%s', landLon='%s',landHea='%s' WHERE displayName='%s'" % (lat, lon, heading, mission)
x.execute(query)
conn.ping(True)
</code>```

However now when my Internet connection breaks the script also crashes since It can't update the variables. My connection normally reestablishes within one minute. (the script runs on a vehicle which is moving. Internet connection is established via a GSM Modem)

Is it better to re-open every time the connection to the server prior an update of the variable so I can see if the connection has been established or is there a better way?

答:
You could just ping the connection first, instead of after the query, as that should reconnect if necessary.

Setup:

```<code>conn = pymysql.connect(host= "server",
                       user="user",
                       passwd="pw",
                       db="db",
                       charset='utf8')
</code>```

and every second:

```<code>query = "UPDATE missionFilesDelDro SET landLat = '%s', landLon='%s',landHea='%s' WHERE displayName='%s'" % (lat, lon, heading, mission)
conn.ping()
x = conn.cursor()
x.execute(query)
</code>```

Ref https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/connections.py#L872

It's still possible that the connection could drop after the ping() but before the execute(), which would then fail. For handling that you would need to trap the error, something similar to

```<code>from time import sleep

MAX_ATTEMPTS = 10

# every second:
query = "UPDATE missionFilesDelDro SET landLat = '%s', landLon='%s',landHea='%s' WHERE displayName='%s'" % (lat, lon, heading, mission)
inserted = False
attempts = 0

while (not inserted) and attempts < MAX_ATTEMPTS:
    attempts += 1
    try:
        conn.ping()
        x = conn.cursor()
        x.execute(query)
        inserted = True
    except StandardError: # it would be better to use the specific error, not StandardError
        sleep(10) # however long is appropriate between tries
        # you could also do a whole re-connection here if you wanted

if not inserted:
     # do something
     #raise RuntimeError("Couldn't insert the record after {} attempts.".format(MAX_ATTEMPTS))
     pass
</code>```

Title: Python sending data to a MySQL DB

Body:
I have a script running, updating certain values in a DB once a second.
At the start of the script I first connect to the DB:

conn = pymysql.connect(host= "server",
               user="user",
               passwd="pw",
               db="db",
               charset='utf8')
x = conn.cursor()

I leave the connection open for the running time of the script (around 30min)

With this code I update certain values once every second:

query = "UPDATE missionFilesDelDro SET landLat = '%s', landLon='%s',landHea='%s' WHERE displayName='%s'" % (lat, lon, heading, mission)
x.execute(query)
conn.ping(True)

However now when my Internet connection breaks the script also crashes since It can't update the variables. My connection normally reestablishes within one minute. (the script runs on a vehicle which is moving. Internet connection is established via a GSM Modem)

Is it better to re-open every time the connection to the server prior an update of the variable so I can see if the connection has been established or is there a better way?

Body:
You could just ping the connection first, instead of after the query, as that should reconnect if necessary.

Setup:

conn = pymysql.connect(host= "server",
                       user="user",
                       passwd="pw",
                       db="db",
                       charset='utf8')

and every second:

query = "UPDATE missionFilesDelDro SET landLat = '%s', landLon='%s',landHea='%s' WHERE displayName='%s'" % (lat, lon, heading, mission)
conn.ping()
x = conn.cursor()
x.execute(query)

Ref https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/connections.py#L872

It's still possible that the connection could drop after the ping() but before the execute(), which would then fail. For handling that you would need to trap the error, something similar to

from time import sleep

MAX_ATTEMPTS = 10

# every second:
query = "UPDATE missionFilesDelDro SET landLat = '%s', landLon='%s',landHea='%s' WHERE displayName='%s'" % (lat, lon, heading, mission)
inserted = False
attempts = 0

while (not inserted) and attempts < MAX_ATTEMPTS:
    attempts += 1
    try:
        conn.ping()
        x = conn.cursor()
        x.execute(query)
        inserted = True
    except StandardError: # it would be better to use the specific error, not StandardError
        sleep(10) # however long is appropriate between tries
        # you could also do a whole re-connection here if you wanted

if not inserted:
     # do something
     #raise RuntimeError("Couldn't insert the record after {} attempts.".format(MAX_ATTEMPTS))
     pass


问:
Interface, abstract class and inheriting subclass with same Method, that gets different type arguments, which is used?
I have these interface and classes:

```<code>public interface AlternateLight {

     public String change(long time);
}

public abstract class AbstractLight {

    public String change(int time) {
        return "AbstractLight Method was used";
    }
}

public class DistinctAlternateLight extends AbstractLight implements AlternateLight {

    public String change(long time) {
        return "DistinctAlternateLight Method was used";
    }
}
</code>```

Now I call the method change() with following main-method:

```<code>public class WhatUsedTest {

    public static void main(String[] args) {
        AlternateLight al = new DistinctAlternateLight();
        System.out.println(al.change(100));
    }
}
</code>```

It prints "DistinctAlternateLight Method was used", but why? I thought since I didn't put a "L" behind the 100 as argument, it would call the method of the abstract class, because its method takes integers. With missing out on the "L", I guessed the compiler wouldn't handle the 100 as a long value and call the method taking longs, but it does. Why is that so?

答:
You can also see that the type of "al" object is an interface type, so you can`t call the method from super class without casting, you also can`t call any method from AbstractLight without casting. You can only call methods there were declared in interface class. In that case, compiler will favour the method from the interface class.
You can force the compiler to call a method from abstract class if you write something like that:</p>

```<code>System.out.println(((AbstractLight)al).change(100));
</code>```

Body:
I have these interface and classes:

public interface AlternateLight {

     public String change(long time);
}

public abstract class AbstractLight {

    public String change(int time) {
        return "AbstractLight Method was used";
    }
}

public class DistinctAlternateLight extends AbstractLight implements AlternateLight {

    public String change(long time) {
        return "DistinctAlternateLight Method was used";
    }
}

Now I call the method change() with following main-method:

public class WhatUsedTest {

    public static void main(String[] args) {
        AlternateLight al = new DistinctAlternateLight();
        System.out.println(al.change(100));
    }
}

It prints "DistinctAlternateLight Method was used", but why? I thought since I didn't put a "L" behind the 100 as argument, it would call the method of the abstract class, because its method takes integers. With missing out on the "L", I guessed the compiler wouldn't handle the 100 as a long value and call the method taking longs, but it does. Why is that so?

Body:
You can also see that the type of "al" object is an interface type, so you can`t call the method from super class without casting, you also can`t call any method from AbstractLight without casting. You can only call methods there were declared in interface class. In that case, compiler will favour the method from the interface class.
You can force the compiler to call a method from abstract class if you write something like that:

System.out.println(((AbstractLight)al).change(100));


问:
Converting Java date string to JavaScript date
Is there any JavaScript library that takes Java's SimpleDateFormat pattern and parses a date/time string into a Date object?

For example, given "2010-12-20" and "yyyy-MM-dd", the function would parse "2010-12-20" and return a JavaScript Date.

I noticed that jQuery UI's Date Picker can format and parse a date string, but it doesn't work with a time string.

Thanks.

答: I would try the Datejs library: http://www.datejs.com/</p>

ContentLicense: CC BY-SA 2.5


问:
Loop wregex always return false and high cpu usage around 50%
I have a bunch keyword need to loop to match a wchar_t string.

the string is

5698@#$%notepad^&343235/ chrome $56&6556firefox$%#$23

and the keyword is

notepad, chrome, firefox

I try to loop it always return FALSE and when i see cpu usage. it so extensive around 50%.

this the code.

```<code>            unsigned int i;

            wchar_t * keyword[] = {L"chrome", L"notepad", L"firefox");

            for (i = 0; i < 3; i++)
            {
                wchar_t * s = L"5698@#$%notepad^&343235/ chrome $56&6556firefox$%#$23";

                wcmatch m;

                wchar_t regex[MAX_PATH];

                swprintf(regex, MAX_PATH, L"%s%s", L".+", keyword[i]);

                wregex r(regex);

                if (regex_search(s, m, r))
                {
                    cout << "It's found" << endl;
                }

                else
                {
                    cout << "It's not found" << endl;
                }
</code>```

thsi my real project code. enumerate process and match the process and return bool value.

```<code>#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <Psapi.h>
#include <string>
#include <regex>

using namespace std;

int main()
{
    FILE *pFile;
    wchar_t *file = L"d:\\a.txt";
    wchar_t line[100][MAX_PATH];
    unsigned int a = 0;
    if (_wfopen_s(&pFile, file, L"r, ccs = UNICODE") == 0)
    {
        while (fgetws(line[a], 100, pFile))
        {
            a++;
        }
    }

    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;

    if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
    {
        return 1;
    }

    cProcesses = cbNeeded / sizeof(DWORD);

    wchar_t jszProcessName[4096] = { 0 };

    for (i = 0; i < cProcesses; i++)
    {
        if (aProcesses[i] != 0)
        {
            wchar_t szProcessName[MAX_PATH] = TEXT("Unknown");
            DWORD processID = aProcesses[i];

            HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
                                        PROCESS_VM_READ,
                                        FALSE, processID);

            if (NULL != hProcess)
            {
                HMODULE hMod;
                DWORD cbNeeded;

                if (EnumProcessModules(hProcess, &hMod, sizeof(hMod),
                    &cbNeeded))
                {
                    GetModuleBaseName(hProcess, hMod, szProcessName,
                        sizeof(szProcessName) / sizeof(TCHAR));

                    wcsncat_s(jszProcessName,szProcessName , 1000);

                }
            }
        }
    }

    unsigned int c;

        for (c = 0; c < a; c++)
        {
            wchar_t * s = jszProcessName;

            wcmatch m;

            wchar_t regex[MAX_PATH];

            swprintf(regex, MAX_PATH, L"%s%s", L".+", line[c]);

            wregex r(regex);

            if (regex_search(s, m, r))
            {
                cout << "It's found" << endl;
            }

            else
            {
                cout << "It's not found" << endl;
            }

        }

    return 0;
}
</code>```

答:
have your regex keywords separated by | characters:

```<code>(notepad|chrome|firefox)
</code>```

https://regex101.com/r/PAZBbx/1

Body:
I have a bunch keyword need to loop to match a wchar_t string.

the string is

5698@#$%notepad^&343235/ chrome $56&6556firefox$%#$23

and the keyword is

notepad, chrome, firefox

I try to loop it always return FALSE and when i see cpu usage. it so extensive around 50%.

this the code.

            unsigned int i;

            wchar_t * keyword[] = {L"chrome", L"notepad", L"firefox");

            for (i = 0; i < 3; i++)
            {
                wchar_t * s = L"5698@#$%notepad^&343235/ chrome $56&6556firefox$%#$23";

                wcmatch m;

                wchar_t regex[MAX_PATH];

                swprintf(regex, MAX_PATH, L"%s%s", L".+", keyword[i]);

                wregex r(regex);

                if (regex_search(s, m, r))
                {
                    cout << "It's found" << endl;
                }

                else
                {
                    cout << "It's not found" << endl;
                }

thsi my real project code. enumerate process and match the process and return bool value.

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <Psapi.h>
#include <string>
#include <regex>

using namespace std;

int main()
{
    FILE *pFile;
    wchar_t *file = L"d:\\a.txt";
    wchar_t line[100][MAX_PATH];
    unsigned int a = 0;
    if (_wfopen_s(&pFile, file, L"r, ccs = UNICODE") == 0)
    {
        while (fgetws(line[a], 100, pFile))
        {
            a++;
        }
    }

    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;

    if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
    {
        return 1;
    }

    cProcesses = cbNeeded / sizeof(DWORD);

    wchar_t jszProcessName[4096] = { 0 };

    for (i = 0; i < cProcesses; i++)
    {
        if (aProcesses[i] != 0)
        {
            wchar_t szProcessName[MAX_PATH] = TEXT("Unknown");
            DWORD processID = aProcesses[i];

            HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
                                        PROCESS_VM_READ,
                                        FALSE, processID);

            if (NULL != hProcess)
            {
                HMODULE hMod;
                DWORD cbNeeded;

                if (EnumProcessModules(hProcess, &hMod, sizeof(hMod),
                    &cbNeeded))
                {
                    GetModuleBaseName(hProcess, hMod, szProcessName,
                        sizeof(szProcessName) / sizeof(TCHAR));

                    wcsncat_s(jszProcessName,szProcessName , 1000);

                }
            }
        }
    }

    unsigned int c;

        for (c = 0; c < a; c++)
        {
            wchar_t * s = jszProcessName;

            wcmatch m;

            wchar_t regex[MAX_PATH];

            swprintf(regex, MAX_PATH, L"%s%s", L".+", line[c]);

            wregex r(regex);

            if (regex_search(s, m, r))
            {
                cout << "It's found" << endl;
            }

            else
            {
                cout << "It's not found" << endl;
            }

        }

    return 0;
}

Body:
have your regex keywords separated by | characters:

(notepad|chrome|firefox)

https://regex101.com/r/PAZBbx/1


问:
Angular4/Javascript Date changing after Date constructor call with timezone
On my Angular 4 application I'm getting an date from my API call as '1990-03-31T23:00:00-06:00' string but when try to create a Date object and do getMonth() I'm getting the wrong day. After testing around in the console:

```<code>> var x = new Date('1990-03-31T23:00:00-06:00');
undefined
 > x
Sun Apr 01 1990 00:00:00 GMT-0500 (Central Daylight Time)
> var x = new Date('1990-03-31T23:00:00');
Sat Mar 31 1990 23:00:00 GMT-0500 (Central Daylight Time)
> new Date().getTimezoneOffset();
360
</code>```

and here's my code:

new Date(this.bsSelected.StatementDate).getMonth()

Not sure why this happening and how to avoid it. My temporary solution is to remove the TimeZone from the API output but I wonder if I understood the problem I could come up with a better solution.

答:
JavaScript always converts to your local timezone when you use the Date object. If you don't need the timezone information you can do what you are already doing to strip it from the data.
If you need to preserve timezone information you can use a third part library like Moment Timezone.</p>

Body:
On my Angular 4 application I'm getting an date from my API call as '1990-03-31T23:00:00-06:00' string but when try to create a Date object and do getMonth() I'm getting the wrong day. After testing around in the console:

> var x = new Date('1990-03-31T23:00:00-06:00');
undefined
 > x
Sun Apr 01 1990 00:00:00 GMT-0500 (Central Daylight Time)
> var x = new Date('1990-03-31T23:00:00');
Sat Mar 31 1990 23:00:00 GMT-0500 (Central Daylight Time)
> new Date().getTimezoneOffset();
360

and here's my code:

new Date(this.bsSelected.StatementDate).getMonth()

Not sure why this happening and how to avoid it. My temporary solution is to remove the TimeZone from the API output but I wonder if I understood the problem I could come up with a better solution.


问:
javascript replace text inside of parenthases
I'm trying to replace text inside of parenthases with the same text surrounded by my text between parenthases

```<code>text.replace(/\[([^\][]+)]/g, "<span class='font-weight-bold underline'>$1</span>")
</code>```

so If I have this is my [name]
It replaces it to this is my name

I need something similar for parentheses.

How can I replace text globally between parentheses? It's not a simple as I thought it would be.

答:
Try this...</p>

```<code>text.replace(/ *\([^)]*\) */g, "<span class='font-weight-bold underline'>$1</span>");
</code>```

Body:
I'm trying to replace text inside of parenthases with the same text surrounded by my text between parenthases

text.replace(/\[([^\][]+)]/g, "$1")

so If I have this is my [name]
It replaces it to this is my name

I need something similar for parentheses.

How can I replace text globally between parentheses? It's not a simple as I thought it would be.

Body:
Try this...

text.replace(/ *\([^)]*\) */g, "<span class='font-weight-bold underline'>$1</span>");


问:
How to install a specific version of Angular with Angular CLI?
I searched through google and angular cli doc but couldn't find any way to install a specific version of Angular using Angular CLI. is it even possible?</p>

答:
Specify the version you want in the 'dependencies' section of your package.json, then from your root project folder in the console/terminal run this:

```<code>npm install
</code>```

For example, the following will specifically install v4.3.4

```<code>"dependencies": {
    "@angular/common": "4.3.4",
    "@angular/compiler": "4.3.4",
    "@angular/core": "4.3.4",
    "@angular/forms": "4.3.4",
    "@angular/http": "4.3.4",
    "@angular/platform-browser": "4.3.4",
    "@angular/platform-browser-dynamic": "4.3.4",
    "@angular/router": "4.3.4",
  }
</code>```

You can also add the following modifiers to the version number to vary how specific you need the version to be:

caret ^

Updates you to the most recent major version, as specified by the first number:

```<code>^4.3.0
</code>```

will load the latest 4.x.x release, but will not load 5.x.x

tilde ~

Update you to the most recent minor version, as specified by the second number:

```<code>~4.3.0
</code>```

will load the latest 4.3.x release, but will not load 4.4.x

Body:
Specify the version you want in the 'dependencies' section of your package.json, then from your root project folder in the console/terminal run this:

npm install

For example, the following will specifically install v4.3.4

"dependencies": {
    "@angular/common": "4.3.4",
    "@angular/compiler": "4.3.4",
    "@angular/core": "4.3.4",
    "@angular/forms": "4.3.4",
    "@angular/http": "4.3.4",
    "@angular/platform-browser": "4.3.4",
    "@angular/platform-browser-dynamic": "4.3.4",
    "@angular/router": "4.3.4",
  }

You can also add the following modifiers to the version number to vary how specific you need the version to be:

caret ^

Updates you to the most recent major version, as specified by the first number:

^4.3.0

will load the latest 4.x.x release, but will not load 5.x.x

tilde ~

Update you to the most recent minor version, as specified by the second number:

~4.3.0

will load the latest 4.3.x release, but will not load 4.4.x


问:
How to connect to a local database in SQL Server Management Studio?
I have downloaded the SQL Server Management Studio (SSMS) 2016 to recover a huge .bak file which is an old backup of a database. But first of all I need to connect to a DB Server.

After install, I execute SSMS and it asks me to connect to a DB Server. I don't have any and I saw that it is possible to create a "local" db by typing only a dot '.' for Server Name and use Windows authentication.

It is not working; how to do it?

答:
Open SSMS -> Connect

Server name: (LocalDb)\MSSQLLocalDB,

Choose Windows Authentication.

For a reference:


问:
Error when creating dictionaries from text files
I've been working on a function which will update two dictionaries (similar authors, and awards they've won) from an open text file. The text file looks something like this:

```<code>Brabudy, Ray
Hugo Award
Nebula Award
Saturn Award
Ellison, Harlan
Heinlein, Robert
Asimov, Isaac
Clarke, Arthur

Ellison, Harlan
Nebula Award
Hugo Award
Locus Award
Stephenson, Neil
Vonnegut, Kurt
Morgan, Richard
Adams, Douglas
</code>```

And so on. The first name is an authors name (last name first, first name last), followed by awards they may have won, and then authors who are similar to them. This is what I've got so far:

```<code>def load_author_dicts(text_file, similar_authors, awards_authors):
    name_of_author = True
    awards = False
    similar = False
    for line in text_file:
        if name_of_author:
            author = line.split(', ')
            nameA = author[1].strip() + ' ' + author[0].strip()
            name_of_author = False
            awards = True
            continue
        if awards:
            if ',' in line:
                awards = False
                similar = True
            else:
                if nameA in awards_authors:
                    listawards = awards_authors[nameA]
                    listawards.append(line.strip())
                else:
                    listawards = []
                    listawards.append(line.strip()
                    awards_authors[nameA] = listawards
        if similar:
            if line == '\n':
                similar = False
                name_of_author = True
            else:
                sim_author = line.split(', ')
                nameS = sim_author[1].strip() + ' ' + sim_author[0].strip()
                if nameA in similar_authors:
                    similar_list = similar_authors[nameA]
                    similar_list.append(nameS)
                else:
                    similar_list = []
                    similar_list.append(nameS)
                    similar_authors[nameA] = similar_list
                continue
</code>```

This works great! However, if the text file contains an entry with just a name (i.e. no awards, and no similar authors), it screws the whole thing up, generating an IndexError: list index out of range at this part Zname = sim_author[1].strip()+" "+sim_author[0].strip() )

How can I fix this? Maybe with a 'try, except function' in that area?

Also, I wouldn't mind getting rid of those continue functions, I wasn't sure how else to keep it going. I'm still pretty new to this, so any help would be much appreciated! I keep trying stuff and it changes another section I didn't want changed, so I figured I'd ask the experts.

答:
How about doing it this way, just to get the data in, then manipulate the dictionary any ways you want.

test.txt contains your data

```<code>Brabudy, Ray
Hugo Award
Nebula Award
Saturn Award
Ellison, Harlan
Heinlein, Robert
Asimov, Isaac
Clarke, Arthur

Ellison, Harlan
Nebula Award
Hugo Award
Locus Award
Stephenson, Neil
Vonnegut, Kurt
Morgan, Richard
Adams, Douglas
</code>```

And my code to parse it.

award_parse.py

```<code>data = {}
name = ""
awards = []

f = open("test.txt")

for l in f:
    # make sure the line is not blank don't process blank lines
    if not l.strip() == "":

        # if this is a name and we're not already working on an author then set the author
        # otherwise treat this as a new author and set the existing author to a key in the dictionary
        if "," in l and len(name) == 0:
            name = l.strip()

        elif "," in l and len(name) > 0:
            # check to see if recipient is already in list, add to end of existing list if he/she already
            # exists.
            if not name.strip() in data:
                data[name] = awards
            else:
                data[name].extend(awards)

            name = l.strip()
            awards = []

        # process any lines that are not blank, and do not have a ,
        else:
            awards.append(l.strip())

f.close()

for k, v in data.items():
    print("%s got the following awards: %s" % (k,v))
</code>```

Body:
I've been working on a function which will update two dictionaries (similar authors, and awards they've won) from an open text file. The text file looks something like this:

Brabudy, Ray
Hugo Award
Nebula Award
Saturn Award
Ellison, Harlan
Heinlein, Robert
Asimov, Isaac
Clarke, Arthur

Ellison, Harlan
Nebula Award
Hugo Award
Locus Award
Stephenson, Neil
Vonnegut, Kurt
Morgan, Richard
Adams, Douglas

And so on. The first name is an authors name (last name first, first name last), followed by awards they may have won, and then authors who are similar to them. This is what I've got so far:

def load_author_dicts(text_file, similar_authors, awards_authors):
    name_of_author = True
    awards = False
    similar = False
    for line in text_file:
        if name_of_author:
            author = line.split(', ')
            nameA = author[1].strip() + ' ' + author[0].strip()
            name_of_author = False
            awards = True
            continue
        if awards:
            if ',' in line:
                awards = False
                similar = True
            else:
                if nameA in awards_authors:
                    listawards = awards_authors[nameA]
                    listawards.append(line.strip())
                else:
                    listawards = []
                    listawards.append(line.strip()
                    awards_authors[nameA] = listawards
        if similar:
            if line == '\n':
                similar = False
                name_of_author = True
            else:
                sim_author = line.split(', ')
                nameS = sim_author[1].strip() + ' ' + sim_author[0].strip()
                if nameA in similar_authors:
                    similar_list = similar_authors[nameA]
                    similar_list.append(nameS)
                else:
                    similar_list = []
                    similar_list.append(nameS)
                    similar_authors[nameA] = similar_list
                continue

This works great! However, if the text file contains an entry with just a name (i.e. no awards, and no similar authors), it screws the whole thing up, generating an IndexError: list index out of range at this part Zname = sim_author[1].strip()+" "+sim_author[0].strip() )

How can I fix this? Maybe with a 'try, except function' in that area?

Also, I wouldn't mind getting rid of those continue functions, I wasn't sure how else to keep it going. I'm still pretty new to this, so any help would be much appreciated! I keep trying stuff and it changes another section I didn't want changed, so I figured I'd ask the experts.

Body:
How about doing it this way, just to get the data in, then manipulate the dictionary any ways you want.

test.txt contains your data

Brabudy, Ray
Hugo Award
Nebula Award
Saturn Award
Ellison, Harlan
Heinlein, Robert
Asimov, Isaac
Clarke, Arthur

Ellison, Harlan
Nebula Award
Hugo Award
Locus Award
Stephenson, Neil
Vonnegut, Kurt
Morgan, Richard
Adams, Douglas

And my code to parse it.

award_parse.py

data = {}
name = ""
awards = []

f = open("test.txt")

for l in f:
    # make sure the line is not blank don't process blank lines
    if not l.strip() == "":

        # if this is a name and we're not already working on an author then set the author
        # otherwise treat this as a new author and set the existing author to a key in the dictionary
        if "," in l and len(name) == 0:
            name = l.strip()

        elif "," in l and len(name) > 0:
            # check to see if recipient is already in list, add to end of existing list if he/she already
            # exists.
            if not name.strip() in data:
                data[name] = awards
            else:
                data[name].extend(awards)

            name = l.strip()
            awards = []

        # process any lines that are not blank, and do not have a ,
        else:
            awards.append(l.strip())

f.close()

for k, v in data.items():
    print("%s got the following awards: %s" % (k,v))


问:
nHibernate Zero or One to one using mapping by code
I am modelling a person and a death certificate where a person can have zero or one death certificates. If I have:

```<code>public class Person
{
  public string PersonId { get; set; }
  public virtual DeathCertificate { get; set; }
}
</code>```

and:

```<code>public class DeathCertificate
{
  public string DeathCertificateId { get; set; }
  public string PersonId { get; set; }
  public virtual Person { get; set; }
}
</code>```

Where DeathCertificateId is the primary key of DeathCertificate in the database.

With the following in the mapping for the person:

```<code>  this.OneToOne(
    entity => entity.DeathCertificate,
    mapper =>
    {
      mapper.Access(Accessor.Property);
      mapper.Cascade(Cascade.Detach | Cascade.Persist);
      mapper.PropertyReference(p => p.Person);
      mapper.Constrained(false);
    });
</code>```

And this for the death certificate:

```<code>  this.ManyToOne(
    entity => entity.Person,
    mapper =>
    {
      mapper.Column("PERSON_ID");
      mapper.Cascade(Cascade.None);
      mapper.Unique(true);
    });
</code>```

Unfortunately, this generates SQL similar to the following whenever I query person whether I join it in or not:

```<code>select ...
from person p
left outer join deathcertificate dc
   on dc.person_id = p.person_id
where p.person_id = 'ABC123'
</code>```

So it all works, but I only want a death certificate when I explicitly join it in.

I think I've got something wrong in my mappings. Can anyone help?

答:
Changing:

```<code>mapper.Constrained(false);
</code>```

to

```<code>mapper.Constrained(true);
</code>```

on the DeathCertificate mapping fixed my problem.

See https://ayende.com/blog/3960/nhibernate-mapping-one-to-one for details.

Body:
I am modelling a person and a death certificate where a person can have zero or one death certificates. If I have:

public class Person
{
  public string PersonId { get; set; }
  public virtual DeathCertificate { get; set; }
}

and:

public class DeathCertificate
{
  public string DeathCertificateId { get; set; }
  public string PersonId { get; set; }
  public virtual Person { get; set; }
}

Where DeathCertificateId is the primary key of DeathCertificate in the database.

With the following in the mapping for the person:

  this.OneToOne(
    entity => entity.DeathCertificate,
    mapper =>
    {
      mapper.Access(Accessor.Property);
      mapper.Cascade(Cascade.Detach | Cascade.Persist);
      mapper.PropertyReference(p => p.Person);
      mapper.Constrained(false);
    });

And this for the death certificate:

  this.ManyToOne(
    entity => entity.Person,
    mapper =>
    {
      mapper.Column("PERSON_ID");
      mapper.Cascade(Cascade.None);
      mapper.Unique(true);
    });

Unfortunately, this generates SQL similar to the following whenever I query person whether I join it in or not:

select ...
from person p
left outer join deathcertificate dc
   on dc.person_id = p.person_id
where p.person_id = 'ABC123'

So it all works, but I only want a death certificate when I explicitly join it in.

I think I've got something wrong in my mappings. Can anyone help?

Body:
Changing:

mapper.Constrained(false);

to

mapper.Constrained(true);

on the DeathCertificate mapping fixed my problem.

See https://ayende.com/blog/3960/nhibernate-mapping-one-to-one for details.


问:
Django: List all where one field combines all its unique values
I got stuck. Problem I have is that I would like to create a list of objects.all() but where all objects, where one ForeignKey is the same, should be combined to one entry in a list.

My Model:

```<code>class TournamentStandings(models.Model):
    tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE)
    player = models.ForeignKey(Player, on_delete=models.CASCADE)
    player_place = models.FloatField(verbose_name=u"Place")
</code>```

The list I would like to get is something like this:

ID | Player | Tournament| Place
1 | Name_1 | Tournament_1, Tournament_2| Place_on_tournament_1, P_o_t_2
2 |Name_2 |Tournament_1, Tournament_2| Place_on_tournament_1, P_o_t_2

So the ForeignKey(Player) would be the one I would like to limit and combine entries. I tried the generic view for objects.all() and the loop in my template:

```<code>{% for player in ranking_list %}
  <tr>
    <td>{{ ranking_list.id }}</td>
    <td>{{ ranking_list.player }}</td>
    <td>{{ ranking_list.tournament }}</td>
    <td> {{ ranking_list.player_place }} </td>
  </tr>
{% endfor %}
</code>```

It didn't work. Any hints ??

答: Add an order_by to your query so that standings for the same player are sequential, and pass the result into itertools.groupby to get "sublists" (all standings for the same player grouped together). You can then process/format those in any way you like.

Body:
I got stuck. Problem I have is that I would like to create a list of objects.all() but where all objects, where one ForeignKey is the same, should be combined to one entry in a list.

My Model:

class TournamentStandings(models.Model):
    tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE)
    player = models.ForeignKey(Player, on_delete=models.CASCADE)
    player_place = models.FloatField(verbose_name=u"Place")

The list I would like to get is something like this:

ID | Player | Tournament| Place
1 | Name_1 | Tournament_1, Tournament_2| Place_on_tournament_1, P_o_t_2
2 |Name_2 |Tournament_1, Tournament_2| Place_on_tournament_1, P_o_t_2

So the ForeignKey(Player) would be the one I would like to limit and combine entries. I tried the generic view for objects.all() and the loop in my template:

{% for player in ranking_list %}

    {{ ranking_list.id }}
    {{ ranking_list.player }}
    {{ ranking_list.tournament }}
     {{ ranking_list.player_place }}

{% endfor %}

It didn't work. Any hints ??


问:
Shiny: unwanted space added by plotOutput() and/or renderPlot()
Either plotOutput or renderPlot seems to add a bunch of extra white space around a plot. I've added background colours to the plot and the layout column to illustrate this. Essentially, I would like to be completely rid of this white space, leaving only the area coloured in blue, which should then align itself to the left of the column.

I know that this can be adjusted using the width argument, but having it a either 100% or auto doesn't seem to work properly.

Thanks!

```<code>library(shiny)
library(ggplot2)

# Create sample data
animals <- as.data.frame(
  table(Species =
          c(rep("Moose", sample(1:100, 1)),
            rep("Frog", sample(1:100, 1)),
            rep("Dragonfly", sample(1:100, 1))
          )))

server <- function(input, output) {

  output$pieChart <- renderPlot({

    # Create pie chart
    ggplot(animals, aes(x = "", y = Freq, fill = Species)) +
      geom_bar(width = 1, stat = "identity") +
      coord_polar("y", start=0) +
      theme(plot.background = element_rect(fill = "lightblue"))
  })
}

ui <- fluidPage(

  fluidRow(
    column(4,
           style = "background-color:lightgreen",
           align = "left",
           HTML("filler<br>"),
           plotOutput("pieChart")
    )
  )
)

shinyApp(ui = ui, server = server)
</code>```

答:
I had a similar, but not identical, issue with a map. I knew what aspect ratio I wanted in the map (exactly 1:1 for me), much like you have with your pie chart, and I wanted it to occupy as much of the width of the responsive column as it could, changing the height accordingly. However, I didn't want it to be too big, so I added a line of logic to cap it to 400 pixels wide.

My approach was to draw a dummy ggplot object that was invisible, then query the client session to learn about its size. Then I could pass that size as an explicit parameter to the actual desired plot.

```<code># you need to include `session` as a third argument here
server <- function(input, output, session) {

  # blank (plot for width) ----
  output$blank <- renderPlot({
    ggplot(data.frame(x = 1), aes(NA, NA)) + geom_blank() + theme_void()
  })

  blankwidth <- reactive({
          # this is the magic that makes it work
    bw <- session$clientData$output_blank_width
    if (bw > 400) 400 else bw
  })

  blankheight <- reactive({
    blankwidth() / 1.25
    # whatever aspect ratio you need
  })

  output$plotofinterest <- renderPlot({
    ggplot(iris[sample.int(150,50),], aes(1, fill = Species)) +
      geom_bar() + coord_polar(theta = "y")
  }, height = blankheight, width = blankwidth)
     # this is the necessary bit
}

# ui.R

ui <- fluidPage(
  fluidRow(
    column(4,
           style = "background-color:lightgreen",
           plotOutput('blank', width = '100%', height = 0),
           plotOutput('plotofinterest', inline = T)
    ),
    column(8,
           style = "background-color:lightblue",
           HTML("filler")
    )
  )
)

shinyApp(ui, server)
</code>```

If you make the window narrower, the plot will be less than the 400px cap, and it will take up the whole column. If you make it wider, the right-side green space gets larger. I haven't noticed a big loss of performance from drawing extra plots to get this info back from the client. Even when you drag around the window size to play with it, it updates quite quickly.

You do need to figure out what aspect ratio you want it drawn at. grid will automatically add whitespace like Claus explained to the unrestricted pair of margins, so it's fair to just kind of eyeball it until it looks good to you.

Body:
Either plotOutput or renderPlot seems to add a bunch of extra white space around a plot. I've added background colours to the plot and the layout column to illustrate this. Essentially, I would like to be completely rid of this white space, leaving only the area coloured in blue, which should then align itself to the left of the column.

I know that this can be adjusted using the width argument, but having it a either 100% or auto doesn't seem to work properly.

Thanks!

library(shiny)
library(ggplot2)

# Create sample data
animals <- as.data.frame(
  table(Species =
          c(rep("Moose", sample(1:100, 1)),
            rep("Frog", sample(1:100, 1)),
            rep("Dragonfly", sample(1:100, 1))
          )))

server <- function(input, output) {

  output$pieChart <- renderPlot({

    # Create pie chart
    ggplot(animals, aes(x = "", y = Freq, fill = Species)) +
      geom_bar(width = 1, stat = "identity") +
      coord_polar("y", start=0) +
      theme(plot.background = element_rect(fill = "lightblue"))
  })
}

ui <- fluidPage(

  fluidRow(
    column(4,
           style = "background-color:lightgreen",
           align = "left",
           HTML("filler
"),
           plotOutput("pieChart")
    )
  )
)

shinyApp(ui = ui, server = server)

Body:
I had a similar, but not identical, issue with a map. I knew what aspect ratio I wanted in the map (exactly 1:1 for me), much like you have with your pie chart, and I wanted it to occupy as much of the width of the responsive column as it could, changing the height accordingly. However, I didn't want it to be too big, so I added a line of logic to cap it to 400 pixels wide.

My approach was to draw a dummy ggplot object that was invisible, then query the client session to learn about its size. Then I could pass that size as an explicit parameter to the actual desired plot.

# you need to include `session` as a third argument here
server <- function(input, output, session) {

  # blank (plot for width) ----
  output$blank <- renderPlot({
    ggplot(data.frame(x = 1), aes(NA, NA)) + geom_blank() + theme_void()
  })

  blankwidth <- reactive({
          # this is the magic that makes it work
    bw <- session$clientData$output_blank_width
    if (bw > 400) 400 else bw
  })

  blankheight <- reactive({
    blankwidth() / 1.25
    # whatever aspect ratio you need
  })

  output$plotofinterest <- renderPlot({
    ggplot(iris[sample.int(150,50),], aes(1, fill = Species)) +
      geom_bar() + coord_polar(theta = "y")
  }, height = blankheight, width = blankwidth)
     # this is the necessary bit
}

# ui.R

ui <- fluidPage(
  fluidRow(
    column(4,
           style = "background-color:lightgreen",
           plotOutput('blank', width = '100%', height = 0),
           plotOutput('plotofinterest', inline = T)
    ),
    column(8,
           style = "background-color:lightblue",
           HTML("filler")
    )
  )
)

shinyApp(ui, server)

If you make the window narrower, the plot will be less than the 400px cap, and it will take up the whole column. If you make it wider, the right-side green space gets larger. I haven't noticed a big loss of performance from drawing extra plots to get this info back from the client. Even when you drag around the window size to play with it, it updates quite quickly.

You do need to figure out what aspect ratio you want it drawn at. grid will automatically add whitespace like Claus explained to the unrestricted pair of margins, so it's fair to just kind of eyeball it until it looks good to you.


答:
It's due to the polymorphism, if you declare your variable with AlternateLight class and this type has only acces to change(long time).

be careful. If you use interface as reference type and assign an object of implementing class to it then you can call only those methods that are declared inside the interface. This is quite obvious because the implementing class can define methods of its own that are not a part of the contract between the interface and class. So, to call those methods you have to use the class as reference type as following:

```<code>DistinctAlternateLight al =new DistinctAlternateLight();
</code>```

Title: Interface, abstract class and inheriting subclass with same Method, that gets different type arguments, which is used?

Body:
It's due to the polymorphism, if you declare your variable with AlternateLight class and this type has only acces to change(long time).

be careful. If you use interface as reference type and assign an object of implementing class to it then you can call only those methods that are declared inside the interface. This is quite obvious because the implementing class can define methods of its own that are not a part of the contract between the interface and class. So, to call those methods you have to use the class as reference type as following:

DistinctAlternateLight al =new DistinctAlternateLight();


问:
Using Java merge to sum a number in a Map<String, Map<String, Integer>>
I have a variable

Map<String, Map<String, Integer>> movieToStateCount

It will look a little bit like

```<code>"movieToStateCount": {
    "Monster's Inc": {
        "Alabama": 1500,
        "Ohio": 5,
        "Hawaii": 715
    },
    "Wall-E": {
        "Alabama": 30000,
        "Ohio": 5000,
        "Hawaii": 14589
    }
}
</code>```

The way that I get these numbers is by iterating over a database such that whenever I get a new entry I want to add 1 to my Integer in my movieToStateCount. If I were just updating stateCount I could do something like

stateCount.merge(state, 1, Integer::sum);

But, is there a way to do this merge over the map of maps? Or, do I need to just go in and do the null check myself?

Thanks,

答:
Came up with the following function and a little test in main method:

```<code>public static void main(String[] args) {
    final Map<String, Map<String, Integer>> movieToStateCount = new HashMap<>();
    addTo(movieToStateCount, "Oldboy", "Texas");
    addTo(movieToStateCount, "Oldboy", "Texas");
    addTo(movieToStateCount, "Oldboy", "Alabama");
    addTo(movieToStateCount, "LOTR", "Somewhere");
    System.out.println(movieToStateCount);
  }

  private static void addTo(final Map<String, Map<String, Integer>> movieToStateCount,
          final String movie, final String state) {
    movieToStateCount.merge(movie, new HashMap<String, Integer>() {{ put(state, 1); }},
        (m1, m2) -> { m1.put(state, m1.getOrDefault(state, 0) + m2.get(state)); return m1; });
  }
</code>```

Regarding the original question, didn't come up with a solution that would allow not to check for null, because getOrDefault effectively does that.

Body:
I have a variable

Map<String, Map<String, Integer>> movieToStateCount

It will look a little bit like

"movieToStateCount": {
    "Monster's Inc": {
        "Alabama": 1500,
        "Ohio": 5,
        "Hawaii": 715
    },
    "Wall-E": {
        "Alabama": 30000,
        "Ohio": 5000,
        "Hawaii": 14589
    }
}

The way that I get these numbers is by iterating over a database such that whenever I get a new entry I want to add 1 to my Integer in my movieToStateCount. If I were just updating stateCount I could do something like

stateCount.merge(state, 1, Integer::sum);

But, is there a way to do this merge over the map of maps? Or, do I need to just go in and do the null check myself?

Thanks,

Body:
Came up with the following function and a little test in main method:

public static void main(String[] args) {
    final Map<String, Map<String, Integer>> movieToStateCount = new HashMap<>();
    addTo(movieToStateCount, "Oldboy", "Texas");
    addTo(movieToStateCount, "Oldboy", "Texas");
    addTo(movieToStateCount, "Oldboy", "Alabama");
    addTo(movieToStateCount, "LOTR", "Somewhere");
    System.out.println(movieToStateCount);
  }

  private static void addTo(final Map<String, Map<String, Integer>> movieToStateCount,
          final String movie, final String state) {
    movieToStateCount.merge(movie, new HashMap<String, Integer>() {{ put(state, 1); }},
        (m1, m2) -> { m1.put(state, m1.getOrDefault(state, 0) + m2.get(state)); return m1; });
  }

Regarding the original question, didn't come up with a solution that would allow not to check for null, because getOrDefault effectively does that.


问:
Python: check whether a word is spelled correctly
I'm looking for a an easy way to check whether a certain string is a correctly-spelled English word. For example, 'looked' would return True while 'hurrr' would return False. I don't need spelling suggestions or any spelling-correcting features. Just a simple function that takes a string and returns a boolean value.</p>

答:
I was looking for the same functionality and struggled to find an existing library that works in Windows, 64 bit. PyEnchant, although a great library, isn't currently active and doesn't work in 64 bit. Other libraries I found didn't work in Windows.

I finally found a solution that I hope others will find valuable.

The solution...

Use nltk

Extract the word list from nltk.corpus.brown

Convert the word list to a set (for efficient searching)

Use the in keyword to determine if your string is in the set

```<code>from nltk.corpus import brown
word_list = brown.words()
word_set = set(word_list)

# Check if word is in set
"looked" in word_set  # Returns True
"hurrr" in word_set  # Returns False
</code>```

Use a timer check and you'll see this takes virtually no time to search the set. A test on 1,000 words took 0.004 seconds.

Body:
I was looking for the same functionality and struggled to find an existing library that works in Windows, 64 bit. PyEnchant, although a great library, isn't currently active and doesn't work in 64 bit. Other libraries I found didn't work in Windows.

I finally found a solution that I hope others will find valuable.

The solution...

Use nltk

Extract the word list from nltk.corpus.brown

Convert the word list to a set (for efficient searching)

Use the in keyword to determine if your string is in the set

from nltk.corpus import brown
word_list = brown.words()
word_set = set(word_list)

# Check if word is in set
"looked" in word_set  # Returns True
"hurrr" in word_set  # Returns False

Use a timer check and you'll see this takes virtually no time to search the set. A test on 1,000 words took 0.004 seconds.


问:
Exclude entities based on property IsDeleted value when loading from DbSet<TEntity>
I'm using entity framework and in my context I've done some stuff like:

```<code>public override int SaveChanges()
{
    foreach (var entry in ChangeTracker.Entries())
    {
        if (entry.Entity is Base entity)
        {
            if (entry.State == EntityState.Added)
            {
                entity.Created = DateTime.UtcNow;
                entity.Modified = DateTime.UtcNow;
            }
            else if (entry.State == EntityState.Modified)
            {
                entity.Modified = DateTime.UtcNow;
            }
        }
    }
    return base.SaveChanges();
}
</code>```

Where Base is:

```<code>    public int Id { get; set; }
    public DateTime? Created { get; set; }
    public DateTime? Modified { get; set; }
    public bool IsDeleted { get; set; }
</code>```

Now what I'm trying to do is when I load properties using my context like:

```<code>_context.MyEntities.AsEnumerable(something);
</code>```

I want it to select all entities that have the IsDeleted property set to false. Is it possible to do this in the DbContext like I'm making changes by overriding SaveChanges()

I can see that there is a method to override, but not sure how to go about it:

```<code>public override DbSet<TEntity> Set<TEntity>()
{
    return base.Set<TEntity>();
}
</code>```

答:
If I understand you correctly you need to add something like this in DbContext

```<code>public DbSet<MyEntity> ExistingMyEntities {
    get { return MyEntities.Where(x => !x.IsDeleted); }
}
</code>```

So then as you want you can use context object to retrieve not deleted entities.

UPDATE

Also you can filter by IsDeleted with model builder (if there is used soft delete How can I automatically filter out soft deleted entities with Entity Framework?)

```<code>public class MyContext : DbContext
{
    public virtual IDbSet<MyEntity> MyEntities { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyEntities>()
            .Map(m => m.Requires("IsDeleted")).HasValue(false).Ignore(m => m.IsDeleted);
    }
}
</code>```

I was misinformed with Ignore, but as Jan Muncinsky noticed there can be used HasValue method for filtering.

Body:
I'm using entity framework and in my context I've done some stuff like:

public override int SaveChanges()
{
    foreach (var entry in ChangeTracker.Entries())
    {
        if (entry.Entity is Base entity)
        {
            if (entry.State == EntityState.Added)
            {
                entity.Created = DateTime.UtcNow;
                entity.Modified = DateTime.UtcNow;
            }
            else if (entry.State == EntityState.Modified)
            {
                entity.Modified = DateTime.UtcNow;
            }
        }
    }
    return base.SaveChanges();
}

Where Base is:

    public int Id { get; set; }
    public DateTime? Created { get; set; }
    public DateTime? Modified { get; set; }
    public bool IsDeleted { get; set; }

Now what I'm trying to do is when I load properties using my context like:

_context.MyEntities.AsEnumerable(something);

I want it to select all entities that have the IsDeleted property set to false. Is it possible to do this in the DbContext like I'm making changes by overriding SaveChanges()

I can see that there is a method to override, but not sure how to go about it:

public override DbSet<TEntity> Set<TEntity>()
{
    return base.Set<TEntity>();
}

Body:
If I understand you correctly you need to add something like this in DbContext

public DbSet<MyEntity> ExistingMyEntities {
    get { return MyEntities.Where(x => !x.IsDeleted); }
}

So then as you want you can use context object to retrieve not deleted entities.

UPDATE

Also you can filter by IsDeleted with model builder (if there is used soft delete How can I automatically filter out soft deleted entities with Entity Framework?)

public class MyContext : DbContext
{
    public virtual IDbSet<MyEntity> MyEntities { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyEntities>()
            .Map(m => m.Requires("IsDeleted")).HasValue(false).Ignore(m => m.IsDeleted);
    }
}

I was misinformed with Ignore, but as Jan Muncinsky noticed there can be used HasValue method for filtering.


问:
Best solutions for multi-language website
I'm currently having a regular HTML website in multiple languages. I've tried something with PHP, but that didn't turned out very well. What I need is a Multi language site without:
- Subdomains (like en.domain.tld)
- Paths (like domain.tld/en)

What I do need:
- Languages that are stored in sessions/cookies
- Languages which can be used around the whole site (with one place to store the language files, if that's necessary)
- Preferably without visible indications in the URL (like ?lang=en).

A bit like how Google does it, because I also have multiple TLDs, so the user shouldn't be required to change their language by visiting another domain like .de, if they set their language to English from the .com site.

What is the best solution for this? I'm also very new to making websites, so that's why I'm asking.

答:
What i prefer to do is

Create a localization directory at the top level of your app

index.html

app.js

localization/

Inside localization directory create two files

web-en.json

```<code>{
"title":"Hello world",
"desc":"languages are fun"
}
</code>```

web-es.json

```<code>{
"title":"Hola Mundo",
"desc":"idiomas son divertidos"
}
</code>```

Install this library  "jquery-localize": "https://github.com/coderifous/jquery-localize.git"

bower install jquery-localize

Include the library

Add the attributes to your HTML tags

Hello World will go here

Translated desc will replace this text

Call the library onReady

$(function(){
    $("[data-localize]").localize("localization/web");
};

Body:
What i prefer to do is

Create a localization directory at the top level of your app

index.html

app.js

localization/

Inside localization directory create two files

web-en.json

{
"title":"Hello world",
"desc":"languages are fun"
}

web-es.json

{
"title":"Hola Mundo",
"desc":"idiomas son divertidos"
}

Install this library  "jquery-localize": "https://github.com/coderifous/jquery-localize.git"

bower install jquery-localize

Include the library

Add the attributes to your HTML tags

Hello World will go here

Translated desc will replace this text

Call the library onReady

$(function(){
    $("[data-localize]").localize("localization/web");
};


问:
Vim autocomplete from ctags for system headers only works when popup is triggered manually
On OS X, I generated a set of ctags for the system includes using the following command:

```<code>ctags -f c -h ".h" -R --c-kinds=+p --fields=+iaS --extra=+q /usr/include
</code>```

This was run inside of a ~/.vim/ctags/ directory, where I put all of the ctags I generate for system-wide header files (I also have stuff for ROS and CPP that I load conditionally, but that's neither here nor there).

Anyway.  The ctags file is set correctly in my .vimrc, and vim can definitely see the ctags, but for some reason the autocomplete popup will only display results from #included header files if I write out the entire symbol and then start backspacing.  As an example, if I #include <string.h> in a project, and then I want to call strlen(), and I start to type str in to the active vim buffer, I will only get results for symbols that are currently in the vim buffer.  But, if I type out strlen and then start backspacing one or two characters and hit <C-n>, the popup menu will be populated with matches from any other included header files.

EDIT: Turns out, if I just hit "s" then <C-n>, it works as well.  So the problem seems to be that it only works if the popup menu is launched manually.  Which makes me think that it's a plugin problem (see below)

Additional information:

completeopt is set to completeopt=menuone,menu,preview,longest

I have OmniCppComplete, which I suppose could be interfering with the behavior.  It is currently not being conditionally loaded for C++ files only. If you want me to edit and post my OmniCppComplete settings from my .vimrc, just ask.

I also have AutoComplPop installed, but I haven't done anything to configure it, so it's running with its default settings.  Haven't really researched the plugin, so no idea if some of it's behavior could be interfering with the results.

I have AutoTag and TagBar installed, but those should only be fiddling with the current directory's local tagfile.

I'm honestly pretty new to Vim, and I just have no idea where to start debugging this issue, whether it be with a random plugin or with my .vimrc settings.

答:
I have not mastered this yet, but I do think the following observation may be of help.

Vim's default auto complete which can be quite noisy, often gets in the way of what you call with <C-x><C-o>.  Specifically, I found myself calling up my tags based completions with <C-x><C-o> only to have them replaced with continued typing with Vim's default suggestions using my open buffers.

The suggestion of shutting off one of the plugins makes sense.  In my case the key was how to shut down Vim's default behavior.  I have seen several people (and to which I now include myself), set the length of the expression to a high number before triggering Vim's default. For me that is:

```<code>    let g:deoplete#auto_complete_start_length = 99
</code>```

... this way you eliminate the default layer of completions that comes and goes regardless of the commands you intended to inform your work.

This still feels like a hack but it helps keep my work focused on the tag-based completions.

FYI: I use NVIM on a Mac.

Body:
On OS X, I generated a set of ctags for the system includes using the following command:

ctags -f c -h ".h" -R --c-kinds=+p --fields=+iaS --extra=+q /usr/include

This was run inside of a ~/.vim/ctags/ directory, where I put all of the ctags I generate for system-wide header files (I also have stuff for ROS and CPP that I load conditionally, but that's neither here nor there).

Anyway.  The ctags file is set correctly in my .vimrc, and vim can definitely see the ctags, but for some reason the autocomplete popup will only display results from #included header files if I write out the entire symbol and then start backspacing.  As an example, if I #include <string.h> in a project, and then I want to call strlen(), and I start to type str in to the active vim buffer, I will only get results for symbols that are currently in the vim buffer.  But, if I type out strlen and then start backspacing one or two characters and hit <C-n>, the popup menu will be populated with matches from any other included header files.

EDIT: Turns out, if I just hit "s" then <C-n>, it works as well.  So the problem seems to be that it only works if the popup menu is launched manually.  Which makes me think that it's a plugin problem (see below)

Additional information:

completeopt is set to completeopt=menuone,menu,preview,longest

I have OmniCppComplete, which I suppose could be interfering with the behavior.  It is currently not being conditionally loaded for C++ files only. If you want me to edit and post my OmniCppComplete settings from my .vimrc, just ask.

I also have AutoComplPop installed, but I haven't done anything to configure it, so it's running with its default settings.  Haven't really researched the plugin, so no idea if some of it's behavior could be interfering with the results.

I have AutoTag and TagBar installed, but those should only be fiddling with the current directory's local tagfile.

I'm honestly pretty new to Vim, and I just have no idea where to start debugging this issue, whether it be with a random plugin or with my .vimrc settings.

Body:
I have not mastered this yet, but I do think the following observation may be of help.

Vim's default auto complete which can be quite noisy, often gets in the way of what you call with <C-x><C-o>.  Specifically, I found myself calling up my tags based completions with <C-x><C-o> only to have them replaced with continued typing with Vim's default suggestions using my open buffers.

The suggestion of shutting off one of the plugins makes sense.  In my case the key was how to shut down Vim's default behavior.  I have seen several people (and to which I now include myself), set the length of the expression to a high number before triggering Vim's default. For me that is:

    let g:deoplete#auto_complete_start_length = 99

... this way you eliminate the default layer of completions that comes and goes regardless of the commands you intended to inform your work.

This still feels like a hack but it helps keep my work focused on the tag-based completions.

FYI: I use NVIM on a Mac.


问:
Postgres pg_dump cache lookup failed for index
I am trying to create a back-up of a postgres database using the following command (omitting details):

```<code>$ pg_dump -h $host -p 5432 -U $user $db > db.sql
</code>```

After some time, I get an error (formatted)

```<code>pg_dump: [archiver (db)] query failed: ERROR:  cache lookup failed for index 1184605879
pg_dump: [archiver (db)] query was:
SELECT  t.tableoid,
        t.oid,
        t.relname AS indexname,
        pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef,
        t.relnatts AS indnkeys,
        i.indkey,
        i.indisclustered,
        false AS indisreplident,
        t.relpages,
        c.contype,
        c.conname,
        c.condeferrable,
        c.condeferred,
        c.tableoid AS contableoid,
        c.oid AS conoid,
        pg_catalog.pg_get_constraintdef(c.oid, false) AS condef,
        (SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace,
        t.reloptions AS indreloptions
FROM pg_catalog.pg_index i
JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid)
LEFT JOIN pg_catalog.pg_constraint c ON (i.indrelid = c.conrelid AND i.indexrelid = c.conindid AND c.contype IN ('p','u','x'))
WHERE i.indrelid = '1184605870'::pg_catalog.oid AND i.indisvalid AND i.indisready
ORDER BY indexname
</code>```

I then verified the index ID in pg_index does not exist. Is there some way to fix this, or some way to ignore this error and continue so I can continue exporting non-pg_catalog data?

答:
Your database is corrupted, and you should restore from a backup.

If are not afraid of messing with the catalogs (make a physical backup first!):

Set the configuration parameter allow_system_table_mods to on so you can modify system catalogs. Then

```<code>DELETE FROM pg_catalog.pg_index WHERE indexrelid = 1184605879;
</code>```

Maybe that gets your database in a state where you can dump it (minus that index).

If there are more problems, you might end up extracting table data one by one with COPY and see what else you can salvage.

Body:
I am trying to create a back-up of a postgres database using the following command (omitting details):

$ pg_dump -h $host -p 5432 -U $user $db > db.sql

After some time, I get an error (formatted)

pg_dump: [archiver (db)] query failed: ERROR:  cache lookup failed for index 1184605879
pg_dump: [archiver (db)] query was:
SELECT  t.tableoid,
        t.oid,
        t.relname AS indexname,
        pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef,
        t.relnatts AS indnkeys,
        i.indkey,
        i.indisclustered,
        false AS indisreplident,
        t.relpages,
        c.contype,
        c.conname,
        c.condeferrable,
        c.condeferred,
        c.tableoid AS contableoid,
        c.oid AS conoid,
        pg_catalog.pg_get_constraintdef(c.oid, false) AS condef,
        (SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace,
        t.reloptions AS indreloptions
FROM pg_catalog.pg_index i
JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid)
LEFT JOIN pg_catalog.pg_constraint c ON (i.indrelid = c.conrelid AND i.indexrelid = c.conindid AND c.contype IN ('p','u','x'))
WHERE i.indrelid = '1184605870'::pg_catalog.oid AND i.indisvalid AND i.indisready
ORDER BY indexname

I then verified the index ID in pg_index does not exist. Is there some way to fix this, or some way to ignore this error and continue so I can continue exporting non-pg_catalog data?

Body:
Your database is corrupted, and you should restore from a backup.

If are not afraid of messing with the catalogs (make a physical backup first!):

Set the configuration parameter allow_system_table_mods to on so you can modify system catalogs. Then

DELETE FROM pg_catalog.pg_index WHERE indexrelid = 1184605879;

Maybe that gets your database in a state where you can dump it (minus that index).

If there are more problems, you might end up extracting table data one by one with COPY and see what else you can salvage.


问:
How to Reduce Multiple Repeating Lines of Tidyverse Code - for Multiple Charts with X by Different Y's - Using a Vector of Names
```<code>library(tidyverse)
</code>```

Using the Iris dataset, the code below uses a tidyverse approach to create multiple charts and is ultimately what I want to achieve. However, it seems repetitive to write out the three lines for "gg1","gg2", and "gg3", so I'm attempting to rewrite this in a more efficient way. (See code below)

```<code>iris0 <- iris %>%
group_by(Species) %>%
nest() %>%
mutate(
gg1 = map(data, ~ ggplot(., aes(Sepal.Length, Sepal.Width)) + geom_point()),
gg2 = map(data, ~ ggplot(., aes(Sepal.Length, Petal.Width)) + geom_point()),
gg3 = map(data, ~ ggplot(., aes(Sepal.Length, Petal.Length)) + geom_point()),
g = pmap(list(gg1, gg2, gg3), ~ gridExtra::grid.arrange(..1, ..2, ..3))
)
</code>```

Ignoring the final gridExtra part for now as well as the names (gg1, gg2,and gg3), below is an attempt to produce the three charts from the code above in one line of code by using a vector of names called Y. But this doesn't seem to work. I've tried a few other variants, but help would be appreciated...

```<code>Y<-c("Sepal.Width","Petal.Width","Petal.Length")

iris0<-iris%>%
group_by(Species)%>%
nest()%>%
mutate(
   map(data,~ggplot(.,aes(Sepal.Length))+geom_point(aes_string(Y))))
</code>```

答:
I think reshaping and using different grouping variables may be the easier-to-follow approach here, but you can attempt something the lines you are currently working with using a double map loop to loop through each species and each y variable.

Don't forget to define the y argument when mapping to the y aesthetic in geom_point.  That will avoid at least some of the errors you are getting now.

I include code for sending the plots on to grid.arrange.

```<code>iris %>%
     group_by(Species) %>%
     nest() %>%
     mutate(graphs = map(data, function(x) {
               map(Y, function(y) ggplot(x, aes(Sepal.Length )) +
                                       geom_point( aes_string(y = y) ) )
               }),
          grid.graphs = map(graphs, ~gridExtra::grid.arrange(grobs = .x) ) )
</code>```

You can add species names to the multiplots using the top argument, but I had to group the nested dataset for this to work.

```<code>iris %>%
    group_by(Species) %>%
    nest() %>%
    group_by(Species) %>%
    mutate(graphs = map(data, function(x) {
        map(Y, function(y) ggplot(x, aes(Sepal.Length )) +
                geom_point( aes_string(y = y) ) )
    }),
    grid.graphs = map(graphs, ~gridExtra::grid.arrange(grobs = .x,
                                                       top = grid::textGrob(Species) ) ) )
</code>```

I find nested loops relatively difficult to follow.  A reshaping approach would take a fair amount more code, so ends up looking pretty complicated.  Essentially you make your dataset long, then nest on both species and the y variable prior to making the plots.

I ended up doing a second nest for the grid.arrange, which seems pretty convoluted.

```<code>iris %>%
     gather(variable, yvar, one_of(Y) ) %>%
     group_by(Species, variable) %>%
     nest() %>%
     group_by(Species, variable) %>%
     mutate(graphs = map(data, ~ggplot(.x, aes(Sepal.Length, yvar) ) +
                              geom_point() +
                              labs(y = unique(variable) ) ) ) %>%
     group_by(Species) %>%
     nest(graphs, .key = "graphs") %>%
     mutate(grid.graphs = map(graphs, ~gridExtra::grid.arrange(grobs = flatten(.x)) ) )
</code>```

Body:
library(tidyverse)

Using the Iris dataset, the code below uses a tidyverse approach to create multiple charts and is ultimately what I want to achieve. However, it seems repetitive to write out the three lines for "gg1","gg2", and "gg3", so I'm attempting to rewrite this in a more efficient way. (See code below)

iris0 <- iris %>%
group_by(Species) %>%
nest() %>%
mutate(
gg1 = map(data, ~ ggplot(., aes(Sepal.Length, Sepal.Width)) + geom_point()),
gg2 = map(data, ~ ggplot(., aes(Sepal.Length, Petal.Width)) + geom_point()),
gg3 = map(data, ~ ggplot(., aes(Sepal.Length, Petal.Length)) + geom_point()),
g = pmap(list(gg1, gg2, gg3), ~ gridExtra::grid.arrange(..1, ..2, ..3))
)

Ignoring the final gridExtra part for now as well as the names (gg1, gg2,and gg3), below is an attempt to produce the three charts from the code above in one line of code by using a vector of names called Y. But this doesn't seem to work. I've tried a few other variants, but help would be appreciated...

Y<-c("Sepal.Width","Petal.Width","Petal.Length")

iris0<-iris%>%
group_by(Species)%>%
nest()%>%
mutate(
   map(data,~ggplot(.,aes(Sepal.Length))+geom_point(aes_string(Y))))

Body:
I think reshaping and using different grouping variables may be the easier-to-follow approach here, but you can attempt something the lines you are currently working with using a double map loop to loop through each species and each y variable.

Don't forget to define the y argument when mapping to the y aesthetic in geom_point.  That will avoid at least some of the errors you are getting now.

I include code for sending the plots on to grid.arrange.

iris %>%
     group_by(Species) %>%
     nest() %>%
     mutate(graphs = map(data, function(x) {
               map(Y, function(y) ggplot(x, aes(Sepal.Length )) +
                                       geom_point( aes_string(y = y) ) )
               }),
          grid.graphs = map(graphs, ~gridExtra::grid.arrange(grobs = .x) ) )

You can add species names to the multiplots using the top argument, but I had to group the nested dataset for this to work.

iris %>%
    group_by(Species) %>%
    nest() %>%
    group_by(Species) %>%
    mutate(graphs = map(data, function(x) {
        map(Y, function(y) ggplot(x, aes(Sepal.Length )) +
                geom_point( aes_string(y = y) ) )
    }),
    grid.graphs = map(graphs, ~gridExtra::grid.arrange(grobs = .x,
                                                       top = grid::textGrob(Species) ) ) )

I find nested loops relatively difficult to follow.  A reshaping approach would take a fair amount more code, so ends up looking pretty complicated.  Essentially you make your dataset long, then nest on both species and the y variable prior to making the plots.

I ended up doing a second nest for the grid.arrange, which seems pretty convoluted.

iris %>%
     gather(variable, yvar, one_of(Y) ) %>%
     group_by(Species, variable) %>%
     nest() %>%
     group_by(Species, variable) %>%
     mutate(graphs = map(data, ~ggplot(.x, aes(Sepal.Length, yvar) ) +
                              geom_point() +
                              labs(y = unique(variable) ) ) ) %>%
     group_by(Species) %>%
     nest(graphs, .key = "graphs") %>%
     mutate(grid.graphs = map(graphs, ~gridExtra::grid.arrange(grobs = flatten(.x)) ) )