问:
C# - Directory Search not returning results for parent directory
I have this file count function that is not returning results from my parent directory. It does return results of all sub directories. During my debugging I def see the parent directory being passed as my Directory.GetDirectories(sDir) but once it hits  Directory.GetFiles(d) it already changed to the sub directories. I am banging my head against a wall on this one. Clearly, it must be my foreach loop but I am not seeing it.

The file structure I am passing is:

C:\Users\xxxxx\Desktop\Temp Logs

but it has three sub directories:

C:\Users\xxxxx\Desktop\Temp Logs\sub1

C:\Users\xxxxx\Desktop\Temp Logs\sub2

C:\Users\xxxxx\Desktop\Temp Logs\sub3

Does anyone see my error?

```<code>     private static string fileCount(string sDir, string sfileType)
    {
        int count = 0;
        string extension;
        foreach (string d in Directory.GetDirectories(sDir))
        {
            foreach (string file in Directory.GetFiles(d))
            {
                extension = Path.GetExtension(file);
                if (extension.ToUpper().Equals(sfileType.ToUpper()))
                {
                    TimeSpan fileAge = DateTime.Now - File.GetLastWriteTime(file);
                    if (fileAge.Days > int.Parse(ConfigurationManager.AppSettings["numberOfDays"]))
                    {
                        count++;
                    }
                }
            }
        }
        return count.ToString();
    }
</code>```

答:
You need another loop for the parent directory but outside you current loop</p>

```<code>foreach (string file in Directory.GetFiles(parent_path))
        {
            extension = Path.GetExtension(file);
            if (extension.ToUpper().Equals(sfileType.ToUpper()))
            {
                TimeSpan fileAge = DateTime.Now - File.GetLastWriteTime(file);
                if (fileAge.Days > int.Parse(ConfigurationManager.AppSettings["numberOfDays"]))
                {
                    count++;
                }
            }
        }
</code>```

Body:
I have this file count function that is not returning results from my parent directory. It does return results of all sub directories. During my debugging I def see the parent directory being passed as my Directory.GetDirectories(sDir) but once it hits  Directory.GetFiles(d) it already changed to the sub directories. I am banging my head against a wall on this one. Clearly, it must be my foreach loop but I am not seeing it.

The file structure I am passing is:

C:\Users\xxxxx\Desktop\Temp Logs

but it has three sub directories:

C:\Users\xxxxx\Desktop\Temp Logs\sub1

C:\Users\xxxxx\Desktop\Temp Logs\sub2

C:\Users\xxxxx\Desktop\Temp Logs\sub3

Does anyone see my error?

     private static string fileCount(string sDir, string sfileType)
    {
        int count = 0;
        string extension;
        foreach (string d in Directory.GetDirectories(sDir))
        {
            foreach (string file in Directory.GetFiles(d))
            {
                extension = Path.GetExtension(file);
                if (extension.ToUpper().Equals(sfileType.ToUpper()))
                {
                    TimeSpan fileAge = DateTime.Now - File.GetLastWriteTime(file);
                    if (fileAge.Days > int.Parse(ConfigurationManager.AppSettings["numberOfDays"]))
                    {
                        count++;
                    }
                }
            }
        }
        return count.ToString();
    }

Body:
You need another loop for the parent directory but outside you current loop

foreach (string file in Directory.GetFiles(parent_path))
        {
            extension = Path.GetExtension(file);
            if (extension.ToUpper().Equals(sfileType.ToUpper()))
            {
                TimeSpan fileAge = DateTime.Now - File.GetLastWriteTime(file);
                if (fileAge.Days > int.Parse(ConfigurationManager.AppSettings["numberOfDays"]))
                {
                    count++;
                }
            }
        }


来源: stackexchange

问:
Xamarin, Firebase: " Default FirebaseApp is not initialized in this process" - though initializeApp() is called?
Im starting to go crazy over that line:

Java.Lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.TalkAboutTv.TalkAboutTv. Make sure to call FirebaseApp.initializeApp(Context) first.

I have no clue what is causing that. I AM calling FirebaseApp.IntApp(this) and my package name is matching ... Why is it not working?

```<code>protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);
}

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView (Resource.Layout.Main);

    firebase = new FirebaseClient("2131099704");
    Firebase.FirebaseApp.InitializeApp(this);

    FirebaseDatabase.Instance.GetReference("chats").AddValueEventListener(this);

    fab = FindViewById<Button>(Resource.Id.fab);
    edtChat = FindViewById<EditText>(Resource.Id.input);
    lstChat = FindViewById<ListView>(Resource.Id.list_of_messages);

    fab.Click += delegate
    {

        PostMessage();
    };

    if (FirebaseAuth.Instance.CurrentUser == null)
        StartActivityForResult(new Android.Content.Intent(this, typeof(SignIn)), MyResultCode);
    else
    {
        Toast.MakeText(this, "Welcome " + FirebaseAuth.Instance.CurrentUser.Email, ToastLength.Short).Show();
        DisplayChatMessage();
    }
}

private async void PostMessage()
{
    var items = await firebase.Child("chats").PostAsync(new MessageContent(FirebaseAuth.Instance.CurrentUser.Email, edtChat.Text));
    edtChat.Text = "";
}

public void OnCancelled(DatabaseError error)
{

}

public void OnDataChange(DataSnapshot snapshot)
{
    DisplayChatMessage();
}

private async void DisplayChatMessage()
{
    lstMessage.Clear();
    var items = await firebase.Child("chats")
        .OnceAsync<MessageContent>();

    foreach (var item in items)
        lstMessage.Add(item.Object);
    ListViewAdapter adapter = new ListViewAdapter(this, lstMessage);
    lstChat.Adapter = adapter;
    }
}
</code>```

}

答:
Try to initialize firebase within your Application class (OnCreate method).
But first download the google-services.json file from the project console, and make sure it has the "GoogleServicesJson" value as Build Action.</p>

ContentLicense: CC BY-SA 3.0

Body:
Im starting to go crazy over that line:

Java.Lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.TalkAboutTv.TalkAboutTv. Make sure to call FirebaseApp.initializeApp(Context) first.

I have no clue what is causing that. I AM calling FirebaseApp.IntApp(this) and my package name is matching ... Why is it not working?

protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);
}

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView (Resource.Layout.Main);

    firebase = new FirebaseClient("2131099704");
    Firebase.FirebaseApp.InitializeApp(this);

    FirebaseDatabase.Instance.GetReference("chats").AddValueEventListener(this);

    fab = FindViewById<Button>(Resource.Id.fab);
    edtChat = FindViewById<EditText>(Resource.Id.input);
    lstChat = FindViewById<ListView>(Resource.Id.list_of_messages);

    fab.Click += delegate
    {

        PostMessage();
    };

    if (FirebaseAuth.Instance.CurrentUser == null)
        StartActivityForResult(new Android.Content.Intent(this, typeof(SignIn)), MyResultCode);
    else
    {
        Toast.MakeText(this, "Welcome " + FirebaseAuth.Instance.CurrentUser.Email, ToastLength.Short).Show();
        DisplayChatMessage();
    }
}

private async void PostMessage()
{
    var items = await firebase.Child("chats").PostAsync(new MessageContent(FirebaseAuth.Instance.CurrentUser.Email, edtChat.Text));
    edtChat.Text = "";
}

public void OnCancelled(DatabaseError error)
{

}

public void OnDataChange(DataSnapshot snapshot)
{
    DisplayChatMessage();
}

private async void DisplayChatMessage()
{
    lstMessage.Clear();
    var items = await firebase.Child("chats")
        .OnceAsync<MessageContent>();

    foreach (var item in items)
        lstMessage.Add(item.Object);
    ListViewAdapter adapter = new ListViewAdapter(this, lstMessage);
    lstChat.Adapter = adapter;
    }
}

}


问:
Deleting content of every string after first empty space
How can I delete everything after first empty space in a string which user selects? I was reading this how to remove some words from a string in java. Can this help me in my case?</p>

答:
Assuming that there is no space in the beginning of the string.
Follow these steps-

Split the string at space. It will create an array.

Get the first element of that array.

Hope this helps.

```<code>str = "Example string"
String[] _arr = str.split("\\s");
String word = _arr[0];
</code>```

You need to consider multiple white spaces and space in the beginning before considering the above code.

I am not native to JAVA Programming but have an idea that it has split function for string.
And the reference you cited in the question is bit complex, while you can achieve the desired thing very easily.

P.S. In future if you make a mind to get two words or three, splitting method is better (assuming you have already dealt with multiple white-spaces) else substring is better.

Body:
Assuming that there is no space in the beginning of the string.
Follow these steps-

Split the string at space. It will create an array.

Get the first element of that array.

Hope this helps.

str = "Example string"
String[] _arr = str.split("\\s");
String word = _arr[0];

You need to consider multiple white spaces and space in the beginning before considering the above code.

I am not native to JAVA Programming but have an idea that it has split function for string.
And the reference you cited in the question is bit complex, while you can achieve the desired thing very easily.

P.S. In future if you make a mind to get two words or three, splitting method is better (assuming you have already dealt with multiple white-spaces) else substring is better.


问:
who do you prefer ObjectSet or CreateQuery in EF 4?
i have been coding below. But i find another method secand part . which one is more preferable than other. what is the differece? whic one has more performance than other?

```<code>public T Single(Func<T, bool> predicate)
{
    return _context.CreateQuery<T>("[" + typeof(T).Name + "]").Where(predicate).Single();
}
</code>```

ANOTHER USAGE

```<code>public T Single(Func<T, bool> predicate)
{
    return _objectSet.Single<T>(predicate);
}
</code>```

which one is more prefer than other?

答:
They are completely different things, with completely different purposes.

ObjectSet<T> is a strongly-typed property which allows you to run LINQ queries against the conceptual model.  (ctx.Apples.Where(x => x.Color == "Red")).

CreateQuery<T> is a method which allows you to run native SQL against the physical model. Also known as EntitySQL. (SELECT * FROM dbo.Apples WHERE Color = "Red")

ObjectSet<T> is more type-safe, because entities on the model are exposed as properties on the ObjectSet, which is typed via generics. CreateQuery<T> on the other hand is also typed to the entity, but the actual query is EntitySQL, a string parameter - meaning possible runtime errors can occur because of typos. The only runtime errors you will get with ObjectSet<T> is CLR specific errors (null references, etc) or SQL specific errors (foreign key constraint, PK violation, etc).

As @adrift also mentions, IObjectSet<T> is mockable, however of course you could create a proxy/wrapper class for CreateQuery<T> and mock that.

I have used Entity Framework 4.0 for the past few months and have not found a single usage for CreateQuery<T>. I either use ObjectSet<T> or Stored Procedures.

ContentLicense: CC BY-SA 2.5

Body:
i have been coding below. But i find another method secand part . which one is more preferable than other. what is the differece? whic one has more performance than other?

public T Single(Func<T, bool> predicate)
{
    return _context.CreateQuery<T>("[" + typeof(T).Name + "]").Where(predicate).Single();
}

ANOTHER USAGE

public T Single(Func<T, bool> predicate)
{
    return _objectSet.Single<T>(predicate);
}

which one is more prefer than other?


问:
Using a variable outside of a loop, value changes within the loop
I am relatively new to programming and I have come across an issue whilst trying to write a function that utilizes loops. The function should work as such:

The array Data consists of a 51X2 set of doubles, which are all used in the program through the initial for loop, the a variable and the b variable. The X and Y variables are both set to the minimum values of the array.

Using the a and X variables as an example, the X value is compared to a and incremented until it surpasses a. The number of loop iterations are tracked by the c variable. This c variable is then used in the Graph array. The same procedure occurs for the b and Y variables. This process is repeated for every value of S to analyse all data points from the Data array.

The issue I'm having is that the c and d variables don't change relative to the changes inside the loops. The variables will not change from their initialized value. I am looking to find a solution that allows for the c and d variables to change in relation to the number of iterations of the for loop.

The relevant function code can be seen below:

```<code>void Data_Plot(double Data[51][2], char Graph[44][56])
{
    int N = 50;
    int S,q,r;
    int c = 0;
    int d = 0;
    double a = Data[S][0];
    double b = Data[S][1];
    double X = Data[0][0];
    double Y = Data[0][1];
    for (S=0;S<N;S++)
    {
        for(X;X<a;X+=0.1428571429)
        {
            c++;
        }
        for(Y;Y<b;Y+=2)
        {
            d++;
        }

        Graph[c][d] = '*';
    }
</code>```

I am aware that my code is very unoptimized and messy, but I can fix those issues up with future projects after I have finished this one.

Edit: I would like to note that I have attempted this with c and d being set to other values, as well as being left as NULL. The same result occurred regardless of the variable initialization.

答:
Since a and b depend on S, which you change during the for loop, you need to move those variables inside the loop.

```<code>void Data_Plot(double Data[51][2], char Graph[44][56])
{
    int N = 50;
    int S,q,r;
    int c = 0;
    int d = 0;
    double X = Data[0][0];
    double Y = Data[0][1];
    for (S=0;S<N;S++)
    {
        double a = Data[S][0];
        for(X;X<a;X+=0.1428571429)
        {
            c++;
        }

        double b = Data[S][1];
        for(Y;Y<b;Y+=2)
        {
            d++;
        }

        Graph[c][d] = '*';
    }
</code>```

Body:
I am relatively new to programming and I have come across an issue whilst trying to write a function that utilizes loops. The function should work as such:

The array Data consists of a 51X2 set of doubles, which are all used in the program through the initial for loop, the a variable and the b variable. The X and Y variables are both set to the minimum values of the array.

Using the a and X variables as an example, the X value is compared to a and incremented until it surpasses a. The number of loop iterations are tracked by the c variable. This c variable is then used in the Graph array. The same procedure occurs for the b and Y variables. This process is repeated for every value of S to analyse all data points from the Data array.

The issue I'm having is that the c and d variables don't change relative to the changes inside the loops. The variables will not change from their initialized value. I am looking to find a solution that allows for the c and d variables to change in relation to the number of iterations of the for loop.

The relevant function code can be seen below:

void Data_Plot(double Data[51][2], char Graph[44][56])
{
    int N = 50;
    int S,q,r;
    int c = 0;
    int d = 0;
    double a = Data[S][0];
    double b = Data[S][1];
    double X = Data[0][0];
    double Y = Data[0][1];
    for (S=0;S<N;S++)
    {
        for(X;X<a;X+=0.1428571429)
        {
            c++;
        }
        for(Y;Y<b;Y+=2)
        {
            d++;
        }

        Graph[c][d] = '*';
    }

I am aware that my code is very unoptimized and messy, but I can fix those issues up with future projects after I have finished this one.

Edit: I would like to note that I have attempted this with c and d being set to other values, as well as being left as NULL. The same result occurred regardless of the variable initialization.

Body:
Since a and b depend on S, which you change during the for loop, you need to move those variables inside the loop.

void Data_Plot(double Data[51][2], char Graph[44][56])
{
    int N = 50;
    int S,q,r;
    int c = 0;
    int d = 0;
    double X = Data[0][0];
    double Y = Data[0][1];
    for (S=0;S<N;S++)
    {
        double a = Data[S][0];
        for(X;X<a;X+=0.1428571429)
        {
            c++;
        }

        double b = Data[S][1];
        for(Y;Y<b;Y+=2)
        {
            d++;
        }

        Graph[c][d] = '*';
    }


问:
PHP check whether property exists in object or class
I understand PHP does not have a pure object variable, but I want to check whether a property is in the given object or class.

```<code>$ob = (object) array('a' => 1, 'b' => 12);
</code>```

or

```<code>$ob = new stdClass;
$ob->a = 1;
$ob->b = 2;
</code>```

In JS, I can write this to check if variable a exists in an object:

```<code>if ('a' in ob)
</code>```

In PHP, can anything like this be done?

答:
Neither isset or property_exists work for me.

isset returns false if the property exists but is NULL.

property_exists returns true if the property is part of the object's class definition, even if it has been unset.

I ended up going with:

```<code>    $exists = array_key_exists($property, get_object_vars($obj));
</code>```

Example:

```<code>    class Foo {
        public $bar;

        function __construct() {
            $property = 'bar';

            isset($this->$property); // FALSE
            property_exists($this, $property); // TRUE
            array_key_exists($property, get_object_vars($this)); // TRUE

            unset($this->$property);

            isset($this->$property); // FALSE
            property_exists($this, $property); // TRUE
            array_key_exists($property, get_object_vars($this)); // FALSE

            $this->$property = 'baz';

            isset($this->$property); // TRUE
            property_exists($this, $property); // TRUE
            array_key_exists($property, get_object_vars($this));  // TRUE
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I understand PHP does not have a pure object variable, but I want to check whether a property is in the given object or class.

$ob = (object) array('a' => 1, 'b' => 12);

or

$ob = new stdClass;
$ob->a = 1;
$ob->b = 2;

In JS, I can write this to check if variable a exists in an object:

if ('a' in ob)

In PHP, can anything like this be done?

Body:
Neither isset or property_exists work for me.

isset returns false if the property exists but is NULL.

property_exists returns true if the property is part of the object's class definition, even if it has been unset.

I ended up going with:

    $exists = array_key_exists($property, get_object_vars($obj));

Example:

    class Foo {
        public $bar;

        function __construct() {
            $property = 'bar';

            isset($this->$property); // FALSE
            property_exists($this, $property); // TRUE
            array_key_exists($property, get_object_vars($this)); // TRUE

            unset($this->$property);

            isset($this->$property); // FALSE
            property_exists($this, $property); // TRUE
            array_key_exists($property, get_object_vars($this)); // FALSE

            $this->$property = 'baz';

            isset($this->$property); // TRUE
            property_exists($this, $property); // TRUE
            array_key_exists($property, get_object_vars($this));  // TRUE
        }
    }


问:
Local Maven Repo have no Symbols
I created an local Maven Repo and deploy a own lib there:
with:

```<code>mvn clean package install deploy
</code>```

on:

    http://maven.apache.org/xsd/maven-4.0.0.xsd">
        4.0.0

```<code>    <groupId>de.example</groupId>
    <artifactId>example-lib</artifactId>
    <version>0.0.1</version>
    <packaging>jar</packaging>
<name>example-lib</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<distributionManagement>
    <repository>
        <id>example.repo</id>
        <name>example internal mvn repository</name>
        <url>file://${project.basedir}/../mvn-repo</url>
    </repository>
</distributionManagement>
</code>```

Now Another project consumes it with:

```<code>    <repositories>
        <repository>
            <id>example.repo</id>
            <url>file://${project.basedir}/../mvn-repo</url>
        </repository>
    </repositories>
...
        <dependency>
            <groupId>de.example</groupId>
            <artifactId>example-lib</artifactId>
            <version>0.0.1</version>
        </dependency>
</code>```

...

but upon compiling the project all symbols are missing from the lib (but the dependency IS resolved, and the .jar file is there)

```<code>[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /C:/Users/gregor/Documents/dev/repo/example/core/src/main/java/de/example/core/CoreApplication.java:[11,31] package de.example.examplelib does not exist
[ERROR] /C:/Users/gregor/Documents/dev/repo/example/core/src/main/java/de/example/core/DbExampleService.java:[11,42] package de.example.examplelib.db.example does not exist
[ERROR] /C:/Users/gregor/Documents/dev/repo/example/core/src/main/java/de/example/core/DbExampleService.java:[12,42] package de.example.examplelib.db.example does not exist
[ERROR] /C:/Users/gregor/Documents/dev/repo/example/core/src/main/java/de/example/core/DbExampleService.java:[19,17] cannot find symbol
  symbol:   class UserRepository
  location: class de.example.core.DbExampleService
[ERROR] /C:/Users/gregor/Documents/dev/repo/example/core/src/main/java/de/example/core/DbExampleService.java:[35,39] cannot find symbol
  symbol:   class User
  location: class de.example.core.DbExampleService
</code>```

I have searched for the last 4 hours, maybe I just miss a little basic thing??
Open for hints. Thanks in advance.

答:
When Maven cannot find a dependency, it explicitly says so.
Your problem is of a different nature; it appears that your jar might be actually empty (i.e. you have the right dependency; it just isn't packaged right).

Maven repository is just a simple collection of files; you can just go in it and open up your jar; I suggest to check your mvn-repo to see if the jar you're including contains the classes you expect to contain.

In case I'm right (i.e. your jar isn't packaged right) look at the default maven directory structure etc (Maven is used to pick up java files by default from src/main/java; perhaps you use a different source folder and you're not telling this to Maven?)

Edit 1 Summing up the discussion in the comments and other answer :

So far, we know that your jar is packaged incorrectly. Well, it is packaged incorrectly for the purpose of being consumed by other projects. Therefore, the error that you're seeing is normal. Punctually, the error is because you're referring to the class
de/example/examplelib/db/example/User.class for example, but this class is located in the wrong place (the de package should be in the root of the jar and not in the BOOT-INF/classes folder).

Most likely, this happens because the pom.xml file that you're using to package your library is inheriting from a spring-boot parent (or you have some other config in it that you haven't shown).
Therefore, in the light of these things, you need to re-state your problem:

Do you want your library-jar to be a spring-boot executable jar? If yes, then I can't help you because I don't know very much spring-boot, and I don't know if you can have a spring-boot jar which is both executable and library. If no, then you need to remove spring-boot as a parent and re-package it.

Did you intended your second project to be a spring-boot executable? If yes, then you need to add the parent that you have in your lib project.

Title: Local Maven Repo have no Symbols

Body:
I created an local Maven Repo and deploy a own lib there:
with:

mvn clean package install deploy

on:

    http://maven.apache.org/xsd/maven-4.0.0.xsd">
        4.0.0

    <groupId>de.example</groupId>
    <artifactId>example-lib</artifactId>
    <version>0.0.1</version>
    <packaging>jar</packaging>
<name>example-lib</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<distributionManagement>
    <repository>
        <id>example.repo</id>
        <name>example internal mvn repository</name>
        <url>file://${project.basedir}/../mvn-repo</url>
    </repository>
</distributionManagement>

Now Another project consumes it with:

    <repositories>
        <repository>
            <id>example.repo</id>
            <url>file://${project.basedir}/../mvn-repo</url>
        </repository>
    </repositories>
...
        <dependency>
            <groupId>de.example</groupId>
            <artifactId>example-lib</artifactId>
            <version>0.0.1</version>
        </dependency>

...

but upon compiling the project all symbols are missing from the lib (but the dependency IS resolved, and the .jar file is there)

[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /C:/Users/gregor/Documents/dev/repo/example/core/src/main/java/de/example/core/CoreApplication.java:[11,31] package de.example.examplelib does not exist
[ERROR] /C:/Users/gregor/Documents/dev/repo/example/core/src/main/java/de/example/core/DbExampleService.java:[11,42] package de.example.examplelib.db.example does not exist
[ERROR] /C:/Users/gregor/Documents/dev/repo/example/core/src/main/java/de/example/core/DbExampleService.java:[12,42] package de.example.examplelib.db.example does not exist
[ERROR] /C:/Users/gregor/Documents/dev/repo/example/core/src/main/java/de/example/core/DbExampleService.java:[19,17] cannot find symbol
  symbol:   class UserRepository
  location: class de.example.core.DbExampleService
[ERROR] /C:/Users/gregor/Documents/dev/repo/example/core/src/main/java/de/example/core/DbExampleService.java:[35,39] cannot find symbol
  symbol:   class User
  location: class de.example.core.DbExampleService

I have searched for the last 4 hours, maybe I just miss a little basic thing??
Open for hints. Thanks in advance.


答:
```<code>// Taking 'str' as your string
// To remove the first space(s) of the string,
str = str.trim();
int index = str.indexOf(" ");
String word = str.substring(0, index);
</code>```

This is just one method of many.

```<code>str = str.replaceAll("\\s+", " "); // This replaces one or more spaces with one space
String[] words = str.split("\\s");
String first = words[0];
</code>```

Title: Deleting content of every string after first empty space

Body: How can I delete everything after first empty space in a string which user selects? I was reading this how to remove some words from a string in java. Can this help me in my case?

Body:
// Taking 'str' as your string
// To remove the first space(s) of the string,
str = str.trim();
int index = str.indexOf(" ");
String word = str.substring(0, index);

This is just one method of many.

str = str.replaceAll("\\s+", " "); // This replaces one or more spaces with one space
String[] words = str.split("\\s");
String first = words[0];


问:
Django base template (using bootstrap3) overwrites index.html completely
I've created a base.html file where I want my bootstrap3 navbar and footer to live. These will be used on every page of my site.

However, the base.html & corresponding css file that goes with it seems to overwrite all of the index.html file and specific css for that view.

I've read the django documentation and closely-related questions like this one on overriding the base template. Other website have tutorials but still aren't making sense. I believe I am misunderstanding something fundamental.

Here is the code:

base.html:

```<code><!DOCTYPE html> {% load staticfiles %}
<html>
<head>
    <link rel="stylesheet" href="/static/css/main.css" />
    <!-- jquery -->
    <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <!-- [/] jquery -->
</head>
<body>
    {# Load the tag library #} {% load bootstrap3 %} {# Load CSS and JavaScript #} {% bootstrap_css %} {% bootstrap_javascript %} {# Display django.contrib.messages as Bootstrap alerts #} {% bootstrap_messages %} {# Navigation Menu #}
    <header>
        <nav class="navbar navbar-default">
            ----->Navbar code here<-----
        </nav>
    </header>
    <footer>
        <div class="container">
            <p>Good stuff is here in the footer</p>
        </div>
    </footer>
</body>
</html>
</code>```

index.html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta name="description" content="Online community">
    <meta name="author" content="My name">
    <title>Planet</title>
    <link href="/static/css/homepage.css" rel="stylesheet">
</head>
<body>
    {% extends 'base.html' %}
    {% block content %}
    <p>WORDS WORDS WORDS WORDS</p>
    <h1>HERE ARE SOME BIG WORDS ON THE MAIN PAGE</h1>
{% endblock content %}
</body>
</html>
</code>```

I can include the css files for index.html & base.html if it helps but I believe the problem lies somewhere with my understanding of extending the base template and how to use {% block content %}. I can remove that block and it doesn't seem to matter either.

Thank you for any insights you can provide.

答:
It looks like you're trying to use template extending

In simplicity, you should structure your files like so:

base.html

```<code><head> </head>

<body>
{% block content %}
    index.html will be loaded and everything within
    the block named "content" will display here
{% endblock %}
</body>

<footer> </footer>
</code>```

index.html

```<code>{% extends 'base.html' %}

{% block content %}
    Everything within this block, named "content", will
    be inserted into the "content" block of base.html
{% endblock %}
</code>```

Your combined HTML would look like this once it passes through Django's templating system:

```<code><head> </head>
<body>
    Everything within this block, named "content", will
    be inserted into the "content" block of base.html
</body>
<footer> </footer>
</code>```

Your view will need to return the rendered index.html.  This system is designed such that you can continue to use base.html with other templates to maintain a standard structure or page design, while modifying only the content on those pages with different versions of index.html.

Body:
I've created a base.html file where I want my bootstrap3 navbar and footer to live. These will be used on every page of my site.

However, the base.html & corresponding css file that goes with it seems to overwrite all of the index.html file and specific css for that view.

I've read the django documentation and closely-related questions like this one on overriding the base template. Other website have tutorials but still aren't making sense. I believe I am misunderstanding something fundamental.

Here is the code:

base.html:

<!DOCTYPE html> {% load staticfiles %}

    <link rel="stylesheet" href="/static/css/main.css" />

    {# Load the tag library #} {% load bootstrap3 %} {# Load CSS and JavaScript #} {% bootstrap_css %} {% bootstrap_javascript %} {# Display django.contrib.messages as Bootstrap alerts #} {% bootstrap_messages %} {# Navigation Menu #}

            ----->Navbar code here<-----

Good stuff is here in the footer

index.html:

<!DOCTYPE html>

    <meta name="description" content="Online community">
    <meta name="author" content="My name">
    <title>Planet</title>
    <link href="/static/css/homepage.css" rel="stylesheet">

    {% extends 'base.html' %}
    {% block content %}

WORDS WORDS WORDS WORDS

HERE ARE SOME BIG WORDS ON THE MAIN PAGE

{% endblock content %}

I can include the css files for index.html & base.html if it helps but I believe the problem lies somewhere with my understanding of extending the base template and how to use {% block content %}. I can remove that block and it doesn't seem to matter either.

Thank you for any insights you can provide.

Body:
It looks like you're trying to use template extending

In simplicity, you should structure your files like so:

base.html

<head> </head>

<body>
{% block content %}
    index.html will be loaded and everything within
    the block named "content" will display here
{% endblock %}
</body>

<footer> </footer>

index.html

{% extends 'base.html' %}

{% block content %}
    Everything within this block, named "content", will
    be inserted into the "content" block of base.html
{% endblock %}

Your combined HTML would look like this once it passes through Django's templating system:

<head> </head>
<body>
    Everything within this block, named "content", will
    be inserted into the "content" block of base.html
</body>
<footer> </footer>

Your view will need to return the rendered index.html.  This system is designed such that you can continue to use base.html with other templates to maintain a standard structure or page design, while modifying only the content on those pages with different versions of index.html.


问:
Binary Trees -- Tracing through code
Given the binary tree shown below, determine the order in which the nodes of the binary tree shown below are visited assuming the function A(root) is invoked.  Assume that the tree nodes and pointers are defined as shown.  Assume that root is a pointer to the node containing 60.
My answer to this problem is given below. Is it correct? What did I do wrong?

```<code>                                   60
                                 /    \
                                30     90
                               /  \   /
                              5   38  77
                               \  /  / \
                               8 32 62  88

struct treeNode{
  int data;
  struct treeNode *left, *right:
  {

struct treeNode *tree_ptr;

void A(struct treeNode *node_ptr){
    if (node_ptr != NULL){
    printf(“%d ,”,node_ptr->data);
    B(node_ptr->left);
    B(node_ptr->right);
   }
}

void B(struct treeNode *node_ptr){
    if (node_ptr != NULL) {
    A(node_ptr->left);
    printf(“%d ,”,node_ptr->data);
    A(node_ptr->right);
   }
 }
</code>```

Answer:
In void A it says to first print node_ptr-> data so 60 gets printed
Then the function calls B(node_ptr->left) then within B, A gets called (node_ptr->left) then you print that data which is 5. And then A(node_ptr->right) gets called go back up to A, print that data so 8 gets printed. Now Im not so sure what to do next but I get logically it would make sense to print 30 but Im not sure how the ptr gets from 8 to 30. And then if you continue in the same pattern 38 gets printed and 32 gets printed.
For the right subtree...
90 77 62 88

答:
For starters, your code has a bunch of errors in it. I'm guessing it should be more like this:

```<code>struct treeNode{
  int data;
  struct treeNode *left, *right;
}

treeNode *tree_ptr;

void A(treeNode *node_ptr){
    if (node_ptr != NULL){  /// this could be just if(node_ptr)
        printf(“%d ,”,node_ptr->data);
        B(node_ptr->left);
        B(node_ptr->right);
    }
}

void B(treeNode *node_ptr){
    if (node_ptr != NULL) {
        A(node_ptr->left);
        printf(“%d ,”,node_ptr->data);
        A(node_ptr->right);
    }
}
</code>```

You're also mixing two different traversal algorithms. A() is pre-order, B() is in-order. A() and B() should be calling themselves, not each other. (Yet another reason to use real variable/function names instead of A, B, and such.)

Title: Binary Trees -- Tracing through code

Body:
Given the binary tree shown below, determine the order in which the nodes of the binary tree shown below are visited assuming the function A(root) is invoked.  Assume that the tree nodes and pointers are defined as shown.  Assume that root is a pointer to the node containing 60.
My answer to this problem is given below. Is it correct? What did I do wrong?

                                   60
                                 /    \
                                30     90
                               /  \   /
                              5   38  77
                               \  /  / \
                               8 32 62  88

struct treeNode{
  int data;
  struct treeNode *left, *right:
  {

struct treeNode *tree_ptr;

void A(struct treeNode *node_ptr){
    if (node_ptr != NULL){
    printf(“%d ,”,node_ptr->data);
    B(node_ptr->left);
    B(node_ptr->right);
   }
}

void B(struct treeNode *node_ptr){
    if (node_ptr != NULL) {
    A(node_ptr->left);
    printf(“%d ,”,node_ptr->data);
    A(node_ptr->right);
   }
 }

Answer:
In void A it says to first print node_ptr-> data so 60 gets printed
Then the function calls B(node_ptr->left) then within B, A gets called (node_ptr->left) then you print that data which is 5. And then A(node_ptr->right) gets called go back up to A, print that data so 8 gets printed. Now Im not so sure what to do next but I get logically it would make sense to print 30 but Im not sure how the ptr gets from 8 to 30. And then if you continue in the same pattern 38 gets printed and 32 gets printed.
For the right subtree...
90 77 62 88

Body:
For starters, your code has a bunch of errors in it. I'm guessing it should be more like this:

struct treeNode{
  int data;
  struct treeNode *left, *right;
}

treeNode *tree_ptr;

void A(treeNode *node_ptr){
    if (node_ptr != NULL){  /// this could be just if(node_ptr)
        printf(“%d ,”,node_ptr->data);
        B(node_ptr->left);
        B(node_ptr->right);
    }
}

void B(treeNode *node_ptr){
    if (node_ptr != NULL) {
        A(node_ptr->left);
        printf(“%d ,”,node_ptr->data);
        A(node_ptr->right);
    }
}

You're also mixing two different traversal algorithms. A() is pre-order, B() is in-order. A() and B() should be calling themselves, not each other. (Yet another reason to use real variable/function names instead of A, B, and such.)


问:
Jackson: parse ZonedDateTime with timezone id
With Spring MVC (Spring boot) I can deserialize ZonedDateTime from

```<code>2016-07-26T05:30:47+01:00
</code>```

but not from

```<code>2016-07-26T05:30:47+01:00 Europe/Paris
</code>```

How can I explicitly add timezone and still be able to deserialize it?

答:
You can specify a pattern with an optional section (delimited by []), to indicate that some field is optional, and add this to the respective field using the @JsonFormat annotation.

For example, take this class:

```<code>public class OptionalTimeZoneTest {

    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssXXX[ VV]")
    private ZonedDateTime date;

    // getter and setter
}
</code>```

Note the last part ([ VV]): the pattern inside [] is an optional section, so the parser tries to parse it, if present. And the pattern VV is the zone id (or timezone's name; for more details, take a look at the javadoc)

With this, both formats can be read:

```<code>ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
// add this to preserve the same offset (don't convert to UTC)
mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);

// without timezone
String json = "{ \"date\": \"2016-07-26T05:30:47+01:00\" }";
OptionalTimeZoneTest value = mapper.readValue(json, OptionalTimeZoneTest.class);
System.out.println(value.getDate()); // 2016-07-26T05:30:47+01:00

// with timezone
json = "{ \"date\": \"2016-07-26T05:30:47+01:00 Europe/Paris\" }";
value = mapper.readValue(json, OptionalTimeZoneTest.class);
System.out.println(value.getDate()); // 2016-07-26T05:30:47+02:00[Europe/Paris]
</code>```

The output is:

2016-07-26T05:30:47+01:00

  2016-07-26T05:30:47+02:00[Europe/Paris]

Note that in the first case the output is 2016-07-26T05:30:47+01:00 (because it doesn't have a timezone, so the +01:00 offset is applied).

But in the second case the output is 2016-07-26T05:30:47+02:00[Europe/Paris], because in Europe/Paris timezone, 26/07/2016 is summer-time (so the offset is +02:00). And the java.time API were implemented in a way that the timezone takes precedence when parsing such a String.

If you want all ZonedDateTime instances to be converted to UTC, you can remove this line:

```<code>mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);
</code>```

Without it, the dates will be converted to UTC, and the output will be:

2016-07-26T04:30:47Z[UTC]

  2016-07-26T03:30:47Z[UTC]

Body:
With Spring MVC (Spring boot) I can deserialize ZonedDateTime from

2016-07-26T05:30:47+01:00

but not from

2016-07-26T05:30:47+01:00 Europe/Paris

How can I explicitly add timezone and still be able to deserialize it?

Body:
You can specify a pattern with an optional section (delimited by []), to indicate that some field is optional, and add this to the respective field using the @JsonFormat annotation.

For example, take this class:

public class OptionalTimeZoneTest {

    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssXXX[ VV]")
    private ZonedDateTime date;

    // getter and setter
}

Note the last part ([ VV]): the pattern inside [] is an optional section, so the parser tries to parse it, if present. And the pattern VV is the zone id (or timezone's name; for more details, take a look at the javadoc)

With this, both formats can be read:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
// add this to preserve the same offset (don't convert to UTC)
mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);

// without timezone
String json = "{ \"date\": \"2016-07-26T05:30:47+01:00\" }";
OptionalTimeZoneTest value = mapper.readValue(json, OptionalTimeZoneTest.class);
System.out.println(value.getDate()); // 2016-07-26T05:30:47+01:00

// with timezone
json = "{ \"date\": \"2016-07-26T05:30:47+01:00 Europe/Paris\" }";
value = mapper.readValue(json, OptionalTimeZoneTest.class);
System.out.println(value.getDate()); // 2016-07-26T05:30:47+02:00[Europe/Paris]

The output is:

2016-07-26T05:30:47+01:00

  2016-07-26T05:30:47+02:00[Europe/Paris]

Note that in the first case the output is 2016-07-26T05:30:47+01:00 (because it doesn't have a timezone, so the +01:00 offset is applied).

But in the second case the output is 2016-07-26T05:30:47+02:00[Europe/Paris], because in Europe/Paris timezone, 26/07/2016 is summer-time (so the offset is +02:00). And the java.time API were implemented in a way that the timezone takes precedence when parsing such a String.

If you want all ZonedDateTime instances to be converted to UTC, you can remove this line:

mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);

Without it, the dates will be converted to UTC, and the output will be:

2016-07-26T04:30:47Z[UTC]

  2016-07-26T03:30:47Z[UTC]


问:
PowerQuery M text.contains with OR logical operator, and non-casesensitive matching?
I have a column with site domains like:

juegos.abc.com

blogs.abc.com

reddit.com

elpais.com

I want to crate a conditional column, that tells me if a domain is "media" or "community" based on a given list of domains.
I can do it manually from "create conditional column" in PowerBi but it will take me a million years.
Instead I've tried:

```<code>"Added Conditional Column18" = Table.AddColumn(#"Added Conditional Column17", "sitio.tipo", each if Text.Contains([Content.thread.site], "elpais OR elmundo OR elconfidencial OR abc OR lavanguardia OR 20minutos OR eldiario OR rtve OR elespanol OR eleconomista OR publico OR telecinco OR lasexta OR cuatro") then "medio" else "comunidad" )
</code>```

Not working.
Also tried:

```<code>"Added Conditional Column18" = Table.AddColumn(#"Added Conditional Column17", "sitio.tipo", each if Text.Contains([Content.thread.site], "elpais" OR "elmundo" OR "elconfidencial" OR "abc" OR "lavanguardia" OR "20minutos" OR "eldiario" OR "rtve" OR "elespanol" OR "eleconomista" OR "publico" OR "telecinco" OR "lasexta" OR "cuatro") then "medio" else "comunidad" )
</code>```

Same problem. I tried to find how to use operators withing the documentation, but it doesn't say much. Just what operators you can use, but I don't really know how to use it within this formula.

I also noticed with other conditional columns that it does precision matching, so, for example, if I specify "ABC" and the cell contains "abc" it won't match. I want it to be non-casesensitive, is it possible?

答:
Text.Contains takes a third argument which tells it how to do comparisons. If you want to ignore the case, use Comparer.OrdinalIgnoreCase, like Text.Contains([column], "Text", Comparer.OrdinalIgnoreCase).

That being said, Text.Contains will only check if the exact text value you pass into the second parameter is in the first parameter. If you want to check that the text value contains any value in a list, you'll need to use something like List.Contains, which also takes in a comparer as its third argument.

This should do what you want:

"Added Conditional Column18" = Table.AddColumn(#"Added Conditional Column17", "sitio.tipo", each if List.Contains({"elpais", "elmundo", "elconfidencial", "abc", "lavanguardia", "20minutos", "eldiario", "rtve", "elespanol", "eleconomista", "publico", "telecinco", "lasexta",  "cuatro"}, [Content.thread.site], Comparer.OrdinalIgnoreCase) then "medio" else "comunidad")

You can make this simpler if you have the list of domains in another table column. In that case replace the list in the first parameter with the reference to a column, like Query_Name[column_name].

Body:
I have a column with site domains like:

juegos.abc.com

blogs.abc.com

reddit.com

elpais.com

I want to crate a conditional column, that tells me if a domain is "media" or "community" based on a given list of domains.
I can do it manually from "create conditional column" in PowerBi but it will take me a million years.
Instead I've tried:

"Added Conditional Column18" = Table.AddColumn(#"Added Conditional Column17", "sitio.tipo", each if Text.Contains([Content.thread.site], "elpais OR elmundo OR elconfidencial OR abc OR lavanguardia OR 20minutos OR eldiario OR rtve OR elespanol OR eleconomista OR publico OR telecinco OR lasexta OR cuatro") then "medio" else "comunidad" )

Not working.
Also tried:

"Added Conditional Column18" = Table.AddColumn(#"Added Conditional Column17", "sitio.tipo", each if Text.Contains([Content.thread.site], "elpais" OR "elmundo" OR "elconfidencial" OR "abc" OR "lavanguardia" OR "20minutos" OR "eldiario" OR "rtve" OR "elespanol" OR "eleconomista" OR "publico" OR "telecinco" OR "lasexta" OR "cuatro") then "medio" else "comunidad" )

Same problem. I tried to find how to use operators withing the documentation, but it doesn't say much. Just what operators you can use, but I don't really know how to use it within this formula.

I also noticed with other conditional columns that it does precision matching, so, for example, if I specify "ABC" and the cell contains "abc" it won't match. I want it to be non-casesensitive, is it possible?


问:
Mocking Methods on an Instance Variable in Python
I'm trying to figure out how to properly Mock an instance variable which is an instance of another class that has methods used by the parent class.

Here's a simplified example of the problem domain:

```<code>import unittest
import mock

class Client:
    def action(self):
        return True

class Service:
    def __init__(self):
        self.client = Client()

class Handler:
    def __init__(self):
        self._service = Service()

    def example(self):
        return self._service.client.action()

class TestHandler(unittest.TestCase):

    @mock.patch('__main__.Handler._service')
    def test_example_client_action_false(self):
        """Test Example When Action is False"""
        handler = Handler()
        self.assertFalse(handler.example())

if __name__ == '__main__':
    unittest.main()
</code>```

The resulting test raises:

```<code>AttributeError: __main__.Handler does not have the attribute '_service'
</code>```

How do I properly mock the Service or Client such that action returns False for my test case?

答:
Can be done by mock the action return value</p>

```<code>class TestHandler(unittest.TestCase):

@mock.patch('__main__.Client.action')
def test_example_client_action_false(self, mock_client_action):
    """Test Example When Action is False"""
    mock_client_action.return_value = False
    handler = Handler()
    self.assertFalse(handler.example())
</code>```

Body:
I'm trying to figure out how to properly Mock an instance variable which is an instance of another class that has methods used by the parent class.

Here's a simplified example of the problem domain:

import unittest
import mock

class Client:
    def action(self):
        return True

class Service:
    def __init__(self):
        self.client = Client()

class Handler:
    def __init__(self):
        self._service = Service()

    def example(self):
        return self._service.client.action()

class TestHandler(unittest.TestCase):

    @mock.patch('__main__.Handler._service')
    def test_example_client_action_false(self):
        """Test Example When Action is False"""
        handler = Handler()
        self.assertFalse(handler.example())

if __name__ == '__main__':
    unittest.main()

The resulting test raises:

AttributeError: __main__.Handler does not have the attribute '_service'

How do I properly mock the Service or Client such that action returns False for my test case?

Body:
Can be done by mock the action return value

class TestHandler(unittest.TestCase):

@mock.patch('__main__.Client.action')
def test_example_client_action_false(self, mock_client_action):
    """Test Example When Action is False"""
    mock_client_action.return_value = False
    handler = Handler()
    self.assertFalse(handler.example())


问:
How to publish modules which are actually changed in gradle instead of all(not changed) to setup CI?
I am setting up the CI model for one project.This project is almost having 500 modules approx.We just update the workspace everytime through our CI tool and build modules which is actually changed.We are using gradle to build all modules my requirement is to publish only those modules which are changed in the current build to nexus snapshot repository.I know there is gradle task to publish the artifacts but only to publish to changed modules is the requirement.

Below is the example.

```<code>A
B
C
D
E
F
</code>```

If there is a change in B and F then I want to publish only B and F modules in nexus and if change is in A and F then publish only A and F module.

Something similar to

```<code> class IncrementalReverseTask extends DefaultTask {
      @InputDirectory
      def File inputDir

      @OutputDirectory
      def File outputDir

      @TaskAction
      void execute(IncrementalTaskInputs inputs) {
          if (!inputs.incremental)
              project.delete(outputDir.listFiles())

          inputs.outOfDate { change ->
              def targetFile = project.file("$outputDir/${change.file.name}")
              targetFile.text = change.file.text.reverse()
          }

          inputs.removed { change ->
              def targetFile = project.file("$outputDir/${change.file.name}")
              if (targetFile.exists()) {
                  targetFile.delete()
              }
          }
      }
  }
</code>```

I tried in below way and getting this issue

```<code>publishing {
    publications {
        maven(MavenPublication) {
            groupId 'com.example'
            artifactId 'core'
            version '1.0-SNAPSHOT'
            from components.java

    }
    }
    repositories {
    maven {
        credentials {
            username "abcde"
            password "***********"
            }
            url "https://nexus.test.com/content/repositories/snapshots"
            }
            }
    }

task incrementalPublishToMavenRepository(type: IncrementalPublishToMavenRepository) {
  inputDir = file('.')
  publication = project.tasks.getByPath(":${project.name}:publishMavenPublicationToMavenRepository").publication
}

class IncrementalPublishToMavenRepository extends org.gradle.api.publish.maven.tasks.PublishToMavenRepository {
    @InputDirectory
    def File inputDir

    @OutputDirectory
    File generatedFileDir = project.file("${project.buildDir}/libs")

    @TaskAction
    void perform(IncrementalTaskInputs inputs) {
        println 'hello this should be executed ones'
    }
}
</code>```

and getting below error

```<code>gradle jar incrementalPublishToMavenRepository

Configuration on demand is an incubating feature.
:core:compileJava UP-TO-DATE
:core:processResources NO-SOURCE
:core:classes UP-TO-DATE
:core:jar UP-TO-DATE
:app:compileJava UP-TO-DATE
:app:processResources UP-TO-DATE
:app:classes UP-TO-DATE
:app:jar UP-TO-DATE
:app:generatePomFileForMavenPublication
:app:incrementalPublishToMavenRepository FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:incrementalPublishToMavenRepository'.
> The 'repository' property is required

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
</code>```

答:
I tried to skip the uploadArchives method in below way when it is not creating the jar file

```<code>subprojects {
    apply plugin: 'java'
    apply plugin: 'maven'

    repositories {
        mavenCentral()
    }

    uploadArchives {
    repositories {
       mavenDeployer {
             repository(url: "https://repo.test.com/nexus/repos/snapshots") {
             authentication(userName: "abcdef", password: "******")
}
             pom.version = "1.1-SNAPSHOT"
             pom.groupId = "com.test"
       }
    }
}
uploadArchives {
  onlyIf { jar.didWork }
}

}
</code>```

Below is the output when I run with clean

```<code>:app:clean
:core:clean
:core:compileJava
:core:processResources NO-SOURCE
:core:classes
:core:jar
:app:compileJava
:app:processResources
:app:classes
:app:jar
:app:copyLicense
:app:startScripts
:app:distTar
:app:distZip
:app:uploadArchives
:core:uploadArchives
</code>```

Below is the output when run without clean

```<code>:core:compileJava UP-TO-DATE
:core:processResources NO-SOURCE
:core:classes UP-TO-DATE
:core:jar UP-TO-DATE
:app:compileJava UP-TO-DATE
:app:processResources UP-TO-DATE
:app:classes UP-TO-DATE
:app:jar UP-TO-DATE
:app:copyLicense UP-TO-DATE
:app:startScripts UP-TO-DATE
:app:distTar UP-TO-DATE
:app:distZip UP-TO-DATE
:app:uploadArchives SKIPPED
:core:uploadArchives SKIPPED
</code>```

Body:
I am setting up the CI model for one project.This project is almost having 500 modules approx.We just update the workspace everytime through our CI tool and build modules which is actually changed.We are using gradle to build all modules my requirement is to publish only those modules which are changed in the current build to nexus snapshot repository.I know there is gradle task to publish the artifacts but only to publish to changed modules is the requirement.

Below is the example.

A
B
C
D
E
F

If there is a change in B and F then I want to publish only B and F modules in nexus and if change is in A and F then publish only A and F module.

Something similar to

 class IncrementalReverseTask extends DefaultTask {
      @InputDirectory
      def File inputDir

      @OutputDirectory
      def File outputDir

      @TaskAction
      void execute(IncrementalTaskInputs inputs) {
          if (!inputs.incremental)
              project.delete(outputDir.listFiles())

          inputs.outOfDate { change ->
              def targetFile = project.file("$outputDir/${change.file.name}")
              targetFile.text = change.file.text.reverse()
          }

          inputs.removed { change ->
              def targetFile = project.file("$outputDir/${change.file.name}")
              if (targetFile.exists()) {
                  targetFile.delete()
              }
          }
      }
  }

I tried in below way and getting this issue

publishing {
    publications {
        maven(MavenPublication) {
            groupId 'com.example'
            artifactId 'core'
            version '1.0-SNAPSHOT'
            from components.java

    }
    }
    repositories {
    maven {
        credentials {
            username "abcde"
            password "***********"
            }
            url "https://nexus.test.com/content/repositories/snapshots"
            }
            }
    }

task incrementalPublishToMavenRepository(type: IncrementalPublishToMavenRepository) {
  inputDir = file('.')
  publication = project.tasks.getByPath(":${project.name}:publishMavenPublicationToMavenRepository").publication
}

class IncrementalPublishToMavenRepository extends org.gradle.api.publish.maven.tasks.PublishToMavenRepository {
    @InputDirectory
    def File inputDir

    @OutputDirectory
    File generatedFileDir = project.file("${project.buildDir}/libs")

    @TaskAction
    void perform(IncrementalTaskInputs inputs) {
        println 'hello this should be executed ones'
    }
}

and getting below error

gradle jar incrementalPublishToMavenRepository

Configuration on demand is an incubating feature.
:core:compileJava UP-TO-DATE
:core:processResources NO-SOURCE
:core:classes UP-TO-DATE
:core:jar UP-TO-DATE
:app:compileJava UP-TO-DATE
:app:processResources UP-TO-DATE
:app:classes UP-TO-DATE
:app:jar UP-TO-DATE
:app:generatePomFileForMavenPublication
:app:incrementalPublishToMavenRepository FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:incrementalPublishToMavenRepository'.
> The 'repository' property is required

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Body:
I tried to skip the uploadArchives method in below way when it is not creating the jar file

subprojects {
    apply plugin: 'java'
    apply plugin: 'maven'

    repositories {
        mavenCentral()
    }

    uploadArchives {
    repositories {
       mavenDeployer {
             repository(url: "https://repo.test.com/nexus/repos/snapshots") {
             authentication(userName: "abcdef", password: "******")
}
             pom.version = "1.1-SNAPSHOT"
             pom.groupId = "com.test"
       }
    }
}
uploadArchives {
  onlyIf { jar.didWork }
}

}

Below is the output when I run with clean

:app:clean
:core:clean
:core:compileJava
:core:processResources NO-SOURCE
:core:classes
:core:jar
:app:compileJava
:app:processResources
:app:classes
:app:jar
:app:copyLicense
:app:startScripts
:app:distTar
:app:distZip
:app:uploadArchives
:core:uploadArchives

Below is the output when run without clean

:core:compileJava UP-TO-DATE
:core:processResources NO-SOURCE
:core:classes UP-TO-DATE
:core:jar UP-TO-DATE
:app:compileJava UP-TO-DATE
:app:processResources UP-TO-DATE
:app:classes UP-TO-DATE
:app:jar UP-TO-DATE
:app:copyLicense UP-TO-DATE
:app:startScripts UP-TO-DATE
:app:distTar UP-TO-DATE
:app:distZip UP-TO-DATE
:app:uploadArchives SKIPPED
:core:uploadArchives SKIPPED


问:
Tried creating and writing to a file, but I'm getting error messages
I'm trying to learn how to create a file and write to it on Java. I've been watching videos online on how to do it. Unfortunately using the exact same code as the person doing the lesson, I come up with these errors which I don't understand.

```<code>java.io.IOException: No such file or directory
    at java.io.UnixFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:1012)
    at CompanyAdder.main(CompanyAdder.java:26)
java.io.FileNotFoundException: C:/Users/mychalco/Desktop/ASreader.txt (No such file or directory)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
    at java.io.FileWriter.<init>(FileWriter.java:90)
    at CompanyAdder.main(CompanyAdder.java:35)
</code>```

I know that there's apparently an error on line 26 and 35, but I don't understand what else is happening. Here's my code:

```<code>import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

public class CompanyAdder
{
    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        //String addCompanyName = "Y";
        //String companyName;

        File newFile = new File("C:/Users/mychalco/Desktop/ASreader.txt");

        if(newFile.exists())
        {
            System.out.println("The file already exists");
        }
        else
        {
            try
            {
                newFile.createNewFile();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }

            try
            {
                FileWriter fileW = new FileWriter(newFile);
                BufferedWriter buffW = new BufferedWriter(fileW);
                /*System.out.println("Add a company name: ");

                while (addCompanyName.equalsIgnoreCase("Y"))
                {
                    companyName = sc.next();
                    buffW.write(companyName);
                    System.out.println("Do you want to add another company? (Y/N) ");
                    addCompanyName = sc.next();
                }*/
                buffW.close();
                System.out.println("Company names added!");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

}
</code>```

Ignore the comment lines, those were some alterations I tried to make to the code.

Thanks, Cheers.

答:
Try to use File.separator in this way:

```<code>File newFile = new File("C:"+File.separator+"Users"+File.separator+"mychalco"+File.separator+"Desktop"+File.separator+"ASreader.txt");
</code>```

Body:
I'm trying to learn how to create a file and write to it on Java. I've been watching videos online on how to do it. Unfortunately using the exact same code as the person doing the lesson, I come up with these errors which I don't understand.

java.io.IOException: No such file or directory
    at java.io.UnixFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:1012)
    at CompanyAdder.main(CompanyAdder.java:26)
java.io.FileNotFoundException: C:/Users/mychalco/Desktop/ASreader.txt (No such file or directory)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
    at java.io.FileWriter.<init>(FileWriter.java:90)
    at CompanyAdder.main(CompanyAdder.java:35)

I know that there's apparently an error on line 26 and 35, but I don't understand what else is happening. Here's my code:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

public class CompanyAdder
{
    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        //String addCompanyName = "Y";
        //String companyName;

        File newFile = new File("C:/Users/mychalco/Desktop/ASreader.txt");

        if(newFile.exists())
        {
            System.out.println("The file already exists");
        }
        else
        {
            try
            {
                newFile.createNewFile();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }

            try
            {
                FileWriter fileW = new FileWriter(newFile);
                BufferedWriter buffW = new BufferedWriter(fileW);
                /*System.out.println("Add a company name: ");

                while (addCompanyName.equalsIgnoreCase("Y"))
                {
                    companyName = sc.next();
                    buffW.write(companyName);
                    System.out.println("Do you want to add another company? (Y/N) ");
                    addCompanyName = sc.next();
                }*/
                buffW.close();
                System.out.println("Company names added!");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

}

Ignore the comment lines, those were some alterations I tried to make to the code.

Thanks, Cheers.

Body:
Try to use File.separator in this way:

File newFile = new File("C:"+File.separator+"Users"+File.separator+"mychalco"+File.separator+"Desktop"+File.separator+"ASreader.txt");


问:
How do you disable slider arrows on a header image in wordpress?
Website home

Hello. I am using the Flash sitebuilder theme in Wordpress and I am wondering what kind of CSS I would have to use to disable these slider arrows, as I only want one image to be displayed. The website link is here

Some of the CSS I've tried is

```<code>.swiper-button-next {
visibility:        none;
}

.swiper-button-prev
{
visibility:        none;
}
</code>```

But I'm not really sure what I'm doing. Thanks

答:
In your code : </p>

```<code>   <div class="swiper-container swiper-container-horizontal">
</code>```

<p>just remove this line and end <\div> .... hope this is work. </p>

Body:
Website home

Hello. I am using the Flash sitebuilder theme in Wordpress and I am wondering what kind of CSS I would have to use to disable these slider arrows, as I only want one image to be displayed. The website link is here

Some of the CSS I've tried is

.swiper-button-next {
visibility:        none;
}

.swiper-button-prev
{
visibility:        none;
}

But I'm not really sure what I'm doing. Thanks

Body:
In your code :

   <div class="swiper-container swiper-container-horizontal">

just remove this line and end <\div> .... hope this is work.


问:
Jackson Modules not being registered in all Spring Boot ObjectMapper instances?
I have a Spring Boot application where my Jackson modules are being registered, like jdk8, jsr-310 and money. The objectmapper used by actuator endpoints uses the same objectmapper and the modules are registered, but when I call my defined WebMVC @RestController endpoints, a different objectmapper instance is used with no defined modules registered. How do I solve this problem? </p>

答: Thanks to above comment by M. Deinum I have solved it. There was an @EnableWebMvc annotation on an imported class. Removing this solves the problem. </p>


问:
Font for Words in a sentence needs to be italic using vb
I need to display the following content in the body of my email. Words "orders" and
"dispatch" need to be in italic.

code in VB:

```<code>tlBody = tlBody.Replace("DBCOLUMN1", ds.Tables(1).Rows(1)(0).ToString)
tlBody = tlBody.Replace(“001value”, “ All ““orders” “must be within the
 “”dispatch”” date.”)
</code>```

DBCOLUMN1 is grabbed from database table which has "Action" as value

Desired output

Action:

All “orders” must be within the “dispatch” date.

Current output

Action:

All “orders” must be within the “dispatch” date.

答:
Using System.Net.Mail.MailMessage class to send your email, you can format the body as Html

```<code>MailMessage.IsBodyHtml = True
</code>```

Then, the body can contain italic tags

```<code>tlBody = tlBody.Replace("001value", " All <i>orders</i> must be within the <i>dispatch</i> date.")
</code>```

Here's a complete example with bold tags (works the same way): http://www.systemnetmail.com/faq/3.1.2.aspx

Body:
I need to display the following content in the body of my email. Words "orders" and
"dispatch" need to be in italic.

code in VB:

tlBody = tlBody.Replace("DBCOLUMN1", ds.Tables(1).Rows(1)(0).ToString)
tlBody = tlBody.Replace(“001value”, “ All ““orders” “must be within the
 “”dispatch”” date.”)

DBCOLUMN1 is grabbed from database table which has "Action" as value

Desired output

Action:

All “orders” must be within the “dispatch” date.

Current output

Action:

All “orders” must be within the “dispatch” date.

Body:
Using System.Net.Mail.MailMessage class to send your email, you can format the body as Html

MailMessage.IsBodyHtml = True

Then, the body can contain italic tags

tlBody = tlBody.Replace("001value", " All <i>orders</i> must be within the <i>dispatch</i> date.")

Here's a complete example with bold tags (works the same way): http://www.systemnetmail.com/faq/3.1.2.aspx


问:
C# - Directory Search not returning results for parent directory
I have this file count function that is not returning results from my parent directory. It does return results of all sub directories. During my debugging I def see the parent directory being passed as my Directory.GetDirectories(sDir) but once it hits  Directory.GetFiles(d) it already changed to the sub directories. I am banging my head against a wall on this one. Clearly, it must be my foreach loop but I am not seeing it.

The file structure I am passing is:

C:\Users\xxxxx\Desktop\Temp Logs

but it has three sub directories:

C:\Users\xxxxx\Desktop\Temp Logs\sub1

C:\Users\xxxxx\Desktop\Temp Logs\sub2

C:\Users\xxxxx\Desktop\Temp Logs\sub3

Does anyone see my error?

```<code>     private static string fileCount(string sDir, string sfileType)
    {
        int count = 0;
        string extension;
        foreach (string d in Directory.GetDirectories(sDir))
        {
            foreach (string file in Directory.GetFiles(d))
            {
                extension = Path.GetExtension(file);
                if (extension.ToUpper().Equals(sfileType.ToUpper()))
                {
                    TimeSpan fileAge = DateTime.Now - File.GetLastWriteTime(file);
                    if (fileAge.Days > int.Parse(ConfigurationManager.AppSettings["numberOfDays"]))
                    {
                        count++;
                    }
                }
            }
        }
        return count.ToString();
    }
</code>```

答:
The array you use in the foreach only contains SubDirectories. Add the parent and your good to go!</p>

```<code>private static string fileCount(string sDir, string sfileType)
{
    int count = 0;
    string extension;
    List<string> directoriesToCheck = Directory.GetDirectories(sDir).ToList();
    directoriesToCheck.Add(sDir);
    foreach (string d in directoriesToCheck)
    {
        foreach (string file in Directory.GetFiles(d))
        {
            extension = System.IO.Path.GetExtension(file);
            if (extension.ToUpper().Equals(sfileType.ToUpper()))
            {
                TimeSpan fileAge = DateTime.Now - File.GetLastWriteTime(file);
                if (fileAge.Days > int.Parse(ConfigurationManager.AppSettings["numberOfDays"]))
                {
                    count++;
                }
            }
        }
    }
    return count.ToString();
}
</code>```

Body:
I have this file count function that is not returning results from my parent directory. It does return results of all sub directories. During my debugging I def see the parent directory being passed as my Directory.GetDirectories(sDir) but once it hits  Directory.GetFiles(d) it already changed to the sub directories. I am banging my head against a wall on this one. Clearly, it must be my foreach loop but I am not seeing it.

The file structure I am passing is:

C:\Users\xxxxx\Desktop\Temp Logs

but it has three sub directories:

C:\Users\xxxxx\Desktop\Temp Logs\sub1

C:\Users\xxxxx\Desktop\Temp Logs\sub2

C:\Users\xxxxx\Desktop\Temp Logs\sub3

Does anyone see my error?

     private static string fileCount(string sDir, string sfileType)
    {
        int count = 0;
        string extension;
        foreach (string d in Directory.GetDirectories(sDir))
        {
            foreach (string file in Directory.GetFiles(d))
            {
                extension = Path.GetExtension(file);
                if (extension.ToUpper().Equals(sfileType.ToUpper()))
                {
                    TimeSpan fileAge = DateTime.Now - File.GetLastWriteTime(file);
                    if (fileAge.Days > int.Parse(ConfigurationManager.AppSettings["numberOfDays"]))
                    {
                        count++;
                    }
                }
            }
        }
        return count.ToString();
    }

Body:
The array you use in the foreach only contains SubDirectories. Add the parent and your good to go!

private static string fileCount(string sDir, string sfileType)
{
    int count = 0;
    string extension;
    List<string> directoriesToCheck = Directory.GetDirectories(sDir).ToList();
    directoriesToCheck.Add(sDir);
    foreach (string d in directoriesToCheck)
    {
        foreach (string file in Directory.GetFiles(d))
        {
            extension = System.IO.Path.GetExtension(file);
            if (extension.ToUpper().Equals(sfileType.ToUpper()))
            {
                TimeSpan fileAge = DateTime.Now - File.GetLastWriteTime(file);
                if (fileAge.Days > int.Parse(ConfigurationManager.AppSettings["numberOfDays"]))
                {
                    count++;
                }
            }
        }
    }
    return count.ToString();
}


问:
Increase reCAPTCHA session timeout
I'm using the Google reCAPTCHA component and have been asked to increase the session timeout. I couldn't find any solution for this. Can it be done? Many thanks.

答: I'm afraid there's no solution for this, as the reCAPTCHA challenge is served from Google, so the session is not between your app and the user but with the reCAPTCHA service and the user. Think of reCAPTCHA as a multi-tenant web app (where each tenant is the site that's displaying it), and the only settings available to each tenant are the authentication keys and the type of challenge that should be displayed.</p>

Title: Increase reCAPTCHA session timeout


问:
Django 1.9 to 1.10 raises NoReverseMatch: u'en-gb' is not a registered namespace
I am trying to update my 1.9 application to 1.10 and I am getting the following error on running all my unit tests:

```<code>Traceback (most recent call last):   File "/home/…/tests/views/test_configurator.py", line 261, in test_view_configurator_post
    args=[self.configurator.id]),   File "/home/…/.virtualenvs/intranet/lib/python2.7/site-packages/django/urls/base.py", line 87, in reverse
    raise NoReverseMatch("%s is not a registered namespace" % key) NoReverseMatch: 'en-gb' is not a registered namespace
</code>```

My setting.py file contains the following:

```<code>LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
TIME_ZONE = 'Europe/London'
</code>```

What am I missing?

答:
I encountered this as well, and I narrowed down the cause. I think it's a regression in Django, but I don't have time to write up a full bug report. Here's what I know.

Django waits until the first call to django.urls.reverse to populate all the namespaces to a cached dict.

There's been some changes to that population procedure recently.
They added a populating flag that is set to True when you start populating, and is shared across calls to reverse. If the population process happens to make a call to django.urls.reverse, the flag will prevent infinite recursion.

The population process involves importing URL patterns - the urls.py files you have in your apps. If anything during that import process raises an exception, e.g. an undefined name at the top-level of a module in my case, the population algorithm doesn't catch that, and just stops outright, and leaves the populating flag to True. That error, at least for me, was propagated to the top level and I saw it in test runner output.

All subsequent calls to django.urls.reverse raise a NoReverseMatch error for the en-us namespace. Following the code, this is because at the start of the population procedure, if the populating flag is truthy, the process just returns and returns the cached namespace dict, which is empty, causing a KeyError for en-us, causing a NoReverseMatch for en-us.

You should look at the errors that occurred before the first NoReverseMatch to find your culprit. For more info, I think this is the commit that introduced the regression. It has a link to the Django issue it fixed. I think the fix would be to set the populating flag to False in case of an exception, but I'm not sure.

Body:
I am trying to update my 1.9 application to 1.10 and I am getting the following error on running all my unit tests:

Traceback (most recent call last):   File "/home/…/tests/views/test_configurator.py", line 261, in test_view_configurator_post
    args=[self.configurator.id]),   File "/home/…/.virtualenvs/intranet/lib/python2.7/site-packages/django/urls/base.py", line 87, in reverse
    raise NoReverseMatch("%s is not a registered namespace" % key) NoReverseMatch: 'en-gb' is not a registered namespace

My setting.py file contains the following:

LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
TIME_ZONE = 'Europe/London'

What am I missing?


问:
How could I replace a form with text when form is submitted?
I want my form to disappear when someone submits it (and it passes all of the error checking)
and text replaces where it was and says something like "Thank you a confirmation email has been sent"

What are some ways I would be able to do this?

I have the form working and the error checks and everything working, all I would need to do is make it disappear when the user clicks submit..

I am using php, Thanks!

答:
```<code>var td = document.forms.contact.parentNode
if (td.innerHTML) {
    td.innerHTML = "your message"
} else {
    td.textContent = "your message"
}
</code>```

If you are submitting using AJAX, put it at the end
If you are using basic forms, put it as a function in the onSubmit attribute of your form

Example:

```<code><form onSubmit="emptyForm();"
</code>```

Body:
var td = document.forms.contact.parentNode
if (td.innerHTML) {
    td.innerHTML = "your message"
} else {
    td.textContent = "your message"
}

If you are submitting using AJAX, put it at the end
If you are using basic forms, put it as a function in the onSubmit attribute of your form

Example:

<form onSubmit="emptyForm();"


问:
Clicks not passed through to custom component in Vue 2
I'm including a bunch of posts like this:

```<code><template>
  <div id="posts">
    <div id="posts-wrapper">
      <post v-for="(item, key) in posts" :key="item.id" :post="item" :isListItem="true"></post>
    </div>
    <infinite-loading :on-infinite="onInfinite" ref="infiniteLoading">
      <span slot="no-more">
        There are no more posts
      </span>
    </infinite-loading>
  </div>
</template>

<script>
import InfiniteLoading from 'vue-infinite-loading'
import posts from '@/api/posts'
import post from '@/components/Post'

export default {
  name: 'posts',
  components: {
    post,
    InfiniteLoading,
  },
  data () {
    return {
      posts: []
    }
  },
  methods: {
    onInfinite() {
        posts.getPosts(page++).then(posts => {
        this.posts = this.posts.concat(posts);
        this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
      })
    }
  }
};
</script>
</code>```

And here is the post component:

```<code><template>
  <v-card class="post-list-item" v-bind:class="{ clickable: isListItem }" @click.native="openPost">
    <div class="header">
      {{ post.name }}
    </div>
    <div class="image">

    </div>
    <div class="data">

    </div>
    <!-- same handler bound here just for testing -->
    <div class="button" v-on:click.native="openPost">
      Open post
    </div>
  </v-card>
</template>

<script>
  export default {
    name: 'post',
    methods: {
      openPost() {
        console.log('post opening');
      }
    },
    props: {
      post: {
        type: Object,
        required: true
      },
      isListItem: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {}
    }
  }
</script>
</code>```

The problem is that the clicks are not passed through, ie. the openPost() method is never called. If I set a listener in the parent, then that works, but is not what I'm looking for. The clicks should be handled within the component itself.

The v-card is a Vuetify component.

What am I doing wrong?

答:
I had the same problem, but i solved it by using </p>

```<code>v-on:click
</code>```

<p>instead of </p>

```<code>@click.native
</code>```

Body:
I'm including a bunch of posts like this:

<template>

      <post v-for="(item, key) in posts" :key="item.id" :post="item" :isListItem="true"></post>

    <infinite-loading :on-infinite="onInfinite" ref="infiniteLoading">

        There are no more posts

    </infinite-loading>

</template>

And here is the post component:

<template>
  <v-card class="post-list-item" v-bind:class="{ clickable: isListItem }" @click.native="openPost">

      {{ post.name }}

      Open post

  </v-card>
</template>

The problem is that the clicks are not passed through, ie. the openPost() method is never called. If I set a listener in the parent, then that works, but is not what I'm looking for. The clicks should be handled within the component itself.

The v-card is a Vuetify component.

What am I doing wrong?

Body:
I had the same problem, but i solved it by using

v-on:click

instead of

@click.native


问:
Synchronize accelerometer and Gyroscope / Android
I am developing a mobile application under android and I need to retrieve the data from the accelerometer and gyroscope at exactly the same time ie I need to synchronize the two sensors to simultaneously read their values . I need to use a Service (not an Activity) but the value of the two event.timestamp are completely different.

```<code>public void onSensorChanged(SensorEvent event) {

    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        xa =event.values[0] ;
        ya =event.values[1] ;
        za =event.values[2] ;
        ta= event.timestamp;

    }

    if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
        xg = event.values[0];
        yg = event.values[1];
        zg = event.values[2];
        tg = event.timestamp;
   }
</code>```

Thank you.

答:
Use 2 boolean flags, one for accelerometer and another for gyroscope, when both of them true it means you get at least one time from both of them, posibly one of them will have 3 or more times. Accelerometer sensor is quite fast. When both of them true set them to false again to get data from them again. You can't synchronize sensors with Sensor api.</p>

```<code>boolean isAccelData = false;
boolean isGyroData = false;

public void onSensorChanged(SensorEvent event) {

    if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
        isAccelData = true;
    }
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        isGyroData = true;
    }
    if (isAccelData & isGyroData) {
        // DO something here
        isAccelData = false;
        isGyroData = false;
    }
}
</code>```

Body:
I am developing a mobile application under android and I need to retrieve the data from the accelerometer and gyroscope at exactly the same time ie I need to synchronize the two sensors to simultaneously read their values . I need to use a Service (not an Activity) but the value of the two event.timestamp are completely different.

public void onSensorChanged(SensorEvent event) {

    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        xa =event.values[0] ;
        ya =event.values[1] ;
        za =event.values[2] ;
        ta= event.timestamp;

    }

    if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
        xg = event.values[0];
        yg = event.values[1];
        zg = event.values[2];
        tg = event.timestamp;
   }

Thank you.

Body:
Use 2 boolean flags, one for accelerometer and another for gyroscope, when both of them true it means you get at least one time from both of them, posibly one of them will have 3 or more times. Accelerometer sensor is quite fast. When both of them true set them to false again to get data from them again. You can't synchronize sensors with Sensor api.

boolean isAccelData = false;
boolean isGyroData = false;

public void onSensorChanged(SensorEvent event) {

    if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
        isAccelData = true;
    }
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        isGyroData = true;
    }
    if (isAccelData & isGyroData) {
        // DO something here
        isAccelData = false;
        isGyroData = false;
    }
}


问:
Know if app downloaded from a website
I am implementing deep linking. On our website, the app download banner is there. If a user clicks on download button and the app is downloaded. Is there a way to know that this app was downloaded after redirecting too appstore from our website or user directly went to app store, searched for the app and downloaded.</p>

答:
Strictly speaking, this is 'attribution', not 'deep linking'. Deferred deep linking might be involved if you want to send users directly to a specific place in your app after they download by clicking on the banner button, but tracking who downloaded is a separate problem.

iTunes Connect campaign links track this to a certain extent, but they are often found to be unreliable. You'll probably want a third-party install attribution tool like Branch.io (full disclosure: I'm on the Branch team) or Firebase Dynamic Links. Branch actually has an out-of-the-box smart banner option.

If you're doing a lot of paid ads, you might also want to investigate ad attribution providers like Adjust, Tune, or AppsFlyer.

Title: Know if app downloaded from a website


问:
Deleting content of every string after first empty space
How can I delete everything after first empty space in a string which user selects? I was reading this how to remove some words from a string in java. Can this help me in my case?</p>

答:
You can use replaceAll with a regex \s.* which match every thing after space:

```<code>String str = "Hello java word!";
str = str.replaceAll("\\s.*", "");
</code>```

output

```<code>Hello
</code>```

regex demo

Like @Coffeehouse Coder mention in comment, This solution will replace every thing if the input start with space, so if you want to avoid this case, you can trim your input using string.trim() so it can remove the spaces in start and in end.

Body:
You can use replaceAll with a regex \s.* which match every thing after space:

String str = "Hello java word!";
str = str.replaceAll("\\s.*", "");

output

Hello

regex demo

Like @Coffeehouse Coder mention in comment, This solution will replace every thing if the input start with space, so if you want to avoid this case, you can trim your input using string.trim() so it can remove the spaces in start and in end.


答:
The simplest solution in my opinion would be to just locate the index which the user wants it to be cut off at and then call the substring() method from 0 to the index they wanted.  Set that = to a new string and you have the string they want.

If you want to replace the string then just set the original string = to the result of the substring() method.

Link to substring() method: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)

Body: How can I delete everything after first empty space in a string which user selects? I was reading this how to remove some words from a string in java. Can this help me in my case?


问:
Rolling effect in ListBox
This is a follow-up to this question

Increase FontSize for hovered element in WPF ListBox

I have a ListBox where I want a "rolling" effect. From start all my items in the ListBox have a FontSize of 12, and when IsMouseOver="True" they get FontSize=18. Now I want the item below and above the IsMouseOvered item to get FontSize 16. I've got a feeling this is not so straight forward. Anyone got any idea?

This is my ListBox now

```<code><ListBox Name="ListBox" ItemsSource="{Binding MyList}" DisplayMemberPath="Property1">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="TextBlock.FontSize" Value="18"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>
</code>```

Thanks

答: It appears you are going for the fish eye effect. There are varying solutions out there for WPF which provide this behavior for you in the form of a reusable panel for instance. They generally focus on images however the concept is the same. This solution shows an example in pure XAML.</p>

Title: Rolling effect in ListBox

Body:
This is a follow-up to this question

Increase FontSize for hovered element in WPF ListBox

I have a ListBox where I want a "rolling" effect. From start all my items in the ListBox have a FontSize of 12, and when IsMouseOver="True" they get FontSize=18. Now I want the item below and above the IsMouseOvered item to get FontSize 16. I've got a feeling this is not so straight forward. Anyone got any idea?

This is my ListBox now

<ListBox Name="ListBox" ItemsSource="{Binding MyList}" DisplayMemberPath="Property1">
    <ListBox.ItemContainerStyle>

        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Thanks


问:
How to load data to dashboard view from Mysql Server?
I have a lot of data coming from different places and getting stored in MySQL database. I want to create a dashboard view of that. There are two problems,

I want the data to show up on the dashboard page as soon as it gets inserted into the database. (avoid using lookup).

A solution in Java/JavaScript language is expected.

Can I use firebase or something similar that loads data automatically?

I have seen some live dashboards and I keep on wondering how they do it. It will be great if community can provide link to some good tutorials.

答:
Assuming that you have your service running on: http://localhost:4848/ and it has the 2 methods. The first insert on Mysql the and the other get the information of the table that you inserting.

var apiURL = 'localhost:4848/'; // Web service URL
displayUsers(); // When the documents load

function insertUser(input) {
  var apiMethod = 'insert/user';
  var data = $("#username").val();

  $.ajax({
    type: "POST",
    url: (apiURL + apiMethod),
    data: data,
    success: function (response) {
      displayUsers();
    },
    dataType: 'text'
  });
}

function displayUsers() {
  var apiMethod = 'getAll';
  $.ajax({
    type: "POST",
    url: (apiURL + apiMethod),
    success: function (response) {
      $('#user-list').text(response);
    },
    dataType: 'text'
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form">
  <input type="text" id="username">
  <input type="submit" value="Add" onclick="insertUser()">
</div>
<div class="list" id="user-list">
</div></code>```

Also watch this Post. About firebase I don't know what could help you. But I think this may help you.

Body:
Assuming that you have your service running on: http://localhost:4848/ and it has the 2 methods. The first insert on Mysql the and the other get the information of the table that you inserting.

var apiURL = 'localhost:4848/'; // Web service URL
displayUsers(); // When the documents load

function insertUser(input) {
  var apiMethod = 'insert/user';
  var data = $("#username").val();

  $.ajax({
    type: "POST",
    url: (apiURL + apiMethod),
    data: data,
    success: function (response) {
      displayUsers();
    },
    dataType: 'text'
  });
}

function displayUsers() {
  var apiMethod = 'getAll';
  $.ajax({
    type: "POST",
    url: (apiURL + apiMethod),
    success: function (response) {
      $('#user-list').text(response);
    },
    dataType: 'text'
  });
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form">
  <input type="text" id="username">
  <input type="submit" value="Add" onclick="insertUser()">
</div>
<div class="list" id="user-list">
</div>

Also watch this Post. About firebase I don't know what could help you. But I think this may help you.


问:
how we can add element at the starting of array in every operation and compute sum of any given range.?
You are initially given an array of N integers ( 1<=N<=105 ). Given this array, you have to perform 2 kinds of operations :

```<code>(i) Operation 1 : Op1( l, r )
</code>```

You are given 2 integers l and r. ( 1 <= l <= r <= current size of the array ). You need to return the sum of all the elements with indices between l and r ( both inclusive ). That is, if the elements currently in the array are a1, a2, a3.... an, you need to return the following sum : al + al+1 + al+2 ... + ar.

```<code>(ii) Operation 2 : Op2( x )
</code>```

You are given a single integer x ( |x| <= 109 ). Add this element to the beginning of the array. After this operation, x will now become a1, the old a1 will now become a2, and so on. The size of the array will increase by 1.

I made segment tree with the initial given array and could compute range sum....but how i could add one element in segment tree and modify it accordingly?

答:
Try this offline algorithm:-

First read in the array a.

Then read in all the queries and store them and also count the no of type 2 queries, let it be K.

Now create a new array b of length K+length of(a).

Now starting at index 1 in b and traversing your queries backwards, for every type 2 query add its element to array b.

Now build a Segment tree or Binary Indexed tree on array b.

Use a variable c to count the no of type 2 queries encountered till now and initialize it to 0.

Then traverse your list of queries and for each query of type 2 just increment c by 1.

For query of type 1 having range l...r in array a, its range in array b will correspond to (l+k-c)...(r+k-c).

So use the Segment tree or Binary indexed tree built above to answer this query on the transformed range.
I hope that it was helpful.

Body:
You are initially given an array of N integers ( 1<=N<=105 ). Given this array, you have to perform 2 kinds of operations :

(i) Operation 1 : Op1( l, r )

You are given 2 integers l and r. ( 1 <= l <= r <= current size of the array ). You need to return the sum of all the elements with indices between l and r ( both inclusive ). That is, if the elements currently in the array are a1, a2, a3.... an, you need to return the following sum : al + al+1 + al+2 ... + ar.

(ii) Operation 2 : Op2( x )

You are given a single integer x ( |x| <= 109 ). Add this element to the beginning of the array. After this operation, x will now become a1, the old a1 will now become a2, and so on. The size of the array will increase by 1.

I made segment tree with the initial given array and could compute range sum....but how i could add one element in segment tree and modify it accordingly?