问:
Sys.Date() showing the wrong date
I do not know what happened but am getting irritated with this. I am currently in the GMT-8 Time Zone. When I type Sys.Date() it returns the tomorrow's date.

As of now the current date & time is 12/7/17 10:41 PM:
I type Sys.time() and this is what i get:

```<code>Sys.time()
[1] "2017-12-08 14:37:22 GMT"
</code>```

I then try to setup my time zone: Sys.setenv(TZ=Sys.timezone())

It clears without errors... and then I type Sys.Date() again and get

```<code>Sys.Date()
[1] "2017-12-08"
</code>```

It should be 12/7/17 !!

Any help is appreciated.

答:
On my mac system, I saw this with R 3.4.1 after updating to Mac OS 10.13.2:

```<code>Sys.time()
[1] "2017-12-08 20:52:01 GMT"
Warning:
In as.POSIXlt.POSIXct(x, tz) :
  unknown timezone 'zone/tz/2017c.1.0/zoneinfo/Europe/Berlin'
</code>```

I could fix that by setting Sys.setenv(TZ = "Europe/Berlin"). Valid timezone names for the US can be found using grep('^US/', OlsonNames(), value = TRUE).

After upgrading to R 3.4.3 I see this:

```<code>Sys.time()
[1] "2017-12-08 21:57:15 CET"

Sys.timezone()
#[1] "Europe/Berlin"
</code>```

So this looks like an issue due to an OS update. In fact, the release notes for R 3.4.3 say this:

A workaround has been added for the changes in location of time-zone
  files in macOS 10.13 ‘High Sierra’ and again in 10.13.1, so the
  default time zone is deduced correctly from the system setting when R
  is configured with --with-internal-tzcode (the default on macOS).

Title: Sys.Date() showing the wrong date

Body:
I do not know what happened but am getting irritated with this. I am currently in the GMT-8 Time Zone. When I type Sys.Date() it returns the tomorrow's date.

As of now the current date & time is 12/7/17 10:41 PM:
I type Sys.time() and this is what i get:

Sys.time()
[1] "2017-12-08 14:37:22 GMT"

I then try to setup my time zone: Sys.setenv(TZ=Sys.timezone())

It clears without errors... and then I type Sys.Date() again and get

Sys.Date()
[1] "2017-12-08"

It should be 12/7/17 !!

Any help is appreciated.

Body:
On my mac system, I saw this with R 3.4.1 after updating to Mac OS 10.13.2:

Sys.time()
[1] "2017-12-08 20:52:01 GMT"
Warning:
In as.POSIXlt.POSIXct(x, tz) :
  unknown timezone 'zone/tz/2017c.1.0/zoneinfo/Europe/Berlin'

I could fix that by setting Sys.setenv(TZ = "Europe/Berlin"). Valid timezone names for the US can be found using grep('^US/', OlsonNames(), value = TRUE).

After upgrading to R 3.4.3 I see this:

Sys.time()
[1] "2017-12-08 21:57:15 CET"

Sys.timezone()
#[1] "Europe/Berlin"

So this looks like an issue due to an OS update. In fact, the release notes for R 3.4.3 say this:

A workaround has been added for the changes in location of time-zone
  files in macOS 10.13 ‘High Sierra’ and again in 10.13.1, so the
  default time zone is deduced correctly from the system setting when R
  is configured with --with-internal-tzcode (the default on macOS).

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Vertical align card-content in Materialize card
I'm just trying to vertical align the text in the card and not impact anything else. You can see what I'm doing here: Working example

My very simple code is here:

```<code><body>
  <div class="container">
    <div class="row top-pad">
      <div class="col s4">
        <%= image_tag "logo.png", class:"responsive-img" %>
      </div>
  </div>
    <img class="responsive-img" src="cool_pic.jpg">

  <div class="container vert-align">
      <div class="row">
        <div class="col s4 offset-s4">
          <div class="card medium">
            <div class="card-image">
              <%= image_tag "hi2.png" %>
              <!--<span class="card-title">Card Title</span>-->
            </div>
            <div class="card-content">
              <p>Welcome to FBA Shipping by ByteStand.
                A super simple way to automate fulfilling FBA items
                in the US and abroad.</p>
            </div>
            <div class="card-action">
              <button class="waves-effect btn stroke-btn">Let's Get Started!</button>
            </div>
          </div>
        </div>
      </div>
  </div>
</body>
</code>```

I've tried valign-wrapper everywhere as well as vert-align all to no avail.

Here is my entire CSS as well:

```<code>.vert-align {
  margin: 0px;
    padding: 0px;
    float: left;
    width: 100%;
    position: absolute;
    top: 50%;
    transform: translateY(-50%) translateX(-50%);
    left: 50%;
}

.stroke-btn {
  background-color: white !important;
  border-style: solid;
  border-width: 1px;
  border-color: #311b92;
  color: #311b92 !important;
}

.top-pad {
  padding-top: 20px;
}

.card {
    max-width: 400px;
    overflow: hidden;
}

.custom-align .card {
  display: flex;
  flex-direction: column;
}

.custom-align .card-content {
  flex: 1;
  max-height: 100% !important;
  align-items: center;
  display: flex;
  margin-bottom: 50px;
}
</code>```

答:
You can add a custom class to the container (for example replace vert-align with custom-align) and then try flex by adding this CSS code :

.custom-align .card {
  display: flex;
  flex-direction: column;
}

.custom-align .card-content {
  flex: 1;
  max-height: 100%;
  align-items: center;
  display: flex;
  margin-bottom: 50px;
}```

Am not sure about the remaining CSS of the page, so if it's not working you may add more specifity or use important

ContentLicense: CC BY-SA 3.0

Body:
I'm just trying to vertical align the text in the card and not impact anything else. You can see what I'm doing here: Working example

My very simple code is here:

        <%= image_tag "logo.png", class:"responsive-img" %>

              <%= image_tag "hi2.png" %>

Welcome to FBA Shipping by ByteStand.
                A super simple way to automate fulfilling FBA items
                in the US and abroad.

              <button class="waves-effect btn stroke-btn">Let's Get Started!</button>

I've tried valign-wrapper everywhere as well as vert-align all to no avail.

Here is my entire CSS as well:

.vert-align {
  margin: 0px;
    padding: 0px;
    float: left;
    width: 100%;
    position: absolute;
    top: 50%;
    transform: translateY(-50%) translateX(-50%);
    left: 50%;
}

.stroke-btn {
  background-color: white !important;
  border-style: solid;
  border-width: 1px;
  border-color: #311b92;
  color: #311b92 !important;
}

.top-pad {
  padding-top: 20px;
}

.card {
    max-width: 400px;
    overflow: hidden;
}

.custom-align .card {
  display: flex;
  flex-direction: column;
}

.custom-align .card-content {
  flex: 1;
  max-height: 100% !important;
  align-items: center;
  display: flex;
  margin-bottom: 50px;
}

Body:
You can add a custom class to the container (for example replace vert-align with custom-align) and then try flex by adding this CSS code :

.custom-align .card {
  display: flex;
  flex-direction: column;
}

.custom-align .card-content {
  flex: 1;
  max-height: 100%;
  align-items: center;
  display: flex;
  margin-bottom: 50px;
}

Am not sure about the remaining CSS of the page, so if it's not working you may add more specifity or use important


问:
Apache Spark JDBC SQL Injection (pyspark)
I am trying to submit a sql query to jdbc while being protected from sql injection attacks. I have some code such as

```<code>from pyspark import SparkContext
from pyspark.sql import DataFrameReader, SQLContext
from pyspark.sql.functions import col
url = 'jdbc:mysql://.../....'
properties = {'user': '', 'driver': 'com.mysql.jdbc.Driver', 'password': ''}
sc = SparkContext("local[*]", "name")
sqlContext = SQLContext(sc)
from pyspark.sql.functions import desc
pushdown_query = """(
    select * from my_table
    where timestamp > {}
) AS tmp""".format(my_date)
df = sqlContext.read.jdbc(url=url, properties=properties, table=pushdown_query)
</code>```

Can I use bind params somehow?

Any solution that prevents SQL injection here would work.

I also use SQLAlchemy if that helps.

答:
If you use SQLAlchemy, you can try:

```<code>from sqlalchemy.dialects import mysql
from sqlalchemy import text

pushdown_query = str(
  text("""(select * from my_table  where timestamp > :my_date ) AS tmp""")
      .bindparams(my_date=my_date)
      .compile(dialect=mysql.dialect(), compile_kwargs={"literal_binds": True}))

df = sqlContext.read.jdbc(url=url, properties=properties, table=pushdown_query)
</code>```

but in a simple case, like this one,  there is no need for subqueries. You can:

```<code>df = (sqlContext.read
    .jdbc(url=url, properties=properties, table=my_table)
    .where(col("timestamp") > my_date)))
</code>```

and if you worry about SQL injections, it is possible you have a bigger problem. If alone has (almost) no security mechanisms built-in and probably shouldn't be exposed in untrusted environment.

Body:
I am trying to submit a sql query to jdbc while being protected from sql injection attacks. I have some code such as

from pyspark import SparkContext
from pyspark.sql import DataFrameReader, SQLContext
from pyspark.sql.functions import col
url = 'jdbc:mysql://.../....'
properties = {'user': '', 'driver': 'com.mysql.jdbc.Driver', 'password': ''}
sc = SparkContext("local[*]", "name")
sqlContext = SQLContext(sc)
from pyspark.sql.functions import desc
pushdown_query = """(
    select * from my_table
    where timestamp > {}
) AS tmp""".format(my_date)
df = sqlContext.read.jdbc(url=url, properties=properties, table=pushdown_query)

Can I use bind params somehow?

Any solution that prevents SQL injection here would work.

I also use SQLAlchemy if that helps.

Body:
If you use SQLAlchemy, you can try:

from sqlalchemy.dialects import mysql
from sqlalchemy import text

pushdown_query = str(
  text("""(select * from my_table  where timestamp > :my_date ) AS tmp""")
      .bindparams(my_date=my_date)
      .compile(dialect=mysql.dialect(), compile_kwargs={"literal_binds": True}))

df = sqlContext.read.jdbc(url=url, properties=properties, table=pushdown_query)

but in a simple case, like this one,  there is no need for subqueries. You can:

df = (sqlContext.read
    .jdbc(url=url, properties=properties, table=my_table)
    .where(col("timestamp") > my_date)))

and if you worry about SQL injections, it is possible you have a bigger problem. If alone has (almost) no security mechanisms built-in and probably shouldn't be exposed in untrusted environment.


问:
Action mode is not applied to toolbar (being used as action bar), when using with ListView CHOICE_MODE_MULTIPLE_MODAL
In my project I'm replacing the Action Bar with a Tool Bar. I inherited my theme from Theme.Material.Light.NoActionBar and called setActionBar from my Activity's onCreate to pass the toolbar. So far so good. The problem is when I use a ListView with CHOICE_MODE_MULTIPLE_MODAL. The action mode appears on top of the Too Bar, where the actual Action Bar would've reside, had I not removed it with NoActionBar theme.

Is there something I need to configure in the ListView? Or the MultiChoiceModeListener?

Here is my super trivial code for activity

```<code>public class MainActivity extends Activity implements ActionMode.Callback, AbsListView.MultiChoiceModeListener {

static final ArrayList<String> values = new ArrayList<>(Arrays.asList("Apple", "Ball", "Cat", "Dog", "Elephant", "Flower"));
ArrayAdapter<String> adapter;
ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setActionBar(findViewById(R.id.toolbar));

    lv = findViewById(R.id.wordList);
    adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_activated_1, values);
    lv.setAdapter(adapter);
    lv.setMultiChoiceModeListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_normal, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Toast.makeText(this, "This is a test", Toast.LENGTH_SHORT).show();
    return true;
}

@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
    getMenuInflater().inflate(R.menu.menu_active, menu);
    mode.setTitle("Go CAPS!");
    return true;
}

@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
    return false;
}

@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
    turnWordsToUppercase();
    mode.finish();

    return true;
}

@Override
public void onDestroyActionMode(ActionMode mode) {
    lv.clearChoices();
    lv.requestLayout();
}

@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}

void turnWordsToUppercase() {
    //Logic for turning words to uppercase
}
</code>```

}

Here is my theme

```<code><style name="AppTheme" parent="android:Theme.Material.Light.NoActionBar">
    <item name="android:colorPrimary">@color/colorPrimary</item>
    <item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="android:colorAccent">@color/colorAccent</item>
    <item name="windowActionModeOverlay">true</item>
</style>
</code>```

答: you need to add <item name="windowActionModeOverlay">true</item> to your app theme

Body:
In my project I'm replacing the Action Bar with a Tool Bar. I inherited my theme from Theme.Material.Light.NoActionBar and called setActionBar from my Activity's onCreate to pass the toolbar. So far so good. The problem is when I use a ListView with CHOICE_MODE_MULTIPLE_MODAL. The action mode appears on top of the Too Bar, where the actual Action Bar would've reside, had I not removed it with NoActionBar theme.

Is there something I need to configure in the ListView? Or the MultiChoiceModeListener?

Here is my super trivial code for activity

public class MainActivity extends Activity implements ActionMode.Callback, AbsListView.MultiChoiceModeListener {

static final ArrayList<String> values = new ArrayList<>(Arrays.asList("Apple", "Ball", "Cat", "Dog", "Elephant", "Flower"));
ArrayAdapter<String> adapter;
ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setActionBar(findViewById(R.id.toolbar));

    lv = findViewById(R.id.wordList);
    adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_activated_1, values);
    lv.setAdapter(adapter);
    lv.setMultiChoiceModeListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_normal, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Toast.makeText(this, "This is a test", Toast.LENGTH_SHORT).show();
    return true;
}

@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
    getMenuInflater().inflate(R.menu.menu_active, menu);
    mode.setTitle("Go CAPS!");
    return true;
}

@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
    return false;
}

@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
    turnWordsToUppercase();
    mode.finish();

    return true;
}

@Override
public void onDestroyActionMode(ActionMode mode) {
    lv.clearChoices();
    lv.requestLayout();
}

@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}

void turnWordsToUppercase() {
    //Logic for turning words to uppercase
}

}

Here is my theme


问:
What is the Visual Studio 08 C# Assembly Information GUID setting for?
I am developing a C# Application and I was verifying the setting for publishing the application.  What is the GUID setting under the Assembly Information section?</p>

答:
It's used if you intend calling your .NET assembly from COM.

This article describes the steps.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Mitch Wheat

LastEditorDisplayName: Mitch Wheat


问:
My batch script doesn't work. Can anyone tell me why?
I need help with my script. All of the stuff keeps falling through and not doing the goto. Can you help?</p>

```<code>@ECHO OFF
goto joshua
:joshua
Echo Hello my name is Joshua.
echo What is yours?
set /p name=
cls
Echo Hello %name%.
cls
Echo How are you?
set /p feeling=
cls
echo Is this good?
echo Im sorry I am still learning human feelings.
set /p humanfeelings=Yes/No
if %humanfeelings%==Yes goto Good
if %humanfeelings%==No goto Bad
cls
:Good
Echo Well that is pleasent.
Echo Would you like to play a game %name%?
set /p answer=Yes/No
if %answer%==Yes goto startmenu
if %answer%== No goto quit
cls
:Bad
echo That is not good.
echo Would you like to play a game %name%?
set /p answera=Yes/No
if %answera%==Yes goto startmenu
if %answera%== No goto later
cls
:startmenu
start menu.bat
cls
:later
Echo That is fine %name%, maybe later
pause
exit
</code>```

答:
Try removing the space before the word No in these lines:

```<code>if %answer%== No goto quit
</code>```

and

```<code>if %answera%== No goto later
</code>```

Like many of us who have outlived our usefulness, the batch interpreter is old and fussy. :-)

Body:
I need help with my script. All of the stuff keeps falling through and not doing the goto. Can you help?

@ECHO OFF
goto joshua
:joshua
Echo Hello my name is Joshua.
echo What is yours?
set /p name=
cls
Echo Hello %name%.
cls
Echo How are you?
set /p feeling=
cls
echo Is this good?
echo Im sorry I am still learning human feelings.
set /p humanfeelings=Yes/No
if %humanfeelings%==Yes goto Good
if %humanfeelings%==No goto Bad
cls
:Good
Echo Well that is pleasent.
Echo Would you like to play a game %name%?
set /p answer=Yes/No
if %answer%==Yes goto startmenu
if %answer%== No goto quit
cls
:Bad
echo That is not good.
echo Would you like to play a game %name%?
set /p answera=Yes/No
if %answera%==Yes goto startmenu
if %answera%== No goto later
cls
:startmenu
start menu.bat
cls
:later
Echo That is fine %name%, maybe later
pause
exit

Body:
Try removing the space before the word No in these lines:

if %answer%== No goto quit

and

if %answera%== No goto later

Like many of us who have outlived our usefulness, the batch interpreter is old and fussy. :-)


问:
How to define invariant of python binsearch algorithm from lib?
I found the following code in python lib:

```<code>def bisect_left(a, x, lo=0, hi=None):
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if a[mid] < x: lo = mid+1
        else: hi = mid
    return lo
</code>```

Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e < x, and all e in
a[i:] have e >= x.

What is an invariant of this algorithm? I wanna to understand that it is correct.

答: The algorithm is known as Binary Search Alorithm. It works on sorted list to find an element in O(logn) (normally finding an element in a list requires O(n) to iterate over all elements). The magic behind it is as follows: Suppose you have a sorted array from 1 to 1000. you want to check whether 247 is exist or not, one way is iterate over all elements but the the other is using BST i.e. check the median value, if it is greater than 247, It means that if 247 exist on this array it should be placed somewhere in the first have of the array and in this way you simply ignore the second half and so on. </p>

Body:
I found the following code in python lib:

def bisect_left(a, x, lo=0, hi=None):
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if a[mid] < x: lo = mid+1
        else: hi = mid
    return lo

Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e < x, and all e in
a[i:] have e >= x.

What is an invariant of this algorithm? I wanna to understand that it is correct.


问:
Export/Import Task Group
We are using TFS 2017 update 2 on-premises.
We want to update our test environment with the build definitions from production. With an extension we could copy the build definitions https://marketplace.visualstudio.com/items?itemName=onlyutkarsh.ExportImportBuildDefinition , but this does not export the task-group of the build definition.

Are there ways to export the task group and import it in another project or in my case in a different TFS server?

答:
The functionality to export Task Groups is certainly present in VSTS. Although the documentation says that is is available in TFS 2017,

https://learn.microsoft.com/en-us/vsts/build-release/concepts/library/task-groups

We haven't seen the References tab being added as of writing this answer. We are using TFS 2017 Update 2. I haven't seen it being added for TFS Update 3 either

Title: Export/Import Task Group


问:
C++: More precise timing intervals
I need to periodically do a particular task and am currently using nanosleep.

The task needs to be run every second or every 10 seconds.

Is there a better way to do this than:

```<code>while(true)
{
 doTask();
 sleep();
}
</code>```

Walter

答:
You can use a thread library to create a thread which handle run the doTask(). Your main thread just keeps sleeping and runs every 1 second or 10 seconds.

This can be done with a QTimer and a QRunnable.

http://doc.qt.nokia.com/latest/qtimer.html

According to the dock, the resolution is around 1 ms in most cases. For your need, this should be sufficient.

Title: C++: More precise timing intervals

Body:
I need to periodically do a particular task and am currently using nanosleep.

The task needs to be run every second or every 10 seconds.

Is there a better way to do this than:

while(true)
{
 doTask();
 sleep();
}

Walter


问:
How can a private class method be tested in Scala?
I have a companion object with a private method, like so:

```<code>package com.example.people

class Person(val age: Int)

object Person {
  private def transform(p: Person): Person = new Person(p.age + 1)
}
</code>```

I would like to test this method, with something like:

```<code>class PersonSpec extends FlatSpec {

  "A Person" should "transform correctly" in {
    val p1 = new Person(1)
    val p2 = Person.transform(p1) // doesn't compile, because transform is private!
    assert( p2 === new Person(2) )
  }

}
</code>```

Any help on having test code access private methods?

Actually, as it is written, I might be able to create a subclass of Person, but what if Person is declared as final or sealed?

Thanks!

答:
Personally, I say make everything public and just prepend with _ or __ to indicate that other devs shouldn't use it.

I realize this is Scala and not Python, but regardless, "We're all consenting adults here."

"Private" methods aren't actually private (for example) and certainly aren't secure, so why make life harder for what is essentially a social contract? Prepend and be done -- if another dev wants to go poking around in dark places, they either have a good reason or deserve what they get.

Body:
I have a companion object with a private method, like so:

package com.example.people

class Person(val age: Int)

object Person {
  private def transform(p: Person): Person = new Person(p.age + 1)
}

I would like to test this method, with something like:

class PersonSpec extends FlatSpec {

  "A Person" should "transform correctly" in {
    val p1 = new Person(1)
    val p2 = Person.transform(p1) // doesn't compile, because transform is private!
    assert( p2 === new Person(2) )
  }

}

Any help on having test code access private methods?

Actually, as it is written, I might be able to create a subclass of Person, but what if Person is declared as final or sealed?

Thanks!


问:
Border around progress bar
I am trying to get border around a progress bar, but not able to get

What I am getting:

I don't want to fill the background with blue colour.

This is what I want:

This is the XML file

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
    <shape>
        <solid android:color="#1669A0" />
        <corners android:radius="10dp" />
    </shape>
</item>
<item android:id="@android:id/progress">
    <clip>
        <layer-list>
            <item>
                <color android:color="#00000000" />
            </item>
            <item
                android:left="5dp"
                android:top="5dp"
                android:right="5dp"
                android:bottom="5dp">
                <shape>
                    <solid android:color="#00FF00" />
                    <corners android:radius="10dp" />
                </shape>
            </item>
        </layer-list>
    </clip>
</item>
</layer-list>
</code>```

答:
Maybe it will be helpful for other people who have the same problem:
You can just add line in shape section to add stroke (as a border) to it and then add proper padding in progress section (usually equal or bigger than stroke width).

Example:

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="10dp"/>
            <solid android:color="YOUR BACKGROUND COLOR HERE"/>
            <stroke android:color="YOUR BORDER COLOR HERE" android:width="5dp" />
        </shape>
    </item>

    <item android:id="@android:id/progress"
        android:top="5dp"
        android:bottom="5dp"
        android:right="5dp"
        android:left="5dp">
        <clip>
            <scale android:scaleWidth="100%" >
                <shape>
                    <corners android:radius="10dp"/>
                    <solid android:color="YOUR PROGRESS COLOR HERE"/>
                </shape>
            </scale>
        </clip>
    </item>
</layer-list>
</code>```

You will get something like that:

Title: Border around progress bar

Body:
I am trying to get border around a progress bar, but not able to get

What I am getting:

I don't want to fill the background with blue colour.

This is what I want:

This is the XML file

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
    <shape>
        <solid android:color="#1669A0" />
        <corners android:radius="10dp" />
    </shape>
</item>
<item android:id="@android:id/progress">
    <clip>
        <layer-list>
            <item>
                <color android:color="#00000000" />
            </item>
            <item
                android:left="5dp"
                android:top="5dp"
                android:right="5dp"
                android:bottom="5dp">
                <shape>
                    <solid android:color="#00FF00" />
                    <corners android:radius="10dp" />
                </shape>
            </item>
        </layer-list>
    </clip>
</item>
</layer-list>

Body:
Maybe it will be helpful for other people who have the same problem:
You can just add line in shape section to add stroke (as a border) to it and then add proper padding in progress section (usually equal or bigger than stroke width).

Example:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="10dp"/>
            <solid android:color="YOUR BACKGROUND COLOR HERE"/>
            <stroke android:color="YOUR BORDER COLOR HERE" android:width="5dp" />
        </shape>
    </item>

    <item android:id="@android:id/progress"
        android:top="5dp"
        android:bottom="5dp"
        android:right="5dp"
        android:left="5dp">
        <clip>
            <scale android:scaleWidth="100%" >
                <shape>
                    <corners android:radius="10dp"/>
                    <solid android:color="YOUR PROGRESS COLOR HERE"/>
                </shape>
            </scale>
        </clip>
    </item>
</layer-list>

You will get something like that:


问:
How to send from JAVA String(path of file) to C?
i want to send from java some paths to C.

For example i have a folder that have 4 subfoldes... From java i read the length of them from the code below and it returns me 4.

```<code>     public static int GetLength(){File file = new File("C:\\Registrations");
           File[] files = file.listFiles(new FileFilter(){
             public boolean accept(File f) {
                 return f.isDirectory();   }});
                  return files.length;}     }
</code>```

Now with a thread i start to call the function that connect with C

```<code>      public Start(){ Thread listeningThread = new Thread(new Runnable(){
        public void run(){
        new Match(GetDBNumber());  }  });
        listeningThread.start();}
</code>```

So far all good. Now from MATCH(int x) class i want to call a C code and every time give the path of the Main folder each time

```<code>    *PSEUDOCODE*      public class Match {
                       public Match( int len){
                      System.out.println("subfolders  : "+len);
                      for (i=0; i<len; i++)
                      {     //Some way call C programm (like an exe)
                            //with the first,second,third,fourth path
                      }
                        ....      }
</code>```

The C code that will recieve the path will be look like that...

```<code>            int main()     {
            FILE *fp = fopen(FilePATH, "r");
            ......
            ......
            return 0;                                 }
</code>```

I try with ProcessBuilder but i cant send the path every time with this way...

```<code>          ProcessBuilder p = new ProcessBuilder();
           //receive.exe is the exe that Codeblocks create after built the C code
          p.command("C:\\Users\\PC\\Documents\\NetBeansProjects\\TEST\\C\\recieve.exe");
         try {
             p.start();
             } catch (Exception e) {System.out.println("Error");

            }
</code>```

答:
Depends on a lot of variables.  I'll assume that you are building the C code and can change how things are passed, so...

Easiest to hardest:

Pass it in as a command line parameter (only works once per C file execution)

Write/update a text file on your hard drive that the C program can watch

Use TCP/IP and send messages over a pre-designated socket

Build as a shared library or DLL and Use JNI to call the C functions

If you were doing this professionally and this was just the beginning of a larger development effort you'd be wise to look into more professional tooling:

a message bus (Apache has one called ActiveMQ) is designed to do exactly what you are trying to do (and so much more)

a shared cache (Hazlecast can connect Java to C++ and nearly everything else and share data freely)

A shared table in a database that both languages can access.

These are much higher initial investment in time (otherwise free) but they have innumerable features that you could continue to take advantage of as your system grows.

Body:
i want to send from java some paths to C.

For example i have a folder that have 4 subfoldes... From java i read the length of them from the code below and it returns me 4.

     public static int GetLength(){File file = new File("C:\\Registrations");
           File[] files = file.listFiles(new FileFilter(){
             public boolean accept(File f) {
                 return f.isDirectory();   }});
                  return files.length;}     }

Now with a thread i start to call the function that connect with C

      public Start(){ Thread listeningThread = new Thread(new Runnable(){
        public void run(){
        new Match(GetDBNumber());  }  });
        listeningThread.start();}

So far all good. Now from MATCH(int x) class i want to call a C code and every time give the path of the Main folder each time

    *PSEUDOCODE*      public class Match {
                       public Match( int len){
                      System.out.println("subfolders  : "+len);
                      for (i=0; i<len; i++)
                      {     //Some way call C programm (like an exe)
                            //with the first,second,third,fourth path
                      }
                        ....      }

The C code that will recieve the path will be look like that...

            int main()     {
            FILE *fp = fopen(FilePATH, "r");
            ......
            ......
            return 0;                                 }

I try with ProcessBuilder but i cant send the path every time with this way...

          ProcessBuilder p = new ProcessBuilder();
           //receive.exe is the exe that Codeblocks create after built the C code
          p.command("C:\\Users\\PC\\Documents\\NetBeansProjects\\TEST\\C\\recieve.exe");
         try {
             p.start();
             } catch (Exception e) {System.out.println("Error");

            }


问:
How to check if a riot tag exists?
How can I check if a riot tag has already been loaded and compiled (in-browser with script tag), in order to avoid doing it again, programmatically.

In other words, what should I use instead of doesTagExist function in my simplified code, below?

```<code>if (!doesTagExist('my-tag')) {
    riot.compile('/path/to/my-tag', function() {
        riot.mount('dom-node', 'my-tag');
    });
} else {
    riot.mount('dom-node', 'my-tag');
}
</code>```

答:
had same problem. After bit of research I think you can't get it directly. Implementation is stored inside __TAG_IMPL which is not accessible from outside. You can however access selector for all implemented tags via riot.util.tags.selectTags(), which returns comma separated list of selectors i.e. datepicker,[data-is="datepicker"].

Oneliner for convenience

```<code>riot.util.tags.selectTags().search(/(^|,)my-tag($|,)/g) >= 0
</code>```

or depending on your purity inclination

```<code>riot.util.tags.selectTags().search('"my-tag"')
</code>```

Note, that first version is future-proof, if riot decides to start using single commas in selector.

Title: How to check if a riot tag exists?

Body:
How can I check if a riot tag has already been loaded and compiled (in-browser with script tag), in order to avoid doing it again, programmatically.

In other words, what should I use instead of doesTagExist function in my simplified code, below?

if (!doesTagExist('my-tag')) {
    riot.compile('/path/to/my-tag', function() {
        riot.mount('dom-node', 'my-tag');
    });
} else {
    riot.mount('dom-node', 'my-tag');
}

Body:
had same problem. After bit of research I think you can't get it directly. Implementation is stored inside __TAG_IMPL which is not accessible from outside. You can however access selector for all implemented tags via riot.util.tags.selectTags(), which returns comma separated list of selectors i.e. datepicker,[data-is="datepicker"].

Oneliner for convenience

riot.util.tags.selectTags().search(/(^|,)my-tag($|,)/g) >= 0

or depending on your purity inclination

riot.util.tags.selectTags().search('"my-tag"')

Note, that first version is future-proof, if riot decides to start using single commas in selector.


问:
Pass argument to void function
How to pass argument line to void? it keep show error the data type should be

line [100][260]

I try other ways like

wchar_t * line[][]

still can't

```<code>#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <windows.h>

using namespace std;

  void test(DWORD a, wchar_t * line[])
    {

        unsigned int i;

        for (i = 0; i < a; i++)
        {
            wcout << line[i];
        }

    }

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

        test(a, line);

        return 0;
    }
</code>```

Thank you

答:
Your function wants a 1-dimensional array of pointers to null-terminated strings. But you are trying to pass it a 2-dimensional array of chars instead.  They are NOT the same thing!

At the very least, you can create a second array that contains pointers to the elements of the first array, eg:

```<code>#include "stdafx.h"

#include <iostream>
#include <fstream>

#include <windows.h>

void test(DWORD a, wchar_t * lines[])
{
    for (unsigned int i = 0; i < a; ++i) {
        std::wcout << lines[i] << std::endl;
    }
}

int main()
{
    FILE *pFile;
    wchar_t *file = L"d:\\a.txt";
    wchar_t lineData[100][MAX_PATH];
    wchar_t* lines[100];
    wchar_t *line;

    unsigned int a = 0;
    if (_wfopen_s(&pFile, file, L"r, ccs = UNICODE") == 0)
    {
        do
        {
            line = lineData[a];

            if (!fgetws(line, MAX_PATH, pFile))
                break;

            size_t len = wcslen(line);
            if ((len > 0) && (line[len-1] == L'\n'))
                line[--len] = 0;

            lines[a] = line;
        }
        while (++a < 100);

        fclose(pFile);
    }

    test(a, lines);

    return 0;
}
</code>```

That being said, since you are using C++ anyway, you should be using C++ functionality instead of C functionality to read the file, eg:

```<code>#include "stdafx.h"
#include <windows.h>

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

void test(const std::vector<std::wstring> &lines)
{
    for (std::wstring &line : lines) {
        std::wcout << line << std::endl;
    }

    /* or: prior to C++11:

    for (std::size_t i = 0; i < lines.size(); ++i) {
        std::wcout << lines[i] << std::endl;
    }

    or:

    for (std::vector<std::wstring>::iterator iter = lines.begin(); iter != lines.end(); ++iter) {
        std::wcout << *iter << std::endl;
    }
    */
}

int main()
{
    std::vector<std::wstring> lines;
    std::wstring line;

    std::wifstream file(L"d:\\a.txt");
    if (file.is_open())
    {
        while (std::getline(file, line)) {
            lines.push_back(line);
        }
        file.close();
    }

    test(lines);

    return 0;
}
</code>```

Title: Pass argument to void function

Body:
How to pass argument line to void? it keep show error the data type should be

line [100][260]

I try other ways like

wchar_t * line[][]

still can't

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <windows.h>

using namespace std;

  void test(DWORD a, wchar_t * line[])
    {

        unsigned int i;

        for (i = 0; i < a; i++)
        {
            wcout << line[i];
        }

    }

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

        test(a, line);

        return 0;
    }

Thank you

Body:
Your function wants a 1-dimensional array of pointers to null-terminated strings. But you are trying to pass it a 2-dimensional array of chars instead.  They are NOT the same thing!

At the very least, you can create a second array that contains pointers to the elements of the first array, eg:

#include "stdafx.h"

#include <iostream>
#include <fstream>

#include <windows.h>

void test(DWORD a, wchar_t * lines[])
{
    for (unsigned int i = 0; i < a; ++i) {
        std::wcout << lines[i] << std::endl;
    }
}

int main()
{
    FILE *pFile;
    wchar_t *file = L"d:\\a.txt";
    wchar_t lineData[100][MAX_PATH];
    wchar_t* lines[100];
    wchar_t *line;

    unsigned int a = 0;
    if (_wfopen_s(&pFile, file, L"r, ccs = UNICODE") == 0)
    {
        do
        {
            line = lineData[a];

            if (!fgetws(line, MAX_PATH, pFile))
                break;

            size_t len = wcslen(line);
            if ((len > 0) && (line[len-1] == L'\n'))
                line[--len] = 0;

            lines[a] = line;
        }
        while (++a < 100);

        fclose(pFile);
    }

    test(a, lines);

    return 0;
}

That being said, since you are using C++ anyway, you should be using C++ functionality instead of C functionality to read the file, eg:

#include "stdafx.h"
#include <windows.h>

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

void test(const std::vector<std::wstring> &lines)
{
    for (std::wstring &line : lines) {
        std::wcout << line << std::endl;
    }

    /* or: prior to C++11:

    for (std::size_t i = 0; i < lines.size(); ++i) {
        std::wcout << lines[i] << std::endl;
    }

    or:

    for (std::vector<std::wstring>::iterator iter = lines.begin(); iter != lines.end(); ++iter) {
        std::wcout << *iter << std::endl;
    }
    */
}

int main()
{
    std::vector<std::wstring> lines;
    std::wstring line;

    std::wifstream file(L"d:\\a.txt");
    if (file.is_open())
    {
        while (std::getline(file, line)) {
            lines.push_back(line);
        }
        file.close();
    }

    test(lines);

    return 0;
}


问:
Custom UICollection view layout
I'm trying to configure a collection view to have the following custom layout shown in the attached image:
. Essentially, I want to be able to configure my collection view so it appears to be based off rows instead of columns. For example:

Row 1: 3 equally sized squares, each 1/3 the width of the screen

Row 2: 1 square that's 2/3 the width of the screen, and then 2 squares stacked on
       top of each other that are each 1/3 the width of the screen.

Row 3: 1 rectangle that fills the width of the screen

Row 4: 2 equally sized squares, each 1/2 the width of the screen

I've gone through multiple UICollectionViewLayout and UICollectionViewDelegateFlowLayout tutorials, but have been unable to find the information I need.

答:
You need to implement a custom UICollectionViewLayout.

Precompute the location of all of the squares in your repeat in prepareLayout

Return the height of your content by using the (repeat height) * (number of items in collection) / (number of items in repeat) + the height at the remainder in collectionViewContentSize (this means you should cache the content height for each item in step 1, but the height is not the height of that square (its the height of the tallest element in that row)

In layoutAttributesForElementsInRect you need to figure out what repeat row your rect starts in and what row of the repeat it ends in.  You then return all of the cached layout attributes for those rows from step 1, but you have to add back a y value equal to (repeat count) / (first item index) * (repeat height).

basically its a bunch of math but when you divide it into repeating sections, the problem becomes which repeat am I in (divide) and what element within that repeat do I need (modulus), and it's much easier to solve.

I did something similar to this but with multiple repeats that could be arranged in different orders and it took a few hours to get it working without any bugs.  Its a lot of math and very tedious.

Title: Custom UICollection view layout


问:
How does this thing work this way,just explain
```<code>import pygame

pygame.init()
Display = pygame.display.set_mode((800,600))
pygame.display.set_caption("Blocky")

red = (157, 139, 215)
black = (0,0,0)

Display.fill(red)
pygame.draw.rect(Display,black,(400,300,200,80))

pygame.display.update()

excape = False

while not excape:
    for dork in pygame.event.get():
        print (dork)
</code>```

[

Works correctly But When I copy and paste red to pygame.draw under the update function it doesn't work.. Why doesn't ?

答:
PyGame draws in buffer in memory and updata() / flip() sends data from this buffer to video card which will display it on monitor.

It is popular method for problem with flicking screen and it is called Double Buffering

If you draw after update() then it will be not send to video card.

BTW: In normal game you draw and use update() in while loop so it doesn't make problem.

Body:
import pygame

pygame.init()
Display = pygame.display.set_mode((800,600))
pygame.display.set_caption("Blocky")

red = (157, 139, 215)
black = (0,0,0)

Display.fill(red)
pygame.draw.rect(Display,black,(400,300,200,80))

pygame.display.update()

excape = False

while not excape:
    for dork in pygame.event.get():
        print (dork)

[

Works correctly But When I copy and paste red to pygame.draw under the update function it doesn't work.. Why doesn't ?


问:
mysqldump - How to get line break instead of LF in contents?
mysqldump uses LF in field values, Is it possible to get line break instead of LF?</p>

```<code>INSERT IGNORE INTO `tbl1` VALUES (1, 2, "A\nB\nC");
INSERT IGNORE INTO `tbl1` VALUES (1, 2, "A
B
C");
</code>```

答:
mysqldump dumps data as they were inserted.
If you want to transform data, you should do it right after the dumping.
You can use sed for this or whatever you prefer.

This converts \n\r to \n with sed:

```<code>mysqldump.exe -uuser -p mydb | sed "s/\\\r\\\n/\\\n/g"
</code>```

Body:
mysqldump uses LF in field values, Is it possible to get line break instead of LF?

INSERT IGNORE INTO `tbl1` VALUES (1, 2, "A\nB\nC");
INSERT IGNORE INTO `tbl1` VALUES (1, 2, "A
B
C");

Body:
mysqldump dumps data as they were inserted.
If you want to transform data, you should do it right after the dumping.
You can use sed for this or whatever you prefer.

This converts \n\r to \n with sed:

mysqldump.exe -uuser -p mydb | sed "s/\\\r\\\n/\\\n/g"


问:
How to go to a website and wait 10 seconds after that redirect to another website
I use webbrowser1.Navigate  to launch web pages. I want to launch a website and keep it 10 seconds. after 10 seconds I want to redirect to the another webpage, etc

I use these codes but it shows only 2nd web page..

```<code>private void button3_Click(object sender, System.EventArgs e)
{
    textBox4.Text = textBox3.Text;
    string[] groups = textBox4.Text.Split('\n');

    timer1.Interval = timer1.Interval + 10000;
    webBrowser1.Navigate("https://mbasic.facebook.com/groups/516524655403741");
    timer1.Interval = timer1.Interval + 10000;
    webBrowser1.Navigate("https://mbasic.facebook.com/groups/548734261950831");
}
</code>```

I use the Timer class to wait 10 seconds but it is not working...

I want to launch 2 as I mentioned above. But this codes shows only 2nd webpage after executing..

Can you explain how I need to adapt my method to launch 1st web page and wait 10 seconds and redirect to 2nd web page?

答:
You have to keep in mind that in Windows Forms code is executed by firing events. You can't wait by expecting the code to stop for 10 seconds (and still have a responsive application).

Instead hook up the Tick event of the timer. That will fire every 10 seconds and use a list to hand the Tick event work. I've chosen to use an IEnumerator to keep track of the work but you could also use a Queue or an array where you keep track with an index counter.  Your implementation might look like this:

```<code>private void timer1_Tick(object sender, EventArgs e)
{
    // the enumerator has a Current, navigate to it
    webBrowser1.Navigate(websites.Current);
    // we stop the timer if there are no more websites
    timer1.Enabled = websites.MoveNext();
}

IEnumerator<string> websites; // this will keep track of the urls to navigate

private void button1_Click(object sender, EventArgs e)
{
    // set up a list with url's and then get its Enumarator
    websites = new List<string> {
        "https://mbasic.facebook.com/groups/516524655403741" ,
        "https://mbasic.facebook.com/groups/548734261950831"
    }.GetEnumerator();
    // enable the timer
    timer1.Enabled = true;
    // make sure our enumerator is going
    websites.MoveNext();
}
</code>```

Make sure your Timer.Interval is set to 10,000 from the Form Designer and hook the Tick event to the event handler:

With a 2 seconds interval this will be your result:

Body:
I use webbrowser1.Navigate  to launch web pages. I want to launch a website and keep it 10 seconds. after 10 seconds I want to redirect to the another webpage, etc

I use these codes but it shows only 2nd web page..

private void button3_Click(object sender, System.EventArgs e)
{
    textBox4.Text = textBox3.Text;
    string[] groups = textBox4.Text.Split('\n');

    timer1.Interval = timer1.Interval + 10000;
    webBrowser1.Navigate("https://mbasic.facebook.com/groups/516524655403741");
    timer1.Interval = timer1.Interval + 10000;
    webBrowser1.Navigate("https://mbasic.facebook.com/groups/548734261950831");
}

I use the Timer class to wait 10 seconds but it is not working...

I want to launch 2 as I mentioned above. But this codes shows only 2nd webpage after executing..

Can you explain how I need to adapt my method to launch 1st web page and wait 10 seconds and redirect to 2nd web page?

Body:
You have to keep in mind that in Windows Forms code is executed by firing events. You can't wait by expecting the code to stop for 10 seconds (and still have a responsive application).

Instead hook up the Tick event of the timer. That will fire every 10 seconds and use a list to hand the Tick event work. I've chosen to use an IEnumerator to keep track of the work but you could also use a Queue or an array where you keep track with an index counter.  Your implementation might look like this:

private void timer1_Tick(object sender, EventArgs e)
{
    // the enumerator has a Current, navigate to it
    webBrowser1.Navigate(websites.Current);
    // we stop the timer if there are no more websites
    timer1.Enabled = websites.MoveNext();
}

IEnumerator<string> websites; // this will keep track of the urls to navigate

private void button1_Click(object sender, EventArgs e)
{
    // set up a list with url's and then get its Enumarator
    websites = new List<string> {
        "https://mbasic.facebook.com/groups/516524655403741" ,
        "https://mbasic.facebook.com/groups/548734261950831"
    }.GetEnumerator();
    // enable the timer
    timer1.Enabled = true;
    // make sure our enumerator is going
    websites.MoveNext();
}

Make sure your Timer.Interval is set to 10,000 from the Form Designer and hook the Tick event to the event handler:

With a 2 seconds interval this will be your result:


问:
Piece back together numpy slices into original array
if you split a numpy array using slices like this:

Assuming data looked like this:
    [[ Y X X X....]
    [Y X X X....]]

```<code>X_test = data_test[:, 1:]
y_test = data_test[:, 0]
</code>```

I assumed this would work but I cannot find documentation in the process.

```<code>test_assembled = [:, y_test:X_test]
</code>```

答:
With

```<code>X_test = data_test[:, 1:]
y_test = data_test[:, 0]
</code>```

changes to X_test or y_test will be seen in data_test.  So you don't need to reassemble them to propagate changes.  They are views.

An assembly using np.concatante (or its derivatives, stack, c_ etc) will produce a new array, with its own databuffer.  That may, or may not be what you want.

In this case the only tricky part about concatenating them is the X_test is 2d, while y_test (indexed with a scalar) is 1d.  The concatenating has to take that into account.  The explicit way is to

```<code>y_temp = y_test[:,None]
new_data = np.concatenate((y_temp, X_test), axis=1)
</code>```

np.column_stack and c_ are convenience functions that can do that y_temp step for you.

Equally good is to construct a 'blank' receiver array, and copy the arrays with the same slicing notation.

```<code>new_data = np.zeros_like(data_test)
new_data[:, 1:] = X_test
new_data[:,0] = y_test
</code>```

In fact you could do that assignment to data_test, but there's no need to do that.

Verification:

```<code>In [135]: data_test = np.arange(12).reshape(3,4)
In [136]: data_test
Out[136]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [137]: X_test = data_test[:,1:]
In [139]: y_test = data_test[:,0]
In [140]: y_test
Out[140]: array([0, 4, 8])
In [141]: y_test *= 10
In [142]: data_test
Out[142]:
array([[ 0,  1,  2,  3],
       [40,  5,  6,  7],
       [80,  9, 10, 11]])
In [143]: np.concatenate((y_test[:,None], X_test), axis=1)
Out[143]:
array([[ 0,  1,  2,  3],
       [40,  5,  6,  7],
       [80,  9, 10, 11]])
In [144]: np.column_stack((y_test, X_test))
Out[144]:
array([[ 0,  1,  2,  3],
       [40,  5,  6,  7],
       [80,  9, 10, 11]])
In [145]: new = np.zeros_like(data_test)
In [146]: new[:,1:] = X_test
In [147]: new[:,0] = y_test/10
In [148]: new
Out[148]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
</code>```

Body:
if you split a numpy array using slices like this:

Assuming data looked like this:
    [[ Y X X X....]
    [Y X X X....]]

X_test = data_test[:, 1:]
y_test = data_test[:, 0]

I assumed this would work but I cannot find documentation in the process.

test_assembled = [:, y_test:X_test]

Body:
With

X_test = data_test[:, 1:]
y_test = data_test[:, 0]

changes to X_test or y_test will be seen in data_test.  So you don't need to reassemble them to propagate changes.  They are views.

An assembly using np.concatante (or its derivatives, stack, c_ etc) will produce a new array, with its own databuffer.  That may, or may not be what you want.

In this case the only tricky part about concatenating them is the X_test is 2d, while y_test (indexed with a scalar) is 1d.  The concatenating has to take that into account.  The explicit way is to

y_temp = y_test[:,None]
new_data = np.concatenate((y_temp, X_test), axis=1)

np.column_stack and c_ are convenience functions that can do that y_temp step for you.

Equally good is to construct a 'blank' receiver array, and copy the arrays with the same slicing notation.

new_data = np.zeros_like(data_test)
new_data[:, 1:] = X_test
new_data[:,0] = y_test

In fact you could do that assignment to data_test, but there's no need to do that.

Verification:

In [135]: data_test = np.arange(12).reshape(3,4)
In [136]: data_test
Out[136]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [137]: X_test = data_test[:,1:]
In [139]: y_test = data_test[:,0]
In [140]: y_test
Out[140]: array([0, 4, 8])
In [141]: y_test *= 10
In [142]: data_test
Out[142]:
array([[ 0,  1,  2,  3],
       [40,  5,  6,  7],
       [80,  9, 10, 11]])
In [143]: np.concatenate((y_test[:,None], X_test), axis=1)
Out[143]:
array([[ 0,  1,  2,  3],
       [40,  5,  6,  7],
       [80,  9, 10, 11]])
In [144]: np.column_stack((y_test, X_test))
Out[144]:
array([[ 0,  1,  2,  3],
       [40,  5,  6,  7],
       [80,  9, 10, 11]])
In [145]: new = np.zeros_like(data_test)
In [146]: new[:,1:] = X_test
In [147]: new[:,0] = y_test/10
In [148]: new
Out[148]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])


问:
How do I set up a multi-stage test pipeline in sbt?
Specifically, for a Scalatra project, but the question probably applies to most.

For example, I typically want to run:

unit tests

code quality checks (coverage, duplication, complexity, jsLint!)

integration tests (not too many!)

acceptance tests (usually a "pre-checkin" subset)

regression tests (basically the same as acceptance tests, but a bigger set)

performance tests

I want to run different subsets of these by context - i.e. after a simple code change I might just run the first three; before checking in I might want to run a bigger set, and the Continuous Integration server might have a "fast" and a "slow" build that have even bigger sets.

The basic sbt docs seem to assume a single "test" target - is there a recommended way to implement multiple test phases like this?

答:
You may want to look at this blog about using integrated testing with SBT and Hudson:

http://henkelmann.eu/2010/11/14/sbt_hudson_with_test_integration

Then, to add your own actions you can use this page:

http://code.google.com/p/simple-build-tool/wiki/CustomActions

Basically, though, you will probably want to add a new action for each of your testing steps, in order to get the particular events you want to happen.


问:
Allow or disallow value change in combo box based on initial value to new value
I am trying to write code for a data certification status combobox that will allow or not allow the user to change the status based on specific guidelines:

User may change status from Raw to Clean, no restriction

User may change status from Clean to Certified, no restriction

User may change status from Raw to Certified after answering yes to verify all necessary QA/QC has been done

User may change status from Clean to Raw, if answers yes to proceed and provides explanation in "Comments" field

User may not change status from Certified to Clean, or from Certified to Raw

I assume I would use a Select statement where Case 1 = Raw (ID=1), Case 2 = Clean (ID=2), Case 3 = Certified (ID=3). The IDs 1, 2, and 3 are the ID values in the lookup table for the data certification status'. What I'm struggling with is how I set the "Before" value to compare to the "Current" value, when the user has already selected a different value.

Also, I'm using the "OnChange" event. But wondering if "BeforeUpdate" or "OnDirty" events would be better.

Any help would be greatly appreciated.

答:
use "BeforeUpdate" Event on combox</p>

```<code>If Me.Combo3.OldValue = 1 And Me.Combo3.Value = 2 Then
    Dim x
    x = MsgBox("all necessary QA/QC has been done? ", vbYesNo)
    If x = vbNo Then
    MsgBox "any thing you want to write"
    Cancel = True
    End If

End If
</code>```

Body:
use "BeforeUpdate" Event on combox

If Me.Combo3.OldValue = 1 And Me.Combo3.Value = 2 Then
    Dim x
    x = MsgBox("all necessary QA/QC has been done? ", vbYesNo)
    If x = vbNo Then
    MsgBox "any thing you want to write"
    Cancel = True
    End If

End If


问:
Create KenBurns with minimum possible zoom
I am using this library

I am trying to create app with minimal possible zoom.
In my application I have small area where the images are presented as slide show. But the images are big so when kenburns effect starts it it zoomed too much.

How can I set the zoom level ?

答: You need to create your own TransitionGenerator. If you want the keep the random movement and control the zoom, a good place to start is to base your custom TransitionGenerator off this one. The highlighted line (120) uses a random zoom factor. Hardcoding it will do what you need.


问:
Javascript: issue with inheritance test (JS Definitive Guide book supplied code issue)
I'm new to Javascript. Usually write Python/PHP. Currently reading through JavaScript: The Definitive Guide: Activate Your Web Pages (Definitive Guides).

Part of the example code used I'm trying to figure out why it won't work, and the detailed explanation why too if possible, is below over properties getter/setters and inheritance.

The function I'm using:

```<code>function inherit(p) {
     if (p == null) throw TypeError();
     if (Object.create) return Object.create(p);
     var t = typeof p;
     if (t !== "object" && t !== "function") throw TypeError();
     function f() {};
     f.prototype = p;
     return new f();
}

var p = {
    x: 1.0,
    y: 1.0,
    get r() {
        return Math.sqrt(this.x*this.x + this.y*this.y);
    },
    set r(newvalue) {
        var oldvalue = Math.sqrt(this.x*this.x + this.y*this.y);
        var ratio = newvalue/oldvalue;
        this.x *= ratio;
        this.y *= ratio;
    },
        get theta() { return Math.atan2(this.y, this.x); }
};
</code>```

When I run a test. I can't see anything being inherited.

```<code>> var q = inherit(p)
undefined
> q
{}
> p
{ x: 1, y: 1, r: [Getter/Setter], theta: [Getter] }
</code>```

Why is this? I am currently using node v6.11.3 on Mac to run this.

Update:

Discovered how to show all values in an Object. Setting enumerable:True to an object will auto-display all values. What I was trying to figure out how to do. For any who also use Node.js.

答: if you use Object.getOwnPropertyDescriptors(Object.getPrototypeOf(q)) you should see the inherited properties from p. If you check equality with Object.getPrototypeOf(), the prototype of q should be equal to p.

Body:
I'm new to Javascript. Usually write Python/PHP. Currently reading through JavaScript: The Definitive Guide: Activate Your Web Pages (Definitive Guides).

Part of the example code used I'm trying to figure out why it won't work, and the detailed explanation why too if possible, is below over properties getter/setters and inheritance.

The function I'm using:

function inherit(p) {
     if (p == null) throw TypeError();
     if (Object.create) return Object.create(p);
     var t = typeof p;
     if (t !== "object" && t !== "function") throw TypeError();
     function f() {};
     f.prototype = p;
     return new f();
}

var p = {
    x: 1.0,
    y: 1.0,
    get r() {
        return Math.sqrt(this.x*this.x + this.y*this.y);
    },
    set r(newvalue) {
        var oldvalue = Math.sqrt(this.x*this.x + this.y*this.y);
        var ratio = newvalue/oldvalue;
        this.x *= ratio;
        this.y *= ratio;
    },
        get theta() { return Math.atan2(this.y, this.x); }
};

When I run a test. I can't see anything being inherited.

> var q = inherit(p)
undefined
> q
{}
> p
{ x: 1, y: 1, r: [Getter/Setter], theta: [Getter] }

Why is this? I am currently using node v6.11.3 on Mac to run this.

Update:

Discovered how to show all values in an Object. Setting enumerable:True to an object will auto-display all values. What I was trying to figure out how to do. For any who also use Node.js.


问:
mirror prime generator python
I am currently enrolled in a Python programming course and last week we got a homework problem which was to Develop a program to generate all prime numbers less or equal to n whose mirror is also prime, I can't see where I am going wrong, please help!

```<code>import math

def mirror_prime(n):
    answer = True
    # Test 0 and 1
    if n==0 or n==1:
        answer = False
    # End if

    # Test even numbers
    if n != 2 and n%2==0:
        answer= False
    # End if

    # Test if there is a proper odd divisor
        for d in range (3, int(math.sqrt(n))+1, 2):
            if n%d==0:
                answer=False
            # End if
        # End for

    #Reverse n
    mirror_n = int(str(n)[::-1])
    mirror_answer = True

    # Test 0 and 1
    if mirror_n==0 or mirror_n==1:
        mirror_answer = False
    # End if

def mirror_prime_generator(n):
    for i in range(3, n+1):
        print (mirror_prime(i))
</code>```

I am expecting to get a list of all prime numbers whose mirror is also prime less or equal to n

The result i get when i put mirror_prime_generator(n) into the shell, it justs prints none however many times n is, so if n is 23 it will print none 23 times

答:
You have to consider what you want your functions to do. As far as I can tell, the function mirror_prime(n) answers the question "are both n and its mirror prime?", which is a binary question (either true or false). If that is the case, which is entirely reasonable, restructure your mirror_prime_generator loop like this:

```<code>def mirror_prime_generator(n):
    for i in range(3, n+1):
        if mirror_prime(i):
            print(i)
</code>```

This is, of course, assuming that mirror_prime actually returns a correct result, but that seems like your whole task so I won't give you that.

Title: mirror prime generator python

Body:
I am currently enrolled in a Python programming course and last week we got a homework problem which was to Develop a program to generate all prime numbers less or equal to n whose mirror is also prime, I can't see where I am going wrong, please help!

import math

def mirror_prime(n):
    answer = True
    # Test 0 and 1
    if n==0 or n==1:
        answer = False
    # End if

    # Test even numbers
    if n != 2 and n%2==0:
        answer= False
    # End if

    # Test if there is a proper odd divisor
        for d in range (3, int(math.sqrt(n))+1, 2):
            if n%d==0:
                answer=False
            # End if
        # End for

    #Reverse n
    mirror_n = int(str(n)[::-1])
    mirror_answer = True

    # Test 0 and 1
    if mirror_n==0 or mirror_n==1:
        mirror_answer = False
    # End if

def mirror_prime_generator(n):
    for i in range(3, n+1):
        print (mirror_prime(i))

I am expecting to get a list of all prime numbers whose mirror is also prime less or equal to n

The result i get when i put mirror_prime_generator(n) into the shell, it justs prints none however many times n is, so if n is 23 it will print none 23 times

Body:
You have to consider what you want your functions to do. As far as I can tell, the function mirror_prime(n) answers the question "are both n and its mirror prime?", which is a binary question (either true or false). If that is the case, which is entirely reasonable, restructure your mirror_prime_generator loop like this:

def mirror_prime_generator(n):
    for i in range(3, n+1):
        if mirror_prime(i):
            print(i)

This is, of course, assuming that mirror_prime actually returns a correct result, but that seems like your whole task so I won't give you that.


问:
Spring 3.2 with Java 7 and Java 8
I have read following questions related to Spring 3.2 and Java 8 compatibility issues but i still have few open questions.

Java 8 Spring compatibility

spring-core 3.2.9 + java 8

Spring 3.2.x with Java 8

Let's say there is an artifact (e.g. DAL) that uses Spring 3.2 and this artifact has to be shared between java 7 service (Service A) and java 8 service ( Service B). These services will compiled and run against respective Java/JVMs.

Now question is -  will it be possible to use DAL in both Service-A and Service-B?

As per snippet 1, it should work because Java 8 runtime supports the Spring 3.2 libraries compiled against Java 7 but as per snippet 2 this shouldn't work as Service-B has been complied against java 8 and it is going to use DAL that has been compiled against java 7.

Snippet 1:

However some spring release notes says that the Spring Framework 3.2.x will support deployment on JDK 8 runtimes for applications compiled against JDK 7 (with -target 1.7) or earlier. Note that it won’t support JDK 8’s bytecode format (-target 1.8, as needed for lambdas); please upgrade to Spring Framework 4.0 for that purpose.

Snippet 2:

Versions of the Spring Framework that are older than 4.0M1 do not work with classes that are compiled for Java 8.

答:
There is no point of migrating to Java 8 with Spring 3.x, Its better to move to JDK 1.8 and Spring 4.x. The JDK 8 migration should not be an issue unless the code has to be changed for JDK 8 features.

Spring 3.2.9 will be the best bet in terms of Java 8 byte code support.

Title: Spring 3.2 with Java 7 and Java 8


问:
How do I draw a smooth line with a finger slide/touch motion on the iPhone?
I have the following code but it is not smooth. If I draw a circle, i see the sharp corners.</p>

```<code>UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), YES);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
</code>```

答:
You are seeing some of the sharp corners because you are drawing too many short antialiased line segments, which all takes more than 1/60th of a second, thus you end up missing UI touch event updates, which leads to a more jaggy path.

2D CG drawing is not accelerated on iOS devices.

If you want to stick with CG drawing, try drawing only the last 4 or so line segments, maybe turn off antialiasing, and see if that's smoother.  Then fill in the rest after the path drawing is done (touch up).

Body:
I have the following code but it is not smooth. If I draw a circle, i see the sharp corners.

UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), YES);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


问:
interest of .SD within data.table operations
I have a question concerning data.table.
I love it but I think I was/am sometime misusing the .SD, and I would appreciate some clarification about when it is interesting to use it in data.table.

Here are two examples where I came to think that I was misusing .SD :

The first one is as discussed here (thanks for the Henry's comment)

```<code>library(microbenchmark)
library(data.table)

DTlength <- 2000
DT <-
  data.table(
    id = rep(sapply(combn(LETTERS, 6, simplify = FALSE), function(x) {
      paste(x, collapse = "")
    }), each = 4)[1:DTlength],
    replicate(10, sample(1001, DTlength, replace = TRUE)),
    Answer = sample(c("Yes", "No"), DTlength, TRUE)
  )

microbenchmark(
  "without SD" = {
    b <- DT[, Answer[1], by = id][, V1]
  },
  "without SD alternative" = {
    b <- DT[DT[, .I[1], by = id][, V1], Answer]
  },
  "with SD" = {
    b <- DT[, .SD[1, Answer], by = id][, V1]
  }
)

Unit: microseconds
                   expr        min         lq        mean     median         uq        max neval
             without SD    455.795    493.949    569.4979    529.847    558.564   2323.283   100
 without Sd alternative    961.231   1010.667   1160.9114   1060.513   1113.641   7783.798   100
                with SD 121217.691 123557.590 131071.5699 127495.437 130340.977 240317.227   100
</code>```

.SD operation are quite slow compared to alternative in grouping operations.
Even if you want to group to the entire data.table, the alternatives are slightly faster (although the time difference here is maybe not worth the loss of clarity of the syntax):

```<code>microbenchmark(
  "with SD" = {b <-DT[,.SD[1], by = id]},
  "Without SD" = {b <- DT[DT[,.I[1],by = id][,V1]]}
)

Unit: milliseconds
       expr      min       lq     mean   median       uq      max neval
    with SD 1.058872 1.361436 1.560866 1.643078 1.741540 1.960206   100
 Without SD 1.067898 1.169642 1.279443 1.233437 1.348719 1.781334   100
</code>```

The second example illustrates the fact that you can't really use .SD to assign new variable to a value with a condition within groups (or I didn't find the way):

```<code>DT[, .SD[V1 - V1[1] > 100][, plouf2 := Answer], by = id] # doesn't assign plouf2
DT[DT[, .I[V1 - V1[1] > 100], by = id][, V1], plouf2 := Answer] # this does
</code>```

There are two situations where I found it useful to use .SD : the DT[,lapply(.SD,fun),.SDcols = ] use that is very convenient, and when one wants to assign all values in the group to a particular value that meets a particular condition within the group :

```<code>DT[, plouf3 := .SD[V1 - V1[1] > 100, Answer][1], by = id]
# all values are assigned, which is actually different from
DT[DT[, .I[V1 - V1[1] > 100][1], by = id][, V1], plouf2 := Answer]
# where only the values that match the condition V1-V1[1]>100 are assigned
</code>```

So my question: are there other situations where it is needed/interesting to use .SD ?

Thank you in advance for the help.

答:
Regarding your first question

The benchmark would only be fair if all three methods would generate the same output. The "without SD alternative" method generates a different result, so let's set that one aside.

The "with SD" and "without SD" methods generate the same output but the latter is more efficient. Here is why: when you do ... .SD[1, Answer] ... you are basically subsetting all of the columns for the matching rows, then you are performing the next operation (which is to fetch the first value of the vector Answer) on this subset. However, in the "without SD" method, you are only subsetting one vector (not all vectors) and then fetching the first value of that one vector. The unnecessary subsetting of the additional, unused columns in the "with SD" method is what makes it slow.

Regarding your second question

This command does not assign the values to DT:

DT[, .SD[V1 - V1[1] > 100][, plouf2 := Answer], by = id]

The reason is that the .SD operator is a one-way operator, that is if you change something in the subset that .SD gives you, it doesn't apply it back on the larger data.table but only applies it on the in-memory copy of the subset. It is not fair to call it an in-memory copy, because .SD does not actually copy the data (it just points the relevant portion of the memory that holds the subset of interest), but the point is that assignments to it will only be applied to this in-memory pointer and not the original underlying data.

Note: You could argue, then, that it should not support assignments whatsoever. I don't know what Matt Dowle thinks, but in my humble opinion, the assignment is actually a useful feature! For instance:

DT.2 <- DT[, .SD[V1 - V1[1] > 100][, plouf2 := Answer], by = id]

This way I have a very short, highly readable piece of code, that generates the output I desire and stores it in a new data.table without modifying the original data.table! Any other way that I can think of to generate this exact output without using .SD and without touching the original data.table involves much longer code.

Regarding your last question

.SD is useful when you want to deal with many or all columns of a data.table and not just a few or only one column. (This is why the "with SD" method you used in the first part is not an appropriate way to do what you want to do). The examples provided in What does .SD stand for in data.table in R are very useful to demonstrate when .SD can be very handy. In my opinion, the main advantage of .SD is not with the efficiency at the which the code runs, but rather, in the efficiency in which you can turn a concept into R code, and the readability of that piece of code.

Body:
I have a question concerning data.table.
I love it but I think I was/am sometime misusing the .SD, and I would appreciate some clarification about when it is interesting to use it in data.table.

Here are two examples where I came to think that I was misusing .SD :

The first one is as discussed here (thanks for the Henry's comment)

library(microbenchmark)
library(data.table)

DTlength <- 2000
DT <-
  data.table(
    id = rep(sapply(combn(LETTERS, 6, simplify = FALSE), function(x) {
      paste(x, collapse = "")
    }), each = 4)[1:DTlength],
    replicate(10, sample(1001, DTlength, replace = TRUE)),
    Answer = sample(c("Yes", "No"), DTlength, TRUE)
  )

microbenchmark(
  "without SD" = {
    b <- DT[, Answer[1], by = id][, V1]
  },
  "without SD alternative" = {
    b <- DT[DT[, .I[1], by = id][, V1], Answer]
  },
  "with SD" = {
    b <- DT[, .SD[1, Answer], by = id][, V1]
  }
)

Unit: microseconds
                   expr        min         lq        mean     median         uq        max neval
             without SD    455.795    493.949    569.4979    529.847    558.564   2323.283   100
 without Sd alternative    961.231   1010.667   1160.9114   1060.513   1113.641   7783.798   100
                with SD 121217.691 123557.590 131071.5699 127495.437 130340.977 240317.227   100

.SD operation are quite slow compared to alternative in grouping operations.
Even if you want to group to the entire data.table, the alternatives are slightly faster (although the time difference here is maybe not worth the loss of clarity of the syntax):

microbenchmark(
  "with SD" = {b <-DT[,.SD[1], by = id]},
  "Without SD" = {b <- DT[DT[,.I[1],by = id][,V1]]}
)

Unit: milliseconds
       expr      min       lq     mean   median       uq      max neval
    with SD 1.058872 1.361436 1.560866 1.643078 1.741540 1.960206   100
 Without SD 1.067898 1.169642 1.279443 1.233437 1.348719 1.781334   100

The second example illustrates the fact that you can't really use .SD to assign new variable to a value with a condition within groups (or I didn't find the way):

DT[, .SD[V1 - V1[1] > 100][, plouf2 := Answer], by = id] # doesn't assign plouf2
DT[DT[, .I[V1 - V1[1] > 100], by = id][, V1], plouf2 := Answer] # this does

There are two situations where I found it useful to use .SD : the DT[,lapply(.SD,fun),.SDcols = ] use that is very convenient, and when one wants to assign all values in the group to a particular value that meets a particular condition within the group :

DT[, plouf3 := .SD[V1 - V1[1] > 100, Answer][1], by = id]
# all values are assigned, which is actually different from
DT[DT[, .I[V1 - V1[1] > 100][1], by = id][, V1], plouf2 := Answer]
# where only the values that match the condition V1-V1[1]>100 are assigned

So my question: are there other situations where it is needed/interesting to use .SD ?

Thank you in advance for the help.


问:
copy variable number of lines based on start and end triggers
I have a script that collects only the important lines of text from multiple log files and writes them to a separate text file. It works as long as I provide a string snippet to search for. Once found, it will copy the entire line of text where it found the string snippet. Now I need it to select multiple lines of text based on known starting and ending text snippets. The total number of lines between/including the starting and ending text snippets varies among the log files that I'm reading. I've searched and tried lots of things, but can't get it to work. I'm providing what I have so far.

I'm not a python newbie, but far from an expert. Any/All advice is truly appreciated.

```<code>import os, time, datetime, fnmatch, re
from time import strftime, time

# Open log file to record actions
dirName = "D://GISlogs//" + strftime("%Y%m%d")
global pubfilePrefix
pubfilePrefix = datetime.datetime.now() + datetime.timedelta(minutes=1)
pubfileName = "D://GISlogs//" + strftime("%Y%m%d") + "//" + pubfilePrefix.strftime("%Y%m%d_%H%M%S") + "_SUMMARIZE_MorningActivities.txt"
if os.path.exists(pubfileName) and os.path.isfile(pubfileName) and os.access(pubfileName, os.W_OK):
    with open(pubfileName, "a") as myFile:
        myFile.write(strftime("%Y-%m-%d %H:%M:%S") + "  SUMMARIZING ALL GIS ACTIVITIES1" + "\r\n" + "\r\n")
else:
    try:
        os.makedirs(dirName)
        with open(pubfileName, "a") as myFile:
            myFile.write(strftime("%Y-%m-%d %H:%M:%S") + "  SUMMARIZING ALL GIS ACTIVITIES2" + "\r\n" + "\r\n")
    except OSError:
        if os.path.isdir(dirName):
            with open(pubfileName, "a") as myFile:
                myFile.write(strftime("%Y-%m-%d %H:%M:%S") + "  SUMMARIZING ALL GIS ACTIVITIES3" + "\r\n" + "\r\n")

def Search_LogFile(searchPhrase, titleBlock):
    if searchPhrase == "~-~-~":
        with open(pubfileName, "a") as myFile:
            myFile.write("\r\n" + titleBlock + "\r\n" + "---------------------------------------------------------------------------------------" + "\r\n")

    with open("D://GISlogs//" + strftime("%Y%m%d") + "//" + searchFile, "r") as readFile:
        for readLine in readFile:
            if searchPhrase in readLine:
                if re.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2} ").match(readLine):
                    readLine = readLine[11:]
                with open(pubfileName, "a") as myFile:
                    myFile.write(readLine)

for searchFile in os.listdir(dirName):

    if fnmatch.fnmatch(searchFile, "*COPY_TaxRollData.txt"):
        Search_LogFile("~-~-~", "Acquiring Updated Data from PVA")
        Search_LogFile(" - DELETING PREVIOUSLY DOWNLOADED PVA DATA", "")
        Search_LogFile(" - DOWNLOADING THE LATEST SNAPSHOT OF PUBLIC INQUIRY DATABASE", "")
        Search_LogFile(" - ARCHIVING ALL DOWNLOADED FILES", "")
        Search_LogFile(" - RECONCILING NEW DOWNLOAD WITH PRIOR DATA", "")
        Search_LogFile(" - EXECUTING FME MODEL TO OVERWRITE PVA DATA IN SDE", "")

    if fnmatch.fnmatch(searchFile, "*INTEGRATE_TaxRollData.txt"):
        Search_LogFile("~-~-~", "Integrating Updated Data from PVA into the SDE Production EGDB")
        Search_LogFile("|INFORM|Reading table/feature class '", "")
        Search_LogFile("|INFORM|Opened Shape File '", "")
        Search_LogFile("|INFORM|CSV reader: Opening dataset '", "")
        Search_LogFile("|ERROR |", "")
        Search_LogFile("|INFORM|Translation was SUCCESSFUL", "")
        Search_LogFile("|INFORM|FME Session Duration:", "")
        #THE NEXT 9 LINES IS MY LATEST ATTEMPT. IT WORKS OUTSIDE OF THIS BLOCK OF CODE, BUT NOT HERE
        valid=False
        for line in searchFile:
            if re.compile(".*Features Written Summary.*").match(line):
                valid=True
            if re.compile(".*Total Features Written.*").match(line):
                valid=False
            if valid:
                with open(pubfileName, "a") as myFile:
                    myFile.write(line)
        #Search_LogFile("Features Written Summary", "")
        Search_LogFile("  PVA TAX ROLL DATA HAS BEEN RE-INTEGRATED IN THE SDE PRODUCTION DATABASE", "")

print('\r\n' +'The Script Completed successfully')
</code>```

To clarify further - the text "Features Written Summary" is on the line that I want my capture to begin with, and "Total Features Written" is on the line that I want my capture to end with (I want to copy the entire line where both snippets appear as well as everything in between).  Both starting and ending snippets appear only once in the log file.

@MadPhysicist When I run the code, it finds the first log file and looks for specific phrases. When it finds them it writes the entire line of text where it found the phrase to a different text file. It then looks for the next specific phrase and does the same thing. After looking for all of the specific phrases in that log file, it will find the next log file and look for a different set of phrases specific to that particular log file.  It works great.

But what I'm trying to add is a little different tweak that I can't figure out.  In the second log file, I want to copy more than one consecutive line found within it to my other text file.  I can copy the start line and end line using the method described above, but the wrinkle is that I also want to copy all of the lines of text between the start line and end line.  The number of lines between the start and end lines can vary as well, so that can't be hard-coded.

答:
So I have a working solution now, but I'm not sure if it's the most efficient and/or could be designed better. I'm going to put it in place, but if anyone can think of a better way to go about what I'm trying to do here, I'm all ears...</p>

```<code>import os, time, datetime, fnmatch, re
from time import strftime, time

# Open log file to record actions
dirName = "D://GISlogs//" + strftime("%Y%m%d")
global pubfilePrefix
pubfilePrefix = datetime.datetime.now() + datetime.timedelta(minutes=1)
pubfileName = "D://GISlogs//" + strftime("%Y%m%d") + "//" +
pubfilePrefix.strftime("%Y%m%d_%H%M%S") + "_SUMMARIZE_MorningActivities.txt"
if os.path.exists(pubfileName) and os.path.isfile(pubfileName) and os.access(pubfileName, os.W_OK):
    with open(pubfileName, "a") as myFile:
        myFile.write(strftime("%Y-%m-%d %H:%M:%S") + "  SUMMARIZING ALL GIS ACTIVITIES1" + "\r\n" + "\r\n")
else:
    try:
        os.makedirs(dirName)
        with open(pubfileName, "a") as myFile:
            myFile.write(strftime("%Y-%m-%d %H:%M:%S") + "  SUMMARIZING ALL GIS ACTIVITIES2" + "\r\n" + "\r\n")
    except OSError:
        if os.path.isdir(dirName):
            with open(pubfileName, "a") as myFile:
                myFile.write(strftime("%Y-%m-%d %H:%M:%S") + "  SUMMARIZING ALL GIS ACTIVITIES3" + "\r\n" + "\r\n")

def Search_LogFile(searchPhrase, titleBlock):
    if searchPhrase == "~-~-~":
        with open(pubfileName, "a") as myFile:
            myFile.write("\r\n" + titleBlock + "\r\n" + "---------------------------------------------------------------------------------------" + "\r\n")

    with open("D://GISlogs//" + strftime("%Y%m%d") + "//" + searchFile, "r") as readFile:
        for readLine in readFile:
            if searchPhrase in readLine:
                if re.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2} ").match(readLine):
                    readLine = readLine[11:]
                with open(pubfileName, "a") as myFile:
                    myFile.write(readLine)

            if searchPhrase in readLine and searchPhrase == "Features Written Summary":
                valid=False
                for line in readFile:
                    if re.compile(".*|                           Features Written Summary.*").match(line):
                        valid = True
                    if re.compile(".*END - ProcessID.*").match(line):
                        valid = False
                    if valid:
                        if re.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2} ").match(line):
                            line = line[11:]
                            with open(pubfileName, "a") as myFile:
                                myFile.write(line)

for searchFile in os.listdir(dirName):

    if fnmatch.fnmatch(searchFile, "*COPY_TaxRollData.txt"):
        Search_LogFile("~-~-~", "Acquiring Updated Data from PVA")
        Search_LogFile(" - DELETING PREVIOUSLY DOWNLOADED PVA DATA", "")
        Search_LogFile(" - DOWNLOADING THE LATEST SNAPSHOT OF PUBLIC INQUIRY DATABASE", "")
        Search_LogFile(" - ARCHIVING ALL DOWNLOADED FILES", "")
        Search_LogFile(" - RECONCILING NEW DOWNLOAD WITH PRIOR DATA", "")
        Search_LogFile(" - DISCONNECTING W: DRIVE", "")
        Search_LogFile(" - EXECUTING FME MODEL TO OVERWRITE PVA DATA IN SDE", "")

    if fnmatch.fnmatch(searchFile, "*INTEGRATE_TaxRollData.txt"):
        Search_LogFile("~-~-~", "Integrating Updated Data from PVA into the SDE Production EGDB")
        Search_LogFile("Reading table/feature class '", "")
        Search_LogFile("Opened Shape File '", "")
        Search_LogFile("CSV reader: Opening dataset '", "")
        Search_LogFile("|ERROR |", "")
        #Search_LogFile("|WARN  |", "")
        Search_LogFile("Features Written Summary", "")
</code>```

Body:
I have a script that collects only the important lines of text from multiple log files and writes them to a separate text file. It works as long as I provide a string snippet to search for. Once found, it will copy the entire line of text where it found the string snippet. Now I need it to select multiple lines of text based on known starting and ending text snippets. The total number of lines between/including the starting and ending text snippets varies among the log files that I'm reading. I've searched and tried lots of things, but can't get it to work. I'm providing what I have so far.

I'm not a python newbie, but far from an expert. Any/All advice is truly appreciated.

import os, time, datetime, fnmatch, re
from time import strftime, time

# Open log file to record actions
dirName = "D://GISlogs//" + strftime("%Y%m%d")
global pubfilePrefix
pubfilePrefix = datetime.datetime.now() + datetime.timedelta(minutes=1)
pubfileName = "D://GISlogs//" + strftime("%Y%m%d") + "//" + pubfilePrefix.strftime("%Y%m%d_%H%M%S") + "_SUMMARIZE_MorningActivities.txt"
if os.path.exists(pubfileName) and os.path.isfile(pubfileName) and os.access(pubfileName, os.W_OK):
    with open(pubfileName, "a") as myFile:
        myFile.write(strftime("%Y-%m-%d %H:%M:%S") + "  SUMMARIZING ALL GIS ACTIVITIES1" + "\r\n" + "\r\n")
else:
    try:
        os.makedirs(dirName)
        with open(pubfileName, "a") as myFile:
            myFile.write(strftime("%Y-%m-%d %H:%M:%S") + "  SUMMARIZING ALL GIS ACTIVITIES2" + "\r\n" + "\r\n")
    except OSError:
        if os.path.isdir(dirName):
            with open(pubfileName, "a") as myFile:
                myFile.write(strftime("%Y-%m-%d %H:%M:%S") + "  SUMMARIZING ALL GIS ACTIVITIES3" + "\r\n" + "\r\n")

def Search_LogFile(searchPhrase, titleBlock):
    if searchPhrase == "~-~-~":
        with open(pubfileName, "a") as myFile:
            myFile.write("\r\n" + titleBlock + "\r\n" + "---------------------------------------------------------------------------------------" + "\r\n")

    with open("D://GISlogs//" + strftime("%Y%m%d") + "//" + searchFile, "r") as readFile:
        for readLine in readFile:
            if searchPhrase in readLine:
                if re.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2} ").match(readLine):
                    readLine = readLine[11:]
                with open(pubfileName, "a") as myFile:
                    myFile.write(readLine)

for searchFile in os.listdir(dirName):

    if fnmatch.fnmatch(searchFile, "*COPY_TaxRollData.txt"):
        Search_LogFile("~-~-~", "Acquiring Updated Data from PVA")
        Search_LogFile(" - DELETING PREVIOUSLY DOWNLOADED PVA DATA", "")
        Search_LogFile(" - DOWNLOADING THE LATEST SNAPSHOT OF PUBLIC INQUIRY DATABASE", "")
        Search_LogFile(" - ARCHIVING ALL DOWNLOADED FILES", "")
        Search_LogFile(" - RECONCILING NEW DOWNLOAD WITH PRIOR DATA", "")
        Search_LogFile(" - EXECUTING FME MODEL TO OVERWRITE PVA DATA IN SDE", "")

    if fnmatch.fnmatch(searchFile, "*INTEGRATE_TaxRollData.txt"):
        Search_LogFile("~-~-~", "Integrating Updated Data from PVA into the SDE Production EGDB")
        Search_LogFile("|INFORM|Reading table/feature class '", "")
        Search_LogFile("|INFORM|Opened Shape File '", "")
        Search_LogFile("|INFORM|CSV reader: Opening dataset '", "")
        Search_LogFile("|ERROR |", "")
        Search_LogFile("|INFORM|Translation was SUCCESSFUL", "")
        Search_LogFile("|INFORM|FME Session Duration:", "")
        #THE NEXT 9 LINES IS MY LATEST ATTEMPT. IT WORKS OUTSIDE OF THIS BLOCK OF CODE, BUT NOT HERE
        valid=False
        for line in searchFile:
            if re.compile(".*Features Written Summary.*").match(line):
                valid=True
            if re.compile(".*Total Features Written.*").match(line):
                valid=False
            if valid:
                with open(pubfileName, "a") as myFile:
                    myFile.write(line)
        #Search_LogFile("Features Written Summary", "")
        Search_LogFile("  PVA TAX ROLL DATA HAS BEEN RE-INTEGRATED IN THE SDE PRODUCTION DATABASE", "")

print('\r\n' +'The Script Completed successfully')

To clarify further - the text "Features Written Summary" is on the line that I want my capture to begin with, and "Total Features Written" is on the line that I want my capture to end with (I want to copy the entire line where both snippets appear as well as everything in between).  Both starting and ending snippets appear only once in the log file.

@MadPhysicist When I run the code, it finds the first log file and looks for specific phrases. When it finds them it writes the entire line of text where it found the phrase to a different text file. It then looks for the next specific phrase and does the same thing. After looking for all of the specific phrases in that log file, it will find the next log file and look for a different set of phrases specific to that particular log file.  It works great.

But what I'm trying to add is a little different tweak that I can't figure out.  In the second log file, I want to copy more than one consecutive line found within it to my other text file.  I can copy the start line and end line using the method described above, but the wrinkle is that I also want to copy all of the lines of text between the start line and end line.  The number of lines between the start and end lines can vary as well, so that can't be hard-coded.

Body:
So I have a working solution now, but I'm not sure if it's the most efficient and/or could be designed better. I'm going to put it in place, but if anyone can think of a better way to go about what I'm trying to do here, I'm all ears...

import os, time, datetime, fnmatch, re
from time import strftime, time

# Open log file to record actions
dirName = "D://GISlogs//" + strftime("%Y%m%d")
global pubfilePrefix
pubfilePrefix = datetime.datetime.now() + datetime.timedelta(minutes=1)
pubfileName = "D://GISlogs//" + strftime("%Y%m%d") + "//" +
pubfilePrefix.strftime("%Y%m%d_%H%M%S") + "_SUMMARIZE_MorningActivities.txt"
if os.path.exists(pubfileName) and os.path.isfile(pubfileName) and os.access(pubfileName, os.W_OK):
    with open(pubfileName, "a") as myFile:
        myFile.write(strftime("%Y-%m-%d %H:%M:%S") + "  SUMMARIZING ALL GIS ACTIVITIES1" + "\r\n" + "\r\n")
else:
    try:
        os.makedirs(dirName)
        with open(pubfileName, "a") as myFile:
            myFile.write(strftime("%Y-%m-%d %H:%M:%S") + "  SUMMARIZING ALL GIS ACTIVITIES2" + "\r\n" + "\r\n")
    except OSError:
        if os.path.isdir(dirName):
            with open(pubfileName, "a") as myFile:
                myFile.write(strftime("%Y-%m-%d %H:%M:%S") + "  SUMMARIZING ALL GIS ACTIVITIES3" + "\r\n" + "\r\n")

def Search_LogFile(searchPhrase, titleBlock):
    if searchPhrase == "~-~-~":
        with open(pubfileName, "a") as myFile:
            myFile.write("\r\n" + titleBlock + "\r\n" + "---------------------------------------------------------------------------------------" + "\r\n")

    with open("D://GISlogs//" + strftime("%Y%m%d") + "//" + searchFile, "r") as readFile:
        for readLine in readFile:
            if searchPhrase in readLine:
                if re.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2} ").match(readLine):
                    readLine = readLine[11:]
                with open(pubfileName, "a") as myFile:
                    myFile.write(readLine)

            if searchPhrase in readLine and searchPhrase == "Features Written Summary":
                valid=False
                for line in readFile:
                    if re.compile(".*|                           Features Written Summary.*").match(line):
                        valid = True
                    if re.compile(".*END - ProcessID.*").match(line):
                        valid = False
                    if valid:
                        if re.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2} ").match(line):
                            line = line[11:]
                            with open(pubfileName, "a") as myFile:
                                myFile.write(line)

for searchFile in os.listdir(dirName):

    if fnmatch.fnmatch(searchFile, "*COPY_TaxRollData.txt"):
        Search_LogFile("~-~-~", "Acquiring Updated Data from PVA")
        Search_LogFile(" - DELETING PREVIOUSLY DOWNLOADED PVA DATA", "")
        Search_LogFile(" - DOWNLOADING THE LATEST SNAPSHOT OF PUBLIC INQUIRY DATABASE", "")
        Search_LogFile(" - ARCHIVING ALL DOWNLOADED FILES", "")
        Search_LogFile(" - RECONCILING NEW DOWNLOAD WITH PRIOR DATA", "")
        Search_LogFile(" - DISCONNECTING W: DRIVE", "")
        Search_LogFile(" - EXECUTING FME MODEL TO OVERWRITE PVA DATA IN SDE", "")

    if fnmatch.fnmatch(searchFile, "*INTEGRATE_TaxRollData.txt"):
        Search_LogFile("~-~-~", "Integrating Updated Data from PVA into the SDE Production EGDB")
        Search_LogFile("Reading table/feature class '", "")
        Search_LogFile("Opened Shape File '", "")
        Search_LogFile("CSV reader: Opening dataset '", "")
        Search_LogFile("|ERROR |", "")
        #Search_LogFile("|WARN  |", "")
        Search_LogFile("Features Written Summary", "")


问:
Android Firebase: No matching client found for the package
I had borrowed an android project from one of my friends and after importing, I got an error that the The application was configured for some other audience - appId doesn't match the one in google-services.json. After that, I knew I had to change the package name of java files and reconnect firebase so, I did. I keep getting an error:

```<code>Error:Execution failed for task ':app:processDebugGoogleServices'.
> No matching client found for package name 'com.***.***.chitchat'
</code>```

I have the same package name in AndroidManifest.xml, build.gradle and google-services.json. Strange is that everyone got their problem solved after making the required changes. Mine still throws an error. Why is that?

答:
The package names of your Java code actually has nothing to do with that error.  It's the application id of your entire app that you need to look at (in your build.gradle).

The google-services plugin looks at your application id and tries to match it against a package name that it fines in your google-services.json file.  If there is no match, it will give you that error.  To resolve this, either change your application id in build.gradle to match the package name that was set up for your app in the Firebase console, or create a new app in the console with a package name that matches your application id.

If you borrowed a project from a friend, I suspect that you also got a hold of their google-services.json, which you typically don't share or check into source control, unless everyone has full access to the same project.  If you're working in your own project, you'll need to set that up in the console and generate a new google-services.json to match your app.

Body:
I had borrowed an android project from one of my friends and after importing, I got an error that the The application was configured for some other audience - appId doesn't match the one in google-services.json. After that, I knew I had to change the package name of java files and reconnect firebase so, I did. I keep getting an error:

Error:Execution failed for task ':app:processDebugGoogleServices'.
> No matching client found for package name 'com.***.***.chitchat'

I have the same package name in AndroidManifest.xml, build.gradle and google-services.json. Strange is that everyone got their problem solved after making the required changes. Mine still throws an error. Why is that?