问:
Transferring ownership of an iPhone app on the app store
My team and I have an app which we're going to be submitting to the store pretty soon, but we know that we'll be selling the app to another company in the near future. Does anyone have any experience with moving an app's ownership to another account?

Specifically, when I sell an app to another company...

How do we move the app to their account (what's the mechanism)?

Can my users still get updates (released by the new owner) without having to re-buy/re-download the app?

答:
I had my own experience with this, and the answer I got from Apple Developer Relations (Although it took a month to get an email response and 6 weeks for the follow up phone call) was (in short) that they currently don't offer any way to transfer individual applications from one developer account to another.

He did so by saying that there was a single "Option" for doing this sort of transfer, which is to delete the app from the account that it is currently on, and then resubmit to the Apple store from the new account under the same name (but it would have a new appstore id).  I pointed out (and he acknowledged) that this would delete any existing user reviews, ruin the upgrade path for existing users, break iAds, in-app purchases, and game center integration.  So it really isn't a solution at all.

He also said that it isn't possible to transfer ownership of all your apps to another existing account (they seem to lack the granularity to move individual apps).  However if I wanted to give up all my apps to another individual it could be possible by creating a corporation (probably S-Corp, although he didn't advise), transferring ownership of my account to the S-Corp (which would be allowed if I were a part owner), and then selling the s-corp to the new owner. (Yikes right?)

The method I plan to go with is the following (I'll update with my success), In my specific case I have a paid application that (.99) that I'm trying to transfer to another owner:

I will create a lightweight application using the same AppID that is designed to inform users that the Application has changed owners, and provide a link to the app store where they can download the new application.  When launched will upload a hashed form of their UDID to a server (which I will now have to maintain) listing them as a previous customer.

I will upload this new lightweight app to my existing account as an upgrade to the other existing application (so that when users update, they will instead be marked as an existing customer, be presented with a message explaining the situation, and a link to the new app)

I will convert my paid app to being a light application that has some functionality, but requires an in-app purchase of .99 to get the full functionality.  Additionally, this new app will check with my server to see if the UDID is in the existing customers database, and if so give them full functionality (without having to do the in-app purchase).

... ARGHH! :)  It's an ugly experience for the customers and a whole hell of a lot of work for the developer... but the only option provided by Apple.  (Although, I'm not sure that it will even work, as it's entirely possible that they will reject my lightweight "update" application from the store, and thereby prevent the hack upgrade path as well)

UPDATE:  Too much work for the person that I was trying to give the application to.  Ended up not proceeding with the plan.  Think that it could probably still work, and would love to hear from anyone who tries it or pulls it off :)

OwnerDisplayName: kfitzpatrick


来源: stackexchange

问:
Can't import Brain.JS into my NodeJS script
I'm trying to write a neural network using brain.js. However, NodeJS doesn't allow me to do that neither with require('brain.js') nor with import 'brain.js'.
Here is my code:

```<code>const brain = require('brain.js')

const config = {
    iterations: 15000,
    log: true,
    logPeriod: 500,
    layers: [10]
}

const net = new brain.recurrent.LSTM()

const conjunctions = {
    0: 'Именительный',
    1: 'Родительный',
    2: 'Дательный',
    3: 'Винительный',
    4: 'Творительный',
    5: 'Предложный'
}

const inputData = [
    // some data for training
]

const test = 'Дельфина'

net.train(inputData)
const output = net.run(test)
console.log(`${conjunctions[output]} падеж`)
</code>```

However, it shows me next error when running with require('brain.js'):

```<code>Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:         c:\Coding\Labs\Node.JS\MochaTest\node_modules\brain.js\src\index.js
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1156:13)
    at Module.load (internal/modules/cjs/loader.js:976:32)
    at Function.Module._load (internal/modules/cjs/loader.js:884:14)
    at Module.require (internal/modules/cjs/loader.js:1016:19)
    at require (internal/modules/cjs/helpers.js:69:18)
    at Object.<anonymous> (c:\Coding\Labs\Node.JS\MochaTest\index.js:1:15)
    at Module._compile (internal/modules/cjs/loader.js:1121:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1160:10)
    at Module.load (internal/modules/cjs/loader.js:976:32)
    at Function.Module._load (internal/modules/cjs/loader.js:884:14) {
      code: 'ERR_REQUIRE_ESM'
</code>```

}

And next error when running with import * as brain from 'brain.js':

```<code>(node:2648) ExperimentalWarning: The ESM module loader is experimental.
file:///c:/Coding/Labs/Node.JS/MochaTest/node_modules/brain.js/src/index.js:1
const activation = require('./activation');
                   ^

ReferenceError: require is not defined
    at file:///c:/Coding/Labs/Node.JS/MochaTest/node_modules/brain.js/src/index.js:1:20
    at ModuleJob.run (internal/modules/esm/module_job.js:109:37)
    at async Loader.import (internal/modules/esm/loader.js:133:24)
</code>```

What should I do and how to import it right when using NodeJS 13.2.0? I have only brain.js and Mocha installed in this module.

答:
enter image description here

just remove "type":"module" in the package.json

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a neural network using brain.js. However, NodeJS doesn't allow me to do that neither with require('brain.js') nor with import 'brain.js'.
Here is my code:

const brain = require('brain.js')

const config = {
    iterations: 15000,
    log: true,
    logPeriod: 500,
    layers: [10]
}

const net = new brain.recurrent.LSTM()

const conjunctions = {
    0: 'Именительный',
    1: 'Родительный',
    2: 'Дательный',
    3: 'Винительный',
    4: 'Творительный',
    5: 'Предложный'
}

const inputData = [
    // some data for training
]

const test = 'Дельфина'

net.train(inputData)
const output = net.run(test)
console.log(`${conjunctions[output]} падеж`)

However, it shows me next error when running with require('brain.js'):

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:         c:\Coding\Labs\Node.JS\MochaTest\node_modules\brain.js\src\index.js
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1156:13)
    at Module.load (internal/modules/cjs/loader.js:976:32)
    at Function.Module._load (internal/modules/cjs/loader.js:884:14)
    at Module.require (internal/modules/cjs/loader.js:1016:19)
    at require (internal/modules/cjs/helpers.js:69:18)
    at Object.<anonymous> (c:\Coding\Labs\Node.JS\MochaTest\index.js:1:15)
    at Module._compile (internal/modules/cjs/loader.js:1121:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1160:10)
    at Module.load (internal/modules/cjs/loader.js:976:32)
    at Function.Module._load (internal/modules/cjs/loader.js:884:14) {
      code: 'ERR_REQUIRE_ESM'

}

And next error when running with import * as brain from 'brain.js':

(node:2648) ExperimentalWarning: The ESM module loader is experimental.
file:///c:/Coding/Labs/Node.JS/MochaTest/node_modules/brain.js/src/index.js:1
const activation = require('./activation');
                   ^

ReferenceError: require is not defined
    at file:///c:/Coding/Labs/Node.JS/MochaTest/node_modules/brain.js/src/index.js:1:20
    at ModuleJob.run (internal/modules/esm/module_job.js:109:37)
    at async Loader.import (internal/modules/esm/loader.js:133:24)

What should I do and how to import it right when using NodeJS 13.2.0? I have only brain.js and Mocha installed in this module.


问:
How to skip the first row of data in SQL Query?
I have this code:

select DOLFUT from [DATABASE $]

How do I get it to get data from the 2nd line? (skip only the first line of data and collect all the rest)

答:
In Access, which you seem to use, you can use:

Select DOLFUT
From [DATABASE $]
Where DOLFUT Not In
    (Select Top 1 T.DOLFUT
    From [DATABASE $] As T
    Order By 1)
```


问:
jquery or js select the first class of an element
I have 3 anchors with 3 divs
The anchors are like that:

```<code><a class="home sharedClass">home</a>

<a class="about sharedClass">about</a>

<a class="contact sharedClass">contact</a>
</code>```

When I click one of them I get the contents of the corresponding div which its id is the same as the first class (home, about or contact)

I have a little jQuery code that has to select the right class But the result is an alert telling the name of theClass:

```<code>$('a.sharedClass').click(function(){

    var theClass = $(this).attr('class[0]');

    alert(theClass)

});
</code>```

The problem is that this function returns "undefined". How to fix this?

Thanks.

答:
The class attribute is not an array. It is a string, as are all attributes. Further, the attr function will be looking for an attribute on the element named class[0] which it will not find.

```<code>$('a.sharedClass').click(function(){
  var theClass = $(this).attr('class'),
      firstClass = (theClass || '').split(' ')[0]; // handle if no class attribute
    alert(firstClass);
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have 3 anchors with 3 divs
The anchors are like that:

home

about

contact

When I click one of them I get the contents of the corresponding div which its id is the same as the first class (home, about or contact)

I have a little jQuery code that has to select the right class But the result is an alert telling the name of theClass:

$('a.sharedClass').click(function(){

    var theClass = $(this).attr('class[0]');

    alert(theClass)

});

The problem is that this function returns "undefined". How to fix this?

Thanks.

Body:
The class attribute is not an array. It is a string, as are all attributes. Further, the attr function will be looking for an attribute on the element named class[0] which it will not find.

$('a.sharedClass').click(function(){
  var theClass = $(this).attr('class'),
      firstClass = (theClass || '').split(' ')[0]; // handle if no class attribute
    alert(firstClass);
});


问:
Conflict of libnfsidmap files while running 'dnf update' on Fedora 30
I run sudo dnf update on my Fedora 30 and after downloading packages I got this error:

```<code>    [DRPM] hplip-common-3.19.12-1.fc30_3.19.12-2.fc30.x86_64.drpm: done
--------------------------------------------------------------------------------
Total                                           677 kB/s | 1.0 GB     26:51
Delta RPMs reduced 1066.4 MB of updates to 1066.3 MB (0.1% saved)
Running transaction check
Transaction check succeeded.
Running transaction test
The downloaded packages were saved in cache until the next successful transaction.
You can remove cached packages by executing 'dnf clean packages'.
Error: Transaction check error:
  file /usr/share/man/man5/idmapd.conf.5.gz from install of nfs-utils-1:2.4.2-3.rc3.fc30.x86_64 conflicts with file from package libnfsidmap-1:2.3.3-7.rc2.fc30.x86_64

Error Summary
-------------
</code>```

Please, tell me, how can I fix this problem?

答: I haven't found a better solution than to exclude nfs-utils packages from upgrade as described here. That works for me.

Body:
I run sudo dnf update on my Fedora 30 and after downloading packages I got this error:

    [DRPM] hplip-common-3.19.12-1.fc30_3.19.12-2.fc30.x86_64.drpm: done
--------------------------------------------------------------------------------
Total                                           677 kB/s | 1.0 GB     26:51
Delta RPMs reduced 1066.4 MB of updates to 1066.3 MB (0.1% saved)
Running transaction check
Transaction check succeeded.
Running transaction test
The downloaded packages were saved in cache until the next successful transaction.
You can remove cached packages by executing 'dnf clean packages'.
Error: Transaction check error:
  file /usr/share/man/man5/idmapd.conf.5.gz from install of nfs-utils-1:2.4.2-3.rc3.fc30.x86_64 conflicts with file from package libnfsidmap-1:2.3.3-7.rc2.fc30.x86_64

Error Summary
-------------

Please, tell me, how can I fix this problem?


问:
Firebase ML kit give FirebaseMLException: Waiting for the text recognition model to be downloaded. Please wait
I'm use firebase ml kit for text recognition but give this exception on emulator and real device.

```<code>W/System.err: com.google.firebase.ml.common.FirebaseMLException: Waiting for the text recognition model to be downloaded. Please wait.
    at com.google.android.gms.internal.firebase_ml.zzjz.zzc(Unknown Source)
    at com.google.android.gms.internal.firebase_ml.zzjz.zza(Unknown Source)
    at com.google.android.gms.internal.firebase_ml.zzic.call(Unknown Source)
    at com.google.android.gms.internal.firebase_ml.zzhx.zza(Unknown Source)
    at com.google.android.gms.internal.firebase_ml.zzhy.run(Unknown Source)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at com.google.android.gms.internal.firebase_ml.zze.dispatchMessage(Unknown Source)
    at android.os.Looper.loop(Looper.java:136)
    at android.os.HandlerThread.run(HandlerThread.java:61)
</code>```

Here my code

```<code>private fun MlProcessText(imageUri:Uri) {
    val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
    val textVision = FirebaseVisionImage.fromBitmap(bitmap)
    val detector = FirebaseVision.getInstance().onDeviceTextRecognizer

    detector.processImage(textVision).addOnSuccessListener { it ->
        val blocks = it.textBlocks
        if (blocks.size == 0 ){

            tvVision.text = "NO TEXT"
        }else{
            blocks.forEach {
                tvVision.append(" ${it.text}")
            }
        }

    }.addOnFailureListener {
        it.printStackTrace() // this is the exception log
        tvVision.text = it.message
    }
}
</code>```

Also i tried :

1- Settings->Apps->Google Play Services->Storage->Manage Space->Clear All Data

2- Low storage check (At least 1Gig free)

And add meta-data

```<code> <meta-data
        android:name="com.google.firebase.ml.vision.DEPENDENCIES"
        android:value="ocr,text" />
</code>```

But still the same error!

UPDATE

After getting stuck for several days i try to use Google Mobile Vision

So i add this to my dependencies

```<code>implementation 'com.google.android.gms:play-services-vision:17.0.2'
</code>```

And use this article for OCR  and in this code

```<code>    //Create the TextRecognizer
    final TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();

    if (!textRecognizer.isOperational()) {
        Log.w(TAG, "Detector dependencies not loaded yet");
    } else {

        //Initialize camerasource to use high resolution and set Autofocus on.
        mCameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
                .setFacing(CameraSource.CAMERA_FACING_BACK)
                .setRequestedPreviewSize(1280, 1024)
                .setAutoFocusEnabled(true)
                .setRequestedFps(2.0f)
                .build();
     }
</code>```

textRecognizer.isOperational() return always false. that mean it does not work too . I think there is something common with this two problem.

So i am steel stuck on text recognizer for android !

Test on : Nox emulator , google Nexus 5X API 26 emulator and on Huawei p10  and Samsung Galaxy S7 real device.

is there any idea to solve this problem?

答:
I've noticed that sometimes the problem is the slow internet connection and just need more time the model to be downloaded.
To minimize the bad user experience I've added this warm up method and call it as soon as the app starts, so when the actual recognition occurs the model to be already downloaded.

/**
 * We call that on startup with hope the needed model will be downloaded as soon as possible;
 * It is used to prevent: "Waiting for the text recognition model to be downloaded. Please wait."
 * exception when recognizing.
 */
public static void warmUp() {
    Bitmap image = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
    image.eraseColor(android.graphics.Color.GREEN);
    FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(image);
    FirebaseVision.getInstance().getOnDeviceTextRecognizer()
            .processImage(firebaseVisionImage)
            .addOnSuccessListener(null)
            .addOnFailureListener(null);
}
```

Body:
I'm use firebase ml kit for text recognition but give this exception on emulator and real device.

W/System.err: com.google.firebase.ml.common.FirebaseMLException: Waiting for the text recognition model to be downloaded. Please wait.
    at com.google.android.gms.internal.firebase_ml.zzjz.zzc(Unknown Source)
    at com.google.android.gms.internal.firebase_ml.zzjz.zza(Unknown Source)
    at com.google.android.gms.internal.firebase_ml.zzic.call(Unknown Source)
    at com.google.android.gms.internal.firebase_ml.zzhx.zza(Unknown Source)
    at com.google.android.gms.internal.firebase_ml.zzhy.run(Unknown Source)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at com.google.android.gms.internal.firebase_ml.zze.dispatchMessage(Unknown Source)
    at android.os.Looper.loop(Looper.java:136)
    at android.os.HandlerThread.run(HandlerThread.java:61)

Here my code

private fun MlProcessText(imageUri:Uri) {
    val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
    val textVision = FirebaseVisionImage.fromBitmap(bitmap)
    val detector = FirebaseVision.getInstance().onDeviceTextRecognizer

    detector.processImage(textVision).addOnSuccessListener { it ->
        val blocks = it.textBlocks
        if (blocks.size == 0 ){

            tvVision.text = "NO TEXT"
        }else{
            blocks.forEach {
                tvVision.append(" ${it.text}")
            }
        }

    }.addOnFailureListener {
        it.printStackTrace() // this is the exception log
        tvVision.text = it.message
    }
}

Also i tried :

1- Settings->Apps->Google Play Services->Storage->Manage Space->Clear All Data

2- Low storage check (At least 1Gig free)

And add meta-data

 <meta-data
        android:name="com.google.firebase.ml.vision.DEPENDENCIES"
        android:value="ocr,text" />

But still the same error!

UPDATE

After getting stuck for several days i try to use Google Mobile Vision

So i add this to my dependencies

implementation 'com.google.android.gms:play-services-vision:17.0.2'

And use this article for OCR  and in this code

    //Create the TextRecognizer
    final TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();

    if (!textRecognizer.isOperational()) {
        Log.w(TAG, "Detector dependencies not loaded yet");
    } else {

        //Initialize camerasource to use high resolution and set Autofocus on.
        mCameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
                .setFacing(CameraSource.CAMERA_FACING_BACK)
                .setRequestedPreviewSize(1280, 1024)
                .setAutoFocusEnabled(true)
                .setRequestedFps(2.0f)
                .build();
     }

textRecognizer.isOperational() return always false. that mean it does not work too . I think there is something common with this two problem.

So i am steel stuck on text recognizer for android !

Test on : Nox emulator , google Nexus 5X API 26 emulator and on Huawei p10  and Samsung Galaxy S7 real device.

is there any idea to solve this problem?


问:
Why do I need a 'return' and a new variable?
I am a newbie in Python programming and I would like to understand better the logic of programming. The code below is intended to create a function that assigns its parameters to a dictionary, prompt the user about an artist and a title name, call the function back passing the arguments (given by the user) to the parameters and print the function (the dictionary).

```<code>def make_album(artist, album_name):
    entry = {'name' : artist, 'album' : album_name}
    return entry

while True:
    print("\nPlease, write your fav artist and title: ")
    print("\nType 'q' to quit.")
    band_name = input('Artist name: ')
    if band_name == 'q':
        break
    title_name = input('Title name: ')
    if title_name == 'q':
        break

comp_entry = make_album(band_name, title_name)
print(comp_entry)
</code>```

The code runs perfectly. But there are two points that I can not understand:

Why do I need the 'return entry' line? The function creates a dictionary and it is done. Why a return?

Why do I need to create a variable in the end, assign the result of the function and print it? There is already a variable (entry) addressed as the dictionary! I would like to just write instead:

```<code>make_album(band_name, title_name):
    print(entry)
</code>```

I know, the code will not run, but I would be very happy with some words explaining me the reason of why these 2 points.

答: What you have to understand is the concept of scope in python. This article is a good place to start.</p>

Body:
I am a newbie in Python programming and I would like to understand better the logic of programming. The code below is intended to create a function that assigns its parameters to a dictionary, prompt the user about an artist and a title name, call the function back passing the arguments (given by the user) to the parameters and print the function (the dictionary).

def make_album(artist, album_name):
    entry = {'name' : artist, 'album' : album_name}
    return entry

while True:
    print("\nPlease, write your fav artist and title: ")
    print("\nType 'q' to quit.")
    band_name = input('Artist name: ')
    if band_name == 'q':
        break
    title_name = input('Title name: ')
    if title_name == 'q':
        break

comp_entry = make_album(band_name, title_name)
print(comp_entry)

The code runs perfectly. But there are two points that I can not understand:

Why do I need the 'return entry' line? The function creates a dictionary and it is done. Why a return?

Why do I need to create a variable in the end, assign the result of the function and print it? There is already a variable (entry) addressed as the dictionary! I would like to just write instead:

make_album(band_name, title_name):
    print(entry)

I know, the code will not run, but I would be very happy with some words explaining me the reason of why these 2 points.


问:
Align image position of button by CSS
I have a Button with a background-image and a text that is more than the width of the image.
How to place the image in the middle of the text

<!DOCTYPE html>

<button class="button">Button text test</button>

```

Button image

答:
The final solution is determine the actual width of the image and to specify the width of the button for the text

.button2 {
  background-color: transparent;
  background-image: url('http://127.0.0.1:25005/pics/item/c1763.png');
  background-size: 60px  60px;
  background-repeat: no-repeat;
  border: none;
  font-size: 16px;
  height: 60px;
  width: 150px;
  text-align: center;
  padding-top: 60px;
  white-space:nowrap;
  background-position: center top;
}```

Title: Align image position of button by CSS

Body:
I have a Button with a background-image and a text that is more than the width of the image.
How to place the image in the middle of the text

<!DOCTYPE html>

<button class="button">Button text test</button>

Button image


答:
That's because the attribute class is just a string. When you get it, you will get all classes in that one string value.
If you want to get items, you can explode it to an array and then access item 0.

```<code>theClass = $(this).attr('class').split(' ', 1)[0];
</code>```

In more modern browsers (about all relevant browsers actually), you can use the classList property of an element to get the list of classes and add to it. I'm not sure if that will return the classes in a particular order, though. I think in implementation it's more a 'bag' than a 'list, because you can check if a class is in it, but not get or modify, say, the first item.

In the end, that's the safest way to use classes anyway. After all, you'd want to check if an element has a class, not if it's the first class per se.

Title: jquery or js select the first class of an element

Body:
That's because the attribute class is just a string. When you get it, you will get all classes in that one string value.
If you want to get items, you can explode it to an array and then access item 0.

theClass = $(this).attr('class').split(' ', 1)[0];

In more modern browsers (about all relevant browsers actually), you can use the classList property of an element to get the list of classes and add to it. I'm not sure if that will return the classes in a particular order, though. I think in implementation it's more a 'bag' than a 'list, because you can check if a class is in it, but not get or modify, say, the first item.

In the end, that's the safest way to use classes anyway. After all, you'd want to check if an element has a class, not if it's the first class per se.


问:
ValueError: could not convert string to float: sklearn
Recently I was working with a dataset in python and got an unexpected error. the error was: ValueError: could not convert string to float. Actually in the dataset there were text data also which I converted into integer with LabelEncoder. But when I am going in the training part where I fit the model, I'm getting this error which makes no sense.

code:

```<code>import sklearn
from sklearn import model_selection
from sklearn import linear_model
from sklearn import preprocessing
import pandas as pd
import pickle
import numpy as np
data = pd.read_csv("house_train.csv")
data = data.fillna(value=0)
dataX_train = data.drop(["SalePrice"], axis = 1)
dataX_test = data.SalePrice

le = preprocessing.LabelEncoder()

dataX_train.MSZoning = le.fit_transform(list(data["MSZoning"]))
dataX_train.Street = le.fit_transform(list(data["Street"]))
dataX_train.Alley = le.fit_transform(list(data["Alley"]))
dataX_train.LotShape = le.fit_transform(list(data["LotShape"]))
dataX_train.LandContour = le.fit_transform(list(data["LandContour"]))
dataX_train.Utilities = le.fit_transform(list(data["Utilities"]))
dataX_train.LotConfig = le.fit_transform(list(data["LotConfig"]))
dataX_train.LandSlope = le.fit_transform(list(data["LandSlope"]))
dataX_train.Neighborhood = le.fit_transform(list(data["Neighborhood"]))
dataX_train.Condition1 = le.fit_transform(list(data["Condition1"]))
dataX_train.Condition2 = le.fit_transform(list(data["Condition2"]))
dataX_train.BldgType = le.fit_transform(list(data["BldgType"]))
dataX_train.HouseStyle = le.fit_transform(list(data["HouseStyle"]))
dataX_train.RoofStyle = le.fit_transform(list(data["RoofStyle"]))
dataX_train.RoofMatl = le.fit_transform(list(data["RoofMatl"]))
dataX_train.Exterior1st = le.fit_transform(list(data["Exterior1st"]))
dataX_train.Exterior2nd = le.fit_transform(list(data["Exterior2nd"]))
dataX_train.MasVnrType = le.fit_transform(list(data["MasVnrType"]))
dataX_train.ExterQual = le.fit_transform(list(data["ExterQual"]))
dataX_train.ExterCond = le.fit_transform(list(data["ExterCond"]))
dataX_train.Foundation = le.fit_transform(list(data["Foundation"]))
dataX_train.BsmtQual = le.fit_transform(list(data["BsmtQual"]))
dataX_train.BsmtExposure = le.fit_transform(list(data["BsmtExposure"]))
dataX_train.BsmtFinType1 = le.fit_transform(list(data["BsmtFinType1"]))
dataX_train.BsmtFinType2 = le.fit_transform(list(data["BsmtFinType2"]))
dataX_train.Heating = le.fit_transform(list(data["Heating"]))
dataX_train.HeatingQC = le.fit_transform(list(data["HeatingQC"]))
dataX_train.CentralAir = le.fit_transform(list(data["CentralAir"]))
dataX_train.Electrical = le.fit_transform(list(data["Electrical"]))
dataX_train.KitchenQual = le.fit_transform(list(data["KitchenQual"]))
dataX_train.Functional = le.fit_transform(list(data["Functional"]))
dataX_train.FireplaceQu = le.fit_transform(list(data["FireplaceQu"]))
dataX_train.GarageType = le.fit_transform(list(data["GarageType"]))
dataX_train.GarageFinish = le.fit_transform(list(data["GarageFinish"]))
dataX_train.GarageQual = le.fit_transform(list(data["GarageQual"]))
dataX_train.GarageCond = le.fit_transform(list(data["GarageCond"]))
dataX_train.PavedDrive = le.fit_transform(list(data["PavedDrive"]))
dataX_train.PoolQC = le.fit_transform(list(data["PoolQC"]))
dataX_train.Fence = le.fit_transform(list(data["Fence"]))
dataX_train.MiscFeature = le.fit_transform(list(data["MiscFeature"]))
dataX_train.SaleType = le.fit_transform(list(data["SaleType"]))
dataX_train.SaleCondition = le.fit_transform(list(data["SaleCondition"]))

best = 0

x_train, x_test, y_train, y_test = model_selection.train_test_split(dataX_train, dataX_test,
test_size = 0.2)
clf = linear_model.LinearRegression()
clf.fit(x_train, y_train)
acc = clf.score(x_test, y_test)
if acc > best:
   best = acc
   with open("housingmodel.pickle", "wb") as f:
      pickle.dump(clf , f)
print(acc)
</code>```

答:
first of all check out if you encoded all of your features in dataX_train, I think you missed something there.

try: dataX_train.dtypes and check if there is any of non-numeric values and then use to_numeric on a non numeric columns. For example

```<code>dataX_train['NonNumericCol'] = dataX_train['NonNumericCol'].apply(pd.to_numeric)
</code>```

Body:
Recently I was working with a dataset in python and got an unexpected error. the error was: ValueError: could not convert string to float. Actually in the dataset there were text data also which I converted into integer with LabelEncoder. But when I am going in the training part where I fit the model, I'm getting this error which makes no sense.

code:

import sklearn
from sklearn import model_selection
from sklearn import linear_model
from sklearn import preprocessing
import pandas as pd
import pickle
import numpy as np
data = pd.read_csv("house_train.csv")
data = data.fillna(value=0)
dataX_train = data.drop(["SalePrice"], axis = 1)
dataX_test = data.SalePrice

le = preprocessing.LabelEncoder()

dataX_train.MSZoning = le.fit_transform(list(data["MSZoning"]))
dataX_train.Street = le.fit_transform(list(data["Street"]))
dataX_train.Alley = le.fit_transform(list(data["Alley"]))
dataX_train.LotShape = le.fit_transform(list(data["LotShape"]))
dataX_train.LandContour = le.fit_transform(list(data["LandContour"]))
dataX_train.Utilities = le.fit_transform(list(data["Utilities"]))
dataX_train.LotConfig = le.fit_transform(list(data["LotConfig"]))
dataX_train.LandSlope = le.fit_transform(list(data["LandSlope"]))
dataX_train.Neighborhood = le.fit_transform(list(data["Neighborhood"]))
dataX_train.Condition1 = le.fit_transform(list(data["Condition1"]))
dataX_train.Condition2 = le.fit_transform(list(data["Condition2"]))
dataX_train.BldgType = le.fit_transform(list(data["BldgType"]))
dataX_train.HouseStyle = le.fit_transform(list(data["HouseStyle"]))
dataX_train.RoofStyle = le.fit_transform(list(data["RoofStyle"]))
dataX_train.RoofMatl = le.fit_transform(list(data["RoofMatl"]))
dataX_train.Exterior1st = le.fit_transform(list(data["Exterior1st"]))
dataX_train.Exterior2nd = le.fit_transform(list(data["Exterior2nd"]))
dataX_train.MasVnrType = le.fit_transform(list(data["MasVnrType"]))
dataX_train.ExterQual = le.fit_transform(list(data["ExterQual"]))
dataX_train.ExterCond = le.fit_transform(list(data["ExterCond"]))
dataX_train.Foundation = le.fit_transform(list(data["Foundation"]))
dataX_train.BsmtQual = le.fit_transform(list(data["BsmtQual"]))
dataX_train.BsmtExposure = le.fit_transform(list(data["BsmtExposure"]))
dataX_train.BsmtFinType1 = le.fit_transform(list(data["BsmtFinType1"]))
dataX_train.BsmtFinType2 = le.fit_transform(list(data["BsmtFinType2"]))
dataX_train.Heating = le.fit_transform(list(data["Heating"]))
dataX_train.HeatingQC = le.fit_transform(list(data["HeatingQC"]))
dataX_train.CentralAir = le.fit_transform(list(data["CentralAir"]))
dataX_train.Electrical = le.fit_transform(list(data["Electrical"]))
dataX_train.KitchenQual = le.fit_transform(list(data["KitchenQual"]))
dataX_train.Functional = le.fit_transform(list(data["Functional"]))
dataX_train.FireplaceQu = le.fit_transform(list(data["FireplaceQu"]))
dataX_train.GarageType = le.fit_transform(list(data["GarageType"]))
dataX_train.GarageFinish = le.fit_transform(list(data["GarageFinish"]))
dataX_train.GarageQual = le.fit_transform(list(data["GarageQual"]))
dataX_train.GarageCond = le.fit_transform(list(data["GarageCond"]))
dataX_train.PavedDrive = le.fit_transform(list(data["PavedDrive"]))
dataX_train.PoolQC = le.fit_transform(list(data["PoolQC"]))
dataX_train.Fence = le.fit_transform(list(data["Fence"]))
dataX_train.MiscFeature = le.fit_transform(list(data["MiscFeature"]))
dataX_train.SaleType = le.fit_transform(list(data["SaleType"]))
dataX_train.SaleCondition = le.fit_transform(list(data["SaleCondition"]))

best = 0

x_train, x_test, y_train, y_test = model_selection.train_test_split(dataX_train, dataX_test,
test_size = 0.2)
clf = linear_model.LinearRegression()
clf.fit(x_train, y_train)
acc = clf.score(x_test, y_test)
if acc > best:
   best = acc
   with open("housingmodel.pickle", "wb") as f:
      pickle.dump(clf , f)
print(acc)

Body:
first of all check out if you encoded all of your features in dataX_train, I think you missed something there.

try: dataX_train.dtypes and check if there is any of non-numeric values and then use to_numeric on a non numeric columns. For example

dataX_train['NonNumericCol'] = dataX_train['NonNumericCol'].apply(pd.to_numeric)


问:
How to parse a complicated nested JSON string in C#?
I have an ugly JSON string that is getting returned from an API that looks like this (this is the result of Console.Write on the string):

```<code>{"d":"\"\\\"\\\\\\\"[{\\\\\\\\\\\\\\\"foo\\\\\\\\\\\\\\\":15,\\\\\\\\\\\\\\\"bar\\\\\\\\\\\\\\\":null}]\\\\\\\"\\\"\\n\""}
</code>```

I am trying to parse this into a C# object in the simplest way possible, so I can access properties like foo and bar. But I am having a difficult time doing this.

I have tried parsing it a number of ways, including:

```<code>// code to get the response string
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var serializedData = "{data: 'data'}";
var responseString = client.UploadString(url, "POST", serializedData);

// parse the response string
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
</code>```

This allows me to access the value of d, which is the actual string I need to parse. I then tried to parse that separately using JArray.Parse(obj["d"]), but I get an error saying that obj["d"] is not an array.

Unfortunately, I have no access to the API itself so can't modify how it's serializing the data it's returning.

Any suggestions?

答:
Replacing escape characters in fine however I would not rely on the console.write command as the definitive output to examine. Here are a couple of other ways: -

Use Postman to make the API call so you can see the raw result. This will (hopefully) show it in an easy to read format that you can then define your class to deserialise to.

Write the raw response to a “.json” file. Open that file in a good editor (such as VS Code or VS itself) to see how the data is actually structured when it is received.

On a side note I would recommend using RestSharp to do the REST calls and Newtonsoft.Json to do the serialising/deserialising.

Body:
I have an ugly JSON string that is getting returned from an API that looks like this (this is the result of Console.Write on the string):

{"d":"\"\\\"\\\\\\\"[{\\\\\\\\\\\\\\\"foo\\\\\\\\\\\\\\\":15,\\\\\\\\\\\\\\\"bar\\\\\\\\\\\\\\\":null}]\\\\\\\"\\\"\\n\""}

I am trying to parse this into a C# object in the simplest way possible, so I can access properties like foo and bar. But I am having a difficult time doing this.

I have tried parsing it a number of ways, including:

// code to get the response string
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var serializedData = "{data: 'data'}";
var responseString = client.UploadString(url, "POST", serializedData);

// parse the response string
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);

This allows me to access the value of d, which is the actual string I need to parse. I then tried to parse that separately using JArray.Parse(obj["d"]), but I get an error saying that obj["d"] is not an array.

Unfortunately, I have no access to the API itself so can't modify how it's serializing the data it's returning.

Any suggestions?


问:
How to fix member Event from @ionic/angular error in Ionic 5
I have upgraded from Ionic 4 to Ionic 5, now getting following error:

ERROR in src/app/app.component.ts(4,10): error TS2305: Module '"/node_modules/@ionic/angular/ionic-angular"' has no exported member 'Events'.

Following import line is causing the issue:

```<code>import { Events, Platform } from '@ionic/angular';
</code>```

How can I fix member Event from @ionic/angular error in Ionic 5?

答:
Events from @ionic/angular package got removed from Ionic 5. You can see the breaking changes in Ionic5 here.

As it's mentioned in the breaking changes, you should use Observables.

For example, you can create the following service:

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class GlobalFooService {

    private fooSubject = new Subject<any>();

    publishSomeData(data: any) {
        this.fooSubject.next(data);
    }

    getObservable(): Subject<any> {
        return this.fooSubject;
    }
}
```

<p>Now, you can subscribe in any component like <code>app.component.ts</code>:</p>

<pre class="lang-js prettyprint-override"><code>@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.scss']
})
export class AppComponent {

    constructor(private globalFooService: GlobalFooService) {
        this.initializeApp();
    }

    initializeApp() {
        // other code

        this.globalFooService.getObservable().subscribe((data) => {
            console.log('Data received', data);
        });
    }
}
</code>```

Now, you just have to emit the event from some other component:

@Component({
    selector: 'app-home',
    templateUrl: 'home.page.html',
    styleUrls: ['home.page.scss']
})
export class HomePage {

    constructor(private globalFooService: GlobalFooService) {
    }

    onSomeButtonClick() {
        this.globalFooService.publishSomeData({
            foo: 'bar'
        });
    }
}
```

This is a very simple solution/example or alternative of the Events but you can tweak your code further to make it a namespaced event with a topic.

I have written a blog on this which can give you a full-featured solution so that with very less code change, you can upgrade your app.

https://medium.com/wizpanda/dealing-with-breaking-change-in-ionic-5-db3ba711dfcd

Body:
I have upgraded from Ionic 4 to Ionic 5, now getting following error:

ERROR in src/app/app.component.ts(4,10): error TS2305: Module '"/node_modules/@ionic/angular/ionic-angular"' has no exported member 'Events'.

Following import line is causing the issue:

import { Events, Platform } from '@ionic/angular';

How can I fix member Event from @ionic/angular error in Ionic 5?

Body:
Events from @ionic/angular package got removed from Ionic 5. You can see the breaking changes in Ionic5 here.

As it's mentioned in the breaking changes, you should use Observables.

For example, you can create the following service:

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class GlobalFooService {

    private fooSubject = new Subject<any>();

    publishSomeData(data: any) {
        this.fooSubject.next(data);
    }

    getObservable(): Subject<any> {
        return this.fooSubject;
    }
}

Now, you can subscribe in any component like app.component.ts:

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

    constructor(private globalFooService: GlobalFooService) {
        this.initializeApp();
    }

    initializeApp() {
        // other code

        this.globalFooService.getObservable().subscribe((data) => {
            console.log('Data received', data);
        });
    }
}

Now, you just have to emit the event from some other component:

@Component({
    selector: 'app-home',
    templateUrl: 'home.page.html',
    styleUrls: ['home.page.scss']
})
export class HomePage {

    constructor(private globalFooService: GlobalFooService) {
    }

    onSomeButtonClick() {
        this.globalFooService.publishSomeData({
            foo: 'bar'
        });
    }
}

This is a very simple solution/example or alternative of the Events but you can tweak your code further to make it a namespaced event with a topic.

I have written a blog on this which can give you a full-featured solution so that with very less code change, you can upgrade your app.

https://medium.com/wizpanda/dealing-with-breaking-change-in-ionic-5-db3ba711dfcd


问:
How can I request parameters in api gateway using cloudformation in aws and pass it down to lambda function?
I am trying to request parameters using API Gateway in AWS CloudFormation. The parameter that I want to pass down from API gateway to Lambda function is 'action'. I have tried the following code and so far I ran into the error, mention below. Can someone please help me with identifying the issue and a possible resolution?</p>

<p>"Invalid mapping expression specified: Validation Result: warnings : [], errors : [Invalid mapping expression specified: Integration.request.path.action] (Service: AmazonApiGateway; Status Code: 400; Error Code: BadRequestException; Request ID: 037f4753-52b5-4276-979a-131a0f903e63)" </p>

```<code>AWSTemplateFormatVersion: "2010-09-09"
Description: "API Gateway and Lambda function"

Resources:
  SampleApi:
    Type: "AWS::ApiGateway::RestApi"
    Properties:
      Name: Sample

  SampleApiMethod:
    Type: "AWS::ApiGateway::Method"
    Properties:
      AuthorizationType: "NONE"
      HttpMethod: "GET"
      RequestParameters:
        method.request.path.action: true
      RequestTemplates:
        application/yaml
      Integration:
        IntegrationHttpMethod: "POST"
        Type: "AWS_PROXY"
        RequestParameters:
          Integration.request.path.action: method.request.path.action
        Uri: !Sub
          - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
          - lambdaArn: !GetAtt "SampleLambda.Arn"
        CacheKeyParameters:
          - method.request.path.action
      ResourceId: !GetAtt "SampleApi.RootResourceId"
      RestApiId: !Ref "SampleApi"

  SampleApiDeployment:
    Type: "AWS::ApiGateway::Deployment"
    DependsOn: "SampleApiMethod"
    Properties:
      RestApiId: !Ref "SampleApi"
      StageName: test

  SampleLambda:
    Type: "AWS::Lambda::Function"
    Properties:
      Code:
        ZipFile: |
            import yaml
            import boto3
            cf_client = boto3.client('cloudformation')
            cf_client.create_stack(
                StackName='your-stack',
                TemplateURL='Some URL',
                Parameters=[
                    {
                        'ParameterKey':'action',
                        'ParameterValue': 'kms:*'
                    },
                ]
            )
      Handler: "index.handler"
      Role: !GetAtt "SampleLambdaRole.Arn"
      Runtime: python3.7

  LambdaApiGatewayInvoke:
    Type: "AWS::Lambda::Permission"
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt "SampleLambda.Arn"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${SampleApi}/*/GET/"

  SampleLambdaRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Action: ["sts:AssumeRole"]
            Effect: "Allow"
            Principal:
              Service: ["lambda.amazonaws.com"]
      Policies:
        - PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action: ["cloudwatch:*", "logs:*"]
                Effect: "Allow"
                Resource: "*"
          PolicyName: "lambdaLogPolicy"
Outputs:
  apiGatewayInvokeURL:
    Value: !Sub 'https://Sample.execute-api.${AWS::Region}.amazonaws.com/test'
</code>```

答:
According to the docs, the key for RequestParameters should be like integration.request.<location>.<name>, with a lowercase i for integration. You are using an uppercase I. From the AWS CloudFormation docs:

Specify the destination by using the following pattern integration.request.location.name, where location is query string, path, or header, and name is a valid, unique parameter name.

Also, your template from above contains a RequestTemplates property which is placed in the wrong hierarchy level. It must be placed below Integration as noted in the AWS CloudFormation docs as well. Here is the correct template for AWS::ApiGateway::Method for you:

```<code>SampleApiMethod:
  Type: "AWS::ApiGateway::Method"
  Properties:
    AuthorizationType: "NONE"
    HttpMethod: "GET"
    RequestParameters:
      method.request.path.action: true
    Integration:
      IntegrationHttpMethod: "POST"
      Type: "AWS_PROXY"
      RequestParameters:
        integration.request.path.action: method.request.path.action
      RequestTemplates:
        "application/yaml": "<define your template here>"
      Uri: !Sub
        - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
        - lambdaArn: !GetAtt "SampleLambda.Arn"
      CacheKeyParameters:
        - method.request.path.action
    ResourceId: !GetAtt "SampleApi.RootResourceId"
    RestApiId: !Ref "SampleApi"
</code>```

More information about defining a request template can be found in the developer reference.

Body:
I am trying to request parameters using API Gateway in AWS CloudFormation. The parameter that I want to pass down from API gateway to Lambda function is 'action'. I have tried the following code and so far I ran into the error, mention below. Can someone please help me with identifying the issue and a possible resolution?

"Invalid mapping expression specified: Validation Result: warnings : [], errors : [Invalid mapping expression specified: Integration.request.path.action] (Service: AmazonApiGateway; Status Code: 400; Error Code: BadRequestException; Request ID: 037f4753-52b5-4276-979a-131a0f903e63)"

AWSTemplateFormatVersion: "2010-09-09"
Description: "API Gateway and Lambda function"

Resources:
  SampleApi:
    Type: "AWS::ApiGateway::RestApi"
    Properties:
      Name: Sample

  SampleApiMethod:
    Type: "AWS::ApiGateway::Method"
    Properties:
      AuthorizationType: "NONE"
      HttpMethod: "GET"
      RequestParameters:
        method.request.path.action: true
      RequestTemplates:
        application/yaml
      Integration:
        IntegrationHttpMethod: "POST"
        Type: "AWS_PROXY"
        RequestParameters:
          Integration.request.path.action: method.request.path.action
        Uri: !Sub
          - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
          - lambdaArn: !GetAtt "SampleLambda.Arn"
        CacheKeyParameters:
          - method.request.path.action
      ResourceId: !GetAtt "SampleApi.RootResourceId"
      RestApiId: !Ref "SampleApi"

  SampleApiDeployment:
    Type: "AWS::ApiGateway::Deployment"
    DependsOn: "SampleApiMethod"
    Properties:
      RestApiId: !Ref "SampleApi"
      StageName: test

  SampleLambda:
    Type: "AWS::Lambda::Function"
    Properties:
      Code:
        ZipFile: |
            import yaml
            import boto3
            cf_client = boto3.client('cloudformation')
            cf_client.create_stack(
                StackName='your-stack',
                TemplateURL='Some URL',
                Parameters=[
                    {
                        'ParameterKey':'action',
                        'ParameterValue': 'kms:*'
                    },
                ]
            )
      Handler: "index.handler"
      Role: !GetAtt "SampleLambdaRole.Arn"
      Runtime: python3.7

  LambdaApiGatewayInvoke:
    Type: "AWS::Lambda::Permission"
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt "SampleLambda.Arn"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${SampleApi}/*/GET/"

  SampleLambdaRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Action: ["sts:AssumeRole"]
            Effect: "Allow"
            Principal:
              Service: ["lambda.amazonaws.com"]
      Policies:
        - PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action: ["cloudwatch:*", "logs:*"]
                Effect: "Allow"
                Resource: "*"
          PolicyName: "lambdaLogPolicy"
Outputs:
  apiGatewayInvokeURL:
    Value: !Sub 'https://Sample.execute-api.${AWS::Region}.amazonaws.com/test'

Body:
According to the docs, the key for RequestParameters should be like integration.request.<location>.<name>, with a lowercase i for integration. You are using an uppercase I. From the AWS CloudFormation docs:

Specify the destination by using the following pattern integration.request.location.name, where location is query string, path, or header, and name is a valid, unique parameter name.

Also, your template from above contains a RequestTemplates property which is placed in the wrong hierarchy level. It must be placed below Integration as noted in the AWS CloudFormation docs as well. Here is the correct template for AWS::ApiGateway::Method for you:

SampleApiMethod:
  Type: "AWS::ApiGateway::Method"
  Properties:
    AuthorizationType: "NONE"
    HttpMethod: "GET"
    RequestParameters:
      method.request.path.action: true
    Integration:
      IntegrationHttpMethod: "POST"
      Type: "AWS_PROXY"
      RequestParameters:
        integration.request.path.action: method.request.path.action
      RequestTemplates:
        "application/yaml": "<define your template here>"
      Uri: !Sub
        - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
        - lambdaArn: !GetAtt "SampleLambda.Arn"
      CacheKeyParameters:
        - method.request.path.action
    ResourceId: !GetAtt "SampleApi.RootResourceId"
    RestApiId: !Ref "SampleApi"

More information about defining a request template can be found in the developer reference.


问:
Django Application running on Ubuntu VPS: This site can’t be reached
I am running an ubuntu 16.04 cloud VPS server. I've set up a venv and activated it, and installed django.
I run the server with

```<code>python3 manage.py runserver 0.0.0.0:8000
</code>```

I am trying to access this application from a remote computer (not inside the same LAN); I'm trying to make the application visible to the world outside the VPS and VPLAN. When I try to access the site in my home computer broswer like: xx.xx.xxx.xxx:8000 I get the error:

This site can’t be reached. http://xx.xx.xxx.xxx:8000/ is unreachable.

Now I've tried a traceroute and it seems to reach the server ok. I also did

```<code>sudo ufw enable
sudo ufw 8000 allow
sudo iptables -S | grep 8000 (and see the proper entries)
</code>```

In the settings file I have:

```<code>ALLOWED_HOSTS = ["*", "0.0.0.0", "localhost", "xx.xx.xxx.xxx","xxx.temporary.link"]
</code>```

If I wget localhost:8000 I get a response fine. I have tried doing all of the above as root and as another dedicated user but it makes no difference.

I ran through this guide

https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04

and I still have the same issue.

Does anyone have any other ideas? Thanks in advance

答:
Try:

```<code>sudo ufw allow 8000
</code>```

Not:

```<code>sudo ufw 8000 allow
</code>```

Body:
I am running an ubuntu 16.04 cloud VPS server. I've set up a venv and activated it, and installed django.
I run the server with

python3 manage.py runserver 0.0.0.0:8000

I am trying to access this application from a remote computer (not inside the same LAN); I'm trying to make the application visible to the world outside the VPS and VPLAN. When I try to access the site in my home computer broswer like: xx.xx.xxx.xxx:8000 I get the error:

This site can’t be reached. http://xx.xx.xxx.xxx:8000/ is unreachable.

Now I've tried a traceroute and it seems to reach the server ok. I also did

sudo ufw enable
sudo ufw 8000 allow
sudo iptables -S | grep 8000 (and see the proper entries)

In the settings file I have:

ALLOWED_HOSTS = ["*", "0.0.0.0", "localhost", "xx.xx.xxx.xxx","xxx.temporary.link"]

If I wget localhost:8000 I get a response fine. I have tried doing all of the above as root and as another dedicated user but it makes no difference.

I ran through this guide

https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04

and I still have the same issue.

Does anyone have any other ideas? Thanks in advance

Body:
Try:

sudo ufw allow 8000

Not:

sudo ufw 8000 allow


问:
How to convert mixed map string back to mixed map in Java
I have a mixed map like: private Map<Integer, Map<Character, Float>> probabilities = new HashMap<>();

And the output for that as string is: this.probabilities.toString() => {0={a=0.5}, 1={s=0.75}, 2={�=1.0}}

So is there I way to convert this output to mixed map as before?

Keep in mind that I can have any type of Character like "}" that could end up looking like:

{0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}

答:
Here is a method for parsing that string back into your nested map.

```<code>static Map<Integer, Map<Character, Float>> parse(String input) {
    if (! input.startsWith("{") || ! input.endsWith("}"))
        throw new IllegalArgumentException("Invalid input (missing surrounding '{}'): " + input);
    Map<Integer, Map<Character, Float>> output = new LinkedHashMap<>();

    Matcher m = Pattern.compile("\\G(\\d+)=\\{(.)=([0-9.]+)\\}(?:, |$)")
            .matcher(input).region(1, input.length() - 1);
    int end = 1;
    while (m.find()) {
        output.computeIfAbsent(Integer.valueOf(m.group(1)), k -> new LinkedHashMap<>())
                .put(m.group(2).charAt(0), Float.valueOf(m.group(3)));
        end = m.end();
    }
    if (end != input.length() - 1)
        throw new IllegalArgumentException("Invalid input at: " + input.substring(end));
    return output;
}
</code>```

Test

```<code>Map<Integer, Map<Character, Float>> probabilities = new TreeMap<>(Map.of(
        0, Map.of('a', 0.25f),
        1, Map.of('"', 0.5f),
        2, Map.of('s', 0.625f),
        3, Map.of('{', 0.75f),
        4, Map.of('�', 0.875f),
        5, Map.of('}', 1.0f)
));
System.out.println("probabilities = " + probabilities);

String input = "{0={a=0.25}, 1={\"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}";
System.out.println("input         = " + input);

Map<Integer, Map<Character, Float>> output = parse(input);
System.out.println("output        = " + output);
</code>```

Output

probabilities = {0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}
input         = {0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}
output        = {0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}
```

Body:
Here is a method for parsing that string back into your nested map.

static Map<Integer, Map<Character, Float>> parse(String input) {
    if (! input.startsWith("{") || ! input.endsWith("}"))
        throw new IllegalArgumentException("Invalid input (missing surrounding '{}'): " + input);
    Map<Integer, Map<Character, Float>> output = new LinkedHashMap<>();

    Matcher m = Pattern.compile("\\G(\\d+)=\\{(.)=([0-9.]+)\\}(?:, |$)")
            .matcher(input).region(1, input.length() - 1);
    int end = 1;
    while (m.find()) {
        output.computeIfAbsent(Integer.valueOf(m.group(1)), k -> new LinkedHashMap<>())
                .put(m.group(2).charAt(0), Float.valueOf(m.group(3)));
        end = m.end();
    }
    if (end != input.length() - 1)
        throw new IllegalArgumentException("Invalid input at: " + input.substring(end));
    return output;
}

Test

Map<Integer, Map<Character, Float>> probabilities = new TreeMap<>(Map.of(
        0, Map.of('a', 0.25f),
        1, Map.of('"', 0.5f),
        2, Map.of('s', 0.625f),
        3, Map.of('{', 0.75f),
        4, Map.of('�', 0.875f),
        5, Map.of('}', 1.0f)
));
System.out.println("probabilities = " + probabilities);

String input = "{0={a=0.25}, 1={\"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}";
System.out.println("input         = " + input);

Map<Integer, Map<Character, Float>> output = parse(input);
System.out.println("output        = " + output);

Output

probabilities = {0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}
input         = {0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}
output        = {0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}


问:
How to pass context for an intent from a method of a class?
Error :  java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
        at com.adriitsolutions.prarthana.AdapterForListView.MyRequestForBloodRequirementListRecyclerView$1.onClick(MyRequestForBloodRequirementListRecyclerView.java:153)
        at android.view.View.performClick(View.java:6935)
Here is my code.

java
((myViewHolderForRecyclerViewOfMenu) viewHolder).iv_my_request_view.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        // showLeadDetails(position);
        context.startActivity(new Intent( context , ViewDonorListActivity.class));
        Log.e("ONCLICK", "View Request");
    }
});

```<code>

Adapter :  @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        holder.sendAt.setText(mData.get(position).getSendAt());
        holder.radius.setText(mData.get(position).getRadius());
        holder.acceptedStatus.setText(mData.get(position).getAcceptedStatus());

        holder.requestBloodGrpType.setImageResource(mData.get( position ).getRequestBloodGrpType() );
        //holder.requestUrgenyType.setImageResource( mData.get( position ).getRequestUrgencyType() );

        holder.viewRequest.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(new Intent(mContext,ViewDonorListActivity.class));
            }
        } );

       /* holder.buttonView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(new Intent(mContext,ViewDonorListActivity.class));
            }
        });*/

    }
</code>```

答:
i made an edit like this in my main activity :

```<code>   public static Context mContext;

public static Context getContext() {
    return mContext;
}
</code>```

and later using this context i was able to pass an intent to call another activity !

```<code>Intent intent = new Intent( MyRequestActivity.getContext() , ViewDonorListActivity.class );
                        MyRequestActivity.getContext().startActivity( intent );
</code>```

Body:
Error :  java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
        at com.adriitsolutions.prarthana.AdapterForListView.MyRequestForBloodRequirementListRecyclerView$1.onClick(MyRequestForBloodRequirementListRecyclerView.java:153)
        at android.view.View.performClick(View.java:6935)
Here is my code.

java
((myViewHolderForRecyclerViewOfMenu) viewHolder).iv_my_request_view.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        // showLeadDetails(position);
        context.startActivity(new Intent( context , ViewDonorListActivity.class));
        Log.e("ONCLICK", "View Request");
    }
});

Adapter :  @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        holder.sendAt.setText(mData.get(position).getSendAt());
        holder.radius.setText(mData.get(position).getRadius());
        holder.acceptedStatus.setText(mData.get(position).getAcceptedStatus());

        holder.requestBloodGrpType.setImageResource(mData.get( position ).getRequestBloodGrpType() );
        //holder.requestUrgenyType.setImageResource( mData.get( position ).getRequestUrgencyType() );

        holder.viewRequest.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(new Intent(mContext,ViewDonorListActivity.class));
            }
        } );

       /* holder.buttonView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(new Intent(mContext,ViewDonorListActivity.class));
            }
        });*/

    }

Body:
i made an edit like this in my main activity :

   public static Context mContext;

public static Context getContext() {
    return mContext;
}

and later using this context i was able to pass an intent to call another activity !

Intent intent = new Intent( MyRequestActivity.getContext() , ViewDonorListActivity.class );
                        MyRequestActivity.getContext().startActivity( intent );


问:
To fetch parent and its children connected thru one attribute
Query to fetch the SEC_CODE of parent its child and all grand children. Children are connected through PREV_SEC value.

According to above image,
1. Here if sec_code is 1 then the query should return 1, 3, 4 7, 8
2. if sec_code is 2 then query return 2.
3. if sec_code is 4 then query return 4,7,8

答:
If you strictly need an Oracle specific solution, You may try below query having CONNECT BY clause -</p>

```<code>SELECT SEC_CODE,SEC_NAME,PREV_SEC
FROM YOURTABLE
START WITH SEC_CODE = 1
CONNECT BY PRIOR PREV_SEC = SEC_CODE;
</code>```

Body:
If you strictly need an Oracle specific solution, You may try below query having CONNECT BY clause -

SELECT SEC_CODE,SEC_NAME,PREV_SEC
FROM YOURTABLE
START WITH SEC_CODE = 1
CONNECT BY PRIOR PREV_SEC = SEC_CODE;


问:
If two values have different data types, Java will automatically promote one of the values to the larger of the two data types?
The rule says that if two values have different data types, Java will automatically promote one of the values to the larger of the two data types?

In the code below, the value assigned to y is larger than the value of x. Therefore, taking the rule into consideration, the printed value should be "Float" but instead it printed "Double. Can you please why it prints Double instead of Float?

```<code>    Double x = 3.21;

    Float y = 4.1f;

    Object o  = (x*y);

    System.out.println( o.getClass().getSimpleName() ); // prints out Double
</code>```

答:
You have misunderstood what "larger" means in the phrase "the larger of the two data types". If it had said "the larger of the two values", then your understanding would have been correct.

A large data type is one that takes up more memory. A double takes up 64 bits, while a float takes up 32 bits, so double is the larger data type.

Note that this behaviour (binary numeric promotion) only applies to numeric types and can't really be described with one single rule such as "If two values have different data types, Java will automatically promote one of the values to the larger of the two data types". For example, a short times a byte gives you an int. This is specified fully in the Java Language Specification.

For more info, see section 5.6.2 in the Java Language Specification.

Body:
The rule says that if two values have different data types, Java will automatically promote one of the values to the larger of the two data types?

In the code below, the value assigned to y is larger than the value of x. Therefore, taking the rule into consideration, the printed value should be "Float" but instead it printed "Double. Can you please why it prints Double instead of Float?

    Double x = 3.21;

    Float y = 4.1f;

    Object o  = (x*y);

    System.out.println( o.getClass().getSimpleName() ); // prints out Double


问:
Getting IE to replace a regex with the literal string "$0"
I'm replacing a bunch of values in a regex with dollar amounts.  The problem is that in IE, if I attempt to replace with an amount of $0 (or, theoretically, $1--$9), the replace never occurs since the it's trying to replace a non-existant group:

```<code>'foo'.replace(/f/g, '$0');
</code>```

I want the result of that replacement to be "$0oo", which it is in Chrome & FF, but not IE9 (haven't tried other versions of IE).

Chrome & FF have an "issue" with the following, in that I can't figure out how to replace with a literal $1:

```<code>'foo'.replace(/(f)/g, '$1')
</code>```

答:
In Chrome and Firefox you can workaround this limitation by using a function as the second argument of the replace function:

```<code>'foo'.replace(/(f)/g, function(){return '$1';}); // => $1oo
</code>```

My own testing shows that IE8 is consistent with the other browsers on this issue.

Body:
I'm replacing a bunch of values in a regex with dollar amounts.  The problem is that in IE, if I attempt to replace with an amount of $0 (or, theoretically, $1--$9), the replace never occurs since the it's trying to replace a non-existant group:

'foo'.replace(/f/g, '$0');

I want the result of that replacement to be "$0oo", which it is in Chrome & FF, but not IE9 (haven't tried other versions of IE).

Chrome & FF have an "issue" with the following, in that I can't figure out how to replace with a literal $1:

'foo'.replace(/(f)/g, '$1')

Body:
In Chrome and Firefox you can workaround this limitation by using a function as the second argument of the replace function:

'foo'.replace(/(f)/g, function(){return '$1';}); // => $1oo

My own testing shows that IE8 is consistent with the other browsers on this issue.


问:
React JSON Schema Dependencies
I am trying to write up a JSONSchema to be used with react-jsonschema-form, but am having trouble getting the dependencies working and in the correct order.

```<code>  "properties":{
      "condition": {
          "type":"string",
          "enum":["1","2"],
           "options": {
           "dependencies":[
              {"id":"one","value":"1"},
              {"id":"two","value":"2"}
              ]
           }
      },
      "one":{
          "id":"one",
          "type":"number"
          },
      "two":{
          "id":"two",
          "type":"string"
      },
      "misc": {
        "type": "string"
      }
  },
  "type": "object"
}
</code>```

In the above, what I had hoped was for valid form data to be...

```<code>{
  "condition": "1",
  "one": 123
  "misc": "abc"
}
</code>```

Or if condition is "2"...

```<code>{
  "condition": "2",
  "two": "something",
  "misc": "abc"
}
</code>```

But instead the dependencies section does not seem to work as I had hoped. So both "one" and "two" can be present regardless of the condition value.

```<code>{
  "condition": "1",
  "one": 123,
  "two": "something",
  "misc": "abc"
}
</code>```

How can I change the JSON Schema so that only the respective field is possible based on the "condition".

Note... order does matter in the schema provided. Please see https://rjsf-team.github.io/react-jsonschema-form/ for demos.

答:
You have to use oneOf operator.
It take multiple dependencies, and if one of them are true,
the json is valid.

Example:

```<code>"oneOf":[
    {
      "required": [
        "name",
        "dateOfBirth"
      ]
    },
    {
      "required": [
        "name",
        "age"
      ]
    }
</code>```

More example can be found here.

Title: React JSON Schema Dependencies

Body:
I am trying to write up a JSONSchema to be used with react-jsonschema-form, but am having trouble getting the dependencies working and in the correct order.

  "properties":{
      "condition": {
          "type":"string",
          "enum":["1","2"],
           "options": {
           "dependencies":[
              {"id":"one","value":"1"},
              {"id":"two","value":"2"}
              ]
           }
      },
      "one":{
          "id":"one",
          "type":"number"
          },
      "two":{
          "id":"two",
          "type":"string"
      },
      "misc": {
        "type": "string"
      }
  },
  "type": "object"
}

In the above, what I had hoped was for valid form data to be...

{
  "condition": "1",
  "one": 123
  "misc": "abc"
}

Or if condition is "2"...

{
  "condition": "2",
  "two": "something",
  "misc": "abc"
}

But instead the dependencies section does not seem to work as I had hoped. So both "one" and "two" can be present regardless of the condition value.

{
  "condition": "1",
  "one": 123,
  "two": "something",
  "misc": "abc"
}

How can I change the JSON Schema so that only the respective field is possible based on the "condition".

Note... order does matter in the schema provided. Please see https://rjsf-team.github.io/react-jsonschema-form/ for demos.

Body:
You have to use oneOf operator.
It take multiple dependencies, and if one of them are true,
the json is valid.

Example:

"oneOf":[
    {
      "required": [
        "name",
        "dateOfBirth"
      ]
    },
    {
      "required": [
        "name",
        "age"
      ]
    }

More example can be found here.


问:
Tensorflow Object Detection API ( TF 2.0) GPU not working
I'm trying to run object detection API from https://github.com/tensorflow/models/tree/master/research/object_detection.
I have installed the API as per the instructions.

When running object_detection_tutorial.ipynb using GPU, nothing is happening at
for image_path in TEST_IMAGE_PATHS: show_inference(detection_model, image_path) for sometime and the kernel dies afterwards.

However, the same code is working when I'm using the CPU.

Following is the config of my machine:

Windows 10

TF2.0.0

CUDA:10.0.130

cuDNN:7.6.4

Graphics:GeForce GTX 1050

答:
with the following config (windows 10, cuda 10.0.13, cudnn 7.6.3, Tensorflow 2.0.0, GTX 1050 laptop) I add a similar problem with jupyter notebook when launching final code part : </p>

```<code>for image_path in TEST_IMAGE_PATHS:
   show_inference(detection_model, image_path)
</code>```

<p>The code is launched then the kernel fails. using nvidia-smi on cmd one can see that the code is going toward the GPU up to 90% of its capabilities. But it fails due to a lack of memory as one can see in the command prompt. GTX 1050 could not be enough for this type of computation </p>

```<code> 2020-02-16 09:41:45.057354: W tensorflow/core/common_runtime/bfc_allocator.cc:239] Allocator (GPU_0_bfc) ran out of memory trying to allocate 2.93GiB with freed_by_count=0. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available.
</code>```

Body:
with the following config (windows 10, cuda 10.0.13, cudnn 7.6.3, Tensorflow 2.0.0, GTX 1050 laptop) I add a similar problem with jupyter notebook when launching final code part :

for image_path in TEST_IMAGE_PATHS:
   show_inference(detection_model, image_path)

The code is launched then the kernel fails. using nvidia-smi on cmd one can see that the code is going toward the GPU up to 90% of its capabilities. But it fails due to a lack of memory as one can see in the command prompt. GTX 1050 could not be enough for this type of computation

 2020-02-16 09:41:45.057354: W tensorflow/core/common_runtime/bfc_allocator.cc:239] Allocator (GPU_0_bfc) ran out of memory trying to allocate 2.93GiB with freed_by_count=0. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available.


问:
how to hide bottom bar of android (back, home) in xamarin forms?
How can I hide the bottom android bar (back button, home button) permanently in xamarin forms? I tried some code but its hiding it temporarily. When I touch the screen, it again shows. But I want to hide it completely. </p>

答:
Also, as Ricardo Dias Morais said,

Some OS "block" this Immersive mode feature, i don't have an Samsung, but in MIUI this happens too, for me, i had to enable the app i wanted in the Fullscreen Mode settings, for me it was: Display > FullscreenMode > Then enable the apps that need to have fullscreen

I can provide more information if it is required :)


问:
Anaconda Prompt(Anaconda3) does not recognize files in a directory
I took to heart the message that support for anaconda2 was dropped. I installed anaconda3 and used 2to3 to convert my *.py codes. Everything seemed to work as expected. I have several 2 line bat codes that cd to a particular directory and then call python to execute a particular *.py code in that directory. By loading Anaconda Prompt(Anaconda3) and invoking the bat file I could run pythons in that directory as expected.

Then, a couple of days ago, I made such a run and got an error message saying the *.py file could not be found. I immediately looked in the directory and the python file was there as expected. I then did a dir command in Anaconda Prompt(Anaconda3) and found that almost no files in the directory were listed. This was happening on my windows 10 laptop.

On my desktop, everything continues to work as expected. Are there any suggestions as to what could cause such a problem and how to fix it.

Thanks,
Mack Elrod

Responding to the request for additional information, I have a bin directory that is in path. In bin\MackData.bat is

c:
cd %USERPROFILE%\Documents\Medev\MackData
copy sugarhist.png sugarhist.old.png
python MackData.py

When I open Anaconda Prompt(Anaconda3) and enter MackData I get

(base) C:\Users\Mack>MackData

(base) C:\Users\Mack>c:

(base) C:\Users\Mack>cd C:\Users\Mack\Documents\Medev\MackData

(base) C:\Users\Mack\Documents\Medev\MackData>copy sugarhist.png sugarhist.old.png
        1 file(s) copied.

(base) C:\Users\Mack\Documents\Medev\MackData>python MackData.py
python: can't open file 'MackData.py': [Errno 2] No such file or directory

(base) C:\Users\Mack\Documents\Medev\MackData>

But MackData.py is a python file in the directory MackData.

This code worked on this laptop until a few days ago and continues to work on my desktop computer. I can, of course, publish MackData.py but that seems irrelevant. The point is that Anaconda can't find it.

Thanks,
Mack

I must submit a sincere apology to this community. I have determined my problem and Anaconda is not responsible in any way. I thank all of you for you concerns and comments.

For any who might be interested I will give a brief outline of what happened. First, I installed Anaconda3. Several days later my directory, MackData, was moved to a new location. I conjecture that happened by me inadvertently letting my hand drag on the touch pad. Then, not knowing the location had changed I updated my laptop from my desktop. My update program not finding MackData where expected recreated it and put only the most recently changed files from the desktop into the new MackData. New but in the correct location. Then of course running my script in the Anaconda3 prompt failed. Doing a dir in the Anaconda3 prompt showed only a few files were there. I then went to Windows File Explore and looked at MackData and saw all of the expected files. I used the quick access feature which unknown to me pointed to the old directory in its new location.

That is not intended to be an excuse but only as an explanation. Again, I do apologize to the community.

Mack Elrod

答:
I'm pretty sure newer anaconda launchers users different environment paths, and not even windows ones.

I suggest either checking the environment path within the anaconda launcher and configurations or, a better solution in my opinion, run these scrips using the regular python engine, without using anaconda (simpler, more determinant and works within your standard environment)


问:
The operator '[]' isn't defined for the class 'Object'. Dart
I have a Widget which on some point navigate to a different page.
like:-

```<code>          Navigator.of(context).pushNamed(
              NextPage.routeName,
              arguments: {
                "tag": this.tag,
                "data": this.data,
              },
            );
</code>```

now clearly Even though argument parameter accepts type Object but it also accepts Map since this sentence is not giving me an error.

And in the NextPage i am accessing the value like:-

```<code>tag: ModalRoute.of(context).settings.arguments["tag"].toString(),
</code>```

Now the vscode is giving me error:-

```<code>The operator '[]' isn't defined for the class 'Object'.
Try defining the operator '[]'.dart(undefined_operator)
</code>```

I don't know why vscode is giving me an error.
So, Either the Object should have the [] or Map should be a type of Object.

Or there is something about the Date which is not clear.

Note: data is object.

How do I remove this error?

答:
ModalRoute.settings.arguments  is a property with the type Object. You cannot call an indexer [] on an Object. Everything in Dart inherits from Object, which is why you can pass your arguments to the ModalRoute no matter what it is. In order to use it, though, you need to first cast it to the type you are expecting to work with.

tag: (ModalRoute.of(context).settings.arguments as Map)["tag"].toString(),
```

Body:
I have a Widget which on some point navigate to a different page.
like:-

          Navigator.of(context).pushNamed(
              NextPage.routeName,
              arguments: {
                "tag": this.tag,
                "data": this.data,
              },
            );

now clearly Even though argument parameter accepts type Object but it also accepts Map since this sentence is not giving me an error.

And in the NextPage i am accessing the value like:-

tag: ModalRoute.of(context).settings.arguments["tag"].toString(),

Now the vscode is giving me error:-

The operator '[]' isn't defined for the class 'Object'.
Try defining the operator '[]'.dart(undefined_operator)

I don't know why vscode is giving me an error.
So, Either the Object should have the [] or Map should be a type of Object.

Or there is something about the Date which is not clear.

Note: data is object.

How do I remove this error?


问:
How to delete an element from a 2D Numpy array without knowing its position
I have a 2D array:
[[0,0], [0,1], [1,0], [1,1]]

I want to delete the [0,1] element without knowing its position within the array (as the elements may be shuffled).

Result should be:
[[0,0], [1,0], [1,1]]

I've tried using numpy.delete but keep getting back a flattened array:

```<code>>>> arr = np.array([[0,0], [0,1], [1,0], [1,1]])
>>> arr
array([[0, 0],
       [0, 1],
       [1, 0],
       [1, 1]])
>>> np.delete(arr, [0,1])
array([0, 1, 1, 0, 1, 1])
</code>```

Specifying the axis removes the 0, 1 elements rather than searching for the element (which makes sense):

```<code>>>> np.delete(arr, [0,1], axis=0)
array([[1, 0],
       [1, 1]])
</code>```

And trying to find the location (as has been suggested) seems equally problematic:

```<code>>>> np.where(arr==[0,1])
(array([0, 1, 1, 3]), array([0, 0, 1, 1]))
</code>```

(Where did that 3 come from?!?)

答:
Here we find all of the rows that match the candidate [0, 1]

```<code>>>> (arr == [0, 1]).all(axis=1)
array([False,  True, False, False])
</code>```

Or alternatively, the rows that do not match the candidate

```<code>>>> ~(arr == [0, 1]).all(axis=1)
array([ True, False,  True,  True])
</code>```

So, to select all those rows that do not match [0, 1]

```<code>>>> arr[~(arr == [0, 1]).all(axis=1)]
array([[0, 0],
       [1, 0],
       [1, 1]])
</code>```

Note that this will create a new array.

Body:
I have a 2D array:
[[0,0], [0,1], [1,0], [1,1]]

I want to delete the [0,1] element without knowing its position within the array (as the elements may be shuffled).

Result should be:
[[0,0], [1,0], [1,1]]

I've tried using numpy.delete but keep getting back a flattened array:

>>> arr = np.array([[0,0], [0,1], [1,0], [1,1]])
>>> arr
array([[0, 0],
       [0, 1],
       [1, 0],
       [1, 1]])
>>> np.delete(arr, [0,1])
array([0, 1, 1, 0, 1, 1])

Specifying the axis removes the 0, 1 elements rather than searching for the element (which makes sense):

>>> np.delete(arr, [0,1], axis=0)
array([[1, 0],
       [1, 1]])

And trying to find the location (as has been suggested) seems equally problematic:

>>> np.where(arr==[0,1])
(array([0, 1, 1, 3]), array([0, 0, 1, 1]))

(Where did that 3 come from?!?)

Body:
Here we find all of the rows that match the candidate [0, 1]

>>> (arr == [0, 1]).all(axis=1)
array([False,  True, False, False])

Or alternatively, the rows that do not match the candidate

>>> ~(arr == [0, 1]).all(axis=1)
array([ True, False,  True,  True])

So, to select all those rows that do not match [0, 1]

>>> arr[~(arr == [0, 1]).all(axis=1)]
array([[0, 0],
       [1, 0],
       [1, 1]])

Note that this will create a new array.


问:
How to automatically scale down a 100% div without showing browser vertical scrollbars?
I have a table with three rows. I have 1 main #container div (height 100%) and inside it is a table with 3 rows. The first and last row have fixed size content. In the second row is a #content div with 100% height and overflow:auto. (actually the table has a lot more rows and the page has more divs, but for the sake of clarity i scalled it down for this question).

If there is more content in #content than fits, a vertical scrollbar should appear next to that div's content. However, a vertical scrollbar appears at the browser window itself. When i set the #content div to a fixed size however, that vertical scrollbar does appear in the correct place.

I must be doing something wrong, or maybe misinterpreting something :) Any ideas? Maybe there's jquery/javascript out there that can monitor the page and when loading/resizing the browser, scales down that particular div?

EDIT: I just created a small example: http://wierdaonline.com/softest.html

In the ideal situation, the whole thing (table) should always be visible in the browser window, without any window scrollbar other than in the #content div.

答: The #container 100% is 100% of the page height which can be more than the window height. Setting html and body height to 100% (=100% of the window) could help, depending on what you are trying to achieve.</p>


问:
Add Hyperlink and Class to every image within a string
I am using Summernote to post blogs but am using a code snippet to upload the images directly to the server rather than within the text itself, the code looks like this:

```<code><script>$(document).ready(function() {
$("#summernote").summernote({
         callbacks: {
        onImageUpload : function(files, editor, welEditable) {

             for(var i = files.length - 1; i >= 0; i--) {
                     sendFile(files[i], this);
            }
        }
    }
    });
});
function sendFile(file, el) {
var form_data = new FormData();
form_data.append('file', file);
$.ajax({
    data: form_data,
    type: "POST",
    url: 'editor-upload.php',
    cache: false,
    contentType: false,
    processData: false,
    success: function(url) {
        $(el).summernote('editor.insertImage', url);
    }
});
}
</script>

<?php
if(empty($_FILES['file']))
{
    exit();
}
$errorImgFile = "./img/img_upload_error.jpg";
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
$destinationFilePath = './img-uploads/'.$newfilename ;
if(!move_uploaded_file($_FILES['file']['tmp_name'], $destinationFilePath)){
    echo $errorImgFile;
}
else{
    echo $destinationFilePath;
}

?>
</code>```

I am trying to now include Lightbox to the embedded images but cannot figure out a way to alter the img tags individually to do this? As an example;

```<code>$string = '<img src="firstimg.jpg"> a little bit of text <img src="secondimg.jpg">';
</code>```

I would need to convert it to something similar to

```<code><a class="example-image-link" href="firstimg.jpg" data-lightbox="example-set"><img class="example-image" src="firstimg.jpg"></a> a little bit of text <a class="example-image-link" href="secondimg.jpg" data-lightbox="example-set"><img class="example-image" src="secondimg.jpg"></a>
</code>```

I've searched around but found nothing to help with this? Any help would be appreciated!

答:
let $string = `<img src="firstimg.jpg"> a little bit of text <img src="secondimg.jpg" >`
let parser = new DOMParser()
let _document = parser.parseFromString($string, "text/html")
let ele = _document.getElementsByTagName("IMG")
for(let i = 0; i < ele.length; i++) {
let wrapper = _document.createElement('a');
wrapper.classList = ["example-image-link"]
wrapper.href = ele[i].src
wrapper.setAttribute('data-lightbox', 'Hello World!');
let myImg =  ele[i]
wrapper.appendChild(myImg.cloneNode(true));
myImg.parentNode.replaceChild(wrapper, myImg);
}

let newStr = `${_document.getElementsByTagName("BODY")[0].innerHTML}`
console.log(newStr)```

You can try with the above logic

Body:
I am using Summernote to post blogs but am using a code snippet to upload the images directly to the server rather than within the text itself, the code looks like this:

<?php
if(empty($_FILES['file']))
{
    exit();
}
$errorImgFile = "./img/img_upload_error.jpg";
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
$destinationFilePath = './img-uploads/'.$newfilename ;
if(!move_uploaded_file($_FILES['file']['tmp_name'], $destinationFilePath)){
    echo $errorImgFile;
}
else{
    echo $destinationFilePath;
}

?>

I am trying to now include Lightbox to the embedded images but cannot figure out a way to alter the img tags individually to do this? As an example;

$string = ' a little bit of text ';

I would need to convert it to something similar to

 a little bit of text

I've searched around but found nothing to help with this? Any help would be appreciated!

Body:
let $string = `<img src="firstimg.jpg"> a little bit of text <img src="secondimg.jpg" >`
let parser = new DOMParser()
let _document = parser.parseFromString($string, "text/html")
let ele = _document.getElementsByTagName("IMG")
for(let i = 0; i < ele.length; i++) {
let wrapper = _document.createElement('a');
wrapper.classList = ["example-image-link"]
wrapper.href = ele[i].src
wrapper.setAttribute('data-lightbox', 'Hello World!');
let myImg =  ele[i]
wrapper.appendChild(myImg.cloneNode(true));
myImg.parentNode.replaceChild(wrapper, myImg);
}

let newStr = `${_document.getElementsByTagName("BODY")[0].innerHTML}`
console.log(newStr)

You can try with the above logic


问:
Can somebody explain what makes this code?
I've hot React component which returns input tag. Can you please explain what is going on at the eighth line ref={element => element && (element.onChange = onChange)}? I

```<code>import React from 'react';

export default function MyInput({
    onChange,
    ...rest
}) {
    return (
        <input
            {...rest}
            ref={element => element && (element.onChange = onChange)}
        />
    );
}
</code>```

答:
React's ref is used to access the DOM directly, and in general is recommended to use as less as possible. The point of functional refs, and keep in mind that they're deprecated, is to assign the element into a class component's variable. e.g.:

```<code>Class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.inputRef = null;
  }

  ...stuff

  render() {
    ...stuff
    <input ref={element => this.inputRef = element} />
  }
}
</code>```

Then, you could do something like:

```<code>this.inputRef.current.style.color = 'blue';
</code>```

In your case, there is no need for this. If you want to assign the onChange you get from props, just do this:

```<code><input {...stuff} onChange={onChange} />
</code>```

Read more about React refs here.

As for element && element.onChange, it's designed to make sure that element exists before accessing it's onChange property. Another way to do it, using optional chaining (only avaliable in react-scripts v3.3 and above), is this:

```<code>element?.onChange
</code>```

Body:
I've hot React component which returns input tag. Can you please explain what is going on at the eighth line ref={element => element && (element.onChange = onChange)}? I

import React from 'react';

export default function MyInput({
    onChange,
    ...rest
}) {
    return (
        <input
            {...rest}
            ref={element => element && (element.onChange = onChange)}
        />
    );
}

Body:
React's ref is used to access the DOM directly, and in general is recommended to use as less as possible. The point of functional refs, and keep in mind that they're deprecated, is to assign the element into a class component's variable. e.g.:

Class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.inputRef = null;
  }

  ...stuff

  render() {
    ...stuff
    <input ref={element => this.inputRef = element} />
  }
}

Then, you could do something like:

this.inputRef.current.style.color = 'blue';

In your case, there is no need for this. If you want to assign the onChange you get from props, just do this:

<input {...stuff} onChange={onChange} />

Read more about React refs here.

As for element && element.onChange, it's designed to make sure that element exists before accessing it's onChange property. Another way to do it, using optional chaining (only avaliable in react-scripts v3.3 and above), is this:

element?.onChange


问:
How to chop a string containing escape sequences to a given length in javascript?
I have some strings I want to be limited to n characters, and if exceeding n characters - to end with ' ...'. Pretty common

My problem is with the strings containing escape sequences, though.

I can utilize regular expressions in some way probably, but shouldn't there be a simple and elegant solution?

答:
Just slice the number of characters you need and add the ellipsis … :)

const longstr = 'long string is here'

const shorten = (str, limit, end = '…') => str.slice(0, limit) + end

console.log(shorten(longstr, 10))```


问:
XMLHttpRequest | Sending a request by hand gets me a response of 2111 characters but using XMLHttpRequest the response has a lenght of 179
I basically copy-pasted the MDN code, and I triple checked the URL. I can't find the reason as to why the responses differ.
For reference, here is my code:
Edit: Didn't see cookies got sent, I'm sorry

function getUsernames(str) {
  console.log(str)
}
function reqListener() {
  alert(getUsernames(this.responseText));
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=%7B%22id%22%3A%2217199917378%22%2C%22include_reel%22%3Atrue%2C%22fetch_mutual%22%3Atrue%2C%22first%22%3A24%7D");
oReq.responseType = "arraybuffer";
oReq.send();

oReq.onload = function(e) {
  var arraybuffer = oReq.response; // not responseText
  console.log(arraybuffer)
  /* ... */
}```

答:
Seems the xmlhttprequest is truncated and does not contain the data you want unless you have key (auth)

Here is something hacky: How can I get a user's media from Instagram without authenticating as a user?

You also have two load handlers. You likely mean this

function getUsernames(str) {
  return JSON.parse(str); // of course do something with this when complete
}
function reqListener() {
  console.log(getUsernames(this.responseText));
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=%7B%22id%22%3A%2217199917378%22%2C%22include_reel%22%3Atrue%2C%22fetch_mutual%22%3Atrue%2C%22first%22%3A24%7D");
oReq.responseType = "text";
oReq.send();```


问:
MVVM binding viewmodel property child to viewmodel property
not sure if my title explains well the issue im having.

In my application i make a service calls to
-retrieve a list of customers.
-retrieve a list of organisations.

Then i bind this list of customers to a listbox on my view.

In my viewmodel i have the following properties:

```<code>IEnumerable<Organisation> Organisations
ObservableCollection<Customer> Customers
</code>```

Organisation properties: OrganisationId, OrganisationName

Customer properties: CustomerId, OrganisationId, CustomerFirstName, CustomerLastName

Inside the Listbox on my view i want to show the organisationname for each customer in the list.

how can i go about binding this in my view? I just want a textblock to show the organisationname for the customer.

答: I would employ a MultiBinding and a MultiValueConverter for this, this is sadly not possible if you are restricted to Silverlight as the tags suggest though...

Body:
not sure if my title explains well the issue im having.

In my application i make a service calls to
-retrieve a list of customers.
-retrieve a list of organisations.

Then i bind this list of customers to a listbox on my view.

In my viewmodel i have the following properties:

IEnumerable<Organisation> Organisations
ObservableCollection<Customer> Customers

Organisation properties: OrganisationId, OrganisationName

Customer properties: CustomerId, OrganisationId, CustomerFirstName, CustomerLastName

Inside the Listbox on my view i want to show the organisationname for each customer in the list.

how can i go about binding this in my view? I just want a textblock to show the organisationname for the customer.