问:
getting null in an @Autowired field in Abstract class
I have a abstract class, and inherited by several subclasses.  In another class i get the class name and need to instantiate the class to call a base method in the parent(abstract) class. But i got null in an @Autowired field 'cache' which used in the base method. The className is an input field from the front end. So i think i have to do instantiate a new object in order to call the method. Thanks in advance!</p>

```<code>public abstract class Data(){
   @Autowired protected Cache cache;

   private Abc getDataContent(){
      if(cache.containsKey()){
        //do something
      }else{
        //do something else
      }
    }
}

public class Data1 extends Data(){
  public Data1(){
    super();
  }
}

public class Data2 extends Data(){
  public Data2(){
    super();
  }
}

public class Resource(){

  public Abc getContent(){
    Class<Data<?>> className = getClassName();
    //className  will be the classCanonicalName of Data1 or Data2;

    return className.newInstance().getDataContent();
  }

}
</code>```

答:
To avoid the null field, you need to let spring manage the beans (objects), and a simple way to do it is to use @Component annotation on Data1 and Data2.

Also, please note that if you manually instantiate an object (e.g. new Data1(); ) then Spring will be unaware of that instance;

Body:
I have a abstract class, and inherited by several subclasses.  In another class i get the class name and need to instantiate the class to call a base method in the parent(abstract) class. But i got null in an @Autowired field 'cache' which used in the base method. The className is an input field from the front end. So i think i have to do instantiate a new object in order to call the method. Thanks in advance!

public abstract class Data(){
   @Autowired protected Cache cache;

   private Abc getDataContent(){
      if(cache.containsKey()){
        //do something
      }else{
        //do something else
      }
    }
}

public class Data1 extends Data(){
  public Data1(){
    super();
  }
}

public class Data2 extends Data(){
  public Data2(){
    super();
  }
}

public class Resource(){

  public Abc getContent(){
    Class<Data<?>> className = getClassName();
    //className  will be the classCanonicalName of Data1 or Data2;

    return className.newInstance().getDataContent();
  }

}


来源: stackexchange

问:
AWS CLI Query IF condition
Could I get help on getting the values of Alias record in the cli table output?

The test.emea.example.com. is an alias.

BTW, if the DNS record is multi-value, how to flat and concatenate the values

Below is the example:

```<code> $ aws route53 list-resource-record-sets --hosted-zone-id Z34XXXXXXXX4EF --query "ResourceRecordSets[?Type=='A']"
[
    {
        "ResourceRecords": [
            {
                "Value": "10.189.134.12"
            }
        ],
        "Type": "A",
        "Name": "dnsforwarder0.emea.example.com.",
        "TTL": 300
    },
    {
        "ResourceRecords": [
            {
                "Value": "10.189.134.47"
            }
        ],
        "Type": "A",
        "Name": "dnsforwarder1.emea.example.com.",
        "TTL": 300
    },
    {
        "ResourceRecords": [
            {
                "Value": "10.189.134.78"
            }
        ],
        "Type": "A",
        "Name": "dnsforwarder2.emea.example.com.",
        "TTL": 300
    },
    {
        "AliasTarget": {
            "HostedZoneId": "Z32O12XQLNTSW2",
            "EvaluateTargetHealth": false,
            "DNSName": "dualstack.kubernetes-elb-k8fca-prod-emea-1745420721.eu-west-1.elb.amazonaws.com."
        },
        "Type": "A",
        "Name": "test.emea.example.com."
    }
]
[Tiger-Pengs-MacBook-Pro:~/aws/aws_fed]
tpeng $ aws route53 list-resource-record-sets --hosted-zone-id Z34XXXXXXXX4EF --query "ResourceRecordSets[?Type=='A'].[Name,Type,ResourceRecords[0].Value]" --output table --color off
-----------------------------------------------------------
|                 ListResourceRecordSets                  |
+----------------------------------+----+-----------------+
|  dnsforwarder0.emea.example.com. |  A |  10.189.134.12  |
|  dnsforwarder1.emea.example.com. |  A |  10.189.134.47  |
|  dnsforwarder2.emea.example.com. |  A |  10.189.134.78  |
|  test.emea.example.com.          |  A |  None           |
+----------------------------------+----+-----------------+
</code>```

答:
You can do this by combining a JMESpath And expression with the keys and contains functions. So this would work:

aws route53 list-resource-record-sets --hosted-zone-id Z34XXXXXXXX4EF \
  --query 'ResourceRecordSets[?Type==`A` && contains(keys(@), `AliasTarget`)].Name'
```

ContentLicense: CC BY-SA 4.0

Title: AWS CLI Query IF condition

Body:
Could I get help on getting the values of Alias record in the cli table output?

The test.emea.example.com. is an alias.

BTW, if the DNS record is multi-value, how to flat and concatenate the values

Below is the example:

 $ aws route53 list-resource-record-sets --hosted-zone-id Z34XXXXXXXX4EF --query "ResourceRecordSets[?Type=='A']"
[
    {
        "ResourceRecords": [
            {
                "Value": "10.189.134.12"
            }
        ],
        "Type": "A",
        "Name": "dnsforwarder0.emea.example.com.",
        "TTL": 300
    },
    {
        "ResourceRecords": [
            {
                "Value": "10.189.134.47"
            }
        ],
        "Type": "A",
        "Name": "dnsforwarder1.emea.example.com.",
        "TTL": 300
    },
    {
        "ResourceRecords": [
            {
                "Value": "10.189.134.78"
            }
        ],
        "Type": "A",
        "Name": "dnsforwarder2.emea.example.com.",
        "TTL": 300
    },
    {
        "AliasTarget": {
            "HostedZoneId": "Z32O12XQLNTSW2",
            "EvaluateTargetHealth": false,
            "DNSName": "dualstack.kubernetes-elb-k8fca-prod-emea-1745420721.eu-west-1.elb.amazonaws.com."
        },
        "Type": "A",
        "Name": "test.emea.example.com."
    }
]
[Tiger-Pengs-MacBook-Pro:~/aws/aws_fed]
tpeng $ aws route53 list-resource-record-sets --hosted-zone-id Z34XXXXXXXX4EF --query "ResourceRecordSets[?Type=='A'].[Name,Type,ResourceRecords[0].Value]" --output table --color off
-----------------------------------------------------------
|                 ListResourceRecordSets                  |
+----------------------------------+----+-----------------+
|  dnsforwarder0.emea.example.com. |  A |  10.189.134.12  |
|  dnsforwarder1.emea.example.com. |  A |  10.189.134.47  |
|  dnsforwarder2.emea.example.com. |  A |  10.189.134.78  |
|  test.emea.example.com.          |  A |  None           |
+----------------------------------+----+-----------------+


问:
React Native: Invariant Violation: Element type invalid:expected string or a class/function but got: undefined
I am trying to display wordpress posts in a react-native app.

The following are the contents on the Blog.js file.

```<code>import React from 'react';
import { StyleSheet, View, TouchableOpacity, Text, Alert, FlatList } from 'react-native';
import { HTML } from 'react-native-render-html';

class BlogItem extends React.Component {

  constructor(props) {
    super(props);
  }

  blogChoice = () => {
    this.props.choosePost(this.props.id);
  }

  render() {
    let blogItems = `
      <a href=${this.props.id} style="textDecorationLine: none; color: #000000;  textAlign: center">
        <img src=${this.props.imageSrc} />
        <h1>${this.props.title}</h1>
        ${this.props.excerpt}
      </a>
    `;
    return (
      <View style={{borderBottomWidth: 2, borderBottomColor: '#000000', borderStyle: 'solid'}}>
        <HTML html={blogItems} onLinkPress={()=>this.blogChoice()} />
      </View>
    );
  }
}

export class Blog extends React.Component {

  static navigationOptions = {
    header: null
  }

  constructor(props) {
    super(props);
    this.state = {blogLoaded: false};
  }

  chooseBlog = (blogID) => {
    console.log(`Blog ID chosen: ${blogID}`);
  }

  componentDidMount() {
    // return fetch('https://public-api.wordpress.com/rest/v1.1/sites/reactnative.travel.blog/posts')
    return fetch('https://public-api.wordpress.com/rest/v1.1/sites/myglobomantics.wordpress.com/posts')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          blogLoaded: true,
          blogList: Array.from(responseJson.posts)
        });
      })
      .catch((error) => {
        console.log(error);
      });
  }

  render() {
    return (
      <View>

        { this.state.blogLoaded && (
          <View style={{ paddingTop: 40 }}>
            <FlatList
              data={this.state.blogList}
              keyExtractor={(item, index) => item.ID.toString()}
              renderItem={({item}) =>
                <BlogItem
                  id={item.ID}
                  title={item.title}
                  imageSrc={item.featured_image}
                  excerpt={item.excerpt}
                  choosePost={this.chooseBlog}
                />
              }
            />
          </View>
        )}

        { !this.state.blogLoaded && (
            <View style={{ paddingTop: 30 }}>
              <Text> LOADING </Text>
            </View>
        )}

      </View>
    );
  }

}
</code>```

And app.js file uses the component as:

```<code>import { Blog } from './app/views/Blog.js';
</code>```

where it creates a stackNavigation.

```<code>const MyRoutes = createStackNavigator({
    HomeRT: {
      screen: Home
    },
    BlogRT: {
      screen: Blog
    },
  },
  {
    'initialRouteName': 'HomeRT'
  }
);

export default createAppContainer(MyRoutes);
</code>```

However when I navigate to the Blog Component, I keep getting this error:

```<code>Device: (96:380) Invariant Violation: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

This error is located at:
    in RCTView
    in BlogItem
    in RCTView
    in u
    in RCTView
    in RCTScrollView
    in ScrollView
    in z
    in b
    in RCTView
    in RCTView
    in Blog
    in t
    in RCTView
    in RCTView
    in RCTView
    in f
    in RCTView
    in f
    in C
    in t
    in n
    in RCTView
    in n
    in RCTView
    in f
    in S
    in t
    in n
    in RCTView
    in t
    in t
    in p
    in r
    in n
    in RCTView
    in RCTView
    in n
    in n
    in v
    in RCTView
    in RCTView
    in c

This error is located at:
    in n
    in RCTView
    in RCTView
    in n
    in n
    in v
    in RCTView
    in RCTView
    in c
</code>```

I have check all the values I am getting from the wordpress API and they are non-null values. Also I tried to remove the BlogItem component and build it incrementally, but could not pin point what causes the error. What am I going wrong? Any help will be appreciated.

答:
Remove the curlies from the HTML import:

```<code>import { HTML } from 'react-native-render-html';
</code>```

I don't think you need destructuring here. I think you want the default export.

What's happening is HTML is undefined and therefore not a "valid element".

If your module has named exports:

```<code>// cool-stuff.js
module.exports = {
  SomeCoolThing: () => console.log('some cool thing'),
  SomeOtherCoolThing: () => console.log('some other cool thing')
}
</code>```

Then you can either import the whole thing and reference the items statically:

```<code>import CoolStuff from './cool-stuff.js';

CoolStuff.SomeCoolThing();
</code>```

or you can destructure it on import to get just the piece(s) you need:

```<code>import {SomeCoolThing} from './cool-stuff.js'

SomeCoolThing();
</code>```

But if a module just has a default export:

```<code>// cool-stuff.js
module.exports = () => console.log('some other cool thing')
</code>```

Then destructuring makes no sense:

```<code>import {SomeCoolThing} from './cool-stuff.js'

SomeCoolThing(); // doesn't exist. blows up.
</code>```

You just want the default export, and you can call it whatever you want:

```<code>import SoCool from './cool-stuff.js'

SoCool(); // works
</code>```

Body:
I am trying to display wordpress posts in a react-native app.

The following are the contents on the Blog.js file.

import React from 'react';
import { StyleSheet, View, TouchableOpacity, Text, Alert, FlatList } from 'react-native';
import { HTML } from 'react-native-render-html';

class BlogItem extends React.Component {

  constructor(props) {
    super(props);
  }

  blogChoice = () => {
    this.props.choosePost(this.props.id);
  }

  render() {
    let blogItems = `

${this.props.title}

        ${this.props.excerpt}

    `;
    return (
      <View style={{borderBottomWidth: 2, borderBottomColor: '#000000', borderStyle: 'solid'}}>
        this.blogChoice()} />
      </View>
    );
  }
}

export class Blog extends React.Component {

  static navigationOptions = {
    header: null
  }

  constructor(props) {
    super(props);
    this.state = {blogLoaded: false};
  }

  chooseBlog = (blogID) => {
    console.log(`Blog ID chosen: ${blogID}`);
  }

  componentDidMount() {
    // return fetch('https://public-api.wordpress.com/rest/v1.1/sites/reactnative.travel.blog/posts')
    return fetch('https://public-api.wordpress.com/rest/v1.1/sites/myglobomantics.wordpress.com/posts')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          blogLoaded: true,
          blogList: Array.from(responseJson.posts)
        });
      })
      .catch((error) => {
        console.log(error);
      });
  }

  render() {
    return (
      <View>

        { this.state.blogLoaded && (
          <View style={{ paddingTop: 40 }}>
            <FlatList
              data={this.state.blogList}
              keyExtractor={(item, index) => item.ID.toString()}
              renderItem={({item}) =>
                <BlogItem
                  id={item.ID}
                  title={item.title}
                  imageSrc={item.featured_image}
                  excerpt={item.excerpt}
                  choosePost={this.chooseBlog}
                />
              }
            />
          </View>
        )}

        { !this.state.blogLoaded && (
            <View style={{ paddingTop: 30 }}>
              <Text> LOADING </Text>
            </View>
        )}

      </View>
    );
  }

}

And app.js file uses the component as:

import { Blog } from './app/views/Blog.js';

where it creates a stackNavigation.

const MyRoutes = createStackNavigator({
    HomeRT: {
      screen: Home
    },
    BlogRT: {
      screen: Blog
    },
  },
  {
    'initialRouteName': 'HomeRT'
  }
);

export default createAppContainer(MyRoutes);

However when I navigate to the Blog Component, I keep getting this error:

Device: (96:380) Invariant Violation: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

This error is located at:
    in RCTView
    in BlogItem
    in RCTView
    in u
    in RCTView
    in RCTScrollView
    in ScrollView
    in z
    in b
    in RCTView
    in RCTView
    in Blog
    in t
    in RCTView
    in RCTView
    in RCTView
    in f
    in RCTView
    in f
    in C
    in t
    in n
    in RCTView
    in n
    in RCTView
    in f
    in S
    in t
    in n
    in RCTView
    in t
    in t
    in p
    in r
    in n
    in RCTView
    in RCTView
    in n
    in n
    in v
    in RCTView
    in RCTView
    in c

This error is located at:
    in n
    in RCTView
    in RCTView
    in n
    in n
    in v
    in RCTView
    in RCTView
    in c

I have check all the values I am getting from the wordpress API and they are non-null values. Also I tried to remove the BlogItem component and build it incrementally, but could not pin point what causes the error. What am I going wrong? Any help will be appreciated.

Body:
Remove the curlies from the HTML import:

import { HTML } from 'react-native-render-html';

I don't think you need destructuring here. I think you want the default export.

What's happening is HTML is undefined and therefore not a "valid element".

If your module has named exports:

// cool-stuff.js
module.exports = {
  SomeCoolThing: () => console.log('some cool thing'),
  SomeOtherCoolThing: () => console.log('some other cool thing')
}

Then you can either import the whole thing and reference the items statically:

import CoolStuff from './cool-stuff.js';

CoolStuff.SomeCoolThing();

or you can destructure it on import to get just the piece(s) you need:

import {SomeCoolThing} from './cool-stuff.js'

SomeCoolThing();

But if a module just has a default export:

// cool-stuff.js
module.exports = () => console.log('some other cool thing')

Then destructuring makes no sense:

import {SomeCoolThing} from './cool-stuff.js'

SomeCoolThing(); // doesn't exist. blows up.

You just want the default export, and you can call it whatever you want:

import SoCool from './cool-stuff.js'

SoCool(); // works


问:
Can I pass a parameter of an OledbCommand to other OledbCommand?
This might be silly question but I need some solution in it.

I've done like

```<code>cmd.CommandText = "Insert Table1(Col1,Col2,Col3,Date) Values (1,'aa',101,?)"
cmd.Connection = con2
cmd.Parameters.AddWithValue("@Date", transdate)
ExecuteQuery(con2,cmd)
</code>```

I wrote below code to avoid writing Using.. End Using everywhere.

Query runs fine if it has no parameter.

```<code>Private Sub ExecuteQuery(con as OledbConnection,cmd as OledbCommand)
Using con1 As New OleDbConnection(con.ConnectionString)
    Using cmd1 As New OleDbCommand(cmd.CommandText)
        cmd1.Connection = con1
        con1.Open()
        cmd1.ExecuteNonQuery()
        con1.Close()
    End Using
End Using
</code>```

It works fine with parameters when I write cmd under Using Block.

But as I said, I am avoiding writing Using everywhere.

But doing like this gives error -- No Given values for one or more required parameters.

答:
You need to adjust your ExecuteQuery because it's making a new command and losing the Parameters. Change it so that it uses the existing command you passed, and disposes it, or transfer the Parameters from your inbound command to the new one

```<code>Private Sub ExecuteQuery(con as OledbConnection, cmd as OledbCommand)
  Using con1 As New OleDbConnection(con.ConnectionString)
    Try
        cmd.Connection = con1
        con1.Open()
        cmd.ExecuteNonQuery()
        con1.Close()
    Finally
        cmd.Dispose()
    End Try
  End Using
End Sub

Private Sub ExecuteQuery(con as OledbConnection,cmd as OledbCommand)
  Using con1 As New OleDbConnection(con.ConnectionString)
    Using cmd1 As New OleDbCommand(cmd.CommandText)
        cmd1.Connection = con1
        ForEach p as Parameter in cmd.Parameters
          cmd1.Parameters.Add(p)
        con1.Open()
        cmd1.ExecuteNonQuery()
        con1.Close()
    End Using
  End Using
End Sub
</code>```

If you're looking for a way to make your db life easier check out Dapper or Entity Framework - you work with objects, it writes all the sql for you. This isn't a cessation of control (you still write the queries) it's delegating the boring aspects of executing your query, going through the results, digging out each text or int and assigning it to your user object's name or age..

If you get to a point where you don't want to write the SQLs either, use Entity Framework, as it can convert between your objects and the db automatically

Body:
This might be silly question but I need some solution in it.

I've done like

cmd.CommandText = "Insert Table1(Col1,Col2,Col3,Date) Values (1,'aa',101,?)"
cmd.Connection = con2
cmd.Parameters.AddWithValue("@Date", transdate)
ExecuteQuery(con2,cmd)

I wrote below code to avoid writing Using.. End Using everywhere.

Query runs fine if it has no parameter.

Private Sub ExecuteQuery(con as OledbConnection,cmd as OledbCommand)
Using con1 As New OleDbConnection(con.ConnectionString)
    Using cmd1 As New OleDbCommand(cmd.CommandText)
        cmd1.Connection = con1
        con1.Open()
        cmd1.ExecuteNonQuery()
        con1.Close()
    End Using
End Using

It works fine with parameters when I write cmd under Using Block.

But as I said, I am avoiding writing Using everywhere.

But doing like this gives error -- No Given values for one or more required parameters.

Body:
You need to adjust your ExecuteQuery because it's making a new command and losing the Parameters. Change it so that it uses the existing command you passed, and disposes it, or transfer the Parameters from your inbound command to the new one

Private Sub ExecuteQuery(con as OledbConnection, cmd as OledbCommand)
  Using con1 As New OleDbConnection(con.ConnectionString)
    Try
        cmd.Connection = con1
        con1.Open()
        cmd.ExecuteNonQuery()
        con1.Close()
    Finally
        cmd.Dispose()
    End Try
  End Using
End Sub

Private Sub ExecuteQuery(con as OledbConnection,cmd as OledbCommand)
  Using con1 As New OleDbConnection(con.ConnectionString)
    Using cmd1 As New OleDbCommand(cmd.CommandText)
        cmd1.Connection = con1
        ForEach p as Parameter in cmd.Parameters
          cmd1.Parameters.Add(p)
        con1.Open()
        cmd1.ExecuteNonQuery()
        con1.Close()
    End Using
  End Using
End Sub

If you're looking for a way to make your db life easier check out Dapper or Entity Framework - you work with objects, it writes all the sql for you. This isn't a cessation of control (you still write the queries) it's delegating the boring aspects of executing your query, going through the results, digging out each text or int and assigning it to your user object's name or age..

If you get to a point where you don't want to write the SQLs either, use Entity Framework, as it can convert between your objects and the db automatically


问:
Expressjs: How to catch form data using POST method?
Guys.

I'm currently building a rather large project and I want to know which the best tool that I can use to catch form data using the POST method. The form is a 'sigin' and 'login' form

I read about 'body-parser' and 'busboy', but I'm a noob and I don't know which is the best choice

答:
I am also new to express but i learned that you dont need to add body-parser as express comes with it by default now

const express = require("express");
const app = express();

app.use(express.json());
```


问:
No data response when sending ajax request to php
i want to send a json data to my php but there is no response when i access it to my php.

this is my ajax request

```<code>    var project = {project:"A"};

 var dataPost = JSON.stringify(project);

     $.ajax({
     url: 'fetchDate.php',
     data: {myData: dataPost},
     type: 'POST',
     datatype:'json',
     contentType: "application/json",
     success: function(data) {
         alert(JSON.stringify(data));
     }
 });
</code>```

});

and this is my php where i process the request and return back the data to test

```<code><?php header("Content-Type: application/json; charset=UTF-8");
  $objProject = json_decode($_GET["myData"]);
  echo json_encode($objProject->project); ?>
</code>```

i'm new to ajax so please i need your help

答:
you don't need to add the content type on your ajax since you're not  actually sending json to the server.

```<code>     $.ajax({
     url: 'fetchDate.php',
     data: {myData: project},
     type: 'POST',
     datatype:'json',
    // contentType: "application/json",
     success: function(data, status, jqXHR) {

         console.log(data,status,jqXHR);
          alert(JSON.stringify(data));
     }
});
</code>```

no need to stringify project object,
in your php just encode it to json

```<code><?php  header("Content-Type: application/json; charset=UTF-8");
 $obj = $_POST['myData'];
 echo json_encode($obj); ?>
</code>```

you should get json string on alert

Body:
i want to send a json data to my php but there is no response when i access it to my php.

this is my ajax request

    var project = {project:"A"};

 var dataPost = JSON.stringify(project);

     $.ajax({
     url: 'fetchDate.php',
     data: {myData: dataPost},
     type: 'POST',
     datatype:'json',
     contentType: "application/json",
     success: function(data) {
         alert(JSON.stringify(data));
     }
 });

});

and this is my php where i process the request and return back the data to test

<?php header("Content-Type: application/json; charset=UTF-8");
  $objProject = json_decode($_GET["myData"]);
  echo json_encode($objProject->project); ?>

i'm new to ajax so please i need your help

Body:
you don't need to add the content type on your ajax since you're not  actually sending json to the server.

     $.ajax({
     url: 'fetchDate.php',
     data: {myData: project},
     type: 'POST',
     datatype:'json',
    // contentType: "application/json",
     success: function(data, status, jqXHR) {

         console.log(data,status,jqXHR);
          alert(JSON.stringify(data));
     }
});

no need to stringify project object,
in your php just encode it to json

<?php  header("Content-Type: application/json; charset=UTF-8");
 $obj = $_POST['myData'];
 echo json_encode($obj); ?>

you should get json string on alert


问:
C# error when read Excel file, this is a strange error
When I read (*.xls) file in C# I get an error.

I see lots of topic about "DCOM Access Denied Problem" and configuration of related problem in SO, but non of them solved my problem. all permission and administrator account was checked.  this is image of error:

Update: this is logged error by app :

```<code>Error       : The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
Stack Trace : at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad)
   at Pardic.WebProcess.frmGetPrice.worker_DoWork(Object sender, DoWorkEventArgs e)
^^-------------------------------------------------------------------^^
Source      : Microsoft.Office.Interop.Excel
Method      : Quit
Date        : 02:21:19 ب.ظ
Time        : 07/03/1398
Computer    : DESKTOP-2QPBGQ1
Error       : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Stack Trace : at Microsoft.Office.Interop.Excel.ApplicationClass.Quit()
   at Pardic.WebProcess.frmGetPrice.worker_DoWork(Object sender, DoWorkEventArgs e)
</code>```

This is Event Windows logs:

```<code>Log Name:      Application
Source:        Application Error
Date:          5/28/2019 2:16:11 PM
Event ID:      1000
Task Category: (100)
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      DESKTOP-2QPBGQ1
Description:
Faulting application name: EXCEL.EXE, version: 15.0.4420.1017, time stamp: 0x506741b5
Faulting module name: ntdll.dll, version: 10.0.14393.2214, time stamp: 0x5ac2f612
Exception code: 0xc0000005
Fault offset: 0x000000000004961c
Faulting process id: 0x1934
Faulting application start time: 0x01d5153a29e7eeb5
Faulting application path: C:\Program Files\Microsoft Office\Office15\EXCEL.EXE
Faulting module path: C:\Windows\SYSTEM32\ntdll.dll
Report Id: 9910317c-cd4c-49b2-8869-76f88b722123
Faulting package full name:
Faulting package-relative application ID:
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Application Error" />
    <EventID Qualifiers="0">1000</EventID>
    <Level>2</Level>
    <Task>100</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2019-05-28T09:46:11.052916900Z" />
    <EventRecordID>20076</EventRecordID>
    <Channel>Application</Channel>
    <Computer>DESKTOP-2QPBGQ1</Computer>
    <Security />
  </System>
  <EventData>
    <Data>EXCEL.EXE</Data>
    <Data>15.0.4420.1017</Data>
    <Data>506741b5</Data>
    <Data>ntdll.dll</Data>
    <Data>10.0.14393.2214</Data>
    <Data>5ac2f612</Data>
    <Data>c0000005</Data>
    <Data>000000000004961c</Data>
    <Data>1934</Data>
    <Data>01d5153a29e7eeb5</Data>
    <Data>C:\Program Files\Microsoft Office\Office15\EXCEL.EXE</Data>
    <Data>C:\Windows\SYSTEM32\ntdll.dll</Data>
    <Data>9910317c-cd4c-49b2-8869-76f88b722123</Data>
    <Data>
    </Data>
    <Data>
    </Data>
  </EventData>
</Event>
</code>```

and this is list of installed program:

```<code>    public static System.Collections.Generic.List<Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo> ReadResult(string fileAddress)
        {
            List<Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo> retList = new List<Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo>();
            Microsoft.Office.Interop.Excel.Application oXL;
            oXL = new Microsoft.Office.Interop.Excel.Application();
            try
            {
                Microsoft.Office.Interop.Excel.Workbook theWorkbook = oXL.Workbooks.Open(fileAddress);
                Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
                foreach (Microsoft.Office.Interop.Excel.Worksheet item in sheets)
                {
                    if (item.Name.Contains("Main"))
                    {
                        Microsoft.Office.Interop.Excel.Range ShtRange = item.UsedRange;
                        int CodeColumnNum = 0;
                        int PriceColumnNum = 0;
                        int NameColumnNum = 0;
                        int num = 0;
                        for (num = 1; num <= ShtRange.Columns.Count; num++)
                        {
                            try
                            {
                                string temp = string.Empty;
                                try
                                {
                                    temp = ShtRange.Cells[1, num].Value2.ToString();
                                }
                                catch
                                {
                                    temp = string.Empty;
                                }
                                if (temp.Contains("كد دارو"))
                                    CodeColumnNum = num;
                                if (temp.Contains("تغيير قيمت"))
                                    PriceColumnNum = num;
                                if (temp.Contains("نام دارو"))
                                    NameColumnNum = num;
                            }
                            catch (Exception ex)
                            {
                                if (CodeColumnNum > 0 && PriceColumnNum > 0 && NameColumnNum > 0)
                                    break;
                                oXL.Quit();
                                throw ex;
                            }
                        }

                        for (num = 2; num <= ShtRange.Rows.Count; num++)
                        {
                            Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo drug = new Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo();
                            string Codetemp = string.Empty;
                            try
                            {
                                Codetemp = ShtRange.Cells[num, CodeColumnNum].Value2.ToString();
                            }
                            catch
                            {
                                Codetemp = string.Empty;
                            }
                            string Pricetemp = string.Empty;
                            try
                            {
                                Pricetemp = ShtRange.Cells[num, PriceColumnNum].Value2.ToString();
                            }
                            catch
                            {
                                Pricetemp = string.Empty;
                            }
                            drug.Drug_Code = CodeAnalize(Codetemp);
                            drug.Drug_Price = PriceAnalize(Pricetemp);
                            drug.Drug_Name = ShtRange.Cells[num, NameColumnNum].Value2;
                            if (drug.Drug_Price != string.Empty && drug.Drug_Code != string.Empty)
                                retList.Add(drug);
                        }
                    }
                }

             theWorkbook.Save();
                return retList;
            }
            catch //(Exception ex)
            {
                return null;
            }
            finally
            {
                oXL.Quit();
            }
        }
</code>```

this problem is appears when I reinstall windows and office. installation office is 2013 (both office and win are 64 bit)

Update:

答: After lot's of hints, works and tips, I Uninstall the Foxit Reader software and now the xls file is work perfectly. why Microsoft couldn't detect this error.</p>

Body:
When I read (*.xls) file in C# I get an error.

I see lots of topic about "DCOM Access Denied Problem" and configuration of related problem in SO, but non of them solved my problem. all permission and administrator account was checked.  this is image of error:

Update: this is logged error by app :

Error       : The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
Stack Trace : at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad)
   at Pardic.WebProcess.frmGetPrice.worker_DoWork(Object sender, DoWorkEventArgs e)
^^-------------------------------------------------------------------^^
Source      : Microsoft.Office.Interop.Excel
Method      : Quit
Date        : 02:21:19 ب.ظ
Time        : 07/03/1398
Computer    : DESKTOP-2QPBGQ1
Error       : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Stack Trace : at Microsoft.Office.Interop.Excel.ApplicationClass.Quit()
   at Pardic.WebProcess.frmGetPrice.worker_DoWork(Object sender, DoWorkEventArgs e)

This is Event Windows logs:

Log Name:      Application
Source:        Application Error
Date:          5/28/2019 2:16:11 PM
Event ID:      1000
Task Category: (100)
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      DESKTOP-2QPBGQ1
Description:
Faulting application name: EXCEL.EXE, version: 15.0.4420.1017, time stamp: 0x506741b5
Faulting module name: ntdll.dll, version: 10.0.14393.2214, time stamp: 0x5ac2f612
Exception code: 0xc0000005
Fault offset: 0x000000000004961c
Faulting process id: 0x1934
Faulting application start time: 0x01d5153a29e7eeb5
Faulting application path: C:\Program Files\Microsoft Office\Office15\EXCEL.EXE
Faulting module path: C:\Windows\SYSTEM32\ntdll.dll
Report Id: 9910317c-cd4c-49b2-8869-76f88b722123
Faulting package full name:
Faulting package-relative application ID:
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Application Error" />
    <EventID Qualifiers="0">1000</EventID>
    <Level>2</Level>
    <Task>100</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2019-05-28T09:46:11.052916900Z" />
    <EventRecordID>20076</EventRecordID>
    <Channel>Application</Channel>
    <Computer>DESKTOP-2QPBGQ1</Computer>
    <Security />
  </System>
  <EventData>
    <Data>EXCEL.EXE</Data>
    <Data>15.0.4420.1017</Data>
    <Data>506741b5</Data>
    <Data>ntdll.dll</Data>
    <Data>10.0.14393.2214</Data>
    <Data>5ac2f612</Data>
    <Data>c0000005</Data>
    <Data>000000000004961c</Data>
    <Data>1934</Data>
    <Data>01d5153a29e7eeb5</Data>
    <Data>C:\Program Files\Microsoft Office\Office15\EXCEL.EXE</Data>
    <Data>C:\Windows\SYSTEM32\ntdll.dll</Data>
    <Data>9910317c-cd4c-49b2-8869-76f88b722123</Data>
    <Data>
    </Data>
    <Data>
    </Data>
  </EventData>
</Event>

and this is list of installed program:

    public static System.Collections.Generic.List<Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo> ReadResult(string fileAddress)
        {
            List<Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo> retList = new List<Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo>();
            Microsoft.Office.Interop.Excel.Application oXL;
            oXL = new Microsoft.Office.Interop.Excel.Application();
            try
            {
                Microsoft.Office.Interop.Excel.Workbook theWorkbook = oXL.Workbooks.Open(fileAddress);
                Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
                foreach (Microsoft.Office.Interop.Excel.Worksheet item in sheets)
                {
                    if (item.Name.Contains("Main"))
                    {
                        Microsoft.Office.Interop.Excel.Range ShtRange = item.UsedRange;
                        int CodeColumnNum = 0;
                        int PriceColumnNum = 0;
                        int NameColumnNum = 0;
                        int num = 0;
                        for (num = 1; num <= ShtRange.Columns.Count; num++)
                        {
                            try
                            {
                                string temp = string.Empty;
                                try
                                {
                                    temp = ShtRange.Cells[1, num].Value2.ToString();
                                }
                                catch
                                {
                                    temp = string.Empty;
                                }
                                if (temp.Contains("كد دارو"))
                                    CodeColumnNum = num;
                                if (temp.Contains("تغيير قيمت"))
                                    PriceColumnNum = num;
                                if (temp.Contains("نام دارو"))
                                    NameColumnNum = num;
                            }
                            catch (Exception ex)
                            {
                                if (CodeColumnNum > 0 && PriceColumnNum > 0 && NameColumnNum > 0)
                                    break;
                                oXL.Quit();
                                throw ex;
                            }
                        }

                        for (num = 2; num <= ShtRange.Rows.Count; num++)
                        {
                            Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo drug = new Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo();
                            string Codetemp = string.Empty;
                            try
                            {
                                Codetemp = ShtRange.Cells[num, CodeColumnNum].Value2.ToString();
                            }
                            catch
                            {
                                Codetemp = string.Empty;
                            }
                            string Pricetemp = string.Empty;
                            try
                            {
                                Pricetemp = ShtRange.Cells[num, PriceColumnNum].Value2.ToString();
                            }
                            catch
                            {
                                Pricetemp = string.Empty;
                            }
                            drug.Drug_Code = CodeAnalize(Codetemp);
                            drug.Drug_Price = PriceAnalize(Pricetemp);
                            drug.Drug_Name = ShtRange.Cells[num, NameColumnNum].Value2;
                            if (drug.Drug_Price != string.Empty && drug.Drug_Code != string.Empty)
                                retList.Add(drug);
                        }
                    }
                }

             theWorkbook.Save();
                return retList;
            }
            catch //(Exception ex)
            {
                return null;
            }
            finally
            {
                oXL.Quit();
            }
        }

this problem is appears when I reinstall windows and office. installation office is 2013 (both office and win are 64 bit)

Update:


问:
How to call methods in laravel
I have been studying Laravel now for one month or more and by brain hurts.
After making my own practice web-app this is what buggers me:

I see 2 ways (at least) to call methods / functions. Sometimes they work, sometimes they don't. Why? And what's the difference?

```<code>return ClubTypes::find($id);
return $this->hasMany()->...
</code>```

And when dealing with sql, sometimes I need to put ->get() and sometimes putting the ->get() will give error of not defined.. what's up with that?

Thank you!

答:
Your question contains a lot of details that are not specific to Laravel but are PHP basics. The most significant one is the difference between instance methods called with the arrow operator -> and static methods called with the double double-point operator ::. Instance methods are used when the method call is relative to an instance of a class (also called object) while static methods are used for methods calls that have to do with a class but are not instance specific. An example:

```<code>$dog = new Dog();
$dog->bark(); // only an actual dog can bark

echo Dog::species(); // "Canis lupus familiaris" will be the same species for all dogs
</code>```

With this information, we can now talk about the actual difference regarding Laravel methods.

Model Query Builder

To perform SQL queries, the model query builder can be used. It provides a convenient interface to build queries. Most of the query builder method calls can be translated to SQL very easily. The following three statements are all the same:

```<code>Dog::query(); // model query builder

DB::table('dogs'); // untyped query builder

FROM dogs // SQL
</code>```

For you the most interesting is the first type of query builder, so here is a more complex example:

```<code>Dog::query()
    ->where('color', 'brown')
    ->where('size', '>=', 50) // centimeter
    ->get();

// in SQL
SELECT *
FROM dogs
WHERE color = 'brown' AND size >= 50
</code>```

The method query() is a static method of the Model base class which returns a new Illuminate\Database\Eloquent\Builder object. Some people prefer calling query() explicitely, but you can also omit the call to it and use

```<code>Dog::where('color', 'brown')
    ->where('size', '>=', 50) // centimeter
    ->get();
</code>```

instead. Here, the Model base class will use the magic __callStatic() function to tunnel the method call to where() to a new Illuminate\Database\Eloquent\Builder object. It basically is there just for convenience and you got it right - it's literally magic.

Relationships

When you define a relationship on a model, you create a function that returns something like HasMany or BelongsTo. These objects are created through convenience methods called with $this->hasMany() or $this->belongsTo():

```<code>public function owner(): BelongsTo
{
    $this->belongsTo(Person::class);
}
</code>```

When you now call this relation (which we assume to be on the Dog class), you have two options:

```<code>$owner = $dog->owner()->first();
$owner = $dog->owner()->getResults(); // the same as first()

$owner = $dog->owner;
</code>```

The first two lines will access the relationship and perform an actual SQL query. It's basically SELECT * FROM persons WHERE id = :owner_id:. The second line on the other hand will return the property owner of the dog object, which can be a relationship. If there is no owner property set on the object and Laravel finds a method called owner() (and the method returns a relationship), Laravel will load this relationship with one of the first two lines, store it under the owner property and return it. So it's again a magic accessor for the first (+ it stores the result). A more explicit version of both together is:

```<code>$dog->loadMissing('owner');
$owner = $dog->owner;
</code>```

get() and first()

Relationships that return many results (such as HasMany) will require you to use get() to receive the results. Other relationships that will only return one result (such as BelongsTo) will require you to use first(). When querying models directly (like Dog::where('color', 'brown')->get()), you can use both, depending on what you want to get. first() will give you the first line of the theoretical result, which requires you to use an orderBy() on the query (so that the database knows which the first line is).

As soon as you retrieved a list of results with get(), you have an object of type Illuminate\Database\Eloquent\Collection and you cannot use query builder methods anymore. Here, the collection methods are applicable. Best you have a look at the method reference.

There is a pitfall, as you can use Dog::all() but not Dog::query()->all(). The all() method is special and can be translated to Dog::query()->get().

Title: How to call methods in laravel

Body:
I have been studying Laravel now for one month or more and by brain hurts.
After making my own practice web-app this is what buggers me:

I see 2 ways (at least) to call methods / functions. Sometimes they work, sometimes they don't. Why? And what's the difference?

return ClubTypes::find($id);
return $this->hasMany()->...

And when dealing with sql, sometimes I need to put ->get() and sometimes putting the ->get() will give error of not defined.. what's up with that?

Thank you!

Body:
Your question contains a lot of details that are not specific to Laravel but are PHP basics. The most significant one is the difference between instance methods called with the arrow operator -> and static methods called with the double double-point operator ::. Instance methods are used when the method call is relative to an instance of a class (also called object) while static methods are used for methods calls that have to do with a class but are not instance specific. An example:

$dog = new Dog();
$dog->bark(); // only an actual dog can bark

echo Dog::species(); // "Canis lupus familiaris" will be the same species for all dogs

With this information, we can now talk about the actual difference regarding Laravel methods.

Model Query Builder

To perform SQL queries, the model query builder can be used. It provides a convenient interface to build queries. Most of the query builder method calls can be translated to SQL very easily. The following three statements are all the same:

Dog::query(); // model query builder

DB::table('dogs'); // untyped query builder

FROM dogs // SQL

For you the most interesting is the first type of query builder, so here is a more complex example:

Dog::query()
    ->where('color', 'brown')
    ->where('size', '>=', 50) // centimeter
    ->get();

// in SQL
SELECT *
FROM dogs
WHERE color = 'brown' AND size >= 50

The method query() is a static method of the Model base class which returns a new Illuminate\Database\Eloquent\Builder object. Some people prefer calling query() explicitely, but you can also omit the call to it and use

Dog::where('color', 'brown')
    ->where('size', '>=', 50) // centimeter
    ->get();

instead. Here, the Model base class will use the magic __callStatic() function to tunnel the method call to where() to a new Illuminate\Database\Eloquent\Builder object. It basically is there just for convenience and you got it right - it's literally magic.

Relationships

When you define a relationship on a model, you create a function that returns something like HasMany or BelongsTo. These objects are created through convenience methods called with $this->hasMany() or $this->belongsTo():

public function owner(): BelongsTo
{
    $this->belongsTo(Person::class);
}

When you now call this relation (which we assume to be on the Dog class), you have two options:

$owner = $dog->owner()->first();
$owner = $dog->owner()->getResults(); // the same as first()

$owner = $dog->owner;

The first two lines will access the relationship and perform an actual SQL query. It's basically SELECT * FROM persons WHERE id = :owner_id:. The second line on the other hand will return the property owner of the dog object, which can be a relationship. If there is no owner property set on the object and Laravel finds a method called owner() (and the method returns a relationship), Laravel will load this relationship with one of the first two lines, store it under the owner property and return it. So it's again a magic accessor for the first (+ it stores the result). A more explicit version of both together is:

$dog->loadMissing('owner');
$owner = $dog->owner;

get() and first()

Relationships that return many results (such as HasMany) will require you to use get() to receive the results. Other relationships that will only return one result (such as BelongsTo) will require you to use first(). When querying models directly (like Dog::where('color', 'brown')->get()), you can use both, depending on what you want to get. first() will give you the first line of the theoretical result, which requires you to use an orderBy() on the query (so that the database knows which the first line is).

As soon as you retrieved a list of results with get(), you have an object of type Illuminate\Database\Eloquent\Collection and you cannot use query builder methods anymore. Here, the collection methods are applicable. Best you have a look at the method reference.

There is a pitfall, as you can use Dog::all() but not Dog::query()->all(). The all() method is special and can be translated to Dog::query()->get().


问:
java.lang.NoClassDefFoundError: android.media.ThumbnailUtils
i try to use the android.media.ThumbnailUtils class to fetch the video thumbnails from  the video which is locate under specified path, for that i use the following code,

```<code>Bitmap thumb = android.media.ThumbnailUtils.createVideoThumbnail("/sdcard/video/sample.mp4",
                MediaStore.Images.Thumbnails.MINI_KIND);
return thumb;
</code>```

but it generates this exception.

        java.lang.NoClassDefFoundError: android.media.ThumbnailUtils

Anyone suggest some idea to solve this.

Thanks.

答: The NoClassDefFoundError makes me think that you're not targeting the right API level.  ThumbnailUtils is only in the SDK as of API level 8 (2.2).  Are you running against Froyo or later?</p>

ContentLicense: CC BY-SA 3.0

Body:
i try to use the android.media.ThumbnailUtils class to fetch the video thumbnails from  the video which is locate under specified path, for that i use the following code,

Bitmap thumb = android.media.ThumbnailUtils.createVideoThumbnail("/sdcard/video/sample.mp4",
                MediaStore.Images.Thumbnails.MINI_KIND);
return thumb;

but it generates this exception.

        java.lang.NoClassDefFoundError: android.media.ThumbnailUtils

Anyone suggest some idea to solve this.

Thanks.


问:
.net: Adding dictionary item - check if it exists or allow exception?
I'm adding items to a StringDictionary and it's possible that a duplicate key will come up. This will of course throw an exception.

If the chance of duplicates is very low (ie it will rarely happen), am I better off using a Try Catch block and leaving it unhandled, or should I always do a .ContainsKey check before adding each entry?

I'm assuming that if the likelihood of duplicate keys was high, then allowing exceptions would be a poor decision as they are expensive.

Thoughts?

Edit

I used reflector on the generic Dictionary and found the following for ContainsKey and TryGetValue, as both were mentioned below.

```<code>public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}
</code>```

And

```<code>public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}
</code>```

Am I missing something, or is TryGetValue doing more work than ContainsKey ?

I appreciate the responses, and for my current purpose I'm going to go with doing a ContainsKey call as the collection will be small, and the code more readable.

答: This issue is a lot simpler as of now for .NET Standard 2.1+ and .NET Core 2.0+. Just use the TryAdd method. It handles all the issues you have the most graceful way.

ContentLicense: CC BY-SA 2.5

Body:
I'm adding items to a StringDictionary and it's possible that a duplicate key will come up. This will of course throw an exception.

If the chance of duplicates is very low (ie it will rarely happen), am I better off using a Try Catch block and leaving it unhandled, or should I always do a .ContainsKey check before adding each entry?

I'm assuming that if the likelihood of duplicate keys was high, then allowing exceptions would be a poor decision as they are expensive.

Thoughts?

Edit

I used reflector on the generic Dictionary and found the following for ContainsKey and TryGetValue, as both were mentioned below.

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}

And

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

Am I missing something, or is TryGetValue doing more work than ContainsKey ?

I appreciate the responses, and for my current purpose I'm going to go with doing a ContainsKey call as the collection will be small, and the code more readable.


答: In order to @Autowire, your object should be in the spring ApplicationContext or the IOC container, you can't directly make an instance of it via reflection beacasue spring is using CGlib proxy to enhance your classes and make it available via application context to inject into your  implementation. Spring Beans and Injection

Title: getting null in an @Autowired field in Abstract class


问:
Multidimensional Array - Illegal String Offset
I have an array that for some reason keeps kicking back an error "Illegal String Offset" I have tried several ways to loop through it but none seem to work.

```<code>$fields = Array (
[cookies] => Array (
    [timeout] => 0
    [votes_per_cookie] => 1
    [enabled] => on
    )
[ip] => Array (
    [timeout] => 0
    [filter] =>
    )
[direct] =>  Array ( )
[membership] => Array (
    [type] => Array ( )
    [once] =>  Array ( )
    )
[captcha] =>  Array ( )
[quota] => Array (
    [votes] => 1000
    )
[date] => Array (
    [start] => 1553846400
    [end] => 1554767940
    [enabled] => on
    )
[selection] => Array (
    [minimum] => 1
    [maximum] => 1
    )
[unique_id] => 1547834405
[results] => Array (
    [require_vote] => Array (
        [enabled] => on
        )
    )
);
</code>```

I am trying to get the value of end in the date array. I have tried this:

```<code>foreach($fields as $field) {
  echo $field['end'];
}
</code>```

this outputs the data but also the illegal offset error.

I have tried this:

```<code>foreach($fields as $key => $value) {
  echo $value['end'];
}
</code>```

This also outputs the same reponse.

if I echo key using the above loop, it returns the appropriate keys (cookies, ip, direct, membership, etc)

I have also tried:

```<code>foreach($fields['date'] as $field) {
    $field['end'];
  }
</code>```

This is just an error.

And finally

```<code>foreach($fields as $field) {
  $field['date']['end'];
}
</code>```

just an error.

答:
Reason: end is the key of child array of date index (which is an index of parent array), so you have to use date also to fetch child-key value

Solution:

```<code>echo $fields['date']['end'];
</code>```

Body:
I have an array that for some reason keeps kicking back an error "Illegal String Offset" I have tried several ways to loop through it but none seem to work.

$fields = Array (
[cookies] => Array (
    [timeout] => 0
    [votes_per_cookie] => 1
    [enabled] => on
    )
[ip] => Array (
    [timeout] => 0
    [filter] =>
    )
[direct] =>  Array ( )
[membership] => Array (
    [type] => Array ( )
    [once] =>  Array ( )
    )
[captcha] =>  Array ( )
[quota] => Array (
    [votes] => 1000
    )
[date] => Array (
    [start] => 1553846400
    [end] => 1554767940
    [enabled] => on
    )
[selection] => Array (
    [minimum] => 1
    [maximum] => 1
    )
[unique_id] => 1547834405
[results] => Array (
    [require_vote] => Array (
        [enabled] => on
        )
    )
);

I am trying to get the value of end in the date array. I have tried this:

foreach($fields as $field) {
  echo $field['end'];
}

this outputs the data but also the illegal offset error.

I have tried this:

foreach($fields as $key => $value) {
  echo $value['end'];
}

This also outputs the same reponse.

if I echo key using the above loop, it returns the appropriate keys (cookies, ip, direct, membership, etc)

I have also tried:

foreach($fields['date'] as $field) {
    $field['end'];
  }

This is just an error.

And finally

foreach($fields as $field) {
  $field['date']['end'];
}

just an error.

Body:
Reason: end is the key of child array of date index (which is an index of parent array), so you have to use date also to fetch child-key value

Solution:

echo $fields['date']['end'];


问:
Could not find artifact io.confluent:kafka-rest-parent:pom:5.4.0-SNAPSHOT and 'parent.relativePath' points at no local
I am using maven 3 to run the application but I am getting the following error:

```<code>[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for io.confluent:kafka-rest:[unknown-version]: Could not find artifact io.confluent:kafka-rest-parent:pom:5.4.0-SNAPSHOT and 'parent.relativePath' points at no local POM @ line 7, column 12
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project io.confluent:kafka-rest:[unknown-version] (D:\Self\kafka-rest\pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for io.confluent:kafka-rest:[unknown-version]: Could not find artifact io.confluent:kafka-rest-parent:pom:5.4.0-SNAPSHOT and 'parent.relativePath' points at no local POM @ line 7, column 12 -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
</code>```

here share pom .xml parent element

http://maven.apache.org/maven-v4_0_0.xsd">

```<code>    <modelVersion>4.0.0</modelVersion>

   <parent>
        <groupId>io.confluent</groupId>
        <artifactId>kafka-rest-parent</artifactId>
        <version>5.4.0-SNAPSHOT</version>
    </parent>

    <artifactId>kafka-rest</artifactId>
    <packaging>jar</packaging>
    <name>kafka-rest</name>
    <description>
        The Kafka REST Proxy provides a RESTful interface to a Kafka cluster, making it easy to
        produce and consume messages, view the state of the cluster, and perform administrative
        actions without using the native Kafka protocol or clients.
    </description>
</code>```

答:
In order to build any Confluent project from the master branch, you must build its parent dependencies. You will not find SNAPSHOTS in a downloadable location

This means checking out Kafka source code, use Gradle to install its current snapshot, then Confluent common library, then Confluent Rest utils, and then the Schema Registry (for the Avro converter), and then finally build REST Proxy.

https://github.com/confluentinc/kafka-rest/wiki/FAQ

If you just want to run the REST Proxy, then download the latest Confluent Platform and configure the rest proxy config file to point at any existing Kafka brokers

Body:
I am using maven 3 to run the application but I am getting the following error:

[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for io.confluent:kafka-rest:[unknown-version]: Could not find artifact io.confluent:kafka-rest-parent:pom:5.4.0-SNAPSHOT and 'parent.relativePath' points at no local POM @ line 7, column 12
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project io.confluent:kafka-rest:[unknown-version] (D:\Self\kafka-rest\pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for io.confluent:kafka-rest:[unknown-version]: Could not find artifact io.confluent:kafka-rest-parent:pom:5.4.0-SNAPSHOT and 'parent.relativePath' points at no local POM @ line 7, column 12 -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException

here share pom .xml parent element

http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

   <parent>
        <groupId>io.confluent</groupId>
        <artifactId>kafka-rest-parent</artifactId>
        <version>5.4.0-SNAPSHOT</version>
    </parent>

    <artifactId>kafka-rest</artifactId>
    <packaging>jar</packaging>
    <name>kafka-rest</name>
    <description>
        The Kafka REST Proxy provides a RESTful interface to a Kafka cluster, making it easy to
        produce and consume messages, view the state of the cluster, and perform administrative
        actions without using the native Kafka protocol or clients.
    </description>


问:
Dynamically add rows to form using Vue.JS
I'm trying to make a dynamic form using Vue. User clicks the add button and another row appears for them to add data. The problem is, i initially set only 1 row at first but , when i put the v-for on the div, 3 extra rows started appearing. I'm confused as to why that happened? Plus, nothing happen when i click the add button. Thanks.

Dynamic vue form

Componenet

```<code><div class="container">
<title>exportDATA | Web to Excel</title>
<div class="mt-4">
        <div class="jumbotron bg-dark col-md-10 offset-md-1">
                <div class="card card-body bg-dark" v-for="(user,index) in users" :key="index">
                   <form>
                        <div class="row">
                            <div class="form-group col-md-3">
                                <label for="email" class="text-white">Username:</label>
                                <input type="text" class="form-control" id="username" v-model="user.username">
                            </div>
                            <div class="form-group col-md-3">
                                <label for="pwd" class="text-white">Password:</label>
                                <input type="password" class="form-control" id="password" v-model="user.password">
                            </div>
                            <div class="form-group col-md-3">
                                <label for="pwd" class="text-white">Phone Number:</label>
                                <input type="text" class="form-control" id="phone" v-model="user.phone">
                            </div>
                            <div class="form-group col-md-3">
                                <label for="pwd" class="text-white">Email</label>
                                <input type="email" class="form-control" id="email" v-model="user.email">
                            </div>
                        </div>
                    </form>
                </div>
             <br>
                <button class="btn btn-secondary float-right" title="Click to add row"><span class="fa fa-plus-square" @click="addMoreData(index)" v-show="index == users.length-1"></span>  Add More Data</button>
        </div>

        <div class="jumbotron bg-dark col-md-10 offset-md-1 ">
            <button class="btn btn-success col-md-6 offset-md-3 p-3"><span class="fa fa-plus-square"></span>  Export to Microsoft Excel</button>
        </div>
</div>
</div>
</code>```

Script

```<code>    export default {
    data(){
      return{
          users:{
              username:'',
              password:'',
              email:'',
              phone:''
          }
      }
    },
    methods:{
        addMoreData(index){
            this.users.push({
                username: '',
                password:'',
                email:'',
                phone:''
                });
        }

    },
    mounted() {
        console.log('Component mounted.')
    }
}
</code>```

答:
Your data should be an array that contains objects as items. In your example, v-for directive iterate properties in one object. </p>

```<code>data(){
      return{
          users: [{
              username:'',
              password:'',
              email:'',
              phone:''
          }]
      }
    },
</code>```

Body:
I'm trying to make a dynamic form using Vue. User clicks the add button and another row appears for them to add data. The problem is, i initially set only 1 row at first but , when i put the v-for on the div, 3 extra rows started appearing. I'm confused as to why that happened? Plus, nothing happen when i click the add button. Thanks.

Dynamic vue form

Componenet

<title>exportDATA | Web to Excel</title>

                   <form>

                                Username:
                                <input type="text" class="form-control" id="username" v-model="user.username">

                                Password:
                                <input type="password" class="form-control" id="password" v-model="user.password">

                                Phone Number:
                                <input type="text" class="form-control" id="phone" v-model="user.phone">

                                Email
                                <input type="email" class="form-control" id="email" v-model="user.email">

                    </form>

                <button class="btn btn-secondary float-right" title="Click to add row">  Add More Data</button>

            <button class="btn btn-success col-md-6 offset-md-3 p-3">  Export to Microsoft Excel</button>

Script

    export default {
    data(){
      return{
          users:{
              username:'',
              password:'',
              email:'',
              phone:''
          }
      }
    },
    methods:{
        addMoreData(index){
            this.users.push({
                username: '',
                password:'',
                email:'',
                phone:''
                });
        }

    },
    mounted() {
        console.log('Component mounted.')
    }
}

Body:
Your data should be an array that contains objects as items. In your example, v-for directive iterate properties in one object.

data(){
      return{
          users: [{
              username:'',
              password:'',
              email:'',
              phone:''
          }]
      }
    },


问:
Modify a svg file using jQuery
I have a svg file with some shape and some text. I'd like to modify the svg at runtime, so that some shape can change color, and some text can change its content.

Let's suppose that I have only two elements in an external svg file:

circle1: a blue filled circle witdh that id

text1: a text containing "--" with that id

Now I can view the file in my html with

```<code><object data="Sample.svg" type="image/svg+xml" width="200" height="200" id="svg1"></object>
</code>```

From a button near the image, using jQuery, I can catch the onClick event: I'd like to fill the cicle with red and change the text to "hello word".

How can I do that? Is there a jQuery based solution?

I have found the jquery.svg plugin, but it seem that you can only modify a runtime created document.

Thanks.

答:
I use svgweb to display and programmatically manipulate SVGs using JavaScript. I use it because it ports SVG to IE6+ using Flash, and because it provides some neat SVG loading features.

Since I like using jQuery so much, I patched it to work with svgweb. I used Keith Woods script as an example. Keith's code doesn't support the latest version of jQuery.

Here is the patch: jquery.svgweb-and-svgdom-patch I've been meaning to give it a proper home in the svgweb contrib, but haven't gotten around to it. It's based on Keith's patch, but has some updates. One thing to know, is that for IE, you'll need to put the following code in a script before jQuery loads:

```<code>document.querySelectorAll = null;
</code>```

It's not enough to do this after jQuery loads anymore, so you'd have to use server-side browser detection to inject it, or client-side browser detection in a script before jQuery.

After all that... You can do stuff like:

```<code>$('#mycirc').attr('fill', 'Red');
</code>```

Title: Modify a svg file using jQuery

Body:
I have a svg file with some shape and some text. I'd like to modify the svg at runtime, so that some shape can change color, and some text can change its content.

Let's suppose that I have only two elements in an external svg file:

circle1: a blue filled circle witdh that id

text1: a text containing "--" with that id

Now I can view the file in my html with

<object data="Sample.svg" type="image/svg+xml" width="200" height="200" id="svg1"></object>

From a button near the image, using jQuery, I can catch the onClick event: I'd like to fill the cicle with red and change the text to "hello word".

How can I do that? Is there a jQuery based solution?

I have found the jquery.svg plugin, but it seem that you can only modify a runtime created document.

Thanks.

Body:
I use svgweb to display and programmatically manipulate SVGs using JavaScript. I use it because it ports SVG to IE6+ using Flash, and because it provides some neat SVG loading features.

Since I like using jQuery so much, I patched it to work with svgweb. I used Keith Woods script as an example. Keith's code doesn't support the latest version of jQuery.

Here is the patch: jquery.svgweb-and-svgdom-patch I've been meaning to give it a proper home in the svgweb contrib, but haven't gotten around to it. It's based on Keith's patch, but has some updates. One thing to know, is that for IE, you'll need to put the following code in a script before jQuery loads:

document.querySelectorAll = null;

It's not enough to do this after jQuery loads anymore, so you'd have to use server-side browser detection to inject it, or client-side browser detection in a script before jQuery.

After all that... You can do stuff like:

$('#mycirc').attr('fill', 'Red');


问:
The request was aborted: Could not create SSL/TLS secure channel
We are unable to connect to an HTTPS server using WebRequest because of this error message:

The request was aborted: Could not create SSL/TLS secure channel.

We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:

```<code>private void Somewhere() {
    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}

private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
   return true;
}
</code>```

The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?

I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP.  Does that change something?

答:
The top-voted answer will probably be enough for most people. However, in some circumstances, you could continue getting a "Could not create SSL/TLS secure channel" error even after forcing TLS 1.2. If so, you may want to consult this helpful article for additional troubleshooting steps. To summarize: independent of the TLS/SSL version issue, the client and server must agree on a "cipher suite." During the "handshake" phase of the SSL connection, the client will list its supported cipher-suites for the server to check against its own list. But on some Windows machines, certain common cipher-suites may have been disabled (seemingly due to well-intentioned attempts to limit attack surface), decreasing the possibility of the client & server agreeing on a cipher suite. If they cannot agree, then you may see "fatal alert code 40" in the event viewer and "Could not create SSL/TLS secure channel" in your .NET program.

The aforementioned article explains how to list all of a machine's potentially-supported cipher suites and enable additional cipher suites through the Windows Registry. To help check which cipher suites are enabled on the client, try visiting this diagnostic page in MSIE. (Using System.Net tracing may give more definitive results.) To check which cipher suites are supported by the server, try this online tool (assuming that the server is Internet-accessible). It should go without saying that Registry edits must be done with caution, especially where networking is involved. (Is your machine a remote-hosted VM? If you were to break networking, would the VM  be accessible at all?)

In my company's case, we enabled several additional "ECDHE_ECDSA" suites via Registry edit, to fix an immediate problem and guard against future problems. But if you cannot (or will not) edit the Registry,  then numerous workarounds (not necessarily pretty) come to mind. For example: your .NET program could delegate its SSL traffic to a separate Python program (which may itself work, for the same reason that Chrome requests may succeed where MSIE requests fail on an affected machine).

Body:
We are unable to connect to an HTTPS server using WebRequest because of this error message:

The request was aborted: Could not create SSL/TLS secure channel.

We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:

private void Somewhere() {
    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}

private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
   return true;
}

The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?

I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP.  Does that change something?


问:
wildcard search with multiple parameters in MYSQL?
I have a table named 'contacts'. which consists of some columns. One of the column's name is 'name'.
I want to create a wildcard search using multiple search parameter in name column in one query.

How do I find multiple records using LIKE phrase?

I have tried this code.

```<code>SELECT * FROM contacts WHERE NAME LIKE '%Sudipta%', '%Hasanuzzaman%', '%Jawad%';
</code>```

I expected This result:

```<code>id    |  name             |
----------------------------
254   | Sudipta Kumar     |
280   | Sudipta Chowdhury |
402   | Hasanuzzaman Khan |
452   | MD. Hasanuzzaman  |
469   | Jawad Karim       |
</code>```

But this error message has been displayed:

Error Code: 1064

You have an error in your SQL syntax;

check the manual that corresponds to your MariaDB server version for the right syntax to use near ' '%Hasanuzzaman%', '%Jawad%' LIMIT 0, 1000' at line 1

Please tell me the query to do the above action...

答:
Use LIKE OR Operator in query

```<code>SELECT * FROM contacts WHERE NAME LIKE '%Sudipta%' OR NAME LIKE '%Hasanuzzaman%' OR NAME LIKE '%Jawad%';
</code>```

Hope this help you

Body:
I have a table named 'contacts'. which consists of some columns. One of the column's name is 'name'.
I want to create a wildcard search using multiple search parameter in name column in one query.

How do I find multiple records using LIKE phrase?

I have tried this code.

SELECT * FROM contacts WHERE NAME LIKE '%Sudipta%', '%Hasanuzzaman%', '%Jawad%';

I expected This result:

id    |  name             |
----------------------------
254   | Sudipta Kumar     |
280   | Sudipta Chowdhury |
402   | Hasanuzzaman Khan |
452   | MD. Hasanuzzaman  |
469   | Jawad Karim       |

But this error message has been displayed:

Error Code: 1064

You have an error in your SQL syntax;

check the manual that corresponds to your MariaDB server version for the right syntax to use near ' '%Hasanuzzaman%', '%Jawad%' LIMIT 0, 1000' at line 1

Please tell me the query to do the above action...

Body:
Use LIKE OR Operator in query

SELECT * FROM contacts WHERE NAME LIKE '%Sudipta%' OR NAME LIKE '%Hasanuzzaman%' OR NAME LIKE '%Jawad%';

Hope this help you


问:
vim: How do I map <F5> to prepend a timestamp to the current word the cursor is on?
In vim, when I press F5, I want it to add a timestamp immediately before the word that the cursor is on.

For example: If I have a file with the following text:

```<code>the quick brown
fox jumps
over the lazy
dog
</code>```

and I press F5 while my cursor is on any of the letters in the word jumps, then I want it to add a timestamp immediately before the word jumps, so that it looks like below:

```<code>the quick brown
fox [ 12:34:50 20190531 ] jumps
over the lazy
dog
</code>```

If I move my cursor to any of the letters in the word dog and press F5, then I want it to look like this:

```<code>the quick brown
fox [ 12:34:50 20190531 ] jumps
over the lazy
[ 12:34:58 20190531 ] dog
</code>```

I currently have these lines in my .vimrc that will add a timestamp wherever the cursor is, but I want it to be a little smarter and add the timestamp immediately before the current word that the cursor is on:

```<code>nmap <F5> i<C-R>=strftime("[ %H:%M:%S %Y%m%d ] ")<CR>
imap <F5> <C-R>=strftime("[ %H:%M:%S %Y%m%d ] ")<CR>
</code>```

答:
Try these:

```<code>nnoremap <F5> T<space>i<C-r>=strftime("[ %H:%M:%S %Y%m%d ] ")<cr><esc>
inoremap <F5> <C-o>T<space><C-r>=strftime("[ %H:%M:%S %Y%m%d ] ")<cr>
</code>```

This uses T<space> to move 'till (t/T) the next space, backwards due to the capital T. An explicit space () would work as well, used <space> to highlight.

Body:
In vim, when I press F5, I want it to add a timestamp immediately before the word that the cursor is on.

For example: If I have a file with the following text:

the quick brown
fox jumps
over the lazy
dog

and I press F5 while my cursor is on any of the letters in the word jumps, then I want it to add a timestamp immediately before the word jumps, so that it looks like below:

the quick brown
fox [ 12:34:50 20190531 ] jumps
over the lazy
dog

If I move my cursor to any of the letters in the word dog and press F5, then I want it to look like this:

the quick brown
fox [ 12:34:50 20190531 ] jumps
over the lazy
[ 12:34:58 20190531 ] dog

I currently have these lines in my .vimrc that will add a timestamp wherever the cursor is, but I want it to be a little smarter and add the timestamp immediately before the current word that the cursor is on:

nmap <F5> i<C-R>=strftime("[ %H:%M:%S %Y%m%d ] ")<CR>
imap <F5> <C-R>=strftime("[ %H:%M:%S %Y%m%d ] ")<CR>

Body:
Try these:

nnoremap <F5> T<space>i<C-r>=strftime("[ %H:%M:%S %Y%m%d ] ")<cr><esc>
inoremap <F5> <C-o>T<space><C-r>=strftime("[ %H:%M:%S %Y%m%d ] ")<cr>

This uses T<space> to move 'till (t/T) the next space, backwards due to the capital T. An explicit space () would work as well, used <space> to highlight.


问:
Why scanf() function is not wait me for entring char at the last in below code
I am trying to getting an value in variable c which has an data type of character but it not ask me or wait me to enter the character

I have used   fflush(stdin);  this to flushing previous value if any but it wont work for me

```<code>int main()
{
int a =10;
float f;
double d;
char c ;

scanf("%d",&a);
printf("%d \n",a);

scanf("%f",&f);
printf("%f \n",f);

scanf("%lf",&d);
printf("%lf \n",d);

fflush(stdin);

scanf("%c",&c);
printf("%c \n",c);
return 0;
}
</code>```

Here is what my output looks like

答:
The left over \n from the scanf("%lf",&d); will be consumed at scanf("%c",&c);.

Hence the double line feed in the output.

This answer from the marked duplicate seems to provide a good workaround for the problem (emphasis mine):

```<code>scanf(" %c",&c);
    // ^
</code>```

You can probably rescue it by using " %c" instead of "%c" for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character.

Body:
I am trying to getting an value in variable c which has an data type of character but it not ask me or wait me to enter the character

I have used   fflush(stdin);  this to flushing previous value if any but it wont work for me

int main()
{
int a =10;
float f;
double d;
char c ;

scanf("%d",&a);
printf("%d \n",a);

scanf("%f",&f);
printf("%f \n",f);

scanf("%lf",&d);
printf("%lf \n",d);

fflush(stdin);

scanf("%c",&c);
printf("%c \n",c);
return 0;
}

Here is what my output looks like

Body:
The left over \n from the scanf("%lf",&d); will be consumed at scanf("%c",&c);.

Hence the double line feed in the output.

This answer from the marked duplicate seems to provide a good workaround for the problem (emphasis mine):

scanf(" %c",&c);
    // ^

You can probably rescue it by using " %c" instead of "%c" for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character.


问:
How to aggregate the value from DISTINCT row using LINQ
I have following data:

```<code>Name    Priority
A       3
A       5
B       1
C       1
C       3
C       2
</code>```

I want to get list of distinct names with All priority, so the result

would look like:

```<code>Name    priorities
A       3,5
B       1
C       1,3,2
</code>```

How can I use Linq to do that?

答:
Use this overload of GroupBy</p>

```<code>var grouped = myList.GroupBy(i => i.Name, i => i.Priority,
    (Name, Priorities) => new {Name, Priorities});
</code>```

Body:
I have following data:

Name    Priority
A       3
A       5
B       1
C       1
C       3
C       2

I want to get list of distinct names with All priority, so the result

would look like:

Name    priorities
A       3,5
B       1
C       1,3,2

How can I use Linq to do that?

Body:
Use this overload of GroupBy

var grouped = myList.GroupBy(i => i.Name, i => i.Priority,
    (Name, Priorities) => new {Name, Priorities});


问:
Trying to understand matrices (3D programming)
http://i52.tinypic.com/5mmjoi.png <- take a peek here for the equations

Well, I've been studying matrices lately as I was interested more into the workings of changes of coordinate systems, obj->world and such. And I am looking at this couple of equations which are trying to interpret the vector-matrix multiplication as a linear combination of the matrix's row vectors scaled by the individual components of the u vector.

I do understand that they are just "reshaping" it into a few components, scaling the basis vectors of the translated coordinate system. The standard vector product is exactly the same as the combined row vectors scaled by x,y,z. It's more intuitive to see it when it is decomposed as such than just vague multiplications of the y coordinate with the second vector's x coordinate in the standard version and then added to the z and x values, how the dot product dictates.

My question is: How does one know what alterations are allowed, he just simply picks out the parts of the solution vector, sorting it by x, y and z. Do you simply do that or are there rules. The result certainly is correct, he has all the stuff necessary for a linear combination but how does he know what can and can't he touch?

A little more elaboration, even from the top, would be appreciated? Basically how and why does this work? Thanks everyone!

答:
If I understand your question correctly, it's just a matter of grouping like terms.  We start with regular multiplication uM:

```<code>            | m11 m12 m13 |
| x y z | * | m21 m22 m23 | = | xm11+ym21+zm31 xm12+ym22+zm32 xm13+ym23+zm33 |
            | m31 m32 m33 |
</code>```

The author of your image wants to show that the dot product of the vector with each column is the same thing as taking a weighted sum of each row so that's how he breaks the resulting vector apart.  He's free to break it apart any which way he wants so long as the final sum remains the same.

E.g.:

```<code>| xm11+ym21+zm31 xm12+ym22+zm32 xm13+ym23+zm33 | =
| xm11+ym21 xm12+ym22 xm13+ym23 | + | zm31 zm32 zm33 | =
| xm11 xm12 xm13 | + | ym21 ym22 ym23 | + | zm31 zm32 zm33 | =
| xm11 ym22 zm33 | + | ym21 zm32 xm13 | + | zm31 xm12 ym23 | =
| xm11+ym21+zm31-1 xm12+ym22+zm32-1 xm13+ym23+zm33-1 | + | 1 1 1 |
</code>```

Etc.

Body:
If I understand your question correctly, it's just a matter of grouping like terms.  We start with regular multiplication uM:

            | m11 m12 m13 |
| x y z | * | m21 m22 m23 | = | xm11+ym21+zm31 xm12+ym22+zm32 xm13+ym23+zm33 |
            | m31 m32 m33 |

The author of your image wants to show that the dot product of the vector with each column is the same thing as taking a weighted sum of each row so that's how he breaks the resulting vector apart.  He's free to break it apart any which way he wants so long as the final sum remains the same.

E.g.:

| xm11+ym21+zm31 xm12+ym22+zm32 xm13+ym23+zm33 | =
| xm11+ym21 xm12+ym22 xm13+ym23 | + | zm31 zm32 zm33 | =
| xm11 xm12 xm13 | + | ym21 ym22 ym23 | + | zm31 zm32 zm33 | =
| xm11 ym22 zm33 | + | ym21 zm32 xm13 | + | zm31 xm12 ym23 | =
| xm11+ym21+zm31-1 xm12+ym22+zm32-1 xm13+ym23+zm33-1 | + | 1 1 1 |

Etc.


问:
How can I conditionally insert a character into a string?
Brand new to programming, what I've learned so far I've just copied from similar examples online.

This is a random sentence generator for a foreign language. But, I want to insert a character in between two specific characters in a string if they happen to occur next to each other. In this case, I want the characters in the evowel and avowel variables to be separated by 'y'.

I thought I could try a conditional split + rejoin, but I'm not sure how to search for (in this case) evowel_avowel, split it at that boundary, insert y, then join it back. So a randomly generated string 'eametetuk' would change to 'eyametetuk', 'eseapah' > 'eseyapah' etc.

Edit: I need to be able to handle anything in the evowel with anything in the avowel. For simplicity's sake I've only included two varations of each, but the language has more vowels and more variations (so roughly 60 permutations where this change needs to happen).

Would I need to create my own function for this? I'm guessing I would need regex somewhere.

import random

c1 = ("e","é")
c2 = ("a","se")
root = ("apa","mete")
tense = ("h","tuk")

avowel = ("a","á")
evowel = ("e","é")

#syntax
x = [c1,c2,root,tense]

#randomly selects morphemes
s = "".join([random.choice(i) for i in x])

print(s)
```

答:
You can just do a replacement like below.</p>

```<code>import random

c1 = ("e","é")
c2 = ("a","se")
root = ("apa","mete")
tense = ("h","tuk")

avowel = "éá"
avowelr= "éyá"
evowel = "ea"
evowelr = "eya"

#syntax
x = [c1,c2,root,tense]

#randomly selects morphemes
s = "".join([random.choice(i) for i in x])
s = s.replace(avowel, avowelr)
s = s.replace(evowel, evowelr)
print(s)
</code>```

Body:
You can just do a replacement like below.

import random

c1 = ("e","é")
c2 = ("a","se")
root = ("apa","mete")
tense = ("h","tuk")

avowel = "éá"
avowelr= "éyá"
evowel = "ea"
evowelr = "eya"

#syntax
x = [c1,c2,root,tense]

#randomly selects morphemes
s = "".join([random.choice(i) for i in x])
s = s.replace(avowel, avowelr)
s = s.replace(evowel, evowelr)
print(s)


问:
how to overcome error in images array in javascript
I am trying to insert images (at present there are 7 images)into an array using a for loop and preview(display) those images in a scroll bar. the particular image from the scroll bar on click should appear in the given div.(the should be expanded to the size of the div)
this is for a certificate generator

this js code I triedenter image description here so far

// var div = document.createElement("div");
// div.style.width = "300px";
// div.style.height = "300px";
// div.style.background = "red";
// document.getElementById("con").appendChild(div);
var image=
[
  "themes/theme1.jpg",
  "themes/theme2.jpg",
  "themes/theme3.jpg",
  "themes/theme4.jpg",
  "themes/theme5.jpg",
  "themes/theme6.jpg",
  "themes/theme7.jpg"
];
var arrayLength=image.length;
var i;
var div = document.getElementById("main");
for (i =0;i<arrayLength;i++)
{
  var img=document.createElement("img");
  img.setAttribute("src",image[i]);
  img.setAttribute("width","100");
  img.setAttribute("height","100");
  img.addEventListener('click', function click(event) {
    console.log(img);
    document.getElementById('expandedImage').appendChild(img);
  },false);
  div.appendChild(img);
  // img = null;
}
// function myFunction(img) {
//   var expandImg = document.getElementById("expandedImg");
//   var main = document.getElementById("main");
//   expandImg.src = img.src;
//   expandImg.parentElement.style.display = "block";
// }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" src='index.css'>
</head>
<body>
  <div id="expandedImage" style="width:800px; height:500px;float:left;
border: 1px solid black">
  </div>
  <!-- <div id="con"></div> -->
  <div id="main" style="width:150px; height: 500px; overflow-y:
scroll;float:right">
  </div>
  <script src="index.js"></script>
</body
</html></code>```

I expect the output to be the image I click on, but the actual output is the 7th image of my array

答:
You are passing img variable and your img variable have last created img element.

Instead of img document.getElementById('expandedImage').appendChild(img);

pass this to append click image.

document.getElementById('expandedImage').appendChild(this);

var image = [
  "https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg",
  "themes/theme2.jpg",
  "themes/theme3.jpg",
  "themes/theme4.jpg"
];
var arrayLength = image.length;
var i;
var div = document.getElementById("main");
for (i = 0; i < arrayLength; i++) {
  var img = document.createElement("img");
  img.setAttribute("src", image[i]);
  img.setAttribute("width", "100");
  img.setAttribute("height", "100");
  img.addEventListener('click', function click(event) {
    document.getElementById('expandedImage').appendChild(this);
  }, false);
  div.appendChild(img);
  // img = null;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="expandedImage" style="width:800px; height:500px;float:left;
        border: 1px solid black">
</div>
<!-- <div id="con"></div> -->
<div id="main" style="width:150px; height: 500px; overflow-y:
        scroll;float:right">
</div></code>```

Body:
I am trying to insert images (at present there are 7 images)into an array using a for loop and preview(display) those images in a scroll bar. the particular image from the scroll bar on click should appear in the given div.(the should be expanded to the size of the div)
this is for a certificate generator

this js code I triedenter image description here so far

// var div = document.createElement("div");
// div.style.width = "300px";
// div.style.height = "300px";
// div.style.background = "red";
// document.getElementById("con").appendChild(div);
var image=
[
  "themes/theme1.jpg",
  "themes/theme2.jpg",
  "themes/theme3.jpg",
  "themes/theme4.jpg",
  "themes/theme5.jpg",
  "themes/theme6.jpg",
  "themes/theme7.jpg"
];
var arrayLength=image.length;
var i;
var div = document.getElementById("main");
for (i =0;i<arrayLength;i++)
{
  var img=document.createElement("img");
  img.setAttribute("src",image[i]);
  img.setAttribute("width","100");
  img.setAttribute("height","100");
  img.addEventListener('click', function click(event) {
    console.log(img);
    document.getElementById('expandedImage').appendChild(img);
  },false);
  div.appendChild(img);
  // img = null;
}
// function myFunction(img) {
//   var expandImg = document.getElementById("expandedImg");
//   var main = document.getElementById("main");
//   expandImg.src = img.src;
//   expandImg.parentElement.style.display = "block";
// }

<!DOCTYPE html>

<link rel="stylesheet" type="text/css" src='index.css'>

</body

I expect the output to be the image I click on, but the actual output is the 7th image of my array

Body:
You are passing img variable and your img variable have last created img element.

Instead of img document.getElementById('expandedImage').appendChild(img);

pass this to append click image.

document.getElementById('expandedImage').appendChild(this);

var image = [
  "https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg",
  "themes/theme2.jpg",
  "themes/theme3.jpg",
  "themes/theme4.jpg"
];
var arrayLength = image.length;
var i;
var div = document.getElementById("main");
for (i = 0; i < arrayLength; i++) {
  var img = document.createElement("img");
  img.setAttribute("src", image[i]);
  img.setAttribute("width", "100");
  img.setAttribute("height", "100");
  img.addEventListener('click', function click(event) {
    document.getElementById('expandedImage').appendChild(this);
  }, false);
  div.appendChild(img);
  // img = null;
}

<div id="expandedImage" style="width:800px; height:500px;float:left;
        border: 1px solid black">
</div>
<!-- <div id="con"></div> -->
<div id="main" style="width:150px; height: 500px; overflow-y:
        scroll;float:right">
</div>


问:
in a Dataset column amount mention in abbreviated Million & Billion how to remove and calculate mean of this column
IN data set column "revenue" numeric value mention in $sign and abbreviated Million and Billion form. How to calculate mean value of "Revenue" </p>

```<code>enter code here
 B_l$revenue<-split(B_l$revenue, split="M", Split="B")/1000
</code>```

答:
An option is to use sub to remove the "B|M" with sub and calculate the mean of the column

```<code>mean(as.numeric(sub("B|M", "", B_l$revenue)), na.rm = TRUE)
</code>```

Or using parse_number to extract the numeric part and then get the mean

```<code>library(readr)
mean(parse_number(B_l$revenue), na.rm = TRUE)
</code>```

It is not clear about the division.  If the 'B' elements should be divided by 1000

```<code>i1 <- grepl("B", B_l$revenue)
v1 <- parse_number(B_l$revenue)
v1[i1] <- v1[i1]/1000
mean(v1)
</code>```

Body:
IN data set column "revenue" numeric value mention in $sign and abbreviated Million and Billion form. How to calculate mean value of "Revenue"

enter code here
 B_l$revenue<-split(B_l$revenue, split="M", Split="B")/1000

Body:
An option is to use sub to remove the "B|M" with sub and calculate the mean of the column

mean(as.numeric(sub("B|M", "", B_l$revenue)), na.rm = TRUE)

Or using parse_number to extract the numeric part and then get the mean

library(readr)
mean(parse_number(B_l$revenue), na.rm = TRUE)

It is not clear about the division.  If the 'B' elements should be divided by 1000

i1 <- grepl("B", B_l$revenue)
v1 <- parse_number(B_l$revenue)
v1[i1] <- v1[i1]/1000
mean(v1)


问:
How to use setValues in google scripts
I'm trying to print a 2D array into a spreadsheet, but I am getting some error and I couldn't find any solution.

Here is my solution:

```<code>var URL = blabla
var Sheets = [bla,ble,bli]
var doc = SpreadsheetApp.openByUrl(URL);
var ss3 = doc.getSheetByName(Sheets[2]);
var FinalFacil = [[Matematicas, 1 Medio, Funciones, 6?,
Facil, A;B;C;D;E, D], [Matematicas, 1 Medio, Funciones, 7?, Facil,
A;B;C;D;E, E], [Matematicas, 1 Medio, Funciones, 3?, Facil, A;B;C;D;E, A],
[Matematicas, 1 Medio, Funciones, 4?, Facil, A;B;C;D;E, B]]
ss3.getRange("A1:G4").setValues(FinalFacil);
</code>```

And I am getting the following error: Cannot find method setValues((class))

答:
The problem occurs because is ss3 is undefined. It's undefined because the third element of Sheets is undefined too.

If your spreadsheet has a sheet named bli replace

```<code>var Sheets = [bla,ble,bli]
</code>```

by

```<code>var Sheets = [bla,ble,'bli']
</code>```

Title: How to use setValues in google scripts

Body:
I'm trying to print a 2D array into a spreadsheet, but I am getting some error and I couldn't find any solution.

Here is my solution:

var URL = blabla
var Sheets = [bla,ble,bli]
var doc = SpreadsheetApp.openByUrl(URL);
var ss3 = doc.getSheetByName(Sheets[2]);
var FinalFacil = [[Matematicas, 1 Medio, Funciones, 6?,
Facil, A;B;C;D;E, D], [Matematicas, 1 Medio, Funciones, 7?, Facil,
A;B;C;D;E, E], [Matematicas, 1 Medio, Funciones, 3?, Facil, A;B;C;D;E, A],
[Matematicas, 1 Medio, Funciones, 4?, Facil, A;B;C;D;E, B]]
ss3.getRange("A1:G4").setValues(FinalFacil);

And I am getting the following error: Cannot find method setValues((class))

Body:
The problem occurs because is ss3 is undefined. It's undefined because the third element of Sheets is undefined too.

If your spreadsheet has a sheet named bli replace

var Sheets = [bla,ble,bli]

by

var Sheets = [bla,ble,'bli']