问:
How to wrap a Text in JavaFX
I am trying to create a simple JavaFX app where Texts are programmatically added to a VBox positioned in a Scrollpane (so that, when there are too many texts, the window can be scrolled to see other parts of the overall).

My problem is that my Texts do not wrap : they just go out of the window on a single line.

Using preceding StackOverflow answers, I successively tried :

deactivating the horizontal scrolling of my scrollpane,

setting the ScrollPane with fitToWidth="true"

binding my Texts widthProperty to that of one of the enclosing layouts

binding my Texts widthProperty to that of the scene itself (which I would like to avoid, as I need to set the first in the Initialize() method of my controller, when the Scene is not yet available, it didn't work anyway).

None of these made any difference (besides the disappearance of the horizontal scrollbar, which is pointless, since you can scroll by panning anyway).

Here is my fxml :

```<code><BorderPane fx:controller="org.duckdns.spacedock.lifepathfx.PathController" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1">
<center>
<ScrollPane hbarPolicy="NEVER" pannable="true" fitToWidth="true" fx:id="scrollPane" >
    <content>
    <VBox fx:id="mainBox" >

    </VBox>
    </content>
</ScrollPane>
</center>
<top>
<ToolBar>
    <items>
    <Button mnemonicParsing="false" text="Back" onAction="#rollback" />
    </items>
</ToolBar>
</top>
</code>```

And here is the code where I add my Texts :

```<code>private void displayNewParagraph()
{
Text text = new Text(someFunctionReturningAString());
text.wrappingWidthProperty().bind(mainBox.widthProperty().subtract(15));
mainBox.getChildren().add(text);
}
</code>```

Note : I am using a fullscreen stage as I want my app to display about the same way on every screen size. That is why I am not using a fixed width for the Texts.

Edit : I tried another thing : binding the ScrollPane and the VBox width properties with :

```<code>mainBox.maxWidthProperty().bind(scrollPane.widthProperty().subtract(10).subtract(10));
mainBox.minWidthProperty().bind(scrollPane.widthProperty().subtract(10).subtract(10));
</code>```

All it did was deactivating the horizontal scrolling, but the Texts still don't wrap : so now they go out the window and can't be seen in their entirety.

Edit2 : I also tried :

```<code>text.setWrappingWidth(mainBox.widthProperty().intValue() - 10);
</code>```

didn't work either : the text just won't wrap at all.

Edit3 : I tried this simple experiment :

```<code>text.setWrappingWidth(150);
System.out.println("wrapping width:" + text.getWrappingWidth());
</code>```

wrapping width:150 is outputed but the text doesn't wrap... now I am confused.

答:
Alright, answering my own question, I found out the normal procedure is to wrap the Texts in a TextFlow object. Do this and the Texts wrap nicely.

What I don't understand is why absolutely nowhere in the doc is it written that Texts won't wrap if they are in a *Box in a ScrollPane even if you set their wrapping width properly.

That said it is working now, Texts are being added to the TextFlow instead of the Box directly and everyone is happy.

Title: How to wrap a Text in JavaFX

Body:
I am trying to create a simple JavaFX app where Texts are programmatically added to a VBox positioned in a Scrollpane (so that, when there are too many texts, the window can be scrolled to see other parts of the overall).

My problem is that my Texts do not wrap : they just go out of the window on a single line.

Using preceding StackOverflow answers, I successively tried :

deactivating the horizontal scrolling of my scrollpane,

setting the ScrollPane with fitToWidth="true"

binding my Texts widthProperty to that of one of the enclosing layouts

binding my Texts widthProperty to that of the scene itself (which I would like to avoid, as I need to set the first in the Initialize() method of my controller, when the Scene is not yet available, it didn't work anyway).

None of these made any difference (besides the disappearance of the horizontal scrollbar, which is pointless, since you can scroll by panning anyway).

Here is my fxml :

<BorderPane fx:controller="org.duckdns.spacedock.lifepathfx.PathController" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1">

<ScrollPane hbarPolicy="NEVER" pannable="true" fitToWidth="true" fx:id="scrollPane" >
    <content>
    <VBox fx:id="mainBox" >

    </VBox>
    </content>
</ScrollPane>

<top>
<ToolBar>
    <items>
    <Button mnemonicParsing="false" text="Back" onAction="#rollback" />
    </items>
</ToolBar>
</top>

And here is the code where I add my Texts :

private void displayNewParagraph()
{
Text text = new Text(someFunctionReturningAString());
text.wrappingWidthProperty().bind(mainBox.widthProperty().subtract(15));
mainBox.getChildren().add(text);
}

Note : I am using a fullscreen stage as I want my app to display about the same way on every screen size. That is why I am not using a fixed width for the Texts.

Edit : I tried another thing : binding the ScrollPane and the VBox width properties with :

mainBox.maxWidthProperty().bind(scrollPane.widthProperty().subtract(10).subtract(10));
mainBox.minWidthProperty().bind(scrollPane.widthProperty().subtract(10).subtract(10));

All it did was deactivating the horizontal scrolling, but the Texts still don't wrap : so now they go out the window and can't be seen in their entirety.

Edit2 : I also tried :

text.setWrappingWidth(mainBox.widthProperty().intValue() - 10);

didn't work either : the text just won't wrap at all.

Edit3 : I tried this simple experiment :

text.setWrappingWidth(150);
System.out.println("wrapping width:" + text.getWrappingWidth());

wrapping width:150 is outputed but the text doesn't wrap... now I am confused.


来源: stackexchange

问:
Javascript validation: Block special characters
How can I restrict users from entering special characters in the text box. I want only numbers and alphabets to be entered ( Typed / Pasted ).

Any samples?

答:
A few of the options are deprecated as of today. So watch out for those.

If you try <input onkeypress="blockSpecialCharacters(event)" />, an IDE like WebStorm will slash out <s>event</s> and tell you:

Deprecated symbol used, consults docs for better alternative

Then when you get to the JavaScript, console.log(e.keyCode) will also give <s>keyCode</s> and say:

Deprecated symbol used, consults docs for better alternative

Anyways I did it using jQuery.

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>

<input id="theInput" />

<script>
    function blockSpecialCharacters(e) {
            let key = e.key;
            let keyCharCode = key.charCodeAt(0);

            // 0-9
            if(keyCharCode >= 48 && keyCharCode <= 57) {
                return key;
            }
            // A-Z
            if(keyCharCode >= 65 && keyCharCode <= 90) {
                return key;
            }
            // a-z
            if(keyCharCode >= 97 && keyCharCode <= 122) {
                return key;
            }

            return false;
    }

    $('#theInput').keypress(function(e) {
        blockSpecialCharacters(e);
    });
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
A few of the options are deprecated as of today. So watch out for those.

If you try <input onkeypress="blockSpecialCharacters(event)" />, an IDE like WebStorm will slash out <s>event</s> and tell you:

Deprecated symbol used, consults docs for better alternative

Then when you get to the JavaScript, console.log(e.keyCode) will also give <s>keyCode</s> and say:

Deprecated symbol used, consults docs for better alternative

Anyways I did it using jQuery.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>

<input id="theInput" />

<script>
    function blockSpecialCharacters(e) {
            let key = e.key;
            let keyCharCode = key.charCodeAt(0);

            // 0-9
            if(keyCharCode >= 48 && keyCharCode <= 57) {
                return key;
            }
            // A-Z
            if(keyCharCode >= 65 && keyCharCode <= 90) {
                return key;
            }
            // a-z
            if(keyCharCode >= 97 && keyCharCode <= 122) {
                return key;
            }

            return false;
    }

    $('#theInput').keypress(function(e) {
        blockSpecialCharacters(e);
    });
</script>

ContentLicense: CC BY-SA 4.0


问:
Selenium Button Selector and Click
I want to automate the restart of my router using Selenium on Python. Everything is working fine except for the last step, which is locating the restart button and click it!

I have tried to locate it by (id, css_selector, name, value, xpath), but nothing seemed to work.

Here is my code:

```<code>driver = webdriver.Firefox()
driver.get('http://192.168.100.1')

english = driver.find_element_by_id("English")
english.click()

usr = "username"
pwd = "password"

usrname_box = driver.find_element_by_id("txt_Username")
usrname_box.send_keys(usr)

pwd_box = driver.find_element_by_id("txt_Password")
pwd_box.send_keys(pwd)

submit_ = driver.find_element_by_id("button")
submit_.click()
sleep(1)

resetit = driver.find_element_by_name("maindiv_reset")
resetit.click()
sleep(1)

# This is the one I want to locate
reboot = driver.find_element_by_xpath("//input[@id='btnReboot']")
reboot.click()
</code>```

And this is the HTML code for the target button:

```<code><input class="ApplyButtoncss buttonwidth_150px" name="btnReboot" id="btnReboot" type="button" onclick="Reboot()" bindtext="s0603" value="Restart">
</code>```

When trying anything, I get the error:

```<code>NoSuchElementException: Message: Unable to locate element: (WHATEVER I TRY)
</code>```

A Screenshot of the HTML Page:

Thank you all for your help in advance.

答:
As the target button was included in iframe, I used the following method to solve the problem:

```<code>iframe = driver.find_element_by_id("frameContent")
driver.switch_to.frame(iframe)
driver.find_element_by_id('btnReboot').click()
alert = driver.switch_to_alert()
alert.accept()
</code>```

Thanks a lot to everyone tried to help, especially to DebanjanB

Title: Selenium Button Selector and Click

Body:
I want to automate the restart of my router using Selenium on Python. Everything is working fine except for the last step, which is locating the restart button and click it!

I have tried to locate it by (id, css_selector, name, value, xpath), but nothing seemed to work.

Here is my code:

driver = webdriver.Firefox()
driver.get('http://192.168.100.1')

english = driver.find_element_by_id("English")
english.click()

usr = "username"
pwd = "password"

usrname_box = driver.find_element_by_id("txt_Username")
usrname_box.send_keys(usr)

pwd_box = driver.find_element_by_id("txt_Password")
pwd_box.send_keys(pwd)

submit_ = driver.find_element_by_id("button")
submit_.click()
sleep(1)

resetit = driver.find_element_by_name("maindiv_reset")
resetit.click()
sleep(1)

# This is the one I want to locate
reboot = driver.find_element_by_xpath("//input[@id='btnReboot']")
reboot.click()

And this is the HTML code for the target button:

<input class="ApplyButtoncss buttonwidth_150px" name="btnReboot" id="btnReboot" type="button" onclick="Reboot()" bindtext="s0603" value="Restart">

When trying anything, I get the error:

NoSuchElementException: Message: Unable to locate element: (WHATEVER I TRY)

A Screenshot of the HTML Page:

Thank you all for your help in advance.

Body:
As the target button was included in iframe, I used the following method to solve the problem:

iframe = driver.find_element_by_id("frameContent")
driver.switch_to.frame(iframe)
driver.find_element_by_id('btnReboot').click()
alert = driver.switch_to_alert()
alert.accept()

Thanks a lot to everyone tried to help, especially to DebanjanB


问:
Tiny MCE Problem
I have a problem with the Tiny MCE Editor. In IE When i Copy - paste some HTML content from any where into the Tiny Mce Editor and when i select the portion of the pasted content, i Get a Boxed Border..!! Thats really annoying & while i scroll the editor - it gets out of the editor area. i want to remove/avoid this border.

答: Are you pasting from Microsoft Excel? I tried pasting from web, Word, Excel, and PowerPoint into TinyMCE running in Firefox 3.6 and Internet Explorer 7, and in both browsers I get this when pasting from Excel. it might be worth looking into configuring the paste plugin, where you may be able to detect when this box appears and then remove it. http://tinymce.moxiecode.com/wiki.php/Plugin:paste</p>

Title: Tiny MCE Problem


问:
Sequelize: Return associated results array without embedded objects
With this query:

```<code>const noteRecords = await db.job_notes.findAll({
  attributes: [],
  include: [
    {
      model: db.jobs,
      attributes: [],
      where: {
        id: jobId,
      },
    },
    {
      model: db.notes,
      attributes: ['id', 'body'],
    },
  ],
});
</code>```

Sequelize returns results as:

```<code>[
   {
      "note": {
         "id": "2",
         "body": "Lorem Ipsume Dolor Sumut"
      }
   },
   {
      "note": {
         "id": "3",
         "body": "Sum es est sumus estis sunt"
      }
   }
]
</code>```

While I want it to return as:

```<code>[
  {
     "id": "2",
     "body": "Lorem Ipsume Dolor Sumut"
  },
  {
     "id": "3",
     "body": "Sum es est sumus estis sunt"
  }
]
</code>```

Aside from noteRecords = noteRecords.map(note => note.note) is there a Sequelize way to do get the data formatted in this way?

答:
Solved by changing the query to:

```<code>const noteRecords = await db.notes.findAll({
  include: [
    {
      model: db.jobs,
      attributes: [],
      where: {
        id: jobId,
      },
    },
  ],
});
</code>```

Since my association in db.notes is:

```<code>models.notes.belongsToMany(models.jobs, {
  through: 'job_notes',
  foreignKey: 'note_id',
  sourceKey: 'id',
});
</code>```

Body:
With this query:

const noteRecords = await db.job_notes.findAll({
  attributes: [],
  include: [
    {
      model: db.jobs,
      attributes: [],
      where: {
        id: jobId,
      },
    },
    {
      model: db.notes,
      attributes: ['id', 'body'],
    },
  ],
});

Sequelize returns results as:

[
   {
      "note": {
         "id": "2",
         "body": "Lorem Ipsume Dolor Sumut"
      }
   },
   {
      "note": {
         "id": "3",
         "body": "Sum es est sumus estis sunt"
      }
   }
]

While I want it to return as:

[
  {
     "id": "2",
     "body": "Lorem Ipsume Dolor Sumut"
  },
  {
     "id": "3",
     "body": "Sum es est sumus estis sunt"
  }
]

Aside from noteRecords = noteRecords.map(note => note.note) is there a Sequelize way to do get the data formatted in this way?

Body:
Solved by changing the query to:

const noteRecords = await db.notes.findAll({
  include: [
    {
      model: db.jobs,
      attributes: [],
      where: {
        id: jobId,
      },
    },
  ],
});

Since my association in db.notes is:

models.notes.belongsToMany(models.jobs, {
  through: 'job_notes',
  foreignKey: 'note_id',
  sourceKey: 'id',
});


问:
Erasure - Generic Type information after compilation
I came across the below in a book-

```<code>//Here, T is bound by Object by default.
class Gen<T> {
    T ob; // here, T will be replaced by Object

    Gen(T o) {
        ob = o;
    }

//Return ob.
    T getob() {
        return ob;
    }
}
</code>```

```<code>// Here, T is bound by String.
class GenStr<T extends String> {
    T str; // here, T will be replaced by String
    GenStr(T o) {
      str = o;
    }
    T getstr() { return str; }
}
</code>```

After these two classes are compiled, the T in Gen will be replaced by Object. The T in
GenStr will be replaced by String. You can confirm this by running javap on their compiled
classes. The results are shown here:

```<code>class Gen extends java.lang.Object{
    java.lang.Object ob;
    Gen(java.lang.Object);
    java.lang.Object getob();
}
class GenStr extends java.lang.Object{
    java.lang.String str;
    GenStr(java.lang.String);
    java.lang.String getstr();
}
</code>```

However, I see this-

```<code>public class GenStr<T extends java.lang.String> {
  T str;

  GenStr(T);
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: aload_0
       5: aload_1
       6: putfield      #2                  // Field str:Ljava/lang/String;
       9: return

  T getstr();
    Code:
       0: aload_0
       1: getfield      #2                  // Field str:Ljava/lang/String;
       4: areturn
}
</code>```

```<code>class Gen<T> {
  T ob;

  Gen(T);
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: aload_0
       5: aload_1
       6: putfield      #2                  // Field ob:Ljava/lang/Object;
       9: return

  T getob();
    Code:
       0: aload_0
       1: getfield      #2                  // Field ob:Ljava/lang/Object;
       4: areturn
}
</code>```

Why does the .class files still show the Formal Type parameter <T>?

答:
Why does the .class files still show the Formal Type parameter ?

Simple: so that

at compile time, the compiler can read such .class files and understand that the corresponding class is generic, and can be used in source code as generic

at runtime, so that some code can inspect, well, "reflect" on the generic nature of that class

Type erasure refers to the fact that the information about the specific type used for an instantiated generic class isn't preserved. But the information that this class is generic needs to be in the class file. How else could the compiler know that Gen is generic in those situations where the compiler doesn't see Gen.java, but only Gen.class?!

Body:
I came across the below in a book-

//Here, T is bound by Object by default.
class Gen<T> {
    T ob; // here, T will be replaced by Object

    Gen(T o) {
        ob = o;
    }

//Return ob.
    T getob() {
        return ob;
    }
}

// Here, T is bound by String.
class GenStr<T extends String> {
    T str; // here, T will be replaced by String
    GenStr(T o) {
      str = o;
    }
    T getstr() { return str; }
}

After these two classes are compiled, the T in Gen will be replaced by Object. The T in
GenStr will be replaced by String. You can confirm this by running javap on their compiled
classes. The results are shown here:

class Gen extends java.lang.Object{
    java.lang.Object ob;
    Gen(java.lang.Object);
    java.lang.Object getob();
}
class GenStr extends java.lang.Object{
    java.lang.String str;
    GenStr(java.lang.String);
    java.lang.String getstr();
}

However, I see this-

public class GenStr<T extends java.lang.String> {
  T str;

  GenStr(T);
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: aload_0
       5: aload_1
       6: putfield      #2                  // Field str:Ljava/lang/String;
       9: return

  T getstr();
    Code:
       0: aload_0
       1: getfield      #2                  // Field str:Ljava/lang/String;
       4: areturn
}

class Gen<T> {
  T ob;

  Gen(T);
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: aload_0
       5: aload_1
       6: putfield      #2                  // Field ob:Ljava/lang/Object;
       9: return

  T getob();
    Code:
       0: aload_0
       1: getfield      #2                  // Field ob:Ljava/lang/Object;
       4: areturn
}

Why does the .class files still show the Formal Type parameter <T>?


问:
Package to Find / Parse PDF Tables Delimited by Whitespace
I am attempting to parse through NSDUH data which is publicly available here :

http://datafiles.samhsa.gov/study-series/national-survey-drug-use-and-health-nsduh-nid13517

I have seen Python packages like PDFMiner and tabula-py, but I have not been able to have success when I come across a table that is delimited by white space. Here is an example of a survey response that is difficult to mark as a "table" object :

The most promising piece that I have together is leveraging "xpdf command line tools" available here : https://www.xpdfreader.com/download.html

I put the "pdftotext.exe" file in my Python directory and can create near-perfect text copies of the pdf files I am manipulating with this command :

C:\Users\UserName\Python\Python37> pdftotext.exe -layout NameOfPDF.pdf

Unfortunately, this output would still require a dependency on a series of regular expressions. If there is an open-source software or python package which can detect that the image attached should be treated as one contiguous block with data points within it, then that would solve my problem.

答:
https://camelot-py.readthedocs.io/en/master/

Hands down the best for wha tyou need.


问:
is this a good way to implement a http request to an api?
I am learning how to use third party API and wanted to know if what I have is a good way to implement an HTTP request to an API. I created a private method which is used to display information to front end, I did it this way so I don't put everything in GetResult() Method. is there a better way to do it?

UPDATE 2

```<code>  public ActionResult Main()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetResult(int zipCode)
        {
            ApiController api = new ApiController();
            var weather = api.GetResult(zipCode);

            var tuple = new Tuple<OpenWeatherMap, RootObject>(new OpenWeatherMap(), new RootObject());

            return View("Main", tuple);
        }
 public async Task<Json.RootObject> GetResult(int zipCode)
        {
            const string apiKey = "";
            var client = new HttpClient();

            var response = await client.GetAsync("http://api.openweathermap.org/data/2.5/weather?zip=" +
                                                 zipCode + ",us&APPID=" + apiKey);
            response.EnsureSuccessStatusCode();
            var rootObj = new Json.RootObject();

            var responseBody = await response.Content.ReadAsStringAsync();

            var deserialize = JsonConvert.DeserializeObject<Json.RootObject>(responseBody);

            if (response.IsSuccessStatusCode)
            {
                rootObj.id = deserialize.id;
                rootObj.weather[0].description = deserialize.weather[0].description;
            }

            return rootObj;
        }

</code>```

答:
Keep you requests to other systems hidden behind a Gateway and keep all the gory details about the external API there.  Also best practice is to use one HttpClient per application because they have a design flaw that holds on to sockets after they are disposed.

If you are using dotnet core, then use HttpClientFactory get an instance of a pooled HttpClient

For the HttpClient creation in your Global.asax

```<code>public class MvcApplication : System.Web.HttpApplication
{

    public static HttpClient HttpClient { get; set; }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        HttpClient = new HttpClient();
    }

    protected void Application_End()
    {
        if (HttpClient == null) return;

        HttpClient.Dispose();
    }
}
</code>```

A naive implementation might be

```<code>public class ExternalGateway
{
    private readonly HttpClient _httpClient;

    public ExternalGateway(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<SomeModel> GetSomeExternalResource(Uri uri)
    {
        var response = await _httpClient.GetAsync(uri.AbsoluteUri);

        // TODO: check status
        // do some conversion of the content to your model

        response.EnsureSuccessStatusCode();

        var content = await response.Content.ReadAsStringAsync();

        return JsonConvert.DeserializeObject<SomeModel>(content);
    }
}

public class SomeModel
{
    public string SomeProperty { get; set; }
}
</code>```

replacing you model and the url you want to connect to.

Then your controller can stay clean.

something like

```<code>        var gateway = new ExternalGateway(MvcApplication.HttpClient);
        var model = await gateway.GetSomeExternalResource(new Uri("<your complete url>"));

        return View(model);
</code>```

This assumes that your are going to use a strongly typed model with your view instead of the ViewBag.

Body:
I am learning how to use third party API and wanted to know if what I have is a good way to implement an HTTP request to an API. I created a private method which is used to display information to front end, I did it this way so I don't put everything in GetResult() Method. is there a better way to do it?

UPDATE 2

  public ActionResult Main()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetResult(int zipCode)
        {
            ApiController api = new ApiController();
            var weather = api.GetResult(zipCode);

            var tuple = new Tuple<OpenWeatherMap, RootObject>(new OpenWeatherMap(), new RootObject());

            return View("Main", tuple);
        }
 public async Task<Json.RootObject> GetResult(int zipCode)
        {
            const string apiKey = "";
            var client = new HttpClient();

            var response = await client.GetAsync("http://api.openweathermap.org/data/2.5/weather?zip=" +
                                                 zipCode + ",us&APPID=" + apiKey);
            response.EnsureSuccessStatusCode();
            var rootObj = new Json.RootObject();

            var responseBody = await response.Content.ReadAsStringAsync();

            var deserialize = JsonConvert.DeserializeObject<Json.RootObject>(responseBody);

            if (response.IsSuccessStatusCode)
            {
                rootObj.id = deserialize.id;
                rootObj.weather[0].description = deserialize.weather[0].description;
            }

            return rootObj;
        }

Body:
Keep you requests to other systems hidden behind a Gateway and keep all the gory details about the external API there.  Also best practice is to use one HttpClient per application because they have a design flaw that holds on to sockets after they are disposed.

If you are using dotnet core, then use HttpClientFactory get an instance of a pooled HttpClient

For the HttpClient creation in your Global.asax

public class MvcApplication : System.Web.HttpApplication
{

    public static HttpClient HttpClient { get; set; }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        HttpClient = new HttpClient();
    }

    protected void Application_End()
    {
        if (HttpClient == null) return;

        HttpClient.Dispose();
    }
}

A naive implementation might be

public class ExternalGateway
{
    private readonly HttpClient _httpClient;

    public ExternalGateway(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<SomeModel> GetSomeExternalResource(Uri uri)
    {
        var response = await _httpClient.GetAsync(uri.AbsoluteUri);

        // TODO: check status
        // do some conversion of the content to your model

        response.EnsureSuccessStatusCode();

        var content = await response.Content.ReadAsStringAsync();

        return JsonConvert.DeserializeObject<SomeModel>(content);
    }
}

public class SomeModel
{
    public string SomeProperty { get; set; }
}

replacing you model and the url you want to connect to.

Then your controller can stay clean.

something like

        var gateway = new ExternalGateway(MvcApplication.HttpClient);
        var model = await gateway.GetSomeExternalResource(new Uri("<your complete url>"));

        return View(model);

This assumes that your are going to use a strongly typed model with your view instead of the ViewBag.


问:
Grafana taking measurement as specified time
I have a daily count metric being pushed to prometheus. Its important to have the measurement every few minutes, but I also want the measurement at a specified time (end of the day) to see the daily total. Is there a way to specify a time of the measurement?

I have set the min_step (time step) to be 24h. Doing so gives me measurements at 20:00:00 each day. Ideally this would be 23:50:00 through 23:59:59

The chart type is a Graph, and the PromQL query is:
max(table_row_count) by (table)
with min_step = 24h, format = time series, and min time interval = 24h. Relative time is set to 7d to get a weekly view of the tables.

I am expecting some way to be able to set the timestamp of the query that should be run every 24h.

答:
Prometheus doesn't have any cron features. You would have to revert to scheduling it yourself.

This means that the first requirement is to get the data you want at the given time. This can be easily done by a GET on the url of the metric you want. (by example using curl).

Now, the question is how to feed it to prometheus. I see three possibilities:

dump the content in a file and let node exporter expose it to prometheus (and erase it after a time). A careful rewrite of metrics can be used in prometheus to sanitize it.

write your own exporter to expose it (easy to do, especially since you have the right data format)

push it to a push gateway but there is currently no way to make the data expire.


问:
Aggregating categorical variables to one variable in python 3 pandas
I have a pandas dataframe with 4 columns. like this

```<code>ID  col1                        col2                col3
1   Strongly Positive   Strongly Positive   Weekly Positive
2   Strongly Positive   Strongly Positive   Neutral
3   Strongly Negative   Strongly Negative   Weekly Negative
4   Weekly Negative      Strongly Negative  Neutral
5   Neutral              Neutral            Neutral
6   Strongly Positive   Strongly Negative   Strongly Negative
7   Strongly Negative   Weekly Positive     Neutral
8   Neutral               Weekly Negative   Weekly Positive
</code>```

Each of the columns can take values like (strongly positive, weekly positive, Neutral, weekly negative and strongly negative and an ID column.
I need to create a new column with these logic

If all the column has positive values or atleast one positive and two neutral values then aggregate that record in the new column as positive

If all the three column has neutral value then flag as neutral

If all the columns have negative values or atleast one negative and two neutral values then flag it as negative

If both positive and negative values are thre then flag it as both
by positive i mean either strong or weekly positive and the same for negative as well.

I need the the final data frame to be like this

```<code>ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral                Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive        Both
</code>```

Not able to think of a logic

```<code>ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral            Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive    Both
</code>```

答:
Interesting Outside-Of-Box Solution

```<code>from numpy.core.defchararray import find

a = df.to_numpy().astype(str)
b = np.select([find(a, 'Pos') >= 0, find(a, 'Neg') >= 0], [1, -1], 0)

c = np.select(
    [(b == 0).all(1), (b >=0).all(1), (b <= 0).all(1)],
    ['Neutral', 'Positive', 'Negative'],
    'Both'
)

df.assign(Agg=c)

                 col1               col2               col3       Agg
ID
1   Strongly Positive  Strongly Positive    Weekly Positive  Positive
2   Strongly Positive  Strongly Positive            Neutral  Positive
3   Strongly Negative  Strongly Negative    Weekly Negative  Negative
4     Weekly Negative  Strongly Negative            Neutral  Negative
5             Neutral            Neutral            Neutral   Neutral
6   Strongly Positive  Strongly Negative  Strongly Negative      Both
7   Strongly Negative    Weekly Positive            Neutral      Both
8             Neutral    Weekly Negative    Weekly Positive      Both
</code>```

Slightly Different Take

```<code>from numpy.core.defchararray import find

a = df.to_numpy().astype(str)
b = np.select([find(a, 'Pos') >= 0, find(a, 'Neg') >= 0], [1, -1], 0)

m = {
    (0, 0): 'Neutral', (1, -1): 'Both',
    (1, 1): 'Positive', (1, 0): 'Positive',
    (-1, -1): 'Negative', (0, -1): 'Negative',
}

df.assign(Agg=[*map(m.get, zip(b.max(1), b.min(1)))])

                 col1               col2               col3       Agg
ID
1   Strongly Positive  Strongly Positive    Weekly Positive  Positive
2   Strongly Positive  Strongly Positive            Neutral  Positive
3   Strongly Negative  Strongly Negative    Weekly Negative  Negative
4     Weekly Negative  Strongly Negative            Neutral  Negative
5             Neutral            Neutral            Neutral   Neutral
6   Strongly Positive  Strongly Negative  Strongly Negative      Both
7   Strongly Negative    Weekly Positive            Neutral      Both
8             Neutral    Weekly Negative    Weekly Positive      Both
</code>```

Body:
I have a pandas dataframe with 4 columns. like this

ID  col1                        col2                col3
1   Strongly Positive   Strongly Positive   Weekly Positive
2   Strongly Positive   Strongly Positive   Neutral
3   Strongly Negative   Strongly Negative   Weekly Negative
4   Weekly Negative      Strongly Negative  Neutral
5   Neutral              Neutral            Neutral
6   Strongly Positive   Strongly Negative   Strongly Negative
7   Strongly Negative   Weekly Positive     Neutral
8   Neutral               Weekly Negative   Weekly Positive

Each of the columns can take values like (strongly positive, weekly positive, Neutral, weekly negative and strongly negative and an ID column.
I need to create a new column with these logic

If all the column has positive values or atleast one positive and two neutral values then aggregate that record in the new column as positive

If all the three column has neutral value then flag as neutral

If all the columns have negative values or atleast one negative and two neutral values then flag it as negative

If both positive and negative values are thre then flag it as both
by positive i mean either strong or weekly positive and the same for negative as well.

I need the the final data frame to be like this

ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral                Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive        Both

Not able to think of a logic

ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral            Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive    Both

Body:
Interesting Outside-Of-Box Solution

from numpy.core.defchararray import find

a = df.to_numpy().astype(str)
b = np.select([find(a, 'Pos') >= 0, find(a, 'Neg') >= 0], [1, -1], 0)

c = np.select(
    [(b == 0).all(1), (b >=0).all(1), (b <= 0).all(1)],
    ['Neutral', 'Positive', 'Negative'],
    'Both'
)

df.assign(Agg=c)

                 col1               col2               col3       Agg
ID
1   Strongly Positive  Strongly Positive    Weekly Positive  Positive
2   Strongly Positive  Strongly Positive            Neutral  Positive
3   Strongly Negative  Strongly Negative    Weekly Negative  Negative
4     Weekly Negative  Strongly Negative            Neutral  Negative
5             Neutral            Neutral            Neutral   Neutral
6   Strongly Positive  Strongly Negative  Strongly Negative      Both
7   Strongly Negative    Weekly Positive            Neutral      Both
8             Neutral    Weekly Negative    Weekly Positive      Both

Slightly Different Take

from numpy.core.defchararray import find

a = df.to_numpy().astype(str)
b = np.select([find(a, 'Pos') >= 0, find(a, 'Neg') >= 0], [1, -1], 0)

m = {
    (0, 0): 'Neutral', (1, -1): 'Both',
    (1, 1): 'Positive', (1, 0): 'Positive',
    (-1, -1): 'Negative', (0, -1): 'Negative',
}

df.assign(Agg=[*map(m.get, zip(b.max(1), b.min(1)))])

                 col1               col2               col3       Agg
ID
1   Strongly Positive  Strongly Positive    Weekly Positive  Positive
2   Strongly Positive  Strongly Positive            Neutral  Positive
3   Strongly Negative  Strongly Negative    Weekly Negative  Negative
4     Weekly Negative  Strongly Negative            Neutral  Negative
5             Neutral            Neutral            Neutral   Neutral
6   Strongly Positive  Strongly Negative  Strongly Negative      Both
7   Strongly Negative    Weekly Positive            Neutral      Both
8             Neutral    Weekly Negative    Weekly Positive      Both


答:
Type information about the class is still retained. Type information about individual instances is not.

So, you know that Gen has a class-level type parameter (notionally) called T.

You don't know the T for an instance of Gen at runtime. You can't even determine it from getob: that merely gives you a lower bound on the type (for example if getob returns a String, T could be String, CharSequence, Serializable or Object). And if it returns null, then T could be anything.

You can write code in Java against classes for which you have no source, only the compiled bytecode. The compiler needs information about the generics of such classes in order to be able to ensure they are used type correctly.

Title: Erasure - Generic Type information after compilation


问:
Avoid Typescript to compile some parts of code
Is there any way to avoid some code to be compiled with Typescript compiler dependent on a variable that must be entered on compiler commmand.
This will be usefull for make multiplatform apps that the code is very similar but with little differences. So instead of doing branches and merging all the time code you just tell compiler to not compile or compile some code.

Thanks

答: You can use the package fdef-loader which do it well. it doing preprocessing using WebPack and solve this issue for me.</p>


问:
Changing the value of a radio button to be checked based upon a variable using jquery
I am trying to use a variable value to change the value of a radio button to be checked. I know the variable is working as I am able to change the CSS of the parent element.

```<code>// CODE to alter the current grade options

if (CG == "F") {

//this is not working
    $( "#currentOption1" ).prop('checked', true );
    $("#currentOption2").prop('checked', false);
    $("#currentOption3").prop('checked', false);
    $("#currentOption4").prop('checked', false);
    $("#currentOption5").prop('checked', false);

// this is working - set the class to active for the appearance of the label being selected
    $("#currentOption1").parent().addClass("active");
    $("#currentOption2").parent().removeClass("active");
    $("#currentOption3").parent().removeClass("active");
    $("#currentOption4").parent().removeClass("active");
    $("#currentOption5").parent().removeClass("active");
</code>```

```<code><!-- CWK current grade Options -->
      <h6>Current Grade</h6>
      <div class="btn-group btn-group-toggle" data-toggle="buttons">
        <label class="btn btn-secondary">
          <input type="radio" name="currentOptions" id="currentOption1" autocomplete="off"> Fail
        </label>
        <label class="btn btn-secondary">
          <input type="radio" name="currentOptions" id="currentOption2" autocomplete="off"> Nearly Pass
        </label>
        <label class="btn btn-secondary" >
          <input type="radio" name="currentOptions" id="currentOption3" autocomplete="off"> Pass
        </label>
        <label class="btn btn-secondary">
          <input type="radio" name="currentOptions" id="currentOption4" autocomplete="off"> Merit
        </label>
        <label class="btn btn-secondary">
          <input type="radio" name="currentOptions" id="currentOption5" autocomplete="off"> Distinction
        </label>
      </div>
</code>```

I want to change the html so that each corresponding radio button becomes checked or unchecked. It isn't changing any at present.

The html is contained with a bootstrap modal and uses bootstrap to style the radio as a series of buttons.

答:
There's likely some code that's undoing the .prop('checked', true) afterward. I took your code, wrapped it in $(document).ready() and set CG = "F". Both the checked and parent css are applied as expected.

$(document).ready(function() {
  let CG = "F";

  // CODE to alter the current grade options

  if (CG == "F") {

    //this is not working
    $("#currentOption1").prop('checked', true);
    $("#currentOption2").prop('checked', false);
    $("#currentOption3").prop('checked', false);
    $("#currentOption4").prop('checked', false);
    $("#currentOption5").prop('checked', false);

    // this is working - set the class to active for the appearance of the label being selected
    $("#currentOption1").parent().addClass("active");
    $("#currentOption2").parent().removeClass("active");
    $("#currentOption3").parent().removeClass("active");
    $("#currentOption4").parent().removeClass("active");
    $("#currentOption5").parent().removeClass("active");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  font-weight: bold;
}</code>```

Current Grade

          <input type="radio" name="currentOptions" id="currentOption1" autocomplete="off"> Fail

          <input type="radio" name="currentOptions" id="currentOption2" autocomplete="off"> Nearly Pass

          <input type="radio" name="currentOptions" id="currentOption3" autocomplete="off"> Pass

          <input type="radio" name="currentOptions" id="currentOption4" autocomplete="off"> Merit

          <input type="radio" name="currentOptions" id="currentOption5" autocomplete="off"> Distinction

```

Body:
I am trying to use a variable value to change the value of a radio button to be checked. I know the variable is working as I am able to change the CSS of the parent element.

// CODE to alter the current grade options

if (CG == "F") {

//this is not working
    $( "#currentOption1" ).prop('checked', true );
    $("#currentOption2").prop('checked', false);
    $("#currentOption3").prop('checked', false);
    $("#currentOption4").prop('checked', false);
    $("#currentOption5").prop('checked', false);

// this is working - set the class to active for the appearance of the label being selected
    $("#currentOption1").parent().addClass("active");
    $("#currentOption2").parent().removeClass("active");
    $("#currentOption3").parent().removeClass("active");
    $("#currentOption4").parent().removeClass("active");
    $("#currentOption5").parent().removeClass("active");

Current Grade

          <input type="radio" name="currentOptions" id="currentOption1" autocomplete="off"> Fail

          <input type="radio" name="currentOptions" id="currentOption2" autocomplete="off"> Nearly Pass

          <input type="radio" name="currentOptions" id="currentOption3" autocomplete="off"> Pass

          <input type="radio" name="currentOptions" id="currentOption4" autocomplete="off"> Merit

          <input type="radio" name="currentOptions" id="currentOption5" autocomplete="off"> Distinction

I want to change the html so that each corresponding radio button becomes checked or unchecked. It isn't changing any at present.

The html is contained with a bootstrap modal and uses bootstrap to style the radio as a series of buttons.

Body:
There's likely some code that's undoing the .prop('checked', true) afterward. I took your code, wrapped it in $(document).ready() and set CG = "F". Both the checked and parent css are applied as expected.

$(document).ready(function() {
  let CG = "F";

  // CODE to alter the current grade options

  if (CG == "F") {

    //this is not working
    $("#currentOption1").prop('checked', true);
    $("#currentOption2").prop('checked', false);
    $("#currentOption3").prop('checked', false);
    $("#currentOption4").prop('checked', false);
    $("#currentOption5").prop('checked', false);

    // this is working - set the class to active for the appearance of the label being selected
    $("#currentOption1").parent().addClass("active");
    $("#currentOption2").parent().removeClass("active");
    $("#currentOption3").parent().removeClass("active");
    $("#currentOption4").parent().removeClass("active");
    $("#currentOption5").parent().removeClass("active");
  }
});

.active {
  font-weight: bold;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- CWK current grade Options -->
<h6>Current Grade</h6>
<div class="btn-group btn-group-toggle" data-toggle="buttons">
  <label class="btn btn-secondary">
          <input type="radio" name="currentOptions" id="currentOption1" autocomplete="off"> Fail
        </label>
  <label class="btn btn-secondary">
          <input type="radio" name="currentOptions" id="currentOption2" autocomplete="off"> Nearly Pass
        </label>
  <label class="btn btn-secondary">
          <input type="radio" name="currentOptions" id="currentOption3" autocomplete="off"> Pass
        </label>
  <label class="btn btn-secondary">
          <input type="radio" name="currentOptions" id="currentOption4" autocomplete="off"> Merit
        </label>
  <label class="btn btn-secondary">
          <input type="radio" name="currentOptions" id="currentOption5" autocomplete="off"> Distinction
        </label>
</div>


问:
Split ActivatedRoute queryParams subscription into multiple subscriptions
I want to get Angular ActivatedRoute queryParams changes and execute a function just once and other function every time.

So far the way I found is subscribing twice but I want a better way to do it, maybe using some pipe operator.

```<code>// DO SOMETHING THE FIRST TIME
this.activatedRoute.queryParamMap
      .pipe(
        first(),
        switchMap(params => {
          // HTTP CALL
        })
      )
      .subscribe((data: any) => {
        // DO SOMETHING
      });

// DO SOMETHING ALWAYS
this.activatedRoute.queryParamMap
      .subscribe((params: any) => {
        // DO SOMETHING
      });
</code>```

Is there any other way do this, something like splitSubscription operator??

答:
You could refactor a bit, rather than trying to subscribe multiple times to the activatedRoute.queryParamMap - not sure if the split operator you're asking about is possible. The following pattern is pretty standard

// Class properties
private paramMapSubject = new BehaviourSubject<ParamMap>(null);
// Using a public observable if your binding to components, or exposing in a service
public params$ = this.paramMapSubject.asObservable();

// In your constructor
// componentDestroyed$ is a subject that's nexted in ngOnDestroy
this.activatedRoute.queryParamMap
      .pipe(
        takeUntil(componentDestroyed$)
        tap( params => {
          this.paramMapSubject.next(params)
        }),
      )
      .subscribe();

// In ngOnInit - will only be called once - if it's in a component
this.params$.pipe(
  takeOne(),
  tap( params => {
    // Do Something Once
  }).subscribe()

this.params$.pipe(
  takeUntil(componentDestroyed$)
  tap( params => {
    // Do Something continuously
  }).subscribe()
```

Body:
I want to get Angular ActivatedRoute queryParams changes and execute a function just once and other function every time.

So far the way I found is subscribing twice but I want a better way to do it, maybe using some pipe operator.

// DO SOMETHING THE FIRST TIME
this.activatedRoute.queryParamMap
      .pipe(
        first(),
        switchMap(params => {
          // HTTP CALL
        })
      )
      .subscribe((data: any) => {
        // DO SOMETHING
      });

// DO SOMETHING ALWAYS
this.activatedRoute.queryParamMap
      .subscribe((params: any) => {
        // DO SOMETHING
      });

Is there any other way do this, something like splitSubscription operator??


问:
Vue JS Function not returning an array
I have a property initialized in my data model as such:

```<code>someArray: []
</code>```

I have an array from a function here:

```<code>getMyArray: function (someId) {
                var result = [7, 8, 9, 10];
                return result;
}
</code>```

I'm calling the function here:

```<code>this.someArray = this.getMyArray(value);
</code>```

My property someArray isn't getting the desired result. It's returning a single empty item.

I heard somewhere that I may have to push each item manually instead. Is this true? What am I doing wrong?

EDIT: Full example...

```<code>var app = new Vue({
    el: '[some-app]',
    data: {
        someArray: []
    },
    methods: {
        getMyArray: function (someId) {
                var result = [7, 8, 9, 10];
                return result;
            });
        },
    },
    watch: {
        someChangingId: function (value) {
            this.someArray = this.getMyArray(value);
        }
    },
});
</code>```

答:
In javascript, objects and arrays are references, different from other variable types.

Your could go for:

```<code>myArray: function (value) {
  var result = new Array(4);
  result[0] = 7;
  result[1] = 8;
  result[2] = 9;
  result[3] = 10;
  return result;
}
</code>```

And then use the .slice() method which will correctly copy the array:

```<code>this.someArray = this.myArray('someValue').slice();
</code>```

By the way, I do not understand why you are passing the value parameter, as it is not being used in your function.

Title: Vue JS Function not returning an array

Body:
I have a property initialized in my data model as such:

someArray: []

I have an array from a function here:

getMyArray: function (someId) {
                var result = [7, 8, 9, 10];
                return result;
}

I'm calling the function here:

this.someArray = this.getMyArray(value);

My property someArray isn't getting the desired result. It's returning a single empty item.

I heard somewhere that I may have to push each item manually instead. Is this true? What am I doing wrong?

EDIT: Full example...

var app = new Vue({
    el: '[some-app]',
    data: {
        someArray: []
    },
    methods: {
        getMyArray: function (someId) {
                var result = [7, 8, 9, 10];
                return result;
            });
        },
    },
    watch: {
        someChangingId: function (value) {
            this.someArray = this.getMyArray(value);
        }
    },
});

Body:
In javascript, objects and arrays are references, different from other variable types.

Your could go for:

myArray: function (value) {
  var result = new Array(4);
  result[0] = 7;
  result[1] = 8;
  result[2] = 9;
  result[3] = 10;
  return result;
}

And then use the .slice() method which will correctly copy the array:

this.someArray = this.myArray('someValue').slice();

By the way, I do not understand why you are passing the value parameter, as it is not being used in your function.


问:
How to upload images to server in Flutter?
I would like to upload a image, I am using http.Client() for making requests,

```<code>static uploadImage(String id, File file) {
  var httpClient = createHttpClient();

  Map<String, String> headers = new Map<String, String>();
  headers.putIfAbsent("Authorization", () => "---");
  headers.putIfAbsent("Content-Type", () => "application/json");

  var body=new List();
  body.add(id.)
  httpClient.post(URL_UPLOADIMAGE,headers: headers,body: ,encoding: )
}
</code>```

What should be the body and encoding part for the request ?

答:
First of all choose your image from gallery or Camera

```<code>File _image;
Future _getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
});
}
</code>```

Now call the below function on button click or inside the _getImage() function. With the file i'm uploading other fields also you see in the saveInAttendance()

Don't forget to import package :

```<code>import 'package:dio/dio.dart';
import 'package:path/path.dart';

Future saveInAttendance( BuildContext context,String entryType,String mode) async {
        Dio dio = new Dio();
        FormData formData = new FormData(); // just like JS
        formData.add("inimageFile", new UploadFileInfo(_image, basename(_image.path)));
        formData.add("compID",2);
        formData.add("company_id",2);
        formData.add("EntryType", entryType);
        formData.add("emp_code", 5);
        formData.add("Mode",mode);
        formData.add("location",""+_startLocation.latitude.toString()+"-"+_startLocation.longitude.toString());
        dio.post(url_save_attendance, data: formData, options: Options(
            method: 'POST',
            responseType: ResponseType.json // or ResponseType.JSON
        ))
            .then((r) {
          setState(() {
            var data = json.decode(r.toString());
            if(data["apiMessage"].contains('Saved')){
              warningAlert("Attendance Saved", "Your attendance saved Successfully",context);
            }
          });
        }).catchError(print);
      }
</code>```

For more Info you can visit Here

Body:
I would like to upload a image, I am using http.Client() for making requests,

static uploadImage(String id, File file) {
  var httpClient = createHttpClient();

  Map<String, String> headers = new Map<String, String>();
  headers.putIfAbsent("Authorization", () => "---");
  headers.putIfAbsent("Content-Type", () => "application/json");

  var body=new List();
  body.add(id.)
  httpClient.post(URL_UPLOADIMAGE,headers: headers,body: ,encoding: )
}

What should be the body and encoding part for the request ?

Body:
First of all choose your image from gallery or Camera

File _image;
Future _getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
});
}

Now call the below function on button click or inside the _getImage() function. With the file i'm uploading other fields also you see in the saveInAttendance()

Don't forget to import package :

import 'package:dio/dio.dart';
import 'package:path/path.dart';

Future saveInAttendance( BuildContext context,String entryType,String mode) async {
        Dio dio = new Dio();
        FormData formData = new FormData(); // just like JS
        formData.add("inimageFile", new UploadFileInfo(_image, basename(_image.path)));
        formData.add("compID",2);
        formData.add("company_id",2);
        formData.add("EntryType", entryType);
        formData.add("emp_code", 5);
        formData.add("Mode",mode);
        formData.add("location",""+_startLocation.latitude.toString()+"-"+_startLocation.longitude.toString());
        dio.post(url_save_attendance, data: formData, options: Options(
            method: 'POST',
            responseType: ResponseType.json // or ResponseType.JSON
        ))
            .then((r) {
          setState(() {
            var data = json.decode(r.toString());
            if(data["apiMessage"].contains('Saved')){
              warningAlert("Attendance Saved", "Your attendance saved Successfully",context);
            }
          });
        }).catchError(print);
      }

For more Info you can visit Here


问:
Using Joi and/or Yup for schema validation, is there a way to make a collection of properties required if any of the other properties are present?
Take for example an HTML form that collects the details of a person.

Note: Code snippets are simplified and do not match up with the screenshot exactly. Also, code snippets are written using Yup, which is a very similar library to Joi that targets the browser rather than NodeJS.

In order to submit the form, I want to run validations on the address fields and make them required, but only if the user has partially filled out the address section. As a whole, I want to make the address details optional.

Here is a simplified version of my PersonSchema...

```<code>import { object, string, number } from 'yup'

const PersonSchema = object().shape({
  name: string().required(),
  age: number()
    .positive()
    .integer()
    .required(),
  address: AddressSchema
})
</code>```

Defining AddressSchema in this way does not work because the fields are always required...

```<code>const AddressSchema = object().shape({
  street: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required(),
  city: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required(),
  state: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required()
})
</code>```

And here was my attempt to make address fields dependent on the presence of other address fields, but this does not work because you run into circular dependency issues...

```<code>const AddressSchema = object().shape({
  street: string()
    .when(['city', 'state'], {
      is: (city, state) => city || state,
      then: string()
        .min(2, 'Too Short!')
        .max(50, 'Too Long!')
        .required(),
      otherwise: string()
    }),
  city: string()
    .when(['street', 'state'], {
      is: (street, state) => street || state,
      then: string()
        .min(2, 'Too Short!')
        .max(50, 'Too Long!')
        .required(),
      otherwise: string()
    }),
  state: string()
    .when(['street', 'city'], {
      is: (street, city) => street || city,
      then: string()
        .min(2, 'Too Short!')
        .max(50, 'Too Long!')
        .required(),
      otherwise: string()
    })
})
</code>```

答:
I needed the same optional address check: Rather than checking each field based against every other address field, just set a flag in your form/schema named something like 'addressStarted', then use that as your when trigger. The flag was an explicit choice by the user in my case, but it could just as easily be a hidden value; just toggle the value to true in every onChange handler (if you're using something like Formik), or even just an event listener on an element that contains all the address fields.</p>

```<code>import { object, string, number } from 'yup'

const AddressSchema = object().shape({
  street: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required(),
  city: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required(),
  state: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required()
})

const PersonSchema = object().shape({
  name: string().required(),
  age: number()
    .positive()
    .integer()
    .required(),
  addressStarted: Yup.boolean(),
  address: object().when('addressStarted', {
    is: true,
    then: AddressSchema,
    otherwise: object().notRequired()
  }),
})

</code>```

Body:
Take for example an HTML form that collects the details of a person.

Note: Code snippets are simplified and do not match up with the screenshot exactly. Also, code snippets are written using Yup, which is a very similar library to Joi that targets the browser rather than NodeJS.

In order to submit the form, I want to run validations on the address fields and make them required, but only if the user has partially filled out the address section. As a whole, I want to make the address details optional.

Here is a simplified version of my PersonSchema...

import { object, string, number } from 'yup'

const PersonSchema = object().shape({
  name: string().required(),
  age: number()
    .positive()
    .integer()
    .required(),
  address: AddressSchema
})

Defining AddressSchema in this way does not work because the fields are always required...

const AddressSchema = object().shape({
  street: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required(),
  city: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required(),
  state: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required()
})

And here was my attempt to make address fields dependent on the presence of other address fields, but this does not work because you run into circular dependency issues...

const AddressSchema = object().shape({
  street: string()
    .when(['city', 'state'], {
      is: (city, state) => city || state,
      then: string()
        .min(2, 'Too Short!')
        .max(50, 'Too Long!')
        .required(),
      otherwise: string()
    }),
  city: string()
    .when(['street', 'state'], {
      is: (street, state) => street || state,
      then: string()
        .min(2, 'Too Short!')
        .max(50, 'Too Long!')
        .required(),
      otherwise: string()
    }),
  state: string()
    .when(['street', 'city'], {
      is: (street, city) => street || city,
      then: string()
        .min(2, 'Too Short!')
        .max(50, 'Too Long!')
        .required(),
      otherwise: string()
    })
})

Body:
I needed the same optional address check: Rather than checking each field based against every other address field, just set a flag in your form/schema named something like 'addressStarted', then use that as your when trigger. The flag was an explicit choice by the user in my case, but it could just as easily be a hidden value; just toggle the value to true in every onChange handler (if you're using something like Formik), or even just an event listener on an element that contains all the address fields.

import { object, string, number } from 'yup'

const AddressSchema = object().shape({
  street: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required(),
  city: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required(),
  state: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required()
})

const PersonSchema = object().shape({
  name: string().required(),
  age: number()
    .positive()
    .integer()
    .required(),
  addressStarted: Yup.boolean(),
  address: object().when('addressStarted', {
    is: true,
    then: AddressSchema,
    otherwise: object().notRequired()
  }),
})


问:
How can I generate a requirements.txt file for a package not available on my development platform?
I'm trying to generate requirements/dev.txt and prod.txt files for my python project. I'm using pip-compile-multi to generate them from base.in dev.in and prod.in files. Everything works great until I add tensorflow-gpu==2.0.0a0 into the prod.in file. I get this error when I do: RuntimeError: Failed to pip-compile requirements/prod.in.

I believe this is because tensorflow-gpu is only available on Linux, and my dev machine is a Mac. (If I run pip install tensorflow-gpu==2.0.0a0 I am told there is no distribution for my platform.) Is there a way I can generate a requirements.txt file for pip for a package that is not available on my platform? To be clear, my goal is to generate a requirements.txt file using something like pip-compile-multi (because that will version dependencies) that will only install on Linux, but I want to be able to actually generate the file on any platform.

答:
Currently pip-tools doesn't support this, there's an open issue on github. A workaround suggested by the author of pip-compile-multi is to generate a linux.txt on a linux machine, and then statically link that to a non-generated linux-prod.txt like this

```<code>-r prod.txt
-r linux.txt
</code>```

Body:
Currently pip-tools doesn't support this, there's an open issue on github. A workaround suggested by the author of pip-compile-multi is to generate a linux.txt on a linux machine, and then statically link that to a non-generated linux-prod.txt like this

-r prod.txt
-r linux.txt


问:
Python bar and line chart with groups in one graph
I have a data like this:

```<code>Group   yq        Value1    Value2
G       2014Q1     0.07        1.1
G       2014Q2     0.06        1.09
G       2014Q3     0.09        1.11
G       2014Q4     0.04        1.13
I       2014Q1     0.10        1.2
I       2014Q2     0.13        1.25
I       2014Q3     0.15        1.23
I       2014Q4     0.18        1.4
</code>```

I want to plot line and bar chart in one graph.

I tried to plot bar first, but it output two graphs (2 groups, G and I):

```<code>import matplotlib.pyplot as plt
ax = dataset.groupby('Group')[['yq', 'Value1']].plot(x = 'yq', kind='bar')
</code>```

After that, I tried to draw line chart with it.

```<code>fig, ax1 = plt.subplots(figsize=(7, 5))
ax2 = ax1.twinx()
dataset[['Value1', 'yq', 'Group']].groupby('Group').plot(x = 'yq', kind='bar', color='y', ax=ax1)
dataset[['Value2', 'yq', 'Group']].groupby('Group').plot(x = 'yq', kind='line', marker='d', ax=ax2)
ax1.yaxis.tick_right()
ax2.yaxis.tick_left()
</code>```

However, the plot is weird. It does not proper show all labels on x-axis. To be concise. it just show year rather than year and quarter.

Moreover, the plot does not plot bar chart on it either.

Any suggestion?

I also tried:

```<code>fig, ax = plt.subplots(figsize=(10, 5))
dataset[['Value1', 'yq', 'Group']].plot(x = 'yq', kind='bar', stacked=False, title='get_title', color='grey', ax=ax, grid=False)
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(), dataset[['Value2']].values, linestyle='-', marker='o', color='k', linewidth=1.0, label='percentage')
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax.legend(lines + lines2, labels + labels2, loc='best')
ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")
fig.autofmt_xdate()
plt.show()
</code>```

This plot is incorrect but can plot line and bar on same graph.

答:
The problem is bar plot  sets the x-axis to range(len(dataset)), and use the corresponding labels, while line plot doesn't do so. So you can change the yq to string and use seaborn:

```<code>dataset.yq = dataset.yq.astype(str)

fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twinx()
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax1)
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', marker='d', ax=ax2)
plt.show()
</code>```

gives:

Body:
I have a data like this:

Group   yq        Value1    Value2
G       2014Q1     0.07        1.1
G       2014Q2     0.06        1.09
G       2014Q3     0.09        1.11
G       2014Q4     0.04        1.13
I       2014Q1     0.10        1.2
I       2014Q2     0.13        1.25
I       2014Q3     0.15        1.23
I       2014Q4     0.18        1.4

I want to plot line and bar chart in one graph.

I tried to plot bar first, but it output two graphs (2 groups, G and I):

import matplotlib.pyplot as plt
ax = dataset.groupby('Group')[['yq', 'Value1']].plot(x = 'yq', kind='bar')

After that, I tried to draw line chart with it.

fig, ax1 = plt.subplots(figsize=(7, 5))
ax2 = ax1.twinx()
dataset[['Value1', 'yq', 'Group']].groupby('Group').plot(x = 'yq', kind='bar', color='y', ax=ax1)
dataset[['Value2', 'yq', 'Group']].groupby('Group').plot(x = 'yq', kind='line', marker='d', ax=ax2)
ax1.yaxis.tick_right()
ax2.yaxis.tick_left()

However, the plot is weird. It does not proper show all labels on x-axis. To be concise. it just show year rather than year and quarter.

Moreover, the plot does not plot bar chart on it either.

Any suggestion?

I also tried:

fig, ax = plt.subplots(figsize=(10, 5))
dataset[['Value1', 'yq', 'Group']].plot(x = 'yq', kind='bar', stacked=False, title='get_title', color='grey', ax=ax, grid=False)
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(), dataset[['Value2']].values, linestyle='-', marker='o', color='k', linewidth=1.0, label='percentage')
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax.legend(lines + lines2, labels + labels2, loc='best')
ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")
fig.autofmt_xdate()
plt.show()

This plot is incorrect but can plot line and bar on same graph.

Body:
The problem is bar plot  sets the x-axis to range(len(dataset)), and use the corresponding labels, while line plot doesn't do so. So you can change the yq to string and use seaborn:

dataset.yq = dataset.yq.astype(str)

fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twinx()
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax1)
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', marker='d', ax=ax2)
plt.show()

gives:


问:
get method in Express-mongodb " Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"
I'm currently working in an api with mongodb-nodejs-express implementing a get method that finds all stores in my database using its id, the problem is I keep receiving the following error when I use the get method:

```<code>"error": "Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"
</code>```

This is the link I'm using to prove

```<code>http://localhost:4005/trading/store/1124
</code>```

This is the method I've implemmented

```<code>router.get('/store/:id', async (req, res) => {
    const { id } = req.params;
    const db = await connect();
    try{
    const result = await db.collection(collection).find({ store_id: ObjectID(id)});
    res.json(result)
    }
    catch (error) {
        res.status(500).json({ error: error.toString() });
    }
})
</code>```

This is an example of how my db looks

```<code>{
        "_id": "5cef828a7443855d02fc320e",
        "timestamp": "26/03/2019 18:34",
        "store_id": "1124",
        "user_id": "123",
        "product_id": "949",
        "price": "528"
    },
</code>```

I would really appreciate any hint or help and thanks in advance for taking the time to read my question.

答:
Your strore_id is just a string. So your query should be like this:</p>

```<code>db.collection.find({ store_id: id});
</code>```

Body:
I'm currently working in an api with mongodb-nodejs-express implementing a get method that finds all stores in my database using its id, the problem is I keep receiving the following error when I use the get method:

"error": "Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"

This is the link I'm using to prove

http://localhost:4005/trading/store/1124

This is the method I've implemmented

router.get('/store/:id', async (req, res) => {
    const { id } = req.params;
    const db = await connect();
    try{
    const result = await db.collection(collection).find({ store_id: ObjectID(id)});
    res.json(result)
    }
    catch (error) {
        res.status(500).json({ error: error.toString() });
    }
})

This is an example of how my db looks

{
        "_id": "5cef828a7443855d02fc320e",
        "timestamp": "26/03/2019 18:34",
        "store_id": "1124",
        "user_id": "123",
        "product_id": "949",
        "price": "528"
    },

I would really appreciate any hint or help and thanks in advance for taking the time to read my question.

Body:
Your strore_id is just a string. So your query should be like this:

db.collection.find({ store_id: id});


问:
Can Jackson's node structure be used to write XML?
I'm trying to set up code to create a node tree using jackson which can then be used to write either JSON or XML. I can get the JSON working, but I was hoping to get it outputting XML this way as well.

My example tree would look like this:

```<code>XmlMapper NodeMap = new XmlMapper();

ObjectNode rootNode = NodeMap.createObjectNode();
ObjectNode currentNode = rootNode.putObject("Examples");
currentNode
        .put("Puppy", TRUE)
        .put("Apple", 2)
        .put("Jet", "Li");
currentNode = rootNode.putObject("Single");
currentNode.put("One", 1);
</code>```

Using this tree I can use

```<code>String xml = rootNode.toString();
</code>```

to get

```<code>{"Examples":{"Puppy":true,"Apple":2,"Jet":"Li"},"Single":{"One":1}}
</code>```

which shows the tree has been built correctly, but I've been hoping it would output XML because I'm attaching the tree to an XmlMapper. That alone doesn't seem to be enough, unfortunately.

I know I can take another object and do something like

```<code>XmlMapper XMap = new XmlMapper();
XMap.writeValue(new File(writePath), objectToBeConverted);
</code>```

to get XML but I'm looking to use the nodetree above and .writevalue doesn't seem to work with the nodes.

How would I take the above tree and output (to a String or a file) as XML? Is it possible or am I out of luck with this method?

EDIT: I'm using Jackson version 2.9.2

EDIT2: Turns out I had multiple versions of jackson overlapping, as andrii mentions in the comments under his answer.

答:
you should use writeValueAsString, e.g.:

```<code>    XmlMapper mapper = new XmlMapper();

    com.fasterxml.jackson.databind.node.ObjectNode rootNode = mapper.createObjectNode();
    ObjectNode currentNode = rootNode.putObject("Examples");
    currentNode
            .put("Puppy", true)
            .put("Apple", 2)
            .put("Jet", "Li");
    currentNode = rootNode.putObject("Single");
    currentNode.put("One", 1);

    String xml = mapper.writeValueAsString(rootNode);
</code>```

In addition, I think you're using incompatible dependency version. I was able to reproduce your error having jackson-dataformat-xml:2.9.2 and old jackson-core:2.6.7. Make sure you'r using compatible versions for jackson-dataformat-xml dependencies.

Body:
I'm trying to set up code to create a node tree using jackson which can then be used to write either JSON or XML. I can get the JSON working, but I was hoping to get it outputting XML this way as well.

My example tree would look like this:

XmlMapper NodeMap = new XmlMapper();

ObjectNode rootNode = NodeMap.createObjectNode();
ObjectNode currentNode = rootNode.putObject("Examples");
currentNode
        .put("Puppy", TRUE)
        .put("Apple", 2)
        .put("Jet", "Li");
currentNode = rootNode.putObject("Single");
currentNode.put("One", 1);

Using this tree I can use

String xml = rootNode.toString();

to get

{"Examples":{"Puppy":true,"Apple":2,"Jet":"Li"},"Single":{"One":1}}

which shows the tree has been built correctly, but I've been hoping it would output XML because I'm attaching the tree to an XmlMapper. That alone doesn't seem to be enough, unfortunately.

I know I can take another object and do something like

XmlMapper XMap = new XmlMapper();
XMap.writeValue(new File(writePath), objectToBeConverted);

to get XML but I'm looking to use the nodetree above and .writevalue doesn't seem to work with the nodes.

How would I take the above tree and output (to a String or a file) as XML? Is it possible or am I out of luck with this method?

EDIT: I'm using Jackson version 2.9.2

EDIT2: Turns out I had multiple versions of jackson overlapping, as andrii mentions in the comments under his answer.

Body:
you should use writeValueAsString, e.g.:

    XmlMapper mapper = new XmlMapper();

    com.fasterxml.jackson.databind.node.ObjectNode rootNode = mapper.createObjectNode();
    ObjectNode currentNode = rootNode.putObject("Examples");
    currentNode
            .put("Puppy", true)
            .put("Apple", 2)
            .put("Jet", "Li");
    currentNode = rootNode.putObject("Single");
    currentNode.put("One", 1);

    String xml = mapper.writeValueAsString(rootNode);

In addition, I think you're using incompatible dependency version. I was able to reproduce your error having jackson-dataformat-xml:2.9.2 and old jackson-core:2.6.7. Make sure you'r using compatible versions for jackson-dataformat-xml dependencies.


问:
r - Project Euler 40: getting the final digit wrong

An irrational decimal fraction is created by concatenating the
  positive integers:

0.123456789101112131415161718192021...

It can be seen that the 12th digit of the fractional part is 1.

If dn represents the nth digit of the fractional part, find the value
  of the following expression.

d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000

Problem source here.

I wrote the following code to calculate the digits:

```<code>ans = data.frame(matrix(ncol = 6, nrow=2))
colnames(ans) = c(10,100,1000,10000,100000,1000000)
rownames(ans) = c("length","number")

counter = 1
for(i in c(10,100,1000,10000,100000,1000000))
{
  c = 0
  num = 0

  while (c<i)
  {
    num = num + 1
    c = c + nchar(as.character(num))
  }

  ans[1, counter] = c
  ans[2, counter] = num

  counter = counter + 1
}
</code>```

The output, is:

```<code>> ans
       10 100 1000 10000  1e+05   1e+06
length 11 101 1002 10001 100004 1000004
number 10  55  370  2777  22222  185185
</code>```

In other words, when the irrational number is 11 digit long, its final two digits are 10, which means its 10th digit is 1. When the irrational number is 1002 digits long, its final three digits are 370, which means its 1000th digit is 3. And so on.

From this, the answer I get is: 1 * 1 * 5 * 3 * 7 * 2 * 8. However, the correct answer is 1 * 1 * 5 * 3 * 7 * 2 * 1. It just beats me how it is able to produce correct answers until the final digit.

答:
Here is solution on Python:</p>

```<code>from functools import reduce

def elems_total(elem1, elem2):
    return elem1 * elem2

# store the values
fraction = ''.join([str(x) for x in range(1,1000000)])
total = 1

# get [0, 9, 99 ... 999999]
digits_only_9 = [x for x in range(0, 1000000) if x % 9 == 0 and \
                 len(set(str(x))) == 1 and \
                 str(x).endswith('9')]

summa = reduce(elems_total, [int(fraction[i]) for i in digits_only_9])
print(summa)  # 210
</code>```

Body:
An irrational decimal fraction is created by concatenating the
  positive integers:

0.123456789101112131415161718192021...

It can be seen that the 12th digit of the fractional part is 1.

If dn represents the nth digit of the fractional part, find the value
  of the following expression.

d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000

Problem source here.

I wrote the following code to calculate the digits:

ans = data.frame(matrix(ncol = 6, nrow=2))
colnames(ans) = c(10,100,1000,10000,100000,1000000)
rownames(ans) = c("length","number")

counter = 1
for(i in c(10,100,1000,10000,100000,1000000))
{
  c = 0
  num = 0

  while (c<i)
  {
    num = num + 1
    c = c + nchar(as.character(num))
  }

  ans[1, counter] = c
  ans[2, counter] = num

  counter = counter + 1
}

The output, is:

> ans
       10 100 1000 10000  1e+05   1e+06
length 11 101 1002 10001 100004 1000004
number 10  55  370  2777  22222  185185

In other words, when the irrational number is 11 digit long, its final two digits are 10, which means its 10th digit is 1. When the irrational number is 1002 digits long, its final three digits are 370, which means its 1000th digit is 3. And so on.

From this, the answer I get is: 1 * 1 * 5 * 3 * 7 * 2 * 8. However, the correct answer is 1 * 1 * 5 * 3 * 7 * 2 * 1. It just beats me how it is able to produce correct answers until the final digit.

Body:
Here is solution on Python:

from functools import reduce

def elems_total(elem1, elem2):
    return elem1 * elem2

# store the values
fraction = ''.join([str(x) for x in range(1,1000000)])
total = 1

# get [0, 9, 99 ... 999999]
digits_only_9 = [x for x in range(0, 1000000) if x % 9 == 0 and \
                 len(set(str(x))) == 1 and \
                 str(x).endswith('9')]

summa = reduce(elems_total, [int(fraction[i]) for i in digits_only_9])
print(summa)  # 210


问:
How can I initially apply styling after a component mounts but still respect CSS transitions?
So I'm trying to add some transitions to my react components but can't seem to get it working in ComponentDidMount().  If I have the styling applied onClick, e.g. height: 100%, it will respect the transition on height.  But if I change the styling in ComponentDidMount() it applies it instantly.

For instance this works:

```<code>render() {
    return (
        <div
            className="board"
            onClick={() => {this.element.style.opacity = 1}}>
        </div>
    )
}
</code>```

but this doesn't (at least not as intended):

```<code>componentDidMount() {
    this.element.style.opacity = 1;
}
render() {
    return (
        <div className="board"></div>
    )
}
</code>```

Here's the styling:

.board {
    background: darkslateblue;
    display: inline-block;
    border-radius: 1rem;
    opacity: 0;
    margin: 2rem 0;
    padding: 4rem;
    transition: opacity 2s;
}
```

I'm hoping for the transition to be followed but it's ignoring the transition when changing the styling right off the bat.

答:
try it, this work fine, define setInterval:

```<code>componentDidMount() {
    setInterval(() => {
      this.element.style.opacity = 1;
      this.element.style.width = "230px";
    },1)
  }
</code>```

Body:
So I'm trying to add some transitions to my react components but can't seem to get it working in ComponentDidMount().  If I have the styling applied onClick, e.g. height: 100%, it will respect the transition on height.  But if I change the styling in ComponentDidMount() it applies it instantly.

For instance this works:

render() {
    return (

 {this.element.style.opacity = 1}}>

    )
}

but this doesn't (at least not as intended):

componentDidMount() {
    this.element.style.opacity = 1;
}
render() {
    return (

    )
}

Here's the styling:

.board {
    background: darkslateblue;
    display: inline-block;
    border-radius: 1rem;
    opacity: 0;
    margin: 2rem 0;
    padding: 4rem;
    transition: opacity 2s;
}

I'm hoping for the transition to be followed but it's ignoring the transition when changing the styling right off the bat.

Body:
try it, this work fine, define setInterval:

componentDidMount() {
    setInterval(() => {
      this.element.style.opacity = 1;
      this.element.style.width = "230px";
    },1)
  }


问:
Displaying Json object as a string instead of actual object
I have a function that populates a modal. I would like the modal to show the string from the data, not the JSON object or the JSON obj in string format. ... however it appears to be displaying the literal Json object...I cannot use a toString method because it appears it does not exist. Below is my code.

Modal:

```<code><div class="modal fade" id="receiptModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title">Receipt</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">×</span>
            </button>
        </div>
        <div class="modal-body">
           <div id="receiptTxt">

           </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
        </div>
    </div>
</div>
</code>```

JS:

```<code>  $(".viewReceipt").click(function (e) {

    var rowId = "#" + $(this).data("rowindex");
    var row = $(rowId);
    var transactionID = row.find(".transactionID").html().trim();

    var data = {
        receiptID: transactionID
    };

    console.log("data");
    console.log(data);

    $.ajax({
        url: '@Url.Action("ViewReceipt", "TerminalReceipts")',
        type: "POST",
        data: data,
        dataType: 'html',
        success: function (data) {
            console.log("Success");
            console.log(data)
            $("#receiptTxt").html(data);
            $("#receiptModal").modal('toggle');
        }
    });
});
</code>```

As you can see $("#receiptTxt").html(data); is the issue. It is literally displaying the data obj. I cannot do .html(data).toString().. what other options are there??

@edit

As requested, here is the output of console.log(data)

```<code>{"data":"                  Company Name                   \r\n          2222 Ridgelake Dr           \r\n              Cape Coral, FL, 90726               \r\n                                                \r\n                                                \r\n\r\n              10/4/2018 7:21:13 AM              \r\n\r\number: ABC123                        TID: ABC123\r\nBatch #:                                       0\r\nAccount #:                      XXXXXXXXXXXX2222\r\nTrans #:                                     378\r\nAuth #:                                 00056693\r\nHost Date:                             10/4/2018\r\nHost Time:                              09:24:50\r\nSoftware Version:                        1.0.0.0\r\n\r\n              THIS IS A DEMO                   \r\nTotal:                                    $5.00\r\n                    APPROVED                    \r\n\r\n              THANK YOU VERY MUCH!              \r\n\r\n"}
</code>```

答:
This will give you a nicely formatted JSON string with indentation:

```<code>$("#receiptTxt").html(JSON.stringify(data, null, 2));
</code>```

You will need to insert it into a ``` element instead of a
 to ensure new lines are correctly displayed.

Body:
I have a function that populates a modal. I would like the modal to show the string from the data, not the JSON object or the JSON obj in string format. ... however it appears to be displaying the literal Json object...I cannot use a toString method because it appears it does not exist. Below is my code.

Modal:

Receipt

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×
            </button>

            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>

JS:

  $(".viewReceipt").click(function (e) {

    var rowId = "#" + $(this).data("rowindex");
    var row = $(rowId);
    var transactionID = row.find(".transactionID").html().trim();

    var data = {
        receiptID: transactionID
    };

    console.log("data");
    console.log(data);

    $.ajax({
        url: '@Url.Action("ViewReceipt", "TerminalReceipts")',
        type: "POST",
        data: data,
        dataType: 'html',
        success: function (data) {
            console.log("Success");
            console.log(data)
            $("#receiptTxt").html(data);
            $("#receiptModal").modal('toggle');
        }
    });
});

As you can see $("#receiptTxt").html(data); is the issue. It is literally displaying the data obj. I cannot do .html(data).toString().. what other options are there??

@edit

As requested, here is the output of console.log(data)

{"data":"                  Company Name                   \r\n          2222 Ridgelake Dr           \r\n              Cape Coral, FL, 90726               \r\n                                                \r\n                                                \r\n\r\n              10/4/2018 7:21:13 AM              \r\n\r\number: ABC123                        TID: ABC123\r\nBatch #:                                       0\r\nAccount #:                      XXXXXXXXXXXX2222\r\nTrans #:                                     378\r\nAuth #:                                 00056693\r\nHost Date:                             10/4/2018\r\nHost Time:                              09:24:50\r\nSoftware Version:                        1.0.0.0\r\n\r\n              THIS IS A DEMO                   \r\nTotal:                                    $5.00\r\n                    APPROVED                    \r\n\r\n              THANK YOU VERY MUCH!              \r\n\r\n"}

Body:
This will give you a nicely formatted JSON string with indentation:

$("#receiptTxt").html(JSON.stringify(data, null, 2));

You will need to insert it into a <pre> element instead of a <div> to ensure new lines are correctly displayed.


问:
What does useContext really do?
I'm quite hooked by React but one big question arises to me regarding useContext. It's quite confusing to really know how it's inner workings are.. Like it magically works.

So I have in my main module this:

```<code>
export const Context = React.createContext(SOMEVALUE) // why set this initial value here

const [value, setValue] = useState(SOMEVALUE) // why set this here again?

return(
<Context.Provider value={[value, setValue]}> // why do i have to pass this  inital value here?
<App />
</Context.Provider>
)
</code>```

Next some module inside

```<code>import { Context } from './Main' // why import this when everything was passed?

...

const [value, setValue] = useContext(Context.offline) // what does this help?

</code>```

Now here come's my question:

Why is importing the Context from Main required, and how does React make a connection to the state using this?

答:
- What is the value passed into createContext for?

```<code>export const Context = React.createContext(SOMEVALUE)
</code>```

The value passed in to React.createContext is a fallback value which will ONLY be used if a Context.Consumer is used outside of its Context.Provider. This is different than an initial value.

- Why is the same fallback value being used in useState?

```<code>const [value, setValue] = useState(SOMEVALUE)
</code>```

Using the same value as an initial value and a fallback value is preference and will change based on the use case. This piece is actually setting an initial value, and providing a mechanism to both keep track of and change that value.

- Why do I have to pass the initial value to Context.Provider?

```<code><Context.Provider value={[value, setValue]}>
</code>```

The Context.Provider acts like the publisher in a publisher/subscriber system. It's going to broadcast these values set here to any of the matching Context.Consumers. It does not keep track of the value or provide mechanisms for changing that tracked state. useState from above does that. Context.Provider is just "broadcasting" the value and the function to change that value.

- Why do I have to import the Context I created?

```<code>import { Context } from './Main'

const [ value, setValue ] = useContext(Context)
</code>```

import { Context } is importing the Context object you created and exported from './Main'. The same Context object you're using to render the Provider. This is used to make sure the right Provider is referenced when subscribing.

Prior to hooks, you would subscribe to a react context via: static contextType = MyContext in a class, or with <MyContext.Consumer>. useContext is just another api for doing this as a hook. You have to pass it a Context object so it knows which Context.Provider to subscribe to since there can be any number of them.

Documentation for Context here

Title: What does useContext really do?

Body:
I'm quite hooked by React but one big question arises to me regarding useContext. It's quite confusing to really know how it's inner workings are.. Like it magically works.

So I have in my main module this:

export const Context = React.createContext(SOMEVALUE) // why set this initial value here

const [value, setValue] = useState(SOMEVALUE) // why set this here again?

return(
<Context.Provider value={[value, setValue]}> // why do i have to pass this  inital value here?
<App />
</Context.Provider>
)

Next some module inside

import { Context } from './Main' // why import this when everything was passed?

...

const [value, setValue] = useContext(Context.offline) // what does this help?

Now here come's my question:

Why is importing the Context from Main required, and how does React make a connection to the state using this?

Body:
- What is the value passed into createContext for?

export const Context = React.createContext(SOMEVALUE)

The value passed in to React.createContext is a fallback value which will ONLY be used if a Context.Consumer is used outside of its Context.Provider. This is different than an initial value.

- Why is the same fallback value being used in useState?

const [value, setValue] = useState(SOMEVALUE)

Using the same value as an initial value and a fallback value is preference and will change based on the use case. This piece is actually setting an initial value, and providing a mechanism to both keep track of and change that value.

- Why do I have to pass the initial value to Context.Provider?

<Context.Provider value={[value, setValue]}>

The Context.Provider acts like the publisher in a publisher/subscriber system. It's going to broadcast these values set here to any of the matching Context.Consumers. It does not keep track of the value or provide mechanisms for changing that tracked state. useState from above does that. Context.Provider is just "broadcasting" the value and the function to change that value.

- Why do I have to import the Context I created?

import { Context } from './Main'

const [ value, setValue ] = useContext(Context)

import { Context } is importing the Context object you created and exported from './Main'. The same Context object you're using to render the Provider. This is used to make sure the right Provider is referenced when subscribing.

Prior to hooks, you would subscribe to a react context via: static contextType = MyContext in a class, or with <MyContext.Consumer>. useContext is just another api for doing this as a hook. You have to pass it a Context object so it knows which Context.Provider to subscribe to since there can be any number of them.

Documentation for Context here


问:
How to delegate back to the previous veiwcontroller
here is my navigation on my app

1) homescreenview controller-->composemessageviewcontroller (i am able to use delegate to send data back to homescreenview)

2)homescreenview controller -->messageslistcontroller(tableview)-->detailmessageviewcontroller(which is where my reply button is).

my problem is when i hit reply i want to send back information to homescreenviewcontroller with delegate . how can i do this?

Thanks in advance.

----UPDATE

@XJones, thanks for the detailed explanaion. is this what is should be doing in when i push detailview? please correct me if i am wrong.

(void)pushDetailMessageController{
DetailMessagetController *detailmessage = [[DetailMessagetController alloc] init];
detailmessage.delegate = self;
// push messageListController onto navigation controller here
[detail release];
}

答:
that's a very general question. you're basically asking how to pass information from one controller to another controller. There are different ways to do that, a protocol (what a delegate generally communicates through) is one of them. The quickest thing you can do w/o making assumptions in your code that may be problematic later would be to pass the homeScreenController along as you push messageListController and then detailMessageController. You'll need to define an iVar and property in messageListController and detailMessageController to do this.

Something like:

in messageListController.h:

```<code>#import "HomeScreenController.h"

@interface messageListController : UITableViewController {
    // your iVars
    HomeScreenController *homeScreenController;
@end

@property (nonatomic, assign)    HomeScreenController *    homeScreenController;
</code>```

add the same iVar and property for homeScreenController to detailMessageController.

in homeScreenController.h:

```<code>- (void)pushMessageListController
{
    MessageListController *messageListController = [[MessageListController alloc] init];
    messageListController.homeScreenController = self;
    // push messageListController onto navigation controller here
    [messageListController release];
}
</code>```

in messageListController do the same thing as above when creating and pushing detailMessageController. Now, in detailMessageController you can send messages directly to homeScreenController.

If you want to generalize the above implementation so your controllers aren't specifically knowledgeable about each other then you can define a protocol and pass homeScreenController through as a delegate supporting that protocol.

Body:
that's a very general question. you're basically asking how to pass information from one controller to another controller. There are different ways to do that, a protocol (what a delegate generally communicates through) is one of them. The quickest thing you can do w/o making assumptions in your code that may be problematic later would be to pass the homeScreenController along as you push messageListController and then detailMessageController. You'll need to define an iVar and property in messageListController and detailMessageController to do this.

Something like:

in messageListController.h:

#import "HomeScreenController.h"

@interface messageListController : UITableViewController {
    // your iVars
    HomeScreenController *homeScreenController;
@end

@property (nonatomic, assign)    HomeScreenController *    homeScreenController;

add the same iVar and property for homeScreenController to detailMessageController.

in homeScreenController.h:

- (void)pushMessageListController
{
    MessageListController *messageListController = [[MessageListController alloc] init];
    messageListController.homeScreenController = self;
    // push messageListController onto navigation controller here
    [messageListController release];
}

in messageListController do the same thing as above when creating and pushing detailMessageController. Now, in detailMessageController you can send messages directly to homeScreenController.

If you want to generalize the above implementation so your controllers aren't specifically knowledgeable about each other then you can define a protocol and pass homeScreenController through as a delegate supporting that protocol.