问:
How to replace undefined with null or treat it as false in javascript?
So I'm having this little generator, the info that get displayed should correspond to what values are populated on the database, the example below is a physical address

```<code>this.setState({
   companyEmail: json.data.companyEmail,
   company: json.data.company,
   line1: json.data.line1,
   line2: json.data.line2,
   city: json.data.city,
   ...
});
</code>```

So I could initialize those values with null, undefined or "" it does not matter, on the fetch request the typeof those empty values turn to undefined.

Firebase don't like that, for me it cause no issue, I could hide the element  by checking if it's true or false like so

```<code>{line1 && <span>{line1}<br /></span>}
{line2 && <span>{line2}<br /></span>}
</code>```

Well I mean it works until I tried updating the database, I got this error

Error: Reference.set failed: First argument contains undefined in
  property 'master.business.info.line2'

What I want to do is kindof turning undefined to null, because when sending null remove the child from the db, it's treated like a real value.

On the server side, it's regular db update

```<code>master.update({
   company: company,
   line1: line1,
   line2: line2,
   city: city,
   ...
})
.then(() => {
   response.sendStatus(200);
}).catch(function (err) {
   console.log(err);
   response.sendStatus(204);
});
</code>```

I could use if statement and setState accordingly but that's too much work. I need to make to fetch request because I need those values, it's a form to edit info.

Also using empty strings like "" is not good, it gets display inside span, paragraph or whatever.

This is not a duplicate, on react.js my goal is to not setState for undefined values and keep the init values on the constructor.

答:
Maybe if you change your setState like this:

const {companyEmail, company, line1, line2, city} = json.data;
this.setState({
   companyEmail,
   company,
   line1,
   line2,
   city,
   ...
});
```

<p>If any var doesn't have value, it doesn't add to state.</p>

<p>Here, you could check before update. Try something like this:</p>

<pre class="lang-js prettyprint-override"><code>const objUpdate = {
   company: company,
   line1: line1,
   line2: line2,
   city: city,
   ...
};
const cloneObjUpdate = {...objUpdate};
Object.keys(objUpdate).forEach(key=>{
    if(!Boolean(cloneObjUpdate[key])) delete cloneObjUpdate[key];
});

master.update(cloneObjUpdate);
</code>```

For keep object with null values, just remove delete and set a null value:

const objUpdate = {
   company: company,
   line1: line1,
   line2: line2,
   city: city,
   ...
};
const cloneObjUpdate = {...objUpdate};
Object.keys(objUpdate).forEach(key=>{
    if(!Boolean(cloneObjUpdate[key])) cloneObjUpdate[key] = null;
});
```

Body:
So I'm having this little generator, the info that get displayed should correspond to what values are populated on the database, the example below is a physical address

this.setState({
   companyEmail: json.data.companyEmail,
   company: json.data.company,
   line1: json.data.line1,
   line2: json.data.line2,
   city: json.data.city,
   ...
});

So I could initialize those values with null, undefined or "" it does not matter, on the fetch request the typeof those empty values turn to undefined.

Firebase don't like that, for me it cause no issue, I could hide the element  by checking if it's true or false like so

{line1 && {line1}
}
{line2 && {line2}
}

Well I mean it works until I tried updating the database, I got this error

Error: Reference.set failed: First argument contains undefined in
  property 'master.business.info.line2'

What I want to do is kindof turning undefined to null, because when sending null remove the child from the db, it's treated like a real value.

On the server side, it's regular db update

master.update({
   company: company,
   line1: line1,
   line2: line2,
   city: city,
   ...
})
.then(() => {
   response.sendStatus(200);
}).catch(function (err) {
   console.log(err);
   response.sendStatus(204);
});

I could use if statement and setState accordingly but that's too much work. I need to make to fetch request because I need those values, it's a form to edit info.

Also using empty strings like "" is not good, it gets display inside span, paragraph or whatever.

This is not a duplicate, on react.js my goal is to not setState for undefined values and keep the init values on the constructor.

Body:
Maybe if you change your setState like this:

const {companyEmail, company, line1, line2, city} = json.data;
this.setState({
   companyEmail,
   company,
   line1,
   line2,
   city,
   ...
});

If any var doesn't have value, it doesn't add to state.

Here, you could check before update. Try something like this:

const objUpdate = {
   company: company,
   line1: line1,
   line2: line2,
   city: city,
   ...
};
const cloneObjUpdate = {...objUpdate};
Object.keys(objUpdate).forEach(key=>{
    if(!Boolean(cloneObjUpdate[key])) delete cloneObjUpdate[key];
});

master.update(cloneObjUpdate);

For keep object with null values, just remove delete and set a null value:

const objUpdate = {
   company: company,
   line1: line1,
   line2: line2,
   city: city,
   ...
};
const cloneObjUpdate = {...objUpdate};
Object.keys(objUpdate).forEach(key=>{
    if(!Boolean(cloneObjUpdate[key])) cloneObjUpdate[key] = null;
});


来源: stackexchange

问:
How to load resources which are bundled in an executable jar file which was generated by maven?
I am trying to load my resources which I have bundled in a jar file.
Originally they where placed under src/main/resources/*.wav.

To generate my jar file I have used the maven-jar-plugin.
If I unpack the jar file I can see the resource files.

In my source code I am loading the files with

```<code>AudioSystem.getAudioInputStream(MyClass.class.getResourceAsStream("/my-file.wav"));
</code>```

When I run the application via IntelliJ this seems to work.
However when I try to execute the generated jar file the resources cannot be loaded.

Did I miss something? Maybe the classpath?

EDIT
My pom.xml has the following build property:

```<code>  <build>
    <finalName>${project.artifactId}</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
              <mainClass>MyMain</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <configuration>
          <mainClass>MyMain</mainClass>
        </configuration>
      </plugin>
    </plugins>
  </build>
</code>```

答:
I figured out what the problem was.
The problem has not been with maven.

It was the source code, which should be changed to:

```<code>URL url = this.getClass().getClassLoader().getResource("my-resource.wav");
AudioSystem.getAudioInputStream(url)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to load my resources which I have bundled in a jar file.
Originally they where placed under src/main/resources/*.wav.

To generate my jar file I have used the maven-jar-plugin.
If I unpack the jar file I can see the resource files.

In my source code I am loading the files with

AudioSystem.getAudioInputStream(MyClass.class.getResourceAsStream("/my-file.wav"));

When I run the application via IntelliJ this seems to work.
However when I try to execute the generated jar file the resources cannot be loaded.

Did I miss something? Maybe the classpath?

EDIT
My pom.xml has the following build property:

  <build>
    <finalName>${project.artifactId}</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
              <mainClass>MyMain</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <configuration>
          <mainClass>MyMain</mainClass>
        </configuration>
      </plugin>
    </plugins>
  </build>

Body:
I figured out what the problem was.
The problem has not been with maven.

It was the source code, which should be changed to:

URL url = this.getClass().getClassLoader().getResource("my-resource.wav");
AudioSystem.getAudioInputStream(url)


问:
Angular 2 conditional Validators.required?
How should I go about conditionally requiring a form field? I made a custom validator, but the conditional variables that I pass to the custom validator are static and remain their initial values. What should my custom validator look like to get updated conditional values? Perhaps there is a way to do this with Validators.required instead of a custom validator?

```<code>private foo: boolean = false;
private bar: boolean = true;

constructor(private _fb: FormBuilder) {
    function conditionalRequired(...conditions: boolean[]) {
      return (control: Control): { [s: string]: boolean } => {
        let required: boolean = true;
        for (var i = 0; i < conditions.length; i++) {
          if (conditions[i] === false) {
            required = false;
          }
        }
        if (required && !control.value) {
          return { required: true }
        }
      }
    }
    this.applyForm = _fb.group({
          'firstName': ['', Validators.compose([
            conditionalRequired(this.foo, !this.bar)
          ])],
          ...
    });
}
</code>```

Update (May 17, 2016)

It's been a long time since posting this, but I'd like to reference the .include() and .exclude() methods available on the ControlGroup class for anyone out there who is trying to create this functionality. (docs) While there are probably use cases for a conditional Validator like above, I've found the inclusion and exclusion of controls, control groups, and control arrays to be a great way to handle this. Just set the required validator on the control you'd like and include/exclude it as you please. Hope this helps someone!

答:
Simply use enable() and disable() methods on AbstractControl.

this.myControl.valueChanges.subscribe(
      checked => {
        if (checked) {
          this.otherControl.enable();
        } else {
          this.otherControl.disable();
        }
      }
    );
```

ContentLicense: CC BY-SA 3.0

Body:
How should I go about conditionally requiring a form field? I made a custom validator, but the conditional variables that I pass to the custom validator are static and remain their initial values. What should my custom validator look like to get updated conditional values? Perhaps there is a way to do this with Validators.required instead of a custom validator?

private foo: boolean = false;
private bar: boolean = true;

constructor(private _fb: FormBuilder) {
    function conditionalRequired(...conditions: boolean[]) {
      return (control: Control): { [s: string]: boolean } => {
        let required: boolean = true;
        for (var i = 0; i < conditions.length; i++) {
          if (conditions[i] === false) {
            required = false;
          }
        }
        if (required && !control.value) {
          return { required: true }
        }
      }
    }
    this.applyForm = _fb.group({
          'firstName': ['', Validators.compose([
            conditionalRequired(this.foo, !this.bar)
          ])],
          ...
    });
}

Update (May 17, 2016)

It's been a long time since posting this, but I'd like to reference the .include() and .exclude() methods available on the ControlGroup class for anyone out there who is trying to create this functionality. (docs) While there are probably use cases for a conditional Validator like above, I've found the inclusion and exclusion of controls, control groups, and control arrays to be a great way to handle this. Just set the required validator on the control you'd like and include/exclude it as you please. Hope this helps someone!


问:
Check whether string in palindrome : C# code efficiency
I am coming from C background and recently started writing in C# so please don't mind if my question seems somewhat basic. Basically, i want to write a function which will return true if string is palindrome and false if not.

The string may contain characters like space, ',', ':' which i have to ignore. I have written the code as below

```<code>    static bool IsPalindrome(string s)
    {
        s = s.Replace(" ", "");
        s = s.Replace(",", "");
        s = s.Replace(":", "");

        int j = s.Length - 1;

        for(int i = 0; i < s.Length/2; i++)
        {
            if(s[i].ToString().Equals(s[j].ToString(),StringComparison.InvariantCultureIgnoreCase))
            {
                j--;
            }
            else
            {
                return false;
            }
        }
        return true;

    }
</code>```

where the function will be invoked with the following string

```<code>string s = "A man, a plan, a canal: Panama";
</code>```

I read in the documentation that in C#, string are immutable so each time i do a operation like replace or ToString, a new copy is getting created.

So i wanted to check that
i).  Is this code efficient?
ii). If not, how to make it more efficient.

答:
This solution should be familiar to you if you're coming from a C background. There's no need to allocate a bunch of new strings; just ignore non-letter characters.

There doesn't seem to be a case-insensitive comparison of char values in .NET, so this code assumes that ToLower(...) with the current culture is sufficient.

```<code>public static bool EqualsIgnoreCase(char c1, char c2)
{
    var culture = System.Globalization.CultureInfo.CurrentCulture;
    return Char.ToLower(c1, culture) == Char.ToLower(c2, culture);
}

public static bool IsPalindrome(string s)
{
    switch (s?.Length ?? 0)
    {
        case 0:
            return false;
        case 1:
            return true;
        case 2:
            return EqualsIgnoreCase(s[0], s[1]);
        case 3:
            return EqualsIgnoreCase(s[0], s[2]);
    }

    var firstIndex = 0;
    var lastIndex = s.Length - 1;

    // todo: this probably falls on its face for a string with only non-letters
    do
    {
        while (!Char.IsLetter(s[firstIndex]))
            ++firstIndex;
        while (!Char.IsLetter(s[lastIndex]))
            --lastIndex;
        if (!EqualsIgnoreCase(s[firstIndex++], s[lastIndex--]))
            return false;

    } while (firstIndex < lastIndex);

    return true;
}
</code>```

Body:
I am coming from C background and recently started writing in C# so please don't mind if my question seems somewhat basic. Basically, i want to write a function which will return true if string is palindrome and false if not.

The string may contain characters like space, ',', ':' which i have to ignore. I have written the code as below

    static bool IsPalindrome(string s)
    {
        s = s.Replace(" ", "");
        s = s.Replace(",", "");
        s = s.Replace(":", "");

        int j = s.Length - 1;

        for(int i = 0; i < s.Length/2; i++)
        {
            if(s[i].ToString().Equals(s[j].ToString(),StringComparison.InvariantCultureIgnoreCase))
            {
                j--;
            }
            else
            {
                return false;
            }
        }
        return true;

    }

where the function will be invoked with the following string

string s = "A man, a plan, a canal: Panama";

I read in the documentation that in C#, string are immutable so each time i do a operation like replace or ToString, a new copy is getting created.

So i wanted to check that
i).  Is this code efficient?
ii). If not, how to make it more efficient.

Body:
This solution should be familiar to you if you're coming from a C background. There's no need to allocate a bunch of new strings; just ignore non-letter characters.

There doesn't seem to be a case-insensitive comparison of char values in .NET, so this code assumes that ToLower(...) with the current culture is sufficient.

public static bool EqualsIgnoreCase(char c1, char c2)
{
    var culture = System.Globalization.CultureInfo.CurrentCulture;
    return Char.ToLower(c1, culture) == Char.ToLower(c2, culture);
}

public static bool IsPalindrome(string s)
{
    switch (s?.Length ?? 0)
    {
        case 0:
            return false;
        case 1:
            return true;
        case 2:
            return EqualsIgnoreCase(s[0], s[1]);
        case 3:
            return EqualsIgnoreCase(s[0], s[2]);
    }

    var firstIndex = 0;
    var lastIndex = s.Length - 1;

    // todo: this probably falls on its face for a string with only non-letters
    do
    {
        while (!Char.IsLetter(s[firstIndex]))
            ++firstIndex;
        while (!Char.IsLetter(s[lastIndex]))
            --lastIndex;
        if (!EqualsIgnoreCase(s[firstIndex++], s[lastIndex--]))
            return false;

    } while (firstIndex < lastIndex);

    return true;
}


问:
Unable to send javascript variable to php file using ajax
I want to send a javascript variable to php file which shows the comments on a webpage.

I was able to send this js variable to some other php file, but I can't do it with this comment-list.php file. I guess there is some problem with JSON.

```<code>function listComment() {

        $.ajax({
            url: "Komentarji/comment-list.php",
            data : {page_num: page_num},
            type : 'post',
            success : function(response) {
            }
        });

        $.post("Komentarji/comment-list.php", function(data) {
                            var data = JSON.parse(data);
.
.
.
</code>```

The function is called here:

```<code>$(document).ready(function() {
        listComment();
    });
</code>```

Inside comment-list.php I try to get the variable that was sent with ajax. However it doesn't work and comment's aren't displayed on page. If I delete this line, the comments work again (but of course, I don't get the sent variable).

```<code>$num = $_POST['page_num'];

$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";

$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
    array_push($record_set, $row);
}
mysqli_free_result($result);

mysqli_close($conn);
echo json_encode($record_set);
</code>```

Here is the javascript variable and included php file.

```<code><script>
var page_num = 1;
</script>
<?php
include($_SERVER["DOCUMENT_ROOT"]."/index.php");
?>
</code>```

I get this error in console: Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse ()

As said eariler if I remove the line where I get the variable with post, this error disappears.

答:
Just make your format JSON in your JS script</p>

```<code>$.ajax({
    url : 'Komentarji/comment-list.php',
    type: "POST",
    data: page_num:page_num,
    dataType: "JSON",
    success: function(data)
    {
        console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown){
        console.log(errorThrown);
    }
});
</code>```

Body:
I want to send a javascript variable to php file which shows the comments on a webpage.

I was able to send this js variable to some other php file, but I can't do it with this comment-list.php file. I guess there is some problem with JSON.

function listComment() {

        $.ajax({
            url: "Komentarji/comment-list.php",
            data : {page_num: page_num},
            type : 'post',
            success : function(response) {
            }
        });

        $.post("Komentarji/comment-list.php", function(data) {
                            var data = JSON.parse(data);
.
.
.

The function is called here:

$(document).ready(function() {
        listComment();
    });

Inside comment-list.php I try to get the variable that was sent with ajax. However it doesn't work and comment's aren't displayed on page. If I delete this line, the comments work again (but of course, I don't get the sent variable).

$num = $_POST['page_num'];

$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";

$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
    array_push($record_set, $row);
}
mysqli_free_result($result);

mysqli_close($conn);
echo json_encode($record_set);

Here is the javascript variable and included php file.

<?php
include($_SERVER["DOCUMENT_ROOT"]."/index.php");
?>

I get this error in console: Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse ()

As said eariler if I remove the line where I get the variable with post, this error disappears.

Body:
Just make your format JSON in your JS script

$.ajax({
    url : 'Komentarji/comment-list.php',
    type: "POST",
    data: page_num:page_num,
    dataType: "JSON",
    success: function(data)
    {
        console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown){
        console.log(errorThrown);
    }
});


问:
How to set up a private Docker repository with Artifactory OSS?
I tried to set up a private docker repository using Artifactory OSS (open source version) but could not find how to do it. The online documentation is about using the licensed Artifactory product as a docker repository.

Does anyone know how to set it up in Artifactory OSS?

I installed and started Artifactory OSS, but could not find docker package information. The Package View feature is disabled in OSS version.

答:
According to the Artifactory Comparison Matrix, Artifactory OSS only supports Maven, Gradle and Ivy.

To use the Artifactory Docker package management you have to purchase Artifactory Pro, Artifactory Cloud or Artifactory Enterprise. Another solution is to use Nexus Repository OSS which include this feature in the open source version.


问:
array manipulation
So i'm trying to avoid using vectors to do this, i know it would make it easier, but i'm trying to better my understanding of pointers and arrays. So is there a way to expand and shift an array without using the vectors? Here is what i have so far:</p>

```<code>int *expand(int *&arr, int size)
{
    int *newArray;

    size = size * 2;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;

}
</code>```

答:
The simplest way to do what you want would be the standard library function realloc.

http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/

```<code>int* new_array = (int*) realloc (old_array, new_size * sizeof(int));
</code>```

Note the *sizeof(int). That's important :)

realloc makes sure the contents of *old_array* can be found in *new_array*(it's either the same pointer, or the contents are copied). See the link for details.

Title: array manipulation

Body:
So i'm trying to avoid using vectors to do this, i know it would make it easier, but i'm trying to better my understanding of pointers and arrays. So is there a way to expand and shift an array without using the vectors? Here is what i have so far:

int *expand(int *&arr, int size)
{
    int *newArray;

    size = size * 2;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;

}

Body:
The simplest way to do what you want would be the standard library function realloc.

http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/

int* new_array = (int*) realloc (old_array, new_size * sizeof(int));

Note the *sizeof(int). That's important :)

realloc makes sure the contents of *old_array* can be found in *new_array*(it's either the same pointer, or the contents are copied). See the link for details.


问:
Set mecanim animation playback time/position
I'm trying to set an animator's playback time.  (or, start an animation at a specific time)  I haven't had success with either approach.

Note: I am setting the Animator (an) in the Start().

Code I've tried:

```<code>Public Animator an;

public void SetTime(float time)
{
    an.playbackTime = time;
}
</code>```

答:
Oops, I guess this one was pretty easy!

I didn't see the constructor options for the Play() method!

The answer:

```<code>an.Play("YourAnimation", 0, 0.4f);
</code>```

However, I am still currious why my original code didn't work.  So I figured out how to make an animation play/start at a specific time... Does anyone know how to basically "rewind" an animation to a specific point? (while it's playing)

Body:
I'm trying to set an animator's playback time.  (or, start an animation at a specific time)  I haven't had success with either approach.

Note: I am setting the Animator (an) in the Start().

Code I've tried:

Public Animator an;

public void SetTime(float time)
{
    an.playbackTime = time;
}

Body:
Oops, I guess this one was pretty easy!

I didn't see the constructor options for the Play() method!

The answer:

an.Play("YourAnimation", 0, 0.4f);

However, I am still currious why my original code didn't work.  So I figured out how to make an animation play/start at a specific time... Does anyone know how to basically "rewind" an animation to a specific point? (while it's playing)


问:
Need to filter data rows where the data is past a certain month
Need to look at rows where the date columns is April only. However my data is in YYYY-MM-DD

How can I write a conditional to ensure month = 4 (April.)

答:
Assuming date in string format is stored in date_str column, and df is the Pandas dataframe.

# Convert string date to datetime
df['date'] = pd.to_datetime(df['date_str'], format='%Y-%m-%d')

# Select rows for April
df.loc[df['date'].dt.month == 4]
```


问:
WSJdbcConnection does not wrap any objects of type com.microsoft.sqlserver.jdbc.SQLServerConnection
I am using SQLServerBulkCopy API to store millions of records in SQL Server database. I get an error stating

"com.microsoft.sqlserver.jdbc.SQLServerException: Destination
  connection must be a connection from Microsoft JDBC Driver for SQL
  Server"

during initializing it like

```<code>SQLServerBulkCopy bulkCopy =  new SQLServerBulkCopy(conn);
</code>```

So I unwrapped the connection

```<code>SQLServerConnection conn = connection.unwrap(SQLServerConnection.class);
</code>```

The original connection is com.ibm.ws.rsadapter.jdbc.WSJdbcConnection@8da2f3e2

After going over the following questions previously asked

1. WSJDBCConnection does not wrap objects of type Oracle jdbc Connection

2. I get the `DSRA9122E: com.ibm.ws.rsadapter.jdbc.WSJdbcConnection@d3t7e556 does not wrap any objects of type oracle.jdbc.OracleConnection

I found that it is because of classLoader for sqljdbc42.jar,  mismatch between datasource and the application

So I changed my server.xml like this

```<code> <library id="global">
   <fileset dir="${server.config.dir}/lib/global" includes="*.jar"/>
 </library>

 <jdbcDriver id="SqlJdbcDriver"
                javax.sql.DataSource =
 "com.microsoft.sqlserver.jdbc.SQLServerConnectionPoolDataSource"
                 libraryRef="global"/>

 <application id="myApp" name="myApp" type="ear" location="myApp.ear">
   <classloader commonLibraryRef="global"/>
 </application>
</code>```

The datasource tag resides in another server.xml that is specific for env by env -

```<code><dataSource id="myDS" jdbcDriverRef="SqlJdbcDriver" jndiName="jdbc/myDS">
    <connectionManager agedTimeout="2m" connectionTimeout="2s" maxPoolSize="50" minPoolSize="0" />
    <properties.microsoft.sqlserver databaseName="myDB" serverName="xxx.com" />
</dataSource>
</code>```

The sqljdbc42.jar also resides in lib/global dir.

Also, I removed the dropins dir and placed the myApp in apps dir, as the application tag will not work if the app the present in dropins dir.

After all these changes too, I get the exception

"com.ibm.ws.rsadapter.jdbc.WSJdbcConnection@8155ea2d does not wrap any
  objects of type com.microsoft.sqlserver.jdbc.SQLServerConnection."

Can anybody figure out what's the solution or what still I am missing?

答:
The JDBC wrapper pattern, java.sql.Wrapper.unwrap(c), is for unwrapping as interface classes only, not concrete implementation classes.

com.microsoft.sqlserver.jdbc.SQLServerConnection is an implementation, but fortunately, the Microsoft JDBC Driver also provides an interface for it: com.microsoft.sqlserver.jdbc.ISQLServerConnection.

Try unwrapping as the interface,

```<code>ISQLServerConnection conn = connection.unwrap(ISQLServerConnection.class);
</code>```

Body:
I am using SQLServerBulkCopy API to store millions of records in SQL Server database. I get an error stating

"com.microsoft.sqlserver.jdbc.SQLServerException: Destination
  connection must be a connection from Microsoft JDBC Driver for SQL
  Server"

during initializing it like

SQLServerBulkCopy bulkCopy =  new SQLServerBulkCopy(conn);

So I unwrapped the connection

SQLServerConnection conn = connection.unwrap(SQLServerConnection.class);

The original connection is com.ibm.ws.rsadapter.jdbc.WSJdbcConnection@8da2f3e2

After going over the following questions previously asked

1. WSJDBCConnection does not wrap objects of type Oracle jdbc Connection

2. I get the `DSRA9122E: com.ibm.ws.rsadapter.jdbc.WSJdbcConnection@d3t7e556 does not wrap any objects of type oracle.jdbc.OracleConnection

I found that it is because of classLoader for sqljdbc42.jar,  mismatch between datasource and the application

So I changed my server.xml like this

 <library id="global">
   <fileset dir="${server.config.dir}/lib/global" includes="*.jar"/>
 </library>

 <jdbcDriver id="SqlJdbcDriver"
                javax.sql.DataSource =
 "com.microsoft.sqlserver.jdbc.SQLServerConnectionPoolDataSource"
                 libraryRef="global"/>

 <application id="myApp" name="myApp" type="ear" location="myApp.ear">
   <classloader commonLibraryRef="global"/>
 </application>

The datasource tag resides in another server.xml that is specific for env by env -

<dataSource id="myDS" jdbcDriverRef="SqlJdbcDriver" jndiName="jdbc/myDS">
    <connectionManager agedTimeout="2m" connectionTimeout="2s" maxPoolSize="50" minPoolSize="0" />
    <properties.microsoft.sqlserver databaseName="myDB" serverName="xxx.com" />
</dataSource>

The sqljdbc42.jar also resides in lib/global dir.

Also, I removed the dropins dir and placed the myApp in apps dir, as the application tag will not work if the app the present in dropins dir.

After all these changes too, I get the exception

"com.ibm.ws.rsadapter.jdbc.WSJdbcConnection@8155ea2d does not wrap any
  objects of type com.microsoft.sqlserver.jdbc.SQLServerConnection."

Can anybody figure out what's the solution or what still I am missing?

Body:
The JDBC wrapper pattern, java.sql.Wrapper.unwrap(c), is for unwrapping as interface classes only, not concrete implementation classes.

com.microsoft.sqlserver.jdbc.SQLServerConnection is an implementation, but fortunately, the Microsoft JDBC Driver also provides an interface for it: com.microsoft.sqlserver.jdbc.ISQLServerConnection.

Try unwrapping as the interface,

ISQLServerConnection conn = connection.unwrap(ISQLServerConnection.class);


答:
You shouldn't use $.ajax and $.post to do the same thing, pick one, I'd say remove the $.post one and dont forget to put an exit; statement after you echo the response to avoid PHP to process further code if existing, also worth mentionning but not necessary, you can put the dataType to json so dataType: 'json' in the $.ajax call, dataType is used to tell jQuery what to expect as a response type from the server, as you are echoing the response by encoding it in JSON, you won't need to parse the response on your JS side if you speficied the dataType beforehand.

```<code> $.ajax({
        url: "Komentarji/comment-list.php",
        data : {page_num: page_num},
        type : 'post',
        dataType: 'json',
        success : function(response) {
            console.log(response); //will show the result of echo json_encode($record_set); from your PHP
        }
    });

$num = $_POST['page_num'];

$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";

$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
    array_push($record_set, $row);
}
mysqli_free_result($result);

mysqli_close($conn);
echo json_encode($record_set);
exit; //exit statement here
</code>```

Following discussion with OP who wanted to use the $.post method, this is how it is done, pass the data as an object to the second attribute (more infos here):

```<code>$.post("Komentarji/comment-list.php", {page_num: page_num});
</code>```

Title: Unable to send javascript variable to php file using ajax

Body:
You shouldn't use $.ajax and $.post to do the same thing, pick one, I'd say remove the $.post one and dont forget to put an exit; statement after you echo the response to avoid PHP to process further code if existing, also worth mentionning but not necessary, you can put the dataType to json so dataType: 'json' in the $.ajax call, dataType is used to tell jQuery what to expect as a response type from the server, as you are echoing the response by encoding it in JSON, you won't need to parse the response on your JS side if you speficied the dataType beforehand.

 $.ajax({
        url: "Komentarji/comment-list.php",
        data : {page_num: page_num},
        type : 'post',
        dataType: 'json',
        success : function(response) {
            console.log(response); //will show the result of echo json_encode($record_set); from your PHP
        }
    });

$num = $_POST['page_num'];

$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";

$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
    array_push($record_set, $row);
}
mysqli_free_result($result);

mysqli_close($conn);
echo json_encode($record_set);
exit; //exit statement here

Following discussion with OP who wanted to use the $.post method, this is how it is done, pass the data as an object to the second attribute (more infos here):

$.post("Komentarji/comment-list.php", {page_num: page_num});


问:
Codeigniter project - trying to view the index page (main page in application) using XAMPP
In XAMPP and my current setup I can simply type in https://www.localhost:1234/testsite, and it will automatically load the index.php page in the directory testsite, and display it on the screen.

With codeigniter, I understand the routing is more complex, and I don't know what to do, as a complete beginner, to view the main index page.

The index page that I want to be the home (i.e loaded on typing in https://www.localhost:1234/public_html) is located in C:\xampp\htdocs\public_html\application\views\home\index.php

Can someone please suggest what I need to do to get this working?

I have tried this: https://www.localhost:1234/public_html/application/views/home .but it doesn't work

The .htaccess file, and yes this is a fully fledged hosted site, is as below: What do I need to change here, or can I delete it for working on localhost?

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

# force ssl
RewriteCond     %{SERVER_PORT} ^80$
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule     ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
</code>```

What do I need to type in the URL, or change in the .htaccess file, or somewhere else to simply load the index file as shown above?

I assume a change needs to be made to these two lines, but I'm not sure what?

```<code>RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
</code>```

would the https:///www.%HTTP_HOST} be changed to localhost:1234?

Also, I'm aware of the format as described on the codeigniter website:

https://www.localhost:1234/public_html/home/index/index.php

doesn't work either,

where home is the controller (in application) and index is the function, see below:

```<code>class Home extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('homes');

    }

    public function index()
    {
        //$key = $config['encryption_key'];
        $this->load->view('template/header.php');
        $this->load->view('home/index.php');
        $this->load->view('template/footer.php');
    }
</code>```

I also tried localhost:1234/index.php/home/index as suggested below, to no avail.

答:
Based on your .htaccess I'm assuming this is a fully developed site and not just a blank CodeIgniter install. As such most of your .htaccess rules reference a remote or live site.

I cannot speak for your current setup, but basically by default with no .htaccess CI works as follows.

If you have a controller in application/controllers/ called Test.php and a sub function called some_method then the url is localhost/index.php/test/some_method

In default CodeIgniter installs the index is at localhost/index.php or localhost/index.php/index. The welcome controller you see in default installs actually references controllers/welcome yet although you can access it via localhost/index.php/welcome you can also access it via localhost/index.php and this is where routes/default controllers come in to play. Explaining routes in depth is a bit outside of the scope of stack, but you can find more information here: https://www.codeigniter.com/user_guide/general/routing.html

Being new to CI I can say that the documentation is quite good and you should take your time to understand the architecture before going forward.

If you wish to remove index.php and just see localhost/test/some_method you need some .htaccess rules https://www.codeigniter.com/userguide3/general/urls.html#removing-the-index-php-file

Body:
In XAMPP and my current setup I can simply type in https://www.localhost:1234/testsite, and it will automatically load the index.php page in the directory testsite, and display it on the screen.

With codeigniter, I understand the routing is more complex, and I don't know what to do, as a complete beginner, to view the main index page.

The index page that I want to be the home (i.e loaded on typing in https://www.localhost:1234/public_html) is located in C:\xampp\htdocs\public_html\application\views\home\index.php

Can someone please suggest what I need to do to get this working?

I have tried this: https://www.localhost:1234/public_html/application/views/home .but it doesn't work

The .htaccess file, and yes this is a fully fledged hosted site, is as below: What do I need to change here, or can I delete it for working on localhost?

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

# force ssl
RewriteCond     %{SERVER_PORT} ^80$
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule     ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

What do I need to type in the URL, or change in the .htaccess file, or somewhere else to simply load the index file as shown above?

I assume a change needs to be made to these two lines, but I'm not sure what?

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

would the https:///www.%HTTP_HOST} be changed to localhost:1234?

Also, I'm aware of the format as described on the codeigniter website:

https://www.localhost:1234/public_html/home/index/index.php

doesn't work either,

where home is the controller (in application) and index is the function, see below:

class Home extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('homes');

    }

    public function index()
    {
        //$key = $config['encryption_key'];
        $this->load->view('template/header.php');
        $this->load->view('home/index.php');
        $this->load->view('template/footer.php');
    }

I also tried localhost:1234/index.php/home/index as suggested below, to no avail.


Title: Need to filter data rows where the data is past a certain month

Body:
Need to look at rows where the date columns is April only. However my data is in YYYY-MM-DD

How can I write a conditional to ensure month = 4 (April.)

Body:
Assuming that this is your starting point:

df = pd.DataFrame({
    "x": np.random.rand(13),
    "date": pd.date_range("2019-03-01", "2019-05-31", freq="W")
})

#            x       date
# 0   0.493852 2019-03-03
# 1   0.335280 2019-03-10
# 2   0.892476 2019-03-17
# 3   0.612119 2019-03-24
# 4   0.446722 2019-03-31
# 5   0.236843 2019-04-07
# 6   0.413819 2019-04-14
# 7   0.228923 2019-04-21
# 8   0.401895 2019-04-28
# 9   0.183924 2019-05-05
# 10  0.457840 2019-05-12
# 11  0.490073 2019-05-19
# 12  0.224978 2019-05-26

...you can simply do:

df.date.dt.month == 4

# 0     False
# 1     False
# 2     False
# 3     False
# 4     False
# 5      True
# 6      True
# 7      True
# 8      True
# 9     False
# 10    False
# 11    False
# 12    False
# Name: date, dtype: bool


问:
Are all packages from package.json included in React build?
I created a react app that both server and client shares the same package.json:

```<code>├───build
│   └───static
│       ├───css
│       ├───js
│       └───media
├───server (backend code)
├───src (client code)
├───package.json (shared)
</code>```

My question is very simple, are all packages from package.json included in the final production React build?

For example, I use express for server. Is it included in the React build?

If so, is there any way to avoid it? Or did I choose a wrong architecture?

Edit:

Im using create-react-app, default mode

答:
Im not sure about combining the package.json for both your express and React app, I dont see an advantage to doing this since React uses webpack and combining the express server might mess up some of the default settings, I will share with you how I do it.

When you are in a development build you will have 2 separate apps running independently. Both the create-react-app and the node/express server will be running independently of each other and they will have their own separate package.json.

In production however you will run npm run build on your React app and it will be served as a static file from your express server. A built React app does not have a package.json

I have implemented both of these scenarios you can check it out here

Dev build:
https://github.com/iqbal125/react_hooks_fullstack_skeleton

Produiction Build:
https://github.com/iqbal125/react-prod9

Body:
I created a react app that both server and client shares the same package.json:

├───build
│   └───static
│       ├───css
│       ├───js
│       └───media
├───server (backend code)
├───src (client code)
├───package.json (shared)

My question is very simple, are all packages from package.json included in the final production React build?

For example, I use express for server. Is it included in the React build?

If so, is there any way to avoid it? Or did I choose a wrong architecture?

Edit:

Im using create-react-app, default mode


问:
Silverlight - Bing Maps Control - Clustering of Pushpins
I use the Bing Maps Control and try to cluster Pushpins which are near together on the screen.
Do somebody know a finished Solution for this ?
I only can find solutions for the AJAX Control:
http://blogs.msdn.com/b/keithkin/archive/2009/03/07/customizing-pushpin-clustering-with-virtual-earth-map-control-api.aspx

My Approach:
Basically i loop through all items, determine the Size of them and add them to the layer or not.

That works principally, but if i want to add 1.000.000 items, i create 1.000.000 UIElements to get the Size of them and that is really slow (And needs much memory!) Is there any other approach ?

答:
I have not used it yet personally, but I have found a 3 part article concerning Server-Side Clustering, which for over 5000 data points would be the better choice than client side.

http://jkebeck.wordpress.com/?s=cluster

ContentLicense: CC BY-SA 2.5


问:
Japanese characters won't appear when printed
I am printing Unicode characters in python. All of the symbols I have used so far work except for Japanese characters. When I print the characters, it only shows the "question mark in a box" symbol. How can I fix this?

When I first countered the problem I thought it might be python. I searched Google, but I found almost nothing.
Then I wondered if it was Command Prompt. (I use Command Prompt to test my code.) No relevant results.
For my code, I use a list made of the Unicode characters so I won't have to look up and type the specific code. This is what it looks like.

```<code>UD = [u"\u3053", u"\u3093", u"\u306B", u"\u3061", u"\u306F"]
UDTemp = UD[0] + UD[1] + UD[2] + UD[3] + UD[4]
print(UDTemp)
</code>```

When printing, I expected "こんにちは", but instead I got the weird symbols.

答:
The font has to support the characters.  For example, I have east Asia IMEs installed on a US Windows 10 system, which make available fonts that support Japanese:

To obtain the fonts you want, it is easiest to add the language support for the desired language in Window 10.  To add a language, search for "Language settings":

Once the language is installed, fonts supporting that language will appear in the Console properties, and IMEs will be installed so you can type in that language if you know how to use them.

Body:
I am printing Unicode characters in python. All of the symbols I have used so far work except for Japanese characters. When I print the characters, it only shows the "question mark in a box" symbol. How can I fix this?

When I first countered the problem I thought it might be python. I searched Google, but I found almost nothing.
Then I wondered if it was Command Prompt. (I use Command Prompt to test my code.) No relevant results.
For my code, I use a list made of the Unicode characters so I won't have to look up and type the specific code. This is what it looks like.

UD = [u"\u3053", u"\u3093", u"\u306B", u"\u3061", u"\u306F"]
UDTemp = UD[0] + UD[1] + UD[2] + UD[3] + UD[4]
print(UDTemp)

When printing, I expected "こんにちは", but instead I got the weird symbols.


问:
How to set the background color of a Row() in Flutter?
I'm trying to set up a background color for a Row() widget, but Row itself has no background color or color attribute. I've been able to set the background color of a container to grey, right before the purple-backgrounded text, but the text itself does not fill the background completely and the following spacer does not take any color at all.

So how can I have the Row background set to the "HexColor(COLOR_LIGHT_GREY)" value so it spans over the whole row?

Any idea? Thanks a lot!

Here's the code that I have so far:

```<code>import 'package:flutter/material.dart';
import '../manager/ShoppingListManager.dart';
import '../model/ShoppingListModel.dart';
import '../hexColor.dart';
import '../Constants.dart';

class ShoppingListWidget extends StatelessWidget {
  final Color color = Colors.amberAccent;
  final int shoppingListIndex;

  ShoppingListWidget({this.shoppingListIndex});

  @override
  Widget build(BuildContext context) {
    ShoppingListManager slm = new ShoppingListManager();
    String shoppingListName =
        slm.myShoppingLists.shoppingLists[shoppingListIndex].name;
    int categoryCount =
        slm.myShoppingLists.shoppingLists[shoppingListIndex].categories.length;

    return Scaffold(
      appBar: AppBar(
        title: Text(shoppingListName),
        automaticallyImplyLeading: true,
      ),
      body: ListView.builder(
        itemBuilder: (context, index) {
          Category cat = slm.myShoppingLists.shoppingLists[shoppingListIndex]
              .categories[index];

          return Container(
            decoration: new BoxDecoration(
              border: new Border.all(color: Colors.grey[500]),
              color: Colors.white,
            ),
            child: new Column(
              children: <Widget>[
                getCategoryWidget(context, cat),
                getCategoryItems(context, cat),
              ],
            ),
          );
        },
        itemCount: categoryCount,
      ),
    );
  }

  // Render the category "headline" row where I want to set the background color
  // to HexColor(COLOR_LIGHT_GREY)
  Widget getCategoryWidget(BuildContext context, Category cat) {
    return new Row(
      children: <Widget>[
        new Container(height: 40.0, width: 10.0, color: HexColor(cat.color)),
        new Container(
            height: 40.0, width: 15.0, color: HexColor(COLOR_LIGHT_GREY)),
        new Container(
          child: new Text("Category", textAlign: TextAlign.start,
            style: TextStyle(
                fontFamily: 'Bold',
                fontSize: 18.0,
                color: Colors.black),
          ),
          decoration: new BoxDecoration(
            color: Colors.purple,
          ),
          height: 40.0,
        ),
        Spacer(),

        CircleAvatar(
          backgroundImage:
              new AssetImage('assets/icons/food/food_settings.png'),
          backgroundColor: HexColor(COLOR_LIGHT_GREY),
          radius: 15.0,
        ),
        new Container(height: 15.0, width: 10.0, color: Colors.transparent),
      ],
    );
  }

  // render the category items
  Widget getCategoryItems(BuildContext context, Category cat) {
    return ListView.builder(
      itemBuilder: (context, index) {
        String itemName = "Subcategory";
        return new Row(children: <Widget>[
          new Container(height: 40.0, width: 5.0, color: HexColor(cat.color)),
          new Container(height: 40.0, width: 20.0, color: Colors.white),
          new Container(
            child: new Text(itemName),
              color: Colors.white,
          ),
          Spacer()
        ]);
      },
      itemCount: cat.items.length,
      shrinkWrap: true,
      physics:
          ClampingScrollPhysics(),
    );
  }

}
</code>```

答:
Just wrap your Row with a Container with colour  property like below: </p>

```<code>   Container(
            color: Colors.black,
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Text('Demo', style: TextStyle(color: Colors.white),),
                )
              ],
            ),
          )
</code>```

Body:
I'm trying to set up a background color for a Row() widget, but Row itself has no background color or color attribute. I've been able to set the background color of a container to grey, right before the purple-backgrounded text, but the text itself does not fill the background completely and the following spacer does not take any color at all.

So how can I have the Row background set to the "HexColor(COLOR_LIGHT_GREY)" value so it spans over the whole row?

Any idea? Thanks a lot!

Here's the code that I have so far:

import 'package:flutter/material.dart';
import '../manager/ShoppingListManager.dart';
import '../model/ShoppingListModel.dart';
import '../hexColor.dart';
import '../Constants.dart';

class ShoppingListWidget extends StatelessWidget {
  final Color color = Colors.amberAccent;
  final int shoppingListIndex;

  ShoppingListWidget({this.shoppingListIndex});

  @override
  Widget build(BuildContext context) {
    ShoppingListManager slm = new ShoppingListManager();
    String shoppingListName =
        slm.myShoppingLists.shoppingLists[shoppingListIndex].name;
    int categoryCount =
        slm.myShoppingLists.shoppingLists[shoppingListIndex].categories.length;

    return Scaffold(
      appBar: AppBar(
        title: Text(shoppingListName),
        automaticallyImplyLeading: true,
      ),
      body: ListView.builder(
        itemBuilder: (context, index) {
          Category cat = slm.myShoppingLists.shoppingLists[shoppingListIndex]
              .categories[index];

          return Container(
            decoration: new BoxDecoration(
              border: new Border.all(color: Colors.grey[500]),
              color: Colors.white,
            ),
            child: new Column(
              children: <Widget>[
                getCategoryWidget(context, cat),
                getCategoryItems(context, cat),
              ],
            ),
          );
        },
        itemCount: categoryCount,
      ),
    );
  }

  // Render the category "headline" row where I want to set the background color
  // to HexColor(COLOR_LIGHT_GREY)
  Widget getCategoryWidget(BuildContext context, Category cat) {
    return new Row(
      children: <Widget>[
        new Container(height: 40.0, width: 10.0, color: HexColor(cat.color)),
        new Container(
            height: 40.0, width: 15.0, color: HexColor(COLOR_LIGHT_GREY)),
        new Container(
          child: new Text("Category", textAlign: TextAlign.start,
            style: TextStyle(
                fontFamily: 'Bold',
                fontSize: 18.0,
                color: Colors.black),
          ),
          decoration: new BoxDecoration(
            color: Colors.purple,
          ),
          height: 40.0,
        ),
        Spacer(),

        CircleAvatar(
          backgroundImage:
              new AssetImage('assets/icons/food/food_settings.png'),
          backgroundColor: HexColor(COLOR_LIGHT_GREY),
          radius: 15.0,
        ),
        new Container(height: 15.0, width: 10.0, color: Colors.transparent),
      ],
    );
  }

  // render the category items
  Widget getCategoryItems(BuildContext context, Category cat) {
    return ListView.builder(
      itemBuilder: (context, index) {
        String itemName = "Subcategory";
        return new Row(children: <Widget>[
          new Container(height: 40.0, width: 5.0, color: HexColor(cat.color)),
          new Container(height: 40.0, width: 20.0, color: Colors.white),
          new Container(
            child: new Text(itemName),
              color: Colors.white,
          ),
          Spacer()
        ]);
      },
      itemCount: cat.items.length,
      shrinkWrap: true,
      physics:
          ClampingScrollPhysics(),
    );
  }

}

Body:
Just wrap your Row with a Container with colour  property like below:

   Container(
            color: Colors.black,
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Text('Demo', style: TextStyle(color: Colors.white),),
                )
              ],
            ),
          )


问:
Vertical alignment of MaterialUI Grid items that exist in different Grid containers
I need to execute on a design that calls for three vertical columns. The first and last columns contain MaterialUI cards and the middle column contains a vertical line with dots that are vertically aligned with the start of each of the cards. The heights of the cards themselves are not fixed. I've attached a minified screenshot of the design.

Here is the layout that I have:

<Grid container>
    <Grid item xs={5}>
        <Grid container direction={"column"}>
            cards...
        </Grid>
    </Grid>
    <Grid item xs={2}>
        vertical line...
    </Grid>
    <Grid item xs={5}>
        <Grid container direction={"column"}>
            cards...
        </Grid>
    </Grid>
</Grid>
```

I need to be able to vertically align the cards and the vertical divider line (with dots) as shown in the attached screenshot. However, it's very unclear how one could render elements dependently that exist in different Grid containers.

Design screenshot:

答:
maybe work...

// Add your dot icon in ::before in css file

<Grid container>
    <Grid item xs={6} style={{borderLeft: '1px solid #ccc'>
        <Grid container direction={"column"}>
        // for each item

              <Card />

    enter code here
        </Grid>
    </Grid>
    <Grid item xs={6} style={{borderRight: '1px solid #ccc'>
        <Grid container direction={"column"}>
           // for each item - Like LeftColumns

              <Card />

        </Grid>
    </Grid>
</Grid>```

Body:
I need to execute on a design that calls for three vertical columns. The first and last columns contain MaterialUI cards and the middle column contains a vertical line with dots that are vertically aligned with the start of each of the cards. The heights of the cards themselves are not fixed. I've attached a minified screenshot of the design.

Here is the layout that I have:

<Grid container>
    <Grid item xs={5}>
        <Grid container direction={"column"}>
            cards...
        </Grid>
    </Grid>
    <Grid item xs={2}>
        vertical line...
    </Grid>
    <Grid item xs={5}>
        <Grid container direction={"column"}>
            cards...
        </Grid>
    </Grid>
</Grid>

I need to be able to vertically align the cards and the vertical divider line (with dots) as shown in the attached screenshot. However, it's very unclear how one could render elements dependently that exist in different Grid containers.

Design screenshot:

Body:
maybe work...

// Add your dot icon in ::before in css file
<style>
  leftColumns::before {
    display: ' ';
    position:absolute;
    background: '...';
    top: 0;
    left: 0;
  }
  leftColumns {
  position:relative;
  }
  /* Repeat for RightColumns */

</style>
<Grid container>
    <Grid item xs={6} style={{borderLeft: '1px solid #ccc'>
        <Grid container direction={"column"}>
        // for each item
           <div className="leftColumns" style={{padding: '0 10px'}}>
              <Card />
           </div>

    enter code here
        </Grid>
    </Grid>
    <Grid item xs={6} style={{borderRight: '1px solid #ccc'>
        <Grid container direction={"column"}>
           // for each item - Like LeftColumns
           <div className="RightColumns" style={{padding: '0 10px'}}>
              <Card />
           </div>
        </Grid>
    </Grid>
</Grid>


问:
SQL join with another table results in duplicate records
I'm trying to join two tables.

Table A:

```<code>RowID   Name        Active
4       Bangalore   1
</code>```

Table B:

```<code>Sno  RowID  Type     Stores      Active
1    4      Legal    Center-A    1
2    4      Trade    Center-A01  1
3    5      Trade    Center-B    1
</code>```

Here RowID is a foreign key for Table A.
If the Type is Legal then LegalName should be Center_A and
If the Type is Trade then TradeName should be Center_A01

This is what I tried and but I'm getting two rows one for Legal and other for Trade Type.

```<code>Name        Type      LegalName  TradeName
Bangalore   Legal     Center-A   Center-A01
Bangalore   Trade     Center-A   Center-A01
</code>```

What I really need is something like below

```<code> Name        LegalName  TradeName
 Bangalore   Center-A   Center-A01
</code>```

Do I need to use CASE in this case? Any help would be greatly appreciated.

答:
To achieve this you can make 2 joins, one for trade and second for legal.

```<code>select
     a.[Name]
    ,legal.[Stores] as LegalName
    ,trade.[Stores] as TradeName
from TableA a
join TableB trade
    on a.RowID = trade.RowID
    and trade.[Type] = 'Legal'
join TableB legal
    on a.RowID = legal.RowID
    and trade.[Type] = 'Trade'
</code>```

Body:
I'm trying to join two tables.

Table A:

RowID   Name        Active
4       Bangalore   1

Table B:

Sno  RowID  Type     Stores      Active
1    4      Legal    Center-A    1
2    4      Trade    Center-A01  1
3    5      Trade    Center-B    1

Here RowID is a foreign key for Table A.
If the Type is Legal then LegalName should be Center_A and
If the Type is Trade then TradeName should be Center_A01

This is what I tried and but I'm getting two rows one for Legal and other for Trade Type.

Name        Type      LegalName  TradeName
Bangalore   Legal     Center-A   Center-A01
Bangalore   Trade     Center-A   Center-A01

What I really need is something like below

 Name        LegalName  TradeName
 Bangalore   Center-A   Center-A01

Do I need to use CASE in this case? Any help would be greatly appreciated.

Body:
To achieve this you can make 2 joins, one for trade and second for legal.

select
     a.[Name]
    ,legal.[Stores] as LegalName
    ,trade.[Stores] as TradeName
from TableA a
join TableB trade
    on a.RowID = trade.RowID
    and trade.[Type] = 'Legal'
join TableB legal
    on a.RowID = legal.RowID
    and trade.[Type] = 'Trade'


问:
How to refresh CrystalReportViewer in WPF - VB.NET?
Any Know how to refresh CrystalReportViwer in wpf - vb.net?
I have two CrystalReports, first is working great but on a second I need to click refresh button to show correct data in Crystalreport viewer.

I tried to Discard Saved Data When Loading Reports but didn't helped me.

Public Class Izvjesce

```<code>Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    'dinamički učitati crystal report iz baze podataka
    Dim cryRpt As New ReportDocument

    Dim CrTables As Tables
    Dim crtableLogoninfo As New TableLogOnInfo
    Dim crConnectionInfo As New ConnectionInfo
    ' za dodati labele na crystal report
    Dim txtID As String = lblIDBroj.Content
    Dim txtPoduzece As String = lblPoduzece.Content

    cryRpt.Load("C:\Users\Stjepan Juric\source\repos\Plata\Plata\CrystalReport1.rpt")

    With crConnectionInfo
        .ServerName = lblPath.Content.ToString()
        '.DatabaseName = ""
        '.UserID = ""
        'Password = "password"
    End With

    CrTables = cryRpt.Database.Tables
    For Each CrTable In CrTables
        crtableLogoninfo = CrTable.LogOnInfo
        crtableLogoninfo.ConnectionInfo = crConnectionInfo
        CrTable.ApplyLogOnInfo(crtableLogoninfo)
    Next

    cryRpt.SetParameterValue("TxtID", txtID)
    cryRpt.SetParameterValue("txtNaziv", txtPoduzece)
    cr1.ViewerCore.ReportSource = cryRpt

End Sub

Private Sub Button_Click_1(sender As Object, e As RoutedEventArgs)

    'dinamički učitati crystal report iz baze podataka
    Dim rep2 As New ReportDocument

    Dim CrTables As Tables
    Dim crtableLogoninfo As New TableLogOnInfo
    Dim crConnectionInfo As New ConnectionInfo
    ' za dodati labele na crystal report
    'Dim txtID As String = lblIDBroj.Content
    'Dim txtPoduzece As String = lblPoduzece.Content

    rep2.Load("C:\Users\Stjepan Juric\source\repos\Plata\Plata\CrystalReport2.rpt")

    With crConnectionInfo
        .ServerName = lblPath.Content.ToString()
        '.DatabaseName = ""
        '.UserID = ""
        'Password = "password"
    End With

    CrTables = rep2.Database.Tables
    For Each CrTable In CrTables
        crtableLogoninfo = CrTable.LogOnInfo
        crtableLogoninfo.ConnectionInfo = crConnectionInfo
        CrTable.ApplyLogOnInfo(crtableLogoninfo)
    Next

    'cryRpt.SetParameterValue("TxtID", txtID)
    'cryRpt.SetParameterValue("txtNaziv", txtPoduzece)

    cr1.ViewerCore.ReportSource = rep2

End Sub
</code>```

End Class

答:
I found what is problem.
Just add rep2.refresh to resolve it.</p>

```<code>rep2.Load("C:\Users\Stjepan Juric\source\repos\Plata\Plata\CrystalReport2.rpt")
rep2.Refresh()
</code>```

Body:
Any Know how to refresh CrystalReportViwer in wpf - vb.net?
I have two CrystalReports, first is working great but on a second I need to click refresh button to show correct data in Crystalreport viewer.

I tried to Discard Saved Data When Loading Reports but didn't helped me.

Public Class Izvjesce

Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    'dinamički učitati crystal report iz baze podataka
    Dim cryRpt As New ReportDocument

    Dim CrTables As Tables
    Dim crtableLogoninfo As New TableLogOnInfo
    Dim crConnectionInfo As New ConnectionInfo
    ' za dodati labele na crystal report
    Dim txtID As String = lblIDBroj.Content
    Dim txtPoduzece As String = lblPoduzece.Content

    cryRpt.Load("C:\Users\Stjepan Juric\source\repos\Plata\Plata\CrystalReport1.rpt")

    With crConnectionInfo
        .ServerName = lblPath.Content.ToString()
        '.DatabaseName = ""
        '.UserID = ""
        'Password = "password"
    End With

    CrTables = cryRpt.Database.Tables
    For Each CrTable In CrTables
        crtableLogoninfo = CrTable.LogOnInfo
        crtableLogoninfo.ConnectionInfo = crConnectionInfo
        CrTable.ApplyLogOnInfo(crtableLogoninfo)
    Next

    cryRpt.SetParameterValue("TxtID", txtID)
    cryRpt.SetParameterValue("txtNaziv", txtPoduzece)
    cr1.ViewerCore.ReportSource = cryRpt

End Sub

Private Sub Button_Click_1(sender As Object, e As RoutedEventArgs)

    'dinamički učitati crystal report iz baze podataka
    Dim rep2 As New ReportDocument

    Dim CrTables As Tables
    Dim crtableLogoninfo As New TableLogOnInfo
    Dim crConnectionInfo As New ConnectionInfo
    ' za dodati labele na crystal report
    'Dim txtID As String = lblIDBroj.Content
    'Dim txtPoduzece As String = lblPoduzece.Content

    rep2.Load("C:\Users\Stjepan Juric\source\repos\Plata\Plata\CrystalReport2.rpt")

    With crConnectionInfo
        .ServerName = lblPath.Content.ToString()
        '.DatabaseName = ""
        '.UserID = ""
        'Password = "password"
    End With

    CrTables = rep2.Database.Tables
    For Each CrTable In CrTables
        crtableLogoninfo = CrTable.LogOnInfo
        crtableLogoninfo.ConnectionInfo = crConnectionInfo
        CrTable.ApplyLogOnInfo(crtableLogoninfo)
    Next

    'cryRpt.SetParameterValue("TxtID", txtID)
    'cryRpt.SetParameterValue("txtNaziv", txtPoduzece)

    cr1.ViewerCore.ReportSource = rep2

End Sub

End Class

Body:
I found what is problem.
Just add rep2.refresh to resolve it.

rep2.Load("C:\Users\Stjepan Juric\source\repos\Plata\Plata\CrystalReport2.rpt")
rep2.Refresh()


问:
ADO.NET Data Services & Oracle - RESTful WCF w/ Oracle
I'm looking into WCF and woud like to created my framework in a RESTful way.  I've just started looking into ADO.NET Data Services, but it seems it only supports SQL Server, is this correct?  Can you run in against Oracle?</p>

答:
Please see the following question for a more up-to-date and thorough answer.
Is it possible to expose data from Oracle using OData?</p>


问:
Router link changes the path but Router view doesn’t change
So i have a side navbar and some link in it. The entry point is the homepage. The problem is, when i'm trying to change router-view using router-link in my side navbar, the router-view doesn't change, but the path has change.

So here's my route path on my router.js:

```<code>        {
        path: '/',
        component: Home,
        children: [
                {
                    path: ':name',
                    name: 'theTask',
                    props: true,
                    component: TodoList
                }
            ]
        },
    ],
</code>```

And here's my App.vue

```<code><div class="container">
            <div class="main__content">
                <div class="sidenav">
                    <aside class="menu">
                        <ul class="menu-list">
                            <li><router-link :to="{ name: 'theTask', params: {name: 'today'} }">Today</router-link></li>
                            <li><router-link :to="{ name: 'home' }">Next 7 Days</router-link></li>
                        </ul>
                    </aside>
                </div>
                <div class="content">
                    <router-view></router-view>
                </div>
            </div>
     </div>
</code>```

It rendered the homepage, but when i'm clicking router-link to the child route, it doesn't change the router-view, only the router link.

答:
The real question is what is happening under the Hood.

routes.js

var routes = [{
    path: '/',
    name: 'home', // missed this one
    component: Home,
    children: [
        {
            path: ':name',
            name: 'theTask',
            props: true,
            component: TodoList
        }
    ]
}]
```
<ol>
<li><p>the parent is <code>Home</code> and the child is <code>TodoList</code> the route for parent is <code>/</code> and route for the child is <code>/:name</code>. you are trying to change the view true. and it's changing. But you can't see it. because there is no <code>router-view</code> in the parent of the component you are trying to change.</p>
<p>By default, the parent is <code>App.vue</code> for every object in the routes array(if you don't change it otherwise).
So <code>Parent</code> of component <code>Home</code> is <code>App.vue</code>. But the parent of <code>TodoList</code> is component <code>Home</code>. I am sure your <code>Home.vue</code> doesn't have <code><router-view></code>. When you are trying to render component <code>TodoList</code> it is rendering its parent and then finding <code><router-view></code> in its parent and trying to render itself there. But there isn't. And even if you add <code><router-view></code> in the <code>Home.vue</code> what you will have is both <code>Home</code> and <code>TodoList</code> rendering.</p>
</li>
<li><p>What I presume you are trying to do is to render <code>Home</code> and <code>TodoList</code> render separately on <code>App.vue</code> place. there are 2 options.</p>
</li>
</ol>
<h3>in <code>routes.js</code> file add 2 paths one for <code>/</code> and another for <code>/:name</code></h3>
<pre class="lang-js prettyprint-override"><code>var routes = [
{
    path: '/',
    name: 'home',
    component: Home,
},
{
    path: '/:name',
    name: 'theTask',
    props: true,
    component: TodoList
}];
</code>```

have a base component(if you really need it) and add 2 children.

var routes = [{
    path: '/',
    component: Base,
    children: [
        {
            path: '/',
            name: 'home',
            component: Home
        },
        {
            path: ':name',
            name: 'theTask',
            props: true,
            component: TodoList
        }
    ]
}]
```

Have a closer look at Evan You's example here

Body:
So i have a side navbar and some link in it. The entry point is the homepage. The problem is, when i'm trying to change router-view using router-link in my side navbar, the router-view doesn't change, but the path has change.

So here's my route path on my router.js:

        {
        path: '/',
        component: Home,
        children: [
                {
                    path: ':name',
                    name: 'theTask',
                    props: true,
                    component: TodoList
                }
            ]
        },
    ],

And here's my App.vue

<router-link :to="{ name: 'theTask', params: {name: 'today'} }">Today</router-link>

<router-link :to="{ name: 'home' }">Next 7 Days</router-link>

                    <router-view></router-view>

It rendered the homepage, but when i'm clicking router-link to the child route, it doesn't change the router-view, only the router link.

Body:
The real question is what is happening under the Hood.

routes.js

var routes = [{
    path: '/',
    name: 'home', // missed this one
    component: Home,
    children: [
        {
            path: ':name',
            name: 'theTask',
            props: true,
            component: TodoList
        }
    ]
}]

the parent is Home and the child is TodoList the route for parent is / and route for the child is /:name. you are trying to change the view true. and it's changing. But you can't see it. because there is no router-view in the parent of the component you are trying to change.

By default, the parent is App.vue for every object in the routes array(if you don't change it otherwise).
So Parent of component Home is App.vue. But the parent of TodoList is component Home. I am sure your Home.vue doesn't have <router-view>. When you are trying to render component TodoList it is rendering its parent and then finding <router-view> in its parent and trying to render itself there. But there isn't. And even if you add <router-view> in the Home.vue what you will have is both Home and TodoList rendering.

What I presume you are trying to do is to render Home and TodoList render separately on App.vue place. there are 2 options.

in routes.js file add 2 paths one for / and another for /:name

var routes = [
{
    path: '/',
    name: 'home',
    component: Home,
},
{
    path: '/:name',
    name: 'theTask',
    props: true,
    component: TodoList
}];

have a base component(if you really need it) and add 2 children.

var routes = [{
    path: '/',
    component: Base,
    children: [
        {
            path: '/',
            name: 'home',
            component: Home
        },
        {
            path: ':name',
            name: 'theTask',
            props: true,
            component: TodoList
        }
    ]
}]

Have a closer look at Evan You's example here


问:
How to have min-width and break to next line for contenteditable at same time
I created a text with contenteditable area but I faced a problem : I want contenteditable area to have min width so user will see area even after deleting text in it that's why I used display:inline-block but the contenteditable area does not break to next line it expand only and when I remove display:inline-block the contenteditable area break to next line when reach the end of the line but I can not use min width so if the user delete the text in contenteditable area it just disappear so you need to rreload the page .So how can I have them both ?

span.a{

   display:inline-block;
    min-width:20px;
    border:1px solid black;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> Lorem Ipsum is simply dummy text of the printing and typesetting industry.
   Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, <span  class="a" contenteditable="true" >AAAAAAAAAAAAAAAAAAAAA </span> took a galley of type and scrambled it to make a type specimen book.
   It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
   It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
   and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
   </code>```

答:
One idea is to keep the element inline and consider the :empty pseudo class to add some padding when there is not content. Doing so you will be sure the area will always be visible:

span.a {
  border: 1px solid black;
}
span.a:empty {
  padding-left:10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, <span class="a" contenteditable="true">AAAAAAAAAAA AAAAAAAAAA </span> took a galley of type and scrambled
it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</code>```

Body:
I created a text with contenteditable area but I faced a problem : I want contenteditable area to have min width so user will see area even after deleting text in it that's why I used display:inline-block but the contenteditable area does not break to next line it expand only and when I remove display:inline-block the contenteditable area break to next line when reach the end of the line but I can not use min width so if the user delete the text in contenteditable area it just disappear so you need to rreload the page .So how can I have them both ?

span.a{

   display:inline-block;
    min-width:20px;
    border:1px solid black;

}

 Lorem Ipsum is simply dummy text of the printing and typesetting industry.
   Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, AAAAAAAAAAAAAAAAAAAAA  took a galley of type and scrambled it to make a type specimen book.
   It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
   It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
   and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Body:
One idea is to keep the element inline and consider the :empty pseudo class to add some padding when there is not content. Doing so you will be sure the area will always be visible:

span.a {
  border: 1px solid black;
}
span.a:empty {
  padding-left:10px;
}

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, <span class="a" contenteditable="true">AAAAAAAAAAA AAAAAAAAAA </span> took a galley of type and scrambled
it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.


问:
java.lang.Instantiation Exception while deserializing a byte stream into a Scala case class object
I am trying to deserialize an avro byte stream into a scala case class object. Basically, i had a kafka stream with avro encoded data flowing and now there is an addition to the schema and i am trying to update the scala case class to include the new field. The case class looks like this

```<code>/** Case class to hold the Device data. */
case class DeviceData(deviceId: String,
                sw_version: String,
                timestamp: String,
                reading: Double,
                new_field: Option[String] = None
               )  {
</code>```

this() = this("na", "na", "na", 0, None)
}

The avro schema is as follows:

```<code>{
  "type": "record",
  "name": "some_name",
  "namespace": "some_namespace",
  "fields": [
    {
      "name": "deviceId",
      "type": "string"
    },
    {
      "name": "sw_version",
      "type": "string"
    },
    {
      "name": "timestamp",
      "type": "string"
    },
    {
      "name": "reading",
      "type": "double"
    },
    {
      "name": "new_field",
     "type": ["null", "string"],
      "default": null
    }]}
</code>```

When the data is received i get the following exception:

```<code>java.lang.RuntimeException: java.lang.InstantiationException
</code>```

I can receive the data just fine a consumer written in python so i know that the data is being streamed correctly in the correct format.
I am suspecting the problem is with the creation of the case class constructor, i have tried doing this:

```<code>/** Case class to hold the Device data. */
case class DeviceData(deviceId: String,
                sw_version: String,
                timestamp: String,
                reading: Double,
                new_field: Option[String]
               )  {
this() = this("na", "na", "na", 0, some("na"))
}
</code>```

but no luck.

The deserializer code is (excerpts):

```<code>// reader and decoder for reading avro records
private var reader: DatumReader[T] = null
private var decoder : BinaryDecoder = null
decoder = DecoderFactory.get.binaryDecoder(message, decoder)
reader.read(null.asInstanceOf[T], decoder)
</code>```

I could not find any other examples of having constructors for case classes which are used for deserializing avro, i had posted a related question last year java.lang.NoSuchMethodException for init method in Scala case class and based on the response i was able to implement my current code which has been working fine ever since.

答:
I resolved this problem by following a totally different approach. I used the Confluent Kafka client as provided in this example https://github.com/jfrazee/schema-registry-examples/tree/master/src/main/scala/io/atomicfinch/examples/flink. I also have a Confluent schema registry which is really easy to setup using the containerized all in one solution that comes with kafka and a schema registry https://docs.confluent.io/current/quickstart/ce-docker-quickstart.html.

I had to add confluent dependencies and repo in my pom.xml file. This goes in the repository section.

```<code><repository>
    <id>confluent</id>
    <url>http://packages.confluent.io/maven/</url>
</repository>
</code>```

This goes in the dependency section:

```<code><dependency>
    <groupId>org.apache.flink</groupId>
    <artifactId>flink-avro-confluent-registry</artifactId>
    <version>1.8.0</version>
</dependency>
<dependency>
    <groupId>io.confluent</groupId>
    <artifactId>kafka-avro-serializer</artifactId>
    <!-- For Confluent Platform 5.2.1 -->
    <version>5.2.1</version>
</dependency>
</code>```

With the code provided in https://github.com/jfrazee/schema-registry-examples/blob/master/src/main/scala/io/atomicfinch/examples/flink/ConfluentRegistryDeserializationSchema.scala i was able to talk to Confluent schema registry and then based on the schema id in the avro message header this downloads the schema from the schema reg and gives me back a GenericRecord object from which i can easily any and all fields of interest and create a new DataStream of the DeviceData object.

```<code>val kafka_consumer = new FlinkKafkaConsumer010("prod.perfwarden.minute",
  new ConfluentRegistryDeserializationSchema[GenericRecord](classOf[GenericRecord], "http://localhost:8081"),
  properties)
val device_data_stream = env
  .addSource(kafka_consumer)
  .map({x => new DeviceData(x.get("deviceId").toString,
    x.get("sw_version").toString,
    x.get("timestamp").toString,
    x.get("reading").toString.toDouble,
    x.get("new_field").toString)})
</code>```

The confluent kafka client takes care of deserializing the avro bytes stream as per the schema, including the default values. Setting up the schema registry and using the confluent kafka client may take just a little bit of time to get used to but is probably the better long term solution, just my 2 cents.

Body:
I am trying to deserialize an avro byte stream into a scala case class object. Basically, i had a kafka stream with avro encoded data flowing and now there is an addition to the schema and i am trying to update the scala case class to include the new field. The case class looks like this

/** Case class to hold the Device data. */
case class DeviceData(deviceId: String,
                sw_version: String,
                timestamp: String,
                reading: Double,
                new_field: Option[String] = None
               )  {

this() = this("na", "na", "na", 0, None)
}

The avro schema is as follows:

{
  "type": "record",
  "name": "some_name",
  "namespace": "some_namespace",
  "fields": [
    {
      "name": "deviceId",
      "type": "string"
    },
    {
      "name": "sw_version",
      "type": "string"
    },
    {
      "name": "timestamp",
      "type": "string"
    },
    {
      "name": "reading",
      "type": "double"
    },
    {
      "name": "new_field",
     "type": ["null", "string"],
      "default": null
    }]}

When the data is received i get the following exception:

java.lang.RuntimeException: java.lang.InstantiationException

I can receive the data just fine a consumer written in python so i know that the data is being streamed correctly in the correct format.
I am suspecting the problem is with the creation of the case class constructor, i have tried doing this:

/** Case class to hold the Device data. */
case class DeviceData(deviceId: String,
                sw_version: String,
                timestamp: String,
                reading: Double,
                new_field: Option[String]
               )  {
this() = this("na", "na", "na", 0, some("na"))
}

but no luck.

The deserializer code is (excerpts):

// reader and decoder for reading avro records
private var reader: DatumReader[T] = null
private var decoder : BinaryDecoder = null
decoder = DecoderFactory.get.binaryDecoder(message, decoder)
reader.read(null.asInstanceOf[T], decoder)

I could not find any other examples of having constructors for case classes which are used for deserializing avro, i had posted a related question last year java.lang.NoSuchMethodException for init method in Scala case class and based on the response i was able to implement my current code which has been working fine ever since.

Body:
I resolved this problem by following a totally different approach. I used the Confluent Kafka client as provided in this example https://github.com/jfrazee/schema-registry-examples/tree/master/src/main/scala/io/atomicfinch/examples/flink. I also have a Confluent schema registry which is really easy to setup using the containerized all in one solution that comes with kafka and a schema registry https://docs.confluent.io/current/quickstart/ce-docker-quickstart.html.

I had to add confluent dependencies and repo in my pom.xml file. This goes in the repository section.

<repository>
    <id>confluent</id>
    <url>http://packages.confluent.io/maven/</url>
</repository>

This goes in the dependency section:

<dependency>
    <groupId>org.apache.flink</groupId>
    <artifactId>flink-avro-confluent-registry</artifactId>
    <version>1.8.0</version>
</dependency>
<dependency>
    <groupId>io.confluent</groupId>
    <artifactId>kafka-avro-serializer</artifactId>
    <!-- For Confluent Platform 5.2.1 -->
    <version>5.2.1</version>
</dependency>

With the code provided in https://github.com/jfrazee/schema-registry-examples/blob/master/src/main/scala/io/atomicfinch/examples/flink/ConfluentRegistryDeserializationSchema.scala i was able to talk to Confluent schema registry and then based on the schema id in the avro message header this downloads the schema from the schema reg and gives me back a GenericRecord object from which i can easily any and all fields of interest and create a new DataStream of the DeviceData object.

val kafka_consumer = new FlinkKafkaConsumer010("prod.perfwarden.minute",
  new ConfluentRegistryDeserializationSchema[GenericRecord](classOf[GenericRecord], "http://localhost:8081"),
  properties)
val device_data_stream = env
  .addSource(kafka_consumer)
  .map({x => new DeviceData(x.get("deviceId").toString,
    x.get("sw_version").toString,
    x.get("timestamp").toString,
    x.get("reading").toString.toDouble,
    x.get("new_field").toString)})

The confluent kafka client takes care of deserializing the avro bytes stream as per the schema, including the default values. Setting up the schema registry and using the confluent kafka client may take just a little bit of time to get used to but is probably the better long term solution, just my 2 cents.


问:
How do I integrate Flutter web with Firebase?
I need to integrate my Flutter web app with Firebase. I found information, but it is all about Flutter for mobile apps and I need it for Flutter for web.</p>

答:
Flutter web is currently in a preview phase, which means that it "does not have a plugin system yet.".

Issues on GitHub about this have already been opened. Consider this one.

The alternative it proposes for now is to use the Dart web version of Firebase.

For more information you should consider reading through the issues on GitHub.

This should help you to get started for now.


问:
While loop for iterating all combinations between two values
I want to create a loop that loads all  the iterations of two variables into a dataframe in seperate columns. I want variable "a" to hold values between 0 and 1 in 0.1 increments, and the same for variable "b". In otherwords there should be 100 iterations when complete, starting with 0 & 0, and ending with 1 & 1.

I've tried the following code

```<code>data = [['Decile 1', 10], ['Decile_2', 15], ['Decile_3', 14]]
staging_table = pd.DataFrame(data, columns = ['Decile', 'Volume'])
profile_table = pd.DataFrame(columns = ['Decile', 'Volume'])

a = 0
b = 0

finished = False

while not finished:
    if b != 1:
        if a != 1:
            a = a + 0.1
            staging_table['CAM1_Modifier'] = a
            staging_table['CAM2_Modifier'] = b
            profile_table = profile_table.append(staging_table)
        else:
            b = b + 0.1
    else:
        finished = True

profile_table
</code>```

答:
You can use itertools.product to get all the combinations:</p>

```<code>import itertools
import pandas as pd

x = [i / 10 for i in range(11)]
df = pd.DataFrame(
    list(itertools.product(x, x)),
    columns=["a", "b"]
)

#        a    b
# 0    0.0  0.0
# 1    0.0  0.1
# 2    0.0  0.2
# ...  ...  ...
# 118  1.0  0.8
# 119  1.0  0.9
# 120  1.0  1.0
#
# [121 rows x 2 columns]
</code>```

Body:
I want to create a loop that loads all  the iterations of two variables into a dataframe in seperate columns. I want variable "a" to hold values between 0 and 1 in 0.1 increments, and the same for variable "b". In otherwords there should be 100 iterations when complete, starting with 0 & 0, and ending with 1 & 1.

I've tried the following code

data = [['Decile 1', 10], ['Decile_2', 15], ['Decile_3', 14]]
staging_table = pd.DataFrame(data, columns = ['Decile', 'Volume'])
profile_table = pd.DataFrame(columns = ['Decile', 'Volume'])

a = 0
b = 0

finished = False

while not finished:
    if b != 1:
        if a != 1:
            a = a + 0.1
            staging_table['CAM1_Modifier'] = a
            staging_table['CAM2_Modifier'] = b
            profile_table = profile_table.append(staging_table)
        else:
            b = b + 0.1
    else:
        finished = True

profile_table

Body:
You can use itertools.product to get all the combinations:

import itertools
import pandas as pd

x = [i / 10 for i in range(11)]
df = pd.DataFrame(
    list(itertools.product(x, x)),
    columns=["a", "b"]
)

#        a    b
# 0    0.0  0.0
# 1    0.0  0.1
# 2    0.0  0.2
# ...  ...  ...
# 118  1.0  0.8
# 119  1.0  0.9
# 120  1.0  1.0
#
# [121 rows x 2 columns]


答:
itertools is your friend.

```<code>from itertools import product

for a, b in product(map(lambda x: x / 10, range(10)),
                    map(lambda x: x / 10, range(10))):
  ...
</code>```

range(10) gives us the integers from 0 to 10 (regrettably, range fails on floats). Then we divide those values by 10 to get your range from 0 to 1. Then we take the Cartesian product of that iterable with itself to get every combination.

Title: While loop for iterating all combinations between two values

Body:
itertools is your friend.

from itertools import product

for a, b in product(map(lambda x: x / 10, range(10)),
                    map(lambda x: x / 10, range(10))):
  ...

range(10) gives us the integers from 0 to 10 (regrettably, range fails on floats). Then we divide those values by 10 to get your range from 0 to 1. Then we take the Cartesian product of that iterable with itself to get every combination.


问:
Can't derefence variable so function is satisfied
I can't seem to run this function called factorial() without getting an error.

At first if I have inbuf = atoi(factorial(inbuf));, gcc will spit out,

```<code>main.c:103: warning: passing argument 1 of ‘factorial’ makes integer from pointer without a cast
</code>```

If I change it to inbuf = atoi(factorial(inbuf*));, gcc will spit out,

```<code>main.c:103: error: expected expression before ‘)’ token
</code>```

Relevant code:

```<code>int factorial(int n)
{
    int temp;

    if (n <= 1)
        return 1;
    else
        return temp = n * factorial(n - 1);
} // end factorial

int main (int argc, char *argv[])
{
    char *inbuf[MSGSIZE];
    int fd[2];

    # pipe() code
    # fork() code

    // read the number to factorialize from the pipe
    read(fd[0], inbuf, MSGSIZE);

    // close read
    close(fd[0]);

    // find factorial using input from pipe, convert to string
    inbuf = atoi(factorial(inbuf*));

    // send the number read from the pipe to the recursive factorial() function
    write(fd[1], inbuf, MSGSIZE);

    # more code

} // end main
</code>```

What am I missing about dereferencing and my syntax??

答:
First, change inbuf to: char inbuf[MSGSIZE];

Second, you need to convert inbuf to int to pass it to factorial(). atoi() does exactly that. Then, you grab the result of this operation and convert it back to a string and assign it to inbuf: that's why sprintf() does.

```<code>// find factorial using input from pipe, convert to string
sprintf(inbuf, "%d", factorial(atoi(inbuf)));
</code>```

Body:
I can't seem to run this function called factorial() without getting an error.

At first if I have inbuf = atoi(factorial(inbuf));, gcc will spit out,

main.c:103: warning: passing argument 1 of ‘factorial’ makes integer from pointer without a cast

If I change it to inbuf = atoi(factorial(inbuf*));, gcc will spit out,

main.c:103: error: expected expression before ‘)’ token

Relevant code:

int factorial(int n)
{
    int temp;

    if (n <= 1)
        return 1;
    else
        return temp = n * factorial(n - 1);
} // end factorial

int main (int argc, char *argv[])
{
    char *inbuf[MSGSIZE];
    int fd[2];

    # pipe() code
    # fork() code

    // read the number to factorialize from the pipe
    read(fd[0], inbuf, MSGSIZE);

    // close read
    close(fd[0]);

    // find factorial using input from pipe, convert to string
    inbuf = atoi(factorial(inbuf*));

    // send the number read from the pipe to the recursive factorial() function
    write(fd[1], inbuf, MSGSIZE);

    # more code

} // end main

What am I missing about dereferencing and my syntax??

Body:
First, change inbuf to: char inbuf[MSGSIZE];

Second, you need to convert inbuf to int to pass it to factorial(). atoi() does exactly that. Then, you grab the result of this operation and convert it back to a string and assign it to inbuf: that's why sprintf() does.

// find factorial using input from pipe, convert to string
sprintf(inbuf, "%d", factorial(atoi(inbuf)));