问:
Permutation of an array of strings
I am solving this challenge :
https://www.hackerrank.com/challenges/permutations-of-strings/problem

I am using this algorithm :
https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order

Suppose I enter my array of strings as {"a", "b", "c"}, then the output should be :

```<code>a b c
a c b
b c a
c b a
b a c
c a b
</code>```

Since there are 3 distinct strings, there are 3! = 6 permutations.

The program is also supposed to handle duplicate cases, so if I enter {"a", "b", "b"}, there will only be 3! / 2! = 3 permutations.

Anyways when my program reaches c b a then it quits. Why? How can I fix that?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char** s1, char** s2) // to swap two strings
{
    char* temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}
int next_permutation(int n, char **s)
{
    /**
    * Complete this method
    * Return 0 when there is no next permutation and 1 otherwise
    * Modify array s to its next permutation
    */
    int k, i, l;
    k = i = l = 0;

    for(i = n - 2; i >= 0; i--) // first step
        if(strcmp(s[i], s[i + 1]) < 0) {
            k = i;
            break;
        }

    if(i == -1)
        return 0;

    for(i = n - 1; i >= k + 1; i--) // second step
        if(strcmp(s[k], s[i]) < 0) {
            l = i;
            break;
        }

    swap(&s[k], &s[l]); // third step

    for(i = k + 1; i < n / 2; i++) // fourth step
        swap(&s[i], &s[n - i - 1]);

    return 1;
}

int main() // locked code
{
    char **s;
    int n;
    scanf("%d", &n);
    s = calloc(n, sizeof(char*));
    for (int i = 0; i < n; i++)
    {
        s[i] = calloc(11, sizeof(char));
        scanf("%s", s[i]);
    }
    do
    {
        for (int i = 0; i < n; i++)
            printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
    } while (next_permutation(n, s));
    for (int i = 0; i < n; i++)
        free(s[i]);
    free(s);
    return 0;
}
</code>```

答:
This is the final code:</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char** s1, char** s2) // swaps two strings
{
    char* temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}
int next_permutation(int n, char **s) // function to complete
{
    int k, i, l;
    k = i = l = 0;

    for(i = n - 2; i >= 0; i--) // step 1
        if(strcmp(s[i], s[i + 1]) < 0) {
            k = i;
            break;
        }

    if(i == -1)
        return 0;

    for(i = n - 1; i >= k + 1; i--) // step 2
        if(strcmp(s[k], s[i]) < 0) {
            l = i;
            break;
        }

    swap(&s[k], &s[l]); // step 3

    int inner = k + 1 + n - 1; // step 4
    int cond = inner / 2;
    for(i = n - 1; i > cond; i--)
        swap(&s[i], &s[inner - i]);

    return 1;
}

int main() // locked code
{
    char **s;
    int n;
    scanf("%d", &n);
    s = calloc(n, sizeof(char*));
    for (int i = 0; i < n; i++)
    {
        s[i] = calloc(11, sizeof(char));
        scanf("%s", s[i]);
    }
    do
    {
        for (int i = 0; i < n; i++)
            printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
    } while (next_permutation(n, s));
    for (int i = 0; i < n; i++)
        free(s[i]);
    free(s);
    return 0;
}
</code>```

Title: Permutation of an array of strings

Body:
I am solving this challenge :
https://www.hackerrank.com/challenges/permutations-of-strings/problem

I am using this algorithm :
https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order

Suppose I enter my array of strings as {"a", "b", "c"}, then the output should be :

a b c
a c b
b c a
c b a
b a c
c a b

Since there are 3 distinct strings, there are 3! = 6 permutations.

The program is also supposed to handle duplicate cases, so if I enter {"a", "b", "b"}, there will only be 3! / 2! = 3 permutations.

Anyways when my program reaches c b a then it quits. Why? How can I fix that?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char** s1, char** s2) // to swap two strings
{
    char* temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}
int next_permutation(int n, char **s)
{
    /**
    * Complete this method
    * Return 0 when there is no next permutation and 1 otherwise
    * Modify array s to its next permutation
    */
    int k, i, l;
    k = i = l = 0;

    for(i = n - 2; i >= 0; i--) // first step
        if(strcmp(s[i], s[i + 1]) < 0) {
            k = i;
            break;
        }

    if(i == -1)
        return 0;

    for(i = n - 1; i >= k + 1; i--) // second step
        if(strcmp(s[k], s[i]) < 0) {
            l = i;
            break;
        }

    swap(&s[k], &s[l]); // third step

    for(i = k + 1; i < n / 2; i++) // fourth step
        swap(&s[i], &s[n - i - 1]);

    return 1;
}

int main() // locked code
{
    char **s;
    int n;
    scanf("%d", &n);
    s = calloc(n, sizeof(char*));
    for (int i = 0; i < n; i++)
    {
        s[i] = calloc(11, sizeof(char));
        scanf("%s", s[i]);
    }
    do
    {
        for (int i = 0; i < n; i++)
            printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
    } while (next_permutation(n, s));
    for (int i = 0; i < n; i++)
        free(s[i]);
    free(s);
    return 0;
}

Body:
This is the final code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char** s1, char** s2) // swaps two strings
{
    char* temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}
int next_permutation(int n, char **s) // function to complete
{
    int k, i, l;
    k = i = l = 0;

    for(i = n - 2; i >= 0; i--) // step 1
        if(strcmp(s[i], s[i + 1]) < 0) {
            k = i;
            break;
        }

    if(i == -1)
        return 0;

    for(i = n - 1; i >= k + 1; i--) // step 2
        if(strcmp(s[k], s[i]) < 0) {
            l = i;
            break;
        }

    swap(&s[k], &s[l]); // step 3

    int inner = k + 1 + n - 1; // step 4
    int cond = inner / 2;
    for(i = n - 1; i > cond; i--)
        swap(&s[i], &s[inner - i]);

    return 1;
}

int main() // locked code
{
    char **s;
    int n;
    scanf("%d", &n);
    s = calloc(n, sizeof(char*));
    for (int i = 0; i < n; i++)
    {
        s[i] = calloc(11, sizeof(char));
        scanf("%s", s[i]);
    }
    do
    {
        for (int i = 0; i < n; i++)
            printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
    } while (next_permutation(n, s));
    for (int i = 0; i < n; i++)
        free(s[i]);
    free(s);
    return 0;
}


来源: stackexchange

问:
What is the component a popup menu click originated from
Having a popup menu attached to several components on a form (buttons, but also things like TCharts), I would like to know which component was right clicked to start the popup menu in the first place.

The Sender parameter of the click method just points to the TMenuItem, its parent to the popup menu (or the parenting menu item).

How do I get the originating component?

答: PopUpMenu.PopupComponent indicates the component that last displayed the popup menu in response to the right mouse click </p>

OwnerDisplayName: malach

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
Remove Decimal values in Yaxis Linechart -Primefaces
i'm building a web application using javaEE with jsf/primefaces .

i made this code to display a linechart , but the problem is that the values of y axis are decimal in the chart, they start from 0.5,1,1.5 ...
i tried to set the type of values Arraylist to Integer but it doesn't work because the setData function must always take a Number type as a parametre .

```<code>package managedBean;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;

import org.primefaces.model.chart.Axis;
import org.primefaces.model.chart.AxisType;
import org.primefaces.model.chart.LineChartSeries;
import org.primefaces.model.charts.ChartData;
import org.primefaces.model.charts.line.LineChartDataSet;
import org.primefaces.model.charts.line.LineChartModel;
import org.primefaces.model.charts.line.LineChartOptions;
import org.primefaces.model.charts.optionconfig.title.Title;

import model.ControleVoyage;
import dao.ControleVoyageDao;
@ManagedBean(name = "chartJsViewVoyage")
public class chartJsViewVoyage {
    private LineChartModel lineModel;
    private List<Date> dateVoyageControle;

    @PostConstruct
    public void init() {
        createLineModel();
    }
     public void createLineModel() {
            lineModel = new LineChartModel();
            ChartData data = new ChartData();
            LineChartDataSet dataSet = new LineChartDataSet();
            List<Number> values = new ArrayList<>();
            /*
            ArrayList<Long> coutControlPerDate = new ArrayList();
            coutControlPerDate = (ArrayList<Long>) new dao.ControleLigneDao().getCountControleLign();
            for(int i=0; i<coutControlPerDate.size(); i++) {
                values.add(coutControlPerDate.get(i));
             }
             */
            List<ControleVoyage> listvoyage = new ArrayList();
            listvoyage = new dao.ControleVoyageDao().getAll();
            for(int i=0; i<listvoyage.size(); i++) {
                values.add(listvoyage.get(i).getVoyageControlee().getIdVoyage());
             }

            System.out.println("Count Voyage list");
            System.out.println(values);
            dataSet.setData(values);

            dataSet.setFill(false);
            dataSet.setLabel("Voyages controlée");
            dataSet.setBorderColor("rgb(75, 192, 192)");
            dataSet.setLineTension(0.1);
            data.addChartDataSet(dataSet);

            List<Date> dateVoyageControle = new dao.ControleVoyageDao().getDateControleVoyage();
            List<String> labels = new ArrayList<>();

            for(int i=0; i<dateVoyageControle.size(); i++) {
                labels.add(dateVoyageControle.get(i).toString());
             }
            System.out.println("date list");
            System.out.println(labels);
            data.setLabels(labels);

            //Options
            LineChartOptions options = new LineChartOptions();
//          Title title = new Title();
//          title.setDisplay(true);
//          title.setText("Line Chart");
//          options.setTitle(title);

            lineModel.setOptions(options);
            lineModel.setData(data);

        }

         public LineChartModel getLineModel() {
                return lineModel;
            }

        public void setLineModel(LineChartModel lineModel) {
            this.lineModel = lineModel;
        }

}

</code>```

答:
You can define chart option yAxis.ticks.stepSize: 1 through a call to the method CartesianLinearTicks.setStepSize(Number stepSize).

In your code, this could look as follows:

```<code>LineChartOptions options = new LineChartOptions();
CartesianScales cScales = new CartesianScales();
CartesianLinearAxes linearAxes = new CartesianLinearAxes();
CartesianLinearTicks ticks = new CartesianLinearTicks();
ticks.setBeginAtZero(true);
ticks.setStepSize(1);
linearAxes.setTicks(ticks);
cScales.addYAxesData(linearAxes);
options.setScales(cScales);
</code>```

Body:
i'm building a web application using javaEE with jsf/primefaces .

i made this code to display a linechart , but the problem is that the values of y axis are decimal in the chart, they start from 0.5,1,1.5 ...
i tried to set the type of values Arraylist to Integer but it doesn't work because the setData function must always take a Number type as a parametre .

package managedBean;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;

import org.primefaces.model.chart.Axis;
import org.primefaces.model.chart.AxisType;
import org.primefaces.model.chart.LineChartSeries;
import org.primefaces.model.charts.ChartData;
import org.primefaces.model.charts.line.LineChartDataSet;
import org.primefaces.model.charts.line.LineChartModel;
import org.primefaces.model.charts.line.LineChartOptions;
import org.primefaces.model.charts.optionconfig.title.Title;

import model.ControleVoyage;
import dao.ControleVoyageDao;
@ManagedBean(name = "chartJsViewVoyage")
public class chartJsViewVoyage {
    private LineChartModel lineModel;
    private List<Date> dateVoyageControle;

    @PostConstruct
    public void init() {
        createLineModel();
    }
     public void createLineModel() {
            lineModel = new LineChartModel();
            ChartData data = new ChartData();
            LineChartDataSet dataSet = new LineChartDataSet();
            List<Number> values = new ArrayList<>();
            /*
            ArrayList<Long> coutControlPerDate = new ArrayList();
            coutControlPerDate = (ArrayList<Long>) new dao.ControleLigneDao().getCountControleLign();
            for(int i=0; i<coutControlPerDate.size(); i++) {
                values.add(coutControlPerDate.get(i));
             }
             */
            List<ControleVoyage> listvoyage = new ArrayList();
            listvoyage = new dao.ControleVoyageDao().getAll();
            for(int i=0; i<listvoyage.size(); i++) {
                values.add(listvoyage.get(i).getVoyageControlee().getIdVoyage());
             }

            System.out.println("Count Voyage list");
            System.out.println(values);
            dataSet.setData(values);

            dataSet.setFill(false);
            dataSet.setLabel("Voyages controlée");
            dataSet.setBorderColor("rgb(75, 192, 192)");
            dataSet.setLineTension(0.1);
            data.addChartDataSet(dataSet);

            List<Date> dateVoyageControle = new dao.ControleVoyageDao().getDateControleVoyage();
            List<String> labels = new ArrayList<>();

            for(int i=0; i<dateVoyageControle.size(); i++) {
                labels.add(dateVoyageControle.get(i).toString());
             }
            System.out.println("date list");
            System.out.println(labels);
            data.setLabels(labels);

            //Options
            LineChartOptions options = new LineChartOptions();
//          Title title = new Title();
//          title.setDisplay(true);
//          title.setText("Line Chart");
//          options.setTitle(title);

            lineModel.setOptions(options);
            lineModel.setData(data);

        }

         public LineChartModel getLineModel() {
                return lineModel;
            }

        public void setLineModel(LineChartModel lineModel) {
            this.lineModel = lineModel;
        }

}

Body:
You can define chart option yAxis.ticks.stepSize: 1 through a call to the method CartesianLinearTicks.setStepSize(Number stepSize).

In your code, this could look as follows:

LineChartOptions options = new LineChartOptions();
CartesianScales cScales = new CartesianScales();
CartesianLinearAxes linearAxes = new CartesianLinearAxes();
CartesianLinearTicks ticks = new CartesianLinearTicks();
ticks.setBeginAtZero(true);
ticks.setStepSize(1);
linearAxes.setTicks(ticks);
cScales.addYAxesData(linearAxes);
options.setScales(cScales);


问:
Spark: Merging 2 columns of a DataSet into a single column
I have a table with ids as 2 different columns. I have another table which contains objects associated with the ids. I would like filter out the ids from the table2 for which id exists in either id1 or id2 in Table 1.

Table 1:

```<code>| id1  | id2 |
|  1   |  1  |
|  1   |  1  |
|  1   |  3  |
|  2   |  5  |
|  3   |  1  |
|  3   |  2  |
|  3   |  3  |
</code>```

Table 2:

```<code>| id  | obj   |
|  1  |  'A'  |
|  2  |  'B'  |
|  3  |  'C'  |
|  4  |  'D'  |
|  5  |  'E'  |
|  6  |  'F'  |
|  7  |  'G'  |
</code>```

What I am thinking is to create out a list from table1 containing the unique ids which will be [1, 2, 3, 5] from above example.

Then filter out the data frame on the basis of the list, which will give the result.

```<code>| id  | obj   |
|  1  |  'A'  |
|  2  |  'B'  |
|  3  |  'C'  |
|  5  |  'E'  |
</code>```

Though I have concerns regarding the scalability of the solution. The list can be large and it may even fail to load into memory for some cases. Any recommendations here in this case?

Thanks.

答:
Another approach:

```<code>val id_table = table1.select(explode(array('*)).as("id")).distinct()
val result = table2.join(id_table,"id")
result.show()
</code>```

output:

```<code>+---+---+
| id|obj|
+---+---+
|  1|'A'|
|  2|'B'|
|  3|'C'|
|  5|'E'|
+---+---+
</code>```

Body:
I have a table with ids as 2 different columns. I have another table which contains objects associated with the ids. I would like filter out the ids from the table2 for which id exists in either id1 or id2 in Table 1.

Table 1:

| id1  | id2 |
|  1   |  1  |
|  1   |  1  |
|  1   |  3  |
|  2   |  5  |
|  3   |  1  |
|  3   |  2  |
|  3   |  3  |

Table 2:

| id  | obj   |
|  1  |  'A'  |
|  2  |  'B'  |
|  3  |  'C'  |
|  4  |  'D'  |
|  5  |  'E'  |
|  6  |  'F'  |
|  7  |  'G'  |

What I am thinking is to create out a list from table1 containing the unique ids which will be [1, 2, 3, 5] from above example.

Then filter out the data frame on the basis of the list, which will give the result.

| id  | obj   |
|  1  |  'A'  |
|  2  |  'B'  |
|  3  |  'C'  |
|  5  |  'E'  |

Though I have concerns regarding the scalability of the solution. The list can be large and it may even fail to load into memory for some cases. Any recommendations here in this case?

Thanks.

Body:
Another approach:

val id_table = table1.select(explode(array('*)).as("id")).distinct()
val result = table2.join(id_table,"id")
result.show()

output:

+---+---+
| id|obj|
+---+---+
|  1|'A'|
|  2|'B'|
|  3|'C'|
|  5|'E'|
+---+---+


问:
HTML: dynamic positioning of overlay to center of textarea
I can't manage to dynamically position an overlay over an existing resizable textarea element.
Textarea doesn't seem to allow child nodes inside of itself so I have to create it as independent element

```<code><body>
  <textarea name="description" rows="20" cols="60"></textarea>
  <div class="overlay" style="width: 200px; height: 200px;">Something to show over the center of textarea</div>
</body>
</code>```

I need to position the overlay element exactly to the middle, while adjusting it's position if the textarea size is adjusted.
Probably I could achieve this by adding size change handlers to the TA and recompute the overlay position each time, but this seems yet too cumbersome to me. Are there any other working, more straightforward methods?

答:
You can pull this off with zero javascript by putting the textarea inside a parent element. In this example, I use a div. Make the parent div resizable and stretch the textarea to fill the entire parent div. Then just using relative positioning, you can position another element on top of the textarea directly in the center of the parent div.

.parent
{
resize: both;
width: 300px;
height: 300px;
overflow: hidden;
position: relative;
}

textarea
{
resize: none;
width: 100%;
height: 100%;
background: #eee;
}

.parent .overlay
{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin-top: -50px;
margin-left: -50px;
background: rgba(255, 0, 0, 0.25);
color: white;
font-size: 20px;
box-sizing: border-box;
padding: 35px 0;
text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <textarea></textarea>
  <div class="overlay">Overlay</div>
</div></code>```

Body:
I can't manage to dynamically position an overlay over an existing resizable textarea element.
Textarea doesn't seem to allow child nodes inside of itself so I have to create it as independent element

  <textarea name="description" rows="20" cols="60"></textarea>

Something to show over the center of textarea

I need to position the overlay element exactly to the middle, while adjusting it's position if the textarea size is adjusted.
Probably I could achieve this by adding size change handlers to the TA and recompute the overlay position each time, but this seems yet too cumbersome to me. Are there any other working, more straightforward methods?

Body:
You can pull this off with zero javascript by putting the textarea inside a parent element. In this example, I use a div. Make the parent div resizable and stretch the textarea to fill the entire parent div. Then just using relative positioning, you can position another element on top of the textarea directly in the center of the parent div.

.parent
{
resize: both;
width: 300px;
height: 300px;
overflow: hidden;
position: relative;
}

textarea
{
resize: none;
width: 100%;
height: 100%;
background: #eee;
}

.parent .overlay
{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin-top: -50px;
margin-left: -50px;
background: rgba(255, 0, 0, 0.25);
color: white;
font-size: 20px;
box-sizing: border-box;
padding: 35px 0;
text-align: center;
}

<div class="parent">
  <textarea></textarea>
  <div class="overlay">Overlay</div>
</div>


问:
IIS 10 - maxConcurrentRequestsPerCPU setting over 5000 is ignored
Facing an issue on IIS 10 (Windows Server 2016, .NET 4 integrated mode, classic ASP.NET app) where maxConcurrentRequestsPerCPU setting of over 5000 does not seem to be applied. However setting it to lower values has clear and visible effect.

I'm using JMetter for load testing. If I set thread count to 5000, I see 100% success rate, but anything higher has failure rates regardless of how high I set maxConcurrentRequestsPerCPU and requestQueueLimit. For example testing with 6000 threads consistently renders 16.6% failure rate.

If I set maxConcurrentRequestsPerCPU to something low like 12, I get almost 99% failure rate, so I know the lower bound settings have effect, just not anything over 5000.

The VM has 2 cores assigned, so with 5000 x 2 cores I feel I should be able to successfully test with 10,000 threads.

Aspnet.config

```<code><?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <system.web>
        <applicationPool
           maxConcurrentRequestsPerCPU="50000"
           maxConcurrentThreadsPerCPU="0"
           requestQueueLimit="50000"/>
    </system.web>

    <runtime>
        <legacyUnhandledExceptionPolicy enabled="false" />
        <legacyImpersonationPolicy enabled="true"/>
        <alwaysFlowImpersonationPolicy enabled="false"/>
        <SymbolReadingPolicy enabled="1" />
        <shadowCopyVerifyByTimestamp enabled="true"/>
    </runtime>
    <startup useLegacyV2RuntimeActivationPolicy="true" />
</configuration>
</code>```

What could be overwriting these settings and enforcing the upper bound of 5000?

I feel there is some additional setting that needs to be set to exceed 5000.

Any help / advice would be appreciated at this point. Thanks.

答: if you want to execute more than 5000 requests concurrently, you'll need to increase the requestQueueLimit. The requestQueueLimit restricts the total number of requests in the system. Due to its legacy, it is actually the total number of requests in the system, and not the number of requests in some queue. It's goal is to prevent the server from toppling over due to lack of physical memory, virtual memory, etc. When the limit is reached, incoming requests will receive a quick 503 "Server Too Busy" response.</p>

Body:
Facing an issue on IIS 10 (Windows Server 2016, .NET 4 integrated mode, classic ASP.NET app) where maxConcurrentRequestsPerCPU setting of over 5000 does not seem to be applied. However setting it to lower values has clear and visible effect.

I'm using JMetter for load testing. If I set thread count to 5000, I see 100% success rate, but anything higher has failure rates regardless of how high I set maxConcurrentRequestsPerCPU and requestQueueLimit. For example testing with 6000 threads consistently renders 16.6% failure rate.

If I set maxConcurrentRequestsPerCPU to something low like 12, I get almost 99% failure rate, so I know the lower bound settings have effect, just not anything over 5000.

The VM has 2 cores assigned, so with 5000 x 2 cores I feel I should be able to successfully test with 10,000 threads.

Aspnet.config

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <system.web>
        <applicationPool
           maxConcurrentRequestsPerCPU="50000"
           maxConcurrentThreadsPerCPU="0"
           requestQueueLimit="50000"/>
    </system.web>

    <runtime>
        <legacyUnhandledExceptionPolicy enabled="false" />
        <legacyImpersonationPolicy enabled="true"/>
        <alwaysFlowImpersonationPolicy enabled="false"/>
        <SymbolReadingPolicy enabled="1" />
        <shadowCopyVerifyByTimestamp enabled="true"/>
    </runtime>
    <startup useLegacyV2RuntimeActivationPolicy="true" />
</configuration>

What could be overwriting these settings and enforcing the upper bound of 5000?

I feel there is some additional setting that needs to be set to exceed 5000.

Any help / advice would be appreciated at this point. Thanks.


问:
Getting error while using my custom embedding layer in Tensorflow 2.0
I've made my custom embedding layer but when I'm testing it I'm getting error.
Below is my custom embedding layer.

```<code>class EndTokenLayer(Layer):

  def __init__(self, embedding_dim=128, **kwargs):
    super(EndTokenLayer, self).__init__(**kwargs)
    self.end_token_embedding = tf.Variable(initial_value=tf.random.uniform(shape=(embedding_dim,)), trainable=True)

  def call(self, inputs):
    end_token = tf.tile(tf.reshape(self.end_token_embedding, shape=(1, 1, self.end_token_embedding.shape[0])), [tf.shape(inputs)[0],1,1])
    return tf.keras.layers.concatenate([inputs, end_token], axis=1)
</code>```

But when I'm testing to my train_dataset(from tensorflow slices) which is having shape of one batch
x = (16,13,128) and y = (16,14)

```<code>temp = EndTokenLayer()
print(temp(inputs = train.take(1)))
</code>```

Error logs:
ValueError: Attempt to convert a value () with an unsupported type () to a Tensor.

答:
train.take(1) will give you a new dataset with a single element, not the first element of the dataset. Maybe you want something like this:

temp = EndTokenLayer()
for elem in train.take(1):
    print(temp(inputs=elem))
```

<p>Or just:</p>

<pre class="lang-py prettyprint-override"><code>temp = EndTokenLayer()
print(temp(inputs=next(iter(train))))
</code>```

Body:
I've made my custom embedding layer but when I'm testing it I'm getting error.
Below is my custom embedding layer.

class EndTokenLayer(Layer):

  def __init__(self, embedding_dim=128, **kwargs):
    super(EndTokenLayer, self).__init__(**kwargs)
    self.end_token_embedding = tf.Variable(initial_value=tf.random.uniform(shape=(embedding_dim,)), trainable=True)

  def call(self, inputs):
    end_token = tf.tile(tf.reshape(self.end_token_embedding, shape=(1, 1, self.end_token_embedding.shape[0])), [tf.shape(inputs)[0],1,1])
    return tf.keras.layers.concatenate([inputs, end_token], axis=1)

But when I'm testing to my train_dataset(from tensorflow slices) which is having shape of one batch
x = (16,13,128) and y = (16,14)

temp = EndTokenLayer()
print(temp(inputs = train.take(1)))

Error logs:
ValueError: Attempt to convert a value () with an unsupported type () to a Tensor.

Body:
train.take(1) will give you a new dataset with a single element, not the first element of the dataset. Maybe you want something like this:

temp = EndTokenLayer()
for elem in train.take(1):
    print(temp(inputs=elem))

Or just:

temp = EndTokenLayer()
print(temp(inputs=next(iter(train))))


问:
Wrapping array operation into a function
The input X to my network has the shape (10, 1, 5, 4). I am interested in boxplotting the distribution of input features (four), for each class. So, for example:

```<code>X = np.random.randn(10, 1, 5, 4)
a = np.zeros(5, dtype=int)
b = np.ones(5, dtype=int)
y = np.hstack((a,b))

print(X.shape)
print(y.shape)
(10, 1, 5, 4)
(10,)
</code>```

Then I separate the input Xinto respective classes, like:

```<code>class0, class1 =[],[]
for i in range(len(y)):
  if y[i]==0:
    class0.append(X[i])
  else:
    class1.append(X[i])

class0 = np.array(class0)
class1 = np.array(class1)
</code>```

Taking class0into consideration, I can go ahead to manipulate it in a way that the four features are arranged per column (col1, col2,col3,col4) this way.

```<code>def transformer(myclass):
  #reshape  the class
  k = myclass.transpose((0,1,3,2))
  #access individual feature
  s = k[0][:,0].reshape(-1,1)
  a = k[0][:,1].reshape(-1,1)
  j = k[0][:, 2].reshape(-1,1)
  b = k[0][:, 3].reshape(-1,1)
  rslt = [s,a,j,b]
  return rslt
</code>```

Then plot the features:

```<code>sns.boxplot(data=transformer(class0))
</code>```

This is the general idea of my workflow. Note that the function transformer is hardcoded to access only the first observation (element) of the class it takes as input.

Question: How to I do modify my function to access all observations of the class, not per every single example, for generalised. Such that col1are all features in the class that are in first column for each example.

Do write the following:

```<code>def mytransformer(myclass):
  #first, transpose class
  k = myclass.transpose((0,1,3,2))
  #speed
  for i in range(k):
    s = k[i][:,0].reshape(-1,1)
  return s
</code>```

Which gives the error:

```<code>mytransformer(class0)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-5451e55f03d9> in <module>()
----> 1 mytransformer(class0)

<ipython-input-14-d1a2c8098caf> in mytransformer(myclass)
      3   myclass = myclass.transpose((0,1,3,2))
      4   #speed
----> 5   for i in range(myclass):
      6     s = k[i][:,0].reshape(-1,1)
      7   return s

TypeError: only integer scalar arrays can be converted to a scalar index
</code>```

Is there a way to add legend to the boxplot so that I can give name to each feature?

答:
For your Question 1, You are using for loop range with a NumPy array which instead should have argument as an integer.

Maybe it is,

```<code>for i in range(len(k)):
</code>```

Body:
The input X to my network has the shape (10, 1, 5, 4). I am interested in boxplotting the distribution of input features (four), for each class. So, for example:

X = np.random.randn(10, 1, 5, 4)
a = np.zeros(5, dtype=int)
b = np.ones(5, dtype=int)
y = np.hstack((a,b))

print(X.shape)
print(y.shape)
(10, 1, 5, 4)
(10,)

Then I separate the input Xinto respective classes, like:

class0, class1 =[],[]
for i in range(len(y)):
  if y[i]==0:
    class0.append(X[i])
  else:
    class1.append(X[i])

class0 = np.array(class0)
class1 = np.array(class1)

Taking class0into consideration, I can go ahead to manipulate it in a way that the four features are arranged per column (col1, col2,col3,col4) this way.

def transformer(myclass):
  #reshape  the class
  k = myclass.transpose((0,1,3,2))
  #access individual feature
  s = k[0][:,0].reshape(-1,1)
  a = k[0][:,1].reshape(-1,1)
  j = k[0][:, 2].reshape(-1,1)
  b = k[0][:, 3].reshape(-1,1)
  rslt = [s,a,j,b]
  return rslt

Then plot the features:

sns.boxplot(data=transformer(class0))

This is the general idea of my workflow. Note that the function transformer is hardcoded to access only the first observation (element) of the class it takes as input.

Question: How to I do modify my function to access all observations of the class, not per every single example, for generalised. Such that col1are all features in the class that are in first column for each example.

Do write the following:

def mytransformer(myclass):
  #first, transpose class
  k = myclass.transpose((0,1,3,2))
  #speed
  for i in range(k):
    s = k[i][:,0].reshape(-1,1)
  return s

Which gives the error:

mytransformer(class0)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-5451e55f03d9> in <module>()
----> 1 mytransformer(class0)

<ipython-input-14-d1a2c8098caf> in mytransformer(myclass)
      3   myclass = myclass.transpose((0,1,3,2))
      4   #speed
----> 5   for i in range(myclass):
      6     s = k[i][:,0].reshape(-1,1)
      7   return s

TypeError: only integer scalar arrays can be converted to a scalar index

Is there a way to add legend to the boxplot so that I can give name to each feature?

Body:
For your Question 1, You are using for loop range with a NumPy array which instead should have argument as an integer.

Maybe it is,

for i in range(len(k)):


问:
Pandas .equals method returns different results between windows and linux
I am trying to deploy the same code on windows10 using conda, and the unit tests that work on linux does not function on windows.

On Ubuntu:

df_1

                    col_1                 col_2                      col_3
0                     [-]                     1                        nul
1                     [-]                     1                    pas top
2         [+, plus_small]                     2  personal-minute du centre
3         [+, plus_small]                     2                        top
4         [+, plus_small]                     2                  tres bien
```

<p>when we take a look at the details </p>

<p><strong>df_1.to_dict()</strong></p>

<pre class="lang-py prettyprint-override"><code>{
 'col_1': {0: ['-'], 1: ['-'], 2: ['+', 'plus_small'], 3: ['+', 'plus_small'], 4: ['+', 'plus_small']},
 'col_2': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2},
 'col_3': {0: 'nul', 1: 'pas top', 2: 'personal-minute du centre', 3: 'top', 4: 'tres bien'}
}
</code>```

when we take a look at the details

df_2

                    col_1                 col_2                      col_3
0                     [-]                     1                        nul
1                     [-]                     1                    pas top
2         [+, plus_small]                     2  personal-minute du centre
3         [+, plus_small]                     2                        top
4         [+, plus_small]                     2                  tres bien
```

<p><strong>df_2.to_dict()</strong></p>

<pre class="lang-py prettyprint-override"><code>{
 'col_1': {0: ['-'], 1: ['-'], 2: ['+', 'plus_small'], 3: ['+', 'plus_small'], 4: ['+', 'plus_small']},
 'col_2': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2},
 'col_3': {0: 'nul', 1: 'pas top', 2: 'personal-minute du centre', 3: 'top', 4: 'tres bien'}
}
</code>```

Result

df_1.equals(df_2)
True
```

<p><strong>On Windows10:</strong></p>

<p><strong>df_1</strong></p>

<pre class="lang-py prettyprint-override"><code>                    col_1                 col_2                      col_3
0                     [-]                     1                        nul
1                     [-]                     1                    pas top
2         [+, plus_small]                     2  personal-minute du centre
3         [+, plus_small]                     2                        top
4         [+, plus_small]                     2                  tres bien
</code>```

when we take a look at the details

{
 'col_1': {0: ['-'], 1: ['-'], 2: ['+', 'plus_small'], 3: ['+', 'plus_small'], 4: ['+', 'plus_small']},
 'col_2': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2},
 'col_3': {0: 'nul', 1: 'pas top', 2: 'personal-minute du centre', 3: 'top', 4: 'tres bien'}
}
```

<p><strong>df_2</strong></p>

<pre class="lang-py prettyprint-override"><code>                    col_1                 col_2                      col_3
0                     [-]                     1                        nul
1                     [-]                     1                    pas top
2         [+, plus_small]                     2  personal-minute du centre
3         [+, plus_small]                     2                        top
4         [+, plus_small]                     2                  tres bien
</code>```

when we take a look at the details

df2.to_dict()

{
 'col_1': {0: ['-'], 1: ['-'], 2: ['+', 'plus_small'], 3: ['+', 'plus_small'], 4: ['+', 'plus_small']},
 'col_2': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2},
 'col_3': {0: 'nul', 1: 'pas top', 2: 'personal-minute du centre', 3: 'top', 4: 'tres bien'}
}
```

<pre class="lang-py prettyprint-override"><code>df_1 == df_2
                    col_1                 col_2                      col_3
0                    True                  True                       True
1                    True                  True                       True
2                    True                  True                       True
3                    True                  True                       True
4                    True                  True                       True
</code>```

and then :

df_1.equals(df_2)
False
```

答:
I can replace the .equals method by a to_dict==

Before:

df_1.equals(df_2)
False
```

<p>After:</p>

<pre class="lang-py prettyprint-override"><code>df_1.to_dict() == df_2.to_dict()
True
</code>```

Thank you @Ch3steR for the idea!

Body:
I am trying to deploy the same code on windows10 using conda, and the unit tests that work on linux does not function on windows.

On Ubuntu:

df_1

                    col_1                 col_2                      col_3
0                     [-]                     1                        nul
1                     [-]                     1                    pas top
2         [+, plus_small]                     2  personal-minute du centre
3         [+, plus_small]                     2                        top
4         [+, plus_small]                     2                  tres bien

when we take a look at the details

df_1.to_dict()

{
 'col_1': {0: ['-'], 1: ['-'], 2: ['+', 'plus_small'], 3: ['+', 'plus_small'], 4: ['+', 'plus_small']},
 'col_2': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2},
 'col_3': {0: 'nul', 1: 'pas top', 2: 'personal-minute du centre', 3: 'top', 4: 'tres bien'}
}

when we take a look at the details

df_2

                    col_1                 col_2                      col_3
0                     [-]                     1                        nul
1                     [-]                     1                    pas top
2         [+, plus_small]                     2  personal-minute du centre
3         [+, plus_small]                     2                        top
4         [+, plus_small]                     2                  tres bien

df_2.to_dict()

{
 'col_1': {0: ['-'], 1: ['-'], 2: ['+', 'plus_small'], 3: ['+', 'plus_small'], 4: ['+', 'plus_small']},
 'col_2': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2},
 'col_3': {0: 'nul', 1: 'pas top', 2: 'personal-minute du centre', 3: 'top', 4: 'tres bien'}
}

Result

df_1.equals(df_2)
True

On Windows10:

df_1

                    col_1                 col_2                      col_3
0                     [-]                     1                        nul
1                     [-]                     1                    pas top
2         [+, plus_small]                     2  personal-minute du centre
3         [+, plus_small]                     2                        top
4         [+, plus_small]                     2                  tres bien

when we take a look at the details

{
 'col_1': {0: ['-'], 1: ['-'], 2: ['+', 'plus_small'], 3: ['+', 'plus_small'], 4: ['+', 'plus_small']},
 'col_2': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2},
 'col_3': {0: 'nul', 1: 'pas top', 2: 'personal-minute du centre', 3: 'top', 4: 'tres bien'}
}

df_2

                    col_1                 col_2                      col_3
0                     [-]                     1                        nul
1                     [-]                     1                    pas top
2         [+, plus_small]                     2  personal-minute du centre
3         [+, plus_small]                     2                        top
4         [+, plus_small]                     2                  tres bien

when we take a look at the details

df2.to_dict()

{
 'col_1': {0: ['-'], 1: ['-'], 2: ['+', 'plus_small'], 3: ['+', 'plus_small'], 4: ['+', 'plus_small']},
 'col_2': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2},
 'col_3': {0: 'nul', 1: 'pas top', 2: 'personal-minute du centre', 3: 'top', 4: 'tres bien'}
}

df_1 == df_2
                    col_1                 col_2                      col_3
0                    True                  True                       True
1                    True                  True                       True
2                    True                  True                       True
3                    True                  True                       True
4                    True                  True                       True

and then :

df_1.equals(df_2)
False

Body:
I can replace the .equals method by a to_dict==

Before:

df_1.equals(df_2)
False

After:

df_1.to_dict() == df_2.to_dict()
True

Thank you @Ch3steR for the idea!


问:
Unable to load AWS Credentials
I am following the next example to connects to Amazon Kinesis Data Streams and outputs the joined results to Amazon S3 in parquet format: https://docs.aws.amazon.com/glue/latest/dg/glue-etl-scala-example.html

When I configure the connection to AWS and trying to run it, it throws the next error that can't find the credentials and I have assigned in "C:\Users\user.aws\credentials" also I have added environment variables :

```<code>AWS_ACCESS_KEY_ID=XXX
AWS_SECRET_ACCESS_KEY=XxXX
</code>```

But still failing with:

```<code> ERROR AWSInstanceProfileCredentialsProviderWithRetries: Got an exception while fetching credentials org.apache.s
park.sql.kinesis.shaded.amazonaws.SdkClientException: Unable to load credentials from service endpoint
</code>```

答:
The error message is not about your own credentials that you have in "C:\Users\user.aws\credentials", but about missing credentials in an instance profile.

The class AWSInstanceProfileCredentialsProviderWithRetries extends InstanceProfileCredentialsProvider which is:

Credentials provider implementation that loads credentials from the Amazon EC2 Instance Metadata Service

The code you are executing should be running on EC2 instance, therefore it expects to get credentials form instance role. What's more the instance role should have all necessary permissions which your code requires, e.g., using Kinesis.

From the link provided in your question, it is not clear where the example code should be exactly executed. Whether it is a custom ec2 instance, or some glue-related managed instance.

Title: Unable to load AWS Credentials

Body:
I am following the next example to connects to Amazon Kinesis Data Streams and outputs the joined results to Amazon S3 in parquet format: https://docs.aws.amazon.com/glue/latest/dg/glue-etl-scala-example.html

When I configure the connection to AWS and trying to run it, it throws the next error that can't find the credentials and I have assigned in "C:\Users\user.aws\credentials" also I have added environment variables :

AWS_ACCESS_KEY_ID=XXX
AWS_SECRET_ACCESS_KEY=XxXX

But still failing with:

 ERROR AWSInstanceProfileCredentialsProviderWithRetries: Got an exception while fetching credentials org.apache.s
park.sql.kinesis.shaded.amazonaws.SdkClientException: Unable to load credentials from service endpoint


问:
Can I get data from an NgRx service without updating cache?
I have my service and need to get data using getWithQuery, but I don't need NgRx store to be updated. I just need to get this data and use them in subscribe method.

I've tried different EntityActionOptions.mergeStrategy but cache is still updated.

Any ideas?

Thanks!

答:
The ngrx store purpose is to be responsible for the app state. It means if you want to fetch something you dispatch an action that updates the store and then you select this data from the store.

If you want to fetch data directly skipping the store and select parts - it means you follow against ngrx purpose and perhaps you don't ngrx at all.

If you want to ngrx then consider writing you app in the way that it always puts data into the store if something is updated / fetched and to display the data it's always selected from the store.


问:
Access swift class in objective c parent class
I have created a hybrid App which has both Objective-c and Swift classes.

I have a Main View Controller (parent) from which all other View Controllers are inherited (both written in Objective-c and Swift).

Now the issue I am facing is that I want to access a swift class inside my MainViewController but when I add #import "MyProjectName-Swift.h" in MainViewController.h, I got tons of errors.

The reason for that is because my swift view controllers are also inherited from MainViewController and when I add #import "MyProjectName-Swift.h" to MainViewController.h, all swift classes got confused.

I hope you understand my question. The scenario is a bit complicated and sorry if I haven't explained it any better.

Also, is there a way to import only a single swift class in objective-c instead of doing this #import "MyProjectName-Swift.h"?

Any kind of help would be greatly appreciated.

答:
You can only import "ProductName-Swift.h" in .m files.

To avoid cyclical references, don’t import Swift into an Objective-C header file. Instead, you can forward declare a Swift class to use it in an Objective-C header. Note that you cannot subclass a Swift class in Objective-C.

There is no way to import single Swift class to ObjC file. ProductName-Swift.h is an autogenerated header that defines Objective-C interfaces for all Swift classes in your project that are either annotated with @objc or inherit from NSObject.


问:
Return specific Row first and then other Row follow
I want to print the trending row first and then New and then all other row from the table "employee".

Also i want limit the number of row and in descending order

I was trying this

```<code>SELECT * FROM (SELECT * FROM employee LIMIT 7) sub ORDER BY id DESC
</code>```

Expected Result

答:
You may try ordering with a CASE expression:

```<code>SELECT id, Name, Status
FROM employee
ORDER BY
    CASE Status WHEN 'Trending' THEN 1
                WHEN 'NEW' THEN 2
                ELSE 3 END,
    id DESC
LIMIT 7;
</code>```

Body:
I want to print the trending row first and then New and then all other row from the table "employee".

Also i want limit the number of row and in descending order

I was trying this

SELECT * FROM (SELECT * FROM employee LIMIT 7) sub ORDER BY id DESC

Expected Result

Body:
You may try ordering with a CASE expression:

SELECT id, Name, Status
FROM employee
ORDER BY
    CASE Status WHEN 'Trending' THEN 1
                WHEN 'NEW' THEN 2
                ELSE 3 END,
    id DESC
LIMIT 7;


问:
How to set up cloudkarafka brokers for the confluent rabbitmq source connector?
I'm using kafka connector docker image confluentinc/cp-kafka-connect:5.4.0-beta1 from confluent.

I would like to set up RabbitMQ source connector the way that is described in this article:

https://rmoff.net/2020/01/08/streaming-messages-from-rabbitmq-into-kafka-with-kafka-connect/,

but instead of using local kafka broker, I would like to use the brokers that I have set up into account of  https://www.cloudkarafka.com/

Within the docker-compose.yml, I have managed to establish the connection from the connector container to the cloudkarafka brokers with the following set up:

```<code>kafka-connect-01:
    image: confluentinc/cp-kafka-connect:5.4.0-beta1
    container_name: kafka-connect-01
    hostname: kafka-connect-01
    ports:
      - 8083:8083
    environment:
      CONNECT_LOG4J_APPENDER_STDOUT_LAYOUT_CONVERSIONPATTERN: "[%d] %p %X{connector.context}%m (%c:%L)%n"
      CONNECT_CUB_KAFKA_TIMEOUT: 300
      CONNECT_BOOTSTRAP_SERVERS: "my-cloudkafka-brokers:9094"
      CONNECT_SECURITY_PROTOCOL: "SASL_SSL"
      CONNECT_SASL_MECHANISM: "SCRAM-SHA-256"
      CONNECT_SASL_JAAS_CONFIG: 'org.apache.kafka.common.security.scram.ScramLoginModule required username="username" password="hidden";'
      CONNECT_REST_ADVERTISED_HOST_NAME: 'kafka-connect-01'
      CONNECT_REST_PORT: 8083
      CONNECT_GROUP_ID: username-c-cluster
      CONNECT_CONFIG_STORAGE_TOPIC: username-c-configs
      CONNECT_OFFSET_STORAGE_TOPIC: username-c-offsets
      CONNECT_STATUS_STORAGE_TOPIC: username-c-status
      CONNECT_KEY_CONVERTER: org.apache.kafka.connect.storage.StringConverter
      #CONNECT_KEY_CONVERTER_SCHEMA_REGISTRY_URL: "http://schema-registry:8081"
      CONNECT_VALUE_CONVERTER: org.apache.kafka.connect.converters.ByteArrayConverter
      #CONNECT_VALUE_CONVERTER_SCHEMA_REGISTRY_URL: "http://schema-registry:8081"
      CONNECT_INTERNAL_KEY_CONVERTER: 'org.apache.kafka.connect.storage.StringConverter'
      CONNECT_INTERNAL_VALUE_CONVERTER: 'org.apache.kafka.connect.json.JsonConverter'
      CONNECT_LOG4J_ROOT_LOGLEVEL: 'DEBUG'
      #CONNECT_LOG4J_LOGGERS: 'org.apache.kafka.connect.runtime.rest=WARN,org.reflections=ERROR'
      CONNECT_LOG4J_LOGGERS: 'org.apache.kafka.connect.runtime.rest=DEBUG,org.reflections=ERROR,org.eclipse.jetty.server=DEBUG'
      CONNECT_CONFIG_STORAGE_REPLICATION_FACTOR: '1'
      CONNECT_OFFSET_STORAGE_REPLICATION_FACTOR: '1'
      CONNECT_STATUS_STORAGE_REPLICATION_FACTOR: '1'
      CONNECT_PLUGIN_PATH: '/usr/share/java,/usr/share/confluent-hub-components/,/data/connect-jars'
</code>```

The connectivity issue:

```<code>[source-rabbitmq-00|task-0] [Producer clientId=connector-producer-source-rabbitmq-00-0] Connection with cloudkafka-broker disconnected (org.apache.kafka.common.network.Selector:607)
java.io.EOFException
    at org.apache.kafka.common.network.NetworkReceive.readFrom(NetworkReceive.java:119)
    at org.apache.kafka.common.network.KafkaChannel.receive(KafkaChannel.java:424)
    at org.apache.kafka.common.network.KafkaChannel.read(KafkaChannel.java:385)
    at org.apache.kafka.common.network.Selector.attemptRead(Selector.java:651)
    at org.apache.kafka.common.network.Selector.pollSelectionKeys(Selector.java:572)
    at org.apache.kafka.common.network.Selector.poll(Selector.java:483)
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:539)
    at org.apache.kafka.clients.producer.internals.Sender.runOnce(Sender.java:330)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:239)
    at java.lang.Thread.run(Thread.java:748)
</code>```

occurs with from the RabbitMQ source connector when is trying to publish the message to the CloudKafka brokers (the  DNS of the brokers were on purpose hidden).
I got the same problem, when I was using the following RabbitMQ connector configurations:

Configuration 1:

```<code>curl -i -X PUT -H  "Content-Type:application/json" \
    http://localhost:8083/connectors/source-rabbitmq-01/config \
    -d '{
        "connector.class" : "io.confluent.connect.rabbitmq.RabbitMQSourceConnector",
        "kafka.topic" : "username-myrabbitsinktopic",
        "rabbitmq.queue" : "test-queue-01",
        "rabbitmq.username": "user",
        "rabbitmq.password": "pw",
        "rabbitmq.host": "rabbitmq",
        "rabbitmq.port": "5672",
        "rabbitmq.virtual.host": "/",
        "confluent.license":"",
        "confluent.topic.bootstrap.servers":"cloudkafka-brokers:9094",
    "confluent.topic.sasl.jaas.config": "org.apache.kafka.common.security.scram.ScramLoginModule required username=\"username\" password=\"userpassword\";",
        "confluent.topic.security.protocol":"SASL_SSL",
        "confluent.topic.sasl.mechanism":"SCRAM-SHA-256",
        "value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter",
        "key.converter": "org.apache.kafka.connect.storage.StringConverter",
        "offset.flush.timeout.ms":1200000000
 }'
</code>```

Configuration 2

```<code>curl -i -X PUT -H  "Content-Type:application/json" \
    http://localhost:8083/connectors/source-rabbitmq-00/config \
    -d '{
        "connector.class" : "io.confluent.connect.rabbitmq.RabbitMQSourceConnector",
        "kafka.topic" : "username-myrabbitmqsourcetopic",
        "rabbitmq.queue" : "test-queue-01",
        "rabbitmq.username": "user",
        "rabbitmq.password": "pw",
        "rabbitmq.host": "rabbitmq",
        "rabbitmq.port": "5672",
        "rabbitmq.virtual.host": "/",
        "bootstrap.servers":"cloudkafkabroker:9094",
    "sasl.jaas.config": "org.apache.kafka.common.security.scram.ScramLoginModule required username=\"username\" password=\"password\";",
        "security.protocol":"SASL_SSL",
        "sasl.mechanism":"SCRAM-SHA-256",
        "value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter",
        "key.converter": "org.apache.kafka.connect.storage.StringConverter",
        "offset.flush.timeout.ms":1200000000
 }'
</code>```

Please advice how to configure this rabbitmq connector to use the brokers provided by cloudkafka.
Thank you.

答:
I have succeeded to connect RabbitMQ to CloudKafka by using the following configurations:

a) For the kafka connector

```<code>{
    "connector.class": "io.confluent.connect.rabbitmq.RabbitMQSourceConnector",
    "rabbitmq.port": "5672",
    "rabbitmq.password": "passwd",
    "rabbitmq.queue": "test-queue-01",
    "rabbitmq.host": "rabbitmq",
    "name": "source-rabbitmq-01",
    "kafka.topic": "c0b9uv0s-mytopic",
    "rabbitmq.username": "user",
    "value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter",
    "key.converter": "org.apache.kafka.connect.storage.StringConverter",
    "rabbitmq.virtual.host": "/"
}
</code>```

b) In the docker compose

```<code>version: '3'
services:

  kafka-connect-01:
    image: connect-rabbitmq:latest
    container_name: kafka-connect
    hostname: kafka-connect
    ports:
      - 8083:8083
    environment:
      CONNECT_LOG4J_APPENDER_STDOUT_LAYOUT_CONVERSIONPATTERN: "[%d] %p %X{connector.context}%m (%c:%L)%n"
      CONNECT_CUB_KAFKA_TIMEOUT: 300
      CONNECT_BOOTSTRAP_SERVERS: "cloudkarfkanode:9094"
      CONNECT_SECURITY_PROTOCOL: "SASL_SSL"
      CONNECT_SASL_MECHANISM: "SCRAM-SHA-256"
      CONNECT_SASL_JAAS_CONFIG: "org.apache.kafka.common.security.scram.ScramLoginModule required username=\"user\" password=\"password\";"
      CONNECT_REST_ADVERTISED_HOST_NAME: 'kafka-connect'
      CONNECT_REST_PORT: 8083
      CONNECT_GROUP_ID: user-w-cluster
      CONNECT_CONFIG_STORAGE_TOPIC: user-w-configs
      CONNECT_OFFSET_STORAGE_TOPIC: user-w-offsets
      CONNECT_STATUS_STORAGE_TOPIC: user-w-status
      CONNECT_KEY_CONVERTER: org.apache.kafka.connect.storage.StringConverter
      CONNECT_VALUE_CONVERTER: org.apache.kafka.connect.converters.ByteArrayConverter
      CONNECT_INTERNAL_KEY_CONVERTER: 'org.apache.kafka.connect.storage.StringConverter'
      CONNECT_INTERNAL_VALUE_CONVERTER: 'org.apache.kafka.connect.json.JsonConverter'
      CONNECT_LOG4J_ROOT_LOGLEVEL: 'INFO'
      #CONNECT_LOG4J_LOGGERS: 'org.apache.kafka.connect.runtime.rest=DEBUG,org.reflections=ERROR'
      CONNECT_LOG4J_LOGGERS: 'org.apache.kafka.connect.runtime.rest=INFO,org.reflections=ERROR,org.eclipse.jetty.server=INFO'
      CONNECT_PLUGIN_PATH: '/usr/share/java,/usr/share/confluent-hub-components/,/data/connect-jars'
      CONNECT_PRODUCER_BOOTSTRAP_SERVERS: "cloudkafkanode:9094"
      CONNECT_PRODUCER_SECURITY_PROTOCOL: "SASL_SSL"
      CONNECT_PRODUCER_SASL_MECHANISM: "SCRAM-SHA-256"
      CONNECT_PRODUCER_SASL_JAAS_CONFIG: "org.apache.kafka.common.security.scram.ScramLoginModule required username=\"user\" password=\"password\";"

    command:
      # In the command section, $ are replaced with $$ to avoid the error 'Invalid interpolation format for "command" option'
      - bash
      - -c
      - |
        echo "Installing connector plugins"
        confluent-hub install --no-prompt confluentinc/kafka-connect-rabbitmq:1.1.1

        #
        echo "Launching Kafka Connect worker"
        /etc/confluent/docker/run &
        #
        sleep infinity

  rabbitmq:
    image: rabbitmq:3-management
    container_name: rabbitmq
    environment:
      RABBITMQ_DEFAULT_USER: user
      RABBITMQ_DEFAULT_PASS: password
      RABBITMQ_DEFAULT_VHOST: "/"
    ports:
      - '15672:15672'
      - '5672:5672'
</code>```

The configurations that fixed the mentioned errors are:

```<code>      CONNECT_PRODUCER_BOOTSTRAP_SERVERS: "cloudkafkanode:9094"
      CONNECT_PRODUCER_SECURITY_PROTOCOL: "SASL_SSL"
      CONNECT_PRODUCER_SASL_MECHANISM: "SCRAM-SHA-256"
      CONNECT_PRODUCER_SASL_JAAS_CONFIG: "org.apache.kafka.common.security.scram.ScramLoginModule required username=\"user\" password=\"password\";"
</code>```

I hope this will help others to fix same issue.

Body:
I'm using kafka connector docker image confluentinc/cp-kafka-connect:5.4.0-beta1 from confluent.

I would like to set up RabbitMQ source connector the way that is described in this article:

https://rmoff.net/2020/01/08/streaming-messages-from-rabbitmq-into-kafka-with-kafka-connect/,

but instead of using local kafka broker, I would like to use the brokers that I have set up into account of  https://www.cloudkarafka.com/

Within the docker-compose.yml, I have managed to establish the connection from the connector container to the cloudkarafka brokers with the following set up:

kafka-connect-01:
    image: confluentinc/cp-kafka-connect:5.4.0-beta1
    container_name: kafka-connect-01
    hostname: kafka-connect-01
    ports:
      - 8083:8083
    environment:
      CONNECT_LOG4J_APPENDER_STDOUT_LAYOUT_CONVERSIONPATTERN: "[%d] %p %X{connector.context}%m (%c:%L)%n"
      CONNECT_CUB_KAFKA_TIMEOUT: 300
      CONNECT_BOOTSTRAP_SERVERS: "my-cloudkafka-brokers:9094"
      CONNECT_SECURITY_PROTOCOL: "SASL_SSL"
      CONNECT_SASL_MECHANISM: "SCRAM-SHA-256"
      CONNECT_SASL_JAAS_CONFIG: 'org.apache.kafka.common.security.scram.ScramLoginModule required username="username" password="hidden";'
      CONNECT_REST_ADVERTISED_HOST_NAME: 'kafka-connect-01'
      CONNECT_REST_PORT: 8083
      CONNECT_GROUP_ID: username-c-cluster
      CONNECT_CONFIG_STORAGE_TOPIC: username-c-configs
      CONNECT_OFFSET_STORAGE_TOPIC: username-c-offsets
      CONNECT_STATUS_STORAGE_TOPIC: username-c-status
      CONNECT_KEY_CONVERTER: org.apache.kafka.connect.storage.StringConverter
      #CONNECT_KEY_CONVERTER_SCHEMA_REGISTRY_URL: "http://schema-registry:8081"
      CONNECT_VALUE_CONVERTER: org.apache.kafka.connect.converters.ByteArrayConverter
      #CONNECT_VALUE_CONVERTER_SCHEMA_REGISTRY_URL: "http://schema-registry:8081"
      CONNECT_INTERNAL_KEY_CONVERTER: 'org.apache.kafka.connect.storage.StringConverter'
      CONNECT_INTERNAL_VALUE_CONVERTER: 'org.apache.kafka.connect.json.JsonConverter'
      CONNECT_LOG4J_ROOT_LOGLEVEL: 'DEBUG'
      #CONNECT_LOG4J_LOGGERS: 'org.apache.kafka.connect.runtime.rest=WARN,org.reflections=ERROR'
      CONNECT_LOG4J_LOGGERS: 'org.apache.kafka.connect.runtime.rest=DEBUG,org.reflections=ERROR,org.eclipse.jetty.server=DEBUG'
      CONNECT_CONFIG_STORAGE_REPLICATION_FACTOR: '1'
      CONNECT_OFFSET_STORAGE_REPLICATION_FACTOR: '1'
      CONNECT_STATUS_STORAGE_REPLICATION_FACTOR: '1'
      CONNECT_PLUGIN_PATH: '/usr/share/java,/usr/share/confluent-hub-components/,/data/connect-jars'

The connectivity issue:

[source-rabbitmq-00|task-0] [Producer clientId=connector-producer-source-rabbitmq-00-0] Connection with cloudkafka-broker disconnected (org.apache.kafka.common.network.Selector:607)
java.io.EOFException
    at org.apache.kafka.common.network.NetworkReceive.readFrom(NetworkReceive.java:119)
    at org.apache.kafka.common.network.KafkaChannel.receive(KafkaChannel.java:424)
    at org.apache.kafka.common.network.KafkaChannel.read(KafkaChannel.java:385)
    at org.apache.kafka.common.network.Selector.attemptRead(Selector.java:651)
    at org.apache.kafka.common.network.Selector.pollSelectionKeys(Selector.java:572)
    at org.apache.kafka.common.network.Selector.poll(Selector.java:483)
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:539)
    at org.apache.kafka.clients.producer.internals.Sender.runOnce(Sender.java:330)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:239)
    at java.lang.Thread.run(Thread.java:748)

occurs with from the RabbitMQ source connector when is trying to publish the message to the CloudKafka brokers (the  DNS of the brokers were on purpose hidden).
I got the same problem, when I was using the following RabbitMQ connector configurations:

Configuration 1:

curl -i -X PUT -H  "Content-Type:application/json" \
    http://localhost:8083/connectors/source-rabbitmq-01/config \
    -d '{
        "connector.class" : "io.confluent.connect.rabbitmq.RabbitMQSourceConnector",
        "kafka.topic" : "username-myrabbitsinktopic",
        "rabbitmq.queue" : "test-queue-01",
        "rabbitmq.username": "user",
        "rabbitmq.password": "pw",
        "rabbitmq.host": "rabbitmq",
        "rabbitmq.port": "5672",
        "rabbitmq.virtual.host": "/",
        "confluent.license":"",
        "confluent.topic.bootstrap.servers":"cloudkafka-brokers:9094",
    "confluent.topic.sasl.jaas.config": "org.apache.kafka.common.security.scram.ScramLoginModule required username=\"username\" password=\"userpassword\";",
        "confluent.topic.security.protocol":"SASL_SSL",
        "confluent.topic.sasl.mechanism":"SCRAM-SHA-256",
        "value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter",
        "key.converter": "org.apache.kafka.connect.storage.StringConverter",
        "offset.flush.timeout.ms":1200000000
 }'

Configuration 2

curl -i -X PUT -H  "Content-Type:application/json" \
    http://localhost:8083/connectors/source-rabbitmq-00/config \
    -d '{
        "connector.class" : "io.confluent.connect.rabbitmq.RabbitMQSourceConnector",
        "kafka.topic" : "username-myrabbitmqsourcetopic",
        "rabbitmq.queue" : "test-queue-01",
        "rabbitmq.username": "user",
        "rabbitmq.password": "pw",
        "rabbitmq.host": "rabbitmq",
        "rabbitmq.port": "5672",
        "rabbitmq.virtual.host": "/",
        "bootstrap.servers":"cloudkafkabroker:9094",
    "sasl.jaas.config": "org.apache.kafka.common.security.scram.ScramLoginModule required username=\"username\" password=\"password\";",
        "security.protocol":"SASL_SSL",
        "sasl.mechanism":"SCRAM-SHA-256",
        "value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter",
        "key.converter": "org.apache.kafka.connect.storage.StringConverter",
        "offset.flush.timeout.ms":1200000000
 }'

Please advice how to configure this rabbitmq connector to use the brokers provided by cloudkafka.
Thank you.

Body:
I have succeeded to connect RabbitMQ to CloudKafka by using the following configurations:

a) For the kafka connector

{
    "connector.class": "io.confluent.connect.rabbitmq.RabbitMQSourceConnector",
    "rabbitmq.port": "5672",
    "rabbitmq.password": "passwd",
    "rabbitmq.queue": "test-queue-01",
    "rabbitmq.host": "rabbitmq",
    "name": "source-rabbitmq-01",
    "kafka.topic": "c0b9uv0s-mytopic",
    "rabbitmq.username": "user",
    "value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter",
    "key.converter": "org.apache.kafka.connect.storage.StringConverter",
    "rabbitmq.virtual.host": "/"
}

b) In the docker compose

version: '3'
services:

  kafka-connect-01:
    image: connect-rabbitmq:latest
    container_name: kafka-connect
    hostname: kafka-connect
    ports:
      - 8083:8083
    environment:
      CONNECT_LOG4J_APPENDER_STDOUT_LAYOUT_CONVERSIONPATTERN: "[%d] %p %X{connector.context}%m (%c:%L)%n"
      CONNECT_CUB_KAFKA_TIMEOUT: 300
      CONNECT_BOOTSTRAP_SERVERS: "cloudkarfkanode:9094"
      CONNECT_SECURITY_PROTOCOL: "SASL_SSL"
      CONNECT_SASL_MECHANISM: "SCRAM-SHA-256"
      CONNECT_SASL_JAAS_CONFIG: "org.apache.kafka.common.security.scram.ScramLoginModule required username=\"user\" password=\"password\";"
      CONNECT_REST_ADVERTISED_HOST_NAME: 'kafka-connect'
      CONNECT_REST_PORT: 8083
      CONNECT_GROUP_ID: user-w-cluster
      CONNECT_CONFIG_STORAGE_TOPIC: user-w-configs
      CONNECT_OFFSET_STORAGE_TOPIC: user-w-offsets
      CONNECT_STATUS_STORAGE_TOPIC: user-w-status
      CONNECT_KEY_CONVERTER: org.apache.kafka.connect.storage.StringConverter
      CONNECT_VALUE_CONVERTER: org.apache.kafka.connect.converters.ByteArrayConverter
      CONNECT_INTERNAL_KEY_CONVERTER: 'org.apache.kafka.connect.storage.StringConverter'
      CONNECT_INTERNAL_VALUE_CONVERTER: 'org.apache.kafka.connect.json.JsonConverter'
      CONNECT_LOG4J_ROOT_LOGLEVEL: 'INFO'
      #CONNECT_LOG4J_LOGGERS: 'org.apache.kafka.connect.runtime.rest=DEBUG,org.reflections=ERROR'
      CONNECT_LOG4J_LOGGERS: 'org.apache.kafka.connect.runtime.rest=INFO,org.reflections=ERROR,org.eclipse.jetty.server=INFO'
      CONNECT_PLUGIN_PATH: '/usr/share/java,/usr/share/confluent-hub-components/,/data/connect-jars'
      CONNECT_PRODUCER_BOOTSTRAP_SERVERS: "cloudkafkanode:9094"
      CONNECT_PRODUCER_SECURITY_PROTOCOL: "SASL_SSL"
      CONNECT_PRODUCER_SASL_MECHANISM: "SCRAM-SHA-256"
      CONNECT_PRODUCER_SASL_JAAS_CONFIG: "org.apache.kafka.common.security.scram.ScramLoginModule required username=\"user\" password=\"password\";"

    command:
      # In the command section, $ are replaced with $$ to avoid the error 'Invalid interpolation format for "command" option'
      - bash
      - -c
      - |
        echo "Installing connector plugins"
        confluent-hub install --no-prompt confluentinc/kafka-connect-rabbitmq:1.1.1

        #
        echo "Launching Kafka Connect worker"
        /etc/confluent/docker/run &
        #
        sleep infinity

  rabbitmq:
    image: rabbitmq:3-management
    container_name: rabbitmq
    environment:
      RABBITMQ_DEFAULT_USER: user
      RABBITMQ_DEFAULT_PASS: password
      RABBITMQ_DEFAULT_VHOST: "/"
    ports:
      - '15672:15672'
      - '5672:5672'

The configurations that fixed the mentioned errors are:

      CONNECT_PRODUCER_BOOTSTRAP_SERVERS: "cloudkafkanode:9094"
      CONNECT_PRODUCER_SECURITY_PROTOCOL: "SASL_SSL"
      CONNECT_PRODUCER_SASL_MECHANISM: "SCRAM-SHA-256"
      CONNECT_PRODUCER_SASL_JAAS_CONFIG: "org.apache.kafka.common.security.scram.ScramLoginModule required username=\"user\" password=\"password\";"

I hope this will help others to fix same issue.


问:
reactjs how to filter / check if a any object in an array is present in another array of objects?
im facing the issue when trying to implement some conditional rendering. Here is the context:

the data:

```<code>groups_a : [
             {id:1} ,
             {id:2}
            ]

groups_b : [
             {id:1} ,
             {id:3}
            ]
</code>```

The condition:

I wish to be check each item in groups_b , whether they exist in groups_a . So in this case , the condition should return back true because groups_b has id:1 and so does groups_a

JSX :

```<code>            {###the condition ##
                         ?
            <Button>Approve</Button>
            :
            null
            }
</code>```

答:
You could do this assuming groupA/groupB to be array of object

const groupA = [{id:1}, {id:3}, {id:4}];
const groupB = [{id:1}, {id:3}];

const boolean = groupB.every(obj => groupA.find(aObj => obj.id === aObj.id));
console.log('Method 1:', boolean)
// this will be true if every object in B is included in A

// If these are extremely large arrays you can improve performance by converting groupA into obj, and then checking by that object

const groupAHashMap = groupA.reduce((acc, cur) => ({...acc, [cur.id]: true}), {});
const boolean2 = groupB.every(obj => groupAHashMap[obj.id]);
console.log('Method 2:', boolean2)```

Body:
im facing the issue when trying to implement some conditional rendering. Here is the context:

the data:

groups_a : [
             {id:1} ,
             {id:2}
            ]

groups_b : [
             {id:1} ,
             {id:3}
            ]

The condition:

I wish to be check each item in groups_b , whether they exist in groups_a . So in this case , the condition should return back true because groups_b has id:1 and so does groups_a

JSX :

            {###the condition ##
                         ?
            <Button>Approve</Button>
            :
            null
            }


问:
What should be the format in SimpleDateFormat to print date like this - 01-JUN-20 08.55.27.577984000 AM UTC?
I want to print the current date in this format -
01-JUN-20 08.55.27.577984000 AM UTC. Tried lot of formats in SimpleDateformat but none is working. What is the right way to print like this?</p>

答:
SimpleDateFormat

You can use the following pattern:

```<code>import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class TimeFormatting {
    public static void main(String[] args) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy hh.mm.ss.SSS a Z");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        String formatted = formatter.format(new Date(2015, 4, 4, 13, 7, 19)); //One example date
        System.out.println(formatted);
    }
}
</code>```

This will give the output 04-05-15 11.07.19.000 AM +0000 where +0000 equals to UTC.

Explanation of the pattern dd-MM-yy hh.mm.ss.SSS a Z:

dd = the day

MM = the month

yy = the year

hh = the hour

mm = the minute

ss = the second

SSS = the millisecond. There does not exist a reference to nanoseconds in SimpleDateFormat (see this answer).

a = to show AM/PM

Z = to show the timezone

Additional information

Please note: SimpleDateFormat is deprecated. You should use DateTimeFormatter. One big advantage is that you can also have the nanoseconds (n).

One example:

```<code>import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.ZoneOffset;

public class TimeFormatting {
  public static void main(String[] args) {
   ZonedDateTime time = ZonedDateTime.now(ZoneOffset.UTC);

   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy hh.mm.ss.n a 'UTC'").withZone(ZoneOffset.UTC);
   String timeDate = time.format(formatter);
   System.out.println(timeDate);
  }
}
</code>```

Edit:

If you want to have UTC instead of +0000 with SimpleDateFormat you can use dd-MM-yy hh.mm.ss.SSS a zzz instead.

Body:
SimpleDateFormat

You can use the following pattern:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class TimeFormatting {
    public static void main(String[] args) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy hh.mm.ss.SSS a Z");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        String formatted = formatter.format(new Date(2015, 4, 4, 13, 7, 19)); //One example date
        System.out.println(formatted);
    }
}

This will give the output 04-05-15 11.07.19.000 AM +0000 where +0000 equals to UTC.

Explanation of the pattern dd-MM-yy hh.mm.ss.SSS a Z:

dd = the day

MM = the month

yy = the year

hh = the hour

mm = the minute

ss = the second

SSS = the millisecond. There does not exist a reference to nanoseconds in SimpleDateFormat (see this answer).

a = to show AM/PM

Z = to show the timezone

Additional information

Please note: SimpleDateFormat is deprecated. You should use DateTimeFormatter. One big advantage is that you can also have the nanoseconds (n).

One example:

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.ZoneOffset;

public class TimeFormatting {
  public static void main(String[] args) {
   ZonedDateTime time = ZonedDateTime.now(ZoneOffset.UTC);

   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy hh.mm.ss.n a 'UTC'").withZone(ZoneOffset.UTC);
   String timeDate = time.format(formatter);
   System.out.println(timeDate);
  }
}

Edit:

If you want to have UTC instead of +0000 with SimpleDateFormat you can use dd-MM-yy hh.mm.ss.SSS a zzz instead.


问:
Need to convert a date 09/01/2009 to a CHAR TYPE FORMAT
I need to convert a date 09/01/2009 to a CHAR TYPE FORMAT. The result should have 6 digits.

I knew the TO_CHAR function does it,but its not working for me.

The Date is given as 03/06/08

```<code>SELECT TO_CHAR(030608, 'DD MONTH,YYYY')
 FROM dual;
</code>```

This gives errors-syntax mainly.

It is Oracle database and I have to get the STRING. For example a number like -'200901'

答:
Not sure what you are trying to achieve via the query mentioned, but you need to modify it to
this

```<code>select to_char(to_date('03062008','ddmmyyyy'),'yyyymm') from dual;
</code>```

OR

```<code>select to_char(to_date('030608','ddmmyy'),'yyyymm') from dual;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to convert a date 09/01/2009 to a CHAR TYPE FORMAT. The result should have 6 digits.

I knew the TO_CHAR function does it,but its not working for me.

The Date is given as 03/06/08

SELECT TO_CHAR(030608, 'DD MONTH,YYYY')
 FROM dual;

This gives errors-syntax mainly.

It is Oracle database and I have to get the STRING. For example a number like -'200901'

Body:
Not sure what you are trying to achieve via the query mentioned, but you need to modify it to
this

select to_char(to_date('03062008','ddmmyyyy'),'yyyymm') from dual;

OR

select to_char(to_date('030608','ddmmyy'),'yyyymm') from dual;


问:
Package Installer has stopped
I am developing some app for android which worked well untill this evening.
However the app is working well in emulator but on Archos 80 G9 tablet with android 3.2.80 I got this error

```<code>The application Package installer (process com.android.packageinstaller) has stopped unexpectedly. Please try again.
</code>```

Also here is my manifest XML

```<code>    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="oni.dani"
    android:versionCode="1"
    android:versionName="1.0" >

   <uses-sdk android:minSdkVersion="13"

          />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:debuggable="true"

         >
        <activity
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:name="com.android.onidani.Dashboard" >
            <intent-filter>
                            <action android:name="android.intent.action.MAIN" />
                            <category android:name="android.intent.category.LAUNCHER" />
                        </intent-filter>

        </activity>
        <activity android:name="com.android.onidani.KlasaPrikazBaze"></activity>
        <activity android:name="com.android.onidani.Dashboard"></activity>
        <activity android:name="com.android.onidani.OniDaniActivity"></activity>

    </application>

</manifest>
</code>```

答: in my situation i was passing empty array to requestPermissions. so check if your array is'not empty (String[] permissions)</p>

Title: Package Installer has stopped

Body:
I am developing some app for android which worked well untill this evening.
However the app is working well in emulator but on Archos 80 G9 tablet with android 3.2.80 I got this error

The application Package installer (process com.android.packageinstaller) has stopped unexpectedly. Please try again.

Also here is my manifest XML

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="oni.dani"
    android:versionCode="1"
    android:versionName="1.0" >

   <uses-sdk android:minSdkVersion="13"

          />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:debuggable="true"

         >
        <activity
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:name="com.android.onidani.Dashboard" >
            <intent-filter>
                            <action android:name="android.intent.action.MAIN" />
                            <category android:name="android.intent.category.LAUNCHER" />
                        </intent-filter>

        </activity>
        <activity android:name="com.android.onidani.KlasaPrikazBaze"></activity>
        <activity android:name="com.android.onidani.Dashboard"></activity>
        <activity android:name="com.android.onidani.OniDaniActivity"></activity>

    </application>

</manifest>