问:
What is the meaning of 'No bundle URL present' in react-native?
When I run a react-native project, I get a error no bundle URL present , but I don't know what mistakes I do, I was very confused.

答:
I am running iOS simulator and this method works:

1. Clean your native project

1.a For Android project

```<code>cd android
gradlew clean
</code>```

1.b For iOS project

```<code>cd ios
xcodebuild clean
</code>```

2. Clean your reactnative cach

2.a If you are using npm

```<code>  npm start -- --reset-cache
</code>```

2.b If you are using yarn

```<code>  yarn cache clean
</code>```

After that you can run your project again.

Body:
I am running iOS simulator and this method works:

1. Clean your native project

1.a For Android project

cd android
gradlew clean

1.b For iOS project

cd ios
xcodebuild clean

2. Clean your reactnative cach

2.a If you are using npm

  npm start -- --reset-cache

2.b If you are using yarn

  yarn cache clean

After that you can run your project again.


来源: stackexchange

问:
axios not sending json data
I am trying to post some json data using axios. The axios.post method works well:

```<code>axios.post(
    "http://localhost/api",
    {"k1":"v1","k2":"v2"}
)
</code>```

However, the following code does not work:

```<code>const axiosInstance = axios.create({
    baseURL: 'http://localhost/api',
    method: 'POST',
    data: {"k1":"v1","k2":"v2"}
});
axiosInstance.request()
</code>```

The backend is a Flask app, which cannot receive any data. It cannot even read the 'Content-type' header.
So what is the difference between the above two codes? Any idea how to modify the second method so it can work?

答:
The data you are trying to send is not a JSON.

{"k1":"v1","k2","v2"} should be changed to {"k1":"v1","k2":"v2"}

ContentLicense: CC BY-SA 4.0

Title: axios not sending json data

Body:
I am trying to post some json data using axios. The axios.post method works well:

axios.post(
    "http://localhost/api",
    {"k1":"v1","k2":"v2"}
)

However, the following code does not work:

const axiosInstance = axios.create({
    baseURL: 'http://localhost/api',
    method: 'POST',
    data: {"k1":"v1","k2":"v2"}
});
axiosInstance.request()

The backend is a Flask app, which cannot receive any data. It cannot even read the 'Content-type' header.
So what is the difference between the above two codes? Any idea how to modify the second method so it can work?


问:
Concurrent WriteConflict with MongoDB and NodeJs
I'm creating an application that serves transportation order, while I'm stress testing the application by injecting about 100 orders simultaneously, the mongodb hits WriteConflict due to the numeric sequence id (nid it is required) that I created using the hook. I have tried to add ?retryWrites=true&w=majority into the connection URI and set those in the transaction level, but none of those work. May I know any parts that I'm missing and should give a try (Knowing that is critical section, and using lock/queue should fix, but want to know any other way)? Thank you very much.

The schema for sequence and order (will keep _id that default created, and mongoose did the thing so haven't mention in the schema)

```<code>const SequenceSchema = new Schema<ISequenceDoc>(
  {
    collectionName: {
      type: String,
      trim: true,
      required: true
    },
    nid: {
      type: Number,
      required: true
    }
  },
  {
    collection: 'sequences',
    timestamps: true
  }
);

const OrderSchema = new Schema<IOrderDoc>(
  {
    name: {
      type: String,
      trim: true,
      required: true
    },
    nid: {
      type: Number
    }
  },
  {
    collection: 'orders',
    timestamps: true
  }
);
</code>```

Pre saving hook to assign an numeric id index of hex id to the schema

```<code>OrderSchema.pre('save', async function(next) {
    if (this.isNew) {
      const data = await this.db.model<ISequenceDoc>('Sequence').findOneAndUpdate(
        {
          collectionName: this.collection.collectionName
        },
        {
          $inc: { nid: 1 }
        },
        {
          upsert: true,
          new: true,
          session: this.$session()
        }
      );
      this.set('nid', data.nid);
    }
    next();
});
</code>```

The code that create the order model and save

```<code>async createOrder(orderInfo) => {
const session = await this.connection.startSession();
session.startTransaction({
  readConcern: {
    level: 'majority'
  },
  writeConcern: {
    w: 'majority',
    j: true
  }
});
......
await order.save({session});
await session.commitTransaction();
return order;
}
</code>```

答:
The problem is that all of your transactions modify the same document in the findOneAndUpdate.

Try acquiring your sequence number before starting the transaction.

Body:
I'm creating an application that serves transportation order, while I'm stress testing the application by injecting about 100 orders simultaneously, the mongodb hits WriteConflict due to the numeric sequence id (nid it is required) that I created using the hook. I have tried to add ?retryWrites=true&w=majority into the connection URI and set those in the transaction level, but none of those work. May I know any parts that I'm missing and should give a try (Knowing that is critical section, and using lock/queue should fix, but want to know any other way)? Thank you very much.

The schema for sequence and order (will keep _id that default created, and mongoose did the thing so haven't mention in the schema)

const SequenceSchema = new Schema<ISequenceDoc>(
  {
    collectionName: {
      type: String,
      trim: true,
      required: true
    },
    nid: {
      type: Number,
      required: true
    }
  },
  {
    collection: 'sequences',
    timestamps: true
  }
);

const OrderSchema = new Schema<IOrderDoc>(
  {
    name: {
      type: String,
      trim: true,
      required: true
    },
    nid: {
      type: Number
    }
  },
  {
    collection: 'orders',
    timestamps: true
  }
);

Pre saving hook to assign an numeric id index of hex id to the schema

OrderSchema.pre('save', async function(next) {
    if (this.isNew) {
      const data = await this.db.model<ISequenceDoc>('Sequence').findOneAndUpdate(
        {
          collectionName: this.collection.collectionName
        },
        {
          $inc: { nid: 1 }
        },
        {
          upsert: true,
          new: true,
          session: this.$session()
        }
      );
      this.set('nid', data.nid);
    }
    next();
});

The code that create the order model and save

async createOrder(orderInfo) => {
const session = await this.connection.startSession();
session.startTransaction({
  readConcern: {
    level: 'majority'
  },
  writeConcern: {
    w: 'majority',
    j: true
  }
});
......
await order.save({session});
await session.commitTransaction();
return order;
}


问:
ValidateInput(false) not working
I have read all the similar question on SO already and none of the solutions seem to work for me.  I am submitting HTML (from CKEditor) to a controller

I have [ValidateInput(false)] on my Contoller and on my Action
I also have

```<code><system.web>
      <httpRuntime requestValidationMode="2.0" />
</code>```

in my web.config and the web.config for the Area my view is in.

However my HTML is still getting encoded.

答:
Unbelievable.

I see the error when I declared my instance of CKeditor on of the options set was

```<code>htmlEncodeOutput: true,
</code>```

hangs head in shame *

No idea how that line got in there.  But without it everything works as expected

ContentLicense: CC BY-SA 3.0

Title: ValidateInput(false) not working

Body:
I have read all the similar question on SO already and none of the solutions seem to work for me.  I am submitting HTML (from CKEditor) to a controller

I have [ValidateInput(false)] on my Contoller and on my Action
I also have

<system.web>
      <httpRuntime requestValidationMode="2.0" />

in my web.config and the web.config for the Area my view is in.

However my HTML is still getting encoded.

Body:
Unbelievable.

I see the error when I declared my instance of CKeditor on of the options set was

htmlEncodeOutput: true,

hangs head in shame *

No idea how that line got in there.  But without it everything works as expected


问:
Change globally scoped variable in JavaScript from inside a function
I am having some trouble with changing globally scoped variables through a nested function call.

I am trying to create a script that calls itself every 5 seconds. On the first run it should take the globally scoped variable 'a' and change it. This change is intended to stick so that when the script runs a second time the global variable 'a' is forever changed.

For some reason, this isn' the case though. I have learned about var, const, let and hoisting, but coming from python, I feel my logic is maybe biased?

var a = 'test';

var test_function = function(obj) {
  console.log("This is the first 'a':" + " " + obj);

  if (a == obj) {
    console.log(" This is the win state, our global variable changed on the second run!")

  } else {
    var a = "The 'a' changed";
    console.log("Inner circle: Now our a is:" + " " + a);
  }
  console.log("Second circle: Our 'a' is still:" + " " + a);
  console.log('_________________NEXT_______________')
  return a;
};

//Calls the test_function
function run_interval(obj) {
  test_function(obj)
};

//Defined the interval that is run every 5 sec
setInterval(function() {
  run_interval(a);
}, 5000);```

Any advice would be highly appreciated.

答:
Don't declare var a inside the function. That makes it a local variable instead of updating the global variable.

Just assign the variable without the var declaration.

var a = 'test';

var test_function = function(obj) {
  console.log("This is the first 'a':" + " " + obj);

  if (a == obj) {
    console.log(" This is the win state, our global variable changed on the second run!")

  } else {
    a = "The 'a' changed";
    console.log("Inner circle: Now our a is:" + " " + a);
  }
  console.log("Second circle: Our 'a' is still:" + " " + a);
  console.log('_________________NEXT_______________')
  return a;
};

//Calls the test_function
function run_interval(obj) {
  test_function(obj)
};

//Defined the interval that is run every 5 sec
setInterval(function() {
  run_interval(a);
}, 5000);```

Body:
I am having some trouble with changing globally scoped variables through a nested function call.

I am trying to create a script that calls itself every 5 seconds. On the first run it should take the globally scoped variable 'a' and change it. This change is intended to stick so that when the script runs a second time the global variable 'a' is forever changed.

For some reason, this isn' the case though. I have learned about var, const, let and hoisting, but coming from python, I feel my logic is maybe biased?

var a = 'test';

var test_function = function(obj) {
  console.log("This is the first 'a':" + " " + obj);

  if (a == obj) {
    console.log(" This is the win state, our global variable changed on the second run!")

  } else {
    var a = "The 'a' changed";
    console.log("Inner circle: Now our a is:" + " " + a);
  }
  console.log("Second circle: Our 'a' is still:" + " " + a);
  console.log('_________________NEXT_______________')
  return a;
};

//Calls the test_function
function run_interval(obj) {
  test_function(obj)
};

//Defined the interval that is run every 5 sec
setInterval(function() {
  run_interval(a);
}, 5000);

Any advice would be highly appreciated.


问:
Wait until pallet rack storage has enough space
I would like to insert a wait or another similar block where my pallets have to wait until the pallet rack has enough space to store them. How could I do this? In my project my pallet rack has space for 80 pallets. When 50 pallets get stored at 8 am and 50 pallets at 11 am but the trucks arrive at 12 am to pick them it logically shows the error that there are not enough empty cells. The remaining 20 pallets should wait until it is enough space again after the truck takes 50 pallets.
process</p>

答:
you can use different things:

after your source a queue followed by a restricted area start with a maximum number of accepted agents equal to the capacity of your palletracks... with a restricted area end after your rack pick (recommended)

after your source a queue followed by a hold block. You will block this hold when your palletrack capacity is at its maximum

a wait block that will free agents only when your pallet racks have space


问:
nmap and svnlib_client not working together
I installed nmap on Debian 6 squeeze, 64 bit. When I run nmap it says:

nmap: error while loading shared libraries: libsvn_client-1.so.0: cannot open shared object >file: No such file or directory

so I googled it and found a solution which was.

ln -s /usr/lib/x86_64-linux-gnu/libsvn_client-1.so.1 /usr/lib/libsvn_client-1.so.0

I did that. but I'm still getting the same problem. It created the link successfully but it says nmap is still giving me the same error. Any Ideas?

答: sudo dnf install subversion -y solved the problem in Fedora 32


问:
Can't install matplotlib to pycharm
I have recently started to learn python programming using Python Crash Course. I am stuck as I can't get matplotlib to work in pycharm.

I have pip installed.
I have installed matplotlib using pip via command prompt.

Now, when I open pycharm and go file->settings->project interpreter->download packages and find and press install for matplotlib, I get an error: Command "python setup.py egg_info" failed with error code 1 in C:\Users\Tony\AppData\Local\Temp\pip-install-f2h0rvbb\matplotlib\ . When installing on pycharm it says its using cached file from website I didn't download my matplotlib from.

I have tried "pip install matplotlib" from  pycharm terminal and get the same error.

I have tried typing "pip install matplotlib" from cmd and it does so and says its already satisfied.

Any help or guidance would be appreciated, thanks.

答: Although little late to answer but changing version for python from 3.8 to 3.7 worked for me.

Title: Can't install matplotlib to pycharm


问:
Calling ASP.net Web Service from C# Application
I have a question. How can i invoke a web service and get the result from a C# desktop application. I am making a desktop app and I want it to be able to connect to my online ASP.net web services. How is this possible?</p>

答:
This is possible the same way that you access web services from any other type of application, be it an ASP.NET page, a class library or windows service.

For an explanatory tutorial on the subject, see Accessing a Web Service from a Desktop Application.

OwnerDisplayName: QAH

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Cerebrus


问:
Is Azure role local storage guaranteed to be inaccessible to an application that is next to use the same host?
Suppose my Azure role stores files to the role local filesystem and forgets to delete them. Can another application that uses that host in future possibly get access to those files?

I've read the whitepaper and it's full of marketing style statements but I can't find a definitive statement about how thoroughly the host machine is "cleaned" before a new role is started on it.

Can I be completely sure that another application won't see changes my application does to the filesystem?

答:
Although I am not sure it's properly documented, I am fairly certain that Windows Azure recycles thoroughly whatever local files haven been dumped by a Role into a VM before letting any other Role access the VM. That's a fairly basic security policy.

Then, considering the deployment time on Windows Azure for a new VM (between 6min to 8min) I am pretty sure that the VM itself is pretty much wiped-out clean, not just the local storage, so that whatever by-product files which might have been generated by the OS itself during the execution of the VM does not become available afterward.


问:
Adding and removing robots/vehicles from code instead of specifying it in wbt file
Using the sumo_supervisor example in /usr/local/webots/projects/default/controllers, I am able to generate and delete a vehicle (bmwx) in webots simulation using traci controller.
However when I try to specify ros_automobile as my controller instead of sumo using the following modification in Objects.py file

```<code>defName = "EGO_VEHICLE%d" % index
    vehicleString = "DEF " + defName + " " + model + " {\n"
    #vehicleString += "  translation 10000 0.5 0\n"
    vehicleString += "  translation -3.16697 0.317 -173.705\n"
    vehicleString += "  controller \"ros_automobile\"\n"
    vehicleString += "  sensorsSlotCenter [\n"
    vehicleString += "    GPS {\n"
    vehicleString += "    }\n"
    vehicleString += "   ]\n"
</code>```

I get the following error ([ros_automobile] Error: Only nodes based on the 'Car' node can used the car library.)

I will highly appreciate any guidance that you guys can provide. Thank you for your time.

答:
The sumo supervisor is using a simplified version of the vehicle instead of the the usual one, this is to make the simulation run smoother: https://cyberbotics.com/doc/automobile/car#simple-vehicles

Instead of modifying the sumo controller, you should rather already add the vehicle with the correct controller in your simulation and set the appropriate DEF name so that the sumo supervisor will use it when needed: https://cyberbotics.com/doc/automobile/sumo-interface#use-vehicles-already-present-in-the-world

If your are just interested to insert and remove vehicle and not to use the SUMO interface, to add robot from the controller, it is quite simple you just have to use the supervisor API:
  - https://cyberbotics.com/doc/guide/supervisor-programming
  - https://cyberbotics.com/doc/reference/supervisor
In particular these functions can be used to import new nodes:
https://cyberbotics.com/doc/reference/supervisor#wb_supervisor_field_import_mf_node

Body:
Using the sumo_supervisor example in /usr/local/webots/projects/default/controllers, I am able to generate and delete a vehicle (bmwx) in webots simulation using traci controller.
However when I try to specify ros_automobile as my controller instead of sumo using the following modification in Objects.py file

defName = "EGO_VEHICLE%d" % index
    vehicleString = "DEF " + defName + " " + model + " {\n"
    #vehicleString += "  translation 10000 0.5 0\n"
    vehicleString += "  translation -3.16697 0.317 -173.705\n"
    vehicleString += "  controller \"ros_automobile\"\n"
    vehicleString += "  sensorsSlotCenter [\n"
    vehicleString += "    GPS {\n"
    vehicleString += "    }\n"
    vehicleString += "   ]\n"

I get the following error ([ros_automobile] Error: Only nodes based on the 'Car' node can used the car library.)

I will highly appreciate any guidance that you guys can provide. Thank you for your time.


问:
How to compress or compact a string in Python
I'm making a python "script" that sends a string to a webservice (in C#). I NEED to compress or compact this string, because the bandwidth and MBs data is LIMITED (yeah, in capitals because it's very limited).

I was thinking of converting it into a file and then compressing the file. But I'm looking for a method to directly compress the string.

How can I compress or compact the string?

答:
```<code>import sys
import zlib

text=b"""This function is the primary interface to this module along with
decompress() function. This function returns byte object by compressing the data
given to it as parameter. The function has another parameter called level which
controls the extent of compression. It an integer between 0 to 9. Lowest value 0
stands for no compression and 9 stands for best compression. Higher the level of
compression, greater the length of compressed byte object."""

# Checking size of text
text_size=sys.getsizeof(text)
print("\nsize of original text",text_size)

# Compressing text
compressed = zlib.compress(text)

# Checking size of text after compression
csize=sys.getsizeof(compressed)
print("\nsize of compressed text",csize)

# Decompressing text
decompressed=zlib.decompress(compressed)

#Checking size of text after decompression
dsize=sys.getsizeof(decompressed)
print("\nsize of decompressed text",dsize)

print("\nDifference of size= ", text_size-csize)
</code>```


问:
resample dataframe into first 4 months of each year and sum the values
I wish to do soemthing like per mentioned on my title which is to first extract 4 months from each year and then sum the values of the first 4 months of each year.

my attemp:

```<code>a = pd.DataFrame({'ds': [d for d in pd.date_range(start='2018-01-01', end='2020-05-30')],
             'value': [1 for v in range(881)]})
a.resample('Y', on='ds', loffset='4M').sum()
</code>```

My current output:

```<code>    value
ds
2019-04-30  365
2020-04-30  365
2021-04-30  151
</code>```

My expected output:

```<code>    value
ds
2018-04-30  120
2019-04-30  120
2020-04-30  121
</code>```

答:
You can filter first 4 moths before resample by boolean indexing with Series.dt.month and Series.lt for less like 5, also for starting by 2018 is used YS for start of year:

```<code>df = a[a['ds'].dt.month.lt(5)].resample('YS', on='ds', loffset='4M').sum()
print (df)
            value
ds
2018-04-30    120
2019-04-30    120
2020-04-30    121
</code>```

Body:
I wish to do soemthing like per mentioned on my title which is to first extract 4 months from each year and then sum the values of the first 4 months of each year.

my attemp:

a = pd.DataFrame({'ds': [d for d in pd.date_range(start='2018-01-01', end='2020-05-30')],
             'value': [1 for v in range(881)]})
a.resample('Y', on='ds', loffset='4M').sum()

My current output:

    value
ds
2019-04-30  365
2020-04-30  365
2021-04-30  151

My expected output:

    value
ds
2018-04-30  120
2019-04-30  120
2020-04-30  121

Body:
You can filter first 4 moths before resample by boolean indexing with Series.dt.month and Series.lt for less like 5, also for starting by 2018 is used YS for start of year:

df = a[a['ds'].dt.month.lt(5)].resample('YS', on='ds', loffset='4M').sum()
print (df)
            value
ds
2018-04-30    120
2019-04-30    120
2020-04-30    121


问:
OR Condition Return Error in GQL ( Google app engine) Why?
When i use the OR condion in GQL it return error messege tht "BadQueryError: Parse Error: Expected no additional symbols at symbol OR . Why?

```<code>db.GqlQuery("Select * from vendor where access='public' OR organisation_id='"+ orgid +"'")
</code>```

答:
```<code>    GQL does not have an OR operator. However, it does have an IN operator,
which provides a limited form of OR.
</code>```

Docs clearly says that GQL doesn't have an OR operator..

You could do something like this ..Make two queries and combine the results...

```<code>  vendors=vendor.all()
  pub_vendors = vendors.filter("access = ","public")
  vendors=vendor.all()
  org_vendors = vendors.filter("organisation_id = ",orgid)
  results = pub_vendors.extend(org_vendors)
</code>```

Body:
When i use the OR condion in GQL it return error messege tht "BadQueryError: Parse Error: Expected no additional symbols at symbol OR . Why?

db.GqlQuery("Select * from vendor where access='public' OR organisation_id='"+ orgid +"'")

Body:
    GQL does not have an OR operator. However, it does have an IN operator,
which provides a limited form of OR.

Docs clearly says that GQL doesn't have an OR operator..

You could do something like this ..Make two queries and combine the results...

  vendors=vendor.all()
  pub_vendors = vendors.filter("access = ","public")
  vendors=vendor.all()
  org_vendors = vendors.filter("organisation_id = ",orgid)
  results = pub_vendors.extend(org_vendors)


问:
Download file using WorkManager
I am working/trying with download a file with pause and resume functionality using WorkManager with MVVM.

Here I am seeking pause/resume and download percentage progress update with use of WorkManager. So I am sharing my classes here.

MainActivity.kt

```<code>class MainActivity : AppCompatActivity() {

    lateinit var downloadViewModel : DownloaderViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this,R.layout.activity_main)
        downloadViewModel = ViewModelProviders.of(this).get(DownloaderViewModel::class.java)
        binding.viewmodel = downloadViewModel
        download_button.setOnClickListener({
                startDownload()
        })

        cancel_button.setOnClickListener({
            downloadViewModel.cancelDownloadWork(Constants.TAG_OUTPUT)
            WorkUtils.deleteFile(WorkUtils.getIsbn(Constants.TAG_OUTPUT))
        })

        downloadViewModel.mSavedWorkStatus.observe(this, Observer {

            it?.let {

            }
            if(it?.size!! > 0){
                val workStatus = it.first()
                val workState =  workStatus?.state
                downloadViewModel.updateDownloadWorkState(workState.toString())
                WorkUtils.makeStatusNotification(workState.toString(),this.applicationContext)
            }
        })

        pause_button.setOnClickListener({
            downloadViewModel.cancelDownloadWork(Constants.TAG_OUTPUT)
            val pausedAt = WorkUtils.getFileSize(WorkUtils.getIsbn(DOWNLOAD_URL))
            Log.d("paused at","paused at $pausedAt")
        })

        resume_button.setOnClickListener({
            val resumeFrom = WorkUtils.getFileSize(WorkUtils.getIsbn(DOWNLOAD_URL))
            Log.d("paused at","resumed at ${resumeFrom+1}")
            startDownload()
        })

    }

    fun startDownload() {
        downloadViewModel.downloadUrl =  DOWNLOAD_URL
        downloadViewModel.makeDownloadRequest()
    }

    fun isFileExists(url : String) : Boolean {

        return File(WorkUtils.getAbsolutePath(WorkUtils.getIsbn(url))).exists()

    }
}
</code>```

Constants.kt

```<code>class Constants {
    companion object {

        val DOWNLOAD_URL = "download_url"
        // Notification Channel constants

        // Name of Notification Channel for verbose notifications of background work
        val VERBOSE_NOTIFICATION_CHANNEL_NAME: CharSequence = "Verbose WorkManager Notifications"
        var VERBOSE_NOTIFICATION_CHANNEL_DESCRIPTION = "Shows notifications whenever work starts"
        val NOTIFICATION_TITLE: CharSequence = "WorkRequest Starting"
        val CHANNEL_ID = "VERBOSE_NOTIFICATION"
        val NOTIFICATION_ID = 1

        // The name of the image manipulation work
        internal val IMAGE_MANIPULATION_WORK_NAME = "image_manipulation_work"

        // Other keys
        val OUTPUT_PATH = "blur_filter_outputs"
        val KEY_DOWNLOAD_URL = "KEY_DOWNLOAD_URL"
        internal val TAG_OUTPUT = "OUTPUT"

        val DELAY_TIME_MILLIS: Long = 3000

        // Ensures this class is never instantiated
        private fun Constants() {}
    }
}
</code>```

DownloaderViewModel.kt

To make download request and notify the UI using binding. Cancelling the download(work) using WorkManager instance.

```<code>class DownloaderViewModel : ObservableViewModel() {
    var  mWorkManager : WorkManager = WorkManager.getInstance()

    var   mSavedWorkStatus: LiveData<List<WorkStatus>>
    @Bindable
    var currentDownloadState : MutableLiveData<String> = MutableLiveData()
    init {
        mSavedWorkStatus = mWorkManager.getStatusesByTagLiveData(Constants.TAG_OUTPUT)
    }

    lateinit var  downloadUrl: String
    /**
     * Creates the input data bundle which includes the Uri to operate on
     * @return Data which contains the Image Uri as a String
     */
    private fun createInputData(): Data {
        val builder = Data.Builder()
        if (downloadUrl != null) {
            builder.putString(KEY_DOWNLOAD_URL, downloadUrl)
        }
        return builder.build()
    }

    fun makeDownloadRequest() {

        // Create charging constraint
        val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .setRequiresCharging(true)
                .build()

        // Add WorkRequest to download the epub to the filesystem
        val save = OneTimeWorkRequest.Builder(DownloadWorker::class.java)
                .setConstraints(constraints)
                .setInputData(createInputData())
                .addTag(TAG_OUTPUT)
                .build()
        mWorkManager.enqueue(save)
    }

    fun cancelDownloadWork(tag : String) {
        mWorkManager.cancelAllWorkByTag(tag)
    }

    fun getDownloadWorkState()  {
        getOutputStatus()
    }

    fun updateDownloadWorkState(state: String){
        currentDownloadState.value = state
        notifyPropertyChanged(BR.currentDownloadState)
    }

    internal fun getOutputStatus(): LiveData<List<WorkStatus>> {
        return mWorkManager.getStatusesByTagLiveData(TAG_OUTPUT)
    }
}
</code>```

Worker class : DownloadWorker.kt
This class used to start the download work . As the server supports range request, every OneTimeWorkRequest started with this work range to download the file.

```<code>class DownloadWorker(context : Context,workerParameters: WorkerParameters) : Worker(context,workerParameters) {
    override fun doWork(): Result {

        val applicationContext = applicationContext

        // Makes a notification when the work starts and slows down the work so that it's easier to
        // see each WorkRequest start, even on emulated devices

        lateinit var result : Result
        val inputData : String? = inputData.getString(KEY_DOWNLOAD_URL)
        inputData?.let {
             result =  downloadFile(inputData)

        }
        return result
    }

    fun downloadFile(url : String) : Result {
        var input: InputStream? = null
        var output: OutputStream? = null
        var connection: HttpURLConnection? = null
        lateinit var result : Result

        val isbnFileName = WorkUtils.getIsbn(url);
        val filePathToWrite = WorkUtils.getAbsolutePath(isbnFileName)

        //val path = "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).path}${File.separator}${"file.zip"}"
        Log.d("Download file path :","Download file path :"+filePathToWrite)
        val targetFile = File(filePathToWrite)
        if(!targetFile?.exists()){
            targetFile.createNewFile()
        }

        try {
            val urlConnection = URL(url)
            connection = urlConnection.openConnection() as HttpURLConnection
            val range = WorkUtils.getFileSize(isbnFileName)+1
            connection.setRequestProperty("Range","bytes=${range}-")
            Log.d("Range","Request header Range is $range")
            connection.connect()

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.responseCode != HttpURLConnection.HTTP_OK) {
                Log.e("","Server returned HTTP ${connection.responseCode} ${connection.responseMessage}")
                result =  Result.FAILURE
            }

            // download the file

            input = connection.inputStream

            input?.let {
                output = FileOutputStream(targetFile, false)

                val data = ByteArray(1024 * 4)
                var count: Int

                do {
                    count = input.read(data)
                    if (count != 1) {
                        output!!.write(data, 0, count)

                    } else {
                        break
                    }

                } while (count != -1)
            }

            result = Result.SUCCESS

        } catch (e: Exception) {
            Log.e("Exception occured:",e.message)
            result =  Result.FAILURE
        } finally {
            try {
                output?.close()
                input?.close()
                connection?.disconnect()
            } catch (e: IOException) {
                Log.e("Exception occured:",e.message)
            }
        }
        return result
    }
}
</code>```

Utilities used in this sample
Utils.kt

```<code>class WorkUtils {

    companion object {
        private val TAG = WorkUtils::class.java.getSimpleName()

    fun makeStatusNotification(message: String, context: Context) {

        // Make a channel if necessary
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Create the NotificationChannel, but only on API 26+ because
            // the NotificationChannel class is new and not in the support library
            val name = Constants.VERBOSE_NOTIFICATION_CHANNEL_NAME
            val description = Constants.VERBOSE_NOTIFICATION_CHANNEL_DESCRIPTION
            val importance = NotificationManager.IMPORTANCE_HIGH
            val channel = NotificationChannel(Constants.CHANNEL_ID, name, importance)
            channel.description = description

            // Add the channel
            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            notificationManager?.createNotificationChannel(channel)
        }

        // Create the notification
        val builder = NotificationCompat.Builder(context, Constants.CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(Constants.NOTIFICATION_TITLE)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setVibrate(LongArray(0))

        // Show the notification
        NotificationManagerCompat.from(context).notify(Constants.NOTIFICATION_ID, builder.build())
    }

        /**
         * Method for sleeping for a fixed about of time to emulate slower work
         */
        fun sleep() {
            try {
                Thread.sleep(Constants.DELAY_TIME_MILLIS, 0)
            } catch (e: InterruptedException) {
                Log.d(TAG, e.message)
            }

        }

        fun getIsbn(url: String) : String {
            return url.substring(url.lastIndexOf("/")+1)
        }

        fun getAbsolutePath(isbnFileName: String): String {
            return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()+"/"+isbnFileName+".zip";
        }

        fun getFileSize(isbn:String) : Long {

            val file: File = File(getAbsolutePath(isbn))
            if(!file?.exists())
            {
                return 0
            }else{
                return file?.length()
            }
        }

        fun deleteFile(isbn: String) {
            val file = File(getAbsolutePath(isbn))
            if(file.exists() && file.isFile) {
                file.delete()
            }
        }

    }
}
</code>```

For the UI part with databinding

```<code><?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    >
    <data>

        <import type="com.pkonf.downloadebook.viewmodels.DownloaderViewModel" />

        <variable
            name="viewmodel"
            type="com.pkonf.downloadebook.viewmodels.DownloaderViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

        <TextView
            android:id="@+id/download_status"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:text="@{viewmodel.currentDownloadState}"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <LinearLayout
            android:id="@+id/linearLayout"
            android:layout_width="368dp"
            android:layout_height="50dp"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp"
            android:orientation="horizontal"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent">

            <Button
                android:id="@+id/pause_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="pause_button"
                tools:text="Pause" />

            <Button
                android:id="@+id/resume_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="resume_button"
                tools:text="Resume" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout2"
            android:layout_width="377dp"
            android:layout_height="157dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="28dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp"
            android:gravity="center_horizontal|center_vertical"
            android:orientation="vertical"
            app:layout_constraintBottom_toTopOf="@+id/linearLayout"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/download_status"
            app:layout_constraintVertical_bias="0.95">

            <Button
                android:id="@+id/download_button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="-1dp"
                android:text="Download"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="@id/linearLayout2"
                app:layout_constraintTop_toTopOf="@+id/linearLayout2" />

            <Button
                android:id="@+id/cancel_button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginBottom="8dp"
                android:text="Cancel"
                app:layout_constraintBottom_toBottomOf="@+id/linearLayout2"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/download_button" />

        </LinearLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
</code>```

I have tried with - starting the download - pausing the download (here pausing means cancelling the current OneTimeWorkRequest) and resuming by creating new OneTimeWorkRequest and start/resume with downloaded file length+1 as bytes range in request header.
But the cancel is not working in my case. Don't know what I am doing wrong.
And my questions are,
1. Can we do pause and resume download using WorkManager?
2. Can we update progress bar using WorkManager?
3. Ref : link is this is the only way to update the progress bar?

答:
You can do this, override the onStopped() method of DownloadWorker class and then execute, connection.disconnect()

Something like this:

```<code>class DownloadWorker(context : Context,workerParameters: WorkerParameters) : Worker(context,workerParameters) {
    private val connection: HttpUrlConnection? = null

    override fun doWork(): Result {
        connection = ...

        ...
    }

    override fun onStopped() {
        super.onStopped()
        connection.disconnect()
    }
}
</code>```

Title: Download file using WorkManager

Body:
I am working/trying with download a file with pause and resume functionality using WorkManager with MVVM.

Here I am seeking pause/resume and download percentage progress update with use of WorkManager. So I am sharing my classes here.

MainActivity.kt

class MainActivity : AppCompatActivity() {

    lateinit var downloadViewModel : DownloaderViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this,R.layout.activity_main)
        downloadViewModel = ViewModelProviders.of(this).get(DownloaderViewModel::class.java)
        binding.viewmodel = downloadViewModel
        download_button.setOnClickListener({
                startDownload()
        })

        cancel_button.setOnClickListener({
            downloadViewModel.cancelDownloadWork(Constants.TAG_OUTPUT)
            WorkUtils.deleteFile(WorkUtils.getIsbn(Constants.TAG_OUTPUT))
        })

        downloadViewModel.mSavedWorkStatus.observe(this, Observer {

            it?.let {

            }
            if(it?.size!! > 0){
                val workStatus = it.first()
                val workState =  workStatus?.state
                downloadViewModel.updateDownloadWorkState(workState.toString())
                WorkUtils.makeStatusNotification(workState.toString(),this.applicationContext)
            }
        })

        pause_button.setOnClickListener({
            downloadViewModel.cancelDownloadWork(Constants.TAG_OUTPUT)
            val pausedAt = WorkUtils.getFileSize(WorkUtils.getIsbn(DOWNLOAD_URL))
            Log.d("paused at","paused at $pausedAt")
        })

        resume_button.setOnClickListener({
            val resumeFrom = WorkUtils.getFileSize(WorkUtils.getIsbn(DOWNLOAD_URL))
            Log.d("paused at","resumed at ${resumeFrom+1}")
            startDownload()
        })

    }

    fun startDownload() {
        downloadViewModel.downloadUrl =  DOWNLOAD_URL
        downloadViewModel.makeDownloadRequest()
    }

    fun isFileExists(url : String) : Boolean {

        return File(WorkUtils.getAbsolutePath(WorkUtils.getIsbn(url))).exists()

    }
}

Constants.kt

class Constants {
    companion object {

        val DOWNLOAD_URL = "download_url"
        // Notification Channel constants

        // Name of Notification Channel for verbose notifications of background work
        val VERBOSE_NOTIFICATION_CHANNEL_NAME: CharSequence = "Verbose WorkManager Notifications"
        var VERBOSE_NOTIFICATION_CHANNEL_DESCRIPTION = "Shows notifications whenever work starts"
        val NOTIFICATION_TITLE: CharSequence = "WorkRequest Starting"
        val CHANNEL_ID = "VERBOSE_NOTIFICATION"
        val NOTIFICATION_ID = 1

        // The name of the image manipulation work
        internal val IMAGE_MANIPULATION_WORK_NAME = "image_manipulation_work"

        // Other keys
        val OUTPUT_PATH = "blur_filter_outputs"
        val KEY_DOWNLOAD_URL = "KEY_DOWNLOAD_URL"
        internal val TAG_OUTPUT = "OUTPUT"

        val DELAY_TIME_MILLIS: Long = 3000

        // Ensures this class is never instantiated
        private fun Constants() {}
    }
}

DownloaderViewModel.kt

To make download request and notify the UI using binding. Cancelling the download(work) using WorkManager instance.

class DownloaderViewModel : ObservableViewModel() {
    var  mWorkManager : WorkManager = WorkManager.getInstance()

    var   mSavedWorkStatus: LiveData<List<WorkStatus>>
    @Bindable
    var currentDownloadState : MutableLiveData<String> = MutableLiveData()
    init {
        mSavedWorkStatus = mWorkManager.getStatusesByTagLiveData(Constants.TAG_OUTPUT)
    }

    lateinit var  downloadUrl: String
    /**
     * Creates the input data bundle which includes the Uri to operate on
     * @return Data which contains the Image Uri as a String
     */
    private fun createInputData(): Data {
        val builder = Data.Builder()
        if (downloadUrl != null) {
            builder.putString(KEY_DOWNLOAD_URL, downloadUrl)
        }
        return builder.build()
    }

    fun makeDownloadRequest() {

        // Create charging constraint
        val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .setRequiresCharging(true)
                .build()

        // Add WorkRequest to download the epub to the filesystem
        val save = OneTimeWorkRequest.Builder(DownloadWorker::class.java)
                .setConstraints(constraints)
                .setInputData(createInputData())
                .addTag(TAG_OUTPUT)
                .build()
        mWorkManager.enqueue(save)
    }

    fun cancelDownloadWork(tag : String) {
        mWorkManager.cancelAllWorkByTag(tag)
    }

    fun getDownloadWorkState()  {
        getOutputStatus()
    }

    fun updateDownloadWorkState(state: String){
        currentDownloadState.value = state
        notifyPropertyChanged(BR.currentDownloadState)
    }

    internal fun getOutputStatus(): LiveData<List<WorkStatus>> {
        return mWorkManager.getStatusesByTagLiveData(TAG_OUTPUT)
    }
}

Worker class : DownloadWorker.kt
This class used to start the download work . As the server supports range request, every OneTimeWorkRequest started with this work range to download the file.

class DownloadWorker(context : Context,workerParameters: WorkerParameters) : Worker(context,workerParameters) {
    override fun doWork(): Result {

        val applicationContext = applicationContext

        // Makes a notification when the work starts and slows down the work so that it's easier to
        // see each WorkRequest start, even on emulated devices

        lateinit var result : Result
        val inputData : String? = inputData.getString(KEY_DOWNLOAD_URL)
        inputData?.let {
             result =  downloadFile(inputData)

        }
        return result
    }

    fun downloadFile(url : String) : Result {
        var input: InputStream? = null
        var output: OutputStream? = null
        var connection: HttpURLConnection? = null
        lateinit var result : Result

        val isbnFileName = WorkUtils.getIsbn(url);
        val filePathToWrite = WorkUtils.getAbsolutePath(isbnFileName)

        //val path = "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).path}${File.separator}${"file.zip"}"
        Log.d("Download file path :","Download file path :"+filePathToWrite)
        val targetFile = File(filePathToWrite)
        if(!targetFile?.exists()){
            targetFile.createNewFile()
        }

        try {
            val urlConnection = URL(url)
            connection = urlConnection.openConnection() as HttpURLConnection
            val range = WorkUtils.getFileSize(isbnFileName)+1
            connection.setRequestProperty("Range","bytes=${range}-")
            Log.d("Range","Request header Range is $range")
            connection.connect()

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.responseCode != HttpURLConnection.HTTP_OK) {
                Log.e("","Server returned HTTP ${connection.responseCode} ${connection.responseMessage}")
                result =  Result.FAILURE
            }

            // download the file

            input = connection.inputStream

            input?.let {
                output = FileOutputStream(targetFile, false)

                val data = ByteArray(1024 * 4)
                var count: Int

                do {
                    count = input.read(data)
                    if (count != 1) {
                        output!!.write(data, 0, count)

                    } else {
                        break
                    }

                } while (count != -1)
            }

            result = Result.SUCCESS

        } catch (e: Exception) {
            Log.e("Exception occured:",e.message)
            result =  Result.FAILURE
        } finally {
            try {
                output?.close()
                input?.close()
                connection?.disconnect()
            } catch (e: IOException) {
                Log.e("Exception occured:",e.message)
            }
        }
        return result
    }
}

Utilities used in this sample
Utils.kt

class WorkUtils {

    companion object {
        private val TAG = WorkUtils::class.java.getSimpleName()

    fun makeStatusNotification(message: String, context: Context) {

        // Make a channel if necessary
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Create the NotificationChannel, but only on API 26+ because
            // the NotificationChannel class is new and not in the support library
            val name = Constants.VERBOSE_NOTIFICATION_CHANNEL_NAME
            val description = Constants.VERBOSE_NOTIFICATION_CHANNEL_DESCRIPTION
            val importance = NotificationManager.IMPORTANCE_HIGH
            val channel = NotificationChannel(Constants.CHANNEL_ID, name, importance)
            channel.description = description

            // Add the channel
            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            notificationManager?.createNotificationChannel(channel)
        }

        // Create the notification
        val builder = NotificationCompat.Builder(context, Constants.CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(Constants.NOTIFICATION_TITLE)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setVibrate(LongArray(0))

        // Show the notification
        NotificationManagerCompat.from(context).notify(Constants.NOTIFICATION_ID, builder.build())
    }

        /**
         * Method for sleeping for a fixed about of time to emulate slower work
         */
        fun sleep() {
            try {
                Thread.sleep(Constants.DELAY_TIME_MILLIS, 0)
            } catch (e: InterruptedException) {
                Log.d(TAG, e.message)
            }

        }

        fun getIsbn(url: String) : String {
            return url.substring(url.lastIndexOf("/")+1)
        }

        fun getAbsolutePath(isbnFileName: String): String {
            return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()+"/"+isbnFileName+".zip";
        }

        fun getFileSize(isbn:String) : Long {

            val file: File = File(getAbsolutePath(isbn))
            if(!file?.exists())
            {
                return 0
            }else{
                return file?.length()
            }
        }

        fun deleteFile(isbn: String) {
            val file = File(getAbsolutePath(isbn))
            if(file.exists() && file.isFile) {
                file.delete()
            }
        }

    }
}

For the UI part with databinding

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    >
    <data>

        <import type="com.pkonf.downloadebook.viewmodels.DownloaderViewModel" />

        <variable
            name="viewmodel"
            type="com.pkonf.downloadebook.viewmodels.DownloaderViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

        <TextView
            android:id="@+id/download_status"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:text="@{viewmodel.currentDownloadState}"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <LinearLayout
            android:id="@+id/linearLayout"
            android:layout_width="368dp"
            android:layout_height="50dp"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp"
            android:orientation="horizontal"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent">

            <Button
                android:id="@+id/pause_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="pause_button"
                tools:text="Pause" />

            <Button
                android:id="@+id/resume_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="resume_button"
                tools:text="Resume" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout2"
            android:layout_width="377dp"
            android:layout_height="157dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="28dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp"
            android:gravity="center_horizontal|center_vertical"
            android:orientation="vertical"
            app:layout_constraintBottom_toTopOf="@+id/linearLayout"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/download_status"
            app:layout_constraintVertical_bias="0.95">

            <Button
                android:id="@+id/download_button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="-1dp"
                android:text="Download"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="@id/linearLayout2"
                app:layout_constraintTop_toTopOf="@+id/linearLayout2" />

            <Button
                android:id="@+id/cancel_button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginBottom="8dp"
                android:text="Cancel"
                app:layout_constraintBottom_toBottomOf="@+id/linearLayout2"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/download_button" />

        </LinearLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

I have tried with - starting the download - pausing the download (here pausing means cancelling the current OneTimeWorkRequest) and resuming by creating new OneTimeWorkRequest and start/resume with downloaded file length+1 as bytes range in request header.
But the cancel is not working in my case. Don't know what I am doing wrong.
And my questions are,
1. Can we do pause and resume download using WorkManager?
2. Can we update progress bar using WorkManager?
3. Ref : link is this is the only way to update the progress bar?

Body:
You can do this, override the onStopped() method of DownloadWorker class and then execute, connection.disconnect()

Something like this:

class DownloadWorker(context : Context,workerParameters: WorkerParameters) : Worker(context,workerParameters) {
    private val connection: HttpUrlConnection? = null

    override fun doWork(): Result {
        connection = ...

        ...
    }

    override fun onStopped() {
        super.onStopped()
        connection.disconnect()
    }
}


问:
How to convert ViewModel to utilize state saving?
I have a ViewModel I am currently using to contain data and share values between Fragments.  This model also helps instantiate the data for the app on activity start.

I am now trying to add in state saving functionality to my app, and I'm confused on how to merge the two systems together.  The android docs mention to use this constructor:

public MyViewModel(SavedStateHandle savedStateHandle) {
    mState = savedStateHandle;
}
```

<p>However, I'm unsure on how the state is passed and how this constructor is used in activities (here is my usage):</p>

<pre class="lang-java prettyprint-override"><code> myViewModel = new ViewModelProvider(requireActivity()).get(myViewModel.class);
</code>```

Anyway, since I need to also instantiate data in case the savedState is null, I'm not sure how that part fits in.  For reference, here is a general outline of my ViewModel class:

public class myViewModel extends ViewModel {
//    private MutableLiveData<Integer> foo;  <-- obsolete with state saving

    private SavedStateHandle mState;
    private static final String FOO_KEY = "foo";

    // Do I need this anymore? How do I combine this with the other constructor?
    public myViewModel() {
        foo = new MutableLiveData<>();
        foo.setValue(4);
    }

    // Constructor for the savedStateHandle
    public myViewModel(SavedStateHandle savedStateHandle) { mState = savedStateHandle; }

    LiveData<Integer> getFoo() { return mState.getLiveData(FOO_KEY); }

    void setFoo(int foo) { mState.set(FOO_KEY, foo); }

}
```

Obviously if I take out the old constructor and MutableLiveData member, then when I access the ViewModel in my fragments, the data will be null (because I haven't told the activity to explicitly save a state yet), and I haven't instantiated any data.

答:
You don't need your no argument constructor. Instead, you should use the other getLiveData() method that takes an initial value:

```<code>public class myViewModel extends ViewModel {

    private SavedStateHandle mState;
    private static final String FOO_KEY = "foo";

    public myViewModel(SavedStateHandle savedStateHandle) {
        mState = savedStateHandle;
    }

    LiveData<Integer> getFoo() {
        // Get the LiveData, setting the default value if it doesn't
        // already have a value set.
        return mState.getLiveData(FOO_KEY, 4);
    }

    void setFoo(int foo) { mState.set(FOO_KEY, foo); }

}
</code>```

Body:
I have a ViewModel I am currently using to contain data and share values between Fragments.  This model also helps instantiate the data for the app on activity start.

I am now trying to add in state saving functionality to my app, and I'm confused on how to merge the two systems together.  The android docs mention to use this constructor:

public MyViewModel(SavedStateHandle savedStateHandle) {
    mState = savedStateHandle;
}

However, I'm unsure on how the state is passed and how this constructor is used in activities (here is my usage):

 myViewModel = new ViewModelProvider(requireActivity()).get(myViewModel.class);

Anyway, since I need to also instantiate data in case the savedState is null, I'm not sure how that part fits in.  For reference, here is a general outline of my ViewModel class:

public class myViewModel extends ViewModel {
//    private MutableLiveData<Integer> foo;  <-- obsolete with state saving

    private SavedStateHandle mState;
    private static final String FOO_KEY = "foo";

    // Do I need this anymore? How do I combine this with the other constructor?
    public myViewModel() {
        foo = new MutableLiveData<>();
        foo.setValue(4);
    }

    // Constructor for the savedStateHandle
    public myViewModel(SavedStateHandle savedStateHandle) { mState = savedStateHandle; }

    LiveData<Integer> getFoo() { return mState.getLiveData(FOO_KEY); }

    void setFoo(int foo) { mState.set(FOO_KEY, foo); }

}

Obviously if I take out the old constructor and MutableLiveData member, then when I access the ViewModel in my fragments, the data will be null (because I haven't told the activity to explicitly save a state yet), and I haven't instantiated any data.

Body:
You don't need your no argument constructor. Instead, you should use the other getLiveData() method that takes an initial value:

public class myViewModel extends ViewModel {

    private SavedStateHandle mState;
    private static final String FOO_KEY = "foo";

    public myViewModel(SavedStateHandle savedStateHandle) {
        mState = savedStateHandle;
    }

    LiveData<Integer> getFoo() {
        // Get the LiveData, setting the default value if it doesn't
        // already have a value set.
        return mState.getLiveData(FOO_KEY, 4);
    }

    void setFoo(int foo) { mState.set(FOO_KEY, foo); }

}


问:
Vuejs sum on event change
I have following code that sum price of product to existed number when user increase the quantity of product. But the issue with my code is if user decrease the amount price still gets increased.

Code

html

```<code><el-input-number style="width: 100%;" ref="amount" v-on:change="amoutChanged($event, row)" v-model="row.amount" :min="1"></el-input-number>
</code>```

script

```<code>data() {
    return {
        subtotal: 0,
    }
},
methods: {
    amoutChanged: function(event, row) {
        console.log('amount row: ', row);
        console.log('amount event: ', event);
        // ISSUE: regardes that user increase or decrease the amount number this price gets increased
        this.subtotal = parseInt(this.subtotal) + parseInt(row.price);
    },
}
</code>```

Console results

```<code>amount row:  {barcoded: "8995078803078", …}
  amount: (...)
  barcode_id: (...)
  barcoded: "8995078803078"
  price: (...)
  product: (...)

amount event:  2  // this is amount input by user
</code>```

Question

How to properly increase and decrease price based on user action?

答:
I have done it like this:

I changed subtotal to an computed propertie and sum it with .reduce() and i added a new property called singlePrice so we can multiply with it

var Main = {
  data() {
    return {
      serial_numbers: [{
        barcode_id: '45634643',
        product: 'dfgs546',
        amount: 1,
        price: 100,
        singlePrice: 100,
      },{
        barcode_id: '23523fd',
        product: 'rgdg46546',
        amount: 1,
        price: 100,
        singlePrice: 100,
      },{
        barcode_id: 'fdghdh',
        product: '345634643',
        amount: 1,
        price: 100,
        singlePrice: 100,
      }],
      total: 0,
      num1: 1
    };
  },
  computed: {
     subtotal(){

       return this.serial_numbers.reduce((a,v)=> a + v.price,0)
     }
  },
  methods: {
    addRow() {
     var barcodes = document.createElement('tr');
      this.serial_numbers.push({
        barcode_id: '675476547',
        product: 'hjfgj67',
        amount: 1,
        price: 100,
        singlePrice: 100,
      });
    },
    removeElement: function(index) {
      this.serial_numbers.splice(index, 1);
    },
    amountChanged($event, index){
       let amount = $event;
       this.serial_numbers[index].amount = amount;
       this.serial_numbers[index].price = this.serial_numbers[index].singlePrice * amount;
    }
  }
};
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url("//unpkg.com/element-ui@1.4.0/lib/theme-default/index.css");</code>```

        Serial Number
        Product
        Amount
        Price

          <el-input ref="barcoded" v-model="row.barcode_id"></el-input>

          <el-input ref="product" v-model="row.product" readonly></el-input>

          <el-input-number style="width: 100%;" ref="amount" @change="amountChanged($event, index)" v-model="row.amount" :min="1"></el-input-number>

          <el-input ref="price" v-model="row.price" readonly></el-input>

          <el-link :underline="false" type="danger" v-on:click="removeElement(index);" style="cursor: pointer"></el-link>

    <el-button type="primary" class="button btn-primary" round @click="addRow"> Add row</el-button>

  <el-row :gutter="10">
    <el-col :span="8" :offset="16">

            Sub total

              {{subtotal}}

            Total

              {{total}}

    </el-col>
  </el-row>

```

Title: Vuejs sum on event change

Body:
I have following code that sum price of product to existed number when user increase the quantity of product. But the issue with my code is if user decrease the amount price still gets increased.

Code

html

<el-input-number style="width: 100%;" ref="amount" v-on:change="amoutChanged($event, row)" v-model="row.amount" :min="1"></el-input-number>

script

data() {
    return {
        subtotal: 0,
    }
},
methods: {
    amoutChanged: function(event, row) {
        console.log('amount row: ', row);
        console.log('amount event: ', event);
        // ISSUE: regardes that user increase or decrease the amount number this price gets increased
        this.subtotal = parseInt(this.subtotal) + parseInt(row.price);
    },
}

Console results

amount row:  {barcoded: "8995078803078", …}
  amount: (...)
  barcode_id: (...)
  barcoded: "8995078803078"
  price: (...)
  product: (...)

amount event:  2  // this is amount input by user

Question

How to properly increase and decrease price based on user action?

Body:
I have done it like this:

I changed subtotal to an computed propertie and sum it with .reduce() and i added a new property called singlePrice so we can multiply with it

var Main = {
  data() {
    return {
      serial_numbers: [{
        barcode_id: '45634643',
        product: 'dfgs546',
        amount: 1,
        price: 100,
        singlePrice: 100,
      },{
        barcode_id: '23523fd',
        product: 'rgdg46546',
        amount: 1,
        price: 100,
        singlePrice: 100,
      },{
        barcode_id: 'fdghdh',
        product: '345634643',
        amount: 1,
        price: 100,
        singlePrice: 100,
      }],
      total: 0,
      num1: 1
    };
  },
  computed: {
     subtotal(){

       return this.serial_numbers.reduce((a,v)=> a + v.price,0)
     }
  },
  methods: {
    addRow() {
     var barcodes = document.createElement('tr');
      this.serial_numbers.push({
        barcode_id: '675476547',
        product: 'hjfgj67',
        amount: 1,
        price: 100,
        singlePrice: 100,
      });
    },
    removeElement: function(index) {
      this.serial_numbers.splice(index, 1);
    },
    amountChanged($event, index){
       let amount = $event;
       this.serial_numbers[index].amount = amount;
       this.serial_numbers[index].price = this.serial_numbers[index].singlePrice * amount;
    }
  }
};
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')

@import url("//unpkg.com/element-ui@1.4.0/lib/theme-default/index.css");

<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@1.4.0/lib/index.js"></script>
<div id="app">
  <table class="table table-bordered table-striped table-hover">
    <thead>
      <tr>
        <td><strong>Serial Number</strong></td>
        <td><strong>Product</strong></td>
        <td><strong>Amount</strong></td>
        <td><strong>Price</strong></td>
        <td width="50"></td>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(row, index) in serial_numbers" :key="index">
        <td>
          <el-input ref="barcoded" v-model="row.barcode_id"></el-input>
        </td>
        <td>
          <el-input ref="product" v-model="row.product" readonly></el-input>
        </td>
        <td>
          <el-input-number style="width: 100%;" ref="amount" @change="amountChanged($event, index)" v-model="row.amount" :min="1"></el-input-number>
        </td>
        <td>
          <el-input ref="price" v-model="row.price" readonly></el-input>
        </td>
        <td>
          <el-link :underline="false" type="danger" v-on:click="removeElement(index);" style="cursor: pointer"><i class="fa-2x el-icon-remove"></i></el-link>
        </td>
      </tr>
    </tbody>
  </table>
  <div>
    <el-button type="primary" class="button btn-primary" round @click="addRow"><i class="el-icon-circle-plus"></i> Add row</el-button>
  </div>

  <el-row :gutter="10">
    <el-col :span="8" :offset="16">
      <table class="table table-bordered table-striped table-hover">
        <tbody>
          <tr>
            <th width="100"><strong>Sub total</strong></th>
            <td>
              {{subtotal}}
            </td>
          </tr>
          <tr>
            <th width="100"><strong>Total</strong></th>
            <td>
              {{total}}
            </td>
          </tr>
        </tbody>
      </table>
    </el-col>
  </el-row>
</div>


答:
Your code is:

```<code>else {
    var a = "The 'a' changed";
     console.log("Inner circle: Now our a is:" + " " + a);
}
</code>```

Notice how you again declared the variable as 'var'. This made 'a' in else part a local variable. Remove that var.

Title: Change globally scoped variable in JavaScript from inside a function

Body:
Your code is:

else {
    var a = "The 'a' changed";
     console.log("Inner circle: Now our a is:" + " " + a);
}

Notice how you again declared the variable as 'var'. This made 'a' in else part a local variable. Remove that var.


问:
How to display raw array of pixels to the screen?
I am new to windows programming. I want to display the raw pixel array to the screen without using SetPixel function because it's too slow in my standards. I am using this question as my reference.

I made a small program below to fill the pixel array with random RGB values and display it to the screen. The result wasn't what I anticipated, I got the white canvas. I tried to change this line ptr++ = (b << 16) | (g << 8) | r; to ptr++ = 0x000000FF; expecting red canvas but I got the same result.

```<code>#include <stdlib.h>
#include <time.h>
#include <windows.h>

const int win_width = 500;
const int win_height = 450;

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    RECT rect;
    int width, height;
    COLORREF *display;

    switch (msg)
    {
    case WM_CREATE:
        srand((unsigned int) time(NULL));
        GetClientRect(hWnd, &rect);
        width = rect.right - rect.left;
        height = rect.bottom - rect.top;
        display = (COLORREF *) malloc(sizeof(COLORREF) * width * height);
        COLORREF *ptr = display;

        for (int y = 0; y < height; ++y)
        {
            for (int x = 0; x < width; ++x)
            {
                int r = rand() % 256;
                int g = rand() % 256;
                int b = rand() % 256;

                *ptr++ = (b << 16) | (g << 8) | r;
            }
        }

        break;
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hDC, memDC;
        HBITMAP hBmp, hOldBmp;

        hDC = BeginPaint(hWnd, &ps);
        memDC = CreateCompatibleDC(hDC);
        hBmp = CreateBitmap(width, height, 1, 32, (void *) display);
        hOldBmp = (HBITMAP) SelectObject(memDC, hBmp);

        BitBlt(hDC, rect.left, rect.top, width, height, memDC, 0, 0, SRCCOPY);

        SelectObject(memDC, hOldBmp);
        DeleteObject(hBmp);
        DeleteDC(memDC);

        EndPaint(hWnd, &ps);

        break;
    }
    case WM_CLOSE:
        DestroyWindow(hWnd);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, msg, wParam, lParam);
    }

    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    const TCHAR szClassName[] = TEXT("MyClass");

    WNDCLASS wc;
    HWND hWnd;
    MSG msg;

    wc.style         = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc   = WndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = hInstance;
    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wc.lpszMenuName  = NULL;
    wc.lpszClassName = szClassName;
    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);

    if (!RegisterClass(&wc))
    {
        MessageBox(NULL, TEXT("Window Registration Failed!"), TEXT("Error!"),
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    hWnd = CreateWindow(szClassName,
        TEXT("Random Pixels"),
        WS_OVERLAPPEDWINDOW | WS_VISIBLE,
        CW_USEDEFAULT, CW_USEDEFAULT, win_width, win_height,
        NULL, NULL, hInstance, NULL);

    if (hWnd == NULL)
    {
        MessageBox(NULL, TEXT("Window Creation Failed!"), TEXT("Error!"),
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int) msg.wParam;
}
</code>```

I know there's something wrong with my code inside WM_PAINT but I don't know how to fix it. I will appreciate any form of assistance. Thanks in advance.

答:
The variable display that holds the pixel data has automatic lifetime. Its lifetime ends whenever control leaves WndProc. A consequence is, that every invocation of WndProc starts out with a new (indeterminate) value for display.

To solve this, display needs to have static storage duration. The easiest way to accomplish this is to replace

```<code>COLORREF *display;
</code>```

with

```<code>static COLORREF *display;
</code>```

This has 2 consequences:

The value stored in display survives separate invocations of WndProc.

The value stored in display is now properly zero-initialized.

Body:
I am new to windows programming. I want to display the raw pixel array to the screen without using SetPixel function because it's too slow in my standards. I am using this question as my reference.

I made a small program below to fill the pixel array with random RGB values and display it to the screen. The result wasn't what I anticipated, I got the white canvas. I tried to change this line ptr++ = (b << 16) | (g << 8) | r; to ptr++ = 0x000000FF; expecting red canvas but I got the same result.

#include <stdlib.h>
#include <time.h>
#include <windows.h>

const int win_width = 500;
const int win_height = 450;

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    RECT rect;
    int width, height;
    COLORREF *display;

    switch (msg)
    {
    case WM_CREATE:
        srand((unsigned int) time(NULL));
        GetClientRect(hWnd, &rect);
        width = rect.right - rect.left;
        height = rect.bottom - rect.top;
        display = (COLORREF *) malloc(sizeof(COLORREF) * width * height);
        COLORREF *ptr = display;

        for (int y = 0; y < height; ++y)
        {
            for (int x = 0; x < width; ++x)
            {
                int r = rand() % 256;
                int g = rand() % 256;
                int b = rand() % 256;

                *ptr++ = (b << 16) | (g << 8) | r;
            }
        }

        break;
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hDC, memDC;
        HBITMAP hBmp, hOldBmp;

        hDC = BeginPaint(hWnd, &ps);
        memDC = CreateCompatibleDC(hDC);
        hBmp = CreateBitmap(width, height, 1, 32, (void *) display);
        hOldBmp = (HBITMAP) SelectObject(memDC, hBmp);

        BitBlt(hDC, rect.left, rect.top, width, height, memDC, 0, 0, SRCCOPY);

        SelectObject(memDC, hOldBmp);
        DeleteObject(hBmp);
        DeleteDC(memDC);

        EndPaint(hWnd, &ps);

        break;
    }
    case WM_CLOSE:
        DestroyWindow(hWnd);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, msg, wParam, lParam);
    }

    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    const TCHAR szClassName[] = TEXT("MyClass");

    WNDCLASS wc;
    HWND hWnd;
    MSG msg;

    wc.style         = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc   = WndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = hInstance;
    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wc.lpszMenuName  = NULL;
    wc.lpszClassName = szClassName;
    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);

    if (!RegisterClass(&wc))
    {
        MessageBox(NULL, TEXT("Window Registration Failed!"), TEXT("Error!"),
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    hWnd = CreateWindow(szClassName,
        TEXT("Random Pixels"),
        WS_OVERLAPPEDWINDOW | WS_VISIBLE,
        CW_USEDEFAULT, CW_USEDEFAULT, win_width, win_height,
        NULL, NULL, hInstance, NULL);

    if (hWnd == NULL)
    {
        MessageBox(NULL, TEXT("Window Creation Failed!"), TEXT("Error!"),
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int) msg.wParam;
}

I know there's something wrong with my code inside WM_PAINT but I don't know how to fix it. I will appreciate any form of assistance. Thanks in advance.

Body:
The variable display that holds the pixel data has automatic lifetime. Its lifetime ends whenever control leaves WndProc. A consequence is, that every invocation of WndProc starts out with a new (indeterminate) value for display.

To solve this, display needs to have static storage duration. The easiest way to accomplish this is to replace

COLORREF *display;

with

static COLORREF *display;

This has 2 consequences:

The value stored in display survives separate invocations of WndProc.

The value stored in display is now properly zero-initialized.


问:
Extract Data from JSON Array in Flutter/Dart
This is the response from request.

```<code>var response = [{"id":4731},{"id":4566},{"id":4336},{"id":4333},{"id":4172},{"id":4170},{"id":4168},{"id":4166},{"id":4163},{"id":4161}];
</code>```

How to extract ids and store in List of int using flutter.
I have try this code but not working.

```<code>Future<List<int>> fetchTopIds() async{

     final response = await client.get('$_baseUrl/posts?fields=id');
     final ids = json.decode(response.body);
     return ids.cast<int>();
}
</code>```

答:
Here I attached a complete example of converting a list to JSON and then retrieve the List back from that JSON.</p>

```<code>import 'dart:convert';

void main() {

  List<int> a= [1,2,3]; //List of Integer

  var json= jsonEncode(a); //json Encoded to String
  print(json.runtimeType.toString());

  var dec= jsonDecode(json); //Json Decoded to array of dynamic object

  print(dec.runtimeType.toString());

  a= (dec as List).map((t)=> t as int).toList(); //dynamic array mapped to integer List

  print(a);
}
</code>```

Body:
This is the response from request.

var response = [{"id":4731},{"id":4566},{"id":4336},{"id":4333},{"id":4172},{"id":4170},{"id":4168},{"id":4166},{"id":4163},{"id":4161}];

How to extract ids and store in List of int using flutter.
I have try this code but not working.

Future<List<int>> fetchTopIds() async{

     final response = await client.get('$_baseUrl/posts?fields=id');
     final ids = json.decode(response.body);
     return ids.cast<int>();
}

Body:
Here I attached a complete example of converting a list to JSON and then retrieve the List back from that JSON.

import 'dart:convert';

void main() {

  List<int> a= [1,2,3]; //List of Integer

  var json= jsonEncode(a); //json Encoded to String
  print(json.runtimeType.toString());

  var dec= jsonDecode(json); //Json Decoded to array of dynamic object

  print(dec.runtimeType.toString());

  a= (dec as List).map((t)=> t as int).toList(); //dynamic array mapped to integer List

  print(a);
}


问:
customise environment jupyter notebook
I wish to create a custom environment for my Jupyter notebook, without having to install the various packages from within the session.

Following the instructions at https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/customize-envs.html, I customised the environment as follows

```<code># Modify the following content to add a software customization to an environment.
# To remove an existing customization, delete the entire content and click Apply.

# Add conda channels below defaults, indented by two spaces and a hyphen.
channels:
  - defaults

# To add packages through conda or pip, remove the comment on the following line.
# dependencies:

# Add conda packages here, indented by two spaces and a hyphen.
# Remove the comment on the following line and replace sample package name with your package name:
  - ffmpeg=4.2.2

# Add pip packages here, indented by four spaces and a hyphen.
# Remove the comments on the following lines  and replace sample package name with your package name.
  - pip:
    - numpy==1.18.0
    - pandas==1.0.3
    - matplotlib==3.1.3
</code>```

because I need mpeg codec in my notebook and recent versions of pandas, numpy and matplotlib.

The configurations are

```<code>Environment             Custom env
Creator                 Andrea Chiappo
Language                Python 3.6
Hardware configuration  4 vCPU and 16 GB RAM
Software configuration  Default Python 3.6 + DO
</code>```

However, once I initiate the session, if I try

```<code>import pandas as pd
print(pd.__version__)
</code>```

I get the default version of the package, which is 0.24.1.

Does anybody know how to enable the more recent versions of such Python packages in my jypter session? Many thanks

答:
You need to uncomment the line # dependencies:. And feel free to get rid of all the comments. That will help to spot indentation problems with the YAML format. Try this:

dependencies:
  - ffmpeg=4.2.2
  - pip
  - pip:
    - numpy==1.18.0
    - pandas==1.0.3
    - matplotlib==3.1.3
```

<p><strong>But</strong> installing updates of numpy and pandas from PyPI instead of Anaconda may lead to problems. Some of the Anaconda packages are built for a specific version of numpy and could misbehave if you replace numpy. I recommend that you get packages from Anaconda rather than PyPI wherever that is feasible. In a Python notebook, you can check what changes <code>conda</code> will apply like this:</p>

<pre class="lang-sh prettyprint-override"><code>!conda install --dry-run numpy=1.18
</code>```

Likewise for pandas and matplotlib. Or you specify all three with the same command. Though it won't be obvious then which of the package changes causes dependency updates to be pulled in.

!conda install --dry-run numpy=1.18 pandas=1.0 matplotlib=3.1
```

I didn't try whether the exact fixlevels you want to install are available from Anaconda. If not, or if certain combinations don't work (for example when Anaconda doesn't build a new package version for Python 3.6 anymore), it's you choice whether you want to go with what Anaconda provides, or whether to get the package from PyPI and hope that nothing breaks.

PS:
In the customization above, I've added the pip dependency as a matter of style. Newer versions of conda will complain about having a pip: section when pip is not listed as a dependency. When we roll out new runtimes in WS Cloud, they'll use a newer version of conda.

Title: customise environment jupyter notebook

Body:
I wish to create a custom environment for my Jupyter notebook, without having to install the various packages from within the session.

Following the instructions at https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/customize-envs.html, I customised the environment as follows

# Modify the following content to add a software customization to an environment.
# To remove an existing customization, delete the entire content and click Apply.

# Add conda channels below defaults, indented by two spaces and a hyphen.
channels:
  - defaults

# To add packages through conda or pip, remove the comment on the following line.
# dependencies:

# Add conda packages here, indented by two spaces and a hyphen.
# Remove the comment on the following line and replace sample package name with your package name:
  - ffmpeg=4.2.2

# Add pip packages here, indented by four spaces and a hyphen.
# Remove the comments on the following lines  and replace sample package name with your package name.
  - pip:
    - numpy==1.18.0
    - pandas==1.0.3
    - matplotlib==3.1.3

because I need mpeg codec in my notebook and recent versions of pandas, numpy and matplotlib.

The configurations are

Environment             Custom env
Creator                 Andrea Chiappo
Language                Python 3.6
Hardware configuration  4 vCPU and 16 GB RAM
Software configuration  Default Python 3.6 + DO

However, once I initiate the session, if I try

import pandas as pd
print(pd.__version__)

I get the default version of the package, which is 0.24.1.

Does anybody know how to enable the more recent versions of such Python packages in my jypter session? Many thanks

Body:
You need to uncomment the line # dependencies:. And feel free to get rid of all the comments. That will help to spot indentation problems with the YAML format. Try this:

dependencies:
  - ffmpeg=4.2.2
  - pip
  - pip:
    - numpy==1.18.0
    - pandas==1.0.3
    - matplotlib==3.1.3

But installing updates of numpy and pandas from PyPI instead of Anaconda may lead to problems. Some of the Anaconda packages are built for a specific version of numpy and could misbehave if you replace numpy. I recommend that you get packages from Anaconda rather than PyPI wherever that is feasible. In a Python notebook, you can check what changes conda will apply like this:

!conda install --dry-run numpy=1.18

Likewise for pandas and matplotlib. Or you specify all three with the same command. Though it won't be obvious then which of the package changes causes dependency updates to be pulled in.

!conda install --dry-run numpy=1.18 pandas=1.0 matplotlib=3.1

I didn't try whether the exact fixlevels you want to install are available from Anaconda. If not, or if certain combinations don't work (for example when Anaconda doesn't build a new package version for Python 3.6 anymore), it's you choice whether you want to go with what Anaconda provides, or whether to get the package from PyPI and hope that nothing breaks.

PS:
In the customization above, I've added the pip dependency as a matter of style. Newer versions of conda will complain about having a pip: section when pip is not listed as a dependency. When we roll out new runtimes in WS Cloud, they'll use a newer version of conda.


问:
How to solve a data source error when loading Google Analytics data in Power BI?
I would like to load data from Google Analytics into Power BI.
After transforming the data in the Query Editor, I apply the changes.
At first, I see the message 'Waiting for www.googleapis.com' and the number of rows increases.
After a while, I get the following error message:

Failed to save modifications to the server. Error returned: 'OLE DB or ODBC error: [DataSource.Error] There was an internal error..'

Rows with errors have been removed in one of the steps and I have a stable Internet connection.
Does anyone have suggestions on how to solve this?

答: I was also facing this kind of refreshing issue, First go to edit query and verify the data types and change the data types if needed, after that if you still facing this error, you need to keep open the app.powerbi.com while refresh your PBI dashboard, I was followed the above steps and my issue got resolved now.</p>