问:
How to get access to values from every Activity using Service
I trying to make the app similar to Nissan Leaf Spy. This app receives data from bluetooth interface ELM 327. My goal is to collect data like:

Speed

Temperature

Power

Battery capacity

And some more data

And display them on real time chart using GraphView.
For one parameter is one chart in Activity. So there are at least as many Activities as parameters I need to display. My guess is to use

```<code>Android Services
</code>```

to do work in background to co collect and save every data in different array via bluetooth. Of course when I change Activity to see another Activity the one that works will stop working and there will be no more real time.
The question is: is there any kind of 'superclass' that is always working or do I need to save this data using SQL? Or should I just use intent.putExtraString(key,value) and getIntent().getStringExtra(key). I will be grateful for your help!

答:
About having different activities for different parameters, you need to have just one activity. You can have a graph and different ArrayLists with adapters for parameters and then use one of them to feed the graph according to the parameter selected say, from a Spinner.

To feed those ArrayLists is just as easy. You can have a Service running, for general data collection, with an AsyncTask inside it, which will keep the feed live for a selected parameter when the app is active and not in the background. The Service, by itself, can collect data in some sort of a buffer large enough to feed those graphs.

Remember, AsyncTasks are good for updating UI components without blocking the main thread.

EDIT: Look, if you have an activity (let's consider some other activity than main) where you're going to show the data or graph, you can have AsyncTask running as soon as you enter the activity(you can define a default parameter for a graph to be shown) or when you select from a drop down, giving you real-time data while you're on the activity.

The reason I am using AsyncTask for the live feed is that you can have different UI views and seamlessly integrate without any future problems and that it'd modularize Service into functionalities for serving Activity and would end when you close the app. The Service running in the background would primarily provide to a temp log file or be an InputStream source for AsyncTask when it runs after app launch or activity launch.

Body:
I trying to make the app similar to Nissan Leaf Spy. This app receives data from bluetooth interface ELM 327. My goal is to collect data like:

Speed

Temperature

Power

Battery capacity

And some more data

And display them on real time chart using GraphView.
For one parameter is one chart in Activity. So there are at least as many Activities as parameters I need to display. My guess is to use

Android Services

to do work in background to co collect and save every data in different array via bluetooth. Of course when I change Activity to see another Activity the one that works will stop working and there will be no more real time.
The question is: is there any kind of 'superclass' that is always working or do I need to save this data using SQL? Or should I just use intent.putExtraString(key,value) and getIntent().getStringExtra(key). I will be grateful for your help!


来源: stackexchange

问:
How do i convert the following xml based spring bean to java annotation based beans?
```<code> <bean id="string.message.service" class="com.ce.indiabringsService">
 <constructor-arg ref="com.ce.indiabrings.consumer" />
 <constructor-arg ref="com.ce.indiabrings.value.function" />
 </bean>
</code>```

I want to convert this to java annotation based bean (@Bean).

答:
create a method in configuration class

Construct mentioned object and return.

Annotate the method with @Bean

```<code>@Bean
public com.ce.indiabringsService getindiabringsServiceBean(){
    return new com.ce.indiabringsService(consumerObj,functionObj);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
 <bean id="string.message.service" class="com.ce.indiabringsService">
 <constructor-arg ref="com.ce.indiabrings.consumer" />
 <constructor-arg ref="com.ce.indiabrings.value.function" />
 </bean>

I want to convert this to java annotation based bean (@Bean).

Body:
create a method in configuration class

Construct mentioned object and return.

Annotate the method with @Bean

@Bean
public com.ce.indiabringsService getindiabringsServiceBean(){
    return new com.ce.indiabringsService(consumerObj,functionObj);
}


问:
Add three Buttons in an UIAlertView
I created uialertview, and add two buttons, Now I need to add one more button in alert view. How to edit my code to add one more button?</p>

```<code>UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Refresh" message:@"Are you want to Refresh Data" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
[alert show];
[alert release];
</code>```

答:
If you are really struggling to find the solution, the following code may help you.</p>

```<code>UIAlertView *alert = [[UIAlertView alloc]
                        initWithTitle:@"Refresh"
                              message:@"Are you want to Refresh Data"
                             delegate:self
                    cancelButtonTitle:@"Cancel"
                    otherButtonTitles:@"OK", @"Done", nil];
[alert show];
[alert release];
</code>```

Title: Add three Buttons in an UIAlertView

Body:
I created uialertview, and add two buttons, Now I need to add one more button in alert view. How to edit my code to add one more button?

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Refresh" message:@"Are you want to Refresh Data" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
[alert show];
[alert release];

Body:
If you are really struggling to find the solution, the following code may help you.

UIAlertView *alert = [[UIAlertView alloc]
                        initWithTitle:@"Refresh"
                              message:@"Are you want to Refresh Data"
                             delegate:self
                    cancelButtonTitle:@"Cancel"
                    otherButtonTitles:@"OK", @"Done", nil];
[alert show];
[alert release];


问:
Regular Expression Pattern for different strings to get as a group
I have a string like this:

```<code>var stringToBeMatched = @"S14XV15011.MAXCV_MAXCV = 2323 /m BVASL /d {A1d} /t 2009.08.23 12:01:47 /a dfsd-df/c Imported from: HV2108C2; dfddf-er-author: TVI";
</code>```

/d tag in above string can have any values from below:

```<code>a. /d MBX-JA-DVQ-1811
b. /d Bvala_Mana-CVw.xls
c. /d {A1dq}
d. /d MBX-JA-DVQ-1811 Control valves.pdf
e. /d MBEM306-0005 Data sheet 21P0001A_B_C
f. /d MBA-M30-PE-012-022 2.trinan sep.
</code>```

I am using below pattern to match them but only options b & d get satisfied here:

```<code>var patternToCompare = @"(\{*(?<DocRef>(((\S\s*)+\.[a-zA-Z]+))|(\S\s*)+)\}*)";
</code>```

If I add \w+ as an OR option at start, it matches above option c but not others. Kindly suggest the best possible pattern to match all above options.

答:
Your question sounds vague and complex. Without more examples it's only guess work. But this will match all the \d items</p>

```<code>(^(MB)(A|X|EM).+)|({\A1.+})|(Bvala+.+\.xls)
</code>```

Body:
I have a string like this:

var stringToBeMatched = @"S14XV15011.MAXCV_MAXCV = 2323 /m BVASL /d {A1d} /t 2009.08.23 12:01:47 /a dfsd-df/c Imported from: HV2108C2; dfddf-er-author: TVI";

/d tag in above string can have any values from below:

a. /d MBX-JA-DVQ-1811
b. /d Bvala_Mana-CVw.xls
c. /d {A1dq}
d. /d MBX-JA-DVQ-1811 Control valves.pdf
e. /d MBEM306-0005 Data sheet 21P0001A_B_C
f. /d MBA-M30-PE-012-022 2.trinan sep.

I am using below pattern to match them but only options b & d get satisfied here:

var patternToCompare = @"(\{*(?<DocRef>(((\S\s*)+\.[a-zA-Z]+))|(\S\s*)+)\}*)";

If I add \w+ as an OR option at start, it matches above option c but not others. Kindly suggest the best possible pattern to match all above options.

Body:
Your question sounds vague and complex. Without more examples it's only guess work. But this will match all the \d items

(^(MB)(A|X|EM).+)|({\A1.+})|(Bvala+.+\.xls)


问:
Remove namespace from XSLT output
```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <s:Header xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" />
  <soapenv:Body>
    <swiftResponseResponse xmlns="http://webservice.sbi.com">
      <swiftResponseReturn>15617TS006140|DC768736|13321.49|04-05-2017 15:13:03|SWIFTINR|NA|FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturn>
    </swiftResponseResponse>
  </soapenv:Body>
</soapenv:Envelope>
</code>```

`

my xslt code is `

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://webservice.sbi.com" exclude-result-prefixes="soapenv xsl  xsd xsi xs ">
  <!--<xsl:output method="xml" indent="yes"/>-->
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <!--<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>-->

  <xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="separator" />
    <xsl:choose>
        <xsl:when test="not(contains($text, $separator))">
            <swiftResponseReturnValue>
                <xsl:value-of select="$text"/>
            </swiftResponseReturnValue>
        </xsl:when>
        <xsl:otherwise>
            <swiftResponseReturnValue>
                <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
            </swiftResponseReturnValue>
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $separator)"/>
                <xsl:with-param name="separator" select="$separator"/>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
  <!--<xsl:template match="soapenv:Envelope/soapenv:Body/xs:swiftResponseResponse/xs:swiftResponseReturn">-->
    <xsl:template match="soapenv:Envelope/soapenv:Body/xs:swiftResponseResponse/xs:swiftResponseReturn">
    <!--<xsl:element name="Root">-->
      <!--<xsl:element name="swiftResponseReturn">
        <xsl:value-of select="xs:swiftResponseResponse/xs:swiftResponseReturn"/>
      </xsl:element>-->
    <xsl:copy>
        <xsl:variable name="tokenize">
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="."/>
                <xsl:with-param name="separator" select="'|'"/>
            </xsl:call-template>
        </xsl:variable>
        <xsl:copy-of select="$tokenize"/>
    </xsl:copy>
    <!--</xsl:element>-->

  </xsl:template>

</xsl:stylesheet>
</code>```

`

and my op is `

```<code><swiftResponseReturn xmlns="http://webservice.sbi.com"
                     xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <swiftResponseReturnValue xmlns="">15617TS006140</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">DC768736</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">13321.49</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">04-05-2017 15:13:03</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">SWIFTINR</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">NA</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue>
</swiftResponseReturn>
</code>```

`

and expected output is
`

```<code><swiftResponseReturn>
   <swiftResponseReturnValue1>15617TS006140</swiftResponseReturnValue1>
   <swiftResponseReturnValue2>DC768736</swiftResponseReturnValue2>
   <swiftResponseReturnValue3>13321.49</swiftResponseReturnValue3>
   <swiftResponseReturnValue4>04-05-2017 15:13:03</swiftResponseReturnValue4>
   <swiftResponseReturnValue5>SWIFTINR</swiftResponseReturnValue5>
   <swiftResponseReturnValue6>NA</swiftResponseReturnValue6>
   <swiftResponseReturnValue7>FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue7>
</swiftResponseReturn>
</code>```

`
i have used template to break code pipe separator format.but i don't want namespaces and also want unique identifier to distinguish each output.

答:
You are using xsl:copy to copy the swiftResponseReturn element, but that will include the namespace. You just need to create a new element name xswiftResponseReturn that is in no namespace.

Try replacing your current template with this..

```<code><xsl:template match="xs:swiftResponseReturn">
  <swiftResponseReturn>
     <xsl:call-template name="tokenize">
         <xsl:with-param name="text" select="."/>
         <xsl:with-param name="separator" select="'|'"/>
     </xsl:call-template>
  </swiftResponseReturn>
</xsl:template>
</code>```

Note that you don't really need the full path of the element in your template match here.

Title: Remove namespace from XSLT output

Body:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <s:Header xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" />
  <soapenv:Body>
    <swiftResponseResponse xmlns="http://webservice.sbi.com">
      <swiftResponseReturn>15617TS006140|DC768736|13321.49|04-05-2017 15:13:03|SWIFTINR|NA|FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturn>
    </swiftResponseResponse>
  </soapenv:Body>
</soapenv:Envelope>

`

my xslt code is `

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://webservice.sbi.com" exclude-result-prefixes="soapenv xsl  xsd xsi xs ">

  <xsl:output omit-xml-declaration="yes" indent="yes"/>

  <xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="separator" />
    <xsl:choose>
        <xsl:when test="not(contains($text, $separator))">
            <swiftResponseReturnValue>
                <xsl:value-of select="$text"/>
            </swiftResponseReturnValue>
        </xsl:when>
        <xsl:otherwise>
            <swiftResponseReturnValue>
                <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
            </swiftResponseReturnValue>
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $separator)"/>
                <xsl:with-param name="separator" select="$separator"/>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

    <xsl:template match="soapenv:Envelope/soapenv:Body/xs:swiftResponseResponse/xs:swiftResponseReturn">

    <xsl:copy>
        <xsl:variable name="tokenize">
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="."/>
                <xsl:with-param name="separator" select="'|'"/>
            </xsl:call-template>
        </xsl:variable>
        <xsl:copy-of select="$tokenize"/>
    </xsl:copy>

  </xsl:template>

</xsl:stylesheet>

`

and my op is `

<swiftResponseReturn xmlns="http://webservice.sbi.com"
                     xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <swiftResponseReturnValue xmlns="">15617TS006140</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">DC768736</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">13321.49</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">04-05-2017 15:13:03</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">SWIFTINR</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">NA</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue>
</swiftResponseReturn>

`

and expected output is
`

<swiftResponseReturn>
   <swiftResponseReturnValue1>15617TS006140</swiftResponseReturnValue1>
   <swiftResponseReturnValue2>DC768736</swiftResponseReturnValue2>
   <swiftResponseReturnValue3>13321.49</swiftResponseReturnValue3>
   <swiftResponseReturnValue4>04-05-2017 15:13:03</swiftResponseReturnValue4>
   <swiftResponseReturnValue5>SWIFTINR</swiftResponseReturnValue5>
   <swiftResponseReturnValue6>NA</swiftResponseReturnValue6>
   <swiftResponseReturnValue7>FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue7>
</swiftResponseReturn>

`
i have used template to break code pipe separator format.but i don't want namespaces and also want unique identifier to distinguish each output.

Body:
You are using xsl:copy to copy the swiftResponseReturn element, but that will include the namespace. You just need to create a new element name xswiftResponseReturn that is in no namespace.

Try replacing your current template with this..

<xsl:template match="xs:swiftResponseReturn">
  <swiftResponseReturn>
     <xsl:call-template name="tokenize">
         <xsl:with-param name="text" select="."/>
         <xsl:with-param name="separator" select="'|'"/>
     </xsl:call-template>
  </swiftResponseReturn>
</xsl:template>

Note that you don't really need the full path of the element in your template match here.


问:
sonarqube transfer module to another project
I have the following situation:

```<code>project A
  - sub module A
  - sub module B
</code>```

I want to move the sub module B to another project:

```<code>project B
  - sub module B
</code>```

But now sonarQube comes up with the following error:

```<code>Module "submoduleB" is already part of project "projectA"
</code>```

I could rename key in project A so that it can be used again in project B but then I probably lose the history. Thus, how can I transfer the module's history to another project?

答:
You can't transfer the history.

You could recreate it using sonar.projectDate (docs), but you'll have to do that for the project as a whole; you can't retroactively insert new data into old analyses.

Body:
I have the following situation:

project A
  - sub module A
  - sub module B

I want to move the sub module B to another project:

project B
  - sub module B

But now sonarQube comes up with the following error:

Module "submoduleB" is already part of project "projectA"

I could rename key in project A so that it can be used again in project B but then I probably lose the history. Thus, how can I transfer the module's history to another project?


问:
Saving data with uniq fields
Problem : for simple example we have next table :

```<code> @Entity
 @Table(name = "books")
 public class Book {
     // other columns
     private Set<Genre> genres = new LinkedHashSet<>();

     @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
     @JoinTable(name = "book_genre", joinColumns = {@JoinColumn(name="book_id")}, inverseJoinColumns = {@JoinColumn(name="genre_id")})
     @OrderBy("name ASC")
     public Set<Genre> getGenres() {
             return genres;
     }
 }
</code>```

Genre table(entity) has unique column name, and this column already contains row with name Example genre, now if i'll try to save new book entity with same genre name :

```<code>  Set<Genre> newBookGenres = new LinkedHashSet<>();
  Genre newBookGenre = new Genre("Example genre"); //new genre with name [Example genre]
  newBookGenres.add(newBookGenre);
  Book book = new Book(newBookGenres);
  session.save(book);
</code>```

it will not save that book and throw exception for unique column (Example genre already exists in genre name).

Question : how can i save entities like that? I think, before saving the book, i could search genre table for that book genre names and if there are (in database) genre with the same name, then just replace book genre object with database genre object. But im not sure if it will work and  believe that there is much simplest way.

答:
You variant ,is good , working variant.It's good practices .You can add some validation in java side , for validate that object already exists , and not call dao method for saving if validation is failing. In this case you don't need to try save entity and catching exception. You save time with validation , as save() method might be not so simple as you showed.

Also you can wrap dao method save() it catch block and work with exception , but it's bad practices as you should work with runtime exception instead of handling it with validation in advance.

As your entity(copy) might be modifyed by another user or users during your saving it might bring db constains problem even if your validation was ok. In this case use version for optimistic lock.

Also, do all checks in advance if you can.

Title: Saving data with uniq fields

Body:
Problem : for simple example we have next table :

 @Entity
 @Table(name = "books")
 public class Book {
     // other columns
     private Set<Genre> genres = new LinkedHashSet<>();

     @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
     @JoinTable(name = "book_genre", joinColumns = {@JoinColumn(name="book_id")}, inverseJoinColumns = {@JoinColumn(name="genre_id")})
     @OrderBy("name ASC")
     public Set<Genre> getGenres() {
             return genres;
     }
 }

Genre table(entity) has unique column name, and this column already contains row with name Example genre, now if i'll try to save new book entity with same genre name :

  Set<Genre> newBookGenres = new LinkedHashSet<>();
  Genre newBookGenre = new Genre("Example genre"); //new genre with name [Example genre]
  newBookGenres.add(newBookGenre);
  Book book = new Book(newBookGenres);
  session.save(book);

it will not save that book and throw exception for unique column (Example genre already exists in genre name).

Question : how can i save entities like that? I think, before saving the book, i could search genre table for that book genre names and if there are (in database) genre with the same name, then just replace book genre object with database genre object. But im not sure if it will work and  believe that there is much simplest way.


问:
storing a function template
I want to store some generic functions for later execution. The problem arises about the arguments of functions. For different types I want to create and store same generic function delegate, but I cannot do it. Below is my version of class to get functions;

```<code>public delegate void CGTaskHandler1<T>(T value) where T : IControllerBase;

public class CGTask
{

    private CGTaskHandler1<IControllerBase> Aksiyon;
    private IControllerBase param;

    public void RegisterCGTask(CGTaskHandler1<IControllerBase> aFunc, IControllerBase aParam)
    {
        Aksiyon = aFunc;
        param = aParam;
    }

    public void ExecuteCGTask()
    {
        try
        {
            Aksiyon(param);
        }
        catch (Exception ex)
        {
            Logger.SetLog("action execution failed ", LogType.error, ex.Message)
        }
    }
}
</code>```

by this class I used an interface to collect every different type of argument under same name, however compiler wants exact same type and interface type seems not helping.

```<code>    private void LoadScene(cScene ascn)
    {
        ascn.LoadScene();
    }

    public CGTask GetTask(String btnName)
    {
        CGTask back = new CGTask();
        CGTaskHandler1<IControllerBase> alomelo = LoadScene; // type mismatch
        back.RegisterCGTask(alomelo, thisScene);

        //CGTask2<cScene> back = new CGTask2<cScene>();
        //CGTaskHandler1<cScene> alomelo = LoadScene;
        //back.RegisterCGTask(alomelo, thisScene);

        return back;
    }
</code>```

so I changed my cgtask class to a generic class, so, argument type would be definite since when class is instantiated.

```<code>public class CGTask2<T>
{

    private CGTaskHandler1<T> Aksiyon;
    private T param;

    public void RegisterCGTask(CGTaskHandler1<T> aFunc, T aParam)
    {
        Aksiyon = aFunc;
        param = aParam;
    }

    public void ExecuteCGTask()
    {
        try
        {
            Aksiyon(param);
        }
        catch (Exception ex)
        {
            Logger.SetLog("action execution failed ", LogType.error, ex.Message);
        }
    }
}
</code>```

however same problem I confront when I want to collect them in a list.

```<code> List<CGTask2<IControllerBase>> gorevler = new List<CGTask2<IControllerBase>>();
  gorevler.Add(new CGTask2<cScene>()); // type mismatch
</code>```

I need a way to keep functions like objects. Every time I make use of a generic function delegate I need to specify the type, and types of generic functions are not convertible. Is there a way to do this, keeping references to functions and collecting these references as objects?

```<code> public interface IControllerBase
    {
        void GetTalker();
        void InitiliazeTalker();
    }

    public class cControllerBase : IControllerBase
    {
        public cControllerBase Parent=null;

        protected Talker tk;

        protected void GetTalker()
        {
            tk = Talker.Instance; // not initialized yet
        }

        protected void InitiliazeTalker()
        {
            tk.InitializeReTalk();
        }

    }

    public class cScene : cControllerBase, IControllerBase
    {
        public String ID;
        public String ScenePath;
        public String SceneName;
        public int Slot;
        public String DBParent;
        public List<cAnimation> Animations;
        public List<cExport> Exports;
        public Boolean IsActive;

        public cScene()
        {
            GetTalker();
            Animations = new List<cAnimation>();
            Exports = new List<cExport>();
            //  ID = Guid.NewGuid().ToString();
            IsActive = false;
        }

        public Boolean ParseXml(String pXmlPath)
        {
            if (String.IsNullOrEmpty(pXmlPath)) return false;
            XmlDocument xdoc = new XmlDocument();
            XmlNodeList anims = null;
            XmlNodeList exps = null;
            try
            {
                xdoc.Load(pXmlPath);
                anims = xdoc.SelectNodes("//scene_description/animations/animation");
                exps = xdoc.SelectNodes("//scene_description/exports/export");
            }
            catch (Exception ex)
            {
                Logger.SetLog("xml parse error", LogType.error, ex.Message);
                return false;
            }

            cAnimation tempanim;
            cExport tempexport;

            foreach (XmlNode x in anims)
            {
                tempanim = new cAnimation();
                foreach (XmlAttribute y in x.Attributes)
                {
                    switch (y.Name)
                    {
                        case "name":
                            {
                                tempanim.AnimationName = y.Value;
                                break;
                            }
                        case "duration":
                            {
                                tempanim.AnimationDuration = Globals.GetIntValue(y.Value);
                                break;
                            }
                        case "end_animation_time":
                            {
                                tempanim.AnimationEndTime = Globals.GetIntValue(y.Value);
                                break;
                            }
                        case "start_animation_time":
                            {
                                tempanim.AnimationStartTime = Globals.GetIntValue(y.Value);
                                break;
                            }
                    }
                }
                tempanim.Parent = this;
                Animations.Add(tempanim);
            }

            foreach (XmlNode x in exps)
            {
                tempexport = new cExport();
                foreach (XmlAttribute y in x.Attributes)
                {
                    switch (y.Name)
                    {
                        case "name":
                            {
                                tempexport.ExportName = y.Value;
                                break;
                            }
                        case "type":
                            {
                                switch (y.Value)
                                {
                                    case "String":
                                        {
                                            tempexport.ExportType = ExportDataType.tString;
                                            break;
                                        }
                                    case "File":
                                        {
                                            tempexport.ExportType = ExportDataType.tFile;
                                            break;
                                        }
                                    case "Float":
                                        {
                                            tempexport.ExportType = ExportDataType.tFloat;
                                            break;
                                        }
                                    case "Int":
                                        {
                                            tempexport.ExportType = ExportDataType.tInt;
                                            break;
                                        }
                                    case "Bool":
                                        {
                                            tempexport.ExportType = ExportDataType.tBool;
                                            break;
                                        }
                                }
                                break;
                            }
                        case "value":
                            {
                                tempexport.ExportValue = y.Value;
                                break;
                            }
                    }
                }
                tempexport.Parent = this;
                Exports.Add(tempexport);
            }

            return true;

        }

        public void ActivateScene()
        {
            tk.ActivateScene(Slot, SceneName);
            IsActive = true;
        }

        public void DeactivateScene()
        {
            // to do
            // tk'dan aktif scene listesi yapıp kontrol edebiliyor musun?
            tk.DeactivateScene(Slot);
            IsActive = false;
        }

        public Boolean IsSceneLoaded()
        {
            Boolean back = false;
            back = tk.IsSceneLoaded(SceneName);
            return back;
        }

        public void LoadScene()
        {
            tk.LoadScene(SceneName);
        }

        public void UnloadScene()
        {
            tk.UnloadScene(SceneName);
        }

        public void SetSceneName(String strxmlPath)
        {
            ScenePath = strxmlPath;
            SceneName = strxmlPath.Substring(0, strxmlPath.LastIndexOf('\\'));
            SceneName = SceneName.Replace('\\', '/');
            SceneName = SceneName.Substring(SceneName.IndexOf("Projects") + 9);

        }
    }
</code>```

答:
Well a CGTask2<cScene> is a completely different type to CGTask2<IControllerBase>, you can't equate the two. You would have to have a list of, for example, ITask and make CGTask2 implement that. For example:

```<code>public interface ITask {}

public class CGTask2<T> : ITask
{
    //snip
}
</code>```

And now you can do this:

```<code>List<ITask> gorevler = new List<ITask>();
gorevler.Add(new CGTask2<cScene>());
</code>```

Title: storing a function template

Body:
I want to store some generic functions for later execution. The problem arises about the arguments of functions. For different types I want to create and store same generic function delegate, but I cannot do it. Below is my version of class to get functions;

public delegate void CGTaskHandler1<T>(T value) where T : IControllerBase;

public class CGTask
{

    private CGTaskHandler1<IControllerBase> Aksiyon;
    private IControllerBase param;

    public void RegisterCGTask(CGTaskHandler1<IControllerBase> aFunc, IControllerBase aParam)
    {
        Aksiyon = aFunc;
        param = aParam;
    }

    public void ExecuteCGTask()
    {
        try
        {
            Aksiyon(param);
        }
        catch (Exception ex)
        {
            Logger.SetLog("action execution failed ", LogType.error, ex.Message)
        }
    }
}

by this class I used an interface to collect every different type of argument under same name, however compiler wants exact same type and interface type seems not helping.

    private void LoadScene(cScene ascn)
    {
        ascn.LoadScene();
    }

    public CGTask GetTask(String btnName)
    {
        CGTask back = new CGTask();
        CGTaskHandler1<IControllerBase> alomelo = LoadScene; // type mismatch
        back.RegisterCGTask(alomelo, thisScene);

        //CGTask2<cScene> back = new CGTask2<cScene>();
        //CGTaskHandler1<cScene> alomelo = LoadScene;
        //back.RegisterCGTask(alomelo, thisScene);

        return back;
    }

so I changed my cgtask class to a generic class, so, argument type would be definite since when class is instantiated.

public class CGTask2<T>
{

    private CGTaskHandler1<T> Aksiyon;
    private T param;

    public void RegisterCGTask(CGTaskHandler1<T> aFunc, T aParam)
    {
        Aksiyon = aFunc;
        param = aParam;
    }

    public void ExecuteCGTask()
    {
        try
        {
            Aksiyon(param);
        }
        catch (Exception ex)
        {
            Logger.SetLog("action execution failed ", LogType.error, ex.Message);
        }
    }
}

however same problem I confront when I want to collect them in a list.

 List<CGTask2<IControllerBase>> gorevler = new List<CGTask2<IControllerBase>>();
  gorevler.Add(new CGTask2<cScene>()); // type mismatch

I need a way to keep functions like objects. Every time I make use of a generic function delegate I need to specify the type, and types of generic functions are not convertible. Is there a way to do this, keeping references to functions and collecting these references as objects?

 public interface IControllerBase
    {
        void GetTalker();
        void InitiliazeTalker();
    }

    public class cControllerBase : IControllerBase
    {
        public cControllerBase Parent=null;

        protected Talker tk;

        protected void GetTalker()
        {
            tk = Talker.Instance; // not initialized yet
        }

        protected void InitiliazeTalker()
        {
            tk.InitializeReTalk();
        }

    }

    public class cScene : cControllerBase, IControllerBase
    {
        public String ID;
        public String ScenePath;
        public String SceneName;
        public int Slot;
        public String DBParent;
        public List<cAnimation> Animations;
        public List<cExport> Exports;
        public Boolean IsActive;

        public cScene()
        {
            GetTalker();
            Animations = new List<cAnimation>();
            Exports = new List<cExport>();
            //  ID = Guid.NewGuid().ToString();
            IsActive = false;
        }

        public Boolean ParseXml(String pXmlPath)
        {
            if (String.IsNullOrEmpty(pXmlPath)) return false;
            XmlDocument xdoc = new XmlDocument();
            XmlNodeList anims = null;
            XmlNodeList exps = null;
            try
            {
                xdoc.Load(pXmlPath);
                anims = xdoc.SelectNodes("//scene_description/animations/animation");
                exps = xdoc.SelectNodes("//scene_description/exports/export");
            }
            catch (Exception ex)
            {
                Logger.SetLog("xml parse error", LogType.error, ex.Message);
                return false;
            }

            cAnimation tempanim;
            cExport tempexport;

            foreach (XmlNode x in anims)
            {
                tempanim = new cAnimation();
                foreach (XmlAttribute y in x.Attributes)
                {
                    switch (y.Name)
                    {
                        case "name":
                            {
                                tempanim.AnimationName = y.Value;
                                break;
                            }
                        case "duration":
                            {
                                tempanim.AnimationDuration = Globals.GetIntValue(y.Value);
                                break;
                            }
                        case "end_animation_time":
                            {
                                tempanim.AnimationEndTime = Globals.GetIntValue(y.Value);
                                break;
                            }
                        case "start_animation_time":
                            {
                                tempanim.AnimationStartTime = Globals.GetIntValue(y.Value);
                                break;
                            }
                    }
                }
                tempanim.Parent = this;
                Animations.Add(tempanim);
            }

            foreach (XmlNode x in exps)
            {
                tempexport = new cExport();
                foreach (XmlAttribute y in x.Attributes)
                {
                    switch (y.Name)
                    {
                        case "name":
                            {
                                tempexport.ExportName = y.Value;
                                break;
                            }
                        case "type":
                            {
                                switch (y.Value)
                                {
                                    case "String":
                                        {
                                            tempexport.ExportType = ExportDataType.tString;
                                            break;
                                        }
                                    case "File":
                                        {
                                            tempexport.ExportType = ExportDataType.tFile;
                                            break;
                                        }
                                    case "Float":
                                        {
                                            tempexport.ExportType = ExportDataType.tFloat;
                                            break;
                                        }
                                    case "Int":
                                        {
                                            tempexport.ExportType = ExportDataType.tInt;
                                            break;
                                        }
                                    case "Bool":
                                        {
                                            tempexport.ExportType = ExportDataType.tBool;
                                            break;
                                        }
                                }
                                break;
                            }
                        case "value":
                            {
                                tempexport.ExportValue = y.Value;
                                break;
                            }
                    }
                }
                tempexport.Parent = this;
                Exports.Add(tempexport);
            }

            return true;

        }

        public void ActivateScene()
        {
            tk.ActivateScene(Slot, SceneName);
            IsActive = true;
        }

        public void DeactivateScene()
        {
            // to do
            // tk'dan aktif scene listesi yapıp kontrol edebiliyor musun?
            tk.DeactivateScene(Slot);
            IsActive = false;
        }

        public Boolean IsSceneLoaded()
        {
            Boolean back = false;
            back = tk.IsSceneLoaded(SceneName);
            return back;
        }

        public void LoadScene()
        {
            tk.LoadScene(SceneName);
        }

        public void UnloadScene()
        {
            tk.UnloadScene(SceneName);
        }

        public void SetSceneName(String strxmlPath)
        {
            ScenePath = strxmlPath;
            SceneName = strxmlPath.Substring(0, strxmlPath.LastIndexOf('\\'));
            SceneName = SceneName.Replace('\\', '/');
            SceneName = SceneName.Substring(SceneName.IndexOf("Projects") + 9);

        }
    }

Body:
Well a CGTask2<cScene> is a completely different type to CGTask2<IControllerBase>, you can't equate the two. You would have to have a list of, for example, ITask and make CGTask2 implement that. For example:

public interface ITask {}

public class CGTask2<T> : ITask
{
    //snip
}

And now you can do this:

List<ITask> gorevler = new List<ITask>();
gorevler.Add(new CGTask2<cScene>());


问:
Removing all spaces in an ArrayList. Java
I am taking input from a .txt file and storing it into an ArrayList. I need to get rid of all the spaces so I can parse the ArrayList to an <Integer>. I am going to post commented out sections so you can see what i have tried to use to do this. Thank you. If you can give me somewhere to look that would be great.

```<code>import java.io.*;
import java.util.*;

public class LabWriterReadre {

  public static void main(String [] args){
       BufferedReader br = null;
       BufferedWriter bw = null;
      // fileWriter = new FileWriter("output.txt",false);
       ArrayList<String> storage = new ArrayList<String>();
       ArrayList<String> convertToInt = new ArrayList<String>();
       ArrayList<Integer> matrix = new ArrayList<Integer>();
         String strLine = "";
        int row1,col1,row2,col2;

        try {
            br = new BufferedReader( new FileReader("C:/Users/jeremiahlukus/Desktop/New folder/jj.txt"));
            while( (strLine = br.readLine()) != null)
            {
                System.out.println(strLine);
                storage.add(strLine);
            }
        } catch (FileNotFoundException e) {
            System.err.println("Unable to find the file: fileName");
        } catch (IOException e) {
            System.err.println("Unable to read the file: fileName");
        }

        /*
        String[] trimmedArray = new String[string.size()];
        for (int i = 0; i < string.size(); i++)
        {
            trimmedArray[i] = string[i].trim();
            string.removeAll(Arrays.asList(null,""));
        }
        */
        //string.removeAll(Collections.singleton(""));
       // string.removeAll(Arrays.asList(null,"")

      for (String str : storage)
      {
         if (//str != " ")
             !str.isEmpty())
         {
          convertToInt.add(str);
          //convertToInt.trim();

         }
     }

System.out.println(convertToInt);
}

 /*

       row1 = Integer.parseInt(convertToInt.get(0));
       col1 = Integer.parseInt(convertToInt.get(1));
       row2 = Integer.parseInt(convertToInt.get(2));
       col2 = Integer.parseInt(convertToInt.get(3));

       int[][] matrix1=new int[row1][col1];
       int[][] matrix2=new int[row2][col2];

     */

      //  System.out.println(row1);

        /*
</code>```

This is the .txt file I am reading, _ means space

```<code>3___________3
3_4

1 ______2 3
4_5 _6
7 _8 _9

1 _2_ 3_ 4
5 _6 _7 _8
9_ 10_ 11_ 12
</code>```

This is the ArrayList printed out

```<code>[3______3,_3 _4,__ 1_______2_ 3 , ___4 _5 _6, 7_ 8 _9, 1_ 2_ 3_ 4, 5 _6_ 7_ 8, 9 _10_ 11_ 12]
</code>```

This is what I want to happen

```<code>[3,3,3,4,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,10,11,12]
</code>```

答:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {

  public static void main(String[] args)
  {

      String total="";
      List list=new ArrayList();
    list.add("3______3");
    list.add("_3 _4");
    list.add("__ 1_______2_ 3");
    list.add("3 ");
    list.add(" ___4 _5 _6");
    list.add(" 7_ 8 _9");

    list.add(" 1_ 2_ 3_ 4");
   list.add(" 5 _6_ 7_ 8");
   list.add(" 9 _10_ 11_ 12");

      String firstname1 = list.toString();
      String regex = "[0-9]+";
      firstname1 = firstname1.replaceAll("_", ",");

      firstname1 = firstname1.replace(",", ",");

      String str = firstname1.toString().replaceAll("\\s+", ",").replace("[", "").replace("]", "");

      String arr[] = str.split(",");

      for (int i = 0; i < arr.length; i++) {
          if (arr[i].matches(regex)) {

              total += arr[i] + ",";
          }
      }
      total = total.substring(0, total.length() - 1);
      List finalList = Arrays.asList(total);

      System.out.println(finalList);
     //output-->> [3,3,3,4,1,2,3,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,10,11,12]
  }
}
```

Body:
I am taking input from a .txt file and storing it into an ArrayList. I need to get rid of all the spaces so I can parse the ArrayList to an <Integer>. I am going to post commented out sections so you can see what i have tried to use to do this. Thank you. If you can give me somewhere to look that would be great.

import java.io.*;
import java.util.*;

public class LabWriterReadre {

  public static void main(String [] args){
       BufferedReader br = null;
       BufferedWriter bw = null;
      // fileWriter = new FileWriter("output.txt",false);
       ArrayList<String> storage = new ArrayList<String>();
       ArrayList<String> convertToInt = new ArrayList<String>();
       ArrayList<Integer> matrix = new ArrayList<Integer>();
         String strLine = "";
        int row1,col1,row2,col2;

        try {
            br = new BufferedReader( new FileReader("C:/Users/jeremiahlukus/Desktop/New folder/jj.txt"));
            while( (strLine = br.readLine()) != null)
            {
                System.out.println(strLine);
                storage.add(strLine);
            }
        } catch (FileNotFoundException e) {
            System.err.println("Unable to find the file: fileName");
        } catch (IOException e) {
            System.err.println("Unable to read the file: fileName");
        }

        /*
        String[] trimmedArray = new String[string.size()];
        for (int i = 0; i < string.size(); i++)
        {
            trimmedArray[i] = string[i].trim();
            string.removeAll(Arrays.asList(null,""));
        }
        */
        //string.removeAll(Collections.singleton(""));
       // string.removeAll(Arrays.asList(null,"")

      for (String str : storage)
      {
         if (//str != " ")
             !str.isEmpty())
         {
          convertToInt.add(str);
          //convertToInt.trim();

         }
     }

System.out.println(convertToInt);
}

 /*

       row1 = Integer.parseInt(convertToInt.get(0));
       col1 = Integer.parseInt(convertToInt.get(1));
       row2 = Integer.parseInt(convertToInt.get(2));
       col2 = Integer.parseInt(convertToInt.get(3));

       int[][] matrix1=new int[row1][col1];
       int[][] matrix2=new int[row2][col2];

     */

      //  System.out.println(row1);

        /*

This is the .txt file I am reading, _ means space

3___________3
3_4

1 ______2 3
4_5 _6
7 _8 _9

1 _2_ 3_ 4
5 _6 _7 _8
9_ 10_ 11_ 12

This is the ArrayList printed out

[3______3,_3 _4,__ 1_______2_ 3 , ___4 _5 _6, 7_ 8 _9, 1_ 2_ 3_ 4, 5 _6_ 7_ 8, 9 _10_ 11_ 12]

This is what I want to happen

[3,3,3,4,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,10,11,12]


问:
Specific example: Is it possible to aviod the use of a global variable?
I have the following program and the variable(dictionary) in question is player_info that stores player information (name and goals). In order to solve the error that results currently, I simply need to make player_info a global variable, but I was wondering if stackoverflow experts could suggest or discuss the possibility of alternate ways of solving this problem WITHOUT the use of global variables.

Code

```<code>#FOOTBALL COACH app

#The program allows a user to enter a number of players (their names and goals scored) and then search for a player, returning their average goals for the three matches

import sys
def main():
 mainmenu()

def mainmenu():

  print("=====WELCOME to the MAIN MENU=============")
  print("""
  1..........Add New Players & Goals
  2..........Search by Players
  3..........Quit

  =========================================
  """)

  choice=int(input("Enter choice:"))
  if choice==1:
    addplayers()
  elif choice==2:
    searchplayer(player_info)
  elif choice==3:
    sys.exit()
  else:
    print("You must make a valid choice - 1, 2 or 3")

def addplayers():

  player_info= {} #create a dictionary that stores the player name: player goals

  num_players = int(input("Please enter number of players you wish to enter:"))
  print ("You are entering %s players" %num_players)
  player_data = ['Match 1 goals : ', 'Match 2 goals : ', 'Match 3 goals : ']
  for i in range(0,num_players):
      player_name = input("Enter Player Name :")
      player_info[player_name] = {}
      for entry in player_data:
          player_info[player_name][entry] = int(input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.

  mainmenu()

def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")

main()
</code>```

As mentioned, I am aware that re-writing this in the addplayer() sub would fix the problem:

```<code>global player_info
player_info = {} #create a dictionary that stores the player name: player goals
</code>```

...I am looking for ways to solve the problem WITHOUT the use of global variables.

Update:

One answer below using return player_info is what I would like to go with, but it doesn't quite work yet. Also, I need to return to the main menu each time a player is added, not quite sure how to do this, without a mainmenu call each time. Any suggestions? https://repl.it/JRl5/1

答:
You can use return inside your function to avoid using global variables. A simple example is shown below:

```<code>def addplayers():

    player_info= {}

    name = input("Enter Name: ")
    test = int(input("Enter a number: "))

    player_info[name] = test

    return player_info

player_info = addplayers()
</code>```

If you then wanted to use this in another function you would just pass in the dictionary as an argument to that function:

```<code>def searchplayers(player_info):

    print (player_info)
</code>```

Note: An interesting answer on "Why are global variables evil?"

Edit:

Your addplayers() was calling mainmenu() which itself was being calling within mainmenu(). This is a recursive function and it might be best to avoid these unless there's a good reason for having it. I would put the contents of mainmenu inside a while loop until some condition is met. The complete code is shown below (I have removed the main function as it wasn't really doing anything):

```<code>def mainmenu():

    stop = False

    while stop == False:

        print("=====WELCOME to the MAIN MENU=============")
        print("""
        1..........Add New Players & Goals
        2..........Search by Players
        3..........Quit

        =========================================
        """)

        choice=int(input("Enter choice:"))
        if choice==1:
            player_info = addplayers()
        elif choice==2:
            searchplayer(player_info)
        elif choice==3:
            print ("Exit the main menu")
            stop = True
        else:
            print("You must make a valid choice - 1, 2 or 3")

def addplayers():

    player_info= {} #create a dictionary that stores the player name: player goals

    num_players = int(input("Please enter number of players you wish to enter:"))
    print ("You are entering %s players" %num_players)
    player_data = ['Match 1 goals : ', 'Match 2 goals : ', 'Match 3 goals : ']

    for i in range(0,num_players):
        player_name = input("Enter Player Name :")
        player_info[player_name] = {}

        for entry in player_data:
            player_info[player_name][entry] = int(input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.

    return player_info

def searchplayer(player_info):
    print("===============SEARCH by player: Calculate average goals==================")
    name = input("Player name : ")
    if name in player_info.keys():
        #print student_info
        print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
    else:
        print("Please enter a valid player name:")

mainmenu()
</code>```

Body:
I have the following program and the variable(dictionary) in question is player_info that stores player information (name and goals). In order to solve the error that results currently, I simply need to make player_info a global variable, but I was wondering if stackoverflow experts could suggest or discuss the possibility of alternate ways of solving this problem WITHOUT the use of global variables.

Code

#FOOTBALL COACH app

#The program allows a user to enter a number of players (their names and goals scored) and then search for a player, returning their average goals for the three matches

import sys
def main():
 mainmenu()

def mainmenu():

  print("=====WELCOME to the MAIN MENU=============")
  print("""
  1..........Add New Players & Goals
  2..........Search by Players
  3..........Quit

  =========================================
  """)

  choice=int(input("Enter choice:"))
  if choice==1:
    addplayers()
  elif choice==2:
    searchplayer(player_info)
  elif choice==3:
    sys.exit()
  else:
    print("You must make a valid choice - 1, 2 or 3")

def addplayers():

  player_info= {} #create a dictionary that stores the player name: player goals

  num_players = int(input("Please enter number of players you wish to enter:"))
  print ("You are entering %s players" %num_players)
  player_data = ['Match 1 goals : ', 'Match 2 goals : ', 'Match 3 goals : ']
  for i in range(0,num_players):
      player_name = input("Enter Player Name :")
      player_info[player_name] = {}
      for entry in player_data:
          player_info[player_name][entry] = int(input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.

  mainmenu()

def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")

main()

As mentioned, I am aware that re-writing this in the addplayer() sub would fix the problem:

global player_info
player_info = {} #create a dictionary that stores the player name: player goals

...I am looking for ways to solve the problem WITHOUT the use of global variables.

Update:

One answer below using return player_info is what I would like to go with, but it doesn't quite work yet. Also, I need to return to the main menu each time a player is added, not quite sure how to do this, without a mainmenu call each time. Any suggestions? https://repl.it/JRl5/1

Body:
You can use return inside your function to avoid using global variables. A simple example is shown below:

def addplayers():

    player_info= {}

    name = input("Enter Name: ")
    test = int(input("Enter a number: "))

    player_info[name] = test

    return player_info

player_info = addplayers()

If you then wanted to use this in another function you would just pass in the dictionary as an argument to that function:

def searchplayers(player_info):

    print (player_info)

Note: An interesting answer on "Why are global variables evil?"

Edit:

Your addplayers() was calling mainmenu() which itself was being calling within mainmenu(). This is a recursive function and it might be best to avoid these unless there's a good reason for having it. I would put the contents of mainmenu inside a while loop until some condition is met. The complete code is shown below (I have removed the main function as it wasn't really doing anything):

def mainmenu():

    stop = False

    while stop == False:

        print("=====WELCOME to the MAIN MENU=============")
        print("""
        1..........Add New Players & Goals
        2..........Search by Players
        3..........Quit

        =========================================
        """)

        choice=int(input("Enter choice:"))
        if choice==1:
            player_info = addplayers()
        elif choice==2:
            searchplayer(player_info)
        elif choice==3:
            print ("Exit the main menu")
            stop = True
        else:
            print("You must make a valid choice - 1, 2 or 3")

def addplayers():

    player_info= {} #create a dictionary that stores the player name: player goals

    num_players = int(input("Please enter number of players you wish to enter:"))
    print ("You are entering %s players" %num_players)
    player_data = ['Match 1 goals : ', 'Match 2 goals : ', 'Match 3 goals : ']

    for i in range(0,num_players):
        player_name = input("Enter Player Name :")
        player_info[player_name] = {}

        for entry in player_data:
            player_info[player_name][entry] = int(input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.

    return player_info

def searchplayer(player_info):
    print("===============SEARCH by player: Calculate average goals==================")
    name = input("Player name : ")
    if name in player_info.keys():
        #print student_info
        print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
    else:
        print("Please enter a valid player name:")

mainmenu()


问:
idx_scan is very low in PostgreSQL statistic
I would like to ask help in PostgresSQL optimization.

I have a medium sized table (about 2.000.000 records), and I wrote a very simple query like:

```<code>SELECT COUNT (DISTINCT(user_id))
FROM fp left outer join sd ON fp.session_id = sd.session_id
WHERE fp.license_key = 'license'  AND sd.device_hash = 'hash'
</code>```

I have simple indexes on 'license_key', 'user_id' and 'device_hash' (3 indexes)
The executor does not want to use my license_key index because there are more than 700.000 matches in the table and Seq Scan is better choice.

```<code>Aggregate  (cost=396247.61..396247.62 rows=1 width=17)

  ->  Hash Join  (cost=99668.54..396152.13 rows=38195 width=17)

        Hash Cond: ((fp.session_id)::text = (sd.session_id)::text)

        ->  Seq Scan on fp  (cost=0.00..293450.55 rows=706957 width=45)

              Filter: ((license_key)::text = 'license'::text)

        ->  Hash  (cost=98678.10..98678.10 rows=79235 width=28)

              ->  Bitmap Heap Scan on sd  (cost=2902.50..98678.10 rows=79235 width=28)

                    Recheck Cond: ((device_hash)::text = 'hash'::text)

                    ->  Bitmap Index Scan on "sd.device_hash_btree_idx"  (cost=0.00..2882.69 rows=79235 width=0)

                          Index Cond: ((device_hash)::text = 'hash'::text)
</code>```

I checked my statistics:

```<code>select * from where indexrelname= 'fp_license_key_btree_idx'

relid   |   indexrelname    |   idx_scan   |   idx_tup_read    |   idx_fetch
----------------------------------------------------------------------------
16430   |fp.license_key_btree_idx | 451    |    13641445       |    13641445
</code>```

Can you give me advices ? How Can i improve my idx_scan? Thank you

答:
You could try with CTE and new index:</p>

```<code>CREATE INDEX ON fp USING btree(session_id); --maybe cover license_key as well, but doubt it

WITH s AS (SELECT session_id FROM sd WHERE sd.device_hash = 'hash'),
     f AS (SELECT user_id, session_id
             FROM fp
            WHERE fp.license_key = 'license'
              AND session_id = ANY((SELECT array_agg(session_id) FROM s)::int[]))
SELECT COUNT (DISTINCT(user_id))
FROM f
JOIN s ON f.session_id = s.session_id; --your left join is not left join anyway
</code>```

Body:
I would like to ask help in PostgresSQL optimization.

I have a medium sized table (about 2.000.000 records), and I wrote a very simple query like:

SELECT COUNT (DISTINCT(user_id))
FROM fp left outer join sd ON fp.session_id = sd.session_id
WHERE fp.license_key = 'license'  AND sd.device_hash = 'hash'

I have simple indexes on 'license_key', 'user_id' and 'device_hash' (3 indexes)
The executor does not want to use my license_key index because there are more than 700.000 matches in the table and Seq Scan is better choice.

Aggregate  (cost=396247.61..396247.62 rows=1 width=17)

  ->  Hash Join  (cost=99668.54..396152.13 rows=38195 width=17)

        Hash Cond: ((fp.session_id)::text = (sd.session_id)::text)

        ->  Seq Scan on fp  (cost=0.00..293450.55 rows=706957 width=45)

              Filter: ((license_key)::text = 'license'::text)

        ->  Hash  (cost=98678.10..98678.10 rows=79235 width=28)

              ->  Bitmap Heap Scan on sd  (cost=2902.50..98678.10 rows=79235 width=28)

                    Recheck Cond: ((device_hash)::text = 'hash'::text)

                    ->  Bitmap Index Scan on "sd.device_hash_btree_idx"  (cost=0.00..2882.69 rows=79235 width=0)

                          Index Cond: ((device_hash)::text = 'hash'::text)

I checked my statistics:

select * from where indexrelname= 'fp_license_key_btree_idx'

relid   |   indexrelname    |   idx_scan   |   idx_tup_read    |   idx_fetch
----------------------------------------------------------------------------
16430   |fp.license_key_btree_idx | 451    |    13641445       |    13641445

Can you give me advices ? How Can i improve my idx_scan? Thank you

Body:
You could try with CTE and new index:

CREATE INDEX ON fp USING btree(session_id); --maybe cover license_key as well, but doubt it

WITH s AS (SELECT session_id FROM sd WHERE sd.device_hash = 'hash'),
     f AS (SELECT user_id, session_id
             FROM fp
            WHERE fp.license_key = 'license'
              AND session_id = ANY((SELECT array_agg(session_id) FROM s)::int[]))
SELECT COUNT (DISTINCT(user_id))
FROM f
JOIN s ON f.session_id = s.session_id; --your left join is not left join anyway


问:
Google Tag Manager and property per language in Analytics
I have a multilanguage site and my plan is to track every language apart.
Example:

```<code>domain.com

domain.com/en/

domain.com/de/

domain.com/fr/
</code>```

For now, I have one GA Property and one GTM Container for the whole site. I was thinking of creating multiple Properties in GA for every language and one for all together. So that would look like this:

```<code>domain.com -> GA-1

domain.com/en/ -> GA2

domain.com/de/ -> GA3

domain.com/fr/ -> GA4
</code>```

Now in GTM I would add to the container one Tag for each Property and create a trigger for each property. GA-1 trigger fires on all pages, GA-2 trigger fires on some page views that page path contains /en/, GA-3 trigger fires on some page views that page path contains /de/...

Is this the best practice and would this work like this? or is there another method to achieve this goal? Or is it enough to create some Views in GA and create some filters for each language?

The goal is to track every language in a different property so the starting point is always the language. Maybe there are also different conversions in the properties.

答:
In this situation, the best practice is to only have a single GA property that tracks the whole site. If you then want to only report on the data from a specific section of your site (i.e. a specific language) then you would use GA views (and filters) to achieve this. You would filter based on the Page dimension (e.g. Page starts with /fr).

There is no benefit to creating a property for each language except maybe to prevent you from going above the 10 million hits per property per month limit of the free version of GA. On the other hand, there is a benefit to tracking the entire site in a single property. The main benefit is that it allows you to perform cross-language analysis.

Body:
I have a multilanguage site and my plan is to track every language apart.
Example:

domain.com

domain.com/en/

domain.com/de/

domain.com/fr/

For now, I have one GA Property and one GTM Container for the whole site. I was thinking of creating multiple Properties in GA for every language and one for all together. So that would look like this:

domain.com -> GA-1

domain.com/en/ -> GA2

domain.com/de/ -> GA3

domain.com/fr/ -> GA4

Now in GTM I would add to the container one Tag for each Property and create a trigger for each property. GA-1 trigger fires on all pages, GA-2 trigger fires on some page views that page path contains /en/, GA-3 trigger fires on some page views that page path contains /de/...

Is this the best practice and would this work like this? or is there another method to achieve this goal? Or is it enough to create some Views in GA and create some filters for each language?

The goal is to track every language in a different property so the starting point is always the language. Maybe there are also different conversions in the properties.


问:
Cleaner way to add large block of HTML in javascript in rails
I have a rails app along with angular, and I need to populate a large block of HTML so that it can fill in default text for textarea tag. Currently what I did was add the text like this

```<code>"<div class='navbar navbar-default letter-header hidden-sm hidden-xs'>\n" +
    "  <div class='container'>\n" +
    "    <div class='letter-navbar-header navbar-header'>\n" +
    "      <a href='/'><img src='/assets/logo.png' class='letters-logo navbar-brand'></a>\n" +
    "    </div>\n" +

    "    <div class='navbar-header header-text'>\n" +
    "      <div class='navbar-text'>\n" +
    "        "text" + "\n" +
    "      </div>\n" +
    "    </div>\n" +
    "    <div class='letter-navbar-header navbar-header'>\n" +
    "      <a href='/'>\n" +
    "        <img src='' class='second-logo'>\n" +
    "      </a>\n" +
    "    </div>\n" +
    "    <div class='navbar-header navbar-right'>\n" +
    "      {{ user_login }}" + "\n" +
    "    </div>\n" +
    "  </div>\n" +
    "</div>\n"
</code>```

I would like to know if there is a cleaner way to do it. I have tried using js.erb file with the render function like this

```<code><%= j render('navbar') %>
</code>```

but placed it in the asset folder so the render function is not working https://stackoverflow.com/a/8370847/1087841. I would like to know if there is a better way to do it.

[EDIT]
The js.erb file is actually an angular factory which has default HTML for the navbar, which then can be used by the angular controller to render default data. The factory file is then also gets added to application.js as a require.
this is the textarea that needs default html

```<code><textarea name="t[navigation]" id="input-navigation-bar" ng-model="t.navigation_bar" class="form-control" rows="10"></textarea>
</code>```

I could have placed the value tag with the default html but it has ng-model so nothing gets displayed. So I created a factory for the default data. Now the factory lives in /assets and has a //= require 'default_html_factory' in application.js.

答:
I finally found a way to do it. In the erb page I added

```<code><script>
  <%= render 'style_factory.js.erb' %>
</script>
</code>```

and in the factory I added this

```<code>this.ngapp.factory('TenantStyle', function() {
  return {
    header: "<%= j render 'navbar' %>"
  }
});
</code>```

and in the _navbar.html.erb file I added this

```<code><div class="navbar navbar-default letter-header hidden-sm hidden-xs">
  <div class="container">
    <div class="letter-navbar-header navbar-header">
    </div>

    <div class="navbar-header header-text">
      <div class="navbar-text">
      </div>
    </div>
    <div class='letter-navbar-header navbar-header'>
      <a href='/'>
        <img src='' class='second-logo'>
      </a>
    </div>

    <div class="navbar-header navbar-right">
    </div>
  </div>
</div>
</code>```

and now I can call the factory in angular and get the header value.

Body:
I have a rails app along with angular, and I need to populate a large block of HTML so that it can fill in default text for textarea tag. Currently what I did was add the text like this

"
\n" +
    "
\n" +
    "
\n" +
    "      \n" +
    "
\n" +

    "
\n" +
    "
\n" +
    "        "text" + "\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "      \n" +
    "        \n" +
    "      \n" +
    "
\n" +
    "
\n" +
    "      {{ user_login }}" + "\n" +
    "
\n" +
    "
\n" +
    "
\n"

I would like to know if there is a cleaner way to do it. I have tried using js.erb file with the render function like this

<%= j render('navbar') %>

but placed it in the asset folder so the render function is not working https://stackoverflow.com/a/8370847/1087841. I would like to know if there is a better way to do it.

[EDIT]
The js.erb file is actually an angular factory which has default HTML for the navbar, which then can be used by the angular controller to render default data. The factory file is then also gets added to application.js as a require.
this is the textarea that needs default html

<textarea name="t[navigation]" id="input-navigation-bar" ng-model="t.navigation_bar" class="form-control" rows="10"></textarea>

I could have placed the value tag with the default html but it has ng-model so nothing gets displayed. So I created a factory for the default data. Now the factory lives in /assets and has a //= require 'default_html_factory' in application.js.

Body:
I finally found a way to do it. In the erb page I added

<script>
  <%= render 'style_factory.js.erb' %>
</script>

and in the factory I added this

this.ngapp.factory('TenantStyle', function() {
  return {
    header: "<%= j render 'navbar' %>"
  }
});

and in the _navbar.html.erb file I added this

<div class="navbar navbar-default letter-header hidden-sm hidden-xs">
  <div class="container">
    <div class="letter-navbar-header navbar-header">
    </div>

    <div class="navbar-header header-text">
      <div class="navbar-text">
      </div>
    </div>
    <div class='letter-navbar-header navbar-header'>
      <a href='/'>
        <img src='' class='second-logo'>
      </a>
    </div>

    <div class="navbar-header navbar-right">
    </div>
  </div>
</div>

and now I can call the factory in angular and get the header value.


问:
'MySQL' object has no attribute connection while using mysql.connection.cursor()
Actual code is

```<code>from flask_mysqldb import MySQL

mysql=MySQL(app)
mysql.connection.cursor()
</code>```

I just changed the library flask_mysqldb to flaskext.mysql because I am getting some error while installing flask_mysqldb library.

```<code>from flaskext.mysql import MySQL

mysql=MySQL(app)
mysql.connection.cursor()
</code>```

What is wrong with this code? and also suggest best way of connecting to MySQL database using Flask?

Thanks

答:
You can do something like this

```<code>from flask.ext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'DbToConnect'
app.config['MYSQL_HOST'] = 'localhost'

#Initialize the app for use with this MySQL class
mysql.init_app(app)

cursor = mysql.connection.cursor()
</code>```

More information

Body:
Actual code is

from flask_mysqldb import MySQL

mysql=MySQL(app)
mysql.connection.cursor()

I just changed the library flask_mysqldb to flaskext.mysql because I am getting some error while installing flask_mysqldb library.

from flaskext.mysql import MySQL

mysql=MySQL(app)
mysql.connection.cursor()

What is wrong with this code? and also suggest best way of connecting to MySQL database using Flask?

Thanks

Body:
You can do something like this

from flask.ext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'DbToConnect'
app.config['MYSQL_HOST'] = 'localhost'

#Initialize the app for use with this MySQL class
mysql.init_app(app)

cursor = mysql.connection.cursor()

More information


问:
What concept allows a container to be usable in a range-based for loop?
I have a container which is actually a std::shared_ptr< std::vector< Element > >. I wrapped this type into a MyVector class because I do not want people to mess the things up with the pointer:

```<code>class MyVector
{
    std::shared_ptr< std::vector< Element > > m_vector;
};
</code>```

I want to be able to use MyVector into a range-based for loop like this:

```<code>int main( )
{
    MyVector vector;

    // ...

    for( const auto& element : vector )
    {
        // ...
    }

    return 0;
}
</code>```

So now I have to redirect to the internal pointer the correct functions in order to make it work. To which C++ Concept must MyVector be compliant?
And how can I achieve the result that when the internal std::shared_ptr is nullptr, MyVector behaves exactly like an empty std::vector (so that it will not crash on a range-based loop, but will just make no iteration at all)?

答:
To answer your question take a look at the explanation of range based for loops as in the cppreference documentation

```<code>{
    auto && __range = range_expression ;
    auto __begin = begin_expr ;
    auto __end = end_expr ;
    for ( ; __begin != __end; ++__begin) {
        range_declaration = *__begin;
        loop_statement
    }
}
</code>```

And this quote

If range_expression is an expression of a class type C that has a member named begin and/or a member named end (regardless of the type or accessibility of such member), then begin_expr is __range.begin() and end_expr is __range.end();

So firstly you need to provide a begin() method, an end() method.  Both should return an instance of some sort of iterator class (they can be of different types!)

The iterator returned by begin() should support the preincrement operator and the dereference operator as inferred from the explanation above.

And finally the iterators returned by begin() and end() should be comparable with a !=.

Body:
I have a container which is actually a std::shared_ptr< std::vector< Element > >. I wrapped this type into a MyVector class because I do not want people to mess the things up with the pointer:

class MyVector
{
    std::shared_ptr< std::vector< Element > > m_vector;
};

I want to be able to use MyVector into a range-based for loop like this:

int main( )
{
    MyVector vector;

    // ...

    for( const auto& element : vector )
    {
        // ...
    }

    return 0;
}

So now I have to redirect to the internal pointer the correct functions in order to make it work. To which C++ Concept must MyVector be compliant?
And how can I achieve the result that when the internal std::shared_ptr is nullptr, MyVector behaves exactly like an empty std::vector (so that it will not crash on a range-based loop, but will just make no iteration at all)?

Body:
To answer your question take a look at the explanation of range based for loops as in the cppreference documentation

{
    auto && __range = range_expression ;
    auto __begin = begin_expr ;
    auto __end = end_expr ;
    for ( ; __begin != __end; ++__begin) {
        range_declaration = *__begin;
        loop_statement
    }
}

And this quote

If range_expression is an expression of a class type C that has a member named begin and/or a member named end (regardless of the type or accessibility of such member), then begin_expr is __range.begin() and end_expr is __range.end();

So firstly you need to provide a begin() method, an end() method.  Both should return an instance of some sort of iterator class (they can be of different types!)

The iterator returned by begin() should support the preincrement operator and the dereference operator as inferred from the explanation above.

And finally the iterators returned by begin() and end() should be comparable with a !=.


问:
Type inference weirdness in Eclipse Neon
Good morning everybody,

I've struggled for some time understanding why the following piece of code doesn't compile in Eclipse Neon (JDT 3.12.3.v20170301-0400) but compiles perfectly with javac or Eclipse Mars:

```<code>public class TestLambda {

    protected static <K, V> Map<K, V> newMap(final Function<K, V> loader) {
        return new HashMap<>();
    }

    private final Map<Integer, Integer> working = newMap(key -> {

        final List<String> strings = new ArrayList<>();

        final String[] array = strings.toArray(new String[strings.size()]);
        foo(array);

        return null;
    });

    private final Map<Void, Void> notWorking = newMap(key -> {

        final List<String> strings = new ArrayList<>();

        // This line seems to be the root of all evils
        foo(strings.toArray(new String[strings.size()]));

        return null;
    });

    private void foo(final String[] x) {}

    private void foo(final Integer[] x) {}

}
</code>```

The Eclipse compiler says "Type mismatch: cannot convert from Map<Object,Object> to Map<Void,Void>".

It seems that it cannot know which foo method must be called...

Do I do something wrong?

Thanks in advance for your help

答:
I can reproduce the problem even with the newest version, Eclipse Oxygen. The problem does not occur with any javac version of Java 8 or Java 9 beta.

We can clearly conclude that this is a bug and a weird one.

First, there is no ambiguity here. Both invocations of foo have to end up at foo(String[]) and, in fact, Eclipse doesn’t report an ambiguity problem.

Second, the foo invocation has no impact on the functional type of this lambda expression.

If we change the line foo(strings.toArray(new String[strings.size()])); to foo(strings.toArray());, we will get a real error at foo as no foo(Object[]) exist, but the type inference will correctly resolve Function<Void, Void> for the lambda expression and Map<Void, Void> as newMap’s return type.

We could also create a real ambiguity problem by changing the foo declarations to

```<code>private void foo(final Serializable[] x) {}
private void foo(final CharSequence[] x) {}
</code>```

This will cause an error on both foo invocations, as String[] is compatible with both methods and there is no relationship between Serializable and CharSequence, but the type inference for the newMap invocation is unaffected and resolves to

<Void, Void> Map<Void, Void> newMap(Function<Void, Void>) as expected.

The weirdest thing is, just swapping the order of the foo methods makes the error go away:

```<code>public class TestLambda {

    protected static <K, V> Map<K, V> newMap(final Function<K, V> loader) {
        return new HashMap<>();
    }

    private final Map<Integer, Integer> working = newMap(key -> {

        final List<String> strings = new ArrayList<>();

        final String[] array = strings.toArray(new String[strings.size()]);
        foo(array);

        return null;
    });

    private final Map<Void, Void> notWorking = newMap(key -> {

        final List<String> strings = new ArrayList<>();

        // This line seems to be the root of all evils
        foo(strings.toArray(new String[strings.size()]));

        return null;
    });

    private void foo(final Integer[] x) {}
    private void foo(final String[] x) {}
}
</code>```

compiles fine.

There is a pattern behind it. You can have as many foo overloads you want, as long as the last declared one is applicable to the foo invocation. It doesn’t have to be the most specific one that is finally invoked, e.g. placing another private void foo(final Object[] x) {} at the end of the class will also solve the issue.

That pattern surely has no matching Java language rule…

Body:
Good morning everybody,

I've struggled for some time understanding why the following piece of code doesn't compile in Eclipse Neon (JDT 3.12.3.v20170301-0400) but compiles perfectly with javac or Eclipse Mars:

public class TestLambda {

    protected static <K, V> Map<K, V> newMap(final Function<K, V> loader) {
        return new HashMap<>();
    }

    private final Map<Integer, Integer> working = newMap(key -> {

        final List<String> strings = new ArrayList<>();

        final String[] array = strings.toArray(new String[strings.size()]);
        foo(array);

        return null;
    });

    private final Map<Void, Void> notWorking = newMap(key -> {

        final List<String> strings = new ArrayList<>();

        // This line seems to be the root of all evils
        foo(strings.toArray(new String[strings.size()]));

        return null;
    });

    private void foo(final String[] x) {}

    private void foo(final Integer[] x) {}

}

The Eclipse compiler says "Type mismatch: cannot convert from Map<Object,Object> to Map<Void,Void>".

It seems that it cannot know which foo method must be called...

Do I do something wrong?

Thanks in advance for your help

Body:
I can reproduce the problem even with the newest version, Eclipse Oxygen. The problem does not occur with any javac version of Java 8 or Java 9 beta.

We can clearly conclude that this is a bug and a weird one.

First, there is no ambiguity here. Both invocations of foo have to end up at foo(String[]) and, in fact, Eclipse doesn’t report an ambiguity problem.

Second, the foo invocation has no impact on the functional type of this lambda expression.

If we change the line foo(strings.toArray(new String[strings.size()])); to foo(strings.toArray());, we will get a real error at foo as no foo(Object[]) exist, but the type inference will correctly resolve Function<Void, Void> for the lambda expression and Map<Void, Void> as newMap’s return type.

We could also create a real ambiguity problem by changing the foo declarations to

private void foo(final Serializable[] x) {}
private void foo(final CharSequence[] x) {}

This will cause an error on both foo invocations, as String[] is compatible with both methods and there is no relationship between Serializable and CharSequence, but the type inference for the newMap invocation is unaffected and resolves to

<Void, Void> Map<Void, Void> newMap(Function<Void, Void>) as expected.

The weirdest thing is, just swapping the order of the foo methods makes the error go away:

public class TestLambda {

    protected static <K, V> Map<K, V> newMap(final Function<K, V> loader) {
        return new HashMap<>();
    }

    private final Map<Integer, Integer> working = newMap(key -> {

        final List<String> strings = new ArrayList<>();

        final String[] array = strings.toArray(new String[strings.size()]);
        foo(array);

        return null;
    });

    private final Map<Void, Void> notWorking = newMap(key -> {

        final List<String> strings = new ArrayList<>();

        // This line seems to be the root of all evils
        foo(strings.toArray(new String[strings.size()]));

        return null;
    });

    private void foo(final Integer[] x) {}
    private void foo(final String[] x) {}
}

compiles fine.

There is a pattern behind it. You can have as many foo overloads you want, as long as the last declared one is applicable to the foo invocation. It doesn’t have to be the most specific one that is finally invoked, e.g. placing another private void foo(final Object[] x) {} at the end of the class will also solve the issue.

That pattern surely has no matching Java language rule…


问:
How to invoke controller methods in Spring MVC
I want to hit the readTasks method of my controller when navigating to the root of my web app. I have set a breakpoint in the method but I am not hitting it when debugging on the server. I am using Eclipse.

I nagivate to: http://localhost:8080/ToDoList/ and I see my index page but the controller method is not invoked.

My Controller:

```<code>import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<TaskEntity> readTasks()
    {
        TaskEntityDao tasks = new TaskEntityDaoImpl();
        return tasks.getAllTasks();
    }
}
</code>```

My web.xml:

```<code><web-app version="2.4"
     xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>Dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

I believe I am missing some configuration to initialise the controller, but I am not sure how to go about it. Do I need a configuration file that contains initialisation of every single controller in my application?

答:
You'll need to write a Spring configuration file which includes a component scan for the package that your controller is located in. This tells Spring to initialise this controller when the Spring context loads. You then need to point your servlet to this configuration:</p>

```<code><servlet>
    <servlet-name>Dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
    </init-param>
</servlet>
</code>```

Body:
I want to hit the readTasks method of my controller when navigating to the root of my web app. I have set a breakpoint in the method but I am not hitting it when debugging on the server. I am using Eclipse.

I nagivate to: http://localhost:8080/ToDoList/ and I see my index page but the controller method is not invoked.

My Controller:

import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<TaskEntity> readTasks()
    {
        TaskEntityDao tasks = new TaskEntityDaoImpl();
        return tasks.getAllTasks();
    }
}

My web.xml:

<web-app version="2.4"
     xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>Dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

I believe I am missing some configuration to initialise the controller, but I am not sure how to go about it. Do I need a configuration file that contains initialisation of every single controller in my application?

Body:
You'll need to write a Spring configuration file which includes a component scan for the package that your controller is located in. This tells Spring to initialise this controller when the Spring context loads. You then need to point your servlet to this configuration:

<servlet>
    <servlet-name>Dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
    </init-param>
</servlet>


问:
How to create a copy of a file having length more than 260 characters
How to create a copy of a file having length more than 260 characters including file name using vb.net

When we are trying to create a copy using File.Copy method it throws exception as follows:

"The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters."

Is it possible, then please help...

答:
What I usually do in this instance is:

1) Count the file name length

2) If FileNameLength > 259 then crop the file name enough to handle the new name and then copy the file with a cropped destination name.

OwnerDisplayName: Sugam

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: CodeSlave

OwnerDisplayName: Matias Nino


问:
Pause or stop the video when close icon is clicked
i want to pause/stop the video when close(X) icon is pressed.
Now when i click the X button video keeps playing in the background.
 Also i want that the close icon should come on the player itseld not outside the player.

var hideStr = 'X', showStr = 'Show', hideClass = 'hide';
var buttons = document.querySelectorAll('video + button.close');
for(var b = 0; b < buttons.length; b++){
  var button = buttons[b];
  button.addEventListener('click', function(){
    var video = this.parentNode.childNodes[1];
    video.muted = !video.muted;
    video.classList.toggle (hideClass);
    if(this.textContent == hideStr) this.textContent = showStr;
    else this.textContent = hideStr;
  });
}
$('hideStr').click(function(){
  $(".playvideo").pause();       // Tag name used as a selector
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.relative {
    position: relative;
  left: 00px;
}
.close {
    font-size: 10px;
    position: inherit;
    top: 5px; right: 5px;
}
.hide {
    display: none;
}</code>```

    <video id="playvideo" width="450" controls="controls" >
    <source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
    </video>
     <button class="close">X</button>

```

答:
```<code>let video = document.querySelector('video');

let close = document.querySelector('.close');

close.onclick = () => {
    video.pause();
}
</code>```

<p>in javascript </p>

Body:
i want to pause/stop the video when close(X) icon is pressed.
Now when i click the X button video keeps playing in the background.
 Also i want that the close icon should come on the player itseld not outside the player.

var hideStr = 'X', showStr = 'Show', hideClass = 'hide';
var buttons = document.querySelectorAll('video + button.close');
for(var b = 0; b < buttons.length; b++){
  var button = buttons[b];
  button.addEventListener('click', function(){
    var video = this.parentNode.childNodes[1];
    video.muted = !video.muted;
    video.classList.toggle (hideClass);
    if(this.textContent == hideStr) this.textContent = showStr;
    else this.textContent = hideStr;
  });
}
$('hideStr').click(function(){
  $(".playvideo").pause();       // Tag name used as a selector
});

div.relative {
    position: relative;
  left: 00px;
}
.close {
    font-size: 10px;
    position: inherit;
    top: 5px; right: 5px;
}
.hide {
    display: none;
}

    <video id="playvideo" width="450" controls="controls" >
    <source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
    </video>
     <button class="close">X</button>

Body:
let video = document.querySelector('video');

let close = document.querySelector('.close');

close.onclick = () => {
    video.pause();
}

in javascript


问:
function returning a string of zeros in c
i trying to create a function that return an array of zeros us a char array
and print this array in a file text but when i return a string an addition char was returned

this the text file string the program wrote

this my fuction :

```<code> char *zeros_maker (int kj,int kj1)
{
     char *zeros;
    zeros = (char *) malloc(sizeof(char)*(kj-kj1));
    int i;
    for(i =0;i<kj-kj1;i++)
        zeros[i]='0';
    printf("%s\n",zeros);
    return zeros;
}
</code>```

the instruction i used when i printed in the file

```<code>fprintf(pFile,"%c%s%c &",34,zeros_maker(added_zeros,0),34);
</code>```

Thanks in advance

答:
'0' in C is the value of the encoding used for the digit zero. This is not allowed to have the value 0 by the C standard.

You need to add a NUL-terminator '\0' to the end of the char array, in order for the printf function to work correctly.

Else you run the risk of it running past the end of the char array, with undefined results.

Finally, don't forget to free the allocated memory at some point in your program.

Body:
i trying to create a function that return an array of zeros us a char array
and print this array in a file text but when i return a string an addition char was returned

this the text file string the program wrote

this my fuction :

 char *zeros_maker (int kj,int kj1)
{
     char *zeros;
    zeros = (char *) malloc(sizeof(char)*(kj-kj1));
    int i;
    for(i =0;i<kj-kj1;i++)
        zeros[i]='0';
    printf("%s\n",zeros);
    return zeros;
}

the instruction i used when i printed in the file

fprintf(pFile,"%c%s%c &",34,zeros_maker(added_zeros,0),34);

Thanks in advance


问:
How do I enable @click.middle?
I want to catch middle mouse button click event using @click.middle, but it seems that nothing happens. anyone know why? https://jsfiddle.net/c25e35uh/

  <button @click.middle="test()">
    Click Me
  </button>

new Vue({
  el: '#root',
  methods: {
    test () {
        alert('me')
    }
  }
})
```

In their document, they said clearly that using @click.middle to catch event https://v2.vuejs.org/v2/guide/events.html#Mouse-Button-Modifiers

答:
Try to catch the mouseDown event </p>

```<code><div id="root">
  <button @mouseDown.middle="test">
    Click Me
  </button>
</div>

new Vue({
  el: '#root',
  methods: {
    test () {
        alert('me')
    }
  }
})
</code>```

ContentLicense: CC BY-SA 4.0

Title: How do I enable @click.middle?

Body:
I want to catch middle mouse button click event using @click.middle, but it seems that nothing happens. anyone know why? https://jsfiddle.net/c25e35uh/

  <button @click.middle="test()">
    Click Me
  </button>

new Vue({
  el: '#root',
  methods: {
    test () {
        alert('me')
    }
  }
})

In their document, they said clearly that using @click.middle to catch event https://v2.vuejs.org/v2/guide/events.html#Mouse-Button-Modifiers

Body:
Try to catch the mouseDown event

<div id="root">
  <button @mouseDown.middle="test">
    Click Me
  </button>
</div>

new Vue({
  el: '#root',
  methods: {
    test () {
        alert('me')
    }
  }
})