问:
Passing down an array of Objects as props for a React Component
I want to pass down an array of Objects to a child component. Each child component should return the value of the respective index of dummyData.

Parent Component

```<code>export default function MainContent() {
  const dummyData = [
    {
      id: "1",
      cardIMG: "test.png",
      cardTitle: "Title",
      cardText: "Text"
    },
    {
      id: "2",
      cardIMG: "test1.png",
      cardTitle: "Title",
      cardText: "Text"
    }
  ];

  return (
    <div className="MainContainer">
      <Card props={dummyData} />
      <Card props={dummyData} />
    </div>
  );
}
</code>```

Child Component

```<code>export default function Card(props) {
  return (
    <div className="CardContainer">
      <div className="CardIMG">
        <img src={this.props.CardIMG} alt="" />
      </div>

      <div className="TextContent">
        <h2>{this.props.CardTitle}</h2>
        <p className="TextBlock">{this.props.CardText}</p>
        <button className="ReadMore">Read more</button>
      </div>
    </div>
  );
}
</code>```

答:
Since you are trying to iterate through an array, you have to loop through the items. You can use for, map or each, totally upto you.

Refer loops: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

You can basically do this in your parent component:

```<code>export default function MainContent() {
  const dummyData = [
    {
      id: "1",
      cardIMG: "test.png",
      cardTitle: "Title",
      cardText: "Text"
    },
    {
      id: "2",
      cardIMG: "test1.png",
      cardTitle: "Title",
      cardText: "Text"
    }
  ];

  return (
    <div className="MainContainer">
      {dummyData.map((data) => {
        <Card key={data.id} cardInfo={data} />
      })
    </div>
  );
}
</code>```

And in your child component(which is a functional component, so you can't use this in there), you can do

```<code>export default function Card(props) {
  return (
    <div className="CardContainer">
      <div className="CardIMG">
        <img src={props.cardInfo.cardIMG} alt="" />
      </div>

      <div className="TextContent">
        <h2>{props.cardInfo.CardTitle}</h2>
        <p className="TextBlock">{props.cardInfo.CardText}</p>
        <button className="ReadMore">Read more</button>
      </div>
    </div>
  );
}
</code>```

Body:
I want to pass down an array of Objects to a child component. Each child component should return the value of the respective index of dummyData.

Parent Component

export default function MainContent() {
  const dummyData = [
    {
      id: "1",
      cardIMG: "test.png",
      cardTitle: "Title",
      cardText: "Text"
    },
    {
      id: "2",
      cardIMG: "test1.png",
      cardTitle: "Title",
      cardText: "Text"
    }
  ];

  return (

      <Card props={dummyData} />
      <Card props={dummyData} />

  );
}

Child Component

export default function Card(props) {
  return (

{this.props.CardTitle}

{this.props.CardText}

        <button className="ReadMore">Read more</button>

  );
}

Body:
Since you are trying to iterate through an array, you have to loop through the items. You can use for, map or each, totally upto you.

Refer loops: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

You can basically do this in your parent component:

export default function MainContent() {
  const dummyData = [
    {
      id: "1",
      cardIMG: "test.png",
      cardTitle: "Title",
      cardText: "Text"
    },
    {
      id: "2",
      cardIMG: "test1.png",
      cardTitle: "Title",
      cardText: "Text"
    }
  ];

  return (
    <div className="MainContainer">
      {dummyData.map((data) => {
        <Card key={data.id} cardInfo={data} />
      })
    </div>
  );
}

And in your child component(which is a functional component, so you can't use this in there), you can do

export default function Card(props) {
  return (
    <div className="CardContainer">
      <div className="CardIMG">
        <img src={props.cardInfo.cardIMG} alt="" />
      </div>

      <div className="TextContent">
        <h2>{props.cardInfo.CardTitle}</h2>
        <p className="TextBlock">{props.cardInfo.CardText}</p>
        <button className="ReadMore">Read more</button>
      </div>
    </div>
  );
}


来源: stackexchange

问:
What features are people looking forward to in .Net 4.0 - 4.1
I am very interested in learning what features people are interested in in the forthcoming .net framework(s)?

Whether these be new classes or new controls I am curious to know people views.

答: A framework tuple class and C#4 'dynamic', which I'm going to use everywhere to get one up on people who use 'var' everywhere.   (I know 'dynamic' is not a pure framework feature - but it's part framework)</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Will Dean


问:
import geofire-common with firestore for browser code
I'm a bit confused trying to use geofire-common in browser code.

In the beginning, I've made a successful attempt with NodeJS which uses geofire-common referenced here in the Google documentation and which code looks like this:

import { createRequire } from 'module'; // <------ trick to get a require function
const require = createRequire(import.meta.url);

const { initializeApp, cert } = require('firebase-admin/app');
const { getFirestore } = require('firebase-admin/firestore');

const serviceAccount = require('./serviceAccountKey.json');

initializeApp({
  credential: cert(serviceAccount),
});

const db = getFirestore();
const geofire = require('geofire-common'); //<---------- geofire-common
```
<p>Then, I wanted to make this work from the browser side... and I stumbled uponthis example. In this example, I can see a 'require' function so I guess it has something to do with old school commonJS module:</p>
<pre class="lang-js prettyprint-override"><code>const geofire = require('geofire-common');
</code>```

Require is not part of the standard JavaScript API and should be NodeJS specific (which is a bit strange because i thought the example was browser code), so I've tried to use an ES6 import..

import {geofire} from 'geofire-common';
```
<p>... without success :</p>
<pre class="lang-sh prettyprint-override"><code>The requested module '/node_modules/.vite/geofire-common.js?v=738ba8db' does not provide an export named 'geofire'
</code>```

If some of the JS experts around would be willing to shed some light about those 2 packages and help me to correctly import geofire if it's possible, that would be much appreciated.

答:
I think you can use</p>
```<code>import * as geofire from 'geofire-common';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm a bit confused trying to use geofire-common in browser code.

In the beginning, I've made a successful attempt with NodeJS which uses geofire-common referenced here in the Google documentation and which code looks like this:

import { createRequire } from 'module'; // <------ trick to get a require function
const require = createRequire(import.meta.url);

const { initializeApp, cert } = require('firebase-admin/app');
const { getFirestore } = require('firebase-admin/firestore');

const serviceAccount = require('./serviceAccountKey.json');

initializeApp({
  credential: cert(serviceAccount),
});

const db = getFirestore();
const geofire = require('geofire-common'); //<---------- geofire-common

Then, I wanted to make this work from the browser side... and I stumbled uponthis example. In this example, I can see a 'require' function so I guess it has something to do with old school commonJS module:

const geofire = require('geofire-common');

Require is not part of the standard JavaScript API and should be NodeJS specific (which is a bit strange because i thought the example was browser code), so I've tried to use an ES6 import..

import {geofire} from 'geofire-common';

... without success :

The requested module '/node_modules/.vite/geofire-common.js?v=738ba8db' does not provide an export named 'geofire'

If some of the JS experts around would be willing to shed some light about those 2 packages and help me to correctly import geofire if it's possible, that would be much appreciated.

Body:
I think you can use

import * as geofire from 'geofire-common';


问:
Join on Id in Variant (Array) Snowflake
I have two tables t1 and t2 created as follows:

Create Tables

```<code>CREATE TABLE t1(
    id integer AUTOINCREMENT START 1 INCREMENT 1,
    name varchar(10) DEFAULT RANDSTR(10, random()),
    id_array variant,
)

CREATE TABLE t2(
    id integer AUTOINCREMENT START 1 INCREMENT 1,
    name varchar(10) DEFAULT RANDSTR(10, random())
)
</code>```

Goal

I am looking to join t2 to t1 if the id of the record exists in the t1 variant array.

What I've Tried

I came across the ARRAY_CONTAINS function which looked perfect. But with the following I am receiving no results:

```<code>SELECT t1.id, t2.name
FROM t1, t2
WHERE ARRAY_CONTAINS(t1.id_array, array_construct(t2.id))
</code>```

How Do I Get This?

Any suggestions on how to achieve the following result?

```<code>t1 record:
{id: 1, name: 'A-123', ids_array: '["1", "2"]'}

t2 records:
{id: 1, name: 'test'},
{id: 2, name: 'test2'}
</code>```

Desired Result

```<code>{id: 1, name: 'A-123', joined_name: 'test'},

{id: 1, name: 'A-123', joined_name: 'test2'}
</code>```

答:
So to debug what's happening I added more and more line to the below SQL, but the short story is you have the parameters to ARRAY_CONTAINS back to front:

```<code>WITH t1(id, name, ids_array) AS (
    SELECT column1, column2, SPLIT(column3,',') FROM VALUES
        (1, 'A-123', '1,2')
), t2(id, name) AS (
    SELECT column1, column2 FROM VALUES
        (1, 'test'),
        (2, 'test2')
)
SELECT t1.id
    ,t2.name
    ,t2.id
    ,t1.ids_array
    ,ARRAY_CONTAINS('1'::variant, t1.ids_array) as const_1
    ,ARRAY_CONTAINS('2'::variant, t1.ids_array) as const_2
    ,t2.id::text::variant as v1
    ,ARRAY_CONTAINS(v1, t1.ids_array) as it_works
FROM t1, t2
</code>```

gives:

ID
NAME
ID
IDS_ARRAY
CONST_1
CONST_2
V1
IT_WORKS

1
test
1
[    "1",    "2"  ]
TRUE
TRUE
"1"
TRUE

1
test2
2
[    "1",    "2"  ]
TRUE
TRUE
"2"
TRUE

so now using the correct form:

```<code>WITH t1(id, name, ids_array) AS (
    SELECT column1, column2, SPLIT(column3,',') FROM VALUES
        (1, 'A-123', '1,2')
), t2(id, name) AS (
    SELECT column1, column2 FROM VALUES
        (1, 'test'),
        (2, 'test2')
)
SELECT t1.id
    ,t2.name
FROM t1, t2
WHERE ARRAY_CONTAINS(t2.id::text::variant, t1.ids_array)
</code>```

we get:

ID
NAME

1
test

1
test2

Title: Join on Id in Variant (Array) Snowflake

Body:
I have two tables t1 and t2 created as follows:

Create Tables

CREATE TABLE t1(
    id integer AUTOINCREMENT START 1 INCREMENT 1,
    name varchar(10) DEFAULT RANDSTR(10, random()),
    id_array variant,
)

CREATE TABLE t2(
    id integer AUTOINCREMENT START 1 INCREMENT 1,
    name varchar(10) DEFAULT RANDSTR(10, random())
)

Goal

I am looking to join t2 to t1 if the id of the record exists in the t1 variant array.

What I've Tried

I came across the ARRAY_CONTAINS function which looked perfect. But with the following I am receiving no results:

SELECT t1.id, t2.name
FROM t1, t2
WHERE ARRAY_CONTAINS(t1.id_array, array_construct(t2.id))

How Do I Get This?

Any suggestions on how to achieve the following result?

t1 record:
{id: 1, name: 'A-123', ids_array: '["1", "2"]'}

t2 records:
{id: 1, name: 'test'},
{id: 2, name: 'test2'}

Desired Result

{id: 1, name: 'A-123', joined_name: 'test'},

{id: 1, name: 'A-123', joined_name: 'test2'}

Body:
So to debug what's happening I added more and more line to the below SQL, but the short story is you have the parameters to ARRAY_CONTAINS back to front:

WITH t1(id, name, ids_array) AS (
    SELECT column1, column2, SPLIT(column3,',') FROM VALUES
        (1, 'A-123', '1,2')
), t2(id, name) AS (
    SELECT column1, column2 FROM VALUES
        (1, 'test'),
        (2, 'test2')
)
SELECT t1.id
    ,t2.name
    ,t2.id
    ,t1.ids_array
    ,ARRAY_CONTAINS('1'::variant, t1.ids_array) as const_1
    ,ARRAY_CONTAINS('2'::variant, t1.ids_array) as const_2
    ,t2.id::text::variant as v1
    ,ARRAY_CONTAINS(v1, t1.ids_array) as it_works
FROM t1, t2

gives:

ID
NAME
ID
IDS_ARRAY
CONST_1
CONST_2
V1
IT_WORKS

1
test
1
[    "1",    "2"  ]
TRUE
TRUE
"1"
TRUE

1
test2
2
[    "1",    "2"  ]
TRUE
TRUE
"2"
TRUE

so now using the correct form:

WITH t1(id, name, ids_array) AS (
    SELECT column1, column2, SPLIT(column3,',') FROM VALUES
        (1, 'A-123', '1,2')
), t2(id, name) AS (
    SELECT column1, column2 FROM VALUES
        (1, 'test'),
        (2, 'test2')
)
SELECT t1.id
    ,t2.name
FROM t1, t2
WHERE ARRAY_CONTAINS(t2.id::text::variant, t1.ids_array)

we get:

ID
NAME

1
test

1
test2


问:
azure Subscription " You are not eligible for an Azure subscription"
I have signed up using my Gmail id for a free Azure subscription. After entering details and credit card information I have accepted terms & condition. Onclick of submitting I am getting the message You are not eligible for an Azure subscription
.

答:
The information that you provided for your Azure account profile (including contact email address, street address, and telephone number) should be correct and most importantly You don't already have a Microsoft account that uses the same information

https://learn.microsoft.com/en-us/azure/cost-management-billing/manage/troubleshoot-azure-sign-up


问:
Re-format table, placing multiple column headers as rows
I have a table of fishing catches, showing number of fish and total kg, for all the fishing days. Current format of the data is showing as below

In the other reference table is a list of all the official fish species with codes and names.

How can I re-format the first table so the rows are repeated for each day showing a certain species with the corresponding total catches and kgs in a row. So instead of the species kg and n having their different columns, I would have them in rows while there is only one n and kg column.  I am thinking of looping through the list of all species and based on the numbers it will duplicate the rows in a way with the right values of n and kg of the species in the rows. This is the final format I need. My database is SQL Server.

答:
You can also use a cross apply here, e.g.:

/*
 * Data setup...
 */
create table dbo.Source (
  Day int,
  ALB_n int,
  ALB_kg int,
  BET_n int,
  BET_kg int,
  SWO_n int,
  SWO_kg int
);
insert dbo.Source (Day, ALB_n, ALB_kg, BET_n, BET_kg, SWO_n, SWO_kg) values
  (1, 10, 120, 4, 60, 2, 55),
  (2, 15, 170, 8, 100, 1, 30);
create table dbo.Species (
  Sp_id int,
  Sp_name nvarchar(20)
);
insert dbo.Species (Sp_id, Sp_name) values
  (1, N'Albacore'),
  (2, N'Big eye tuna'),
  (3, N'Sword fish');
/*
 * Unpivot data using cross apply...
 */
select Day, Sp_name as Species, n, kg
from dbo.Source
cross apply dbo.Species
cross apply (
  select
    case
      when Sp_name=N'Albacore' then ALB_n
      when Sp_name=N'Big eye tuna' then BET_n
      when Sp_name=N'Sword fish' then SWO_n
    else null end as n,
    case
      when Sp_name=N'Albacore' then ALB_kg
      when Sp_name=N'Big eye tuna' then BET_kg
      when Sp_name=N'Sword fish' then SWO_kg
    else null end as kg
) unpivotted (n, kg);
```


问:
How do I add a hyperlink in my text using JavaScript?
I'm really new to JS and I tried googling but it did not help. All I'm trying to do is add the medium Post link into my text as a hyperlink. I'm pretty sure I'm half way there but I can't figure it out:

_$ = document.querySelector.bind(document) ;
var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs
var a = document.createElement('a');
a.text = "Medium Post";
a.href = "https://medium.com/@FundsFi/fundsfi-presale-terms-are-here-whitelisting-requirements-fc798d85b284";

// AppendLinkHere.appendChild(a)
// a.title = 'Well well ...
// a.setAttribute('title', 'Well well that\'s a link');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><s.TextDescription style={{ textAlign: "center", color: "var(--primary-text)", }}>
  blah blah blah blah blah blah blah blah blah blah  Medium Post.
</s.TextDescription></code>```

All I want to do is make it so that when people click on the word Medium Post it takes them to a new tab with the medium link. Also, I got the code from this post while searching for an answer: How do I create a link using javascript? And then I realized that I need to added a CSS selector which I can't figure out how to do. So far I've found this post about: How do you add CSS with Javascript?

答:
If you're wanting it to be javascript this might help.

// create anchor link element
let link = document.createElement("a")

// Create txt
let txt = document.createTextNode("Medium Post")

//append txt to anchor element
link.appendChild(txt)

// set the title
link.title ="Medium Post";

// set the href property
link.href = "https://www.medium.com";

// get text to add link to
let el = document.getElementById("p")

// append the link to the el id = "p"
el.appendChild(link)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="textDescription">
  <p id="p">blah blah blah blah blah blah blah blah blah blah </p>
</div></code>```

Hope this helps, let me know if you have any questions.

Body:
I'm really new to JS and I tried googling but it did not help. All I'm trying to do is add the medium Post link into my text as a hyperlink. I'm pretty sure I'm half way there but I can't figure it out:

_$ = document.querySelector.bind(document) ;
var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs
var a = document.createElement('a');
a.text = "Medium Post";
a.href = "https://medium.com/@FundsFi/fundsfi-presale-terms-are-here-whitelisting-requirements-fc798d85b284";

// AppendLinkHere.appendChild(a)
// a.title = 'Well well ...
// a.setAttribute('title', 'Well well that\'s a link');

<s.TextDescription style={{ textAlign: "center", color: "var(--primary-text)", }}>
  blah blah blah blah blah blah blah blah blah blah  Medium Post.
</s.TextDescription>

All I want to do is make it so that when people click on the word Medium Post it takes them to a new tab with the medium link. Also, I got the code from this post while searching for an answer: How do I create a link using javascript? And then I realized that I need to added a CSS selector which I can't figure out how to do. So far I've found this post about: How do you add CSS with Javascript?

Body:
If you're wanting it to be javascript this might help.

// create anchor link element
let link = document.createElement("a")

// Create txt
let txt = document.createTextNode("Medium Post")

//append txt to anchor element
link.appendChild(txt)

// set the title
link.title ="Medium Post";

// set the href property
link.href = "https://www.medium.com";

// get text to add link to
let el = document.getElementById("p")

// append the link to the el id = "p"
el.appendChild(link)

<div class="textDescription">
  <p id="p">blah blah blah blah blah blah blah blah blah blah </p>
</div>

Hope this helps, let me know if you have any questions.


问:
How to set String value of xAxis in MPAndroidChart?
I want to make Line Chart Graph, but i have problem to show value string in xAxis, im used Library Github from MPAndroidChart to LineChart. Please help me how to add String Value and actually to much question i want ask

```<code>private void drawLineChartLine(){

        private float[] yDataL = {40, 60, 70, 80};
        private String[] xDataL = {"Week 1", "Week 1" , "Week 3" , "Week 4"};

        ArrayList<Entry> yEntrys = new ArrayList<>();

        final ArrayList<String> xEntrys = new ArrayList<>();

        for(int i = 0; i < yDataL.length; i++){
            yEntrys.add(new Entry(yDataL[i] ,i));
        }

        for(int i = 1; i < xDataL.length; i++){
            xEntrys.add(xDataL[i]);
        }

        //create the data set
        LineDataSet lineDataset = new LineDataSet(yEntrys, "assa");

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);

        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xEntrys.get((int) value);
            }
        });

        LineData lineData = new LineData(lineDataset);
        lineChart.setData(lineData);
        lineChart.invalidate();
}
</code>```

i got error

Invalid index 40, size is 6

in Code

```<code>xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xEntrys.get((int) value);
            }
        });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to make Line Chart Graph, but i have problem to show value string in xAxis, im used Library Github from MPAndroidChart to LineChart. Please help me how to add String Value and actually to much question i want ask

private void drawLineChartLine(){

        private float[] yDataL = {40, 60, 70, 80};
        private String[] xDataL = {"Week 1", "Week 1" , "Week 3" , "Week 4"};

        ArrayList<Entry> yEntrys = new ArrayList<>();

        final ArrayList<String> xEntrys = new ArrayList<>();

        for(int i = 0; i < yDataL.length; i++){
            yEntrys.add(new Entry(yDataL[i] ,i));
        }

        for(int i = 1; i < xDataL.length; i++){
            xEntrys.add(xDataL[i]);
        }

        //create the data set
        LineDataSet lineDataset = new LineDataSet(yEntrys, "assa");

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);

        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xEntrys.get((int) value);
            }
        });

        LineData lineData = new LineData(lineDataset);
        lineChart.setData(lineData);
        lineChart.invalidate();
}

i got error

Invalid index 40, size is 6

in Code

xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xEntrys.get((int) value);
            }
        });

Body:
//修改X轴内容成字符日期
xAxis.setValueFormatter(new IndexAxisValueFormatter(date));


问:
Kable conditional coloring using row_spec
I'm trying to color cells in each row based on a condition using kable. I saw a few examples of column_spec and cell_spec because it's still a bit manual since I'm interested in conditional coloring by row. Here's an example of column_spec, and wondering if this can be down with row_spec or similar that's more efficient than column_spec or cell_spec?

```<code>mtcars[1:8, 1:8] %>%
      arrange(wt) %>%
      kbl(booktabs = T, linesep = "") %>%
      kable_paper(full_width = F) %>%
      column_spec(6, color = "white", background = ifelse(mtcars[1:8,1:8]$drat > 3, "red", "green"))
</code>```

However, the conditional formatting I'm interested in is coloring, say Mazda RX4 row has any values >10 then red. This is just example data so context isn't relevant here. Thanks!

答:
We can use some dplyr operations before piping into Kable.

```<code>library(tidyverse)
library(knit)
library(kableExtra)

mtcars_kbl <- mtcars[1:8, 1:8]

mtcars_kbl$car = row.names(mtcars_kbl)
row.names(mtcars_kbl) <- NULL

mtcars_kbl %>% arrange(wt) %>%
  relocate(car) %>%
  mutate(
    across(1:8,
           ~ cell_spec(.x,
                       color = ifelse(car == "Mazda RX4" & .x > 10, "white", "black"),
                       background = ifelse(car == "Mazda RX4" & .x > 10, "red", "white")
                       )
           )
    ) %>%
  kable(booktabs = T, linesep = "", format = "html", escape = F) %>%
  kable_paper(full_width = F)
</code>```

Body:
I'm trying to color cells in each row based on a condition using kable. I saw a few examples of column_spec and cell_spec because it's still a bit manual since I'm interested in conditional coloring by row. Here's an example of column_spec, and wondering if this can be down with row_spec or similar that's more efficient than column_spec or cell_spec?

mtcars[1:8, 1:8] %>%
      arrange(wt) %>%
      kbl(booktabs = T, linesep = "") %>%
      kable_paper(full_width = F) %>%
      column_spec(6, color = "white", background = ifelse(mtcars[1:8,1:8]$drat > 3, "red", "green"))

However, the conditional formatting I'm interested in is coloring, say Mazda RX4 row has any values >10 then red. This is just example data so context isn't relevant here. Thanks!

Body:
We can use some dplyr operations before piping into Kable.

library(tidyverse)
library(knit)
library(kableExtra)

mtcars_kbl <- mtcars[1:8, 1:8]

mtcars_kbl$car = row.names(mtcars_kbl)
row.names(mtcars_kbl) <- NULL

mtcars_kbl %>% arrange(wt) %>%
  relocate(car) %>%
  mutate(
    across(1:8,
           ~ cell_spec(.x,
                       color = ifelse(car == "Mazda RX4" & .x > 10, "white", "black"),
                       background = ifelse(car == "Mazda RX4" & .x > 10, "red", "white")
                       )
           )
    ) %>%
  kable(booktabs = T, linesep = "", format = "html", escape = F) %>%
  kable_paper(full_width = F)


问:
iOS animating a view including subviews
I'm trying to make an animation for collapsing a view which includes some subviews.

```<code>[UIView beginAnimations:@"advancedAnimations" context:nil];
[UIView setAnimationDuration:3.0];

CGRect aFrame = aView.frame;
aView.size.height = 0;
aView.frame = aFrame;

[UIView commitAnimations];
</code>```

This animation is doing fine, but for the aView only. Subviews doesn't collapse as expected.
How do I make the subviews collapsing as well? Furthermore, is there a way to recalculate original size after collapsing?

THX

答:
The Swift syntax for setting autoresizingMask is slightly different than ObjC:

```<code>for subview in view.subviews {
    subview.autoresizingMask = [.flexibleWidth, .flexibleLeftMargin, .flexibleRightMargin]
}
</code>```

Title: iOS animating a view including subviews

Body:
I'm trying to make an animation for collapsing a view which includes some subviews.

[UIView beginAnimations:@"advancedAnimations" context:nil];
[UIView setAnimationDuration:3.0];

CGRect aFrame = aView.frame;
aView.size.height = 0;
aView.frame = aFrame;

[UIView commitAnimations];

This animation is doing fine, but for the aView only. Subviews doesn't collapse as expected.
How do I make the subviews collapsing as well? Furthermore, is there a way to recalculate original size after collapsing?

THX

Body:
The Swift syntax for setting autoresizingMask is slightly different than ObjC:

for subview in view.subviews {
    subview.autoresizingMask = [.flexibleWidth, .flexibleLeftMargin, .flexibleRightMargin]
}


问:
Testing private method using power mock which return list of Integers
I have a private method which take a list of integer value returns me a list of integer value. How can i use power mock to test it. I am new to powermock.Can i do the test with easy mock..? how..</p>

答:
From the documentation, in the section called "Common - Bypass encapsulation":

Use Whitebox.invokeMethod(..) to invoke a private method of an
  instance or class.

You can also find examples in the same section.


问:
How to export JavaFX Maven project?
I wrote modular JavaFx Maven project in Eclipse IDE.

Now I am trying to convert it to runnable jarfile, but receive the following error after clicking Next.

How can I fix this?

Details button provides the same text:

```<code>An error has occurred. See error log for more details.
Cannot invoke "org.eclipse.swt.widgets.Combo.getText()" because "this.fDestinationNamesCombo"
is null
</code>```

答: I had the same problem and noticed @jewelsea's suggestion in the comments regarding Maven and it led me to a solution in my case. I'm working with libgdx and used the libgdx Project Setup tool to create the project and then applied their suggestions for converting to the Lwjgl3 library.  Exporting the jar in Eclipse didn't work because I got the same fDestinationNamesCombo error.  Instead, I used this batch command (which the gdxlib setup tool put in the project directory) in a Windows command prompt: "gradlew desktop:dist".  This created a working jar in the desktop\build\libs directory.</p>

Title: How to export JavaFX Maven project?

Body:
I wrote modular JavaFx Maven project in Eclipse IDE.

Now I am trying to convert it to runnable jarfile, but receive the following error after clicking Next.

How can I fix this?

Details button provides the same text:

An error has occurred. See error log for more details.
Cannot invoke "org.eclipse.swt.widgets.Combo.getText()" because "this.fDestinationNamesCombo"
is null


问:
Android Emulator Homescreen Looks Cracked
I can't figure out why this keeps happening. Every emulator that I have created will at some point or another develop a weird glitch on the home screen that makes the device look as if the screen is cracked internally. This doesn't seem to change the way that my apps run or operate. However it is rather frustrating especially seeing as there seems to be no consistency as to when the screen will bug out. Also I can't for the life of me figure out what could possibly be causing the change to occur. Seems to happen at randomly sometimes it will be from the first launch of the emulator and other times I'll use the emulator for a few days and then it will just boot up with the same visual bug out of no where. Image of Cracked Screen Glitch

.

Below is the event log from the launch I used to take the screenshot.

4:36 PM Executing tasks: [:app:assembleDebug] in project D:\App_Dev\Calculator_Demo

4:36 PM Gradle build finished in 1 s 146 ms

4:36 PM App restart successful without requiring a re-install.

4:36 PM Launch succeeded

4:37 PM Adb connection Error:An existing connection was forcibly closed by the remote host

4:37 PM Unable to open connection to ADB server: java.io.IOException: Can't find adb server on port 5037, IPv4 attempt: Connection refused: connect, IPv6 attempt: Connection refused: connect

4:37 PM Cannot reach ADB server, attempting to reconnect.

4:37 PM Failed to start monitoring emulator-5554

4:37 PM * daemon not running; starting now at tcp:5037

4:37 PM * daemon started successfully

4:37 PM Failed to start monitoring emulator-5554

.

Below this is an event log from a  2nd launch after completely closing the emulator.

4:42 PM Executing tasks: [:app:assembleDebug] in project D:\App_Dev\Calculator_Demo

4:42 PM Gradle build finished in 709 ms

4:42 PM App restart successful without requiring a re-install.

4:42 PM Launch succeeded

4:42 PM Failed to start monitoring emulator-5554

答:
I ran into the same problem when I updated Android Studio

Here's how I solved it:

open adb.exe dir. like ..\Android\Sdk\platform-tools

delete all

open Android studio -> File | Settings | Appearance & Behavior | System Settings | Android SDK -> sdk tools -> Android SDK platform-tools

reInstall Android SDK platform-tools

I use this method to get ADB working again.


问:
How to write comments in Kibana console?
Can you provide me with a hint how to comment out lines in Kibana Dev Tools console? I am interested in comment syntax.</p>

答:
If you were to comment out a line or lines, you could add /* */, for example, /* "field": "statType.keyword" */

```<code>GET /exercise-index/_search
{
  "_source": {
    "includes": ["content"]
  },
  "query": {
    "exists": {"field": "inclination"}
  },
  "aggs": {
    "location": {
      "terms": {
        "field": "location"
        /* "size": 10 */
      }
    }
  }
}
</code>```

at the query above, we commented out a line in agg with /* */.

PS:

The syntax check will fail after you add /* */ on a line, but it does not affect the query.

After add /* */, you need to remove comma at the line before to meet the json syntax.

Body:
If you were to comment out a line or lines, you could add /* */, for example, /* "field": "statType.keyword" */

GET /exercise-index/_search
{
  "_source": {
    "includes": ["content"]
  },
  "query": {
    "exists": {"field": "inclination"}
  },
  "aggs": {
    "location": {
      "terms": {
        "field": "location"
        /* "size": 10 */
      }
    }
  }
}

at the query above, we commented out a line in agg with /* */.

PS:

The syntax check will fail after you add /* */ on a line, but it does not affect the query.

After add /* */, you need to remove comma at the line before to meet the json syntax.


问:
Script setValue based on the values of column based on value of other column matching reference
https://docs.google.com/spreadsheets/d/1g5mLRcwBb9rLaJ4qIUy1PLaBNNfuwvXwct1cBr2QVgk/edit#gid=1271563337

basicly im trying to figure out a script that would:

Find match in Relação!A:A to content of Config!B3

in my example ABEV3 it would be Relação!A3

that would find a correponding row 3

so the matching cel in Relação!L:L would be Relação!L3

update Relação!L3 with content of Config!D9

basic idea with part of code that i can do to try to ilustrate

```<code>function setSheetID()
{

  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const sheet_c = ss.getSheetByName('Config');

  var ticket = ss.getRange(3,2,1,1).getValues(); // Config!B3
  var sheetID = ss.getRange(9,4,1,1).getValues(); // Config!D9

  const sheet_r = ss.getSheetByName('Relação');

  var LR = sheet_r.getLastRow();
  var LC = sheet_r.getLastColumn();

  var row_to_match_with_ticket = sheet_r.getRange(1,1,LR,1).getValues(); // Relação!A:A

// that part i have no idea how to get range for target where ticket would match with row_to_match_with_ticket, so i will put the result as example

  for (var i = 0; i <= 1; i++) // i dont understand that, just setting exemple from posts ive seen
  {
    if (row_to_match_with_ticket[i] == ticket )
    {
      var target = sheet_r.getRange(3,12,1,1);  // Relação!L3 // im harcoding result, cos i dont fully understant what i wrote in the example

      sheet_r.getRange(target).setValues(sheetID);
    }
  }

};
</code>```

now i will try to ilustrate with a query: (im not in USA, so ; instead of ,)

to find my target:

query('Relação'!A:L; "SELECT L WHERE (A = '"&Config!B3&"') LIMIT 1";0)

update that cell

UPDATE WITH Config!D9 ( Relação!L:L WHERE Relação!A:A = Config!B3 )

in this case update Relação!L3 WITH VALUES OF Config!D9

searched and results where too complex to me understand and be able to try to adapt to my needs

thanks in advance

Edit: tried to simplify, to make it easier to understand as im terrible to explain aparently, but that script would run on multiple SS that i quite often replace as i improve it, so i need each sheet to update a main sheet

Edit 2: tried to provide a logical way to understant the inputs and outputs, its might be easier to see in the sheet i provided as its comented and colored, tried to describe the best possible way i could

Edit 3: added basic code to try to show what i want to do

答:
I believe your goal is as follows.

You want to retrieve the value of cell "B3" of "Config" sheet.

You want to search the retrieved value from the column "A" of "Relação" sheet.

When the value is found, you want to put the value of cell "D9" of "Config" sheet to the column "L" of the same row of the searched value.

In this case, how about the following sample script?

Sample script:

function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const [src, dst] = ["Config", "Relação"].map(s => ss.getSheetByName(s));
  const [b3, d9] = ["B3", "D9"].map(r => src.getRange(r).getValue());
  const search = dst.getRange("A2:A" + dst.getLastRow()).createTextFinder(b3).findNext();
  if (!search) return;
  search.offset(0, 11).setValue(d9);
}
```

In this answer, the value is searched using TextFinder.

Reference:

createTextFinder(findText)

Body:
https://docs.google.com/spreadsheets/d/1g5mLRcwBb9rLaJ4qIUy1PLaBNNfuwvXwct1cBr2QVgk/edit#gid=1271563337

basicly im trying to figure out a script that would:

Find match in Relação!A:A to content of Config!B3

in my example ABEV3 it would be Relação!A3

that would find a correponding row 3

so the matching cel in Relação!L:L would be Relação!L3

update Relação!L3 with content of Config!D9

basic idea with part of code that i can do to try to ilustrate

function setSheetID()
{

  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const sheet_c = ss.getSheetByName('Config');

  var ticket = ss.getRange(3,2,1,1).getValues(); // Config!B3
  var sheetID = ss.getRange(9,4,1,1).getValues(); // Config!D9

  const sheet_r = ss.getSheetByName('Relação');

  var LR = sheet_r.getLastRow();
  var LC = sheet_r.getLastColumn();

  var row_to_match_with_ticket = sheet_r.getRange(1,1,LR,1).getValues(); // Relação!A:A

// that part i have no idea how to get range for target where ticket would match with row_to_match_with_ticket, so i will put the result as example

  for (var i = 0; i <= 1; i++) // i dont understand that, just setting exemple from posts ive seen
  {
    if (row_to_match_with_ticket[i] == ticket )
    {
      var target = sheet_r.getRange(3,12,1,1);  // Relação!L3 // im harcoding result, cos i dont fully understant what i wrote in the example

      sheet_r.getRange(target).setValues(sheetID);
    }
  }

};

now i will try to ilustrate with a query: (im not in USA, so ; instead of ,)

to find my target:

query('Relação'!A:L; "SELECT L WHERE (A = '"&Config!B3&"') LIMIT 1";0)

update that cell

UPDATE WITH Config!D9 ( Relação!L:L WHERE Relação!A:A = Config!B3 )

in this case update Relação!L3 WITH VALUES OF Config!D9

searched and results where too complex to me understand and be able to try to adapt to my needs

thanks in advance

Edit: tried to simplify, to make it easier to understand as im terrible to explain aparently, but that script would run on multiple SS that i quite often replace as i improve it, so i need each sheet to update a main sheet

Edit 2: tried to provide a logical way to understant the inputs and outputs, its might be easier to see in the sheet i provided as its comented and colored, tried to describe the best possible way i could

Edit 3: added basic code to try to show what i want to do

Body:
I believe your goal is as follows.

You want to retrieve the value of cell "B3" of "Config" sheet.

You want to search the retrieved value from the column "A" of "Relação" sheet.

When the value is found, you want to put the value of cell "D9" of "Config" sheet to the column "L" of the same row of the searched value.

In this case, how about the following sample script?

Sample script:

function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const [src, dst] = ["Config", "Relação"].map(s => ss.getSheetByName(s));
  const [b3, d9] = ["B3", "D9"].map(r => src.getRange(r).getValue());
  const search = dst.getRange("A2:A" + dst.getLastRow()).createTextFinder(b3).findNext();
  if (!search) return;
  search.offset(0, 11).setValue(d9);
}

In this answer, the value is searched using TextFinder.

Reference:

createTextFinder(findText)


问:
UseEffect is not running cleanup on-dismount
I have a MessageInput component which triggers a socket connection to the backend when it mounts, and should disconnect from that socket manually on dismount. I am not sure what happened, but at some point yesterday useEffect simply stopped running cleanup.

When I close the app I see the accumulated disconnections all at once.

User disconnected...
User disconnected...
User disconnected...
```
<p>Is there something I am missing in useEffect?</p>
<p>Here is my code:</p>
<pre class="lang-js prettyprint-override"><code>useEffect(async () => {
    const accessToken = await SecureStore.getItemAsync("access-token");
    const socket = socketClient(`${process.env.REACT_APP_backend_url}/`, {
      auth: {
        authToken: accessToken,
      },
    });
    socket.emit("message", message);
    return () => socket.disconnect();
  }, []);
</code>```

答:
async functions return promises, so you're not actually returning a cleanup function. React ignores the promise that you return to it.

You'll need to do something like this:

```<code>useEffect(() => {
  let socket;
  (async () => {
    const accessToken = await SecureStore.getItemAsync("access-token");
    socket = socketClient(`${process.env.REACT_APP_backend_url}/`, {
      auth: {
        authToken: accessToken,
      },
    });
    socket.emit("message", message);
  })()

  return () => {
    if (socket) {
      socket.disconnect();
    }
  }
}, []);
</code>```

Body:
I have a MessageInput component which triggers a socket connection to the backend when it mounts, and should disconnect from that socket manually on dismount. I am not sure what happened, but at some point yesterday useEffect simply stopped running cleanup.

When I close the app I see the accumulated disconnections all at once.

User disconnected...
User disconnected...
User disconnected...

Is there something I am missing in useEffect?

Here is my code:

useEffect(async () => {
    const accessToken = await SecureStore.getItemAsync("access-token");
    const socket = socketClient(`${process.env.REACT_APP_backend_url}/`, {
      auth: {
        authToken: accessToken,
      },
    });
    socket.emit("message", message);
    return () => socket.disconnect();
  }, []);

Body:
async functions return promises, so you're not actually returning a cleanup function. React ignores the promise that you return to it.

You'll need to do something like this:

useEffect(() => {
  let socket;
  (async () => {
    const accessToken = await SecureStore.getItemAsync("access-token");
    socket = socketClient(`${process.env.REACT_APP_backend_url}/`, {
      auth: {
        authToken: accessToken,
      },
    });
    socket.emit("message", message);
  })()

  return () => {
    if (socket) {
      socket.disconnect();
    }
  }
}, []);


问:
I need something like "using Base::*;"
If my base class has a function func(int) and my derived class has a function func(double), the derived func(double) hides base::func(int).  I can use using to bring the base version into the derive's list of overloads:

```<code>struct base
{
   void func(int);
};

struct derived : base
{
   using base::func;
   void func(double);
}
</code>```

OK, great.  But what if I'm not sure whether base has a func() or not?  ie because I am doing template metaprogramming, I'm not actually sure what base is, but I want to bring its functions up to the same level - if they exist.  ie change the above example to:

```<code>struct base_with
{
   void func(int);
};
struct base_without
{
};

template <typename Base>
struct derived : Base
{
   using Base::func;  // if Base has a func(), I want to bring it in

   void func(double);
}

derived<base_with> testwith; // compiles
derived<base_without> testwithout;  // fails :-(
</code>```

I need using_if like boost::enable_if.  Doesn't seem possible...

Thanks in advance.

答:
Since you're willing to put using statements into your derived class, I assume you know beforehands which members you may be interested to bring in. You can do this using boost::enable_if:

```<code>struct base_with
{
    void func(int) { cout << "func(int)" << endl; }
};

struct base_without { };

// Custom traits, by default assume func() isn't present
template <class T> struct has_func : public boost::false_type { };

template<> struct has_func<base_with> : public boost::true_type { };

// Again, if nothing else is known, assume absence of func(int)
template <typename Base, class UseFunc = void> struct derived : Base
{
    derived() { cout << "ctor: derived without" << endl; }
    void func(double) { cout << "func(double)" << endl; }
};

// Derived with func(int)
template <typename Base> struct derived<Base, typename boost::enable_if< has_func<Base> >::type> : Base
{
    using Base::func;
    derived() { cout << "ctor: derived with" << endl; }
    void func(double) { cout << "func(double)" << endl; }
};
</code>```

Sorry for all the printing statements. Now if you try

```<code>derived<base_with> testwith;
derived<base_without> testwithout;

testwith.func(10);
testwith.func(10.5);
testwithout.func(10);
testwithout.func(10.5);
</code>```

you should see

ctor: derived with

  ctor: derived without

  func(int)

  func(double)

  func(double)

  func(double)

Obviously, this is going to get monstrous if you try to test for several features. If I was doing such mixin-style programming, I'd probably rather use functions with different names for different features so they wouldn't hide each other - then public inheritance would be all that is needed. Interesting question in any case.

Title: I need something like "using Base::*;"

Body:
If my base class has a function func(int) and my derived class has a function func(double), the derived func(double) hides base::func(int).  I can use using to bring the base version into the derive's list of overloads:

struct base
{
   void func(int);
};

struct derived : base
{
   using base::func;
   void func(double);
}

OK, great.  But what if I'm not sure whether base has a func() or not?  ie because I am doing template metaprogramming, I'm not actually sure what base is, but I want to bring its functions up to the same level - if they exist.  ie change the above example to:

struct base_with
{
   void func(int);
};
struct base_without
{
};

template <typename Base>
struct derived : Base
{
   using Base::func;  // if Base has a func(), I want to bring it in

   void func(double);
}

derived<base_with> testwith; // compiles
derived<base_without> testwithout;  // fails :-(

I need using_if like boost::enable_if.  Doesn't seem possible...

Thanks in advance.

Body:
Since you're willing to put using statements into your derived class, I assume you know beforehands which members you may be interested to bring in. You can do this using boost::enable_if:

struct base_with
{
    void func(int) { cout << "func(int)" << endl; }
};

struct base_without { };

// Custom traits, by default assume func() isn't present
template <class T> struct has_func : public boost::false_type { };

template<> struct has_func<base_with> : public boost::true_type { };

// Again, if nothing else is known, assume absence of func(int)
template <typename Base, class UseFunc = void> struct derived : Base
{
    derived() { cout << "ctor: derived without" << endl; }
    void func(double) { cout << "func(double)" << endl; }
};

// Derived with func(int)
template <typename Base> struct derived<Base, typename boost::enable_if< has_func<Base> >::type> : Base
{
    using Base::func;
    derived() { cout << "ctor: derived with" << endl; }
    void func(double) { cout << "func(double)" << endl; }
};

Sorry for all the printing statements. Now if you try

derived<base_with> testwith;
derived<base_without> testwithout;

testwith.func(10);
testwith.func(10.5);
testwithout.func(10);
testwithout.func(10.5);

you should see

ctor: derived with

  ctor: derived without

  func(int)

  func(double)

  func(double)

  func(double)

Obviously, this is going to get monstrous if you try to test for several features. If I was doing such mixin-style programming, I'd probably rather use functions with different names for different features so they wouldn't hide each other - then public inheritance would be all that is needed. Interesting question in any case.


问:
Adding date values to unbalanced panel data
I have a large unbalanced data set where I would like to add 12 additional months to each unique group of identifiers

Here is an example of data:

X
Y
Z
year_month

aaa
bbb
ccc
2008-09-01

aaa
bbb
ccc
2008-10-01

aaa
ddd
eee
2010-06-01

aaa
ddd
eee
2010-07-01

aaa
ddd
eee
2010-08-01

Here is what I would like the data set to look like:

X
Y
Z
year_month

aaa
bbb
ccc
2007-09-01

...
...
...
...

aaa
bbb
ccc
2008-08-01

aaa
bbb
ccc
2008-09-01

aaa
bbb
ccc
2008-10-01

aaa
ddd
eee
2009-06-01

...
...
...
...

aaa
ddd
eee
2010-05-01

aaa
ddd
eee
2010-06-01

aaa
ddd
eee
2010-07-01

aaa
ddd
eee
2010-08-01

I've tried isolating the earliest date for each unique identifier and then adding the date 12 months prior. I then use padr but the results end up adding every day. At least that is what I believe it is doing since this runs for hours.
Here is my code:

test <- date_filler %>%
  group_by(X, Y, Z) %>%
  do(pad(date_filler, interval = "month"))
```

Any help would be appreciated thank you!

答:
library(dplyr)
library(lubridate) # %m-%
dat %>%
  group_by(X, Y, Z) %>%
  summarize(
    year_month = seq(min(year_month) %m-% months(12), max(year_month), by = "month")
  ) %>%
  ungroup()
# # A tibble: 29 x 4
#    X     Y     Z     year_month
#    <chr> <chr> <chr> <date>
#  1 aaa   bbb   ccc   2007-09-01
#  2 aaa   bbb   ccc   2007-10-01
#  3 aaa   bbb   ccc   2007-11-01
#  4 aaa   bbb   ccc   2007-12-01
#  5 aaa   bbb   ccc   2008-01-01
#  6 aaa   bbb   ccc   2008-02-01
#  7 aaa   bbb   ccc   2008-03-01
#  8 aaa   bbb   ccc   2008-04-01
#  9 aaa   bbb   ccc   2008-05-01
# 10 aaa   bbb   ccc   2008-06-01
# # ... with 19 more rows
```
<hr />
<p>Data: I pre-converted <code>year_month</code> to <code>Date</code>-class.</p>
<pre class="lang-r prettyprint-override"><code>dat <- structure(list(X = c("aaa", "aaa", "aaa", "aaa", "aaa"), Y = c("bbb", "bbb", "ddd", "ddd", "ddd"), Z = c("ccc", "ccc", "eee", "eee", "eee"), year_month = structure(c(14123, 14153, 14761, 14791, 14822), class = "Date")), row.names = c(NA, -5L), class = "data.frame")
</code>```

Body:
I have a large unbalanced data set where I would like to add 12 additional months to each unique group of identifiers

Here is an example of data:

X
Y
Z
year_month

aaa
bbb
ccc
2008-09-01

aaa
bbb
ccc
2008-10-01

aaa
ddd
eee
2010-06-01

aaa
ddd
eee
2010-07-01

aaa
ddd
eee
2010-08-01

Here is what I would like the data set to look like:

X
Y
Z
year_month

aaa
bbb
ccc
2007-09-01

...
...
...
...

aaa
bbb
ccc
2008-08-01

aaa
bbb
ccc
2008-09-01

aaa
bbb
ccc
2008-10-01

aaa
ddd
eee
2009-06-01

...
...
...
...

aaa
ddd
eee
2010-05-01

aaa
ddd
eee
2010-06-01

aaa
ddd
eee
2010-07-01

aaa
ddd
eee
2010-08-01

I've tried isolating the earliest date for each unique identifier and then adding the date 12 months prior. I then use padr but the results end up adding every day. At least that is what I believe it is doing since this runs for hours.
Here is my code:

test <- date_filler %>%
  group_by(X, Y, Z) %>%
  do(pad(date_filler, interval = "month"))

Any help would be appreciated thank you!

Body:
library(dplyr)
library(lubridate) # %m-%
dat %>%
  group_by(X, Y, Z) %>%
  summarize(
    year_month = seq(min(year_month) %m-% months(12), max(year_month), by = "month")
  ) %>%
  ungroup()
# # A tibble: 29 x 4
#    X     Y     Z     year_month
#    <chr> <chr> <chr> <date>
#  1 aaa   bbb   ccc   2007-09-01
#  2 aaa   bbb   ccc   2007-10-01
#  3 aaa   bbb   ccc   2007-11-01
#  4 aaa   bbb   ccc   2007-12-01
#  5 aaa   bbb   ccc   2008-01-01
#  6 aaa   bbb   ccc   2008-02-01
#  7 aaa   bbb   ccc   2008-03-01
#  8 aaa   bbb   ccc   2008-04-01
#  9 aaa   bbb   ccc   2008-05-01
# 10 aaa   bbb   ccc   2008-06-01
# # ... with 19 more rows

Data: I pre-converted year_month to Date-class.

dat <- structure(list(X = c("aaa", "aaa", "aaa", "aaa", "aaa"), Y = c("bbb", "bbb", "ddd", "ddd", "ddd"), Z = c("ccc", "ccc", "eee", "eee", "eee"), year_month = structure(c(14123, 14153, 14761, 14791, 14822), class = "Date")), row.names = c(NA, -5L), class = "data.frame")


问:
Side Scrolling Pygame Problme
I was trying to make a side scroller game with pygame ( i am quite new to pygame ) and my game works quite fine but once it turns fast it just gets a weird kind of glitch for a few seconds and it happens occasionally i think its some kind of background error of size not being enough but my screen size is 800, 447 but the background png i use is 1920, 1080 ( the black screen is my background ) Here is my code

```<code>from pygame.locals import *
import os
import sys
import math

pygame.init()

W, H = 800, 447
win = pygame.display.set_mode((W,H))
pygame.display.set_caption('Side Scroller')
x = 200
y = 200
height = 30
width = 30

bg = pygame.image.load(os.path.join('im','bg.png')).convert()
bgX = 0
bgX2 = bg.get_width()

clock = pygame.time.Clock()

class player(object):
    run = [pygame.image.load(os.path.join('im', str(x) + '.png')) for x in range(8,16)]
    jump = [pygame.image.load(os.path.join('im', str(x) + '.png')) for x in range(1,8)]
    slide = [pygame.image.load(os.path.join('images', 'S1.png')),pygame.image.load(os.path.join('images', 'S2.png')),pygame.image.load(os.path.join('images', 'S2.png')),pygame.image.load(os.path.join('images', 'S2.png')), pygame.image.load(os.path.join('images', 'S2.png')),pygame.image.load(os.path.join('images', 'S2.png')), pygame.image.load(os.path.join('images', 'S2.png')), pygame.image.load(os.path.join('images', 'S2.png')), pygame.image.load(os.path.join('images', 'S3.png')), pygame.image.load(os.path.join('images', 'S4.png')), pygame.image.load(os.path.join('images', 'S5.png'))]
    jumpList = [![enter image description here][1]][1][1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,-1,-1,-1,-1,-1,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4]
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.jumping = False
        self.sliding = False
        self.slideCount = 0
        self.jumpCount = 0
        self.runCount = 0
        self.slideUp = False

    def draw(self, win):
        if self.jumping:
            self.y -= self.jumpList[self.jumpCount] * 1.2
            win.blit(self.jump[self.jumpCount//18], (self.x,self.y))
            self.jumpCount += 1
            if self.jumpCount > 108:
                self.jumpCount = 0
                self.jumping = False
                self.runCount = 0
        elif self.sliding or self.slideUp:
            if self.slideCount < 20:
                self.y += 1
            elif self.slideCount == 80:
                self.y -= 19
                self.sliding = False
                self.slideUp = True
            if self.slideCount >= 110:
                self.slideCount = 0
                self.slideUp = False
                self.runCount = 0
            win.blit(self.slide[self.slideCount//10], (self.x,self.y))
            self.slideCount += 1

        else:
            if self.runCount > 42:
                self.runCount = 0
            win.blit(self.run[self.runCount//6], (self.x,self.y))
            self.runCount += 1

def redrawwindow():
      win.blit(bg, (bgX, 0))
      win.blit(bg, (bgX2, 0))
      runner.draw(win)
      pygame.display.update()
run = True
speed = 30[![enter image description here][1]][1]
pygame.time.set_timer(USEREVENT+1, 500)
runner = player(200, 313, 80, 64)
while run:

    bgX -= 1.4
    bgX2 -= 1.4
    if bgX < bg.get_width() * -1:
            bgX = bg.get_width()
    if bgX2 < bg.get_width() * -1:
            bg2 = bg.get_width()
    for event in pygame.event.get():
            if event.type == pygame.QUIT:
                  run = False

            if event.type == USEREVENT+1:
                speed +=1

    keys = pygame.key.get_pressed()
    if keys[pygame.K_SPACE] or keys[pygame.K_UP]:
        if not (runner.jumping):
            runner.jumping = True

    if keys[pygame.K_DOWN]:
        if not (runner.sliding):
            runner.sliding = True

    redrawwindow()
    clock.tick(speed)
pygame.quit()
</code>```

答:
looks like you just need to update your screen so the pixels will update properly.
you can add

```<code>pygame.display.update()
</code>```

to the end of your game loop

if this still don't work then try using this command to fill in the background with just the color black just and clearing everything

```<code>win.fill((0, 0, 0))
</code>```

you should put it at the start of the game loop

Title: Side Scrolling Pygame Problme

Body:
I was trying to make a side scroller game with pygame ( i am quite new to pygame ) and my game works quite fine but once it turns fast it just gets a weird kind of glitch for a few seconds and it happens occasionally i think its some kind of background error of size not being enough but my screen size is 800, 447 but the background png i use is 1920, 1080 ( the black screen is my background ) Here is my code

from pygame.locals import *
import os
import sys
import math

pygame.init()

W, H = 800, 447
win = pygame.display.set_mode((W,H))
pygame.display.set_caption('Side Scroller')
x = 200
y = 200
height = 30
width = 30

bg = pygame.image.load(os.path.join('im','bg.png')).convert()
bgX = 0
bgX2 = bg.get_width()

clock = pygame.time.Clock()

class player(object):
    run = [pygame.image.load(os.path.join('im', str(x) + '.png')) for x in range(8,16)]
    jump = [pygame.image.load(os.path.join('im', str(x) + '.png')) for x in range(1,8)]
    slide = [pygame.image.load(os.path.join('images', 'S1.png')),pygame.image.load(os.path.join('images', 'S2.png')),pygame.image.load(os.path.join('images', 'S2.png')),pygame.image.load(os.path.join('images', 'S2.png')), pygame.image.load(os.path.join('images', 'S2.png')),pygame.image.load(os.path.join('images', 'S2.png')), pygame.image.load(os.path.join('images', 'S2.png')), pygame.image.load(os.path.join('images', 'S2.png')), pygame.image.load(os.path.join('images', 'S3.png')), pygame.image.load(os.path.join('images', 'S4.png')), pygame.image.load(os.path.join('images', 'S5.png'))]
    jumpList = [![enter image description here][1]][1][1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,-1,-1,-1,-1,-1,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4]
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.jumping = False
        self.sliding = False
        self.slideCount = 0
        self.jumpCount = 0
        self.runCount = 0
        self.slideUp = False

    def draw(self, win):
        if self.jumping:
            self.y -= self.jumpList[self.jumpCount] * 1.2
            win.blit(self.jump[self.jumpCount//18], (self.x,self.y))
            self.jumpCount += 1
            if self.jumpCount > 108:
                self.jumpCount = 0
                self.jumping = False
                self.runCount = 0
        elif self.sliding or self.slideUp:
            if self.slideCount < 20:
                self.y += 1
            elif self.slideCount == 80:
                self.y -= 19
                self.sliding = False
                self.slideUp = True
            if self.slideCount >= 110:
                self.slideCount = 0
                self.slideUp = False
                self.runCount = 0
            win.blit(self.slide[self.slideCount//10], (self.x,self.y))
            self.slideCount += 1

        else:
            if self.runCount > 42:
                self.runCount = 0
            win.blit(self.run[self.runCount//6], (self.x,self.y))
            self.runCount += 1

def redrawwindow():
      win.blit(bg, (bgX, 0))
      win.blit(bg, (bgX2, 0))
      runner.draw(win)
      pygame.display.update()
run = True
speed = 30[![enter image description here][1]][1]
pygame.time.set_timer(USEREVENT+1, 500)
runner = player(200, 313, 80, 64)
while run:

    bgX -= 1.4
    bgX2 -= 1.4
    if bgX < bg.get_width() * -1:
            bgX = bg.get_width()
    if bgX2 < bg.get_width() * -1:
            bg2 = bg.get_width()
    for event in pygame.event.get():
            if event.type == pygame.QUIT:
                  run = False

            if event.type == USEREVENT+1:
                speed +=1

    keys = pygame.key.get_pressed()
    if keys[pygame.K_SPACE] or keys[pygame.K_UP]:
        if not (runner.jumping):
            runner.jumping = True

    if keys[pygame.K_DOWN]:
        if not (runner.sliding):
            runner.sliding = True

    redrawwindow()
    clock.tick(speed)
pygame.quit()

Body:
looks like you just need to update your screen so the pixels will update properly.
you can add

pygame.display.update()

to the end of your game loop

if this still don't work then try using this command to fill in the background with just the color black just and clearing everything

win.fill((0, 0, 0))

you should put it at the start of the game loop


问:
Alternatives for wget giving 'ERROR 403: Forbidden'
I'm trying to get text from multiple Pubmed papers using wget, but seems NCBI website don't allow this. Any alternatives?</p>

```<code>Bernardos-MacBook-Pro:pangenome_papers_pubmed_result bernardo$ wget -i ./url.txt
--2016-05-04 10:49:34--  http://www.ncbi.nlm.nih.gov/pmc/articles/PMC4560400/
Resolving www.ncbi.nlm.nih.gov... 130.14.29.110, 2607:f220:41e:4290::110
Connecting to www.ncbi.nlm.nih.gov|130.14.29.110|:80... connected.
HTTP request sent, awaiting response... 403 Forbidden
2016-05-04 10:49:34 ERROR 403: Forbidden.

--2016-05-04 10:49:34--  http://www.ncbi.nlm.nih.gov/pmc/articles/PMC4547177/
Reusing existing connection to www.ncbi.nlm.nih.gov:80.
HTTP request sent, awaiting response... 403 Forbidden
2016-05-04 10:49:34 ERROR 403: Forbidden.
</code>```

答:
Maybe you should try enclosing the url link in double quotes, like</p>
```<code>wget "your_url"
</code>```

Body:
I'm trying to get text from multiple Pubmed papers using wget, but seems NCBI website don't allow this. Any alternatives?

Bernardos-MacBook-Pro:pangenome_papers_pubmed_result bernardo$ wget -i ./url.txt
--2016-05-04 10:49:34--  http://www.ncbi.nlm.nih.gov/pmc/articles/PMC4560400/
Resolving www.ncbi.nlm.nih.gov... 130.14.29.110, 2607:f220:41e:4290::110
Connecting to www.ncbi.nlm.nih.gov|130.14.29.110|:80... connected.
HTTP request sent, awaiting response... 403 Forbidden
2016-05-04 10:49:34 ERROR 403: Forbidden.

--2016-05-04 10:49:34--  http://www.ncbi.nlm.nih.gov/pmc/articles/PMC4547177/
Reusing existing connection to www.ncbi.nlm.nih.gov:80.
HTTP request sent, awaiting response... 403 Forbidden
2016-05-04 10:49:34 ERROR 403: Forbidden.

Body:
Maybe you should try enclosing the url link in double quotes, like

wget "your_url"


问:
How to construct a mesh from given edge points?
I have some points on the edge(left image), and I want to construct a mesh(right), Is there any good algorithm to achieve it? many thanks!

image can see here http://ww3.sinaimg.cn/large/6a2c8e2bjw1dk8jr3t7eaj.jpg

答: If the region is flat or quasi-flat look for Ear Clipping approach (http://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf). In the case of curved surface you need point inside the region and therefore you may need Constrained Delaunay Triangulation (otherwise some edges may not be included in the triangulation).</p>


问:
Downgrade Firebase 9.6 to 9.2.0
What commands must I follow on the command line to downgrade. I ran uninstall and reinstalled as well as nom i -S firebase@... but now when I reload the app it just crashes.</p>

答:
If you have to install an older version of a package, just specify it

```<code>npm install <package>@<version>
</code>```

For example: npm install firebase@9.2.0

You can also add the --save flag to that command to add it to your package.json dependencies, or --save --save-exact flags if you want that exact version specified in your package.json dependencies.

The install command is documented here: https://docs.npmjs.com/cli/install

If you're not sure what versions of a package are available, you can use:

npm view firebase versions

And npm view can be used for viewing other things about a package too.

https://docs.npmjs.com/cli/view

don't forget to remove .lock file first to rebuilt the depedency

can u give the error messege for us....

Title: Downgrade Firebase 9.6 to 9.2.0

Body:
If you have to install an older version of a package, just specify it

npm install <package>@<version>

For example: npm install firebase@9.2.0

You can also add the --save flag to that command to add it to your package.json dependencies, or --save --save-exact flags if you want that exact version specified in your package.json dependencies.

The install command is documented here: https://docs.npmjs.com/cli/install

If you're not sure what versions of a package are available, you can use:

npm view firebase versions

And npm view can be used for viewing other things about a package too.

https://docs.npmjs.com/cli/view

don't forget to remove .lock file first to rebuilt the depedency

can u give the error messege for us....


问:
"Stand in Line" exercise on Freecodecamp
I don't understand a part of a JavaScript exercise on FreeCodeCamp.

This is the subject:

In Computer Science a queue is an abstract Data Structure where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.

Write a function nextInLine which takes an array (arr) and a number (item) as arguments.

Add the number to the end of the array, then remove the first element of the array.

The nextInLine function should then return the element that was removed.

Here is the solution:

function nextInLine(arr, item) {
  arr.push(item);
  var removed = arr.shift();
  return removed;
}```

This is probably very basic but I don't understand the "is stored in removed" on 4th line of the following example run.

Example Run:

Test nextInLine([2,1]); runs.

The nextInLine function is called. arr becomes [2]. item becomes 1.

arr.push(item); Pushes 1 to [2]. So arr is now [2,1].

var removed = arr.shift(); removes the first element. So arr is now [1]. 2 has been removed and is stored in removed.

return removed; 2 is returned.

From my perspective, if 2 had been removed, what's left is 1 and 1 should be store in the variance because when we remove something we except and consider only the remainder which is 1.

However I clearly understand that the removed number is 2, so it feels like a step is missing or is wrong. Is my logic strange?

答:
function nextInLine(arr, item){
  // Only change code below this line
  arr.push(item);
  return arr.shift();

  // Only change code above this line
}

// Setup
const testArr = [1, 2, 3, 4, 5];

// Display code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6));
console.log("After: " + JSON.stringify(testArr));```

Body:
I don't understand a part of a JavaScript exercise on FreeCodeCamp.

This is the subject:

In Computer Science a queue is an abstract Data Structure where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.

Write a function nextInLine which takes an array (arr) and a number (item) as arguments.

Add the number to the end of the array, then remove the first element of the array.

The nextInLine function should then return the element that was removed.

Here is the solution:

function nextInLine(arr, item) {
  arr.push(item);
  var removed = arr.shift();
  return removed;
}

This is probably very basic but I don't understand the "is stored in removed" on 4th line of the following example run.

Example Run:

Test nextInLine([2,1]); runs.

The nextInLine function is called. arr becomes [2]. item becomes 1.

arr.push(item); Pushes 1 to [2]. So arr is now [2,1].

var removed = arr.shift(); removes the first element. So arr is now [1]. 2 has been removed and is stored in removed.

return removed; 2 is returned.

From my perspective, if 2 had been removed, what's left is 1 and 1 should be store in the variance because when we remove something we except and consider only the remainder which is 1.

However I clearly understand that the removed number is 2, so it feels like a step is missing or is wrong. Is my logic strange?


问:
Django Rest Framework: optimize nester serializers performance
I have problem with my endpoint performance which returns around 40 items and response takes around 17 seconds.

I have model:

```<code>class GameTask(models.Model):
    name= models.CharField()
    description = RichTextUploadingField()
    ...
</code>```

and another model like that:

```<code>class TaskLevel(models.Model):
    master_task = models.ForeignKey(GameTask, related_name="sub_levels", on_delete-models.CASCADE)
    sub_tasks = models.ManyToManyField(GameTask, related_name="master_levels")
    ...
</code>```

So basicly I can have "normal" tasks, but when I create TaskLevel object I can add master_task as a task which gonna fasten other tasks added to sub_tasks field.

My serializers look like:

```<code>class TaskBaseSerializer(serializers.ModelSerializer):
    fields created by serializers.SerializerMethodField()
    ...

class TaskLevelSerializer(serializers.ModelSerializer):
    sub_tasks = serializers.SerializerMethodField()

    class Meta:
        model = TaskLevel

    def get_sub_tasks(self, obj: TaskLevel):
        sub_tasks = get_sub_tasks(level=obj, user=self.context["request"].user) # method from other module
        return TaskBaseSerializer(sub_tasks, many=True, context=self.context).data

class TaskSerializer(TaskBaseSerializer):
    levels_config = serializers.SerializerMethodField()

    class Meta:
        model = GameTask

    def get_levels_config(self, obj: GameTask):
        if is_mastertask(obj):
            return dict(
                sub_levels=TaskLevelSerializer(
                    obj.sub_levels.all().order_by("number"), many=True, context=self.context
                ).data,
                progress=get_progress(
                    master_task=obj, user=self.context["request"].user
                ),
            )
        return None
</code>```

When I tried to measure time it turned out that get_levels_config method takes around 0.25 seconds for one multilevel-task (which contain 7 subtasks). Is there any way to improve this performance? If any more detailed methods are needed I will add them

答:
Your code might be suffering from N+1 problem. TaskSerializer.get_levels_config() performs database queries from obj.sub_levels.all().order_by("number").

What happens when serializing multiple instances like:

```<code>TaskSerializer(tasks, many=True)
</code>```

each instance calls .get_levels_config()

You can use prefetch_related & selected_related(more explanation here).

You will have to manually check for prefetched objects since you are using SerializerMethodField. There's also the functions get_progress & get_sub_tasks which I assume does another query.

Here are some examples that can be used around your code:

Prefetching:

```<code>GameTask.objects.prefetch_related("sub_levels", "master_levels")

# Accessing deeper level
GameTask.objects.prefetch_related(
    "sub_levels",
    "master_levels",
    "sub_levels__sub_tasks",
).select_related(
    "master_levels__master_task",
)
</code>```

Checking prefetch:

```<code>def get_sub_tasks(self, obj: TaskLevel):
    if hasattr(obj, "_prefetched_objects_cache") and obj._prefetched_objects_cache.get("sub_tasks", None):
        return obj._prefetched_objects_cache
    return obj.sub_tasks.all()
</code>```

Body:
I have problem with my endpoint performance which returns around 40 items and response takes around 17 seconds.

I have model:

class GameTask(models.Model):
    name= models.CharField()
    description = RichTextUploadingField()
    ...

and another model like that:

class TaskLevel(models.Model):
    master_task = models.ForeignKey(GameTask, related_name="sub_levels", on_delete-models.CASCADE)
    sub_tasks = models.ManyToManyField(GameTask, related_name="master_levels")
    ...

So basicly I can have "normal" tasks, but when I create TaskLevel object I can add master_task as a task which gonna fasten other tasks added to sub_tasks field.

My serializers look like:

class TaskBaseSerializer(serializers.ModelSerializer):
    fields created by serializers.SerializerMethodField()
    ...

class TaskLevelSerializer(serializers.ModelSerializer):
    sub_tasks = serializers.SerializerMethodField()

    class Meta:
        model = TaskLevel

    def get_sub_tasks(self, obj: TaskLevel):
        sub_tasks = get_sub_tasks(level=obj, user=self.context["request"].user) # method from other module
        return TaskBaseSerializer(sub_tasks, many=True, context=self.context).data

class TaskSerializer(TaskBaseSerializer):
    levels_config = serializers.SerializerMethodField()

    class Meta:
        model = GameTask

    def get_levels_config(self, obj: GameTask):
        if is_mastertask(obj):
            return dict(
                sub_levels=TaskLevelSerializer(
                    obj.sub_levels.all().order_by("number"), many=True, context=self.context
                ).data,
                progress=get_progress(
                    master_task=obj, user=self.context["request"].user
                ),
            )
        return None

When I tried to measure time it turned out that get_levels_config method takes around 0.25 seconds for one multilevel-task (which contain 7 subtasks). Is there any way to improve this performance? If any more detailed methods are needed I will add them

Body:
Your code might be suffering from N+1 problem. TaskSerializer.get_levels_config() performs database queries from obj.sub_levels.all().order_by("number").

What happens when serializing multiple instances like:

TaskSerializer(tasks, many=True)

each instance calls .get_levels_config()

You can use prefetch_related & selected_related(more explanation here).

You will have to manually check for prefetched objects since you are using SerializerMethodField. There's also the functions get_progress & get_sub_tasks which I assume does another query.

Here are some examples that can be used around your code:

Prefetching:

GameTask.objects.prefetch_related("sub_levels", "master_levels")

# Accessing deeper level
GameTask.objects.prefetch_related(
    "sub_levels",
    "master_levels",
    "sub_levels__sub_tasks",
).select_related(
    "master_levels__master_task",
)

Checking prefetch:

def get_sub_tasks(self, obj: TaskLevel):
    if hasattr(obj, "_prefetched_objects_cache") and obj._prefetched_objects_cache.get("sub_tasks", None):
        return obj._prefetched_objects_cache
    return obj.sub_tasks.all()


问:
How can I set initial position for slidable_button
I'd like to use slidable_button found here to set a bar happy hour on or off in my app. It doesn't have an initial position so I need to use two buttons, one to set happy hour on and another to turn it off. Ideally I'd like to have it initialize in either the left position or the right position depending on the current state. Unfortunately the package is very new and the author is not contactable.

Is there a way I could modify this code to set an initial button position left or right?

Here is the code I have so far. I have two buttons in separate rows in a column but have only shown the code for one as they are similar.

```<code>           Center(

             child: SlidableButton(
                      width: MediaQuery.of(context).size.width / 3,
                      buttonWidth: 60.0,
                      color: Colors.green,
                      buttonColor: Colors.blue,
                      dismissible: true,
                      label: Center(child: Text(_user.turnOnString!)),
                      child: Padding(
                      padding: const EdgeInsets.all(8.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(''),
                            Text('Start'),
                          ],
                        ),
                      ),
                      onChanged: (position) {
                        if (position == SlidableButtonPosition.right) {_startHappyHour(context, _user);}
                      },
                    ),

           ),
</code>```

答:
switch button would be more suitable for your situation, like lite_rolling_switch, you can set initial value(on/off):</p>
```<code>LiteRollingSwitch(
    //initial value
    value: true,
    textOn: 'disponible',
    textOff: 'ocupado',
    colorOn: Colors.greenAccent[700],
    colorOff: Colors.redAccent[700],
    iconOn: Icons.done,
    iconOff: Icons.remove_circle_outline,
    textSize: 16.0,
    onChanged: (bool state) {
      //Use it to manage the different states
      print('Current State of SWITCH IS: $state');
    },
),
</code>```

Body:
I'd like to use slidable_button found here to set a bar happy hour on or off in my app. It doesn't have an initial position so I need to use two buttons, one to set happy hour on and another to turn it off. Ideally I'd like to have it initialize in either the left position or the right position depending on the current state. Unfortunately the package is very new and the author is not contactable.

Is there a way I could modify this code to set an initial button position left or right?

Here is the code I have so far. I have two buttons in separate rows in a column but have only shown the code for one as they are similar.

           Center(

             child: SlidableButton(
                      width: MediaQuery.of(context).size.width / 3,
                      buttonWidth: 60.0,
                      color: Colors.green,
                      buttonColor: Colors.blue,
                      dismissible: true,
                      label: Center(child: Text(_user.turnOnString!)),
                      child: Padding(
                      padding: const EdgeInsets.all(8.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(''),
                            Text('Start'),
                          ],
                        ),
                      ),
                      onChanged: (position) {
                        if (position == SlidableButtonPosition.right) {_startHappyHour(context, _user);}
                      },
                    ),

           ),

Body:
switch button would be more suitable for your situation, like lite_rolling_switch, you can set initial value(on/off):

LiteRollingSwitch(
    //initial value
    value: true,
    textOn: 'disponible',
    textOff: 'ocupado',
    colorOn: Colors.greenAccent[700],
    colorOff: Colors.redAccent[700],
    iconOn: Icons.done,
    iconOff: Icons.remove_circle_outline,
    textSize: 16.0,
    onChanged: (bool state) {
      //Use it to manage the different states
      print('Current State of SWITCH IS: $state');
    },
),


问:
ValueError: unichr() arg not in range(0x10000) (narrow Python build)
I am trying to convert the html entity to unichar, the html entity is 󮠖
when i try to do the following:

```<code>unichr(int(976918))
</code>```

I got error that:

```<code>ValueError: unichr() arg not in range(0x10000) (narrow Python build)
</code>```

seems like it is out of range conversion for unichar.

答:
In order for this to work, you either need to build Python yourself, specifying

```<code>./configure --enable-unicode=ucs4
</code>```

before compiling, or else you need to move to Python 3.

Even if you do this, there are apparently problems on Windows, which will be fixed in the next version of Python (3.3).

Body:
I am trying to convert the html entity to unichar, the html entity is 󮠖
when i try to do the following:

unichr(int(976918))

I got error that:

ValueError: unichr() arg not in range(0x10000) (narrow Python build)

seems like it is out of range conversion for unichar.

Body:
In order for this to work, you either need to build Python yourself, specifying

./configure --enable-unicode=ucs4

before compiling, or else you need to move to Python 3.

Even if you do this, there are apparently problems on Windows, which will be fixed in the next version of Python (3.3).


问:
fetch() URL data with Javascript React and display as string
I have an api that is called like this :

```<code>http://localhost:5000/record/gopa
</code>```

and it returns the data in this JSON format

```<code>{"pid":{
  "ck":"F1965121910:265.522.5788.37",
  "name":"gopa",
  "cID":"MVOE9BW5ZZOC"}
}
</code>```

I want to call this from a React function Details2() that is called from a router like this:

```<code>import Details2 from "./components/Details2";
const App = () => {
 return (
   <div>
     <Navbar />
     <Routes>
       <Route exact path="/" element={<RecordList />} />
       <Route path="/singlerecord/:id" element={<RecordList1 />} />
       <Route path="/details2/:id" element={<Details2 />} />
     </Routes>
   </div>
 );
};
</code>```

the parameter :id needs to be passed to the function Details2()

This function is located in file /components/Details2.js and is being called correctly.

I have stripped down the Details2.js file to the bare essentials and it contains

```<code>import React from "react";
import { useParams, useNavigate } from "react-router";

export default function Details2() {
 const params = useParams();

 let z = fetch(`http://localhost:5000/record/${params.id.toString()}`).then((response) => {
      return response.json();
    })
 let cname = z.pid.name
 return (
   <div>
     <h3>Details2</h3>
     {params.id.toString()}

   </div>
 );
}
</code>```

I am trying to access the contents of the data that has been returned by the call for onward processing but I am unable to access it in any variable,like cname, that is shown here. No output is available, not even the header.

If I remove the assignment, the program works correctly, displays the HTML that is being returned including the value of params.id.toString() that is being correctly passed from the router.

My simple ask is to be able to access the individual values of the various keys that are being returned from the API. Please help me with the code that is required.

I have seen this article where they do something similar. However in this case they are using a class but I could not find a way to pass parameters into a class, as I am doing in the case of the function Details2().

答:
Here is what finally worked well :-)</p>
```<code>import React, { useEffect, useState } from "react";
import { useParams } from "react-router";

export default function Detail52() {
 const params = useParams();
 const [dbdata, setData] = useState('empty52');

 useEffect(() => {
   async function getData() {
   const response = await fetch(`http://localhost:5000/record/${params.id.toString()}`);
   //const response = await fetch(`http://localhost:5000/record/gopa`);

     if (!response.ok) {
       const message = `An error occurred: ${response.statusText}`;
       window.alert(message);
       return;
     }

     const dbdata = await response.json();
     //dbdata = response.json();
     //window.alert(JSON.stringify(dbdata));
     setData(dbdata);
     //setData('fake data')
   }
   getData();
   return;
 },[dbdata]);

 return (
   <div>
     <h3>Detail Information</h3>

       <p>{JSON.stringify(dbdata)}</p>
   </div>
 );

}
</code>```

Body:
I have an api that is called like this :

http://localhost:5000/record/gopa

and it returns the data in this JSON format

{"pid":{
  "ck":"F1965121910:265.522.5788.37",
  "name":"gopa",
  "cID":"MVOE9BW5ZZOC"}
}

I want to call this from a React function Details2() that is called from a router like this:

import Details2 from "./components/Details2";
const App = () => {
 return (

     <Navbar />
     <Routes>
       <Route exact path="/" element={<RecordList />} />
       <Route path="/singlerecord/:id" element={<RecordList1 />} />
       <Route path="/details2/:id" element={<Details2 />} />
     </Routes>

 );
};

the parameter :id needs to be passed to the function Details2()

This function is located in file /components/Details2.js and is being called correctly.

I have stripped down the Details2.js file to the bare essentials and it contains

import React from "react";
import { useParams, useNavigate } from "react-router";

export default function Details2() {
 const params = useParams();

 let z = fetch(`http://localhost:5000/record/${params.id.toString()}`).then((response) => {
      return response.json();
    })
 let cname = z.pid.name
 return (

Details2

     {params.id.toString()}

 );
}

I am trying to access the contents of the data that has been returned by the call for onward processing but I am unable to access it in any variable,like cname, that is shown here. No output is available, not even the header.

If I remove the assignment, the program works correctly, displays the HTML that is being returned including the value of params.id.toString() that is being correctly passed from the router.

My simple ask is to be able to access the individual values of the various keys that are being returned from the API. Please help me with the code that is required.

I have seen this article where they do something similar. However in this case they are using a class but I could not find a way to pass parameters into a class, as I am doing in the case of the function Details2().

Body:
Here is what finally worked well :-)

import React, { useEffect, useState } from "react";
import { useParams } from "react-router";

export default function Detail52() {
 const params = useParams();
 const [dbdata, setData] = useState('empty52');

 useEffect(() => {
   async function getData() {
   const response = await fetch(`http://localhost:5000/record/${params.id.toString()}`);
   //const response = await fetch(`http://localhost:5000/record/gopa`);

     if (!response.ok) {
       const message = `An error occurred: ${response.statusText}`;
       window.alert(message);
       return;
     }

     const dbdata = await response.json();
     //dbdata = response.json();
     //window.alert(JSON.stringify(dbdata));
     setData(dbdata);
     //setData('fake data')
   }
   getData();
   return;
 },[dbdata]);

 return (
   <div>
     <h3>Detail Information</h3>

       <p>{JSON.stringify(dbdata)}</p>
   </div>
 );

}


问:
Tilt image with UIKit
I want to one board for dama game.. can we tilt the whole board and also show the checkers big to near and small to far.. Like see in attached image..

How to make like that .?

please help me..

答: You want to do a perspective transform on the image or view. Here's a SO answer that might help you get started: How do I apply a perspective transform to a UIView?</p>

Title: Tilt image with UIKit


问:
Returning index of an Array when it stops increasing and begins decreasing
having a problem when running two tests using this code, test 1 returns the whole array, test2 returns the appropriate index. (the point in the array in which it stops decreasing or increasing and starts the reverse) if there is only one sequence it should return -1

the test cases are
Input: [-4, -2, 9, 10]
Output: -1
Input: [5, 4, 3, 2, 10, 11]
Output: 3

```<code>for (i = 0; i < arr.length; i++) {
    while (arr[i] < arr[i + 1]) {
      i++;
      if (arr[i] < arr[i - 1]) {
        return -1
      }
      else if (arr[i] > arr[i + 1]) {
        return i
      }
    } while (arr[i] > arr[i + 1]) {
      i++;
      if (arr[i] > arr[i - 1]) {
        return -1
      } else if (arr[i] < arr[i + 1]) {
        return i
      }
    }
  }
  return arr;

}
</code>```

答:
In the solution below, the isHomogeneous() method returns true if the content of the array is ever-increasing or ever-decreasing. The isIncreasing() method returns true if the array content is constantly decreasing. The isDecreasing() method returns true if the array content is ever-increasing. The getAscendingIndex() method returns the index at which the contents of the array begin to decrease. The getDescendingIndex() method returns the index at which the contents of the array begin to decrease. The application() method contains application code that executes other methods. If the content of the array is not homogeneous (continuously increasing or decreasing), the first index value at which the values start to increase in an array that starts with decreasing values is obtained using the getDescendingIndex() method.

/* Returns true if the array is descending to the elements (homogeneous). */
function isIncreasing(array) {
  for(let i = 0 ; i < array.length ; ++i)
    if(array[i] < array[i + 1])
      return false;
  return true;
}

/* Returns true if the array is incremental (homogeneous) to the elements. */
function isDecreasing(array) {
  for(let i = 0 ; i < array.length ; ++i)
    if(array[i] > array[i + 1])
      return false;
  return true;
}

/* Returns true if the array content is ever-increasing or ever-decreasing. */
function isHomogeneous(array) {
  return isIncreasing(array) || isDecreasing(array);
}

/* return the descending index in the array starting with increasing. */
function getAscendingIndex(array) {
  for(let i = 0 ; i < array.length ; ++i)
    if(array[i] > array[i + 1])
      return i;
  return -1;
}

/* return increasing index in array starting with decreasing. */
function getDescendingIndex(array) {
  for(let i = 0 ; i < array.length ; ++i)
    if(array[i] < array[i + 1])
      return i;
  return -1;
}

/* demo */
function application() {
  let firstArray = [-4, -2, 9, 10];
  let secondArray = [5, 4, 3, 2, 10, 11];

  console.log(`Increasing: ${(isIncreasing(firstArray) == true) ? "true" : "false"}`);
  console.log(`Decreasing: ${(isDecreasing(firstArray) == true) ? "true" : "false"}`);
  console.log(`First Array Index: ${getAscendingIndex(firstArray)}`);

 if(!isHomogeneous(secondArray) && getAscendingIndex(secondArray) != -1) {
    console.log(`Second Array Index: ${getDescendingIndex(secondArray)}`);
  }
}

application();```

Body:
having a problem when running two tests using this code, test 1 returns the whole array, test2 returns the appropriate index. (the point in the array in which it stops decreasing or increasing and starts the reverse) if there is only one sequence it should return -1

the test cases are
Input: [-4, -2, 9, 10]
Output: -1
Input: [5, 4, 3, 2, 10, 11]
Output: 3

for (i = 0; i < arr.length; i++) {
    while (arr[i] < arr[i + 1]) {
      i++;
      if (arr[i] < arr[i - 1]) {
        return -1
      }
      else if (arr[i] > arr[i + 1]) {
        return i
      }
    } while (arr[i] > arr[i + 1]) {
      i++;
      if (arr[i] > arr[i - 1]) {
        return -1
      } else if (arr[i] < arr[i + 1]) {
        return i
      }
    }
  }
  return arr;

}


问:
Project/Task management software? (hosted on-site, with localized russian interface)
I am currently researching what project/task management software is available on the market.
My requirements are:

solution needs to be hosted on my server, located on-site;

it should be possible to switch interface language to russian (since all of employers are russians);

it should not be software oriented (in terms of bugs, features, improvements).

If you know anything that can help me, please leave a comment or an answer!
Thanks in advance!

答: I would recommend Project Management Standard software by Microsoft Project 2010. This software gives managers an easy way to handle projects. They've made a lot of changes to their visuals and I've noticed that this project manager software has given much higher productivity rates.</p>


问:
How to read a file with uneven spaces as delimiter
I have the following string (actually it's from a file):

```<code>cfile <- "  ILE   800   A   MET     1   B\n  ASP   797   A   PHE    38   B\n  GLY   156   A   ASP     5   B\n"
</code>```

How can I read that string into a tibble or data frame, resulting in this (by hand):

```<code>X1.   X2    X3  X4.     X5. X6
<chr>  <dbl> ......         <chr>
ILE   800   A   MET     1   B
ASP   797   A   PHE    38   B
GLY   156   A   ASP     5   B
</code>```

With this:

```<code>readr::read_delim(cfile, col_names = FALSE)
</code>```

I get this which is not what I want:

```<code># A tibble: 3 × 20
  X1    X2    X3    X4    X5       X6 X7    X8    X9    X10   X11   X12   X13   X14   X15     X16   X17
  <lgl> <lgl> <chr> <lgl> <lgl> <dbl> <lgl> <lgl> <chr> <lgl> <lgl> <chr> <lgl> <lgl> <lgl> <dbl> <dbl>
1 NA    NA    ILE   NA    NA      800 NA    NA    A     NA    NA    MET   NA    NA    NA       NA     1
2 NA    NA    ASP   NA    NA      797 NA    NA    A     NA    NA    PHE   NA    NA    NA       38    NA
3 NA    NA    GLY   NA    NA      156 NA    NA    A     NA    NA    ASP   NA    NA    NA       NA     5
</code>```

Not that there's uneven space delimiter, in the input file.

How can I do it properly?

答:
```<code>read.table(text = cfile)
   V1  V2 V3  V4 V5 V6
1 ILE 800  A MET  1  B
2 ASP 797  A PHE 38  B
3 GLY 156  A ASP  5  B
</code>```

Other ways:

```<code>data.table::fread(cfile)
    V1  V2 V3  V4 V5 V6
1: ILE 800  A MET  1  B
2: ASP 797  A PHE 38  B
3: GLY 156  A ASP  5  B

readr::read_table(cfile, col_names = FALSE)
# A tibble: 3 x 6
  X1       X2 X3    X4       X5 X6
  <chr> <dbl> <chr> <chr> <dbl> <chr>
1 ILE     800 A     MET       1 B
2 ASP     797 A     PHE      38 B
3 GLY     156 A     ASP       5 B

readr::read_delim(cfile, delim = ' ', col_names = FALSE,trim_ws = TRUE)
# A tibble: 3 x 6
  X1       X2 X3    X4       X5 X6
  <chr> <dbl> <chr> <chr> <dbl> <chr>
1 ILE     800 A     MET       1 B
2 ASP     797 A     PHE      38 B
3 GLY     156 A     ASP       5 B

read.table(textConnection(cfile))
   V1  V2 V3  V4 V5 V6
1 ILE 800  A MET  1  B
2 ASP 797  A PHE 38  B
3 GLY 156  A ASP  5  B
</code>```

Body:
I have the following string (actually it's from a file):

cfile <- "  ILE   800   A   MET     1   B\n  ASP   797   A   PHE    38   B\n  GLY   156   A   ASP     5   B\n"

How can I read that string into a tibble or data frame, resulting in this (by hand):

X1.   X2    X3  X4.     X5. X6
<chr>  <dbl> ......         <chr>
ILE   800   A   MET     1   B
ASP   797   A   PHE    38   B
GLY   156   A   ASP     5   B

With this:

readr::read_delim(cfile, col_names = FALSE)

I get this which is not what I want:

# A tibble: 3 × 20
  X1    X2    X3    X4    X5       X6 X7    X8    X9    X10   X11   X12   X13   X14   X15     X16   X17
  <lgl> <lgl> <chr> <lgl> <lgl> <dbl> <lgl> <lgl> <chr> <lgl> <lgl> <chr> <lgl> <lgl> <lgl> <dbl> <dbl>
1 NA    NA    ILE   NA    NA      800 NA    NA    A     NA    NA    MET   NA    NA    NA       NA     1
2 NA    NA    ASP   NA    NA      797 NA    NA    A     NA    NA    PHE   NA    NA    NA       38    NA
3 NA    NA    GLY   NA    NA      156 NA    NA    A     NA    NA    ASP   NA    NA    NA       NA     5

Not that there's uneven space delimiter, in the input file.

How can I do it properly?

Body:
read.table(text = cfile)
   V1  V2 V3  V4 V5 V6
1 ILE 800  A MET  1  B
2 ASP 797  A PHE 38  B
3 GLY 156  A ASP  5  B

Other ways:

data.table::fread(cfile)
    V1  V2 V3  V4 V5 V6
1: ILE 800  A MET  1  B
2: ASP 797  A PHE 38  B
3: GLY 156  A ASP  5  B

readr::read_table(cfile, col_names = FALSE)
# A tibble: 3 x 6
  X1       X2 X3    X4       X5 X6
  <chr> <dbl> <chr> <chr> <dbl> <chr>
1 ILE     800 A     MET       1 B
2 ASP     797 A     PHE      38 B
3 GLY     156 A     ASP       5 B

readr::read_delim(cfile, delim = ' ', col_names = FALSE,trim_ws = TRUE)
# A tibble: 3 x 6
  X1       X2 X3    X4       X5 X6
  <chr> <dbl> <chr> <chr> <dbl> <chr>
1 ILE     800 A     MET       1 B
2 ASP     797 A     PHE      38 B
3 GLY     156 A     ASP       5 B

read.table(textConnection(cfile))
   V1  V2 V3  V4 V5 V6
1 ILE 800  A MET  1  B
2 ASP 797  A PHE 38  B
3 GLY 156  A ASP  5  B


问:
Firebase Auth Web: Logout with page reload
I use Firebase with VueJS. Sign-up, sign-in works fine so far but as soon as I reload the page with F5 or load a page with writing to the browsers address bar directly then the auth session is killed, the user isn't signed-in anymore. It works fine as long as I don't reload the page, even if I click route links or get redirected to other pages, the user session keeps alive. It doesn't matter where I reload the page btw.

My login method:

```<code>firebase.auth().signInWithEmailAndPassword(this.username, this.password).then(
                    (user) => {
                        if (user.emailVerified === false) {
                            firebase.auth().signOut()
                        } else {
                            // redirect to lobby page if user is verified and signed in
                            this.$router.push('/lobby')
                        }
                    },
                    function(err) {
                        console.log(err.message)
                    }
                )
</code>```

答:
Use this in your main.js file:

```<code>firebase.auth().onAuthStateChanged(() => {
if (!app) {
    app = createApp(App).use(store).use(router).mount('#app')
}})
</code>```

Firebase will run before Vue app is created.

Body:
I use Firebase with VueJS. Sign-up, sign-in works fine so far but as soon as I reload the page with F5 or load a page with writing to the browsers address bar directly then the auth session is killed, the user isn't signed-in anymore. It works fine as long as I don't reload the page, even if I click route links or get redirected to other pages, the user session keeps alive. It doesn't matter where I reload the page btw.

My login method:

firebase.auth().signInWithEmailAndPassword(this.username, this.password).then(
                    (user) => {
                        if (user.emailVerified === false) {
                            firebase.auth().signOut()
                        } else {
                            // redirect to lobby page if user is verified and signed in
                            this.$router.push('/lobby')
                        }
                    },
                    function(err) {
                        console.log(err.message)
                    }
                )

Body:
Use this in your main.js file:

firebase.auth().onAuthStateChanged(() => {
if (!app) {
    app = createApp(App).use(store).use(router).mount('#app')
}})

Firebase will run before Vue app is created.