问:
Text not being displayed correctly due to code formatted wrong maybe?
I have NSMutableDictionary that I'm retrieving text from. I"m trying to display this text into a tableview cell along with some other text that I want added with it. Here's my non-working code:

```<code>[[cell name] setText:(@"Name:%@",[NameDict valueForKey:@"name"])];
</code>```

I've even tried stringWithFormat and still can't get it to work. I can't get the Name: part to display into the cell along with NameDict value for that key. Any ideas what I'm doing wrong here? Thanks.

答:
I'm not sure where you are getting [cell name] from, but this would be a better solution for you based on your code:

```<code>[[cell name] setText:[NSString stringWithFormat:@"Name:%@",[NameDict objectForKey:@"name"]]];
</code>```

If you are trying to place that text as the cell text, use:

```<code>cell.textLabel.text = [NSString stringWithFormat:@"Name:%@",[NameDict objectForKey:@"name"]];
</code>```

Body:
I have NSMutableDictionary that I'm retrieving text from. I"m trying to display this text into a tableview cell along with some other text that I want added with it. Here's my non-working code:

[[cell name] setText:(@"Name:%@",[NameDict valueForKey:@"name"])];

I've even tried stringWithFormat and still can't get it to work. I can't get the Name: part to display into the cell along with NameDict value for that key. Any ideas what I'm doing wrong here? Thanks.

Body:
I'm not sure where you are getting [cell name] from, but this would be a better solution for you based on your code:

[[cell name] setText:[NSString stringWithFormat:@"Name:%@",[NameDict objectForKey:@"name"]]];

If you are trying to place that text as the cell text, use:

cell.textLabel.text = [NSString stringWithFormat:@"Name:%@",[NameDict objectForKey:@"name"]];


来源: stackexchange

问:
Python dataframe group labeling
Is there any tool in Pandas or other python package to facilitate the labeling of groups of varying number rows in a Pandas’ dataFrame? Here are more detail:

My dataFrame has a column of datetime.datetime objects used as the dataFrame index. The time is not evenly spaced and during a given amount of time, the number of rows varies.

In that dataFrame, I need to make a column that has a different label for each series of rows that span over a constant time span (12 seconds in my case).

For example, using examples with seconds

```<code>Time(s) | label
1           |   0
2           |   0
3           |   0
7           |   0
12         |   1
15         |   1
20         |   1
24          |   2
Etc…
</code>```

I’m looking for an alternative as a brute-force loop. Algorithms somewhat related to that are labeling, segmenting, mapping but i'm not sure what to look for exactly. I was hoping there would be something exploiting python, Pandas and/or Numpy in a more efficient way since the number of rows is gonna be of the order of a hundred millions.

Thanks

ContentLicense: CC BY-SA 3.0

Title: Python dataframe group labeling

Body:
Is there any tool in Pandas or other python package to facilitate the labeling of groups of varying number rows in a Pandas’ dataFrame? Here are more detail:

My dataFrame has a column of datetime.datetime objects used as the dataFrame index. The time is not evenly spaced and during a given amount of time, the number of rows varies.

In that dataFrame, I need to make a column that has a different label for each series of rows that span over a constant time span (12 seconds in my case).

For example, using examples with seconds

Time(s) | label
1           |   0
2           |   0
3           |   0
7           |   0
12         |   1
15         |   1
20         |   1
24          |   2
Etc…

I’m looking for an alternative as a brute-force loop. Algorithms somewhat related to that are labeling, segmenting, mapping but i'm not sure what to look for exactly. I was hoping there would be something exploiting python, Pandas and/or Numpy in a more efficient way since the number of rows is gonna be of the order of a hundred millions.

Thanks

Body:
Demo:

Sample DF:

In [32]: df = pd.DataFrame({'Time':pd.date_range('2017-01-01 00:00:01', freq='3S', periods=15)})

In [33]: df
Out[33]:
                  Time
0  2017-01-01 00:00:01
1  2017-01-01 00:00:04
2  2017-01-01 00:00:07
3  2017-01-01 00:00:10
4  2017-01-01 00:00:13
5  2017-01-01 00:00:16
6  2017-01-01 00:00:19
7  2017-01-01 00:00:22
8  2017-01-01 00:00:25
9  2017-01-01 00:00:28
10 2017-01-01 00:00:31
11 2017-01-01 00:00:34
12 2017-01-01 00:00:37
13 2017-01-01 00:00:40
14 2017-01-01 00:00:43

Solution:

In [34]: df['label'] = df.groupby(pd.Grouper(key='Time', freq='12S')).ngroup()

Result:

In [35]: df
Out[35]:
                  Time  label
0  2017-01-01 00:00:01      0
1  2017-01-01 00:00:04      0
2  2017-01-01 00:00:07      0
3  2017-01-01 00:00:10      0
4  2017-01-01 00:00:13      1
5  2017-01-01 00:00:16      1
6  2017-01-01 00:00:19      1
7  2017-01-01 00:00:22      1
8  2017-01-01 00:00:25      2
9  2017-01-01 00:00:28      2
10 2017-01-01 00:00:31      2
11 2017-01-01 00:00:34      2
12 2017-01-01 00:00:37      3
13 2017-01-01 00:00:40      3
14 2017-01-01 00:00:43      3


问:
IEnumerable Add method available only when using collection initializer
I'm planning to create an immutable class based on JObject.

One of the requirement is to directly deserialize object onto my new custom class, just like we do with JObject.

I've implemented GetEnumerator and Add method to enable collection initializer.

The code looks like below

```<code>public sealed class ImmutableJObject : IEnumerable
{
    readonly jObject jObeject;

    public ImmutableJObject(params object[] content)
    {
        this.jObject = new jObject(content);
    }

    public IEnumerator GetEnumerator()
    {
        return ((IEnumerable)jObject).GetEnumerator();
    }

    public void Add(string propertyName, JToken value)
    {
        this.jObject.Add(propertyName, value);
    }
}
</code>```

Is it possible to make Add method accesible only when collection initializer is utilized?

Being immutable in nature, I don't want Add method to be public.
But, it looks like it needs to be public in order to enable collection initializer

Thanks ahead!

答: No, there is no way to restrict the use of the Add method to a collection initializer.  A collection initializer results in code that constructs the object, and then mutates it, so by definition a type cannot support a collection initializer (that is actually capable of initializing it, i.e. where the collection initializer doesn't just throw an exception) and be immutable.

Body:
I'm planning to create an immutable class based on JObject.

One of the requirement is to directly deserialize object onto my new custom class, just like we do with JObject.

I've implemented GetEnumerator and Add method to enable collection initializer.

The code looks like below

public sealed class ImmutableJObject : IEnumerable
{
    readonly jObject jObeject;

    public ImmutableJObject(params object[] content)
    {
        this.jObject = new jObject(content);
    }

    public IEnumerator GetEnumerator()
    {
        return ((IEnumerable)jObject).GetEnumerator();
    }

    public void Add(string propertyName, JToken value)
    {
        this.jObject.Add(propertyName, value);
    }
}

Is it possible to make Add method accesible only when collection initializer is utilized?

Being immutable in nature, I don't want Add method to be public.
But, it looks like it needs to be public in order to enable collection initializer

Thanks ahead!


问:
Issue trying to implement stacked LSTM layers with Keras
I'm trying to add more LSTM layers to my neural net, but I keep getting the following error:

```<code>ValueError: Error when checking target: expected dense_4 to have 2 dimensions, but got array with shape (385, 128, 1)
</code>```

The code for my model is as follows:

```<code>model = Sequential()

model.add(LSTM(60, return_sequences=True, input_shape=(128, 14)))

model.add(LSTM(60, return_sequences=False))

model.add(Dense(1))

model.compile(loss='mean_squared_error', optimizer='adam')

model.fit(data_train, RUL_train, epochs=number_epochs, batch_size=batch_size, verbose=1)
</code>```

It works fine when I remove the second LSTM layer. Or if I add more dense layers. Just not when I add the LSTM layer. RUL_train has shape (385, 128, 1).
The output of model.summary is as follows:

```<code>_________________________________________________________________
   Layer (type)                 Output Shape              Param #
=================================================================
lstm_15 (LSTM)               (None, 128, 60)           18000
_________________________________________________________________
lstm_16 (LSTM)               (None, 60)                29040
_________________________________________________________________
dense_7 (Dense)              (None, 1)                 61
=================================================================
Total params: 47,101
Trainable params: 47,101
Non-trainable params: 0
_________________________________________________________________
</code>```

Any help appreciated.

答:
This is a bug that was introduced in Keras 2.1.0 (and wasn't completely fixed in 2.1.1). Try installing Keras 2.0.9 or earlier:

```<code>pip uninstall keras
pip install keras==2.0.9
</code>```

https://github.com/fchollet/keras/issues/8481

Body:
I'm trying to add more LSTM layers to my neural net, but I keep getting the following error:

ValueError: Error when checking target: expected dense_4 to have 2 dimensions, but got array with shape (385, 128, 1)

The code for my model is as follows:

model = Sequential()

model.add(LSTM(60, return_sequences=True, input_shape=(128, 14)))

model.add(LSTM(60, return_sequences=False))

model.add(Dense(1))

model.compile(loss='mean_squared_error', optimizer='adam')

model.fit(data_train, RUL_train, epochs=number_epochs, batch_size=batch_size, verbose=1)

It works fine when I remove the second LSTM layer. Or if I add more dense layers. Just not when I add the LSTM layer. RUL_train has shape (385, 128, 1).
The output of model.summary is as follows:

_________________________________________________________________
   Layer (type)                 Output Shape              Param #
=================================================================
lstm_15 (LSTM)               (None, 128, 60)           18000
_________________________________________________________________
lstm_16 (LSTM)               (None, 60)                29040
_________________________________________________________________
dense_7 (Dense)              (None, 1)                 61
=================================================================
Total params: 47,101
Trainable params: 47,101
Non-trainable params: 0
_________________________________________________________________

Any help appreciated.

Body:
This is a bug that was introduced in Keras 2.1.0 (and wasn't completely fixed in 2.1.1). Try installing Keras 2.0.9 or earlier:

pip uninstall keras
pip install keras==2.0.9

https://github.com/fchollet/keras/issues/8481


问:
Python 2.7 build on Sublime Text 3 doesn't print the '\uFFFD' character

The problem.

I'm using Python 2.7 build on Sublime Text 3 and have an issue with printing out.

In some cases I get a pretty confusing output for '\uFFFD' - the 'REPLACEMENT CHARACTER'.

For example:

```<code>print u'\ufffd' # should be '�' - the 'REPLACEMENT CHARACTER'
print u'\u0061' # should be 'a'
-----------------------------------------------------
[Finished in 0.1s]
</code>```

After inversion of the order:

```<code>print u'\u0061'
print u'\ufffd'
-----------------------------------------------------
a
�
[Finished in 0.1s]
</code>```

So, Sublime can printout the '�' character, but for some reason doesn't do it in the 1st case.

And the dependence of the output on the order of statements seems quite strange.

The problem with replacement char leads to very unpredictable printout behavior in general.

For example, I want to printout decoded bytes with error replacement:

```<code>cp1251_bytes = '\xe4\xe0' # 'да' in cp1251
print cp1251_bytes.decode('utf-8', errors='replace')
-----------------------------------------------------
��
[Finished in 0.1s]
</code>```

Let's replace the bytes:

```<code>cp1251_bytes = '\xed\xe5\xf2' # 'нет' in cp1251
print cp1251_bytes.decode('utf-8', errors='replace')
-----------------------------------------------------
[Finished in 0.1s]
</code>```

And add one more print statement:

```<code>cp1251_bytes = '\xed\xe5\xf2' # 'нет' in cp1251
print cp1251_bytes.decode('cp1251')
print cp1251_bytes.decode('utf-8', errors='replace')
-----------------------------------------------------
нет
���
[Finished in 0.1s]
</code>```

Below is the illustration of implementation some other test cases:

Summarizing, there are the following patterns in the described printout behavior:

 it depends on the even/odd number of '\ufffd' chars in print statement

 it depends on the order of print statements

 it depends on the specific build run

My questions:

Why does this happen?

How to fix the problem?

My Python 2.7 sublime-build file:

```<code>{
    "cmd": ["C:\\_Anaconda3\\envs\\python27\\python", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python",
    "env": {"PYTHONIOENCODING": "utf-8"}
}
</code>```

With Python 2.7 installed separately from Anaconda the behavior is exactly the same.

答:
I've reproduced your problem and I've found a solution that works on my platform anyhow: Remove the -u flag from your cmd build config option.

I'm not 100% sure why that works, but it seems to be a poor interaction resulting from the console interpreting an unbuffered stream of data containing multi-byte characters. Here's what I've found:

The -u option switches Python's output to unbuffered

This problem is not at all specific to the replacement character. I've gotten similar behaviour with other characters like "あ" (U+3042).

Similar bad results happen with other encodings. Setting "env": {"PYTHONIOENCODING": "utf-16be"} results in print u'\u3042' outputting 0B.

That last example with the encoding set to UTF-16BE illustrates what I think is going on. The console is receiving one byte at a time because the output is unbuffered. So it receives the 0x30 byte first. The console then determines this is not valid UTF-16BE and decides instead to fallback to ASCII and thus outputs 0. It of courses receives the next byte right after and follows the same logic to output B.

With the UTF-8 encoding, the console receives bytes that can't possibly be interpreted as ASCII, so I believe the console is doing a slightly better job at properly interpreting the unbuffered stream, but it is still running into the difficulties that your question points out.

Body:
The problem.

I'm using Python 2.7 build on Sublime Text 3 and have an issue with printing out.

In some cases I get a pretty confusing output for '\uFFFD' - the 'REPLACEMENT CHARACTER'.

For example:

print u'\ufffd' # should be '�' - the 'REPLACEMENT CHARACTER'
print u'\u0061' # should be 'a'
-----------------------------------------------------
[Finished in 0.1s]

After inversion of the order:

print u'\u0061'
print u'\ufffd'
-----------------------------------------------------
a
�
[Finished in 0.1s]

So, Sublime can printout the '�' character, but for some reason doesn't do it in the 1st case.

And the dependence of the output on the order of statements seems quite strange.

The problem with replacement char leads to very unpredictable printout behavior in general.

For example, I want to printout decoded bytes with error replacement:

cp1251_bytes = '\xe4\xe0' # 'да' in cp1251
print cp1251_bytes.decode('utf-8', errors='replace')
-----------------------------------------------------
��
[Finished in 0.1s]

Let's replace the bytes:

cp1251_bytes = '\xed\xe5\xf2' # 'нет' in cp1251
print cp1251_bytes.decode('utf-8', errors='replace')
-----------------------------------------------------
[Finished in 0.1s]

And add one more print statement:

cp1251_bytes = '\xed\xe5\xf2' # 'нет' in cp1251
print cp1251_bytes.decode('cp1251')
print cp1251_bytes.decode('utf-8', errors='replace')
-----------------------------------------------------
нет
���
[Finished in 0.1s]

Below is the illustration of implementation some other test cases:

Summarizing, there are the following patterns in the described printout behavior:

 it depends on the even/odd number of '\ufffd' chars in print statement

 it depends on the order of print statements

 it depends on the specific build run

My questions:

Why does this happen?

How to fix the problem?

My Python 2.7 sublime-build file:

{
    "cmd": ["C:\\_Anaconda3\\envs\\python27\\python", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python",
    "env": {"PYTHONIOENCODING": "utf-8"}
}

With Python 2.7 installed separately from Anaconda the behavior is exactly the same.


问:
If else embedding inside html
What is the correct way of embedding if else  and elseif conditions inside html?</p>

答:
I recommend the following syntax for readability.

```<code><? if ($condition): ?>
  <p>Content</p>
<? elseif ($other_condition): ?>
  <p>Other Content</p>
<? else: ?>
  <p>Default Content</p>
<? endif; ?>
</code>```

Note, omitting php on the open tags does require that short_open_tags is enabled in your configuration, which is the default. The relevant curly-brace-free conditional syntax is always enabled and can be used regardless of this directive.

ContentLicense: CC BY-SA 2.5

Title: If else embedding inside html

Body:
I recommend the following syntax for readability.

<? if ($condition): ?>
  <p>Content</p>
<? elseif ($other_condition): ?>
  <p>Other Content</p>
<? else: ?>
  <p>Default Content</p>
<? endif; ?>

Note, omitting php on the open tags does require that short_open_tags is enabled in your configuration, which is the default. The relevant curly-brace-free conditional syntax is always enabled and can be used regardless of this directive.


问:
LINQ query to retrieve pivoted data taking too long
I am working on a LINQ query which includes some pivot data as below

```<code>var q = data.GroupBy(x => new
            {
                x.Med.Name,
                x.Med.GenericName,
            }).ToList().Select(g =>
                new SummaryDto
                {
                    Name= g.Key.Name,
                    GenericName = g.Key.GenericName,
                    Data2012 = g.Where(z => z.ProcessDate.Year == 2012).Count(),
                    Data2013 = g.Where(z => z.ProcessDate.Year == 2013).Count(),
                    Data2014 = g.Where(z => z.ProcessDate.Year == 2014).Count(),
                    Data2015 = g.Where(z => z.ProcessDate.Year == 2015).Count(),
                    Data2016 = g.Where(z => z.ProcessDate.Year == 2016).Count(),
                    Data2017 = g.Where(z => z.ProcessDate.Year == 2017).Count(),
                    TotalCount = g.Count(),
                }).AsQueryable();

            return q;
</code>```

The above LINQ takes too long as it queries grp q.Count()*6 times. If there are 10000  records, then it queries 60000 times
Is there a better way to make this faster?

答:
I suggest grouping inside the group by year and then converting to a dictionary to access the counts. Whether it is faster to group with year first and then count in-memory depends on the distribution of the initial grouping, but with the database it may depend on how efficiently it can group by year, so I would test to determine which seems fastest.

In any case grouping by year after the initial grouping is about 33% faster than your query in-memory, but again it is vastly dependent on the distribution. As the number of initial groups increase, the grouping by Year queries slow down to match the original query. Note that the original query without any year counts is about 1/3 the time.

Here is grouping after the database grouping:

```<code>var q = data.GroupBy(x => new {
    x.Med.Name,
    x.Med.GenericName,
}).ToList().Select(g => {
    var gg = g.GroupBy(d => d.ProcessDate.Year).ToDictionary(d => d.Key, d => d.Count());
    return new SummaryDto {
        Name = g.Key.Name,
        GenericName = g.Key.GenericName,
        Data2012 = gg.GetValueOrDefault(2012),
        Data2013 = gg.GetValueOrDefault(2013),
        Data2014 = gg.GetValueOrDefault(2014),
        Data2015 = gg.GetValueOrDefault(2015),
        Data2016 = gg.GetValueOrDefault(2016),
        Data2017 = gg.GetValueOrDefault(2017),
        TotalCount = g.Count(),
    };
}).AsQueryable();
</code>```

Body:
I am working on a LINQ query which includes some pivot data as below

var q = data.GroupBy(x => new
            {
                x.Med.Name,
                x.Med.GenericName,
            }).ToList().Select(g =>
                new SummaryDto
                {
                    Name= g.Key.Name,
                    GenericName = g.Key.GenericName,
                    Data2012 = g.Where(z => z.ProcessDate.Year == 2012).Count(),
                    Data2013 = g.Where(z => z.ProcessDate.Year == 2013).Count(),
                    Data2014 = g.Where(z => z.ProcessDate.Year == 2014).Count(),
                    Data2015 = g.Where(z => z.ProcessDate.Year == 2015).Count(),
                    Data2016 = g.Where(z => z.ProcessDate.Year == 2016).Count(),
                    Data2017 = g.Where(z => z.ProcessDate.Year == 2017).Count(),
                    TotalCount = g.Count(),
                }).AsQueryable();

            return q;

The above LINQ takes too long as it queries grp q.Count()*6 times. If there are 10000  records, then it queries 60000 times
Is there a better way to make this faster?

Body:
I suggest grouping inside the group by year and then converting to a dictionary to access the counts. Whether it is faster to group with year first and then count in-memory depends on the distribution of the initial grouping, but with the database it may depend on how efficiently it can group by year, so I would test to determine which seems fastest.

In any case grouping by year after the initial grouping is about 33% faster than your query in-memory, but again it is vastly dependent on the distribution. As the number of initial groups increase, the grouping by Year queries slow down to match the original query. Note that the original query without any year counts is about 1/3 the time.

Here is grouping after the database grouping:

var q = data.GroupBy(x => new {
    x.Med.Name,
    x.Med.GenericName,
}).ToList().Select(g => {
    var gg = g.GroupBy(d => d.ProcessDate.Year).ToDictionary(d => d.Key, d => d.Count());
    return new SummaryDto {
        Name = g.Key.Name,
        GenericName = g.Key.GenericName,
        Data2012 = gg.GetValueOrDefault(2012),
        Data2013 = gg.GetValueOrDefault(2013),
        Data2014 = gg.GetValueOrDefault(2014),
        Data2015 = gg.GetValueOrDefault(2015),
        Data2016 = gg.GetValueOrDefault(2016),
        Data2017 = gg.GetValueOrDefault(2017),
        TotalCount = g.Count(),
    };
}).AsQueryable();


问:
Using CMake with Qt5 and Qt Plugins
I'd like to avoid using qmake and .pro files. The problem is that I cannot get cmake to work nicely with Qt Plugins. I've included the code below showing the interface, plugin, loader that work correctly for the given .pro file but I cannot figure out how to transfer this functionality to cmake.

Plugin Interface

Pure virtual interface, known by the loader.

```<code>#include <QtCore/qglobal.h>

class HelloPluginInterface
{
public:
    virtual void DoSomething() const = 0;
};

Q_DECLARE_INTERFACE( HelloPluginInterface, "com.harbrick.Qt.HelloPluginInterface")
</code>```

Plugin

Plugin that becomes a .so to be loaded by the loader.

```<code>#include <QtPlugin>
#include "helloplugin_global.h"

class HelloPlugin : public QObject, public HelloPluginInterface
{
    Q_OBJECT
    Q_PLUGIN_METADATA( IID "com.harbrick.Qt.HelloPluginInterface" )
    Q_INTERFACES( HelloPluginInterface )

public:
    void DoSomething() const;
};
</code>```

Plugin Loader

```<code>void MainWindow::LoadPlugin( const QString& pathToLibrary )
{
    QPluginLoader loader( pathToLibrary );
    QObject* instance = loader.instance();

    if( instance )
    {
        HelloPluginInterface *plugin = qobject_cast< HelloPluginInterface* >( instance );
        if(plugin)
        {
            //do stuff
            ...
        }
        else
        {
            qDebug() << "Not a plugin: " << Filename << " = " << loader.errorString();
        }
    }
}
</code>```

CMakeLists.txt

Can't get to work

```<code>project( HelloPlugin )
cmake_minimum_required( VERSION 2.8.11 )

set( CMAKE_INCLUDE_CURRENT_DIR ON )

find_package(Qt5Widgets)

include_directories(
    ${CMAKE_CURRENT_SOURCE_DIR}
)

set( INCLUDE
    cmakeplugin.h
    cmakeplugininterface.h
)

set( SOURCES
    cmakeplugin.cpp
)

add_executable(${PROJECT_NAME} ${INCLUDE} ${SOURCES} ${SRC_LIST})

add_library( cmakePlugin SHARED cmakeplugin.cpp )
</code>```

QMake .pro

Works

```<code>QT       += widgets

TARGET = HelloPlugin
TEMPLATE = lib

SOURCES += helloplugin.cpp

HEADERS += helloplugin.h \
    helloplugin_global.h

CONFIG += plugin debug

INSTALLS += target
</code>```

答:
Qt generates meta code for plugins, add the following to CMakeLists.txt:

```<code>set(CMAKE_AUTOMOC ON)
</code>```

Here's a complete working example:

CMakeLists.txt

```<code>project(test-plugin)
cmake_minimum_required(VERSION 3.2.0)

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)

find_package(Qt5Widgets REQUIRED)

set(COMPILE_OPTIONS -std=c++11)

add_library(test-plugin SHARED test-plugin.cpp)
target_link_libraries(test-plugin PRIVATE Qt5::Widgets)
target_compile_options(test-plugin PRIVATE ${COMPILE_OPTIONS})

add_executable(test-plugin-exec main.cpp)
target_link_libraries(test-plugin-exec PRIVATE Qt5::Widgets)
target_compile_options(test-plugin-exec PRIVATE ${COMPILE_OPTIONS})
</code>```

test-plugin-interface.hpp

```<code>#ifndef TEST_PLUGIN_INTERFACE
#define TEST_PLUGIN_INTERFACE
#include <QtPlugin>

class TestPluginInterface
{
public:
    virtual ~TestPluginInterface() {}
    virtual void doSomething() const = 0;
};

#define TestPluginInterface_iid "whatever.you.want.TestPluginInterface"
Q_DECLARE_INTERFACE(TestPluginInterface, TestPluginInterface_iid)
#endif // TEST_PLUGIN_INTERFACE
</code>```

test-plugin.hpp

```<code>#ifndef TEST_PLUGIN_HPP
#define TEST_PLUGIN_HPP
#include <QObject>
#include <QtPlugin>
#include "test-plugin-interface.hpp"

class TestPlugin : public QObject, public TestPluginInterface
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID TestPluginInterface_iid)
    Q_INTERFACES(TestPluginInterface)

public:
    ~TestPlugin() override {}
    void doSomething() const override;
};
#endif // TEST_PLUGIN_HPP
</code>```

test-plugin.cpp

```<code>#include <QDebug>
#include "test-plugin.hpp"

void TestPlugin::doSomething() const
{
    qDebug()<< "hot dog!";
}
</code>```

main.cpp

```<code>#include <assert.h>
#include <QDebug>
#include <QPluginLoader>
#include "test-plugin.hpp"

constexpr auto ABSOLUTE_PATH_TO_PLUGIN =
    "/path/to/build/libtest-plugin.so";

int main(int argc, char* argv[])
{
    assert(QLibrary::isLibrary(ABSOLUTE_PATH_TO_PLUGIN));
    QPluginLoader loader(ABSOLUTE_PATH_TO_PLUGIN);
    if (auto instance = loader.instance()) {
        if (auto plugin = qobject_cast< TestPluginInterface* >(instance)){
            plugin->doSomething();
        }
        else {
            qDebug()<< "qobject_cast<> returned nullptr";
        }
    }
    else {
      qDebug()<< loader.errorString();
    }
}
</code>```

Title: Using CMake with Qt5 and Qt Plugins

Body:
I'd like to avoid using qmake and .pro files. The problem is that I cannot get cmake to work nicely with Qt Plugins. I've included the code below showing the interface, plugin, loader that work correctly for the given .pro file but I cannot figure out how to transfer this functionality to cmake.

Plugin Interface

Pure virtual interface, known by the loader.

#include <QtCore/qglobal.h>

class HelloPluginInterface
{
public:
    virtual void DoSomething() const = 0;
};

Q_DECLARE_INTERFACE( HelloPluginInterface, "com.harbrick.Qt.HelloPluginInterface")

Plugin

Plugin that becomes a .so to be loaded by the loader.

#include <QtPlugin>
#include "helloplugin_global.h"

class HelloPlugin : public QObject, public HelloPluginInterface
{
    Q_OBJECT
    Q_PLUGIN_METADATA( IID "com.harbrick.Qt.HelloPluginInterface" )
    Q_INTERFACES( HelloPluginInterface )

public:
    void DoSomething() const;
};

Plugin Loader

void MainWindow::LoadPlugin( const QString& pathToLibrary )
{
    QPluginLoader loader( pathToLibrary );
    QObject* instance = loader.instance();

    if( instance )
    {
        HelloPluginInterface *plugin = qobject_cast< HelloPluginInterface* >( instance );
        if(plugin)
        {
            //do stuff
            ...
        }
        else
        {
            qDebug() << "Not a plugin: " << Filename << " = " << loader.errorString();
        }
    }
}

CMakeLists.txt

Can't get to work

project( HelloPlugin )
cmake_minimum_required( VERSION 2.8.11 )

set( CMAKE_INCLUDE_CURRENT_DIR ON )

find_package(Qt5Widgets)

include_directories(
    ${CMAKE_CURRENT_SOURCE_DIR}
)

set( INCLUDE
    cmakeplugin.h
    cmakeplugininterface.h
)

set( SOURCES
    cmakeplugin.cpp
)

add_executable(${PROJECT_NAME} ${INCLUDE} ${SOURCES} ${SRC_LIST})

add_library( cmakePlugin SHARED cmakeplugin.cpp )

QMake .pro

Works

QT       += widgets

TARGET = HelloPlugin
TEMPLATE = lib

SOURCES += helloplugin.cpp

HEADERS += helloplugin.h \
    helloplugin_global.h

CONFIG += plugin debug

INSTALLS += target

Body:
Qt generates meta code for plugins, add the following to CMakeLists.txt:

set(CMAKE_AUTOMOC ON)

Here's a complete working example:

CMakeLists.txt

project(test-plugin)
cmake_minimum_required(VERSION 3.2.0)

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)

find_package(Qt5Widgets REQUIRED)

set(COMPILE_OPTIONS -std=c++11)

add_library(test-plugin SHARED test-plugin.cpp)
target_link_libraries(test-plugin PRIVATE Qt5::Widgets)
target_compile_options(test-plugin PRIVATE ${COMPILE_OPTIONS})

add_executable(test-plugin-exec main.cpp)
target_link_libraries(test-plugin-exec PRIVATE Qt5::Widgets)
target_compile_options(test-plugin-exec PRIVATE ${COMPILE_OPTIONS})

test-plugin-interface.hpp

#ifndef TEST_PLUGIN_INTERFACE
#define TEST_PLUGIN_INTERFACE
#include <QtPlugin>

class TestPluginInterface
{
public:
    virtual ~TestPluginInterface() {}
    virtual void doSomething() const = 0;
};

#define TestPluginInterface_iid "whatever.you.want.TestPluginInterface"
Q_DECLARE_INTERFACE(TestPluginInterface, TestPluginInterface_iid)
#endif // TEST_PLUGIN_INTERFACE

test-plugin.hpp

#ifndef TEST_PLUGIN_HPP
#define TEST_PLUGIN_HPP
#include <QObject>
#include <QtPlugin>
#include "test-plugin-interface.hpp"

class TestPlugin : public QObject, public TestPluginInterface
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID TestPluginInterface_iid)
    Q_INTERFACES(TestPluginInterface)

public:
    ~TestPlugin() override {}
    void doSomething() const override;
};
#endif // TEST_PLUGIN_HPP

test-plugin.cpp

#include <QDebug>
#include "test-plugin.hpp"

void TestPlugin::doSomething() const
{
    qDebug()<< "hot dog!";
}

main.cpp

#include <assert.h>
#include <QDebug>
#include <QPluginLoader>
#include "test-plugin.hpp"

constexpr auto ABSOLUTE_PATH_TO_PLUGIN =
    "/path/to/build/libtest-plugin.so";

int main(int argc, char* argv[])
{
    assert(QLibrary::isLibrary(ABSOLUTE_PATH_TO_PLUGIN));
    QPluginLoader loader(ABSOLUTE_PATH_TO_PLUGIN);
    if (auto instance = loader.instance()) {
        if (auto plugin = qobject_cast< TestPluginInterface* >(instance)){
            plugin->doSomething();
        }
        else {
            qDebug()<< "qobject_cast<> returned nullptr";
        }
    }
    else {
      qDebug()<< loader.errorString();
    }
}


问:
When JWT expires, will the JWT stored in local storage be removed automatically?
I have JWT already stored in the user's browser's local storage.
I have set the JWT's expiration date to be on in 7 days using nodejs/express.

Will the browser detect the expiration date and automatically remove it from the local storage? or will my server have to check the JWT and remove the expired JWT from the user's browser's local storage?

答: Local storage does not have an auto-expiring feature so the browser will not remove the JWT from local storage. It will be up to you or a library to inspect if a JWT has expired and remove it. There is no harm in leaving an expired JWT in local storage as once it has expired no one can use it.</p>


问:
How to pull certain information from excel spreadsheet?
I am extremely new to python and want to learn how to pull certain elements from a data sheet. For example:

How many attributes/categories the data has?

How many missing values the data has?

How many columns the data has?

The frequency of an element in a single column

I have gotten as far as printing the data but am wondering how I can compute the above values via while loops or for loops

```<code>file=open('9car.csv','r')

M=[]
lines=file.readlines()
for row in lines:
     value=row.strip()
     items=value.split()
     # print(items)
     print(value)
     # print(values)

for row in M:
     count=len(row)
     print(count)
</code>```

答: The standard library (documented for your version of python at python.org) contains a module called csv. It has a number of functions for parsing csv files. This may be a better solution for you than trying to read and parse each line from scratch.</p>

Body:
I am extremely new to python and want to learn how to pull certain elements from a data sheet. For example:

How many attributes/categories the data has?

How many missing values the data has?

How many columns the data has?

The frequency of an element in a single column

I have gotten as far as printing the data but am wondering how I can compute the above values via while loops or for loops

file=open('9car.csv','r')

M=[]
lines=file.readlines()
for row in lines:
     value=row.strip()
     items=value.split()
     # print(items)
     print(value)
     # print(values)

for row in M:
     count=len(row)
     print(count)


问:
Visual Studio 2017 Debugger Won't Refresh Browser Anymore
I've used VS for 10 years and have never had this problem until yesterday. I can no longer see changes to my website when I'm debugging using localhost.
For example...I make a change to a .aspx page while I'm debugging and refresh the page in my browser (ctrl+F5), but the change does not appear.  Here's what I've tried so far:

Chrome and Firefox

Exiting IISExpress

Stopping debugger and restarting

Creating a new .aspx page

Closing my solution

Creating a brand new solution

Trying other solutions

Closing VS

Restarting my machine (Windows 7)

Enabling/Disabling BrowserLink

Deleting my Solution (.sln) file

Running VS as administrator

Tools=>Options=>Projects and Solutions=>.NET CORE (unchecked "Don't call MSBuild if a project appears to be upt to date")

Added  Response.Write("Test"); to Page Load of code behind.  Did not show up until I restarted VS.  After adding a second line and setting a breakpoint on it, VS does not recognize the breakpoint and line 2 does not show up in browser.

Important Notes:

.html pages work fine.

The solution builds successfully.

The only change to my system was a windows update the day before that
  installed .NET Core SDK - 2.0.3(x64) and updates to Adobe Flash Player
  27.

答: After two days of trying, finally found a solution.  Had to go into the control panel => Programs and Features => right click on Microsoft Visual Studio 2017 => Change => on the Change Screen look for the "More" drop down and pick "Repair".  Took a long time and required a restart but it appears to have solved the issue.</p>


问:
How can I add assembly binding logs to my MSBuild output?
I have an SSIS project that builds successfully locally, but does not build when it is run on our build server (TeamCity). I get errors along the lines of

SSISBuild.proj(11, 5): Could not load file or assembly 'Microsoft.SqlServer.DTSRuntimeWrap, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

I have the relevant file checked into source control.  Clearly, I'm having some kind of error loading/finding that file.  Is there any way, through MSBuild or the underlying TeamCity agent, to produce more detailed logs as to the Assembly Binding/Discovery process that was executed, in order to enable me to troubleshoot this issue with a little more clarity?

答:
MSBuild cannot build an SSIS project out of the box.  You'll need a custom DLL to tell MSBuild what to do.  This is a good description of what needs to be done, but some of the links may be dated:
https://speaksql.wordpress.com/2013/06/07/a-journey-to-db-deployment-automaton-ssis-build-using-msbuild/

I put up a newer version of the msbuild project which will also help with deployment and building environments: https://github.com/MarkWojciechowicz/MSBI_Builder

This really needs a new blog post
m


问:
Detecting and changing via screen width is not working
So, I checked out Do something if screen width is less than 960 px to see how to execute something if the screen size was less than 960 px. However, it did not work for me. Their answer was this:

```<code>if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}
</code>```

I tried it and it did work. I also already had an alert that told me the screen size;

```<code>var size = $(window).width();
alert(size);
</code>```

and this worked, but this did not:

```<code>if (size < 1200) {
    $("#mobileVersionDetected").css("display", "block");
}
else {
    $("#mobileVersionDetected").css("display", "none");
}
</code>```

Any ideas?

答:
To echo @charlietfl, this is exactly what CSS Media Queries are for. They eliminate the need for script and are more efficient.

    /* Baseline styles applied initially: */
    body { background-color: #b200ff; /* purple */ }

    p    {
      border:1px solid black;
      background: white;
      padding:5px;
      text-align:center;
      font:bold 1.2em Arial;

    }

    /*
       When writing multiple media queries that don't explicitly
       specify a range, the order of the queries matter!!!

       For example:

          With a viewport of 400px wide, both of the the following
          two queries would apply:

           @media screen and (max-width:400px) {...}
           @media screen and (max-width:600px) {...}

      So, the last one would be used.
    */

    /*
       Note that this query uses "min-width",
       not "max-width" so that it handles
       all viewports bigger than 1200
    */
    @media screen and (min-width: 1201px) {
      body { background-color: orange; }
      p:after { content: "over 1200px"; }
    }

    /*
       Here, we're using "max-width" to handle
       viewports up to the specified sizes:
    */
    @media screen and (max-width: 1200px) {
      body { background-color: yellow; }
      p:after { content: "961px to 1200px"; }
    }

    @media screen and (max-width: 960px) {
      body { background-color: blue; }
      p:after { content: "769px to 960px"; }
    }

    @media screen and (max-width: 768px) {
      body { background-color: grey; }
      p:after { content: "551px to 768px"; }
    }

    @media screen and (max-width: 550px) {
      body { background-color: green; }
      p:after { content: "321px to 550px"; }
    }

    @media screen and (max-width:320px) {
      body { background-color: red; }
      p:after { content: "up to 320px wide"; }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p></p></code>```

Body:
So, I checked out Do something if screen width is less than 960 px to see how to execute something if the screen size was less than 960 px. However, it did not work for me. Their answer was this:

if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}

I tried it and it did work. I also already had an alert that told me the screen size;

var size = $(window).width();
alert(size);

and this worked, but this did not:

if (size < 1200) {
    $("#mobileVersionDetected").css("display", "block");
}
else {
    $("#mobileVersionDetected").css("display", "none");
}

Any ideas?

Body:
To echo @charlietfl, this is exactly what CSS Media Queries are for. They eliminate the need for script and are more efficient.

    /* Baseline styles applied initially: */
    body { background-color: #b200ff; /* purple */ }

    p    {
      border:1px solid black;
      background: white;
      padding:5px;
      text-align:center;
      font:bold 1.2em Arial;

    }

    /*
       When writing multiple media queries that don't explicitly
       specify a range, the order of the queries matter!!!

       For example:

          With a viewport of 400px wide, both of the the following
          two queries would apply:

           @media screen and (max-width:400px) {...}
           @media screen and (max-width:600px) {...}

      So, the last one would be used.
    */

    /*
       Note that this query uses "min-width",
       not "max-width" so that it handles
       all viewports bigger than 1200
    */
    @media screen and (min-width: 1201px) {
      body { background-color: orange; }
      p:after { content: "over 1200px"; }
    }

    /*
       Here, we're using "max-width" to handle
       viewports up to the specified sizes:
    */
    @media screen and (max-width: 1200px) {
      body { background-color: yellow; }
      p:after { content: "961px to 1200px"; }
    }

    @media screen and (max-width: 960px) {
      body { background-color: blue; }
      p:after { content: "769px to 960px"; }
    }

    @media screen and (max-width: 768px) {
      body { background-color: grey; }
      p:after { content: "551px to 768px"; }
    }

    @media screen and (max-width: 550px) {
      body { background-color: green; }
      p:after { content: "321px to 550px"; }
    }

    @media screen and (max-width:320px) {
      body { background-color: red; }
      p:after { content: "up to 320px wide"; }
    }

<p></p>


问:
Cordova app not displaying correctly on iPhone X (Simulator)
I tested my Cordova-based app yesterday on the iPhone X Simulator in Xcode 9.0 (9A235) and it didn't look good.
Firstly, instead of filling the full screen area, there was a black area above and below the app content.
And worse, between the app content and the black was two white bars.

Adding cordova-plugin-wkwebview-engine so Cordova renders using WKWebView (not UIWebView) fixes the white bars.
By my app is not migrated from UIWebView to WKWebView due to performance and memory leak issues when using cordova-plugin-wkwebview-engine which occur when loading images downloaded from Inapp Purchase hosted content into an HTML5 canvas (direct file:// access by the Webview is not possible due to security restrictions in WKWebView so the image data must be loaded via cordova-plugin-file).

These screenshots show a test app with a blue background set on the <body>.
Above and below UIWebView, you can see the white bars, but not with WKWebView:

(source: pbrd.co)

(source: pbrd.co)

Both Cordova Webviews exhibit the black areas when compared to a native app which fills the full screen area:

答:
Just a note that the constant keyword use for safe-area margins has been updated to env for 11.2 beta+

https://webkit.org/blog/7929/designing-websites-for-iphone-x/

ContentLicense: CC BY-SA 4.0


问:
Insert a character at a specific location in a string
I would like to insert an extra character (or a new string) at a specific location in a string. For example, I want to insert d at the fourth location in abcefg to get abcdefg.

Now I am using:

```<code>old <- "abcefg"
n <- 4
paste(substr(old, 1, n-1), "d", substr(old, n, nchar(old)), sep = "")
</code>```

I could write a one-line simple function for this task, but I am just curious if there is an existing function for that.

答:
I've made a custom function called substr1 to deal with extracting, replacing and inserting chars in a string. Run these codes at the start of every session. Feel free to try it out and let me know if it needs to be improved.

```<code># extraction
substr1 <- function(x,y) {
  z <- sapply(strsplit(as.character(x),''),function(w) paste(na.omit(w[y]),collapse=''))
  dim(z) <- dim(x)
  return(z) }

# substitution + insertion
`substr1<-` <- function(x,y,value) {
  names(y) <- c(value,rep('',length(y)-length(value)))
  z <- sapply(strsplit(as.character(x),''),function(w) {
    v <- seq(w)
    names(v) <- w
    paste(names(sort(c(y,v[setdiff(v,y)]))),collapse='') })
  dim(z) <- dim(x)
  return(z) }

# demonstration
abc <- 'abc'
substr1(abc,1)
# "a"
substr1(abc,c(1,3))
# "ac"
substr1(abc,-1)
# "bc"
substr1(abc,1) <- 'A'
# "Abc"
substr1(abc,1.5) <- 'A'
# "aAbc"
substr1(abc,c(0.5,2,3)) <- c('A','B')
# "AaB"
</code>```

Body:
I would like to insert an extra character (or a new string) at a specific location in a string. For example, I want to insert d at the fourth location in abcefg to get abcdefg.

Now I am using:

old <- "abcefg"
n <- 4
paste(substr(old, 1, n-1), "d", substr(old, n, nchar(old)), sep = "")

I could write a one-line simple function for this task, but I am just curious if there is an existing function for that.

Body:
I've made a custom function called substr1 to deal with extracting, replacing and inserting chars in a string. Run these codes at the start of every session. Feel free to try it out and let me know if it needs to be improved.

# extraction
substr1 <- function(x,y) {
  z <- sapply(strsplit(as.character(x),''),function(w) paste(na.omit(w[y]),collapse=''))
  dim(z) <- dim(x)
  return(z) }

# substitution + insertion
`substr1<-` <- function(x,y,value) {
  names(y) <- c(value,rep('',length(y)-length(value)))
  z <- sapply(strsplit(as.character(x),''),function(w) {
    v <- seq(w)
    names(v) <- w
    paste(names(sort(c(y,v[setdiff(v,y)]))),collapse='') })
  dim(z) <- dim(x)
  return(z) }

# demonstration
abc <- 'abc'
substr1(abc,1)
# "a"
substr1(abc,c(1,3))
# "ac"
substr1(abc,-1)
# "bc"
substr1(abc,1) <- 'A'
# "Abc"
substr1(abc,1.5) <- 'A'
# "aAbc"
substr1(abc,c(0.5,2,3)) <- c('A','B')
# "AaB"


问:
How can you retrieve (RTO-, MTU- and SRTT-) information from a SCTP message?
How can you retrieve furhter information (like RTO, MTU and SRTT) from a struct sctp_rcvinfo of a received SCTP message?

Everytime a SCTP-message is reveived and processed via a callback function like

static int
receive_cb(struct socket *sock, union sctp_sockstore addr, void *data,
           size_t datalen, struct sctp_rcvinfo rcv, int flags, void *ulp_info)
{...

struct sctp_rcvinfo is filled with these additional information (I suppose).

You can find an example-client here.

But I need to convert this to data like

struct sctp_paddrinfo moreInfo; moreInfo.spinfo_rto .. and so on.

How can you achive this?

答:
RTO, MTU and SRTT are not part of SCTP messages. Endpoints do not exchange this information. Each side calculates its own SRTT and RTO and has it is own MTU.

From your endpoint you cannot obtain information about SRTT, RTO and MTU another side has.

SRTT, RTO and MTU values of your side for the peer can be found in sctp_info structure.

You can obtain this structure with following API call:

int sctp_get_sctp_info(struct sock *sk, struct sctp_association *asoc,
                       struct sctp_info *info);

See definition of sctp_get_sctp_info at sctp.h


问:
My "if statements" do not run, even though the parameters are true
Ok, so my code will compile as if there are no errors, but then the code that should be executed will not truly run. Please help.

```<code>public static void newGameCheck()   {
    String newCharacter = scan.next();
    if (newCharacter.equals("New game"))    {
    //more code here, but it does not get executed for some reason
    }
</code>```

And another example is here:

```<code>public static void warriorTurn()    {
    if (warriorAlive==true) {
        etut.choosingTarget();
        int target= scan.nextInt();
        System.out.println("Now type in which ability you want him to use, make sure to use capitals");
        warrior_Weapons_and_Abilities();

String ability= scan.next();
            if (ability.equals("Anduril, Foe of Terror"))   {
                int damage= 100+((int) (Math.random()*50));
                etut.loseHealth(target, damage);
                mana2=mana2-0;
                etut.displayHealth(target);
            }
            else if (ability.equals("Aethereal Blades"))    {

int damage= 250+((int) (Math.random()*100));
                etut.loseHealth(target, damage);
                mana2=mana2-2;
                etut.displayHealth(target);
            }
            else if (ability.equals("Potion"))  {
            health2=health2+100;
            mana=mana-0;
            etut.displayHealth(target);

    }
</code>```

Here^, whenever I type in the ability name, the code still will not execute

答: Change all scan.next() to scan.nextLine(). scan.next() only will read one word.

Body:
Ok, so my code will compile as if there are no errors, but then the code that should be executed will not truly run. Please help.

public static void newGameCheck()   {
    String newCharacter = scan.next();
    if (newCharacter.equals("New game"))    {
    //more code here, but it does not get executed for some reason
    }

And another example is here:

public static void warriorTurn()    {
    if (warriorAlive==true) {
        etut.choosingTarget();
        int target= scan.nextInt();
        System.out.println("Now type in which ability you want him to use, make sure to use capitals");
        warrior_Weapons_and_Abilities();

String ability= scan.next();
            if (ability.equals("Anduril, Foe of Terror"))   {
                int damage= 100+((int) (Math.random()*50));
                etut.loseHealth(target, damage);
                mana2=mana2-0;
                etut.displayHealth(target);
            }
            else if (ability.equals("Aethereal Blades"))    {

int damage= 250+((int) (Math.random()*100));
                etut.loseHealth(target, damage);
                mana2=mana2-2;
                etut.displayHealth(target);
            }
            else if (ability.equals("Potion"))  {
            health2=health2+100;
            mana=mana-0;
            etut.displayHealth(target);

    }

Here^, whenever I type in the ability name, the code still will not execute


问:
Plot type for illustrating before and after scores
Given a basic dataset like so:

```<code>import pandas as pd

df = pd.DataFrame([
  {'sid': 'SID0', 'before': .5, 'after': .8},
  {'sid': 'SID1', 'before': .6, 'after': .4},
  {'sid': 'SID2', 'before': .2, 'after': .2}
]);
# `before `has max value of 1.0; same for `after`, as these are percentages
</code>```

What's a way of charting the difference between before & after scores?

Thinking to exclude the SID, and showing the distribution properly (# of students matters; not just scatter-plotting the scores). With the SID I played around with slope graphs, but that's just not good to show aggregate reflections.

答:
A proposal: you may plot a line plot for each SID.

```<code>import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame([
  {'sid': 'SID0', 'before': .5, 'after': .8},
  {'sid': 'SID1', 'before': .6, 'after': .4},
  {'sid': 'SID2', 'before': .2, 'after': .2}
]);

df = df.set_index("sid")[['before', "after"]].T

ax = df.plot(marker="o")
ax.set_xlim(-1,2)
ax.set_xticks([0,1])
ax.set_xticklabels(df.index)

plt.show()
</code>```

Body:
Given a basic dataset like so:

import pandas as pd

df = pd.DataFrame([
  {'sid': 'SID0', 'before': .5, 'after': .8},
  {'sid': 'SID1', 'before': .6, 'after': .4},
  {'sid': 'SID2', 'before': .2, 'after': .2}
]);
# `before `has max value of 1.0; same for `after`, as these are percentages

What's a way of charting the difference between before & after scores?

Thinking to exclude the SID, and showing the distribution properly (# of students matters; not just scatter-plotting the scores). With the SID I played around with slope graphs, but that's just not good to show aggregate reflections.

Body:
A proposal: you may plot a line plot for each SID.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame([
  {'sid': 'SID0', 'before': .5, 'after': .8},
  {'sid': 'SID1', 'before': .6, 'after': .4},
  {'sid': 'SID2', 'before': .2, 'after': .2}
]);

df = df.set_index("sid")[['before', "after"]].T

ax = df.plot(marker="o")
ax.set_xlim(-1,2)
ax.set_xticks([0,1])
ax.set_xticklabels(df.index)

plt.show()


答:
```<code><?php if ($foo) { ?>
    <div class="mydiv">Condition is true</div>
<?php } else { ?>
    <div class="myotherdiv">Condition is false</div>
<?php } ?>
</code>```

Title: If else embedding inside html

Body: What is the correct way of embedding if else  and elseif conditions inside html?


问:
Loop for generating lottery numbers
I am working with R and using the expression sort(sample(1:60,6,replace=FALSE)) for generating 6 numbers between 1 and 60, without replacement...

I would like to create a loop using FOR statements that allow to generate n different samples, using the logic above.

Any suggestion about how to build this loop?

答:
Use replicate:

```<code>replicate(sort(sample(1:60, 6, replace = FALSE)), n = 1000)
</code>```

The result is a matrix of size 6x1000, so each column is one sample.

I guess you want to do random draws which would allow equal samples. In case you do want unique samples, I gave it a shot:

```<code>lottery <- function(n) {
  S <- replicate(sort.int(sample(1:60, 6, repl = F)), n = n)
  while(d <- anyDuplicated(S, MARGIN = 2)) {
    S <- cbind(S[, -d], sort.int(sample(1:60, 6, repl = F)))
  }
  S
}
</code>```

Title: Loop for generating lottery numbers

Body:
Use replicate:

replicate(sort(sample(1:60, 6, replace = FALSE)), n = 1000)

The result is a matrix of size 6x1000, so each column is one sample.

I guess you want to do random draws which would allow equal samples. In case you do want unique samples, I gave it a shot:

lottery <- function(n) {
  S <- replicate(sort.int(sample(1:60, 6, repl = F)), n = n)
  while(d <- anyDuplicated(S, MARGIN = 2)) {
    S <- cbind(S[, -d], sort.int(sample(1:60, 6, repl = F)))
  }
  S
}


问:
Chef multiple conditions
I have the following chef/powershell code:

```<code># Configure Registry Keys
powershell_script 'Configure Registry Keys' do
    code <<-EOH

    # Set the default location for data files
    Set-ItemProperty -Path "HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer" -Name DefaultData -Value "D:\\Program Files\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQL\\DATA"

    # Set the default location for log files
    Set-ItemProperty -Path "HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer" -Name DefaultLog -Value "L:\\Program Files\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQL\\DATA"

    # Set the default location for backup files
    Set-ItemProperty -Path "HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer" -Name BackupDirectory -Value "B:\\sqlbackups"

    restart-service *sql* -force
    EOH
    guard_interpreter :powershell_script
    not_if "(Get-ItemProperty \"HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer\").PSObject.Properties.Name -contains \"DefaultData\""
    not_if "(Get-ItemProperty \"HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer\").PSObject.Properties.Name -contains \"DefaultLog\""
    not_if "(Get-ItemProperty \"HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer\").PSObject.Properties.Name -contains \"BackupDirectory\""
 end
</code>```

However when I run it it fails to run:

```<code> * powershell_script[Configure Registry Keys] action run (skipped due to not_if)
</code>```

That's because one of the keys exists but the other two do not.

What I'd like to happen is for the keys to get created if ANY of them don't exist. It seems like with multiple not_ifs if any of them result in a $true then it skipped.

What I want is that if any of them return $false then execute.

I tried to switch my not_if to an only_if but that seems to have the same problem (just in reverse)

So how can I concatenate multiple not_if or only_if statements together so that they all have to return $false (or all $true - depending on if only_if is being used)

Hopefully this makes sense but please let me know if it doesn't :)

答:
Here's a test for any of them not existing:</p>

```<code>not_if "$Name=(Get-ItemProperty 'HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer').PSObject.Properties.Name; $Name -contains 'DefaultData' -and $Name -contains 'DefaultLog' -and $Name -contains 'BackupDirectory'"
</code>```

Title: Chef multiple conditions

Body:
I have the following chef/powershell code:

# Configure Registry Keys
powershell_script 'Configure Registry Keys' do
    code <<-EOH

    # Set the default location for data files
    Set-ItemProperty -Path "HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer" -Name DefaultData -Value "D:\\Program Files\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQL\\DATA"

    # Set the default location for log files
    Set-ItemProperty -Path "HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer" -Name DefaultLog -Value "L:\\Program Files\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQL\\DATA"

    # Set the default location for backup files
    Set-ItemProperty -Path "HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer" -Name BackupDirectory -Value "B:\\sqlbackups"

    restart-service *sql* -force
    EOH
    guard_interpreter :powershell_script
    not_if "(Get-ItemProperty \"HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer\").PSObject.Properties.Name -contains \"DefaultData\""
    not_if "(Get-ItemProperty \"HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer\").PSObject.Properties.Name -contains \"DefaultLog\""
    not_if "(Get-ItemProperty \"HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer\").PSObject.Properties.Name -contains \"BackupDirectory\""
 end

However when I run it it fails to run:

 * powershell_script[Configure Registry Keys] action run (skipped due to not_if)

That's because one of the keys exists but the other two do not.

What I'd like to happen is for the keys to get created if ANY of them don't exist. It seems like with multiple not_ifs if any of them result in a $true then it skipped.

What I want is that if any of them return $false then execute.

I tried to switch my not_if to an only_if but that seems to have the same problem (just in reverse)

So how can I concatenate multiple not_if or only_if statements together so that they all have to return $false (or all $true - depending on if only_if is being used)

Hopefully this makes sense but please let me know if it doesn't :)

Body:
Here's a test for any of them not existing:

not_if "$Name=(Get-ItemProperty 'HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQLServer').PSObject.Properties.Name; $Name -contains 'DefaultData' -and $Name -contains 'DefaultLog' -and $Name -contains 'BackupDirectory'"


问:
WordPress Category custom fields
Hi I want to filter posts with custom category fields. I created custom field and it's working.

```<code>/*  Custom Field for Categories.
    ======================================== */

// Add new term page
function my_taxonomy_add_meta_fields( $taxonomy ) { ?>
    <div class="form-field term-group">
        <label for="show_category">
          <?php _e( 'Show Category', 'codilight-lite' ); ?> <input type="checkbox" id="show_category" name="show_category" value="yes" />
        </label>
    </div><?php
}
add_action( 'category_add_form_fields', 'my_taxonomy_add_meta_fields', 10, 2 );

// Edit term page
function my_taxonomy_edit_meta_fields( $term, $taxonomy ) {
    $show_category = get_term_meta( $term->term_id, 'show_category', true ); ?>

    <tr class="form-field term-group-wrap">
        <th scope="row">
            <label for="show_category"><?php _e( 'Show Category', 'codilight-lite' ); ?></label>
        </th>
        <td>
            <input type="checkbox" id="show_category" name="show_category" value="yes" <?php echo ( $show_category ) ? checked( $show_category, 'yes' ) : ''; ?>/>
        </td>
    </tr><?php
}
add_action( 'category_edit_form_fields', 'my_taxonomy_edit_meta_fields', 10, 2 );

// Save custom meta
function my_taxonomy_save_taxonomy_meta( $term_id, $tag_id ) {
    if ( isset( $_POST[ 'show_category' ] ) ) {
        update_term_meta( $term_id, 'show_category', 'yes' );
    } else {
        update_term_meta( $term_id, 'show_category', '' );
    }
}
add_action( 'created_category', 'my_taxonomy_save_taxonomy_meta', 10, 2 );
add_action( 'edited_category', 'my_taxonomy_save_taxonomy_meta', 10, 2 );
</code>```

Now I want to filter posts which show category select box checked yes. I'm trying query like this but it's not working

```<code>$argswp = array(
'post_type' => "post",
'tax_query' => array( array(
    'taxonomy' => 'season',
    'field' => 'slug',
    'terms' => 'yes'
    )),
);

$the_query = new WP_Query($argswp);
</code>```

I tried slug or id in field section by the way it's still not working. How can I fix this?

答: I think you need to adjust the options more. Specifically the terms, taxonomy, and field</p>

Title: WordPress Category custom fields

Body:
Hi I want to filter posts with custom category fields. I created custom field and it's working.

/*  Custom Field for Categories.
    ======================================== */

// Add new term page
function my_taxonomy_add_meta_fields( $taxonomy ) { ?>

          <?php _e( 'Show Category', 'codilight-lite' ); ?> <input type="checkbox" id="show_category" name="show_category" value="yes" />

<?php
}
add_action( 'category_add_form_fields', 'my_taxonomy_add_meta_fields', 10, 2 );

// Edit term page
function my_taxonomy_edit_meta_fields( $term, $taxonomy ) {
    $show_category = get_term_meta( $term->term_id, 'show_category', true ); ?>

            <?php _e( 'Show Category', 'codilight-lite' ); ?>

            <input type="checkbox" id="show_category" name="show_category" value="yes" <?php echo ( $show_category ) ? checked( $show_category, 'yes' ) : ''; ?>/>

<?php
}
add_action( 'category_edit_form_fields', 'my_taxonomy_edit_meta_fields', 10, 2 );

// Save custom meta
function my_taxonomy_save_taxonomy_meta( $term_id, $tag_id ) {
    if ( isset( $_POST[ 'show_category' ] ) ) {
        update_term_meta( $term_id, 'show_category', 'yes' );
    } else {
        update_term_meta( $term_id, 'show_category', '' );
    }
}
add_action( 'created_category', 'my_taxonomy_save_taxonomy_meta', 10, 2 );
add_action( 'edited_category', 'my_taxonomy_save_taxonomy_meta', 10, 2 );

Now I want to filter posts which show category select box checked yes. I'm trying query like this but it's not working

$argswp = array(
'post_type' => "post",
'tax_query' => array( array(
    'taxonomy' => 'season',
    'field' => 'slug',
    'terms' => 'yes'
    )),
);

$the_query = new WP_Query($argswp);

I tried slug or id in field section by the way it's still not working. How can I fix this?


问:
regex: Match word only when another word is not present
I have this Regex

```<code>/^(?!(.*(Ink|Cartridge).*))(?:.*(\b - Black$\b))/
</code>```

Below are my samples

```<code>no match string
Simple match string - Black
Unmatched line with lowercase - black
Unmatched line with the word Ink within - Black
Unmatched line with the word Cartridge within - Black
Unmatched line with the string' - Black' before the end
</code>```

My regex matches the entire line 2, but I am trying to match just the word
 ' - Black' at the end of the string and not the entire string.

The regular expression syntax should be based on JavaScript regular expressions.

any ideas?

答:
If you need to match the word '-Black' only, the correct regex would be:

```<code>/- Black/
</code>```

The regex above just matches - Black as asked by the question.

However, indeed you have more needs than "matching - Black ", rather you want

all occurrences of the string - Black only when its underlying sentence does not contain Ink nor Cartridge, and only if - Black is at the end of the sentence and not - black (lowercase)

Now, if you just want what I exposed, it is not a problem for you to match ALL the sentence at the same time as the desired - Black string. In fact, this is what capturing is for in the regex world. The parenthesis ( and ) you put in your regex actually "grabs/takes/captures" what's in it for you and STORES it in a variable for later use.

This means :

```<code>/hello (world)/
</code>```

would MATCH hello world but CAPTURE only world. This capture goes into a variable named group, and here I have only one group, so world would be stored in the group number 1.

In order to CALL this group for other purpose (storing/deleting/replacing), you need to write a dollar sign $ followed by the number of the desired group (here 1). For this example, $1 should output world. So this is how you can MATCH something while CAPTURING another.

Thus, coming back to your example. I would suggest you do something like:

```<code>/^(?!(?:.*(?:Ink|Cartridge).*))(?:.*(?: (- Black)$))/gm
</code>```

Look at this regex101, open the substitution tab below the examples, and try to write $1: there you have it,

just - Black.

Then it's up to you to do something with $1.

Body:
I have this Regex

/^(?!(.*(Ink|Cartridge).*))(?:.*(\b - Black$\b))/

Below are my samples

no match string
Simple match string - Black
Unmatched line with lowercase - black
Unmatched line with the word Ink within - Black
Unmatched line with the word Cartridge within - Black
Unmatched line with the string' - Black' before the end

My regex matches the entire line 2, but I am trying to match just the word
 ' - Black' at the end of the string and not the entire string.

The regular expression syntax should be based on JavaScript regular expressions.

any ideas?

Body:
If you need to match the word '-Black' only, the correct regex would be:

/- Black/

The regex above just matches - Black as asked by the question.

However, indeed you have more needs than "matching - Black ", rather you want

all occurrences of the string - Black only when its underlying sentence does not contain Ink nor Cartridge, and only if - Black is at the end of the sentence and not - black (lowercase)

Now, if you just want what I exposed, it is not a problem for you to match ALL the sentence at the same time as the desired - Black string. In fact, this is what capturing is for in the regex world. The parenthesis ( and ) you put in your regex actually "grabs/takes/captures" what's in it for you and STORES it in a variable for later use.

This means :

/hello (world)/

would MATCH hello world but CAPTURE only world. This capture goes into a variable named group, and here I have only one group, so world would be stored in the group number 1.

In order to CALL this group for other purpose (storing/deleting/replacing), you need to write a dollar sign $ followed by the number of the desired group (here 1). For this example, $1 should output world. So this is how you can MATCH something while CAPTURING another.

Thus, coming back to your example. I would suggest you do something like:

/^(?!(?:.*(?:Ink|Cartridge).*))(?:.*(?: (- Black)$))/gm

Look at this regex101, open the substitution tab below the examples, and try to write $1: there you have it,

just - Black.

Then it's up to you to do something with $1.


问:
Python dataframe group labeling
Is there any tool in Pandas or other python package to facilitate the labeling of groups of varying number rows in a Pandas’ dataFrame? Here are more detail:

My dataFrame has a column of datetime.datetime objects used as the dataFrame index. The time is not evenly spaced and during a given amount of time, the number of rows varies.

In that dataFrame, I need to make a column that has a different label for each series of rows that span over a constant time span (12 seconds in my case).

For example, using examples with seconds

```<code>Time(s) | label
1           |   0
2           |   0
3           |   0
7           |   0
12         |   1
15         |   1
20         |   1
24          |   2
Etc…
</code>```

I’m looking for an alternative as a brute-force loop. Algorithms somewhat related to that are labeling, segmenting, mapping but i'm not sure what to look for exactly. I was hoping there would be something exploiting python, Pandas and/or Numpy in a more efficient way since the number of rows is gonna be of the order of a hundred millions.

Thanks

答:
IIUC, and Time(s) is an integer dtype, then I think what you need is the floordiv.</p>

```<code>df['label'] = df['Time(s)'] // 12
</code>```

Title: Python dataframe group labeling

Body:
Is there any tool in Pandas or other python package to facilitate the labeling of groups of varying number rows in a Pandas’ dataFrame? Here are more detail:

My dataFrame has a column of datetime.datetime objects used as the dataFrame index. The time is not evenly spaced and during a given amount of time, the number of rows varies.

In that dataFrame, I need to make a column that has a different label for each series of rows that span over a constant time span (12 seconds in my case).

For example, using examples with seconds

Time(s) | label
1           |   0
2           |   0
3           |   0
7           |   0
12         |   1
15         |   1
20         |   1
24          |   2
Etc…

I’m looking for an alternative as a brute-force loop. Algorithms somewhat related to that are labeling, segmenting, mapping but i'm not sure what to look for exactly. I was hoping there would be something exploiting python, Pandas and/or Numpy in a more efficient way since the number of rows is gonna be of the order of a hundred millions.

Thanks

Body:
IIUC, and Time(s) is an integer dtype, then I think what you need is the floordiv.

df['label'] = df['Time(s)'] // 12


问:
Getting rid of '... does not point to a valid object' for an old git branch
I have a fork of a Git repo and my clone appears to have an issue with an old, no longer existant, branch. I keep seeing this message:

error: refs/heads/t_1140 does not point to a valid object!

I don't have any other messages and the repo works fine. There's no operation that stops me from working on other branches, pushing changes, pulling...etc.

I've looked around and there's less than clear instructions on how to get around this issue. I've tried to execute git fsck --full but I see no errors. Just a load on dangling ... messages.

I've also checked my .git/config and there's no references to this branch and have also checked .git/refs/heads and there's no reference to t_1140

Any idea how to get rid of this error?

p.s I've tried to clone my repo again and it seems like the error is my Github repo too. So, the only thing I can think of right now is to ditch my repo and fork again.

答:
Do a text search through your .git directory for your branch

Use something like grep or findstr and remove all instances.


问:
Write A Header To Multiple WOrkbos
I am dynamically creating an Excel workbook based off an item count - and I want to write esssentially teh same header to each workbook.  My below syntax works for the first workbook, but the second a new workbook is created the error is thrown

This is my syntax - what do I need to do so that the header row is written to each workbook that is created?

```<code>Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Do While Not rs1.EOF
  i = 0
  x = 1
  name = rs1.Fields(0).Value
  Set xlWb = xlApp.Workbooks.Add
  row = 1
  xyz = 0
  Set HeaderWrite = xlWb.Worksheets(1)
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 1"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 2"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 3"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 4"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 5"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 6"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 7"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 8"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 9"
  xyz = xyz + 1
  xlWb.Worksheets(1).Range("$A$2") = name
  Set xlR = xlWb.Worksheets(1).Range("$N$2")
  Set rs2 = Db.OpenRecordset("SELECT * FROM MasterDB", dbOpenDynaset)
  With rs2
     .MoveLast
     .MoveFirst
     Do While Not .EOF
        xlR.Value = .Fields(0).Value
        xlR.Offset(ColumnOffset:=1).Value = .Fields(2).Value
        xlR.Offset(ColumnOffset:=2).Value = "Mainstreem"
        HeaderWrite.Cells(row, xyz + 1).Value = "Dept_" & i
        xyz = xyz + 1
        HeaderWrite.Cells(row, xyz + 1).Value = "Item" & i
        xyz = xyz + 1
        HeaderWrite.Cells(row, xyz + 1).Value = "CRN" & i
        xyz = xyz + 1
        i = i + 1
        Debug.Print i
        If i = 50 Then
           i = 0
           x = x + 1
           xlWb.SaveAs FileName:=sPath & sFile, FileFormat:=xlOpenXMLWorkbook
           xlWb.Close SaveChanges:=True
           Set xlWb = xlApp.Workbooks.Add
           sFile = name & "_" & "SalesLog" & x & ".xlsx"
           xlWb.Worksheets(1).Range("$C$2") = name
           Set xlR = xlWb.Worksheets(1).Range("$Q$2")
        Else
           Set xlR = xlR.Offset(ColumnOffset:=3)
        End If
        .MoveNext
     Loop
     .Close
  End With
</code>```

答:
This is completely untested, but hopefully I have moved things to the correct spots:</p>

```<code>Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Do While Not rs1.EOF
  i = 0
  x = 0  ' was 1 ??
  name = rs1.Fields(0).Value
  Set rs2 = Db.OpenRecordset("SELECT * FROM MasterDB", dbOpenDynaset)
  With rs2
     .MoveLast
     .MoveFirst
     Do While Not .EOF
        If i = 0 Then
           Set xlWb = xlApp.Workbooks.Add
           row = 1  ' This always stays as 1 ?!?!
           xyz = 0
           Set HeaderWrite = xlWb.Worksheets(1)
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 1"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 2"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 3"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 4"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 5"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 6"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 7"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 8"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 9"
           If x = 0 Then
               HeaderWrite.Range("$A$2") = name
               Set xlR = HeaderWrite.Range("$N$2")
           Else
               HeaderWrite.Range("$C$2") = name
               Set xlR = HeaderWrite.Range("$Q$2")
           End If
        End If
        xlR.Value = .Fields(0).Value
        xlR.Offset(ColumnOffset:=1).Value = .Fields(2).Value
        xlR.Offset(ColumnOffset:=2).Value = "Mainstreem"
        xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Dept_" & i
        xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Item" & i
        xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "CRN" & i
        Set xlR = xlR.Offset(ColumnOffset:=3)
        i = i + 1
        Debug.Print i
        If i = 50 Then
           i = 0
           x = x + 1
           'I moved this up - otherwise I don't think you have a filename
           sFile = name & "_" & "SalesLog" & x & ".xlsx"
           xlWb.SaveAs FileName:=sPath & sFile, FileFormat:=xlOpenXMLWorkbook
           xlWb.Close SaveChanges:=True
        End If
        .MoveNext
     Loop
     .Close
  End With
</code>```

Title: Write A Header To Multiple WOrkbos

Body:
I am dynamically creating an Excel workbook based off an item count - and I want to write esssentially teh same header to each workbook.  My below syntax works for the first workbook, but the second a new workbook is created the error is thrown

This is my syntax - what do I need to do so that the header row is written to each workbook that is created?

Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Do While Not rs1.EOF
  i = 0
  x = 1
  name = rs1.Fields(0).Value
  Set xlWb = xlApp.Workbooks.Add
  row = 1
  xyz = 0
  Set HeaderWrite = xlWb.Worksheets(1)
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 1"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 2"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 3"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 4"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 5"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 6"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 7"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 8"
  xyz = xyz + 1
  HeaderWrite.Cells(row, xyz + 1).Value = "Header 9"
  xyz = xyz + 1
  xlWb.Worksheets(1).Range("$A$2") = name
  Set xlR = xlWb.Worksheets(1).Range("$N$2")
  Set rs2 = Db.OpenRecordset("SELECT * FROM MasterDB", dbOpenDynaset)
  With rs2
     .MoveLast
     .MoveFirst
     Do While Not .EOF
        xlR.Value = .Fields(0).Value
        xlR.Offset(ColumnOffset:=1).Value = .Fields(2).Value
        xlR.Offset(ColumnOffset:=2).Value = "Mainstreem"
        HeaderWrite.Cells(row, xyz + 1).Value = "Dept_" & i
        xyz = xyz + 1
        HeaderWrite.Cells(row, xyz + 1).Value = "Item" & i
        xyz = xyz + 1
        HeaderWrite.Cells(row, xyz + 1).Value = "CRN" & i
        xyz = xyz + 1
        i = i + 1
        Debug.Print i
        If i = 50 Then
           i = 0
           x = x + 1
           xlWb.SaveAs FileName:=sPath & sFile, FileFormat:=xlOpenXMLWorkbook
           xlWb.Close SaveChanges:=True
           Set xlWb = xlApp.Workbooks.Add
           sFile = name & "_" & "SalesLog" & x & ".xlsx"
           xlWb.Worksheets(1).Range("$C$2") = name
           Set xlR = xlWb.Worksheets(1).Range("$Q$2")
        Else
           Set xlR = xlR.Offset(ColumnOffset:=3)
        End If
        .MoveNext
     Loop
     .Close
  End With

Body:
This is completely untested, but hopefully I have moved things to the correct spots:

Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Do While Not rs1.EOF
  i = 0
  x = 0  ' was 1 ??
  name = rs1.Fields(0).Value
  Set rs2 = Db.OpenRecordset("SELECT * FROM MasterDB", dbOpenDynaset)
  With rs2
     .MoveLast
     .MoveFirst
     Do While Not .EOF
        If i = 0 Then
           Set xlWb = xlApp.Workbooks.Add
           row = 1  ' This always stays as 1 ?!?!
           xyz = 0
           Set HeaderWrite = xlWb.Worksheets(1)
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 1"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 2"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 3"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 4"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 5"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 6"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 7"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 8"
           xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Header 9"
           If x = 0 Then
               HeaderWrite.Range("$A$2") = name
               Set xlR = HeaderWrite.Range("$N$2")
           Else
               HeaderWrite.Range("$C$2") = name
               Set xlR = HeaderWrite.Range("$Q$2")
           End If
        End If
        xlR.Value = .Fields(0).Value
        xlR.Offset(ColumnOffset:=1).Value = .Fields(2).Value
        xlR.Offset(ColumnOffset:=2).Value = "Mainstreem"
        xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Dept_" & i
        xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "Item" & i
        xyz = xyz + 1 : HeaderWrite.Cells(row, xyz).Value = "CRN" & i
        Set xlR = xlR.Offset(ColumnOffset:=3)
        i = i + 1
        Debug.Print i
        If i = 50 Then
           i = 0
           x = x + 1
           'I moved this up - otherwise I don't think you have a filename
           sFile = name & "_" & "SalesLog" & x & ".xlsx"
           xlWb.SaveAs FileName:=sPath & sFile, FileFormat:=xlOpenXMLWorkbook
           xlWb.Close SaveChanges:=True
        End If
        .MoveNext
     Loop
     .Close
  End With


问:
Sub Folder is affected by root web.config
It should be an easy question ,

I am building a site under IIS ,
For one part of it inside a subdirectory like \blog
I turned it to a vitual directory .

the root folder has its own web.config
and the blog sub Folder has its own .

in the root's web.config I used :

```<code><pages theme="DefaultTheme">
</code>```

and the sub folder seems to be affected by that ,
it causes an error telling I don't have this theme .

What is the solution ?

答: I have not been able to find a solution to this other than to move both applications into subfolders and ensure the parent folder has no Web.config.</p>

OwnerDisplayName: Sypress

Body:
It should be an easy question ,

I am building a site under IIS ,
For one part of it inside a subdirectory like \blog
I turned it to a vitual directory .

the root folder has its own web.config
and the blog sub Folder has its own .

in the root's web.config I used :

<pages theme="DefaultTheme">

and the sub folder seems to be affected by that ,
it causes an error telling I don't have this theme .

What is the solution ?

OwnerDisplayName: Jay S


问:
Store config settings for a .NET DLL (not EXE or Web)
I have a .NET 4 class library project, which is used by multiple web projects. In this class library I need to get a DB connection string and it needs to be the same for all the web projects. Currently I've got it as a setting in each web.config file, but this is not ideal. Is there any way I can have that configuration stored with the DLL, but still allow it to be modified at runtime (ie. hardcoding the connection string is out)?

App.config seems to be generally ignored for a DLL, even though it does get renamed to assemblyname.dll.config and copied to the bin directory for the web. I tried making it an "application setting" (ie. using the auto-generated class derived from System.Configuration.ApplicationSettingsBase) and this appeared to work, but changing the value in the DLL .config file at runtime had no effect, so I suspect it's really just using the hardcoded default value of the setting.

答: There is no way to change this. This is just how .NET works. You have to copy the settings from the DLL app.config to the web.config or programName.exe.config file.


问:
Changing session file names in Laravel 5.1
So Laravel saves it's own session files when someone accesses the website in the /storage/framework/sessions folder. Each of these session file's names are a randomly generated alpha numeric unique name. But, I'd like to somehow rename the files and give my own custom name for it. I've got two options for that.

Change the file name manually once the session file is created (by a create, copy, replace)

Find the function which randomly generates the alphanumeric name and change it with my own way of setting a unique name to each file (this method might come with less complications)

My main end goal is to rename each user's session file to their own userid that's stored in my db. So the names are still unique, the only difference is that I can search through the files easier than if they had random alphanumeric names.

So if anyone knows how I could do any of the above methods or if you can think of a better way to achieve the same, it'd be great. Any help is greatly appreciated!

EDIT: Decided to update here with what I had decided to do finally. I decided not to use the built in session files generated by Laravel and realized it's much easier to make my own file and just have each client access it instead. Thanks to all!

答:
use middleware for the request</p>

```<code>\Illuminate\Session\Middleware\StartSession::class

Route::group(['middleware' => [\Illuminate\Session\Middleware\StartSession::class]], function () {

});
</code>```

Body:
use middleware for the request

\Illuminate\Session\Middleware\StartSession::class

Route::group(['middleware' => [\Illuminate\Session\Middleware\StartSession::class]], function () {

});


问:
separate first word in a string in python re
I need to separate strings into two groups; the first word and the second word or group of words. The words are separated by an underscore and when I use my current code, if there are more than one underscores, it only separates off the last. Here is the code I currently have:

```<code>for record in reader:
s = record['trial']
patternsubgen = re.compile(r'(\w+)\(\w+\)\_(\w+)')
source = "Footit"
if patternsubgen.search(s):
    resultsubgen = patternsubgen.search(s)
    genussubgen = resultsubgen.group(1)
    speciessubgen = resultsubgen.group(2)
    subgen = '%s %s' % (genussubgen, speciessubgen)
    #print(subgen)
else:
    pattern = re.compile(r'(\w+)\_(\w+)')
    if pattern.search(s):
        result = pattern.search(s)
        genus = result.group(1)
        species = result.group(2)
        new = '%s %s' % (genus, species)
        print(new)
</code>```

Here are some examples of the strings:

```<code>Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,
</code>```

what I need is:

```<code>Aphis asclepiadis,
Cinara 011,
Clydesmithia canadensis_1a,
</code>```

what I am getting is:

```<code>Aphis asclepiadis,
Cinara 011,
Clydesmithia_canadensis 1a
</code>```

答:
For the given strings, you could use

```<code>\b([^_\W]+)(?:\([^()]+\))?_(\w+)\b
</code>```

See a demo on regex101.com.

In Python:

```<code>import re

strings = 'Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,'

rx = re.compile(r'\b([^_\W]+)(?:\([^()]+\))?_(\w+)\b')

strings = rx.sub("\g<1> \g<2>", strings)
print(strings)
# Aphis asclepiadis, Cinara 011, Clydesmithia canadensis_1a,
</code>```

Body:
I need to separate strings into two groups; the first word and the second word or group of words. The words are separated by an underscore and when I use my current code, if there are more than one underscores, it only separates off the last. Here is the code I currently have:

for record in reader:
s = record['trial']
patternsubgen = re.compile(r'(\w+)\(\w+\)\_(\w+)')
source = "Footit"
if patternsubgen.search(s):
    resultsubgen = patternsubgen.search(s)
    genussubgen = resultsubgen.group(1)
    speciessubgen = resultsubgen.group(2)
    subgen = '%s %s' % (genussubgen, speciessubgen)
    #print(subgen)
else:
    pattern = re.compile(r'(\w+)\_(\w+)')
    if pattern.search(s):
        result = pattern.search(s)
        genus = result.group(1)
        species = result.group(2)
        new = '%s %s' % (genus, species)
        print(new)

Here are some examples of the strings:

Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,

what I need is:

Aphis asclepiadis,
Cinara 011,
Clydesmithia canadensis_1a,

what I am getting is:

Aphis asclepiadis,
Cinara 011,
Clydesmithia_canadensis 1a

Body:
For the given strings, you could use

\b([^_\W]+)(?:\([^()]+\))?_(\w+)\b

See a demo on regex101.com.

In Python:

import re

strings = 'Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,'

rx = re.compile(r'\b([^_\W]+)(?:\([^()]+\))?_(\w+)\b')

strings = rx.sub("\g<1> \g<2>", strings)
print(strings)
# Aphis asclepiadis, Cinara 011, Clydesmithia canadensis_1a,


问:
Why does an Excel Table function with IF filter with AND condition not return results
I have an Excel book here where I have imported data from CSV, aggregated in a Pivot table. I need to calculate Percentiles on the aggregation, and the function

```<code>{=PERCENTILE.INC(IF(MyTable[label]=$A3,MyTable[elapsed]),$C$1)}
</code>```

did return a result.($A3 is the pivot table row label, $C$1` contains 0.9, = 90%)
I tried to extend the filtering IF statement with another condition using AND but suddenly the Percentile output dropped to 0.
For debug reasons I simplified my condition down to the following:

```<code>{=PERCENTILE.INC(IF(AND(MyTable[label]=$A3, TRUE()),MyTable[elapsed]),$C$1)}
</code>```

The expectation was that the formula result should be identical to the one above but with that AND statement it returns 0. Why?

答:
AND only returns a single value (TRUE if all conditions are fulfilled, FALSE otherwise), it can't return an array, which is what you need here - you can either multiply the conditions with * which mimics AND but does return an array, e.g.

=PERCENTILE.INC(IF((MyTable[label]=$A3)*(Another_condition=TRUE),MyTable[elapsed]),$C$1)

or use another IF like this:

=PERCENTILE.INC(IF(MyTable[label]=$A3,IF(Another_condition=TRUE,MyTable[elapsed])),$C$1)

Body:
I have an Excel book here where I have imported data from CSV, aggregated in a Pivot table. I need to calculate Percentiles on the aggregation, and the function

{=PERCENTILE.INC(IF(MyTable[label]=$A3,MyTable[elapsed]),$C$1)}

did return a result.($A3 is the pivot table row label, $C$1` contains 0.9, = 90%)
I tried to extend the filtering IF statement with another condition using AND but suddenly the Percentile output dropped to 0.
For debug reasons I simplified my condition down to the following:

{=PERCENTILE.INC(IF(AND(MyTable[label]=$A3, TRUE()),MyTable[elapsed]),$C$1)}

The expectation was that the formula result should be identical to the one above but with that AND statement it returns 0. Why?


问:
How to lower the search Icon in my actionBar?
For some reason my search icon is positioned a little bit higher than the settings icon. How do I lower the position of the search icon to match the settings icon in actionBar. Here's what I mean:

Here's my code for search icon, I got this icon from the Android Studio Image Asset Clip Art.

```<code><item

    android:id="@+id/menuSearch"
    android:title="@string/search"
    android:hint="@string/search"
    android:icon="@drawable/ic_search_black_24dp"
    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView"

     />
</code>```

How do I lower the search icon ?

答:
If the concern is only lowering it down, you can try:

Adding some top margin

Negative bottom margin

PS: we should do this only if the image has an included bottom
  padding, otherwise it may not appear correctly on other
  devices if the reason is unknown.  (Maybe include some more top-level hierarchy
  code as well)

Body:
For some reason my search icon is positioned a little bit higher than the settings icon. How do I lower the position of the search icon to match the settings icon in actionBar. Here's what I mean:

Here's my code for search icon, I got this icon from the Android Studio Image Asset Clip Art.

<item

    android:id="@+id/menuSearch"
    android:title="@string/search"
    android:hint="@string/search"
    android:icon="@drawable/ic_search_black_24dp"
    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView"

     />

How do I lower the search icon ?


问:
Unable to get the Query String value
Whenever I'm hitting this URL getting vToken is nothing. Please assist

```<code>Dim vHDR As String = Nothing
If Request.IsLocal Then
     Dim vToken = Request.QueryString("approvalToken")
     If Not vToken Is Nothing Then
         Dim vUser = Helper.ValidateToken(vToken)
         If Not vUser Is Nothing Then
              vHDR = vUser
          End If
      End If
 End If
</code>```

URL:

```<code>http://localhost:56979/#/modules/Review?ID=20582&approvalToken=SIsJ3swuGjpPidOvWPSzuqfcTJH8IywIlVVEnkmIQU6yE93PUQ
</code>```

答:
In a URL, everything beginning with the hash sign (#) is called the Fragment Identifier. The fragment identifier section is the last section of the URL and comes after the url arguments.

So for this url from the question:

```<code>http://localhost:56979/#/modules/Review?ID=20582&approvalToken=SIsJ3swuGjpPidOvWPSzuqfcTJH8IywIlVVEnkmIQU6yE93PUQ
</code>```

there is no query string. The section that looks like a query string was pre-empted to be part of a very long fragment identifier. Even the /modules/Review section that looks like part of the Path is actually part of the fragment.

I suspect somewhere in your base/index page you have a link with a blank href value, which is sometimes expressed with a single hash (#). You click that link, which puts the hash sign into the url:

```<code>http://localhost:56979/#
</code>```

After clicking this link, you then redirect, click a new link, or do some other action that appends the relative url /modules/Review (which may already include the query string) to your current location. But now you have the hash sign as part of that existing location, and so you end up with the url in your question, which doesn't mean what you want it to mean.

I'd have to see a lot more code to tell you exactly how to fix this, but in the context of vb.net (asp.net), if this code runs on the server you probably want to change /modules/Review to ~/modules/Review. If this is done in javascript, I'd need to know more about your page.

Title: Unable to get the Query String value

Body:
Whenever I'm hitting this URL getting vToken is nothing. Please assist

Dim vHDR As String = Nothing
If Request.IsLocal Then
     Dim vToken = Request.QueryString("approvalToken")
     If Not vToken Is Nothing Then
         Dim vUser = Helper.ValidateToken(vToken)
         If Not vUser Is Nothing Then
              vHDR = vUser
          End If
      End If
 End If

URL:

http://localhost:56979/#/modules/Review?ID=20582&approvalToken=SIsJ3swuGjpPidOvWPSzuqfcTJH8IywIlVVEnkmIQU6yE93PUQ

Body:
In a URL, everything beginning with the hash sign (#) is called the Fragment Identifier. The fragment identifier section is the last section of the URL and comes after the url arguments.

So for this url from the question:

http://localhost:56979/#/modules/Review?ID=20582&approvalToken=SIsJ3swuGjpPidOvWPSzuqfcTJH8IywIlVVEnkmIQU6yE93PUQ

there is no query string. The section that looks like a query string was pre-empted to be part of a very long fragment identifier. Even the /modules/Review section that looks like part of the Path is actually part of the fragment.

I suspect somewhere in your base/index page you have a link with a blank href value, which is sometimes expressed with a single hash (#). You click that link, which puts the hash sign into the url:

http://localhost:56979/#

After clicking this link, you then redirect, click a new link, or do some other action that appends the relative url /modules/Review (which may already include the query string) to your current location. But now you have the hash sign as part of that existing location, and so you end up with the url in your question, which doesn't mean what you want it to mean.

I'd have to see a lot more code to tell you exactly how to fix this, but in the context of vb.net (asp.net), if this code runs on the server you probably want to change /modules/Review to ~/modules/Review. If this is done in javascript, I'd need to know more about your page.


问:
python change global string in function
First off i am very new to coding and python. I am trying to call a global string inside of a function. Then I want to change it into an integer. Next, I want to apply some Math to the integer. Finally I want to convert that integer back to a string and send it back to the global to use in other functions.

I have accomplished most of what I needed to do, but I am having trouble sending the string back to the global. I have tried using return() but it just quits the program. Instead I want it to go to another function, while retaining the new value

Relevant code

```<code>current_gold = '10'

def town():
    global current_gold
    print(current_gold)

def pockets():
    global current_gold
    new_gold = int(current_gold) + 5
    new_gold = str(new_gold)
    print(new_gold.zfill(3))

    input("\tPress Enter to return to town")
    town()
</code>```

This is not the full code. I maybe doing stuff drastically wrong though.

答:
```<code>current_gold = '10'
def changeToInt():
    global current_gold
    current_gold = int(current_gold)

print(type(current_gold)) # It's a string right now
changeToInt() # Call our function
print(type(current_gold)) # It's an integer now
</code>```

Or you could do it by passing a parameter to your function like so:

```<code>current_gold = '10'
def changeToInt2(aVariable):
    return int(aVariable)

print(type(current_gold)) # It's a string right now
current_gold = changeToInt2(current_gold) # make current_gold the output of our function when called with current_gold as aVariable
print(type(current_gold)) # It's an int now
</code>```

Title: python change global string in function

Body:
First off i am very new to coding and python. I am trying to call a global string inside of a function. Then I want to change it into an integer. Next, I want to apply some Math to the integer. Finally I want to convert that integer back to a string and send it back to the global to use in other functions.

I have accomplished most of what I needed to do, but I am having trouble sending the string back to the global. I have tried using return() but it just quits the program. Instead I want it to go to another function, while retaining the new value

Relevant code

current_gold = '10'

def town():
    global current_gold
    print(current_gold)

def pockets():
    global current_gold
    new_gold = int(current_gold) + 5
    new_gold = str(new_gold)
    print(new_gold.zfill(3))

    input("\tPress Enter to return to town")
    town()

This is not the full code. I maybe doing stuff drastically wrong though.

Body:
current_gold = '10'
def changeToInt():
    global current_gold
    current_gold = int(current_gold)

print(type(current_gold)) # It's a string right now
changeToInt() # Call our function
print(type(current_gold)) # It's an integer now

Or you could do it by passing a parameter to your function like so:

current_gold = '10'
def changeToInt2(aVariable):
    return int(aVariable)

print(type(current_gold)) # It's a string right now
current_gold = changeToInt2(current_gold) # make current_gold the output of our function when called with current_gold as aVariable
print(type(current_gold)) # It's an int now