问:
react native edit file after build
Is there any way to edit a json file after the app was build? I heard that an apk file can be unzipped, but how about IOS? My goal is to make an app that can be changed by a non-programmer, after it was finished. Adding assets would be also good, but I don't think I would be possible.</p>

答:
This is possible to achieve. There are some services around that provide something calles "on the air updates", like Microsoft Code Push. This kind of services basically changes the js bundle after the app is installed, in a way that you don't have to reinstall the apk from the store to get a new update. If you implement something similar, you can achieve that. All you have to do is edit the js bundle at runtime. I don't know exactly how to achieve that, but it is possible.
It is important to note that this updates are not applicable to the native code (Java/kotlin files on android or Objective-C/Swift files on iOS)

You can check how microsoft implemented it here:
https://github.com/Microsoft/react-native-code-push

Title: react native edit file after build


来源: stackexchange

问:
How to run code and get required output on site "observablehq"
I am new d3.js .I am trying to run code at this link(observablehq).For running this code, I placed that code in index.js file.

```<code>d3 = require("d3@5")
height = 500
margin = ({top: 10, right: 10, bottom: 20, left: 40})
data = Object.assign(d3.csvParse(await FileAttachment("data.csv").text(), d3.autoType), {y: "Population"})
groupKey = data.columns[0]
keys = data.columns.slice(1)
x0 = d3.scaleBand()
    .domain(data.map(d => d[groupKey]))
    .rangeRound([margin.left, width - margin.right])
    .paddingInner(0.1)
x1 = d3.scaleBand()
    .domain(keys)
    .rangeRound([0, x0.bandwidth()])
    .padding(0.05)
y = d3.scaleLinear()
    .domain([0, d3.max(data, d => d3.max(keys, key => d[key]))]).nice()
    .rangeRound([height - margin.bottom, margin.top])
color = d3.scaleOrdinal()
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"])
xAxis = g => g
    .attr("transform", `translate(0,${height - margin.bottom})`)
    .call(d3.axisBottom(x0).tickSizeOuter(0))
    .call(g => g.select(".domain").remove())
yAxis = g => g
    .attr("transform", `translate(${margin.left},0)`)
    .call(d3.axisLeft(y).ticks(null, "s"))
    .call(g => g.select(".domain").remove())
    .call(g => g.select(".tick:last-of-type text").clone()
        .attr("x", 3)
        .attr("text-anchor", "start")
        .attr("font-weight", "bold")
        .text(data.y))
legend = svg => {
  const g = svg
      .attr("transform", `translate(${width},0)`)
      .attr("text-anchor", "end")
      .attr("font-family", "sans-serif")
      .attr("font-size", 10)
    .selectAll("g")
    .data(color.domain().slice().reverse())
    .join("g")
      .attr("transform", (d, i) => `translate(0,${i * 20})`);

  g.append("rect")
      .attr("x", -19)
      .attr("width", 19)
      .attr("height", 19)
      .attr("fill", color);

  g.append("text")
      .attr("x", -24)
      .attr("y", 9.5)
      .attr("dy", "0.35em")
      .text(d => d);
}
chart = {
    const svg = d3.select(DOM.svg(width, height));

    svg.append("g")
        .selectAll("g")
        .data(data)
        .join("g")
        .attr("transform", d => `translate(${x0(d[groupKey])},0)`)
        .selectAll("rect")
        .data(d => keys.map(key => ({key, value: d[key]})))
        .join("rect")
        .attr("x", d => x1(d.key))
        .attr("y", d => y(d.value))
        .attr("width", x1.bandwidth())
        .attr("height", d => y(0) - y(d.value))
        .attr("fill", d => color(d.key));

    svg.append("g")
        .call(xAxis);

    svg.append("g")
        .call(yAxis);

    svg.append("g")
        .call(legend);

    return svg.node();
}
</code>```

After that i called index.js file from html script

```<code><!DOCTYPE html>
<html>
<head>
    <title>Visualization 2 (Multiline graph)</title>
    <link rel="stylesheet" href="styles.css">
    <script src="https://unpkg.com/d3@5.6.0/dist/d3.min.js"></script>
</head>
<body>
<svg width="960" height="500"></svg>
<script src="index.js"></script>
</body>
</html>
</code>```

I created the data.csv file from array

```<code>State,Under 5 Years,5 to 13 Years,14 to 17 Years,18 to 24 Years,25 to 44 Years,45 to 64 Years,65 Years and Over
CA,2704659,4499890,2159981,3853788,10604510,8819342,4114496
TX,2027307,3277946,1420518,2454721,7017731,5656528,2472223
NY,1208495,2141490,1058031,1999120,5355235,5120254,2607672
FL,1140516,1938695, 925060,1607297,4782119,4746856,3187797
IL,894368,1558919,725973,1311479,3596343,3239173,1575308
PA,737462,1345341,679201,1203944,3157759,3414001,1910571
</code>```

This code is not giving the required output that is this graph in vizhub.
 How to get the required output. Here is vizhub link to code

Update:
Code is giving me following error in vizhub

```<code>SyntaxError: Unexpected keyword 'const' (57:4)
/index.js (line 57)
53 :       .attr("dy", "0.35em")
54 :       .text(d => d);
55 : }
56 : chart = {
57 :     const svg = d3.select(DOM.svg(width, height));
         ^
</code>```

答:
The first thing to notice is that the javascript running on observablehq is a different flavor of js. It needs a special library runtime to run on your browser. Thus, if you copy and paste the code to a .js .html file it won't work right away.

Observable's Not Javascript

If you're learning d3 and enjoys Observable environment, you could easily download/embed your code on a page using the runtime.

Downloading and Embedding Notebooks

For example, fetching the notebook code from observable and the runtime from jsdelivr.
Remember, you could download the sources and host it from your own servers.
The code below renders cell chart, the runtime makes sure all the other relevant cells are executed in order.

```
</div>
</div>
</p>

<p>Using same approach but exposing the notebook source code, here you can see how your code is abstracted inside the function <code>export default function notebook(runtime, observer)</code> then the runtime is responsible to run it, last two lines</p>

<pre class="lang-js prettyprint-override"><code>    const runtime = new Runtime();
    const main = runtime.module(notebook, Inspector.into(document.body));
</code>```

```

Now if you want to manually convert the code running on Observable to vanilla js, then you might need to look into other references,

How to run a D3 example

D3 example from Observable on my wordpress site

observable to vanillajs

ContentLicense: CC BY-SA 4.0

Body:
I am new d3.js .I am trying to run code at this link(observablehq).For running this code, I placed that code in index.js file.

d3 = require("d3@5")
height = 500
margin = ({top: 10, right: 10, bottom: 20, left: 40})
data = Object.assign(d3.csvParse(await FileAttachment("data.csv").text(), d3.autoType), {y: "Population"})
groupKey = data.columns[0]
keys = data.columns.slice(1)
x0 = d3.scaleBand()
    .domain(data.map(d => d[groupKey]))
    .rangeRound([margin.left, width - margin.right])
    .paddingInner(0.1)
x1 = d3.scaleBand()
    .domain(keys)
    .rangeRound([0, x0.bandwidth()])
    .padding(0.05)
y = d3.scaleLinear()
    .domain([0, d3.max(data, d => d3.max(keys, key => d[key]))]).nice()
    .rangeRound([height - margin.bottom, margin.top])
color = d3.scaleOrdinal()
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"])
xAxis = g => g
    .attr("transform", `translate(0,${height - margin.bottom})`)
    .call(d3.axisBottom(x0).tickSizeOuter(0))
    .call(g => g.select(".domain").remove())
yAxis = g => g
    .attr("transform", `translate(${margin.left},0)`)
    .call(d3.axisLeft(y).ticks(null, "s"))
    .call(g => g.select(".domain").remove())
    .call(g => g.select(".tick:last-of-type text").clone()
        .attr("x", 3)
        .attr("text-anchor", "start")
        .attr("font-weight", "bold")
        .text(data.y))
legend = svg => {
  const g = svg
      .attr("transform", `translate(${width},0)`)
      .attr("text-anchor", "end")
      .attr("font-family", "sans-serif")
      .attr("font-size", 10)
    .selectAll("g")
    .data(color.domain().slice().reverse())
    .join("g")
      .attr("transform", (d, i) => `translate(0,${i * 20})`);

  g.append("rect")
      .attr("x", -19)
      .attr("width", 19)
      .attr("height", 19)
      .attr("fill", color);

  g.append("text")
      .attr("x", -24)
      .attr("y", 9.5)
      .attr("dy", "0.35em")
      .text(d => d);
}
chart = {
    const svg = d3.select(DOM.svg(width, height));

    svg.append("g")
        .selectAll("g")
        .data(data)
        .join("g")
        .attr("transform", d => `translate(${x0(d[groupKey])},0)`)
        .selectAll("rect")
        .data(d => keys.map(key => ({key, value: d[key]})))
        .join("rect")
        .attr("x", d => x1(d.key))
        .attr("y", d => y(d.value))
        .attr("width", x1.bandwidth())
        .attr("height", d => y(0) - y(d.value))
        .attr("fill", d => color(d.key));

    svg.append("g")
        .call(xAxis);

    svg.append("g")
        .call(yAxis);

    svg.append("g")
        .call(legend);

    return svg.node();
}

After that i called index.js file from html script

<!DOCTYPE html>

    <title>Visualization 2 (Multiline graph)</title>
    <link rel="stylesheet" href="styles.css">

<svg width="960" height="500"></svg>

I created the data.csv file from array

State,Under 5 Years,5 to 13 Years,14 to 17 Years,18 to 24 Years,25 to 44 Years,45 to 64 Years,65 Years and Over
CA,2704659,4499890,2159981,3853788,10604510,8819342,4114496
TX,2027307,3277946,1420518,2454721,7017731,5656528,2472223
NY,1208495,2141490,1058031,1999120,5355235,5120254,2607672
FL,1140516,1938695, 925060,1607297,4782119,4746856,3187797
IL,894368,1558919,725973,1311479,3596343,3239173,1575308
PA,737462,1345341,679201,1203944,3157759,3414001,1910571

This code is not giving the required output that is this graph in vizhub.
 How to get the required output. Here is vizhub link to code

Update:
Code is giving me following error in vizhub

SyntaxError: Unexpected keyword 'const' (57:4)
/index.js (line 57)
53 :       .attr("dy", "0.35em")
54 :       .text(d => d);
55 : }
56 : chart = {
57 :     const svg = d3.select(DOM.svg(width, height));
         ^

Body:
The first thing to notice is that the javascript running on observablehq is a different flavor of js. It needs a special library runtime to run on your browser. Thus, if you copy and paste the code to a .js .html file it won't work right away.

Observable's Not Javascript

If you're learning d3 and enjoys Observable environment, you could easily download/embed your code on a page using the runtime.

Downloading and Embedding Notebooks

For example, fetching the notebook code from observable and the runtime from jsdelivr.
Remember, you could download the sources and host it from your own servers.
The code below renders cell chart, the runtime makes sure all the other relevant cells are executed in order.

<div id="observablehq-758e3cb7"></div>
<script type="module">
import {Runtime, Inspector} from "https://cdn.jsdelivr.net/npm/@observablehq/runtime@4/dist/runtime.js";
import define from "https://api.observablehq.com/@d3/grouped-bar-chart.js?v=3";
const inspect = Inspector.into("#observablehq-758e3cb7");
(new Runtime).module(define, name => name === "chart" ? inspect() : undefined);
</script>

Using same approach but exposing the notebook source code, here you can see how your code is abstracted inside the function export default function notebook(runtime, observer) then the runtime is responsible to run it, last two lines

    const runtime = new Runtime();
    const main = runtime.module(notebook, Inspector.into(document.body));

<script type="module">

import {Runtime, Inspector} from "https://cdn.jsdelivr.net/npm/@observablehq/runtime@4/dist/runtime.js";

// https://observablehq.com/@d3/grouped-bar-chart@81
export default function notebook(runtime, observer) {
  const main = runtime.module();
  const fileAttachments = new Map([["data.csv","https://static.observableusercontent.com/files/72eda648679b19ee477d3b70a598c977219672ab0c809bd42a0e15fb322894dc78dead25bd50ad1613de459d161dc6278b3add8d5f251547b393b10c4cf00a05"]]);
  main.builtin("FileAttachment", runtime.fileAttachments(name => fileAttachments.get(name)));
  main.variable(observer()).define(["md"], function(md){return(
md`# Grouped Bar Chart`
)});
  main.variable(observer("chart")).define("chart", ["d3","DOM","width","height","data","x0","groupKey","keys","x1","y","color","xAxis","yAxis","legend"], function(d3,DOM,width,height,data,x0,groupKey,keys,x1,y,color,xAxis,yAxis,legend)
{
  const svg = d3.select(DOM.svg(width, height));

  svg.append("g")
    .selectAll("g")
    .data(data)
    .join("g")
      .attr("transform", d => `translate(${x0(d[groupKey])},0)`)
    .selectAll("rect")
    .data(d => keys.map(key => ({key, value: d[key]})))
    .join("rect")
      .attr("x", d => x1(d.key))
      .attr("y", d => y(d.value))
      .attr("width", x1.bandwidth())
      .attr("height", d => y(0) - y(d.value))
      .attr("fill", d => color(d.key));

  svg.append("g")
      .call(xAxis);

  svg.append("g")
      .call(yAxis);

  svg.append("g")
      .call(legend);

  return svg.node();
}
);
  main.variable(observer("legend")).define("legend", ["width","color"], function(width,color){return(
svg => {
  const g = svg
      .attr("transform", `translate(${width},0)`)
      .attr("text-anchor", "end")
      .attr("font-family", "sans-serif")
      .attr("font-size", 10)
    .selectAll("g")
    .data(color.domain().slice().reverse())
    .join("g")
      .attr("transform", (d, i) => `translate(0,${i * 20})`);

  g.append("rect")
      .attr("x", -19)
      .attr("width", 19)
      .attr("height", 19)
      .attr("fill", color);

  g.append("text")
      .attr("x", -24)
      .attr("y", 9.5)
      .attr("dy", "0.35em")
      .text(d => d);
}
)});
  main.variable(observer("x0")).define("x0", ["d3","data","groupKey","margin","width"], function(d3,data,groupKey,margin,width){return(
d3.scaleBand()
    .domain(data.map(d => d[groupKey]))
    .rangeRound([margin.left, width - margin.right])
    .paddingInner(0.1)
)});
  main.variable(observer("x1")).define("x1", ["d3","keys","x0"], function(d3,keys,x0){return(
d3.scaleBand()
    .domain(keys)
    .rangeRound([0, x0.bandwidth()])
    .padding(0.05)
)});
  main.variable(observer("y")).define("y", ["d3","data","keys","height","margin"], function(d3,data,keys,height,margin){return(
d3.scaleLinear()
    .domain([0, d3.max(data, d => d3.max(keys, key => d[key]))]).nice()
    .rangeRound([height - margin.bottom, margin.top])
)});
  main.variable(observer("color")).define("color", ["d3"], function(d3){return(
d3.scaleOrdinal()
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"])
)});
  main.variable(observer("xAxis")).define("xAxis", ["height","margin","d3","x0"], function(height,margin,d3,x0){return(
g => g
    .attr("transform", `translate(0,${height - margin.bottom})`)
    .call(d3.axisBottom(x0).tickSizeOuter(0))
    .call(g => g.select(".domain").remove())
)});
  main.variable(observer("yAxis")).define("yAxis", ["margin","d3","y","data"], function(margin,d3,y,data){return(
g => g
    .attr("transform", `translate(${margin.left},0)`)
    .call(d3.axisLeft(y).ticks(null, "s"))
    .call(g => g.select(".domain").remove())
    .call(g => g.select(".tick:last-of-type text").clone()
        .attr("x", 3)
        .attr("text-anchor", "start")
        .attr("font-weight", "bold")
        .text(data.y))
)});
  main.variable(observer("data")).define("data", ["d3","FileAttachment"], async function(d3,FileAttachment){return(
Object.assign(d3.csvParse(await FileAttachment("data.csv").text(), d3.autoType), {y: "Population"})
)});
  main.variable(observer("groupKey")).define("groupKey", ["data"], function(data){return(
data.columns[0]
)});
  main.variable(observer("keys")).define("keys", ["data"], function(data){return(
data.columns.slice(1)
)});
  main.variable(observer("margin")).define("margin", function(){return(
{top: 10, right: 10, bottom: 20, left: 40}
)});
  main.variable(observer("height")).define("height", function(){return(
500
)});
  main.variable(observer("d3")).define("d3", ["require"], function(require){return(
require("d3@5")
)});
  return main;
}

const runtime = new Runtime();
const main = runtime.module(notebook, Inspector.into(document.body));

</script>

Now if you want to manually convert the code running on Observable to vanilla js, then you might need to look into other references,

How to run a D3 example

D3 example from Observable on my wordpress site

observable to vanillajs


问:
Preserve leading zeros in scrapy csv file
I need to preserve the leading zeros while exporting zip codes to the csv file in scrapy. I have the following exporter to implement but it didn't help me.

```<code>import csv

from scrapy.exporters import CsvItemExporter

class QuoteAllDialect(csv.excel):
    quoting = csv.QUOTE_ALL

class QuoteAllCsvItemExporter(CsvItemExporter):

    def __init__(self, *args, **kwargs):
        kwargs.update({'dialect': QuoteAllDialect})
        super(QuoteAllCsvItemExporter, self).__init__(*args, **kwargs)
</code>```

I extract zip codes in the following way. In this way they are never treated as integers:

```<code>addr = response.xpath('//address/span/text()').extract()

full_ad = ", ".join(addr)

zip_code = full_ad[-5:]
</code>```

I need help in finding out the way to implement so that scrapy handles it automatically. Any help would be appreciated. Thanks

答:
I need to preserve the leading zeros while exporting zip codes

It sounds like you are treating zip codes as integers. Don't do that; just treat them as strings. They have no integer meaning (you can't do any reasonable arithmetic on them), so don't interpret them as integers.

Then you won't have to worry about preserving any formatting.

Body:
I need to preserve the leading zeros while exporting zip codes to the csv file in scrapy. I have the following exporter to implement but it didn't help me.

import csv

from scrapy.exporters import CsvItemExporter

class QuoteAllDialect(csv.excel):
    quoting = csv.QUOTE_ALL

class QuoteAllCsvItemExporter(CsvItemExporter):

    def __init__(self, *args, **kwargs):
        kwargs.update({'dialect': QuoteAllDialect})
        super(QuoteAllCsvItemExporter, self).__init__(*args, **kwargs)

I extract zip codes in the following way. In this way they are never treated as integers:

addr = response.xpath('//address/span/text()').extract()

full_ad = ", ".join(addr)

zip_code = full_ad[-5:]

I need help in finding out the way to implement so that scrapy handles it automatically. Any help would be appreciated. Thanks


问:
Can't display Data in ComboBox Control of DropDownStyle (DropDownList)
I have the following requirement,

I have a ComboBox Control (DropDownList Style) which user has to select a given value, but can not edit. Then I save it to a Database    Table, and it's working fine.

```<code>(dataRow("it_discount_profile") = Trim(cmbDisProfile.Text))
</code>```

But when I try to show the same Data in the same ComboBox by retrieving it from the Database, it won't show.

```<code>(cmbDisProfile.Text = Trim(tempTb.Rows(0).Item("it_discount_profile")))
</code>```

When I change the ComboBox to "DropDown Style", it works. But then the User can edit it.

Am I missing something here or is it like that? Any advice will be highly appreciated.

Im filling it in runtime using a procedure.

```<code>Private Sub filldisProfiles()
    Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
    Dim tempTb As DataTable
    Dim myTbClass As myClassTableActivities = New myClassTableActivities()
    tempTb = myTbClass.myFunctionFetchTbData(sqlString)

    cmbDisProfile.DataSource = tempTb
    cmbDisProfile.DisplayMember = "discount_profile"
End Sub
</code>```

Ok. Actually, Im trying to migrate one of my old project from VB to VB.Net. VB.Net is little new to me. Im using a self built classto reduce codes in other places. Im attaching the class below.

My actual requirement is to populate the combo box from a table. I like to do it in run time. I don't want users to edit it. If they want to add a new value, they have separate place (Form) for that. I think im doing it in a wrong way. If possible please give a sample code since I'm not familiar with the proposed method.

```<code>Public Function myFunctionFetchTbData(ByVal inputSqlString As String) As DataTable
    Try
        Dim SqlCmd As New SqlCommand(inputSqlString, conn)
        Dim dataAdapter As New SqlDataAdapter(SqlCmd)

        Dim fetchedDataSet As New DataSet
        fetchedDataSet.Clear()
        dataAdapter.Fill(fetchedDataSet)

        Dim fetchedDataTable As DataTable = fetchedDataSet.Tables(0)

        Return fetchedDataTable

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function

' this sub will update a table
Public Sub MyMethodUpdateTable(ByVal sqlString As String, ByVal tbToUpdate As DataTable)

    Dim SqlCmd As New SqlCommand(sqlString, conn)
    Dim dataAdapter As New SqlDataAdapter(SqlCmd)
    Dim objCommandBuilder As New SqlClient.SqlCommandBuilder(dataAdapter)
    dataAdapter.Update(tbToUpdate)

End Sub

Public Function MyMethodfindRecord(ByVal strSearckKey As String, ByVal tableName As String, ByVal strColumnName As String) As Boolean
    Try
        Dim searchSql As String = "SELECT * FROM " & tableName & " WHERE " & strColumnName & "='" & strSearckKey & "'"

        'Dim searchString As String = txtCategoryCode.Text
        '        searchOwnerCmd.Parameters.Clear()
        '        searchOwnerCmd.Parameters.AddWithValue("a", "%" & search & "%")

        Dim tempTb As DataTable
        Dim myTbClass As myClassTableActivities = New myClassTableActivities()
        tempTb = myTbClass.myFunctionFetchTbData(searchSql)

        If tempTb.Rows.Count = 0 Then
            Return False
        Else
            Return True
        End If

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function
Public Function myFunctionFetchSearchTB(ByVal inputSqlString As String) As DataTable
    Try
        Dim SqlCmd As New SqlCommand(inputSqlString, conn)
        Dim dataAdapter As New SqlDataAdapter(SqlCmd)

        Dim fetchedDataSet As New DataSet
        fetchedDataSet.Clear()
        dataAdapter.Fill(fetchedDataSet)

        Dim fetchedSearchTB As DataTable = fetchedDataSet.Tables(0)

        Return fetchedSearchTB

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function
</code>```

答:
OK. If I understood correctly, you have a problem in retrieving Data [String] from a Database Table into a ComboBox of DropDownStyle [DropDownList].

How do you fill/populate your ComboBox with Data From Database Table ?

In this link, Microsoft docs state, that:

Use the SelectedIndex property to programmatically determine the index
  of the item selected by the user from the DropDownList control. The
  index can then be used to retrieve the selected item from the Items
  collection of the control.

In much more plain English
You can never SET ComboBox.Text Value while in DropDownList by code, which you already knew by testing your code, but you need to use DisplayMember and ValueMember or SelectedIndex.

```<code>ComboBox1.SelectedIndex = ComboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
</code>```

Please consider populating your ComboBox Control from Database Table using (Key,Value) Dictionary collection, here is an example

Body:
I have the following requirement,

I have a ComboBox Control (DropDownList Style) which user has to select a given value, but can not edit. Then I save it to a Database    Table, and it's working fine.

(dataRow("it_discount_profile") = Trim(cmbDisProfile.Text))

But when I try to show the same Data in the same ComboBox by retrieving it from the Database, it won't show.

(cmbDisProfile.Text = Trim(tempTb.Rows(0).Item("it_discount_profile")))

When I change the ComboBox to "DropDown Style", it works. But then the User can edit it.

Am I missing something here or is it like that? Any advice will be highly appreciated.

Im filling it in runtime using a procedure.

Private Sub filldisProfiles()
    Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
    Dim tempTb As DataTable
    Dim myTbClass As myClassTableActivities = New myClassTableActivities()
    tempTb = myTbClass.myFunctionFetchTbData(sqlString)

    cmbDisProfile.DataSource = tempTb
    cmbDisProfile.DisplayMember = "discount_profile"
End Sub

Ok. Actually, Im trying to migrate one of my old project from VB to VB.Net. VB.Net is little new to me. Im using a self built classto reduce codes in other places. Im attaching the class below.

My actual requirement is to populate the combo box from a table. I like to do it in run time. I don't want users to edit it. If they want to add a new value, they have separate place (Form) for that. I think im doing it in a wrong way. If possible please give a sample code since I'm not familiar with the proposed method.

Public Function myFunctionFetchTbData(ByVal inputSqlString As String) As DataTable
    Try
        Dim SqlCmd As New SqlCommand(inputSqlString, conn)
        Dim dataAdapter As New SqlDataAdapter(SqlCmd)

        Dim fetchedDataSet As New DataSet
        fetchedDataSet.Clear()
        dataAdapter.Fill(fetchedDataSet)

        Dim fetchedDataTable As DataTable = fetchedDataSet.Tables(0)

        Return fetchedDataTable

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function

' this sub will update a table
Public Sub MyMethodUpdateTable(ByVal sqlString As String, ByVal tbToUpdate As DataTable)

    Dim SqlCmd As New SqlCommand(sqlString, conn)
    Dim dataAdapter As New SqlDataAdapter(SqlCmd)
    Dim objCommandBuilder As New SqlClient.SqlCommandBuilder(dataAdapter)
    dataAdapter.Update(tbToUpdate)

End Sub

Public Function MyMethodfindRecord(ByVal strSearckKey As String, ByVal tableName As String, ByVal strColumnName As String) As Boolean
    Try
        Dim searchSql As String = "SELECT * FROM " & tableName & " WHERE " & strColumnName & "='" & strSearckKey & "'"

        'Dim searchString As String = txtCategoryCode.Text
        '        searchOwnerCmd.Parameters.Clear()
        '        searchOwnerCmd.Parameters.AddWithValue("a", "%" & search & "%")

        Dim tempTb As DataTable
        Dim myTbClass As myClassTableActivities = New myClassTableActivities()
        tempTb = myTbClass.myFunctionFetchTbData(searchSql)

        If tempTb.Rows.Count = 0 Then
            Return False
        Else
            Return True
        End If

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function
Public Function myFunctionFetchSearchTB(ByVal inputSqlString As String) As DataTable
    Try
        Dim SqlCmd As New SqlCommand(inputSqlString, conn)
        Dim dataAdapter As New SqlDataAdapter(SqlCmd)

        Dim fetchedDataSet As New DataSet
        fetchedDataSet.Clear()
        dataAdapter.Fill(fetchedDataSet)

        Dim fetchedSearchTB As DataTable = fetchedDataSet.Tables(0)

        Return fetchedSearchTB

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function

Body:
OK. If I understood correctly, you have a problem in retrieving Data [String] from a Database Table into a ComboBox of DropDownStyle [DropDownList].

How do you fill/populate your ComboBox with Data From Database Table ?

In this link, Microsoft docs state, that:

Use the SelectedIndex property to programmatically determine the index
  of the item selected by the user from the DropDownList control. The
  index can then be used to retrieve the selected item from the Items
  collection of the control.

In much more plain English
You can never SET ComboBox.Text Value while in DropDownList by code, which you already knew by testing your code, but you need to use DisplayMember and ValueMember or SelectedIndex.

ComboBox1.SelectedIndex = ComboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))

Please consider populating your ComboBox Control from Database Table using (Key,Value) Dictionary collection, here is an example


问:
Visual Studio 2017 error Cannot open "X" for writing - access to path is denied
I'm sorry I cannot seem to fix this error:

Severity  Code    Description Project File    Line    Suppression State
  Error CS2012  Cannot open
  'C:\Users\Usuario\source\repos\WindowsFormsApp1\WindowsFormsApp1\obj\Debug\WindowsFormsApp1.exe'
  for writing -- 'Access to the path
  'C:\Users\Usuario\source\repos\WindowsFormsApp1\WindowsFormsApp1\obj\Debug\WindowsFormsApp1.exe'
  is
  denied.'  WindowsFormsApp1    C:\Users\Usuario\source\repos\WindowsFormsApp1\WindowsFormsApp1\CSC 1   Active

I suppose it has something to do with the file being read only? I tried changing it and it reverts to read only, I tried closing and reopening VS, I tried running it as an administrator, I changed the assembly name and default namespace and now it won't even run the debugger

I'm new to C#, I used to do Java and never had an error like this one, sorry if it's something very simple. By the way I'm using Windows 10 with Bitdefender installed

答:
This issue occurs because the dll file is open some where, suppose you try to delete the dll file from obj folder then also message appears that "The file is open in another program."

In my case, I close all VS instance and copy the root folder and paste it into another folder then open my solution in VS it works fine.

ContentLicense: CC BY-SA 3.0


问:
Print the Pascal triangle when input the height of this triangle in C
```<code>#include<stdio.h>
int factorial(int a){
    int b;
    if (a==0)
        return 1;
    else
        for (b=1;b<=a;b++)
        a=a*b;
}   //factorial of a
int pascal(int i, int j){

        return (factorial(i))/((factorial(j))*factorial(i-j));

}
int main()
{
    int k,n,m,q;
    printf("Input m: ");
    scanf("%d", &m);
    for(k=0;k<m;k++){
        for(n=0;n<=k;n++)
            printf("%d ", pascal(k, n));

        printf("\n");
    }
}
</code>```

I make a program that print the Pascal triangle but it make the right answer if height<=3, when I input m=6; it will print:

```<code>1
1 1
1 3 1
1 0 0 1
1 0 0 0 1
1 0 0 0 0 1
</code>```

Can you help me find the bugs in my code?

答:
that's because you have written the wrong logic in the function factorial().

```<code>for (b=1;b<=a;b++)
    a=a*b;//also , you have to return the value of a here!
</code>```

here, suppose a = 3, then, in 1st iteration, a = 3*1 equals 3, in 2nd iteration, a=3*2 equals 6; since 6>3 ,loop terminates and you got the right answer!!
but if a = 4, then, in 1st iteration, a = 4*1 equals 4, in 2nd iteration, a=4*2 equals 8 which is greater than 4, therefore loop does not executes further and you got the wrong answer!
the correct logic would be, to declare another int variable and initialize it to 1 to store the product of 'a' and the variable in it itself i.e,

```<code> int fac=1;
    for(b=1;b<=a;b++){
        fac = fac*b;
    }
    return fac;
</code>```

so, the full code will be,

```<code>#include<stdio.h>
int factorial(int a){
int b=0;
if (a==0)
    return 1;
else{

   /* for(b=1;b<=a;b++){
        fac = b*(factorial(b-1));// another way to find factorial using recursion
return fac;
}*/
    int fac=1;
    for(b=1;b<=a;b++){
        fac = fac*b;
    }
    return fac;
  }

}   //factorial of a

int pascal(int i, int j){

    return factorial(i) / (factorial(j) *factorial(i-j));
 }
int main()
{
  int k,n,m,q;

   printf("Input m: ");
   scanf("%d", &m);

   for(k=0;k<m;k++){
    for(n=0;n<=k;n++)
        printf("%d ", pascal(k, n));

    printf("\n");
   }
   return 0;  // a good habit to add return 0, to let the compiler know that
             // the code is executed completely
}
</code>```

Body:
#include<stdio.h>
int factorial(int a){
    int b;
    if (a==0)
        return 1;
    else
        for (b=1;b<=a;b++)
        a=a*b;
}   //factorial of a
int pascal(int i, int j){

        return (factorial(i))/((factorial(j))*factorial(i-j));

}
int main()
{
    int k,n,m,q;
    printf("Input m: ");
    scanf("%d", &m);
    for(k=0;k<m;k++){
        for(n=0;n<=k;n++)
            printf("%d ", pascal(k, n));

        printf("\n");
    }
}

I make a program that print the Pascal triangle but it make the right answer if height<=3, when I input m=6; it will print:

1
1 1
1 3 1
1 0 0 1
1 0 0 0 1
1 0 0 0 0 1

Can you help me find the bugs in my code?

Body:
that's because you have written the wrong logic in the function factorial().

for (b=1;b<=a;b++)
    a=a*b;//also , you have to return the value of a here!

here, suppose a = 3, then, in 1st iteration, a = 3*1 equals 3, in 2nd iteration, a=3*2 equals 6; since 6>3 ,loop terminates and you got the right answer!!
but if a = 4, then, in 1st iteration, a = 4*1 equals 4, in 2nd iteration, a=4*2 equals 8 which is greater than 4, therefore loop does not executes further and you got the wrong answer!
the correct logic would be, to declare another int variable and initialize it to 1 to store the product of 'a' and the variable in it itself i.e,

 int fac=1;
    for(b=1;b<=a;b++){
        fac = fac*b;
    }
    return fac;

so, the full code will be,

#include<stdio.h>
int factorial(int a){
int b=0;
if (a==0)
    return 1;
else{

   /* for(b=1;b<=a;b++){
        fac = b*(factorial(b-1));// another way to find factorial using recursion
return fac;
}*/
    int fac=1;
    for(b=1;b<=a;b++){
        fac = fac*b;
    }
    return fac;
  }

}   //factorial of a

int pascal(int i, int j){

    return factorial(i) / (factorial(j) *factorial(i-j));
 }
int main()
{
  int k,n,m,q;

   printf("Input m: ");
   scanf("%d", &m);

   for(k=0;k<m;k++){
    for(n=0;n<=k;n++)
        printf("%d ", pascal(k, n));

    printf("\n");
   }
   return 0;  // a good habit to add return 0, to let the compiler know that
             // the code is executed completely
}


问:
problem with key from firebase - return from my interface is undefined
So im doing the Online Course from Mosh Hamedami. I've been following it more or less but everything is working. I can Add Products to Firebase and Edit/Delete them.
Now I want to implement a "shopping-cart" where I can add a specific CardId and add Items + quantity to that cardId

However I'm facing a problem where i want to add a Product to the firebase shopping-cart. Adding a shopping-cart with an cartId - timestamp works.
Somehow I can't add an item to the cartId.

I got a Problem with the Observable I guess...

the Console Error is :

```<code>_core.js:6260 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'key' of undefined
TypeError: Cannot read property 'key' of undefined_
at ShoppingCartService.<anonymous> (shopping-cart.service.ts:51)

</code>```

It tells me that my product from 'addToCart' is undefined.

```<code>  addToCart(product: Product) {
    this.shoppingCartService.addToCart(product);
    console.log(product);
  }
</code>```

Also my complier tells me that take form .pipe(take(1)) is:

_error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type'Observable'.

somehow pipe(first()) works, but is delivering the same problem with the key.

I've tried a lot can't figure out my mistakes. Im new to Angular as well so..I would really appreciate any kind of tipps where I have to search for the Problem.

shopping-cart.service.ts

```<code>import {Injectable} from '@angular/core';
import {AngularFireDatabase} from "@angular/fire/database";
import {Product} from "./models/product";
import 'rxjs/add/operator/take';
import {take} from "rxjs-compat/operator/take";
import {pipe} from "rxjs";
import {Observable} from "rxjs";
import {first} from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})
export class ShoppingCartService {

  constructor(private db: AngularFireDatabase) {
  }

  //create shopping cart in db + add date(timestamp)
  private create() {
    return this.db.list("/shopping-carts").push({
      dateCreated: new Date().getTime()
    });
  }

  private getCart(cartId: string) {
    return this.db.object('/shopping-carts/' + cartId);
  }

  private getItem(cartId: string, productId: string) {
    return this.db.object('/shopping-carts/' + cartId + '/items/' + productId);
  }

  //getting reference to shopping cart
  private async getOrCreateCartId(): Promise<string> {

    let cartId = localStorage.getItem('cartId');
    if (cartId) return cartId;
    // calls this.create and waits for the response
    let result = await this.create();
    //saves cartId in local storage and returns
    localStorage.setItem('cartId', result.key);
    return result.key;
  }

  //add new product to cart and safe localstorage
  async addToCart(product: Product) {
    const cartId = await this.getOrCreateCartId();
    //reference to products in firebase cart
    const item$ = this.getItem(cartId, product.key);

    item$.snapshotChanges().pipe(take(1)).subscribe((item: any) => {
      if (item) {
        item$.update({product: product, quantity: (item.quantity || 0) + 1});
      }
    });
  }
}
</code>```

product.ts

```<code>export interface Product {
  key : string;
  title : string;
  price : number;
  category : string;
  imageURL : string;
}
</code>```

html which is calling addToCart:

```<code><div class="columns is-multiline is-narrow">
  <ng-container *ngFor="let p of filteredProductsByCategory">
    <div class="column is-one-third">
      <div class="card">
        <figure class="image is-square">
          <img [src]="p.imageURL" alt="{{p.title}}">
        </figure>
      </div>
      <div class="card-content">
        <p class="title"> {{p.title}}</p>
        <p class="subtitle">{{p.price | currency: "USD"}}</p>
        <div
             (click)="addToCart(product)"
             class="button is-outlined is-primary"> Add to Cart</div>
      </div>
    </div>
  </ng-container>
</div>

</code>```

I could also upload my code to GitHub if needed!
Thanks!!

答:
```<code>// add new product to cart and safe localstorage
async addToCart(product: Product) { ... }
</code>```

With a very high probability when calling addToCart the product is simply not set.
You should check the point (*.component.ts or *.component.html?) where the function is called and and product should be set.

edit:

I guess you want to pass p instead of product. Try following:

```<code><div
    (click)="addToCart(p)"
    class="button is-outlined is-primary"> Add to Cart</div>
</code>```

Body:
So im doing the Online Course from Mosh Hamedami. I've been following it more or less but everything is working. I can Add Products to Firebase and Edit/Delete them.
Now I want to implement a "shopping-cart" where I can add a specific CardId and add Items + quantity to that cardId

However I'm facing a problem where i want to add a Product to the firebase shopping-cart. Adding a shopping-cart with an cartId - timestamp works.
Somehow I can't add an item to the cartId.

I got a Problem with the Observable I guess...

the Console Error is :

_core.js:6260 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'key' of undefined
TypeError: Cannot read property 'key' of undefined_
at ShoppingCartService.<anonymous> (shopping-cart.service.ts:51)

It tells me that my product from 'addToCart' is undefined.

  addToCart(product: Product) {
    this.shoppingCartService.addToCart(product);
    console.log(product);
  }

Also my complier tells me that take form .pipe(take(1)) is:

_error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type'Observable'.

somehow pipe(first()) works, but is delivering the same problem with the key.

I've tried a lot can't figure out my mistakes. Im new to Angular as well so..I would really appreciate any kind of tipps where I have to search for the Problem.

shopping-cart.service.ts

import {Injectable} from '@angular/core';
import {AngularFireDatabase} from "@angular/fire/database";
import {Product} from "./models/product";
import 'rxjs/add/operator/take';
import {take} from "rxjs-compat/operator/take";
import {pipe} from "rxjs";
import {Observable} from "rxjs";
import {first} from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})
export class ShoppingCartService {

  constructor(private db: AngularFireDatabase) {
  }

  //create shopping cart in db + add date(timestamp)
  private create() {
    return this.db.list("/shopping-carts").push({
      dateCreated: new Date().getTime()
    });
  }

  private getCart(cartId: string) {
    return this.db.object('/shopping-carts/' + cartId);
  }

  private getItem(cartId: string, productId: string) {
    return this.db.object('/shopping-carts/' + cartId + '/items/' + productId);
  }

  //getting reference to shopping cart
  private async getOrCreateCartId(): Promise<string> {

    let cartId = localStorage.getItem('cartId');
    if (cartId) return cartId;
    // calls this.create and waits for the response
    let result = await this.create();
    //saves cartId in local storage and returns
    localStorage.setItem('cartId', result.key);
    return result.key;
  }

  //add new product to cart and safe localstorage
  async addToCart(product: Product) {
    const cartId = await this.getOrCreateCartId();
    //reference to products in firebase cart
    const item$ = this.getItem(cartId, product.key);

    item$.snapshotChanges().pipe(take(1)).subscribe((item: any) => {
      if (item) {
        item$.update({product: product, quantity: (item.quantity || 0) + 1});
      }
    });
  }
}

product.ts

export interface Product {
  key : string;
  title : string;
  price : number;
  category : string;
  imageURL : string;
}

html which is calling addToCart:

  <ng-container *ngFor="let p of filteredProductsByCategory">

 {{p.title}}

{{p.price | currency: "USD"}}

 Add to Cart

  </ng-container>

I could also upload my code to GitHub if needed!
Thanks!!

Body:
// add new product to cart and safe localstorage
async addToCart(product: Product) { ... }

With a very high probability when calling addToCart the product is simply not set.
You should check the point (*.component.ts or *.component.html?) where the function is called and and product should be set.

edit:

I guess you want to pass p instead of product. Try following:

<div
    (click)="addToCart(p)"
    class="button is-outlined is-primary"> Add to Cart</div>


问:
Java ProcessBuilder is not able to start GNU screen
I'm experiencing a weird behaviour of java's ProcessBuilder.
What I try is to stop a running screen using a shell, delete a few folders and after that restart the screen using another shell script.
The first step, killing the running screen, runs perfectly using:

```<code> ProcessBuilder pb0 = new ProcessBuilder(System.getProperty("user.dir") + "/generator/stop.sh");
</code>```

In this stop.sh shell I simply run

screen -X -S generator kill

which works as it should.
After that I delete my directorys using org.apache.commons.io.FileUtils and then I want to start the screen again. Currently I'm doing it like that:

```<code>    System.out.println("Restarting the generator");

    ProcessBuilder pb1 = new ProcessBuilder();
    pb1.directory(new File(System.getProperty("user.dir") + "/generator"));
    pb1.command("./start.sh");
    try {
        Process process = pb1.start();
        System.out.printf("Started the generator with %d", process.waitFor());
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
</code>```

This gives out "Started the generator with 1" which indicates to me that the screen runs which is simply not the case when checking with screen -ls.
No errors, no clue on how to move forward from here

Inside start.sh:

```<code>screen -S generator java -Xms2G -Xmx2G -jar generator.jar
</code>```

PS: I'm using Debian 10.
Maybe anyone can help me out here?
Greets!

答:
You should never ignore process output, because it's buffer has limited length, and if you don't consume it, it will hang. Im not sure if this is causing your issue, but this is definitely something you should do.

It is also possible that process throws some error that you can't see because you are ignoring it's output (in which case, this will help you to investigate the issue).

Try this:

new ProcessBuilder()
  .redirectOutput(ProcessBuilder.Redirect.INHERIT)
  .redirectError(ProcessBuilder.Redirect.INHERIT)
  ...
```

This will redirect process output stream and input stream to it's parent (which is your application).

Body:
I'm experiencing a weird behaviour of java's ProcessBuilder.
What I try is to stop a running screen using a shell, delete a few folders and after that restart the screen using another shell script.
The first step, killing the running screen, runs perfectly using:

 ProcessBuilder pb0 = new ProcessBuilder(System.getProperty("user.dir") + "/generator/stop.sh");

In this stop.sh shell I simply run

screen -X -S generator kill

which works as it should.
After that I delete my directorys using org.apache.commons.io.FileUtils and then I want to start the screen again. Currently I'm doing it like that:

    System.out.println("Restarting the generator");

    ProcessBuilder pb1 = new ProcessBuilder();
    pb1.directory(new File(System.getProperty("user.dir") + "/generator"));
    pb1.command("./start.sh");
    try {
        Process process = pb1.start();
        System.out.printf("Started the generator with %d", process.waitFor());
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }

This gives out "Started the generator with 1" which indicates to me that the screen runs which is simply not the case when checking with screen -ls.
No errors, no clue on how to move forward from here

Inside start.sh:

screen -S generator java -Xms2G -Xmx2G -jar generator.jar

PS: I'm using Debian 10.
Maybe anyone can help me out here?
Greets!

Body:
You should never ignore process output, because it's buffer has limited length, and if you don't consume it, it will hang. Im not sure if this is causing your issue, but this is definitely something you should do.

It is also possible that process throws some error that you can't see because you are ignoring it's output (in which case, this will help you to investigate the issue).

Try this:

new ProcessBuilder()
  .redirectOutput(ProcessBuilder.Redirect.INHERIT)
  .redirectError(ProcessBuilder.Redirect.INHERIT)
  ...

This will redirect process output stream and input stream to it's parent (which is your application).


问:
Why the need to redefine properties when implementing an interface in TypeScript?
I'm getting into classes and interfaces. And I got one thing about it that annoys me, this is the first time I work with these kind of things so bear with me here..

Let's say I got this interface:

```<code>// IFoo.d.ts
export default interface IFoo {
  foo: string;
  bar: number;
}
</code>```

When I implement it in a class I do the following:

```<code>// FooModel.ts
import IFoo from './IFoo';

export default class FooModel implements IFoo {
  foo: string;
  bar: number;

  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}
</code>```

Why do I have to implement the same properties all over again?

This is basically the same as copy-paste but with a strict convention. Also, I have to type foo and bar a total of 6 times each to get it properly assigned with default optional values, based on an interface.

Is there a more efficient way to do this too?

Edit; I'm trying to achieve the following:

A class with the properties, from which the properties can be used for typescript's checking, like this:
interface

```<code>export default interface FooDTO {
  foo: string;
  bar: number;
}
</code>```

model

```<code>export interface IFoo {
  foo: string;
  bar: number;
}

export default class FooModel implements IFoo {
  foo: string;
  bar: number;

  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}
</code>```

controller

```<code>export default class FooController {
   public static async readAll(): Array<FooDTO> {
      // some model stuff which maps query to dto
      return Array<FooDTO>result;
   }
}
</code>```

答:
Instead of an interface, you could use an abstract class. Same benefits as an interface, but with the possibility of extending it:

```<code>export abstract class IFoo {
  foo: string;
  bar: number;
}

export default class FooModel extends IFoo {
  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}
</code>```

Body:
I'm getting into classes and interfaces. And I got one thing about it that annoys me, this is the first time I work with these kind of things so bear with me here..

Let's say I got this interface:

// IFoo.d.ts
export default interface IFoo {
  foo: string;
  bar: number;
}

When I implement it in a class I do the following:

// FooModel.ts
import IFoo from './IFoo';

export default class FooModel implements IFoo {
  foo: string;
  bar: number;

  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}

Why do I have to implement the same properties all over again?

This is basically the same as copy-paste but with a strict convention. Also, I have to type foo and bar a total of 6 times each to get it properly assigned with default optional values, based on an interface.

Is there a more efficient way to do this too?

Edit; I'm trying to achieve the following:

A class with the properties, from which the properties can be used for typescript's checking, like this:
interface

export default interface FooDTO {
  foo: string;
  bar: number;
}

model

export interface IFoo {
  foo: string;
  bar: number;
}

export default class FooModel implements IFoo {
  foo: string;
  bar: number;

  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}

controller

export default class FooController {
   public static async readAll(): Array<FooDTO> {
      // some model stuff which maps query to dto
      return Array<FooDTO>result;
   }
}

Body:
Instead of an interface, you could use an abstract class. Same benefits as an interface, but with the possibility of extending it:

export abstract class IFoo {
  foo: string;
  bar: number;
}

export default class FooModel extends IFoo {
  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}


问:
Why view.frame.width returns zero?
I created stackView and added three labels to it. Also I put these constraints

```<code>let nameLabel = UILabel()
//set .text, .mode and other for nameLabel
let ellipsisLabel = UILabel()
//set .text, .mode and other for ellipsisLabel
let amountAndMeasureLabel = UILabel()
//set .text, .mode and other for amountAndMeasureLabel

for label in [nameLabel, ellipsisLabel, amountAndMeasureLabel] {
                stackView.addArrangedSubview(label)
            }
NSLayoutConstraint.activate([
                nameLabel.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: 0.0),
                nameLabel.trailingAnchor.constraint(equalTo: ellipsisLabel.leadingAnchor, constant: 0.0),
                nameLabel.widthAnchor.constraint(equalToConstant: nameLabel.intrinsicContentSize.width),
                amountAndMeasureLabel.leadingAnchor.constraint(equalTo: ellipsisLabel.trailingAnchor, constant: 0.0),
                amountAndMeasureLabel.trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: 0.0),
                amountAndMeasureLabel.widthAnchor.constraint(equalToConstant: amountAndMeasureLabel.intrinsicContentSize.width)
            ])

nameLabel.frame.width // 0
ellipsisLabel.frame.width // 0
amountAndMeasureLabel.frame.width // 0
</code>```

I will demonstrate the situation on .xib for better understanding (I don't use this .xib)

But when I tried to get their .frame.width I got zeros.

答:
Just activating constraints doesn't cause a view to layout. If you need stackView to immediately layout its subviews, you need to tell it to:

```<code>stackView.layoutIfNeeded()
</code>```

Otherwise the system will automatically collect and apply all layout updates together the next time it's needed. Since forcing a layout may lead to unnecessary computations (if something later in the draw cycle changes the layout), you should generally avoid calling .layoutIfNeeded() unless you really need it. But it's fully supported if you do.

There is also .setNeedsLayout(), which tells the system that a view needs layout during the next draw cycle. You should use this if something changes layout in a way that the system won't notice. You generally don't need this if your changes are through UIKit itself. UIStackView knows that it needs layout after you call .addArrangedSubview. But if you change some piece of data that your layout relies on, you may need to tell UIKit.

Title: Why view.frame.width returns zero?

Body:
I created stackView and added three labels to it. Also I put these constraints

let nameLabel = UILabel()
//set .text, .mode and other for nameLabel
let ellipsisLabel = UILabel()
//set .text, .mode and other for ellipsisLabel
let amountAndMeasureLabel = UILabel()
//set .text, .mode and other for amountAndMeasureLabel

for label in [nameLabel, ellipsisLabel, amountAndMeasureLabel] {
                stackView.addArrangedSubview(label)
            }
NSLayoutConstraint.activate([
                nameLabel.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: 0.0),
                nameLabel.trailingAnchor.constraint(equalTo: ellipsisLabel.leadingAnchor, constant: 0.0),
                nameLabel.widthAnchor.constraint(equalToConstant: nameLabel.intrinsicContentSize.width),
                amountAndMeasureLabel.leadingAnchor.constraint(equalTo: ellipsisLabel.trailingAnchor, constant: 0.0),
                amountAndMeasureLabel.trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: 0.0),
                amountAndMeasureLabel.widthAnchor.constraint(equalToConstant: amountAndMeasureLabel.intrinsicContentSize.width)
            ])

nameLabel.frame.width // 0
ellipsisLabel.frame.width // 0
amountAndMeasureLabel.frame.width // 0

I will demonstrate the situation on .xib for better understanding (I don't use this .xib)

But when I tried to get their .frame.width I got zeros.

Body:
Just activating constraints doesn't cause a view to layout. If you need stackView to immediately layout its subviews, you need to tell it to:

stackView.layoutIfNeeded()

Otherwise the system will automatically collect and apply all layout updates together the next time it's needed. Since forcing a layout may lead to unnecessary computations (if something later in the draw cycle changes the layout), you should generally avoid calling .layoutIfNeeded() unless you really need it. But it's fully supported if you do.

There is also .setNeedsLayout(), which tells the system that a view needs layout during the next draw cycle. You should use this if something changes layout in a way that the system won't notice. You generally don't need this if your changes are through UIKit itself. UIStackView knows that it needs layout after you call .addArrangedSubview. But if you change some piece of data that your layout relies on, you may need to tell UIKit.


问:
Name a service in docker compose to be used as a hostname
I want to spin up a database container (e.g: MongoDb) with docker-compose so that I can run some tests against the database.

This is my mongodb.yml docker-compose file.

```<code>version: '3.7'
services:
    mongo:
        image: mongo:latest
        restart: always
        ports:
            - 27017:27017
        environment:
            - MONGO_INITDB_ROOT_USERNAME=root
            - MONGO_INITDB_ROOT_PASSWORD=example

    mongo-express:
        image: mongo-express:latest
        restart: always
        ports:
            - 8081:8081
        environment:
            - ME_CONFIG_MONGODB_ADMINUSERNAME=root
            - ME_CONFIG_MONGODB_ADMINPASSWORD=example
        depends_on:
            - mongo
</code>```

When I run it with docker-compose -f mongodb.yml up I can successfully connect to MongoDb on localhost. In other words, the following connection string is valid: "mongodb://root:example@localhost:27017/admin?ssl=false"

I want to use the equivalent to alias so that instead localhost, MongoDb is accessible through hostname potato

In GitLab CI/CD, with a Docker runner, I can spin up a mongo container and provide an alias without any issue. Like this:

```<code>my_ci_cd_job:
  stage: my_stage
  services:
    - name: mongo:latest
      alias: potato
  variables:
    MONGO_INITDB_ROOT_USERNAME: root
    MONGO_INITDB_ROOT_PASSWORD: example
</code>```

This allows me to connect within the GitLab CI/CD with "mongodb://root:example@potato:27017/admin?ssl=false"

I need the same locally, so that I can reuse my connection string.

I've added under image: mongo:latest the following

```<code>container_name: potato
</code>```

But I cannot connect to the server potato. I've tried a few combinations with network, alias, etc. No luck. I don't event understand what I am doing anymore. Isn't there a simple equivalent to give an alias to a container so that my C# app or MongoDb client can access it?

Even the documentation, at the section https://docs.docker.com/compose/compose-file/#external_links is useless in my opinion. It mentions random samples not defined elsewhere.

Any help is much appreciated!

I've tried..

I've tried the following: How do I set hostname in docker-compose? without success

I have spent a few hours reading the docker compose documentation and it's extremly confusing. The fact that most of the questions are out of context without specific examples, does not help either, because it requires some deeper knowledge.

SOLUTION
Thanks to the replies it's clear this is a hacky thing not really recommended.

I went with the recommendations and I have now the connection string as:

```<code>mongodb://root:example@potato:27017/admin?ssl=false
</code>```

by default. That way, I don't need to change anything for my GitLab CI/CD pipeline that has the alias potato for mongo db.

When running locally the mongoDb container with docker compose, it does so in localhost, but I edited my hosts file (e.g: in Windows C:\Windows\System32\drivers\etc, in Linux /etc/hosts) to make any request to potato go to localhost or 127.0.0.1

```<code>127.0.0.1  potato
</code>```

And that way I can connect to MongoDb from my code or Robo3T as if it was running on a host called potato.

Feel free to comment any better alternative if there is. Ta.

答:
If I understand you correctly, you want to bind a hostname (e.g., potato) to an ip address on your host machine.

Afaik this is not possible, but there are workarounds[1].

Everytime you start your docker-compose a network is used between those containers, and there is no way for you to be sure which ip addresses they will get. These could be 172.17.0.0/24 or 172.14.0.0/24 or anything else really.

The only thing you know for sure is that your host will have a service running at port 27017. So you could say that the hostname potato points to localhost on your hostmachine by adding 127.0.0.1 potato to your /etc/hosts file on your host.

That way the connection string "mongodb://root:example@localhost:27017/admin?ssl=false" will point to the local port from the perspective of your host machine, while it will point to the docker container from the perspective of the rest of your docker-compose services.

I do have to say that I find this a hacky approach, and as @DavidMaze said, it's normal to need different connection strings depending on the context you use them in.

[1] https://github.com/dlemphers/docker-local-hosts

Body:
I want to spin up a database container (e.g: MongoDb) with docker-compose so that I can run some tests against the database.

This is my mongodb.yml docker-compose file.

version: '3.7'
services:
    mongo:
        image: mongo:latest
        restart: always
        ports:
            - 27017:27017
        environment:
            - MONGO_INITDB_ROOT_USERNAME=root
            - MONGO_INITDB_ROOT_PASSWORD=example

    mongo-express:
        image: mongo-express:latest
        restart: always
        ports:
            - 8081:8081
        environment:
            - ME_CONFIG_MONGODB_ADMINUSERNAME=root
            - ME_CONFIG_MONGODB_ADMINPASSWORD=example
        depends_on:
            - mongo

When I run it with docker-compose -f mongodb.yml up I can successfully connect to MongoDb on localhost. In other words, the following connection string is valid: "mongodb://root:example@localhost:27017/admin?ssl=false"

I want to use the equivalent to alias so that instead localhost, MongoDb is accessible through hostname potato

In GitLab CI/CD, with a Docker runner, I can spin up a mongo container and provide an alias without any issue. Like this:

my_ci_cd_job:
  stage: my_stage
  services:
    - name: mongo:latest
      alias: potato
  variables:
    MONGO_INITDB_ROOT_USERNAME: root
    MONGO_INITDB_ROOT_PASSWORD: example

This allows me to connect within the GitLab CI/CD with "mongodb://root:example@potato:27017/admin?ssl=false"

I need the same locally, so that I can reuse my connection string.

I've added under image: mongo:latest the following

container_name: potato

But I cannot connect to the server potato. I've tried a few combinations with network, alias, etc. No luck. I don't event understand what I am doing anymore. Isn't there a simple equivalent to give an alias to a container so that my C# app or MongoDb client can access it?

Even the documentation, at the section https://docs.docker.com/compose/compose-file/#external_links is useless in my opinion. It mentions random samples not defined elsewhere.

Any help is much appreciated!

I've tried..

I've tried the following: How do I set hostname in docker-compose? without success

I have spent a few hours reading the docker compose documentation and it's extremly confusing. The fact that most of the questions are out of context without specific examples, does not help either, because it requires some deeper knowledge.

SOLUTION
Thanks to the replies it's clear this is a hacky thing not really recommended.

I went with the recommendations and I have now the connection string as:

mongodb://root:example@potato:27017/admin?ssl=false

by default. That way, I don't need to change anything for my GitLab CI/CD pipeline that has the alias potato for mongo db.

When running locally the mongoDb container with docker compose, it does so in localhost, but I edited my hosts file (e.g: in Windows C:\Windows\System32\drivers\etc, in Linux /etc/hosts) to make any request to potato go to localhost or 127.0.0.1

127.0.0.1  potato

And that way I can connect to MongoDb from my code or Robo3T as if it was running on a host called potato.

Feel free to comment any better alternative if there is. Ta.


问:
Hadoop Pig Latin always fails to Load Data
I'm making my first steps in Hadoop's Pig Latin,but I'm really blocked since i can't load any input data even if it exists

```<code>R = LOAD '/home/cloudera/Desktop/vol.csv' USING PigStorage(';')
AS
(AnneeVol:int,MoisVol:int,JourVol:int,NumVol:int,AeroDep:chararray,AeroArriv:chararray,DistVol:int);
</code>```

File Location

upon running :

```<code>DUMP R;
</code>```

I get this error

```<code>
> Failed Jobs:
JobId   Alias   Feature Message Outputs
job_1590934825774_0010  R   MAP_ONLY    Message: org.apache.pig.backend.executionengine.ExecException: ERROR 2118: Input path does not exist: hdfs://quickstart.cloudera:8020/home/cloudera/pig_lab/input/vol.csv
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:288)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:305)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:322)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:200)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1307)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1304)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1917)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1304)
    at org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob.submit(ControlledJob.java:335)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.pig.backend.hadoop23.PigJobControl.submit(PigJobControl.java:128)
    at org.apache.pig.backend.hadoop23.PigJobControl.run(PigJobControl.java:191)
    at java.lang.Thread.run(Thread.java:745)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher$1.run(MapReduceLauncher.java:270)
Caused by: org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://quickstart.cloudera:8020/home/cloudera/pig_lab/input/vol.csv
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:323)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:265)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigTextInputFormat.listStatus(PigTextInputFormat.java:36)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.getSplits(FileInputFormat.java:387)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:274)
    ... 18 more
    hdfs://quickstart.cloudera:8020/tmp/temp14790577/tmp132115611,

Input(s): Failed to read data from "/home/cloudera/pig_lab/input/vol.csv"

Output(s): Failed to produce result in "hdfs://quickstart.cloudera:8020/tmp/temp14790577/tmp132115611"

</code>```

How do I fix this issue ?
Thank you !

答:
The program try to find the vol.csv in the HDFS not on your local file system

Input path does not exist: hdfs://quickstart.cloudera:8020/home/cloudera/pig_lab/input/vol.csv

Please check core-site.xml for your default fileSystem. Currently it would have value hdfs://quickstart.cloudera:8020. Thats why it searches the file HDFS. You DON'T have to change anything there.

Just add file:// tag before the path to tell the program to find the vol.csv from your local fileSystem.

```<code>R = LOAD 'file:///home/cloudera/Desktop/vol.csv' USING PigStorage(';')  AS (AnneeVol:int,MoisVol:int,JourVol:int,NumVol:int,AeroDep:chararray,AeroArriv:chararray,DistVol:int);
</code>```

Ref: Cloudera blog

If that doesn’t help either put the file in HDFS and then refer that location in your code.

hdfs dfs -put /home/cloudera/Desktop/vol.csv hdfs://quickstart.cloudera:8020/user/<hdfs-user>/
```

<p>Then in your code</p>

```R = LOAD '/user/<hdfs-user>/vol.csv' USING PigStorage(';')  AS (AnneeVol:int,MoisVol:int,JourVol:int,NumVol:int,AeroDep:chararray,AeroArriv:chararray,DistVol:int);
```

Body:
I'm making my first steps in Hadoop's Pig Latin,but I'm really blocked since i can't load any input data even if it exists

R = LOAD '/home/cloudera/Desktop/vol.csv' USING PigStorage(';')
AS
(AnneeVol:int,MoisVol:int,JourVol:int,NumVol:int,AeroDep:chararray,AeroArriv:chararray,DistVol:int);

File Location

upon running :

DUMP R;

I get this error

> Failed Jobs:
JobId   Alias   Feature Message Outputs
job_1590934825774_0010  R   MAP_ONLY    Message: org.apache.pig.backend.executionengine.ExecException: ERROR 2118: Input path does not exist: hdfs://quickstart.cloudera:8020/home/cloudera/pig_lab/input/vol.csv
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:288)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:305)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:322)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:200)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1307)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1304)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1917)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1304)
    at org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob.submit(ControlledJob.java:335)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.pig.backend.hadoop23.PigJobControl.submit(PigJobControl.java:128)
    at org.apache.pig.backend.hadoop23.PigJobControl.run(PigJobControl.java:191)
    at java.lang.Thread.run(Thread.java:745)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher$1.run(MapReduceLauncher.java:270)
Caused by: org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://quickstart.cloudera:8020/home/cloudera/pig_lab/input/vol.csv
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:323)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:265)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigTextInputFormat.listStatus(PigTextInputFormat.java:36)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.getSplits(FileInputFormat.java:387)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:274)
    ... 18 more
    hdfs://quickstart.cloudera:8020/tmp/temp14790577/tmp132115611,

Input(s): Failed to read data from "/home/cloudera/pig_lab/input/vol.csv"

Output(s): Failed to produce result in "hdfs://quickstart.cloudera:8020/tmp/temp14790577/tmp132115611"

How do I fix this issue ?
Thank you !

Body:
The program try to find the vol.csv in the HDFS not on your local file system

Input path does not exist: hdfs://quickstart.cloudera:8020/home/cloudera/pig_lab/input/vol.csv

Please check core-site.xml for your default fileSystem. Currently it would have value hdfs://quickstart.cloudera:8020. Thats why it searches the file HDFS. You DON'T have to change anything there.

Just add file:// tag before the path to tell the program to find the vol.csv from your local fileSystem.

R = LOAD 'file:///home/cloudera/Desktop/vol.csv' USING PigStorage(';')  AS (AnneeVol:int,MoisVol:int,JourVol:int,NumVol:int,AeroDep:chararray,AeroArriv:chararray,DistVol:int);

Ref: Cloudera blog

If that doesn’t help either put the file in HDFS and then refer that location in your code.

hdfs dfs -put /home/cloudera/Desktop/vol.csv hdfs://quickstart.cloudera:8020/user/<hdfs-user>/

Then in your code

R = LOAD '/user/<hdfs-user>/vol.csv' USING PigStorage(';')  AS (AnneeVol:int,MoisVol:int,JourVol:int,NumVol:int,AeroDep:chararray,AeroArriv:chararray,DistVol:int);


问:
how to get html content of <li> among the ajax <li> items
using ajax i am returning set of list items all with different ids . i want to get the html content of one particular list item . i even have the id . but i couldnt get the html content with this</p>

```<code>var li_element = $(req_id).html();
$('.selected_res_cls').append(li_element);
</code>```

答:
Try this

var li_element = $("#"+req_id).text();

$('.selected_res_cls').append(li_element);

Body:
using ajax i am returning set of list items all with different ids . i want to get the html content of one particular list item . i even have the id . but i couldnt get the html content with this

var li_element = $(req_id).html();
$('.selected_res_cls').append(li_element);


问:
How to coordinate bash profile with zsh
I recently switched my shell from bash to zsh. I had set up Anaconda via bash, but now that I'm running zsh as my default shell, I can't find conda or, more importantly, Jupyter. I've figured that to get access to Jupyter I can use exec bash -l, but that seems pointlessly temporary. I would rather access Jupyter locally from zsh. Is there some way to link zsh back to the bash configs?

答:
Since zsh can interpret most of bash, you can have it include the bash init files in its corresponding init files.

To do this, add e.g. the line source ~/.bashrc in ~/.zshrc

Each shell has many different config files and they don't correspond 1:1, so look through and see which ones you want to link. For example, zsh login shells reads both .zlogin and .zprofile, while bash login shells read only the first available of .bash_profile, .bash_login and .profile

Title: How to coordinate bash profile with zsh


问:
How do I go to a file in vim/nerdtree?
I'm trying to transition to vim, but I'm having a hard time mapping over some functionalities in pycharm over to vim.

The first being how do I directly go to a filepath. In pycharm, I believe it is cmd-shift P. You'll type the file-path and it'll take you there. I think there's auto-complete too?

Like -- I know that there's a .css file I want to access. So I'd instinctively start typing: cmd shift p .css and this would return the .css files.

How do I do that in vim?

Thanks!

答:
:edit is the most basic command for editing an existing file.

```<code>:edit <your file name>
</code>```

To get a list of all the files ending in ".css" use :edit e *.css and then press Ctrl+d. See :help c_CTRL-D in Vim for more information.

:find <file> is a more powerful version of :edit. It searches for <file> from the directories listed in your path option. For example, if your current directory is project and the value of the path contains
/path/to/project/**, then :find file.css will search all the subdirectories of project for the "file.css".

There is also a plugin called "ctrlp.vim" that should be similar to what you used in pycharm.

For more information about file navigation, I highly recommend reading "Death by a thousand files", an excellent article by Romain Lafourcade.

Title: How do I go to a file in vim/nerdtree?

Body:
:edit is the most basic command for editing an existing file.

:edit <your file name>

To get a list of all the files ending in ".css" use :edit e *.css and then press Ctrl+d. See :help c_CTRL-D in Vim for more information.

:find <file> is a more powerful version of :edit. It searches for <file> from the directories listed in your path option. For example, if your current directory is project and the value of the path contains
/path/to/project/**, then :find file.css will search all the subdirectories of project for the "file.css".

There is also a plugin called "ctrlp.vim" that should be similar to what you used in pycharm.

For more information about file navigation, I highly recommend reading "Death by a thousand files", an excellent article by Romain Lafourcade.


问:
skip rows until certain 'value' is found - bulk CSV upload, inconsistent pattern of row numbers
I am trying to bulk load and merge two dozen CSV files in R. I am adding a column to my data frame to identify each file by its file name in a column called 'file_name'.

Each file has a number of rows on top that are superfluous. Originally I thought it was a consistent pattern of 16 rows. I leveraged the 'skiprow' command within the read_csv function to address that issue.

However, after closer inspection I discovered that the pattern of 16 rows is inconsistent from file to file. The only consistent pattern I found was that all the 'good data' in each file comes right after a line that says "Attendee Details"

I am trying to figure out a way to skip all the rows before and including the row containing the text "Attendee Details".

Here is my code so far:

```<code>list_of_files <- list.files(pattern='*.csv')

df <- list_of_files %>%
  setNames(nm = .) %>%
  map_df(~read_csv(.x, col_types = cols(), col_names = FALSE), .id = "file_name")
</code>```

Here is what my data looks like:

Here is what I am hoping to load for each file while also skipping over that header row:

I already tried to redesign/configure the code snippets I found in this thread - unfortunately I hit errors and am a bit stuck on where to go from here.

Skip over all lines in a data file before and including a regular string in a loop in R

```<code>for (x in list.files(pattern="*.csv", recursive=TRUE)) {
   all_content <- readLines(x)
   skip = all_content[-c(1:grep("Attendee Details",all_content))]
   input <- read.table(textConnection(skip))
   df <- rbind(df, input)
}

Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec, : line 1 did not have 13 elements
</code>```

Any pointers? Also, I know it is preferred to post a reproducible example here - I couldn't quite figure out how to do that either.

答:
1) As a pointer:

did you initialize df, as in the example? (cbind expects same number of columns, which you apparently do not have here)

are there files without data after the header string? (you might want to exclude those before performing cbind, so maybe read them into a list first)

do the files have varying number of columns after the header string? (same idea as before, either exclude those or use fill = TRUE)

Here is one possible solution with data.table, that also illustrates a reproducible example (but may not consider specifics of you files, obviously):

library(data.table)

makeHeader <- function(x){
    fn <- paste0("myfile_", sprintf("%02d", x), ".csv")
    cat("Attendee report\n", file=fn, append = FALSE)
    cat("Report Generated,01/01/2020\n", file=fn, append = TRUE)
    cat("Topic,topic ", x, "\n", file=fn, append = TRUE)
    cat("Attendee Details\n", file=fn, append = TRUE)
}

# generate files:
set.seed(1)
bigdt <- data.table(col1 = sample(1:12, 1.2e4, replace = TRUE),
                    col2 = sample(LETTERS[1:26], 1.2e4, replace = TRUE),
                    col3 = sample(20:50, 1.2e4, replace = TRUE))
biglist <- split(bigdt, ceiling(seq_len(dim(bigdt)[1])/1e3))
rm(bigdt)
invisible(lapply(seq_along(biglist), makeHeader))
invisible(lapply(seq_along(biglist),
    function(x) fwrite(biglist[[x]],
        file=paste0("myfile_", sprintf("%02d", x), ".csv"), append=TRUE, col.names = TRUE)))

# read files and combine; add column for file name
files <- list.files(pattern="myfile_.*.csv")
DT <- lapply(files, function(x) fread(x, skip="Attendee Details", sep=","))
names(DT) <- files
rbindlist(DT, idcol = "file", fill=TRUE)
#>                 file col1 col2 col3
#>     1: myfile_01.csv    9    N   48
#>     2: myfile_01.csv    4    V   33
#>     3: myfile_01.csv    7    X   22
#>     4: myfile_01.csv    1    W   49
#>     5: myfile_01.csv    2    X   34
#>    ---
#> 11996: myfile_12.csv   10    S   29
#> 11997: myfile_12.csv    5    T   25
#> 11998: myfile_12.csv    8    B   34
#> 11999: myfile_12.csv   11    P   43
#> 12000: myfile_12.csv    1    O   37
```

Created on 2020-05-31 by the reprex package (v0.3.0)

Body:
I am trying to bulk load and merge two dozen CSV files in R. I am adding a column to my data frame to identify each file by its file name in a column called 'file_name'.

Each file has a number of rows on top that are superfluous. Originally I thought it was a consistent pattern of 16 rows. I leveraged the 'skiprow' command within the read_csv function to address that issue.

However, after closer inspection I discovered that the pattern of 16 rows is inconsistent from file to file. The only consistent pattern I found was that all the 'good data' in each file comes right after a line that says "Attendee Details"

I am trying to figure out a way to skip all the rows before and including the row containing the text "Attendee Details".

Here is my code so far:

list_of_files <- list.files(pattern='*.csv')

df <- list_of_files %>%
  setNames(nm = .) %>%
  map_df(~read_csv(.x, col_types = cols(), col_names = FALSE), .id = "file_name")

Here is what my data looks like:

Here is what I am hoping to load for each file while also skipping over that header row:

I already tried to redesign/configure the code snippets I found in this thread - unfortunately I hit errors and am a bit stuck on where to go from here.

Skip over all lines in a data file before and including a regular string in a loop in R

for (x in list.files(pattern="*.csv", recursive=TRUE)) {
   all_content <- readLines(x)
   skip = all_content[-c(1:grep("Attendee Details",all_content))]
   input <- read.table(textConnection(skip))
   df <- rbind(df, input)
}

Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec, : line 1 did not have 13 elements

Any pointers? Also, I know it is preferred to post a reproducible example here - I couldn't quite figure out how to do that either.

Body:
1) As a pointer:

did you initialize df, as in the example? (cbind expects same number of columns, which you apparently do not have here)

are there files without data after the header string? (you might want to exclude those before performing cbind, so maybe read them into a list first)

do the files have varying number of columns after the header string? (same idea as before, either exclude those or use fill = TRUE)

Here is one possible solution with data.table, that also illustrates a reproducible example (but may not consider specifics of you files, obviously):

library(data.table)

makeHeader <- function(x){
    fn <- paste0("myfile_", sprintf("%02d", x), ".csv")
    cat("Attendee report\n", file=fn, append = FALSE)
    cat("Report Generated,01/01/2020\n", file=fn, append = TRUE)
    cat("Topic,topic ", x, "\n", file=fn, append = TRUE)
    cat("Attendee Details\n", file=fn, append = TRUE)
}

# generate files:
set.seed(1)
bigdt <- data.table(col1 = sample(1:12, 1.2e4, replace = TRUE),
                    col2 = sample(LETTERS[1:26], 1.2e4, replace = TRUE),
                    col3 = sample(20:50, 1.2e4, replace = TRUE))
biglist <- split(bigdt, ceiling(seq_len(dim(bigdt)[1])/1e3))
rm(bigdt)
invisible(lapply(seq_along(biglist), makeHeader))
invisible(lapply(seq_along(biglist),
    function(x) fwrite(biglist[[x]],
        file=paste0("myfile_", sprintf("%02d", x), ".csv"), append=TRUE, col.names = TRUE)))

# read files and combine; add column for file name
files <- list.files(pattern="myfile_.*.csv")
DT <- lapply(files, function(x) fread(x, skip="Attendee Details", sep=","))
names(DT) <- files
rbindlist(DT, idcol = "file", fill=TRUE)
#>                 file col1 col2 col3
#>     1: myfile_01.csv    9    N   48
#>     2: myfile_01.csv    4    V   33
#>     3: myfile_01.csv    7    X   22
#>     4: myfile_01.csv    1    W   49
#>     5: myfile_01.csv    2    X   34
#>    ---
#> 11996: myfile_12.csv   10    S   29
#> 11997: myfile_12.csv    5    T   25
#> 11998: myfile_12.csv    8    B   34
#> 11999: myfile_12.csv   11    P   43
#> 12000: myfile_12.csv    1    O   37

Created on 2020-05-31 by the reprex package (v0.3.0)


问:
How to convert Avro Schema object into StructType in spark
I have an RDD of type Row i.e, RDD[Row] and avro schema object .I need to create a dataframe with this info.

I need toconvert avro schema object into StructType for creating DataFrame.

Can you please help .

答:
Updated as of 2020-05-31

Use below if you're on scala 2.12 with a newer spark version.

sbt:

```<code>scalaVersion := "2.12.11"
val sparkVersion = "2.4.5"
libraryDependencies += "org.apache.spark" %% "spark-avro" % sparkVersion
</code>```
```<code>import org.apache.spark.sql.avro.SchemaConverters
import org.apache.spark.sql.types.StructType

val schemaType = SchemaConverters
  .toSqlType(avroSchema)
  .dataType
  .asInstanceOf[StructType]
</code>```

Body:
Updated as of 2020-05-31

Use below if you're on scala 2.12 with a newer spark version.

sbt:

scalaVersion := "2.12.11"
val sparkVersion = "2.4.5"
libraryDependencies += "org.apache.spark" %% "spark-avro" % sparkVersion

import org.apache.spark.sql.avro.SchemaConverters
import org.apache.spark.sql.types.StructType

val schemaType = SchemaConverters
  .toSqlType(avroSchema)
  .dataType
  .asInstanceOf[StructType]


问:
Get the file name of a Qt label image
I am using Qt creator for a c++ gui. I am making a blackjack game. I wanted to be able to change a label to the backside of the card (call it "backside.png"), to the frontside of the card (call it "frontside.png").

When the person clicks on one of the standard buttons, I want to check if the image on the label(call it "cardlabel") is displaying the backside of the card, or the frontside of the card.

If it is showing the backside, then I will change the label to show the frontside of the card, and vice versa.

Is there anyway someone is able to show me (through code), how I can ask "cardlabel", for what image name it is currently using and check to see which side it is currently on. This would be a tremendous help for my project. Thanks!!

答:
I know this thread is old but I can suggest you to "carry" within each object a variable that contains the value of the pixmap so you can read/change it before affecting it to the setPixmap.

My code is in Python but you can translate :)

```<code>self.ui.qlabel.img = "img/light_red.png"
if someRandomCondition:
      self.ui.qlabel.lum = "img/light_green.png"
else:
      self.ui.qlabel.lum = "img/light_red.png"
self.ui.qlabel.setPixmap(QPixmap(self.ui.qlabel.lum))
print(self.ui.qlabel.lum)
</code>```

Title: Get the file name of a Qt label image

Body:
I know this thread is old but I can suggest you to "carry" within each object a variable that contains the value of the pixmap so you can read/change it before affecting it to the setPixmap.

My code is in Python but you can translate :)

self.ui.qlabel.img = "img/light_red.png"
if someRandomCondition:
      self.ui.qlabel.lum = "img/light_green.png"
else:
      self.ui.qlabel.lum = "img/light_red.png"
self.ui.qlabel.setPixmap(QPixmap(self.ui.qlabel.lum))
print(self.ui.qlabel.lum)


问:
How and where does SSL signing apply to emails?
I am trying to find out how SSL signing of emails work and if it gets signed server side or MTA side? I know this is a bit vague maybe but any resources to read or documentation would help a lot :D

Like for example I use a ezComponents mail object to send a mail object to the MTA server. DO I have to sign the mail object inside of PHP by using something

OR

Does the signing happen on the sending server (MTA)?

Just to add some clarity, I would like to use this functionality to send secure emails to customers for their monthly statements and reports. But implementation is irrelevant at this stage, I am interested in docs and resources and wisdom from people that knows :D

EDIT: Okay so I am using S/MIME. does anybody have an idea how to do this? I can't find any good PHP examples.

答:
SSL is a transport protocol, and there's no such thing as "SSL signing of e-mails". This is why you can't find anything.

Signing of e-mail is done using S/MIME standard. Signing is performed by the sender application using sender's X.509 certificate with a corresponding private key. IF the SMTP server has all certificates with keys, it can sign e-mail on behalf of the sender. This is sometimes used in corporate environments.


问:
How to add dots (ellipses) to LabelView as in the table of contents of a book
I have stackView which contains few labelViews in each of which two words are written. And I want them to be separated by an ellipsis across the entire width of labelView. As a result: one word close to the left, another - to the right, and dots between them. Note: the label can take up several lines if the words length is long.

EDIT

Here filling my stackView

```<code>for ingredient in ingredients {
    let textLabel = UILabel()
    textLabel.backgroundColor = UIColor.yellow // just for my needs
    textLabel.widthAnchor.constraint(equalToConstant: ingredientsStackView.frame.width).isActive = true
    textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
    textLabel.text = ingredient.getName() + " " + String(ingredient.getAmount()) + " " + ingredient.getMeasure()
    textLabel.textAlignment = .left
    textLabel.numberOfLines = 0
    textLabel.lineBreakMode = .byWordWrapping
    ingredientsStackView.addArrangedSubview(textLabel)
}
ingredientsStackView.translatesAutoresizingMaskIntoConstraints = false
</code>```

and that looks like this

But I want something like this

You can see dots between ingredientName and ingredientAmount.

I had an idea to implement this through CGFloat conversion here, but this question was closed.

答:
One technique is to use size() or boundingRect(with:options:context:) to calculate the size, repeating that for more and more series of dots, until you reach the desired width.

But that ignores a subtle (but IMHO, important) aspect, namely that the dots from all the rows should all line up perfectly. If they don’t line up, it can be surprisingly distracting.

So, I’d be inclined to define a view that does that, performing a modulus calculation against some common ancestor view coordinate system. And, I’d personally just render the dots as UIBezierPath.

For example:

```<code>class EllipsesView: UIView {
    let spacing: CGFloat = 3
    let radius: CGFloat = 1.5

    var color: UIColor {
        UIColor { traitCollection in
            switch traitCollection.userInterfaceStyle {
            case .dark: return .white
            default:    return .black
            }
        }
    }

    let shapeLayer: CAShapeLayer = {
        let layer = CAShapeLayer()
        layer.strokeColor = UIColor.clear.cgColor
        return layer
    }()

    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        configure()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        configure()
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        shapeLayer.fillColor = color.cgColor

        let point = convert(bounds.origin, to: window)

        let diff = radius * 3 + spacing
        let offset = diff - point.x.truncatingRemainder(dividingBy: diff)

        let rect = CGRect(x: bounds.minX + offset, y: bounds.maxY - radius * 2, width: bounds.width - offset, height: radius * 2)

        let path = UIBezierPath()

        var center = CGPoint(x: rect.minX + radius, y: rect.midY)

        while center.x + radius < rect.maxX {
            path.addArc(withCenter: center, radius: radius, startAngle: 0, endAngle: 2 * .pi, clockwise: true)
            center.x += diff
        }

        shapeLayer.path = path.cgPath
    }
}

private extension EllipsesView {
    func configure() {
        layer.addSublayer(shapeLayer)
    }
}
</code>```

Then you can add your two labels, lining up the bottom of the ellipses view with the bottom baseline of the labels:

```<code>let stringPairs = [("foo", "$1.37"), ("foobar", "$0.42"), ("foobarbaz", "$10.00"), ("foobarbazqux", "$100.00")]
for stringPair in stringPairs {
    let container = UIView()
    container.translatesAutoresizingMaskIntoConstraints = false

    let leftLabel = UILabel()
    leftLabel.translatesAutoresizingMaskIntoConstraints = false
    leftLabel.text = stringPair.0
    leftLabel.setContentHuggingPriority(.required, for: .horizontal)
    container.addSubview(leftLabel)

    let ellipsesView = EllipsesView()
    ellipsesView.translatesAutoresizingMaskIntoConstraints = false
    container.addSubview(ellipsesView)

    let rightLabel = UILabel()
    rightLabel.translatesAutoresizingMaskIntoConstraints = false
    rightLabel.font = UIFont.monospacedDigitSystemFont(ofSize: rightLabel.font.pointSize, weight: .regular)
    rightLabel.text = stringPair.1
    rightLabel.setContentHuggingPriority(.required, for: .horizontal)
    container.addSubview(rightLabel)

    NSLayoutConstraint.activate([
        // horizontal constraints

        leftLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor),
        ellipsesView.leadingAnchor.constraint(equalTo: leftLabel.trailingAnchor, constant: 3),
        rightLabel.leadingAnchor.constraint(equalTo: ellipsesView.trailingAnchor, constant: 3),
        rightLabel.trailingAnchor.constraint(equalTo: container.trailingAnchor),

        // align last baseline of three subviews

        leftLabel.lastBaselineAnchor.constraint(equalTo: ellipsesView.bottomAnchor),
        leftLabel.lastBaselineAnchor.constraint(equalTo: rightLabel.lastBaselineAnchor),

        // vertical constraints to container

        leftLabel.topAnchor.constraint(greaterThanOrEqualTo: container.topAnchor),
        rightLabel.topAnchor.constraint(greaterThanOrEqualTo: container.topAnchor),
        ellipsesView.topAnchor.constraint(equalTo: container.topAnchor),
        leftLabel.bottomAnchor.constraint(equalTo: container.bottomAnchor),
    ])

    verticalStackView.addArrangedSubview(container)
}
</code>```

That yields the ellipses, but they all line up perfectly, too:

Body:
I have stackView which contains few labelViews in each of which two words are written. And I want them to be separated by an ellipsis across the entire width of labelView. As a result: one word close to the left, another - to the right, and dots between them. Note: the label can take up several lines if the words length is long.

EDIT

Here filling my stackView

for ingredient in ingredients {
    let textLabel = UILabel()
    textLabel.backgroundColor = UIColor.yellow // just for my needs
    textLabel.widthAnchor.constraint(equalToConstant: ingredientsStackView.frame.width).isActive = true
    textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
    textLabel.text = ingredient.getName() + " " + String(ingredient.getAmount()) + " " + ingredient.getMeasure()
    textLabel.textAlignment = .left
    textLabel.numberOfLines = 0
    textLabel.lineBreakMode = .byWordWrapping
    ingredientsStackView.addArrangedSubview(textLabel)
}
ingredientsStackView.translatesAutoresizingMaskIntoConstraints = false

and that looks like this

But I want something like this

You can see dots between ingredientName and ingredientAmount.

I had an idea to implement this through CGFloat conversion here, but this question was closed.

Body:
One technique is to use size() or boundingRect(with:options:context:) to calculate the size, repeating that for more and more series of dots, until you reach the desired width.

But that ignores a subtle (but IMHO, important) aspect, namely that the dots from all the rows should all line up perfectly. If they don’t line up, it can be surprisingly distracting.

So, I’d be inclined to define a view that does that, performing a modulus calculation against some common ancestor view coordinate system. And, I’d personally just render the dots as UIBezierPath.

For example:

class EllipsesView: UIView {
    let spacing: CGFloat = 3
    let radius: CGFloat = 1.5

    var color: UIColor {
        UIColor { traitCollection in
            switch traitCollection.userInterfaceStyle {
            case .dark: return .white
            default:    return .black
            }
        }
    }

    let shapeLayer: CAShapeLayer = {
        let layer = CAShapeLayer()
        layer.strokeColor = UIColor.clear.cgColor
        return layer
    }()

    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        configure()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        configure()
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        shapeLayer.fillColor = color.cgColor

        let point = convert(bounds.origin, to: window)

        let diff = radius * 3 + spacing
        let offset = diff - point.x.truncatingRemainder(dividingBy: diff)

        let rect = CGRect(x: bounds.minX + offset, y: bounds.maxY - radius * 2, width: bounds.width - offset, height: radius * 2)

        let path = UIBezierPath()

        var center = CGPoint(x: rect.minX + radius, y: rect.midY)

        while center.x + radius < rect.maxX {
            path.addArc(withCenter: center, radius: radius, startAngle: 0, endAngle: 2 * .pi, clockwise: true)
            center.x += diff
        }

        shapeLayer.path = path.cgPath
    }
}

private extension EllipsesView {
    func configure() {
        layer.addSublayer(shapeLayer)
    }
}

Then you can add your two labels, lining up the bottom of the ellipses view with the bottom baseline of the labels:

let stringPairs = [("foo", "$1.37"), ("foobar", "$0.42"), ("foobarbaz", "$10.00"), ("foobarbazqux", "$100.00")]
for stringPair in stringPairs {
    let container = UIView()
    container.translatesAutoresizingMaskIntoConstraints = false

    let leftLabel = UILabel()
    leftLabel.translatesAutoresizingMaskIntoConstraints = false
    leftLabel.text = stringPair.0
    leftLabel.setContentHuggingPriority(.required, for: .horizontal)
    container.addSubview(leftLabel)

    let ellipsesView = EllipsesView()
    ellipsesView.translatesAutoresizingMaskIntoConstraints = false
    container.addSubview(ellipsesView)

    let rightLabel = UILabel()
    rightLabel.translatesAutoresizingMaskIntoConstraints = false
    rightLabel.font = UIFont.monospacedDigitSystemFont(ofSize: rightLabel.font.pointSize, weight: .regular)
    rightLabel.text = stringPair.1
    rightLabel.setContentHuggingPriority(.required, for: .horizontal)
    container.addSubview(rightLabel)

    NSLayoutConstraint.activate([
        // horizontal constraints

        leftLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor),
        ellipsesView.leadingAnchor.constraint(equalTo: leftLabel.trailingAnchor, constant: 3),
        rightLabel.leadingAnchor.constraint(equalTo: ellipsesView.trailingAnchor, constant: 3),
        rightLabel.trailingAnchor.constraint(equalTo: container.trailingAnchor),

        // align last baseline of three subviews

        leftLabel.lastBaselineAnchor.constraint(equalTo: ellipsesView.bottomAnchor),
        leftLabel.lastBaselineAnchor.constraint(equalTo: rightLabel.lastBaselineAnchor),

        // vertical constraints to container

        leftLabel.topAnchor.constraint(greaterThanOrEqualTo: container.topAnchor),
        rightLabel.topAnchor.constraint(greaterThanOrEqualTo: container.topAnchor),
        ellipsesView.topAnchor.constraint(equalTo: container.topAnchor),
        leftLabel.bottomAnchor.constraint(equalTo: container.bottomAnchor),
    ])

    verticalStackView.addArrangedSubview(container)
}

That yields the ellipses, but they all line up perfectly, too: