问:
Python json decode error when opening a basic json file
I have an issue opening a pretty basic json file just as a test and I am getting the following output:

```<code>\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

Here is the python code:

```<code>import json

with open('test1.json') as f:
    data = json.load(f)

print(data)
</code>```

Here is the test.json contents:

```<code>{ "Days" : [
    {
        "Date": "04-04-13",
        "Price": "1.61"
    },
    {
        "Date": "04-11-13",
        "Price": "1.61"
    }
    ]
}
</code>```

Any help much appreciated, thank you!

答:
I'm pretty sure that your test1.json file contains a byte order mark. Use the encoding parameter for open() function. Use actual encoding of your file; if I can only guess UTF-8, use encoding='utf-8-sig' as follows:

```<code>import json

path_to_file='D:\\Python\\SO3\\data\\test1.json'

with open(path_to_file, encoding='utf-8-sig') as f:
    data = json.load(f)

print(data)
</code>```

Output: D:\Python\SO3\61667193.py

```<code>{'Days': [{'Price': '1.61', 'Date': '04-04-13'}, {'Price': '1.61', 'Date': '04-11-13'}]}
</code>```

Note: You can detect real encoding/BOM using the following function by ivan_pozdeev:

```<code>def detect_by_bom(path,default):
    with open(path, 'rb') as f:
        raw = f.read(4)    #will read less if the file is smaller
    for enc,boms in \
            ('utf-8-sig',(codecs.BOM_UTF8,)),\
            ('utf-16',(codecs.BOM_UTF16_LE,codecs.BOM_UTF16_BE)),\
            ('utf-32',(codecs.BOM_UTF32_LE,codecs.BOM_UTF32_BE)):
        if any(raw.startswith(bom) for bom in boms): return enc
    return default
</code>```

Body:
I have an issue opening a pretty basic json file just as a test and I am getting the following output:

\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Here is the python code:

import json

with open('test1.json') as f:
    data = json.load(f)

print(data)

Here is the test.json contents:

{ "Days" : [
    {
        "Date": "04-04-13",
        "Price": "1.61"
    },
    {
        "Date": "04-11-13",
        "Price": "1.61"
    }
    ]
}

Any help much appreciated, thank you!

Body:
I'm pretty sure that your test1.json file contains a byte order mark. Use the encoding parameter for open() function. Use actual encoding of your file; if I can only guess UTF-8, use encoding='utf-8-sig' as follows:

import json

path_to_file='D:\\Python\\SO3\\data\\test1.json'

with open(path_to_file, encoding='utf-8-sig') as f:
    data = json.load(f)

print(data)

Output: D:\Python\SO3\61667193.py

{'Days': [{'Price': '1.61', 'Date': '04-04-13'}, {'Price': '1.61', 'Date': '04-11-13'}]}

Note: You can detect real encoding/BOM using the following function by ivan_pozdeev:

def detect_by_bom(path,default):
    with open(path, 'rb') as f:
        raw = f.read(4)    #will read less if the file is smaller
    for enc,boms in \
            ('utf-8-sig',(codecs.BOM_UTF8,)),\
            ('utf-16',(codecs.BOM_UTF16_LE,codecs.BOM_UTF16_BE)),\
            ('utf-32',(codecs.BOM_UTF32_LE,codecs.BOM_UTF32_BE)):
        if any(raw.startswith(bom) for bom in boms): return enc
    return default


来源: stackexchange

问:
Ambiguous call on overloaded variadic template function
I downloaded a C++ library to support multiple dimension array from github, when I built it using GCC8.2.0, the complier ran into a message saying an overrload function is ambiguous.  Consider following code:

```<code>// basic function, set the length i for the dimension D
template<int Rank,int D>
void set_array(std::array<int,Rank>& A,int i)
{
    A[D] = i;
}

// function with parameter pack, set the length for all dimensions recursively
template<int Rank,int D,typename... indices>
void set_array(std::array<int,Rank>& A,int i,indices... idx)
{
    A[D] = i;
    set_array<Rank,D+1>(A,idx...);
}

// class calls set_array in allocation
template<typename T,int Rank>
class MultiArray
{

private:
    std::array<int,Rank> _dim = {{0}};

    template<typename... indices>
    void allocate(indices... idx) {
        static_assert(sizeof...(idx) == Rank,
                      "NUMBER OF INDICES PASSED TO ALLOCATE DOES NOT MATCH RANK OF ARRAY");
        set_array<Rank,0>(_dim,idx...);
    }
};

// code to create object of above MultiArray class.

MultiArray<int, 1> a;
a.allocate(10)
</code>```

The compiler error message is:
call  of overrloaded "set_array<1,0>(std::array&, int&) is ambiguous,

My understanding is when calling set_array<1, 0>(_dim, 10), the compiler can not know which one should be used because the parameter pack can be empty. I tried some ways to fix but failed. Is there any solution to help me out?  Thank you in advance!

答:
Your problem here is parameter packs are allowed to be empty.  If you do have an empty pack, then

```<code>void set_array(std::array<int,Rank>& A,int i,indices... idx)
</code>```

is just

```<code>void set_array(std::array<int,Rank>& A,int i)
</code>```

which matches your non-variadic template.  You need to handle having an empty parameter pack and easiest way to do that is to add an extra parameter like

```<code>template<int Rank,int D, typename First, typename... Rest>
void set_array(std::array<int,Rank>& A,int i,First first, Rest... rest)
{
    A[D] = i;
    set_array<Rank,D+1>(A,first, rest...);
}
</code>```

and now if you call the function with only 2 parameters you'll get the non variadic overload and 3 or more will call the variadic one.

ContentLicense: CC BY-SA 4.0

Body:
I downloaded a C++ library to support multiple dimension array from github, when I built it using GCC8.2.0, the complier ran into a message saying an overrload function is ambiguous.  Consider following code:

// basic function, set the length i for the dimension D
template<int Rank,int D>
void set_array(std::array<int,Rank>& A,int i)
{
    A[D] = i;
}

// function with parameter pack, set the length for all dimensions recursively
template<int Rank,int D,typename... indices>
void set_array(std::array<int,Rank>& A,int i,indices... idx)
{
    A[D] = i;
    set_array<Rank,D+1>(A,idx...);
}

// class calls set_array in allocation
template<typename T,int Rank>
class MultiArray
{

private:
    std::array<int,Rank> _dim = {{0}};

    template<typename... indices>
    void allocate(indices... idx) {
        static_assert(sizeof...(idx) == Rank,
                      "NUMBER OF INDICES PASSED TO ALLOCATE DOES NOT MATCH RANK OF ARRAY");
        set_array<Rank,0>(_dim,idx...);
    }
};

// code to create object of above MultiArray class.

MultiArray<int, 1> a;
a.allocate(10)

The compiler error message is:
call  of overrloaded "set_array<1,0>(std::array&, int&) is ambiguous,

My understanding is when calling set_array<1, 0>(_dim, 10), the compiler can not know which one should be used because the parameter pack can be empty. I tried some ways to fix but failed. Is there any solution to help me out?  Thank you in advance!

Body:
Your problem here is parameter packs are allowed to be empty.  If you do have an empty pack, then

void set_array(std::array<int,Rank>& A,int i,indices... idx)

is just

void set_array(std::array<int,Rank>& A,int i)

which matches your non-variadic template.  You need to handle having an empty parameter pack and easiest way to do that is to add an extra parameter like

template<int Rank,int D, typename First, typename... Rest>
void set_array(std::array<int,Rank>& A,int i,First first, Rest... rest)
{
    A[D] = i;
    set_array<Rank,D+1>(A,first, rest...);
}

and now if you call the function with only 2 parameters you'll get the non variadic overload and 3 or more will call the variadic one.


问:
vue checkbox insanity, how to toggle a global checkbox if all checkboxes inside it are true
how can i do a checkbox system with a structure like:
i have multiple checkbox groups and each of them got there very own checkboxes inside.
and if all children checkboxes inside are true then toggle the daddy checkbox to true.
if either one of the children are false, then toggle the checked="true" from the daddy checkbox to false.
the daddy checkbox should only be true if all of his own children are set to true.

i did a little codesandbox to show what i mean.

This is the tale of the childrens and there daddy (checkbox)

答:
your sandbox has been updated.
you were simply returning the checkboxes that are checked inside checkGroupCheckbox function.

you will need to check if the checked boxes length is equal to the length of all the boxes and update the checked prop of the current group.

methods: {
    checkGroupCheckbox(group) {
      group.checked =
        group.checkboxes.filter(item => item.checked).length ===
        group.checkboxes.length;
    }
  }
```

updated fiddle can be found here.

Body:
your sandbox has been updated.
you were simply returning the checkboxes that are checked inside checkGroupCheckbox function.

you will need to check if the checked boxes length is equal to the length of all the boxes and update the checked prop of the current group.

methods: {
    checkGroupCheckbox(group) {
      group.checked =
        group.checkboxes.filter(item => item.checked).length ===
        group.checkboxes.length;
    }
  }

updated fiddle can be found here.


问:
using functions of an implemented interface creates 'not a function' error
I defined an interface with variables and a function.

When trying to use the function implemented for a class I get 'ERROR TypeError: ...getPrice is not a function"

The definition of the class and interface:

```<code>export interface Charge {
  code: string;
  name: string;

  getPrice: (category: string) => number;
}

export class StorePrice implements Charge {
  code: string;
  name: string;

  getPrice(category: string): number {
    return 234;
  }
}
</code>```

The component:

```<code>@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {

  charges: Charge[];

  constructor() {
    this.charges = [
      {
        code: "125",
        name: "apple"
      } as StorePrice,
    ];
  }

  asStorePrice(charge: Charge) {
    return charge as StorePrice;
  }
}
</code>```

The HTML where I actually use the function:

```<code><div>
  <div *ngFor="let charge of charges">

  {{asStorePrice(charge).getPrice()}}

  </div>
</div>
</code>```

答:
the problem is this:

```<code>this.charges = [
  {
    code: "125",
    name: "apple"
  } as StorePrice,
];
</code>```

You could create an Object of StorePrice :

```<code>new StorePrice('125', 'apple');
</code>```

with:

```<code>export class StorePrice implements Charge {

  constructor(
      public code: string,
      public name: string
  ) {}

  getPrice(category: string): number {
    return 234;
  }
}
</code>```

Body:
I defined an interface with variables and a function.

When trying to use the function implemented for a class I get 'ERROR TypeError: ...getPrice is not a function"

The definition of the class and interface:

export interface Charge {
  code: string;
  name: string;

  getPrice: (category: string) => number;
}

export class StorePrice implements Charge {
  code: string;
  name: string;

  getPrice(category: string): number {
    return 234;
  }
}

The component:

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {

  charges: Charge[];

  constructor() {
    this.charges = [
      {
        code: "125",
        name: "apple"
      } as StorePrice,
    ];
  }

  asStorePrice(charge: Charge) {
    return charge as StorePrice;
  }
}

The HTML where I actually use the function:

  {{asStorePrice(charge).getPrice()}}

Body:
the problem is this:

this.charges = [
  {
    code: "125",
    name: "apple"
  } as StorePrice,
];

You could create an Object of StorePrice :

new StorePrice('125', 'apple');

with:

export class StorePrice implements Charge {

  constructor(
      public code: string,
      public name: string
  ) {}

  getPrice(category: string): number {
    return 234;
  }
}


问:
Falsely identifying duplicate parameter names?
I have this prices object

```<code>const prices = {
  hotDog: 453,
  burger: 765,
  sausage: 634,
  corn: 234,
};
</code>```

When I tried to sort them based on prices, the problem occurs in the function arguments of the custom compare function that I wrote

```<code>const f = Object.entries(prices).sort(([_, p1], [_, p2]) => p1 - p2);
// debugger;
console.table(f);
</code>```

Error: Uncaught SyntaxError: Duplicate parameter name not allowed in this context

The parameters however have different names -  p1 and p2.

Of course if I remove destructuring and use Object.entries(prices).sort((p1, p2) => p1[1] - p2[1]); it works fine, but the question is why does the error say "Duplicate parameters name"?

答:
your problem comes from sort(([_, p1], [_, p2]) try with sort(([x, p1], [y, p2])

Even if you don't use variable _, engine will evaluate those parameters.

Body:
I have this prices object

const prices = {
  hotDog: 453,
  burger: 765,
  sausage: 634,
  corn: 234,
};

When I tried to sort them based on prices, the problem occurs in the function arguments of the custom compare function that I wrote

const f = Object.entries(prices).sort(([_, p1], [_, p2]) => p1 - p2);
// debugger;
console.table(f);

Error: Uncaught SyntaxError: Duplicate parameter name not allowed in this context

The parameters however have different names -  p1 and p2.

Of course if I remove destructuring and use Object.entries(prices).sort((p1, p2) => p1[1] - p2[1]); it works fine, but the question is why does the error say "Duplicate parameters name"?


问:
Add files to a ZIP archive?
What component or method can be used to specify a list of filenames and then zip them into a single archive?

I dont need advanced features or anything really, but if I could add some filenames to a stringlist for example then put those files into a ZIP that would be good.

Ive tried searching a few components but not sure which ones to use.

Thanks

答: In addition to VCLZip that Chris mentioned, Abbrevia (one of the old TurboPower packages) is available for free at SourceForge. If you need Delphi 2010/XE versions, you can find those available at SongBeamer (if the changes haven't been incorporated into the SF tree yet). As I was well educated about in the comments to my answer, the D2010/XE changes (as well as many bugfixes and new features) have been added to the project at SF, so the SongBeamer version is no longer needed.

ContentLicense: CC BY-SA 3.0

Title: Add files to a ZIP archive?


问:
Multer returns req.file as undefined, and req.file.location as location undefined while uploading file to aws bucket
I am trying to upload images to s3 Bucket. And have tried many solutions online yet I get the above errors. I don't want to store images locally, instead I want to upload them directly to s3 bucket. Any help would be appreciated.

This is Upload.js file

```<code>const AWS = require('aws-sdk');
const Keys = require('../Config/dev');
const { v4: uuidv4 } = require('uuid');
const axios = require('axios').default;
const multer = require('multer');
const multerS3 = require('multer-s3');

const s3 = new AWS.S3({
  accessKeyId: Keys.accessKeyId,
  secretAccessKey: Keys.secretAccessKey,
  region : 'ap-south-1'
});

var upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'thebucketname',
    acl : "public-read",
    metadata: function (req, file, cb) {
      cb(null, {fieldName: file.fieldname});
    },
    key: function (req, file , cb){
        cb(new Date().toISOString().replace(/[-T:\.Z]/g, "") + file.originalname);
    }
  })
});

module.exports = upload;
</code>```

This is the router code

```<code>const express = require('express');
const Router = express.Router();
const controllers = require('../controllers/controllers.js');
const uploader = require('../controllers/Upload');
const singleUpload = uploader.single('img');

Router.post('/single-image',(req, res)=>{
    singleUpload(req, res , (err)=>{
        if(!req.file){
            console.log(req.file);
        }else
        {
        console.log(req.file);
        return res.json({'imageUrl': req.file.location});
        }
    });
});
</code>```

This is how I am using postman for api request. I have also set Content-Type to Multipart/form-data inside the Headers in postman. I get the error "undefined" for req.file when I do this.

Also, If I use

```<code> app.use(multer({dest:'./public/uploads/'}).single('file'));
</code>```

my file gets stored in the 'uploads' folder but then I get the error "req.file.location undefined", and file doesn't upload to aws.

答:
Firstly, if you want to upload files to s3 and not store it on your server, you can store the uploaded file as an in-memory buffer instead of writing it on your server and then uploading to s3. NOTE: this in-memory method is not recommended with large files or a large number of small files, because you need to ensure that your server has enough memory to deal with the uploads.

Then you can just pass the buffer to the s3 upload function. I don't know much about some package called multer-s3 that you've apparantly used so I'm not using that. I had made it for an array of files but it should work for single files also. I combined your code with some of my code and came up with the following:

```<code>//aws-sdk for node
const AWS = require('aws-sdk');
AWS.config.update({ region: <your region here> });

//S3
const S3 = new AWS.S3({});

const express = require('express');
const Router = express.Router();
const controllers = require('../controllers/controllers.js');
const uploader = require('../controllers/Upload');

//import multer
const multer = require("multer");

//make multer ready for in-memory storage of uploaded file
const multerMemoryStorage = multer.memoryStorage();
const multerUploadInMemory = multer({
    storage: multerMemoryStorage
});

//using multer.single as a middleware is what I prefer
Router.post('/single-image',multerUploadInMemory.single("filename"),async(req, res)=>{

    try{

        if(!req.file || !req.file.buffer){
            throw new Error("File or buffer not found");
        }

        const uploadResult = await S3.upload({
                    Bucket: "yourBucketName",
                    Key: "WhateverKeynameYouWantToGive",
                    Body: req.file.buffer,
                    ACL: 'public-read'
                }).promise();

        console.log(`Upload Successful!`);

        res.send({
            message: "file uploaded"
        })

    }catch(e){
        console.error(`ERROR: ${e.message}`);

        res.status(500).send({
            message: e.message
        })
    }

});
</code>```

You can first use console.log(req.file) to see if it's not undefined (which it shouldn't be) and you can check if you're getting the buffer property in the file.

Also, it says in a "warning" here that you should never add multer as a global middleware, so app.use(multer({dest:'./public/uploads/'}) is a no-no.

Body:
I am trying to upload images to s3 Bucket. And have tried many solutions online yet I get the above errors. I don't want to store images locally, instead I want to upload them directly to s3 bucket. Any help would be appreciated.

This is Upload.js file

const AWS = require('aws-sdk');
const Keys = require('../Config/dev');
const { v4: uuidv4 } = require('uuid');
const axios = require('axios').default;
const multer = require('multer');
const multerS3 = require('multer-s3');

const s3 = new AWS.S3({
  accessKeyId: Keys.accessKeyId,
  secretAccessKey: Keys.secretAccessKey,
  region : 'ap-south-1'
});

var upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'thebucketname',
    acl : "public-read",
    metadata: function (req, file, cb) {
      cb(null, {fieldName: file.fieldname});
    },
    key: function (req, file , cb){
        cb(new Date().toISOString().replace(/[-T:\.Z]/g, "") + file.originalname);
    }
  })
});

module.exports = upload;

This is the router code

const express = require('express');
const Router = express.Router();
const controllers = require('../controllers/controllers.js');
const uploader = require('../controllers/Upload');
const singleUpload = uploader.single('img');

Router.post('/single-image',(req, res)=>{
    singleUpload(req, res , (err)=>{
        if(!req.file){
            console.log(req.file);
        }else
        {
        console.log(req.file);
        return res.json({'imageUrl': req.file.location});
        }
    });
});

This is how I am using postman for api request. I have also set Content-Type to Multipart/form-data inside the Headers in postman. I get the error "undefined" for req.file when I do this.

Also, If I use

 app.use(multer({dest:'./public/uploads/'}).single('file'));

my file gets stored in the 'uploads' folder but then I get the error "req.file.location undefined", and file doesn't upload to aws.

Body:
Firstly, if you want to upload files to s3 and not store it on your server, you can store the uploaded file as an in-memory buffer instead of writing it on your server and then uploading to s3. NOTE: this in-memory method is not recommended with large files or a large number of small files, because you need to ensure that your server has enough memory to deal with the uploads.

Then you can just pass the buffer to the s3 upload function. I don't know much about some package called multer-s3 that you've apparantly used so I'm not using that. I had made it for an array of files but it should work for single files also. I combined your code with some of my code and came up with the following:

//aws-sdk for node
const AWS = require('aws-sdk');
AWS.config.update({ region: <your region here> });

//S3
const S3 = new AWS.S3({});

const express = require('express');
const Router = express.Router();
const controllers = require('../controllers/controllers.js');
const uploader = require('../controllers/Upload');

//import multer
const multer = require("multer");

//make multer ready for in-memory storage of uploaded file
const multerMemoryStorage = multer.memoryStorage();
const multerUploadInMemory = multer({
    storage: multerMemoryStorage
});

//using multer.single as a middleware is what I prefer
Router.post('/single-image',multerUploadInMemory.single("filename"),async(req, res)=>{

    try{

        if(!req.file || !req.file.buffer){
            throw new Error("File or buffer not found");
        }

        const uploadResult = await S3.upload({
                    Bucket: "yourBucketName",
                    Key: "WhateverKeynameYouWantToGive",
                    Body: req.file.buffer,
                    ACL: 'public-read'
                }).promise();

        console.log(`Upload Successful!`);

        res.send({
            message: "file uploaded"
        })

    }catch(e){
        console.error(`ERROR: ${e.message}`);

        res.status(500).send({
            message: e.message
        })
    }

});

You can first use console.log(req.file) to see if it's not undefined (which it shouldn't be) and you can check if you're getting the buffer property in the file.

Also, it says in a "warning" here that you should never add multer as a global middleware, so app.use(multer({dest:'./public/uploads/'}) is a no-no.


问:
Android Kotlin get data from a clicked item in Recyclerview and pass it between fragments
So I have two data classes (OutletListDataClass and ProductListDataClass) that are currently used by two different fragments (OutletListFragment.kt and ProductListFragment.kt, directly connected in navigation graph.).

Both of there fragments are RecyclerView. I want to extract the information from clicked item in OutletListFragment.kt (That contained in the two data classes) and pass it to ProductListFragment.kt.

These are the data classes I use in both fragments:

OutletListDataClass

```<code>data class OutletListPOJODataClasses(

    @SerializedName("data")
    @Expose
    var data: List<OutletListPOJODataClassesDataItem>? = null,

    @SerializedName("error")
    val error: OutletListDataClassError? = null
)

data class OutletListPOJODataClassesDataItem(
    @SerializedName("stk_prodcode")//Both data classes have this variable
    @Expose
    val stkProdcode: String? = null,

    @SerializedName("stk_allqty")
    @Expose
    val stkAllqty: Int? = null,

    @SerializedName("skt_lastupdate")
    @Expose
    val sktLastupdate: String? = null,

    @SerializedName("outlet_address")
    @Expose
    val outletAddress: String? = null,

    @SerializedName("outlet_name")
    @Expose
    val outletName: String? = null,

    @SerializedName("stk_outcode")
    @Expose
    val stkOutcode: String? = null
)
</code>```

ProductListDataClass

```<code>data class ProductListPOJODataClasses(

    @field:SerializedName("data")
    val data: List<ProductListPOJODataClassesDataItem?>? = null,

    @field:SerializedName("error")
    val error: ProductListDataClassError? = null
)

data class ProductListDataClassError(

    @field:SerializedName("msg")
    val msg: String? = null,

    @field:SerializedName("code")
    val code: Int? = null,

    @field:SerializedName("status")
    val status: Boolean? = null
)

data class ProductListPOJODataClassesDataItem(
    @field:SerializedName("stk_prodcode")  //Both data classes have this variable
    val stkProdcode: String? = null,

    @field:SerializedName("stk_allqty")
    val stkAllqty: Int? = null,

    @field:SerializedName("pro_saleprice")
    val proSaleprice: Int? = null,

    @field:SerializedName("skt_lastupdate")
    val sktLastupdate: String? = null,

    @field:SerializedName("stk_outcode")
    val stkOutcode: String? = null,

    @field:SerializedName("pro_name")
    val proName: String? = null
)
</code>```

As You can see, these two data Classes contains the sa.me variable (StkOutcode). And That's what I want to extract (From OutletListDataItem)

Here's the code snippet of the current OutletListFragment.kt:

```<code>override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    (activity as AppCompatActivity).supportActionBar?.title = "Product List"

    binding = DataBindingUtil.inflate(
        inflater,
        R.layout.fragment_product_stock_outlet_list,
        container,
        false
    )

    //Show Progressbar While loading data
    showProgressBar()

    //Apply layout manager
    binding.rvOutletList.layoutManager = LinearLayoutManager((activity as AppCompatActivity))

    //Fetch Outlet List Data
    fetchOutletListData()

    // Declare that this fragment has menu
    setHasOptionsMenu(true)

    // Set action bar title to "Outlet List"
    (activity as AppCompatActivity).supportActionBar?.title = "Outlet List"

    return binding.root
}
</code>```

And this is the recyclerview adapter I created for OutletListFragment.
OutletListAdapter

```<code> class OutletListItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    fun bind(
        outlet: OutletListPOJODataClassesDataItem,
        clickListener: OutletListOnItemClickListener?
    ) {
        itemView.outletName.text = outlet.outletName

        itemView.setOnClickListener {
            clickListener?.onItemClicked(outlet)
        }
    }
}

class OutletListAdapter(private var outletList: OutletListPOJODataClasses, private val itemClickListener: OutletListOnItemClickListener)
: RecyclerView.Adapter<OutletListItemHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OutletListItemHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.outlet_list_item_layout, parent, false)
        return OutletListItemHolder(v)
    }

    override fun getItemCount(): Int = outletList.data!!.size

    override fun onBindViewHolder(holder: OutletListItemHolder, position: Int) {
        val outlet = outletList.data?.get(position)
        if (outlet != null) {
            holder.bind(outlet, itemClickListener)
        }
    }
}

interface OutletListOnItemClickListener{
    fun onItemClicked(outlet: OutletListPOJODataClassesDataItem)
}
</code>```

How I can get the variable I want from the Data class in OutletListFragment.kt and pass it to ProductListFragment.kt ? If there's anything unclear, let me know.

Edit:

This is the snippet of the navigation.xml:

```<code><fragment
    android:id="@+id/productStockOutletList"
    android:name="com.example.switchingandroidappproject.mainFragments.ProductStockOutletListFragment"
    android:label="ProductStockOutletList" >
    <action
        android:id="@+id/action_productStockOutletList_to_productListFragment"
        app:destination="@id/productListFragment"
        app:enterAnim="@android:anim/slide_in_left"
        app:exitAnim="@android:anim/slide_out_right"
        app:popEnterAnim="@android:anim/slide_in_left"
        app:popExitAnim="@anim/slide_out_left" />
</fragment>

<fragment
    android:id="@+id/productListFragment"
    android:name="com.example.switchingandroidappproject.mainFragments.ProductListFragment"
    android:label="ProductListFragment" />
</code>```

答:
If you are using Jetpack Navigation (and as you are referring to things like "navigation graphs", so clearly you are using Jetpack Navigation), then to pass arguments between navigation destinations, you must define an <action with the right arguments that is then passed as some variant of parcelable data to the other fragment.

This is the example from the docs:

```<code><action android:id="@+id/startMyFragment"
    app:destination="@+id/myFragment">
    <argument
        android:name="myArg"
        app:argType="integer"
        android:defaultValue="1" />
</action>
</code>```

So in your case, it should like you need something like

```<code><navigation ...>
    <action android:id="@+id/toProductListFragment"
        app:destination="@+id/productListFragment">
        <argument
            android:name="stkProdcode"
            app:argType="string" />
    </action>
</code>```

Apparently this stuff only works if you also enable the safeargs plugin (as otherwise you have to "remember" this key yourself, or write the NavDirections class by hand, or put together the Bundle yourself - either way, Jetpack Navigation expects you to use Safeargs to pass arguments):

```<code>buildscript {
    dependencies {
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.2.2"
</code>```

And

```<code>apply plugin: "androidx.navigation.safeargs.kotlin"
</code>```

And then you should be able to do

```<code>class OutletListFragment: Fragment(), OutletListOnItemClickListener {
    ....

    override fun onItemClicked(outlet: OutletListPOJODataClassesDataItem) {
        Navigation.findNavController(view).navigate(NavigationDirections.toProductListFragment(outlet.stkProdcode))
    }
}
</code>```

And due to limitations of Jetpack Navigation, you also have to duplicate the argument definition into the <fragment tag as well:

```<code><fragment
    android:id="@+id/productListFragment"
    android:name="com.example.switchingandroidappproject.mainFragments.ProductListFragment"
    android:label="ProductListFragment" >
    <argument
        android:name="stkProdcode"
        app:argType="string" />
</fragment>
</code>```

Make sure not to make a typo (android:name mismatch) as you'd run into unexpected failures).

Now you can obtain your arguments on the other side as

```<code>val args = ProductListFragmentArgs.fromBundle(getArguments())
val code = args.stkProdcode
</code>```

I don't really use Jetpack Navigation, so I'm surprised to see that you have to duplicate the fragment args to the action args, but there you have it.

...to think with what I use in place of Jetpack Navigation, this is as simple as

```<code>// send
backstack.goTo(ProductListScreen(stkProdCode))
// receive
val prodCode = getKey<ProductListScreen>().stkProdCode
</code>```

And is just as (if not more) type-safe.  *grumble* *grumble* but that doesn't help your case, that's not Jetpack Navigation.

Body:
So I have two data classes (OutletListDataClass and ProductListDataClass) that are currently used by two different fragments (OutletListFragment.kt and ProductListFragment.kt, directly connected in navigation graph.).

Both of there fragments are RecyclerView. I want to extract the information from clicked item in OutletListFragment.kt (That contained in the two data classes) and pass it to ProductListFragment.kt.

These are the data classes I use in both fragments:

OutletListDataClass

data class OutletListPOJODataClasses(

    @SerializedName("data")
    @Expose
    var data: List<OutletListPOJODataClassesDataItem>? = null,

    @SerializedName("error")
    val error: OutletListDataClassError? = null
)

data class OutletListPOJODataClassesDataItem(
    @SerializedName("stk_prodcode")//Both data classes have this variable
    @Expose
    val stkProdcode: String? = null,

    @SerializedName("stk_allqty")
    @Expose
    val stkAllqty: Int? = null,

    @SerializedName("skt_lastupdate")
    @Expose
    val sktLastupdate: String? = null,

    @SerializedName("outlet_address")
    @Expose
    val outletAddress: String? = null,

    @SerializedName("outlet_name")
    @Expose
    val outletName: String? = null,

    @SerializedName("stk_outcode")
    @Expose
    val stkOutcode: String? = null
)

ProductListDataClass

data class ProductListPOJODataClasses(

    @field:SerializedName("data")
    val data: List<ProductListPOJODataClassesDataItem?>? = null,

    @field:SerializedName("error")
    val error: ProductListDataClassError? = null
)

data class ProductListDataClassError(

    @field:SerializedName("msg")
    val msg: String? = null,

    @field:SerializedName("code")
    val code: Int? = null,

    @field:SerializedName("status")
    val status: Boolean? = null
)

data class ProductListPOJODataClassesDataItem(
    @field:SerializedName("stk_prodcode")  //Both data classes have this variable
    val stkProdcode: String? = null,

    @field:SerializedName("stk_allqty")
    val stkAllqty: Int? = null,

    @field:SerializedName("pro_saleprice")
    val proSaleprice: Int? = null,

    @field:SerializedName("skt_lastupdate")
    val sktLastupdate: String? = null,

    @field:SerializedName("stk_outcode")
    val stkOutcode: String? = null,

    @field:SerializedName("pro_name")
    val proName: String? = null
)

As You can see, these two data Classes contains the sa.me variable (StkOutcode). And That's what I want to extract (From OutletListDataItem)

Here's the code snippet of the current OutletListFragment.kt:

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    (activity as AppCompatActivity).supportActionBar?.title = "Product List"

    binding = DataBindingUtil.inflate(
        inflater,
        R.layout.fragment_product_stock_outlet_list,
        container,
        false
    )

    //Show Progressbar While loading data
    showProgressBar()

    //Apply layout manager
    binding.rvOutletList.layoutManager = LinearLayoutManager((activity as AppCompatActivity))

    //Fetch Outlet List Data
    fetchOutletListData()

    // Declare that this fragment has menu
    setHasOptionsMenu(true)

    // Set action bar title to "Outlet List"
    (activity as AppCompatActivity).supportActionBar?.title = "Outlet List"

    return binding.root
}

And this is the recyclerview adapter I created for OutletListFragment.
OutletListAdapter

 class OutletListItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    fun bind(
        outlet: OutletListPOJODataClassesDataItem,
        clickListener: OutletListOnItemClickListener?
    ) {
        itemView.outletName.text = outlet.outletName

        itemView.setOnClickListener {
            clickListener?.onItemClicked(outlet)
        }
    }
}

class OutletListAdapter(private var outletList: OutletListPOJODataClasses, private val itemClickListener: OutletListOnItemClickListener)
: RecyclerView.Adapter<OutletListItemHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OutletListItemHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.outlet_list_item_layout, parent, false)
        return OutletListItemHolder(v)
    }

    override fun getItemCount(): Int = outletList.data!!.size

    override fun onBindViewHolder(holder: OutletListItemHolder, position: Int) {
        val outlet = outletList.data?.get(position)
        if (outlet != null) {
            holder.bind(outlet, itemClickListener)
        }
    }
}

interface OutletListOnItemClickListener{
    fun onItemClicked(outlet: OutletListPOJODataClassesDataItem)
}

How I can get the variable I want from the Data class in OutletListFragment.kt and pass it to ProductListFragment.kt ? If there's anything unclear, let me know.

Edit:

This is the snippet of the navigation.xml:

<fragment
    android:id="@+id/productStockOutletList"
    android:name="com.example.switchingandroidappproject.mainFragments.ProductStockOutletListFragment"
    android:label="ProductStockOutletList" >
    <action
        android:id="@+id/action_productStockOutletList_to_productListFragment"
        app:destination="@id/productListFragment"
        app:enterAnim="@android:anim/slide_in_left"
        app:exitAnim="@android:anim/slide_out_right"
        app:popEnterAnim="@android:anim/slide_in_left"
        app:popExitAnim="@anim/slide_out_left" />
</fragment>

<fragment
    android:id="@+id/productListFragment"
    android:name="com.example.switchingandroidappproject.mainFragments.ProductListFragment"
    android:label="ProductListFragment" />

Body:
If you are using Jetpack Navigation (and as you are referring to things like "navigation graphs", so clearly you are using Jetpack Navigation), then to pass arguments between navigation destinations, you must define an <action with the right arguments that is then passed as some variant of parcelable data to the other fragment.

This is the example from the docs:

<action android:id="@+id/startMyFragment"
    app:destination="@+id/myFragment">
    <argument
        android:name="myArg"
        app:argType="integer"
        android:defaultValue="1" />
</action>

So in your case, it should like you need something like

<navigation ...>
    <action android:id="@+id/toProductListFragment"
        app:destination="@+id/productListFragment">
        <argument
            android:name="stkProdcode"
            app:argType="string" />
    </action>

Apparently this stuff only works if you also enable the safeargs plugin (as otherwise you have to "remember" this key yourself, or write the NavDirections class by hand, or put together the Bundle yourself - either way, Jetpack Navigation expects you to use Safeargs to pass arguments):

buildscript {
    dependencies {
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.2.2"

And

apply plugin: "androidx.navigation.safeargs.kotlin"

And then you should be able to do

class OutletListFragment: Fragment(), OutletListOnItemClickListener {
    ....

    override fun onItemClicked(outlet: OutletListPOJODataClassesDataItem) {
        Navigation.findNavController(view).navigate(NavigationDirections.toProductListFragment(outlet.stkProdcode))
    }
}

And due to limitations of Jetpack Navigation, you also have to duplicate the argument definition into the <fragment tag as well:

<fragment
    android:id="@+id/productListFragment"
    android:name="com.example.switchingandroidappproject.mainFragments.ProductListFragment"
    android:label="ProductListFragment" >
    <argument
        android:name="stkProdcode"
        app:argType="string" />
</fragment>

Make sure not to make a typo (android:name mismatch) as you'd run into unexpected failures).

Now you can obtain your arguments on the other side as

val args = ProductListFragmentArgs.fromBundle(getArguments())
val code = args.stkProdcode

I don't really use Jetpack Navigation, so I'm surprised to see that you have to duplicate the fragment args to the action args, but there you have it.

...to think with what I use in place of Jetpack Navigation, this is as simple as

// send
backstack.goTo(ProductListScreen(stkProdCode))
// receive
val prodCode = getKey<ProductListScreen>().stkProdCode

And is just as (if not more) type-safe.  *grumble* *grumble* but that doesn't help your case, that's not Jetpack Navigation.


问:
Slowdown in Game of Life with Objects - Why?
I am working on recreating Game of Life in different ways, taking Coding Train’s video as the starting point. What I am trying to add is ‘color inheritance’: A newborn cell ‘inheriting’ the color from the average of the neighbouring cells’ colours.

I have made two versions: The first one has a 2D grid array for cells, and each cell is an array with RGB values.

```<code>grid[i][j] = [255,0,100]
</code>```

A for loop iterates through the grid array and draws boxes of the right colour on the right position on the canvas. It then checks if the cell should be alive or dead next generation. This works fine without any slowdown, no matter the size of the grid.

https://editor.p5js.org/umutreldem/sketches/1qCmEzHlY

The second version fills each element of the grid array with Cell objects. This object receives its coordinates on the grid and its size. The color is given relative to its position on the grid.

```<code>function Cell(x, y, size) {
this.x = x * size;
this.y = y * size;
this.size = size;

//...

this.r = x * 10;
this.g = y * 10;
this.b = x+y;
</code>```

The Cell object has functions for determining how many alive neighbours it has, inheriting colour from neighbours, etc. It is the same process as the first version. Then in draw() the grid is looped twice: once for determining the next status of each cell, and once for changing the cells to their new state.

This version experiences massive slowdown, especially at higher resolutions.
https://editor.p5js.org/umutreldem/sketches/2skO6-2Cm

I would like to add more features to this, such as keeping count of the age of each cell (for how long it is alive,) and using making an object for each cell makes more sense to me.

With my limited experience with p5.js / JavaScript in general, I cannot understand why this is the case. The function of both versions is the same (apart from one extra loop in the second version), so why does the second version tax the computer this much?

答:
In your second example (using objects) you draw a every square, even if it is "empty".
In your first example, you only draw a square when the cell is active, and thus save computation by not drawing black squares on a black background :)

You can simply comment out the else statement in the "object version" to get the same computational savings.

```<code>this.show = function() {

    if (this.status == 1) {
      fill(color(this.r, this.g, this.b));
      stroke(0);
      square(this.x, this.y, this.size);
    }
    // else {
    //       fill(20);
    //       stroke(0);
    //       square(this.x, this.y, this.size);
    //   }
  }
</code>```

Here is a modified version, which seems to work reasonably fast.

Body:
I am working on recreating Game of Life in different ways, taking Coding Train’s video as the starting point. What I am trying to add is ‘color inheritance’: A newborn cell ‘inheriting’ the color from the average of the neighbouring cells’ colours.

I have made two versions: The first one has a 2D grid array for cells, and each cell is an array with RGB values.

grid[i][j] = [255,0,100]

A for loop iterates through the grid array and draws boxes of the right colour on the right position on the canvas. It then checks if the cell should be alive or dead next generation. This works fine without any slowdown, no matter the size of the grid.

https://editor.p5js.org/umutreldem/sketches/1qCmEzHlY

The second version fills each element of the grid array with Cell objects. This object receives its coordinates on the grid and its size. The color is given relative to its position on the grid.

function Cell(x, y, size) {
this.x = x * size;
this.y = y * size;
this.size = size;

//...

this.r = x * 10;
this.g = y * 10;
this.b = x+y;

The Cell object has functions for determining how many alive neighbours it has, inheriting colour from neighbours, etc. It is the same process as the first version. Then in draw() the grid is looped twice: once for determining the next status of each cell, and once for changing the cells to their new state.

This version experiences massive slowdown, especially at higher resolutions.
https://editor.p5js.org/umutreldem/sketches/2skO6-2Cm

I would like to add more features to this, such as keeping count of the age of each cell (for how long it is alive,) and using making an object for each cell makes more sense to me.

With my limited experience with p5.js / JavaScript in general, I cannot understand why this is the case. The function of both versions is the same (apart from one extra loop in the second version), so why does the second version tax the computer this much?

Body:
In your second example (using objects) you draw a every square, even if it is "empty".
In your first example, you only draw a square when the cell is active, and thus save computation by not drawing black squares on a black background :)

You can simply comment out the else statement in the "object version" to get the same computational savings.

this.show = function() {

    if (this.status == 1) {
      fill(color(this.r, this.g, this.b));
      stroke(0);
      square(this.x, this.y, this.size);
    }
    // else {
    //       fill(20);
    //       stroke(0);
    //       square(this.x, this.y, this.size);
    //   }
  }

Here is a modified version, which seems to work reasonably fast.


问:
Error: System.Data.OleDb.OleDbException: 'No value given for one or more required parameters'
I keep on getting this error when trying to use OleDb, and can't figure out how to solve the issue. I've tried referencing other websites and whatnot but got nothing. Here is what my code looks like:

```<code>OleDbCommand command = new OleDbCommand(@"SELECT [Name], [Config status], [OverallStatus], [NumHosts], [numEffectiveHosts], [TotalCpu], [NumCpuCores], [NumCpuThreads], [EffectiveCpu], [TotalMemory], [EffectiveMemory], [Num VMotions], [HA enabled], [Failover Level], [AdmissionControlEnabled], [Host monitoring], [HB Datastore Candidate Policy], [Isolation Response], [Restart Priority], [Cluster Settings], [Max Failures], [Max Failure Window], [Failure Interval], [Min Up Time], [VM Monitoring], [DRS enabled], [DRS default VM behavior], [DRS vmotion rate], [DPM enabled], [DPM default behavior], [DPM Host Power Action Rate] FROM [" + Sheet + "$]", conn); //Selects everything inside excel file
        DataTable Data = new DataTable();
        OleDbDataAdapter adapter = new OleDbDataAdapter(command);
        adapter.Fill(Data); //Puts all data inside a DataSet
</code>```

The error occurs on the adapter.Fill(Data) line. Thanks for any help you may bring!

Edit: For further details, I am trying to pull data out of an Excel spreadsheet using OleDb, put that data into a DataTable object, and then use entity framework to push that data to a SQL server database. In my excel spreadsheet, the sheet I'm trying to access is named "vCluster". Could the issues lie in my OleDbConnection string?

答:
You need to remove $ from the query.

```<code>@"SELECT [Name], [Config status], [OverallStatus], [NumHosts], [numEffectiveHosts], [TotalCpu], [NumCpuCores], [NumCpuThreads], [EffectiveCpu], [TotalMemory], [EffectiveMemory], [Num VMotions], [HA enabled], [Failover Level], [AdmissionControlEnabled], [Host monitoring], [HB Datastore Candidate Policy], [Isolation Response], [Restart Priority], [Cluster Settings], [Max Failures], [Max Failure Window], [Failure Interval], [Min Up Time], [VM Monitoring], [DRS enabled], [DRS default VM behavior], [DRS vmotion rate], [DPM enabled], [DPM default behavior], [DPM Host Power Action Rate] FROM [" + temp + "]";
</code>```

Body:
I keep on getting this error when trying to use OleDb, and can't figure out how to solve the issue. I've tried referencing other websites and whatnot but got nothing. Here is what my code looks like:

OleDbCommand command = new OleDbCommand(@"SELECT [Name], [Config status], [OverallStatus], [NumHosts], [numEffectiveHosts], [TotalCpu], [NumCpuCores], [NumCpuThreads], [EffectiveCpu], [TotalMemory], [EffectiveMemory], [Num VMotions], [HA enabled], [Failover Level], [AdmissionControlEnabled], [Host monitoring], [HB Datastore Candidate Policy], [Isolation Response], [Restart Priority], [Cluster Settings], [Max Failures], [Max Failure Window], [Failure Interval], [Min Up Time], [VM Monitoring], [DRS enabled], [DRS default VM behavior], [DRS vmotion rate], [DPM enabled], [DPM default behavior], [DPM Host Power Action Rate] FROM [" + Sheet + "$]", conn); //Selects everything inside excel file
        DataTable Data = new DataTable();
        OleDbDataAdapter adapter = new OleDbDataAdapter(command);
        adapter.Fill(Data); //Puts all data inside a DataSet

The error occurs on the adapter.Fill(Data) line. Thanks for any help you may bring!

Edit: For further details, I am trying to pull data out of an Excel spreadsheet using OleDb, put that data into a DataTable object, and then use entity framework to push that data to a SQL server database. In my excel spreadsheet, the sheet I'm trying to access is named "vCluster". Could the issues lie in my OleDbConnection string?

Body:
You need to remove $ from the query.

@"SELECT [Name], [Config status], [OverallStatus], [NumHosts], [numEffectiveHosts], [TotalCpu], [NumCpuCores], [NumCpuThreads], [EffectiveCpu], [TotalMemory], [EffectiveMemory], [Num VMotions], [HA enabled], [Failover Level], [AdmissionControlEnabled], [Host monitoring], [HB Datastore Candidate Policy], [Isolation Response], [Restart Priority], [Cluster Settings], [Max Failures], [Max Failure Window], [Failure Interval], [Min Up Time], [VM Monitoring], [DRS enabled], [DRS default VM behavior], [DRS vmotion rate], [DPM enabled], [DPM default behavior], [DPM Host Power Action Rate] FROM [" + temp + "]";


问:
SICP Ex. 1.17 - "fast-multiply" slower than "multiply"?
The following function as introduction to this exercise illustrates multiplication defined in terms of addition. This is the simplest "easy to write down", recursive definition.

(define (star a b)
  (if (= b 0)
      0
      (+ a (star a (- b 1)))))
```

<p>First thing I did when I saw that, following previous exercises, is write an iterative form which doesn't blow the stack:</p>

<pre class="lang-lisp prettyprint-override"><code>(define (star a b)
  (star-iter a b 0))
(define (star-iter a counter sum)
  (if (= counter 0)
      sum
      (star-iter a (- counter 1) (+ a sum))))
</code>```

Exercise 1.17 then encourages us to find an invariant so as to reduce the problem size, the idea being to get from O(n) to O(logn) number of steps (without, when that particular step is carried out, doing anything to update the result - all we do in that step is to reduce/transform the problem definition - that being what is meant by 'find an invariant') (see line 3 of the first code block below - nothing is being added to the result in that step).

For the fast version, the question says we should use the functions halve and double and seems to imply these would be available as machine operations (constant time?).  I've implemented the "fast" version just spoofing those functions as follows:

(define (fast-star a b)
  (cond ((or (= b 0) (= a 0)) 0)
        ((even? a)      (fast-star (/ a 2) (* 2 b)))
        (else      (+ a (fast-star a       (- b 1))))))
```

<p>And the same thing in iterative form (i.e. O(1) space):</p>

<p>(note how <code>+ a</code> on line 4 above just moves to the accumulator, end of line 6 below, to get this in tail position)</p>

<pre class="lang-lisp prettyprint-override"><code>(define (fast-star b)
  (fast-star-iter a b 0))
(define (fast-star-iter a b sum)
  (cond ((or (= a 0) (= b 0)) sum)
        ((even? a) (fast-star-iter (/ a 2) (* 2 b) sum))
        (else      (fast-star-iter a       (- b 1) (+ a sum)))))
</code>```

So this is kind of a "what's the point" question - these functions are slower than the first two given above. The first of these four functions blows the stack so it's not useful. But the second doesn't. That one is faster than any of these two "fast" versions under my testing.

Am I missing anything here?  Curious if there's a way to implement halve and double so they actually give the log(n) result being suggested here. There must be otherwise there would have been no sense in the question.

Note that the order of a & b matters a lot if they are different sizes - like multiplying 2, 100 times or 100, 2 times, the first being 100 steps, the latter 2 steps. That would be something to add to this function later. But curious about halve and double to start with.

答:
There's a subtle bug in your code, that's why it's slow. This should fix it, for versions 3 and 4:

```<code>(define (fast-star a b)
  (cond ((or (= b 0) (= a 0)) 0)
        ((even? b) (fast-star (* 2 a) (/ b 2.0)))
        (else (+ a (fast-star a (- b 1))))))

(define (fast-star-iter a b sum)
  (cond ((or (= a 0) (= b 0)) sum)
        ((even? b) (fast-star-iter (* 2 a) (/ b 2.0) sum))
        (else (fast-star-iter a (- b 1) (+ a sum)))))
</code>```

The idea is to keep adding a and decreasing b at each iteration, but depending on the condition sometimes you were decreasing b and sometimes you were doubling it! Also notice that I'm dividing b by 2.0 to get rid of exact arithmetic, which is slower.

Of course, you could do things the other way around: adding b and decreasing a - the important part is to be consistent about it, halving the problem on one parameter and doubling the other parameter, and the one that was doubled is the one that we need to add to the final result.

Body:
The following function as introduction to this exercise illustrates multiplication defined in terms of addition. This is the simplest "easy to write down", recursive definition.

(define (star a b)
  (if (= b 0)
      0
      (+ a (star a (- b 1)))))

First thing I did when I saw that, following previous exercises, is write an iterative form which doesn't blow the stack:

(define (star a b)
  (star-iter a b 0))
(define (star-iter a counter sum)
  (if (= counter 0)
      sum
      (star-iter a (- counter 1) (+ a sum))))

Exercise 1.17 then encourages us to find an invariant so as to reduce the problem size, the idea being to get from O(n) to O(logn) number of steps (without, when that particular step is carried out, doing anything to update the result - all we do in that step is to reduce/transform the problem definition - that being what is meant by 'find an invariant') (see line 3 of the first code block below - nothing is being added to the result in that step).

For the fast version, the question says we should use the functions halve and double and seems to imply these would be available as machine operations (constant time?).  I've implemented the "fast" version just spoofing those functions as follows:

(define (fast-star a b)
  (cond ((or (= b 0) (= a 0)) 0)
        ((even? a)      (fast-star (/ a 2) (* 2 b)))
        (else      (+ a (fast-star a       (- b 1))))))

And the same thing in iterative form (i.e. O(1) space):

(note how + a on line 4 above just moves to the accumulator, end of line 6 below, to get this in tail position)

(define (fast-star b)
  (fast-star-iter a b 0))
(define (fast-star-iter a b sum)
  (cond ((or (= a 0) (= b 0)) sum)
        ((even? a) (fast-star-iter (/ a 2) (* 2 b) sum))
        (else      (fast-star-iter a       (- b 1) (+ a sum)))))

So this is kind of a "what's the point" question - these functions are slower than the first two given above. The first of these four functions blows the stack so it's not useful. But the second doesn't. That one is faster than any of these two "fast" versions under my testing.

Am I missing anything here?  Curious if there's a way to implement halve and double so they actually give the log(n) result being suggested here. There must be otherwise there would have been no sense in the question.

Note that the order of a & b matters a lot if they are different sizes - like multiplying 2, 100 times or 100, 2 times, the first being 100 steps, the latter 2 steps. That would be something to add to this function later. But curious about halve and double to start with.

Body:
There's a subtle bug in your code, that's why it's slow. This should fix it, for versions 3 and 4:

(define (fast-star a b)
  (cond ((or (= b 0) (= a 0)) 0)
        ((even? b) (fast-star (* 2 a) (/ b 2.0)))
        (else (+ a (fast-star a (- b 1))))))

(define (fast-star-iter a b sum)
  (cond ((or (= a 0) (= b 0)) sum)
        ((even? b) (fast-star-iter (* 2 a) (/ b 2.0) sum))
        (else (fast-star-iter a (- b 1) (+ a sum)))))

The idea is to keep adding a and decreasing b at each iteration, but depending on the condition sometimes you were decreasing b and sometimes you were doubling it! Also notice that I'm dividing b by 2.0 to get rid of exact arithmetic, which is slower.

Of course, you could do things the other way around: adding b and decreasing a - the important part is to be consistent about it, halving the problem on one parameter and doubling the other parameter, and the one that was doubled is the one that we need to add to the final result.


问:
Google Assistant - "Getting test version of" after Production Release
Submitted actions for google production review and it has been approved.

Then I invoked the action but still, it is prompting "Getting the test version of *****" as the initial response and then the welcome message.

Please provide the solution.

答:
This is just happening for you, and possibly for anyone who is in the Alpha or Beta channels.

You can go into the simulator and indicate which version you want to use. This will apply for both the simulator and devices linked with the same account. If you have the new simulator, you can select "Settings"

then select which version you should use from the dropdown.

Alpha and Beta channel users can go to the same URL they used to connect to the channel and indicate they want to switch to the production version.


问:
MySQL Stored function to return name on id input
I have this table

I want to create stored function that takes empno and returns its manager (boss) name. (one employee is boss of other employee)
this is the code i tried but it returned error
MYSQL said: The query was empty

```<code>CREATE FUNCTION MANAGER1(ENO int) RETURNS varchar DETERMINISTIC
BEGIN
    DECLARE MANAGER_NAME varchar(MAX);
    Select name into MANAGER_NAME where boss = ENO;
    RETURN varchar MANAGER_NAME

DELIMITER $$ ;
</code>```

答:
Check once again with following query for creating stored function:

```<code>DELIMITER //
CREATE FUNCTION getManager1(eno int(11))
RETURNS varchar(255)
DETERMINISTIC
    BEGIN
    DECLARE manager_name varchar(250);
    Select name into manager_name FROM employees where id = eno;
    return manager_name;
    END //
DELIMITER ;
</code>```

In your stored procedure statement, END tag is missing and table name is also missing in SELECT statement. I have executed query mentioned here. Please match with your query and check what is missing in your query posted in question.

Body:
I have this table

I want to create stored function that takes empno and returns its manager (boss) name. (one employee is boss of other employee)
this is the code i tried but it returned error
MYSQL said: The query was empty

CREATE FUNCTION MANAGER1(ENO int) RETURNS varchar DETERMINISTIC
BEGIN
    DECLARE MANAGER_NAME varchar(MAX);
    Select name into MANAGER_NAME where boss = ENO;
    RETURN varchar MANAGER_NAME

DELIMITER $$ ;

Body:
Check once again with following query for creating stored function:

DELIMITER //
CREATE FUNCTION getManager1(eno int(11))
RETURNS varchar(255)
DETERMINISTIC
    BEGIN
    DECLARE manager_name varchar(250);
    Select name into manager_name FROM employees where id = eno;
    return manager_name;
    END //
DELIMITER ;

In your stored procedure statement, END tag is missing and table name is also missing in SELECT statement. I have executed query mentioned here. Please match with your query and check what is missing in your query posted in question.


问:
Does unique.data.table with by behave like dplyr::distinct with .keep_all = TRUE?
I want to get unique rows in a data frame based on one variable, while still choosing which rows (based on other variables) are included.

Example:

```<code>dt <- as.data.table(list(group = c("A", "A", "B", "B", "C", "C"), number = c(1, 2, 1, 2, 2, 1)))
</code>```

I would normally do this, as it allows me to always keep the row where number == 1.

```<code>dt %>%
arrange(group, number) %>%
distinct(group, .keep_all = TRUE)
</code>```

This is now too slow, and I'm hoping the data.table equivalent will be faster.

This seems to work:

```<code>dt <- dt[order(group, number)]
unique(dt, by = c("group"))
</code>```

But I couldn't find anything in the unique.data.table documentation which says that the first row per group is the one which is kept. Is it safe to assume it is?

答:
How about subsetting .SD in j?

```<code>library(data.table)
dt[order(group,number),.SD[1],by=group]
#   group number
#1:     A      1
#2:     B      1
#3:     C      1
</code>```

You might also find using .I faster because it avoids assembling .SD:

In this version, we first assemble a list of row indices using the .I special symbol and subset those indices by ones that equal 1 and then take the first ([1]) by group. We then access just the indices with $V1 and subset the original dt by that.

```<code>dt[,.I[number == 1][1], by=group]
   group V1
1:     A  1
2:     B  3
3:     C  6

dt[dt[,.I[number == 1][1], by=group]$V1]
   group number
1:     A      1
2:     B      1
3:     C      1
</code>```

Edit:

As @IceCreamToucan points out in the comments, another, easier to read option is with head.data.table:

```<code>dt[order(group,number), head(.SD, 1), by=group]
   group number
1:     A      1
2:     B      1
3:     C      1
</code>```

Body:
I want to get unique rows in a data frame based on one variable, while still choosing which rows (based on other variables) are included.

Example:

dt <- as.data.table(list(group = c("A", "A", "B", "B", "C", "C"), number = c(1, 2, 1, 2, 2, 1)))

I would normally do this, as it allows me to always keep the row where number == 1.

dt %>%
arrange(group, number) %>%
distinct(group, .keep_all = TRUE)

This is now too slow, and I'm hoping the data.table equivalent will be faster.

This seems to work:

dt <- dt[order(group, number)]
unique(dt, by = c("group"))

But I couldn't find anything in the unique.data.table documentation which says that the first row per group is the one which is kept. Is it safe to assume it is?

Body:
How about subsetting .SD in j?

library(data.table)
dt[order(group,number),.SD[1],by=group]
#   group number
#1:     A      1
#2:     B      1
#3:     C      1

You might also find using .I faster because it avoids assembling .SD:

In this version, we first assemble a list of row indices using the .I special symbol and subset those indices by ones that equal 1 and then take the first ([1]) by group. We then access just the indices with $V1 and subset the original dt by that.

dt[,.I[number == 1][1], by=group]
   group V1
1:     A  1
2:     B  3
3:     C  6

dt[dt[,.I[number == 1][1], by=group]$V1]
   group number
1:     A      1
2:     B      1
3:     C      1

Edit:

As @IceCreamToucan points out in the comments, another, easier to read option is with head.data.table:

dt[order(group,number), head(.SD, 1), by=group]
   group number
1:     A      1
2:     B      1
3:     C      1


问:
Force an applyBinding in knockout.js
I'm using knockout to bind a dom-element to a view-model and everything works great the first time a view-model is applied to the dom-element.

Later on a very similar view-model is applied to the same dom-element but the bindings won't update - probably because knockout believes it is the same view-model as before.

Is there a way to force knockout to apply the new view-model and discard the old view-model?

答:
The most common approach is to use the template binding.  It would look something like:

```<code><div data-bind="template: { name: 'mainTmpl', data: myData }"></div>

var viewModel = {
    myData: ko.observable(),
}
</code>```

Now, you can set myData to your new view model like:  viewModel.myData(newData) and the template binding will handle re-rendering your content based on the new data.

Otherwise, you can do something like call: ko.cleanNode(yourRootElement) (or pass document) and then ko.applyBindings(yourNewViewModel) to remove the bindings and apply them to a new view model.

Title: Force an applyBinding in knockout.js

Body:
The most common approach is to use the template binding.  It would look something like:

<div data-bind="template: { name: 'mainTmpl', data: myData }"></div>

var viewModel = {
    myData: ko.observable(),
}

Now, you can set myData to your new view model like:  viewModel.myData(newData) and the template binding will handle re-rendering your content based on the new data.

Otherwise, you can do something like call: ko.cleanNode(yourRootElement) (or pass document) and then ko.applyBindings(yourNewViewModel) to remove the bindings and apply them to a new view model.


问:
How to read contents from a file and store it in a hash-map in clojure?
I got a small problem in clojure. I am new to this programming environment and need a little help. I have got a text file in this format :

```<code>1|John Smith|123 Here Street|456-4567
2|Sue Jones|43 Rose Court Street|345-7867
3|Fan Yuhong|165 Happy Lane|345-4533
</code>```

I want to parse each line in file and want to store data in hashmap in this way :

```<code>{ 1 : [John Smith, 123 here street, 456-4567], 2 : ... }
</code>```

Here is my code till now but I have not got any success.

```<code>(defn readcustfile[]
  (def cust-file (clojure.string/split-lines (slurp "cust.txt")))

  (doseq [line cust-file]
    (def cust-id (nth (clojure.string/split line #"\|") 0))
    (def cust-name (str (nth (clojure.string/split line #"\|") 1)))
    (def cust-add (str (nth (clojure.string/split line #"\|") 2)))
    (def cust-phone (str (nth (clojure.string/split line #"\|") 3)))
    (def cust-data (str cust-name "," cust-add "," cust-phone))
    (def cust (map (fn [[id name add phone]]
                     (list (Integer/parseInt cust-id)
                           (hash-map :name cust-name
                                     :add cust-add
                                     :phone cust-phone))
    )
  )
(readcustfile)
</code>```

答:
```<code>(def cust-file ["1|John Smith|123 Here Street|456-4567"
                "2|Sue Jones|43 Rose Court Street|345-7867"
                "3|Fan Yuhong|165 Happy Lane|345-4533"])

(into {}                      ;; construc new hash map from coll
                              ;; (into {} ["key" "data"]) => {"key" "data"}
      (for [line cust-file    ;; `for` instead of `doseq`
                              ;; (`doseq` will return nil, but `for` - results of iteration)
            :let [[id & data] ;; shortend `let` alias, use desctructjion to get `id` and rest as `data`
                  (clojure.string/split line #"\|")]]
        [(Integer/parseInt id) data])) ;; return pair [id [name add phone]] for every line

;; => {1 ("John Smith" "123 Here Street" "456-4567"),
;;     2 ("Sue Jones" "43 Rose Court Street" "345-7867"),
;;     3 ("Fan Yuhong" "165 Happy Lane" "345-4533")}
</code>```

Body:
I got a small problem in clojure. I am new to this programming environment and need a little help. I have got a text file in this format :

1|John Smith|123 Here Street|456-4567
2|Sue Jones|43 Rose Court Street|345-7867
3|Fan Yuhong|165 Happy Lane|345-4533

I want to parse each line in file and want to store data in hashmap in this way :

{ 1 : [John Smith, 123 here street, 456-4567], 2 : ... }

Here is my code till now but I have not got any success.

(defn readcustfile[]
  (def cust-file (clojure.string/split-lines (slurp "cust.txt")))

  (doseq [line cust-file]
    (def cust-id (nth (clojure.string/split line #"\|") 0))
    (def cust-name (str (nth (clojure.string/split line #"\|") 1)))
    (def cust-add (str (nth (clojure.string/split line #"\|") 2)))
    (def cust-phone (str (nth (clojure.string/split line #"\|") 3)))
    (def cust-data (str cust-name "," cust-add "," cust-phone))
    (def cust (map (fn [[id name add phone]]
                     (list (Integer/parseInt cust-id)
                           (hash-map :name cust-name
                                     :add cust-add
                                     :phone cust-phone))
    )
  )
(readcustfile)


问:
How to create a vector of variables using summarise?
Here is a beginner's problem:

I like using summarise(), but sometimes I find it difficult storing the results.
For example, I know I can store 1 value in the following manner:

```<code>stdv <- Data %>%
 filter(x == 1) %>%
 summarise(stdv = sd(y))
</code>```

But I get in trouble if I try to do so for more than 1 variable.
I think it's something to do with creating a vector o variables in the beginning but this doesn't work:

```<code>c(dog, cat) <- Data %>%
 filter(x == 1) %>%
 summarise(dog = sd(y),
           cat = mean(y))
</code>```

Can someone help? Thank ya

答:
You can store it in a vector like this:

```<code>save_vector <- df %>%
  summarise(dog = sd(id),
            cat = var(id)) %>%
  unlist()
save_vector

#     dog      cat
#1.636392 2.677778
</code>```

Data

```<code>structure(list(id = c("1", "4", "3", "4", "6", "3", "5", "6",
"2", "3")), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

Body:
Here is a beginner's problem:

I like using summarise(), but sometimes I find it difficult storing the results.
For example, I know I can store 1 value in the following manner:

stdv <- Data %>%
 filter(x == 1) %>%
 summarise(stdv = sd(y))

But I get in trouble if I try to do so for more than 1 variable.
I think it's something to do with creating a vector o variables in the beginning but this doesn't work:

c(dog, cat) <- Data %>%
 filter(x == 1) %>%
 summarise(dog = sd(y),
           cat = mean(y))

Can someone help? Thank ya

Body:
You can store it in a vector like this:

save_vector <- df %>%
  summarise(dog = sd(id),
            cat = var(id)) %>%
  unlist()
save_vector

#     dog      cat
#1.636392 2.677778

Data

structure(list(id = c("1", "4", "3", "4", "6", "3", "5", "6",
"2", "3")), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))


问:
Datetime Stacked Bar Chart with Matplotlib from dataframe
Background:

I am stuck. Or just having a blonde moment. I'm like a deer looking at headlights.

I've queried the following dataframe from MySQL table.

```<code>date          operation
2020-05-07        A
2020-05-08        B
2020-05-08        A
2020-05-12        A
2020-05-12        A
2020-05-12        B
2020-05-13        C
2020-05-13        A
2020-05-13        B
2020-05-14        A
2020-05-19        B
2020-05-21        A
2020-05-25        A
2020-05-26        B
2020-05-26        C
2020-05-26        A
2020-05-26        A
2020-05-29        A
</code>```

I have no idea how to make it a stacked bar chart with matplotlib.

Research:

Grouped Bar-Chart with customized DateTime Index using pandas and Matplotlib

Stacked bar plot using Matplotlib

Question:

How can I generate a stack-bar-chart with matplot lib with the above sample data?

Code snippet:

```<code>import datetime as dt
import mysql.connector
import os
import pandas as pd
# import numpy as np
import matplotlib.pyplot as plt
import datetime

def generate_monthly_graph():
    query = "SELECT [...]`"
    mycursor.execute(query)
    mycursor.execute(query)
    data = mycursor.fetchall()

    df = pd.DataFrame(data, columns=['date', 'operation'])

    df = df.set_index('date')

    df.index = pd.to_datetime(df.index)
</code>```

答:
You can use crosstab then plot.bar:

```<code># convert to date, no need for set_index
df.date = pd.to_datetime(df.date)

pd.crosstab(df.date,df.operation).plot.bar(stacked=True)
</code>```

Output:

If you want monthly, you can use dt.to_period('M') to get monthly dates and crosstab:

```<code>pd.crosstab(df.date.dt.to_period('M'),df.operation).plot.bar(stacked=True)
</code>```

Output (for the sample data):

Update to have all the dates on the x-axis:

```<code>df['date'] = pd.to_datetime(df.date)

mindate, maxdate = df['date'].agg(['min','max'])

all_dates = pd.date_range(mindate, maxdate, freq='D').date

(pd.crosstab(df.date,df.operation)
   .reindex(all_dates)
   .plot.bar(stacked=True)
)
</code>```

Output:

Body:
Background:

I am stuck. Or just having a blonde moment. I'm like a deer looking at headlights.

I've queried the following dataframe from MySQL table.

date          operation
2020-05-07        A
2020-05-08        B
2020-05-08        A
2020-05-12        A
2020-05-12        A
2020-05-12        B
2020-05-13        C
2020-05-13        A
2020-05-13        B
2020-05-14        A
2020-05-19        B
2020-05-21        A
2020-05-25        A
2020-05-26        B
2020-05-26        C
2020-05-26        A
2020-05-26        A
2020-05-29        A

I have no idea how to make it a stacked bar chart with matplotlib.

Research:

Grouped Bar-Chart with customized DateTime Index using pandas and Matplotlib

Stacked bar plot using Matplotlib

Question:

How can I generate a stack-bar-chart with matplot lib with the above sample data?

Code snippet:

import datetime as dt
import mysql.connector
import os
import pandas as pd
# import numpy as np
import matplotlib.pyplot as plt
import datetime

def generate_monthly_graph():
    query = "SELECT [...]`"
    mycursor.execute(query)
    mycursor.execute(query)
    data = mycursor.fetchall()

    df = pd.DataFrame(data, columns=['date', 'operation'])

    df = df.set_index('date')

    df.index = pd.to_datetime(df.index)

Body:
You can use crosstab then plot.bar:

# convert to date, no need for set_index
df.date = pd.to_datetime(df.date)

pd.crosstab(df.date,df.operation).plot.bar(stacked=True)

Output:

If you want monthly, you can use dt.to_period('M') to get monthly dates and crosstab:

pd.crosstab(df.date.dt.to_period('M'),df.operation).plot.bar(stacked=True)

Output (for the sample data):

Update to have all the dates on the x-axis:

df['date'] = pd.to_datetime(df.date)

mindate, maxdate = df['date'].agg(['min','max'])

all_dates = pd.date_range(mindate, maxdate, freq='D').date

(pd.crosstab(df.date,df.operation)
   .reindex(all_dates)
   .plot.bar(stacked=True)
)

Output:


问:
how do i pass data among components using props
friends, I am a React beginner, and I have a problem with passing data between components using props
I have three components Users, UserList, and AddUser. In the UserList component, all the users should be displayed and AddUser component contains a form. I want to grab data from the forms and update my state in Users component. My pages are Home, User List and Add New User

```<code>import React, { Component } from "react";
import UserList from "./userList";

class Users extends Component {
  state = {
    users: [
      {
        name: "ali",
        lastname: "ahmadi",
        language: "python",
        gender: "male",
        score: 100,
      },
      {
        name: "Ahmad",
        lastname: "moradi",
        language: "JavaScript",
        gender: "male",
        score: 90,
      },
    ],
  };
  removeUser = (name) => {
    let users = this.state.users.filter((user) => {
      return user.name !== name;
    });
    this.setState({
      users,
    });
  };
  render() {
    return (
      <div>
        <UserList users={this.state.users} removeUser={this.removeUser} />
      </div>
    );
  }
}

export default Users;
</code>```

and my user list components code

```<code>
import React from "react";
import Users from "./user";

const UserList = (props) => {
  const { users } = props;
  console.log(users);

  return (
    <div className="container">
      <h1 className="text-center mt-4" style={{ fontFamily: "tahoma" }}>
        All Users
      </h1>
    </div>
  );
};

export default UserList;
</code>```

here is my form component

```<code>import React, { Component } from "react";
import Users from "./user";

class AddUser extends Component {
  state = {
    name: "",
    lastname: "",
    language: "",
    score: 0,
    gender: "",
  };
  handleChange = (e) => {
    this.setState({
      [e.target.id]: e.target.value,
      gender: e.target.value,
    });
  };
  handleSubmit = (e) => {
    e.preventDefault();
  };

  render() {
    return (
      <div className="container">
        <form onSubmit={this.handleSubmit} className="col-lg-8 m-auto">
          <fieldset className="form-group">
            <legend>Add New User</legend>

            <div className="form-group ">
              <input
                type="text"
                className="form-control"
                id="name"
                placeholder="Name"
                onChange={this.handleChange}
              />
              <input
                type="text"
                className="form-control my-2"
                id="lastname"
                placeholder="Last Name"
                onChange={this.handleChange}
              />
              <input
                type="text"
                className="form-control my-2"
                id="language"
                placeholder="Language"
                onChange={this.handleChange}
              />
              <input
                type="number"
                className="form-control my-2"
                id="score"
                placeholder="Your Score"
                onChange={this.handleChange}
              />
              <div className="form-check form-check-inline">
                <label className="form-check-label" htmlFor="inlineRadio1">
                  <b style={{ position: "relative", top: -2 }}> Male</b>
                </label>
                <input
                  className="form-check-input mx-2"
                  type="radio"
                  value="male"
                  name="gender"
                  onChange={this.handleChange}
                ></input>
              </div>
              <div className="form-check form-check-inline">
                <label className="form-check-label" htmlFor="inlineRadio1">
                  <b style={{ position: "relative", top: -2 }}> Female</b>
                </label>
                <input
                  className="form-check-input mx-2"
                  type="radio"
                  name="gender"
                  value="female"
                  onChange={this.handleChange}
                ></input>
              </div>
              <br />
              <button className="btn btn-outline-info btn-md mt-2">Add</button>
            </div>
          </fieldset>
        </form>
      </div>
    );
  }
}

export default AddUser;

</code>```

it prints undefined I don't know what's the problem

答:
You have a typo here,
import UserList from "./userList";

It should be
import UserList from "./UserList";

Body:
friends, I am a React beginner, and I have a problem with passing data between components using props
I have three components Users, UserList, and AddUser. In the UserList component, all the users should be displayed and AddUser component contains a form. I want to grab data from the forms and update my state in Users component. My pages are Home, User List and Add New User

import React, { Component } from "react";
import UserList from "./userList";

class Users extends Component {
  state = {
    users: [
      {
        name: "ali",
        lastname: "ahmadi",
        language: "python",
        gender: "male",
        score: 100,
      },
      {
        name: "Ahmad",
        lastname: "moradi",
        language: "JavaScript",
        gender: "male",
        score: 90,
      },
    ],
  };
  removeUser = (name) => {
    let users = this.state.users.filter((user) => {
      return user.name !== name;
    });
    this.setState({
      users,
    });
  };
  render() {
    return (

        <UserList users={this.state.users} removeUser={this.removeUser} />

    );
  }
}

export default Users;

and my user list components code

import React from "react";
import Users from "./user";

const UserList = (props) => {
  const { users } = props;
  console.log(users);

  return (

        All Users

  );
};

export default UserList;

here is my form component

import React, { Component } from "react";
import Users from "./user";

class AddUser extends Component {
  state = {
    name: "",
    lastname: "",
    language: "",
    score: 0,
    gender: "",
  };
  handleChange = (e) => {
    this.setState({
      [e.target.id]: e.target.value,
      gender: e.target.value,
    });
  };
  handleSubmit = (e) => {
    e.preventDefault();
  };

  render() {
    return (

        <form onSubmit={this.handleSubmit} className="col-lg-8 m-auto">
          <fieldset className="form-group">
            <legend>Add New User</legend>

              <input
                type="text"
                className="form-control"
                id="name"
                placeholder="Name"
                onChange={this.handleChange}
              />
              <input
                type="text"
                className="form-control my-2"
                id="lastname"
                placeholder="Last Name"
                onChange={this.handleChange}
              />
              <input
                type="text"
                className="form-control my-2"
                id="language"
                placeholder="Language"
                onChange={this.handleChange}
              />
              <input
                type="number"
                className="form-control my-2"
                id="score"
                placeholder="Your Score"
                onChange={this.handleChange}
              />

                   Male

                <input
                  className="form-check-input mx-2"
                  type="radio"
                  value="male"
                  name="gender"
                  onChange={this.handleChange}
                ></input>

                   Female

                <input
                  className="form-check-input mx-2"
                  type="radio"
                  name="gender"
                  value="female"
                  onChange={this.handleChange}
                ></input>

              <button className="btn btn-outline-info btn-md mt-2">Add</button>

          </fieldset>
        </form>

    );
  }
}

export default AddUser;

it prints undefined I don't know what's the problem


问:
Jenkins copyArtifact permission
I have tried to use the Copy Artifact Plugin in a Jenkinsfile as this:

```<code>copyArtifacts(projectName: 'myProject', selector: lastSuccessful(), filter: '*.png*', target: 'Figures');
</code>```

The code is working but I also need to the the permission of 'myProject' to use the plugin. Via Jenkins it's a tic-box like this:

I can only check the ticbox if I don't use a Jenkins file in the Jenkins job.

Question: How can I set the permission in the jenkins file directly instead of using the ticbox?

答:
Declarative pipeline:</p>

```<code>pipeline {
    agent any;
    options {
        copyArtifactPermission('job1,job2,...');
    }
    stages{...}
}
</code>```

Title: Jenkins copyArtifact permission

Body:
I have tried to use the Copy Artifact Plugin in a Jenkinsfile as this:

copyArtifacts(projectName: 'myProject', selector: lastSuccessful(), filter: '*.png*', target: 'Figures');

The code is working but I also need to the the permission of 'myProject' to use the plugin. Via Jenkins it's a tic-box like this:

I can only check the ticbox if I don't use a Jenkins file in the Jenkins job.

Question: How can I set the permission in the jenkins file directly instead of using the ticbox?

Body:
Declarative pipeline:

pipeline {
    agent any;
    options {
        copyArtifactPermission('job1,job2,...');
    }
    stages{...}
}


问:
getting data from database table using cursor in android
I have one employee table which has column values

```<code>("store_loc_id","name","password","address_id","role_id",
"retailer_id").
</code>```

I want to get the name and password from this table using cursor. how can i do??

答:
```<code>public Cursor getEmployee() {
    try {
        return db.query(employee, new String[] { "name", "password" },
                null, null, null, null, null);
    } catch (SQLException e) {
        Log.e("Exception on query", e.toString());
        return null;
    }
}

Cursor c = db.getEmployee();
    if (c == null) {
        // do nothing
    } else {
        if (c.getCount() > 0) {
            if (c.moveToFirst()) {
                do {
                    String Name = c.getString(0);
                    String Password = c.getString(1);
                } while (c.moveToNext());
            }
        }
}
</code>```

Body:
I have one employee table which has column values

("store_loc_id","name","password","address_id","role_id",
"retailer_id").

I want to get the name and password from this table using cursor. how can i do??


问:
Does + 1 really matter in the python function below?
I am new to programming and I'm taking a online course in python. I have a question to ask about a line in the below function:

```<code>def sum_first_n(n):
    result = 0
    for i in range(n):
        result += i + 1
    print(result)
sum_first_n(100)
</code>```

The result is 5050. Now looking at line 4: result += i  + 1, if I remove the  + 1  from that line, I still get the same result. Can anyone kindly explain what the work of + 1 is or can it be omitted when writing?

答:
It will definitely make a difference in your output. First, when i is 0, the resulting integer has the value 1, for the next iteration of the loop, 2 will be added to the result so the result would equal 3.
Whereas if the incrementation by 1 didn't exist the value of the result would be 2 and so on.
So it will have an impact for sure!</p>

Body:
I am new to programming and I'm taking a online course in python. I have a question to ask about a line in the below function:

def sum_first_n(n):
    result = 0
    for i in range(n):
        result += i + 1
    print(result)
sum_first_n(100)

The result is 5050. Now looking at line 4: result += i  + 1, if I remove the  + 1  from that line, I still get the same result. Can anyone kindly explain what the work of + 1 is or can it be omitted when writing?


问:
How to export the output of a SQL query to Excel using PowerShell?
I have a script which pulls data from a SQL database and gives the o/p in excel but the o/p comes under single column. I want to have it in different colums. This is my script:

```<code>     $SQLServer = ""
     $SQLDBName = ""
     $SqlQuery = ""
     $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
     $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True; User ID = $uid; Password = $pwd;"
     $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
     $SqlCmd.CommandText = $SqlQuery
     $SqlCmd.Connection = $SqlConnection
     $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
     $SqlAdapter.SelectCommand = $SqlCmd
     $DataSet = New-Object System.Data.DataSet
     $SqlAdapter.Fill($DataSet)
     $DataSet.Tables[0] | out-file "C:\Users\sql.csv"
</code>```

I also tried this script:

```<code>    $SQLServer = ""
    $SQLDBName = ""
    $SqlQuery = "select request_number,actioneer,audited_date from form_submission where actioneer ='XXXX' AND audited_date between '2020-05-19 00:00:00:000' and '2020-05-19 19:16:00:000';"| | Select @{n='request_number';e={request_number}}, @{n='actioneer';e={actioneer}} ,@{n ='audited_date';e={audited_date}}
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Server = $SQLServer; Database =
    $SQLDBName; Integrated Security = True; User ID = $uid; Password = $pwd;"
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = $SqlQuery
    $SqlCmd.Connection = $SqlConnection
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)

    $DataSet.Tables[0] | out-file "C:\Users\sql.csv"
</code>```

But this leads to the following error:

```<code>Exception calling "Fill" with "1" argument(s): "Must declare the scalar variable "@"."
At C:\Users\sraghur\Documents\sql powershell.ps1:12 char:1
+ $SqlAdapter.Fill($DataSet)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException
</code>```

答:
Is it really necessary to use .net methods instead of "Invoke-Sqlcmd"?

I usually use something like

```<code>Invoke-Sqlcmd -ServerInstance $strSQLServer -Database $strDatabase -QueryTimeout 180 -ConnectionTimeout 180 -query "select sqlcolumn1, sqlcolumn2, sqlcolumn3 from xxx" `
| Select-Object -Property sqlcolumn1, sqlcolumn2, sqlcolumn3 `
| Export-Csv "C:\Temp\SQLOutput.csv" -Encoding UTF8 -Delimiter ";" -NoTypeInformation
</code>```

(You might have to install powershell module "SqlServer" beforehand)

On the other hand: Depending on the delimiter char used, the method of opening the file in Excel might be the problem: Restart Excel and choose "File > Open > ..." instead of double-clicking.

In case both doesn't work, you could also select - as LordPupazz recommended - the "single column" you were talking about and use "data > text to columns" (+ choose the correct delimiter).

Body:
I have a script which pulls data from a SQL database and gives the o/p in excel but the o/p comes under single column. I want to have it in different colums. This is my script:

     $SQLServer = ""
     $SQLDBName = ""
     $SqlQuery = ""
     $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
     $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True; User ID = $uid; Password = $pwd;"
     $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
     $SqlCmd.CommandText = $SqlQuery
     $SqlCmd.Connection = $SqlConnection
     $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
     $SqlAdapter.SelectCommand = $SqlCmd
     $DataSet = New-Object System.Data.DataSet
     $SqlAdapter.Fill($DataSet)
     $DataSet.Tables[0] | out-file "C:\Users\sql.csv"

I also tried this script:

    $SQLServer = ""
    $SQLDBName = ""
    $SqlQuery = "select request_number,actioneer,audited_date from form_submission where actioneer ='XXXX' AND audited_date between '2020-05-19 00:00:00:000' and '2020-05-19 19:16:00:000';"| | Select @{n='request_number';e={request_number}}, @{n='actioneer';e={actioneer}} ,@{n ='audited_date';e={audited_date}}
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Server = $SQLServer; Database =
    $SQLDBName; Integrated Security = True; User ID = $uid; Password = $pwd;"
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = $SqlQuery
    $SqlCmd.Connection = $SqlConnection
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)

    $DataSet.Tables[0] | out-file "C:\Users\sql.csv"

But this leads to the following error:

Exception calling "Fill" with "1" argument(s): "Must declare the scalar variable "@"."
At C:\Users\sraghur\Documents\sql powershell.ps1:12 char:1
+ $SqlAdapter.Fill($DataSet)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException

Body:
Is it really necessary to use .net methods instead of "Invoke-Sqlcmd"?

I usually use something like

Invoke-Sqlcmd -ServerInstance $strSQLServer -Database $strDatabase -QueryTimeout 180 -ConnectionTimeout 180 -query "select sqlcolumn1, sqlcolumn2, sqlcolumn3 from xxx" `
| Select-Object -Property sqlcolumn1, sqlcolumn2, sqlcolumn3 `
| Export-Csv "C:\Temp\SQLOutput.csv" -Encoding UTF8 -Delimiter ";" -NoTypeInformation

(You might have to install powershell module "SqlServer" beforehand)

On the other hand: Depending on the delimiter char used, the method of opening the file in Excel might be the problem: Restart Excel and choose "File > Open > ..." instead of double-clicking.

In case both doesn't work, you could also select - as LordPupazz recommended - the "single column" you were talking about and use "data > text to columns" (+ choose the correct delimiter).


问:
How to Upload Many Files to Google Colab?
I am working on a image segmentation machine learning project and I would like to test it out on Google Colab.

For the training dataset, I have 700 images, mostly 256x256, that I need to upload into a python numpy array for my project. I also have thousands of corresponding mask files to upload. They currently exist in a variety of subfolders on Google drive, but I have been unable to upload them to Google Colab for use in my project.

So far I have attempted using Google Fuse which seems to have very slow upload speeds and PyDrive which has given me a variety of authentication errors. I have been using the Google Colab I/O example code for the most part.

How should I go about this? Would PyDrive be the way to go? Is there code somewhere for uploading a folder structure or many files at a time?

答:
There are many ways to do so :

You might want to push your data into a github repository then in Google Colab code cell you can run :

!git clone https://www.github.com/{repo}.git

You can upload your data to Google drive  then in your code cell :

from google.colab import drive

drive.mount('/content/drive')

Use transfer.sh tool : you can visit here to see how it works :

transfer.sh


问:
If Statement with Multiple Conditions vs Individual If Statements
I would like to check each condition and return if true.

Is it better to have:

1. Multiple conditions in a single if statement?

```<code>if (string.IsNullOrEmpty(myStr) ||
    myBool == true ||
    myList.Count == 0)
{
    return;
}
</code>```

2. Or multiple if statements, each checking a different condition.

```<code>if (string.IsNullOrEmpty(myStr))
{
    return;
}

if (myBool == true)
{
    return;
}

if (myList.Count == 0)
{
    return;
}
</code>```

If myStr is Empty.

My thought is that the first way checks all 3 conditions before it reaches the return (or does it)?

And the second way only has to check the 1st condition string.IsNullOrEmpty, reaches the return, and doesn't have to process the other 2 condition checks below it.

Or does the compiler optimize the code to work most efficient no matter how the source is written?

答:
They are equivalent. The || operator short-circuits, so as soon as it reaches a condition that is true, it stops checking other conditions and returns true.

The | operator does not short-circuit, so it would evaluate every operand before returning a value.

Same goes for && and & but with false. As soon as a false condition is reached, the && operator returns false.

So your two methods are functionally identical. Use whichever one you think is the cleanest, easiest to infer intent, etc.

Or does the compiler optimize the code to work most efficient no matter how the source is written?

Well, the optimizer can make changes to code for efficiency, but it cannot change the functional behavior, meaning it won't change the order of the operations.  Imagine you had something like:

```<code>if ((x == 0) || (y/x > 1))
</code>```

this is a common way to prevent divide-by-zero errors. If the compiler could rearrange the operands, then it could introduce divide-by-zero errors.

Body:
I would like to check each condition and return if true.

Is it better to have:

1. Multiple conditions in a single if statement?

if (string.IsNullOrEmpty(myStr) ||
    myBool == true ||
    myList.Count == 0)
{
    return;
}

2. Or multiple if statements, each checking a different condition.

if (string.IsNullOrEmpty(myStr))
{
    return;
}

if (myBool == true)
{
    return;
}

if (myList.Count == 0)
{
    return;
}

If myStr is Empty.

My thought is that the first way checks all 3 conditions before it reaches the return (or does it)?

And the second way only has to check the 1st condition string.IsNullOrEmpty, reaches the return, and doesn't have to process the other 2 condition checks below it.

Or does the compiler optimize the code to work most efficient no matter how the source is written?

Body:
They are equivalent. The || operator short-circuits, so as soon as it reaches a condition that is true, it stops checking other conditions and returns true.

The | operator does not short-circuit, so it would evaluate every operand before returning a value.

Same goes for && and & but with false. As soon as a false condition is reached, the && operator returns false.

So your two methods are functionally identical. Use whichever one you think is the cleanest, easiest to infer intent, etc.

Or does the compiler optimize the code to work most efficient no matter how the source is written?

Well, the optimizer can make changes to code for efficiency, but it cannot change the functional behavior, meaning it won't change the order of the operations.  Imagine you had something like:

if ((x == 0) || (y/x > 1))

this is a common way to prevent divide-by-zero errors. If the compiler could rearrange the operands, then it could introduce divide-by-zero errors.