问:
Variable outside of value not permanently changing
I have the following code for a maze solving bot:

```<code>def main():
    axioms = {
        "Y":"F",
        "X":"R",
        "-Y":"B",
        "-X":"L"
        }

    def rotate():
        axioms = list(axioms.items())
        new = []
        new.append((axioms[0][0], axioms[1][1]))
        new.append((axioms[1][0], axioms[2][1]))
        new.append((axioms[2][0], axioms[3][1]))
        new.append((axioms[3][0], axioms[0][1]))
        return dict(new)

    def move(dir):
        if dir == "F":
            log("Moving forward.")
            API.moveForward()
        elif dir == "L":
            log("Turning left.")
            axioms = rotate()
            API.turnLeft()
            API.moveForward()
        elif dir == "R":
            log("Turning right.")
            axioms = rotate()
            axioms = rotate()
            axioms = rotate()
            API.turnRight()
            API.moveForward()
        elif dir == "B":
            log("Turning back.")
            axioms = rotate()
            axioms = rotate()
            API.turnLeft()
            API.turnLeft()
            API.moveForward()

    def calculateNext(current):
        #calculate possible turns
        if current[3] == False:
            if sensor.front() == True:
                del current[2][(next(key for key, value in axioms.items() if value == "F"))]
            if sensor.left() == True:
                del current[2][(next(key for key, value in axioms.items() if value == "L"))]
            if sensor.right() == True:
                del current[2][(next(key for key, value in axioms.items() if value == "R"))]
            current[3] = True

        #find preferred turn
        values = []
        for temp in current[2]:
            values.append(current[2][temp][1])

        #check for inconsistency
        def retry():
            global preferred
            if all(x==values[0] for x in values) == True and values[0] > current[1]:
                current[1] += 2
                retry()
            else:
                preferred = min(values)
        retry()

        preferedTurns = []
        #for temp in current[2]:
        preferedTurns.append(next(key for key, value in current[2].items() if value[1] == preferred))

        return preferedTurns[0]
</code>```

The problem is the axioms variable. I have it outside of the calculateNext function and when its values change, within calculateNext such as,

```<code>    def rotate():
        axioms = list(axioms.items())
        new = []
        new.append((axioms[0][0], axioms[1][1]))
        new.append((axioms[1][0], axioms[2][1]))
        new.append((axioms[2][0], axioms[3][1]))
        new.append((axioms[3][0], axioms[0][1]))
        return dict(new)
...
...
...

    def move(dir):
        if dir == "F":
            log("Moving forward.")
            API.moveForward()
        elif dir == "L":
            log("Turning left.")
            axioms = rotate(axioms)
            API.turnLeft()
            API.moveForward()
        elif dir == "R":
            log("Turning right.")
            axioms = rotate(axioms)
            axioms = rotate(axioms)
            axioms = rotate(axioms)
            API.turnRight()
            API.moveForward()
        elif dir == "B":
            log("Turning back.")
            axioms = rotate(axioms)
            axioms = rotate(axioms)
            API.turnLeft()
            API.turnLeft()
            API.moveForward()
</code>```

they do not save to the variable and the same values are used instead of the new ones.

答:
To maintain the value of a variable across functions you have several options, such as: use a global variable, use a class to share properties along methods, use a mutable variable and mutate rather than reassign it, or pass the variable as a parameter and return it at the end of the function.

As axioms is a dict and therefore mutable, rewriting rotate to change its values in place (rather than reassigning) might work best for you

```<code>def rotate():
    values = list(axioms.values())
    for k, v in zip(axioms, values[1:] + [values[0]]):
        axioms[k] = v
</code>```

You would then just call it as rotate()

Body:
I have the following code for a maze solving bot:

def main():
    axioms = {
        "Y":"F",
        "X":"R",
        "-Y":"B",
        "-X":"L"
        }

    def rotate():
        axioms = list(axioms.items())
        new = []
        new.append((axioms[0][0], axioms[1][1]))
        new.append((axioms[1][0], axioms[2][1]))
        new.append((axioms[2][0], axioms[3][1]))
        new.append((axioms[3][0], axioms[0][1]))
        return dict(new)

    def move(dir):
        if dir == "F":
            log("Moving forward.")
            API.moveForward()
        elif dir == "L":
            log("Turning left.")
            axioms = rotate()
            API.turnLeft()
            API.moveForward()
        elif dir == "R":
            log("Turning right.")
            axioms = rotate()
            axioms = rotate()
            axioms = rotate()
            API.turnRight()
            API.moveForward()
        elif dir == "B":
            log("Turning back.")
            axioms = rotate()
            axioms = rotate()
            API.turnLeft()
            API.turnLeft()
            API.moveForward()

    def calculateNext(current):
        #calculate possible turns
        if current[3] == False:
            if sensor.front() == True:
                del current[2][(next(key for key, value in axioms.items() if value == "F"))]
            if sensor.left() == True:
                del current[2][(next(key for key, value in axioms.items() if value == "L"))]
            if sensor.right() == True:
                del current[2][(next(key for key, value in axioms.items() if value == "R"))]
            current[3] = True

        #find preferred turn
        values = []
        for temp in current[2]:
            values.append(current[2][temp][1])

        #check for inconsistency
        def retry():
            global preferred
            if all(x==values[0] for x in values) == True and values[0] > current[1]:
                current[1] += 2
                retry()
            else:
                preferred = min(values)
        retry()

        preferedTurns = []
        #for temp in current[2]:
        preferedTurns.append(next(key for key, value in current[2].items() if value[1] == preferred))

        return preferedTurns[0]

The problem is the axioms variable. I have it outside of the calculateNext function and when its values change, within calculateNext such as,

    def rotate():
        axioms = list(axioms.items())
        new = []
        new.append((axioms[0][0], axioms[1][1]))
        new.append((axioms[1][0], axioms[2][1]))
        new.append((axioms[2][0], axioms[3][1]))
        new.append((axioms[3][0], axioms[0][1]))
        return dict(new)
...
...
...

    def move(dir):
        if dir == "F":
            log("Moving forward.")
            API.moveForward()
        elif dir == "L":
            log("Turning left.")
            axioms = rotate(axioms)
            API.turnLeft()
            API.moveForward()
        elif dir == "R":
            log("Turning right.")
            axioms = rotate(axioms)
            axioms = rotate(axioms)
            axioms = rotate(axioms)
            API.turnRight()
            API.moveForward()
        elif dir == "B":
            log("Turning back.")
            axioms = rotate(axioms)
            axioms = rotate(axioms)
            API.turnLeft()
            API.turnLeft()
            API.moveForward()

they do not save to the variable and the same values are used instead of the new ones.

Body:
To maintain the value of a variable across functions you have several options, such as: use a global variable, use a class to share properties along methods, use a mutable variable and mutate rather than reassign it, or pass the variable as a parameter and return it at the end of the function.

As axioms is a dict and therefore mutable, rewriting rotate to change its values in place (rather than reassigning) might work best for you

def rotate():
    values = list(axioms.values())
    for k, v in zip(axioms, values[1:] + [values[0]]):
        axioms[k] = v

You would then just call it as rotate()


来源: stackexchange

问:
Changing mm/dd/yyyy and m/dd/yyyy to yyyy
I have a data set with the dates written as follows:

5/18/12
12/20/10
2/17/08

etc

Is there a way to transform these into yyyy format? I'm struggling because they didn't include 0s in front of the months, so each date is a different number of characters long.

ContentLicense: CC BY-SA 4.0

Body:
We can use as.Date with format in base R

format(as.Date(c("5/18/12", "12/20/10", "2/17/08"), "%m/%d/%y") , "%Y")
#[1] "2012" "2010" "2008"


问:
Argument of type 'number' is not assignable to parameter of type 'never' in array.includes()
I'm receiving a Typescript error,

error TS2345: Argument of type 'number' is not assignable to parameter
of type 'string & number'. Type 'number' is not assignable to type
'string'. 112

```<code>setProductPrices(productPrices.filter(
  (p): boolean => !selectedProductIds.includes(p.id)));
                                               ^^^^
</code>```

from the following code:

```<code>export interface IProductPrice {
    id: number;
}
const [productPrices, setProductPrices] = useState<IProductPrice[]>([]);
const [selectedProductIds, setSelectedProductIds] = useState<string[] | number[]>([]);

const deleteSelectedProducts = (): void => {
        setProductPrices(productPrices.filter((p): boolean => !selectedProductIds.includes(p.id)));
        setSelectedProductIds([]);
};
</code>```

The includes() method is supposedly
expecting a parameter of 'never' while p.id is a number. Does anyone know how to fix this?

答:
The Problem

When you have a union of arrays of different types, you can't call methods on them.

The Reason

You have string[] | number[], and so .filter is:

```<code>  ((filterFunc: (x: string) => boolean) => string[])
| ((filterFunc: (x: number) => boolean) => number[])
</code>```

When TS combines those signatures, it's going to union the two filterFunc signatures together:

```<code>  ((x: number) => boolean)
| ((x: string) => boolean)
</code>```

This is a little unintuitive, but this simplifies to (x: number & string) => boolean.  Because if you have a function that take X, or a function that takes Y, the only safe thing to pass is something that is both X and Y, or X & Y.

number & string however, is an impossible type, which "simplifies" to never.  Hence why the signature is (x: never) => boolean.

The Fix

Ideally you'd only use string[] or number[] but not both.  (Just looking at the code, it's a little mysterious why id can only be number, but "selected product ids" can be strings, too)

But if you do need to support both strings and numbers, the easiest fix here is to use Array<string | number> instead of string[] | number[]: the single array type doesn't have the issue of trying to union together two .filter signatures.

You can either change your state to be of that type:

```<code>const [selectedProductIds, setSelectedProductIds] = useState<Array<string | number>>([]);
</code>```

This is simple, but has the downside that it will allow arrays of mixed strings and numbers, which may not be desirable.  (e.g. setSelectProductIds(['0', 1, '2'])

If not, you can temporarily cast to Array<string | number>, do the filter, then cast back to string[] | number[].  This is not super clean, but should be safe:

```<code>setProductPrices(
    (productPrices as Array<string | number>).filter((p): boolean => !selectedProductIds.includes(p.id)) as (string[] | number[])
);
</code>```

Body:
I'm receiving a Typescript error,

error TS2345: Argument of type 'number' is not assignable to parameter
of type 'string & number'. Type 'number' is not assignable to type
'string'. 112

setProductPrices(productPrices.filter(
  (p): boolean => !selectedProductIds.includes(p.id)));
                                               ^^^^

from the following code:

export interface IProductPrice {
    id: number;
}
const [productPrices, setProductPrices] = useState<IProductPrice[]>([]);
const [selectedProductIds, setSelectedProductIds] = useState<string[] | number[]>([]);

const deleteSelectedProducts = (): void => {
        setProductPrices(productPrices.filter((p): boolean => !selectedProductIds.includes(p.id)));
        setSelectedProductIds([]);
};

The includes() method is supposedly
expecting a parameter of 'never' while p.id is a number. Does anyone know how to fix this?

Body:
The Problem

When you have a union of arrays of different types, you can't call methods on them.

The Reason

You have string[] | number[], and so .filter is:

  ((filterFunc: (x: string) => boolean) => string[])
| ((filterFunc: (x: number) => boolean) => number[])

When TS combines those signatures, it's going to union the two filterFunc signatures together:

  ((x: number) => boolean)
| ((x: string) => boolean)

This is a little unintuitive, but this simplifies to (x: number & string) => boolean.  Because if you have a function that take X, or a function that takes Y, the only safe thing to pass is something that is both X and Y, or X & Y.

number & string however, is an impossible type, which "simplifies" to never.  Hence why the signature is (x: never) => boolean.

The Fix

Ideally you'd only use string[] or number[] but not both.  (Just looking at the code, it's a little mysterious why id can only be number, but "selected product ids" can be strings, too)

But if you do need to support both strings and numbers, the easiest fix here is to use Array<string | number> instead of string[] | number[]: the single array type doesn't have the issue of trying to union together two .filter signatures.

You can either change your state to be of that type:

const [selectedProductIds, setSelectedProductIds] = useState<Array<string | number>>([]);

This is simple, but has the downside that it will allow arrays of mixed strings and numbers, which may not be desirable.  (e.g. setSelectProductIds(['0', 1, '2'])

If not, you can temporarily cast to Array<string | number>, do the filter, then cast back to string[] | number[].  This is not super clean, but should be safe:

setProductPrices(
    (productPrices as Array<string | number>).filter((p): boolean => !selectedProductIds.includes(p.id)) as (string[] | number[])
);


问:
jQuery.Deferred().then, how to resolve with multiple parameters
So my API expects that when a particular deferred is resolved it gets 2 params.

```<code>fn().done(function(arg1, arg2) {
  console.log(arg1, arg2);
}).fail(function(err) {
  console.error(err);
});
</code>```

Now relating to the fn function above, it needs to first wait for some other deferred to return before resolve.

```<code>function other() {
  // stubbed out to always resolve
  return $.Deferred().resolve().promise();
}

function fn() {
  return other().then(function() {
    return [1, 2];
  });
}
</code>```

But this is not working, because arg1 will come as [1, 2] and arg2 will be undefined. I cannot figure out how to return something from Deferred.then() first success filter function argument so that the resulting piped deferred resolves with multiple arguments.

Of course I can do this:

```<code>function fn() {
  var done = $.Deferred();
  other().done(function(){
    done.resolve(1, 2);
  }).fail(function(){
    done.reject.apply(done, arguments);
  });
  return done.promise();
}
</code>```

But that is not nearly as elegant as using .then() and I now need to worry about the negative failure case API each time even though I know that I'm merely piping the rejected state through.

And yes, I could also change fn() api to resolve with an array, but I am really hoping there is an elegant solution to this.

答:
The callback passed to then can return a new $.Deferred with 2 arguments like this:</p>

```<code>function other() {
  // stubbed out to always resolve
  return $.Deferred().resolve().promise();
}

function fn() {
  return other().then(function() {
    return $.Deferred().resolve(1, 2).promise();
  });
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So my API expects that when a particular deferred is resolved it gets 2 params.

fn().done(function(arg1, arg2) {
  console.log(arg1, arg2);
}).fail(function(err) {
  console.error(err);
});

Now relating to the fn function above, it needs to first wait for some other deferred to return before resolve.

function other() {
  // stubbed out to always resolve
  return $.Deferred().resolve().promise();
}

function fn() {
  return other().then(function() {
    return [1, 2];
  });
}

But this is not working, because arg1 will come as [1, 2] and arg2 will be undefined. I cannot figure out how to return something from Deferred.then() first success filter function argument so that the resulting piped deferred resolves with multiple arguments.

Of course I can do this:

function fn() {
  var done = $.Deferred();
  other().done(function(){
    done.resolve(1, 2);
  }).fail(function(){
    done.reject.apply(done, arguments);
  });
  return done.promise();
}

But that is not nearly as elegant as using .then() and I now need to worry about the negative failure case API each time even though I know that I'm merely piping the rejected state through.

And yes, I could also change fn() api to resolve with an array, but I am really hoping there is an elegant solution to this.

Body:
The callback passed to then can return a new $.Deferred with 2 arguments like this:

function other() {
  // stubbed out to always resolve
  return $.Deferred().resolve().promise();
}

function fn() {
  return other().then(function() {
    return $.Deferred().resolve(1, 2).promise();
  });
}


问:
Using statsmodel estimations with scikit-learn cross validation, is it possible?
I posted this question to Cross Validated forum and later realized may be this would find appropriate audience in stackoverlfow instead.

I am looking for a way I can use the fit object (result) ontained from python statsmodel to feed into cross_val_score of scikit-learn cross_validation method?
The attached link suggests that it may be possible but I have not succeeded.

I am getting the following error

estimator should a be an estimator implementing 'fit' method
  statsmodels.discrete.discrete_model.BinaryResultsWrapper object at
  0x7fa6e801c590 was passed

Refer this link

答:
Following the suggestion of David (which gave me an error, complaining about missing function get_parameters) and the scikit learn documentation, I created the following wrapper for a linear regression.
It has the same interface of sklearn.linear_model.LinearRegression but in addition has also the function summary(), which gives the info about p-values, R2 and other statistics, as in statsmodels.OLS.

```<code>import statsmodels.api as sm
from sklearn.base import BaseEstimator, RegressorMixin
import pandas as pd
import numpy as np

from sklearn.utils.multiclass import check_classification_targets
from sklearn.utils.validation import check_X_y, check_is_fitted, check_array
from sklearn.utils.multiclass import unique_labels
from sklearn.utils.estimator_checks import check_estimator

class MyLinearRegression(BaseEstimator, RegressorMixin):
    def __init__(self, fit_intercept=True):

        self.fit_intercept = fit_intercept

    """
    Parameters
    ------------
    column_names: list
            It is an optional value, such that this class knows
            what is the name of the feature to associate to
            each column of X. This is useful if you use the method
            summary(), so that it can show the feature name for each
            coefficient
    """
    def fit(self, X, y, column_names=() ):

        if self.fit_intercept:
            X = sm.add_constant(X)

        # Check that X and y have correct shape
        X, y = check_X_y(X, y)

        self.X_ = X
        self.y_ = y

        if len(column_names) != 0:
            cols = column_names.copy()
            cols = list(cols)
            X = pd.DataFrame(X)
            cols = column_names.copy()
            cols.insert(0,'intercept')
            print('X ', X)
            X.columns = cols

        self.model_ = sm.OLS(y, X)
        self.results_ = self.model_.fit()
        return self

    def predict(self, X):
        # Check is fit had been called
        check_is_fitted(self, 'model_')

        # Input validation
        X = check_array(X)

        if self.fit_intercept:
            X = sm.add_constant(X)
        return self.results_.predict(X)

    def get_params(self, deep = False):
        return {'fit_intercept':self.fit_intercept}

    def summary(self):
        print(self.results_.summary() )
</code>```

Example of use:

```<code>cols = ['feature1','feature2']
X_train = df_train[cols].values
X_test = df_test[cols].values
y_train = df_train['label']
y_test = df_test['label']
model = MyLinearRegression()
model.fit(X_train, y_train)
model.summary()
model.predict(X_test)
</code>```

If you want to show the names of the columns, you can call

```<code>model.fit(X_train, y_train, column_names=cols)
</code>```

To use it in cross_validation:

```<code>from sklearn.model_selection import cross_val_score
scores = cross_val_score(MyLinearRegression(), X_train, y_train, cv=10, scoring='neg_mean_squared_error')
scores
</code>```

Body:
Following the suggestion of David (which gave me an error, complaining about missing function get_parameters) and the scikit learn documentation, I created the following wrapper for a linear regression.
It has the same interface of sklearn.linear_model.LinearRegression but in addition has also the function summary(), which gives the info about p-values, R2 and other statistics, as in statsmodels.OLS.

import statsmodels.api as sm
from sklearn.base import BaseEstimator, RegressorMixin
import pandas as pd
import numpy as np

from sklearn.utils.multiclass import check_classification_targets
from sklearn.utils.validation import check_X_y, check_is_fitted, check_array
from sklearn.utils.multiclass import unique_labels
from sklearn.utils.estimator_checks import check_estimator

class MyLinearRegression(BaseEstimator, RegressorMixin):
    def __init__(self, fit_intercept=True):

        self.fit_intercept = fit_intercept

    """
    Parameters
    ------------
    column_names: list
            It is an optional value, such that this class knows
            what is the name of the feature to associate to
            each column of X. This is useful if you use the method
            summary(), so that it can show the feature name for each
            coefficient
    """
    def fit(self, X, y, column_names=() ):

        if self.fit_intercept:
            X = sm.add_constant(X)

        # Check that X and y have correct shape
        X, y = check_X_y(X, y)

        self.X_ = X
        self.y_ = y

        if len(column_names) != 0:
            cols = column_names.copy()
            cols = list(cols)
            X = pd.DataFrame(X)
            cols = column_names.copy()
            cols.insert(0,'intercept')
            print('X ', X)
            X.columns = cols

        self.model_ = sm.OLS(y, X)
        self.results_ = self.model_.fit()
        return self

    def predict(self, X):
        # Check is fit had been called
        check_is_fitted(self, 'model_')

        # Input validation
        X = check_array(X)

        if self.fit_intercept:
            X = sm.add_constant(X)
        return self.results_.predict(X)

    def get_params(self, deep = False):
        return {'fit_intercept':self.fit_intercept}

    def summary(self):
        print(self.results_.summary() )

Example of use:

cols = ['feature1','feature2']
X_train = df_train[cols].values
X_test = df_test[cols].values
y_train = df_train['label']
y_test = df_test['label']
model = MyLinearRegression()
model.fit(X_train, y_train)
model.summary()
model.predict(X_test)

If you want to show the names of the columns, you can call

model.fit(X_train, y_train, column_names=cols)

To use it in cross_validation:

from sklearn.model_selection import cross_val_score
scores = cross_val_score(MyLinearRegression(), X_train, y_train, cv=10, scoring='neg_mean_squared_error')
scores


问:
mysql union of 2 tables
I have 2 tables:

```<code>table A (id, user_id, flag)

table B (id, user_id, flag)
</code>```

Here If I take Count of table A it comes as 10 and that of B 5

So Total = 10 + 5 = 15.

```<code>SELECT * FROM table A
LEFT JOIN table B ON table B.user_id = table A.user_id
UNION ALL
SELECT * FROM table A
RIGHT JOIN table B ON table B.user_id = table A.user_id
</code>```

So It should Come 15 instead it showing 50.

答:
You need to make sure the data in your tables are correct.

Table A Should have 15 rows

```<code>SELECT COUNT(*) as 'rowCountTableA' FROM table_a;
</code>```

Table B Should have 5 rows

```<code>SELECT COUNT(*) as 'rowCountTableB' FROM table_b;
</code>```

If your tables are correct and have exactly matching column names you can join them together by specifying asterisks to get all column values.

If however the columns in your table have a few different column names that are in table_a that are not in table_b you must call out the column names instead of using asterisk to get all values.

EXAMPLE:

```<code>SELECT (id,user_id,flag) FROM table_a
UNION ALL
SELECT (id,user_id,flag) FROM table_b
</code>```

Title: mysql union of 2 tables

Body:
I have 2 tables:

table A (id, user_id, flag)

table B (id, user_id, flag)

Here If I take Count of table A it comes as 10 and that of B 5

So Total = 10 + 5 = 15.

SELECT * FROM table A
LEFT JOIN table B ON table B.user_id = table A.user_id
UNION ALL
SELECT * FROM table A
RIGHT JOIN table B ON table B.user_id = table A.user_id

So It should Come 15 instead it showing 50.

Body:
You need to make sure the data in your tables are correct.

Table A Should have 15 rows

SELECT COUNT(*) as 'rowCountTableA' FROM table_a;

Table B Should have 5 rows

SELECT COUNT(*) as 'rowCountTableB' FROM table_b;

If your tables are correct and have exactly matching column names you can join them together by specifying asterisks to get all column values.

If however the columns in your table have a few different column names that are in table_a that are not in table_b you must call out the column names instead of using asterisk to get all values.

EXAMPLE:

SELECT (id,user_id,flag) FROM table_a
UNION ALL
SELECT (id,user_id,flag) FROM table_b


问:
When do I use if/endif versus If{}?
Well the question is self explanatory.

In PHP when do I use the if/endif notation instead of the standard if(something){} notation?

Example:

```<code><?php if($a == 5): ?>
A is equal to 5
<?php endif; ?>
</code>```

Versus:

```<code><?php if($a == 5){ ?>
A is equal to 5
<?php } ?>
</code>```

答:
It is a stylistic choice.  They are analogous and one is not better than another.

The former can be good in certain circumstances because it may be easier to read when mired in the middle of an HTML block set.

Title: When do I use if/endif versus If{}?

Body:
Well the question is self explanatory.

In PHP when do I use the if/endif notation instead of the standard if(something){} notation?

Example:

<?php if($a == 5): ?>
A is equal to 5
<?php endif; ?>

Versus:

<?php if($a == 5){ ?>
A is equal to 5
<?php } ?>


问:
Run kafka producer with a fixed/static list of brokers
Usually the kafka java client (used within Spring boot, but that does not really matter here, I think, just as a side node) uses the boostrap.servers config (which expects a list of broker addresses:port) to establish an initial connection. Afterwards, a metadata request is used to discover all members of the cluster, which are currently registered.

My question now is, how this discovery can be disabled in the java client. I want to have the KafkaProducer use the list of brokers I supply to it as a fixed, static one.

A little bit more background

The platform my Spring application is deployed to, does not allow internet access to any port, except when using an HTTP proxy (443 or 80). The other alternative is to use a TCP proxy, which works similar to this:

The proxy provides a hostname and port an application can connect to

Once connected, the data stream is forwarded to the previously (during the creation of the proxy) named hostname and port

In that way, the platform can control what traffic is coming from who and is going where, which is a security requirement in my organisation. The communication path then looks like:

```<code>----------------------         -------------         -----------------------
| Application client |  <--->  | TCP Proxy |  <--->  | Target (e.g. kafka) |
----------------------         -------------         -----------------------
</code>```

However, this method does not really work with the public kafka cluster I need to talk to, as the kafka broker in the boostrap.servers list (which I can connect to perfectly fine) will return the list of nodes with the public endpoint names I can not connect to (as they're not going through the proxy).

So, instead of using the discovery functionality of the Kafka client, I would like to use a fixed, pre-defined list of brokers, which I can setup to use the TCP proxy. However, I didn't see any solution for that in the API so far and hope for some help here.

I'm aware, that not using this functionality makes it impossible for the application to use the dynamic changes of the kafka cluster state (when a broker goes away and another one is spinned up), however, this is ok in my scenario and all given circumstances.

答:
does not allow internet access to any port, except when using an HTTP proxy (443 or 80).

Have you considered using the Confluent REST Proxy?

The Confluent REST Proxy provides a RESTful interface to a Kafka cluster, making it easy to produce and consume messages, view the state of the cluster, and perform administrative actions without using the native Kafka protocol or clients

Maven coords for a Client

```<code><dependency>
    <groupId>io.confluent</groupId>
    <artifactId>kafka-rest</artifactId>
    <version>5.3.2</version>
</dependency>
</code>```

There is also an envoy proxy solution in the works - https://github.com/envoyproxy/envoy/issues/2852

And another TCP proxy for k8s environments - https://github.com/grepplabs/kafka-proxy

However, exposing NodePorts / headless service ports would be the correct way to expose a k8s kafka cluster

Body:
Usually the kafka java client (used within Spring boot, but that does not really matter here, I think, just as a side node) uses the boostrap.servers config (which expects a list of broker addresses:port) to establish an initial connection. Afterwards, a metadata request is used to discover all members of the cluster, which are currently registered.

My question now is, how this discovery can be disabled in the java client. I want to have the KafkaProducer use the list of brokers I supply to it as a fixed, static one.

A little bit more background

The platform my Spring application is deployed to, does not allow internet access to any port, except when using an HTTP proxy (443 or 80). The other alternative is to use a TCP proxy, which works similar to this:

The proxy provides a hostname and port an application can connect to

Once connected, the data stream is forwarded to the previously (during the creation of the proxy) named hostname and port

In that way, the platform can control what traffic is coming from who and is going where, which is a security requirement in my organisation. The communication path then looks like:

----------------------         -------------         -----------------------
| Application client |  <--->  | TCP Proxy |  <--->  | Target (e.g. kafka) |
----------------------         -------------         -----------------------

However, this method does not really work with the public kafka cluster I need to talk to, as the kafka broker in the boostrap.servers list (which I can connect to perfectly fine) will return the list of nodes with the public endpoint names I can not connect to (as they're not going through the proxy).

So, instead of using the discovery functionality of the Kafka client, I would like to use a fixed, pre-defined list of brokers, which I can setup to use the TCP proxy. However, I didn't see any solution for that in the API so far and hope for some help here.

I'm aware, that not using this functionality makes it impossible for the application to use the dynamic changes of the kafka cluster state (when a broker goes away and another one is spinned up), however, this is ok in my scenario and all given circumstances.

Body:
does not allow internet access to any port, except when using an HTTP proxy (443 or 80).

Have you considered using the Confluent REST Proxy?

The Confluent REST Proxy provides a RESTful interface to a Kafka cluster, making it easy to produce and consume messages, view the state of the cluster, and perform administrative actions without using the native Kafka protocol or clients

Maven coords for a Client

<dependency>
    <groupId>io.confluent</groupId>
    <artifactId>kafka-rest</artifactId>
    <version>5.3.2</version>
</dependency>

There is also an envoy proxy solution in the works - https://github.com/envoyproxy/envoy/issues/2852

And another TCP proxy for k8s environments - https://github.com/grepplabs/kafka-proxy

However, exposing NodePorts / headless service ports would be the correct way to expose a k8s kafka cluster


问:
Enabling / Disabling Features in a Laravel App
I'm building a Laravel app, which has a number of various features. I want to be able to enable or disable them depending on a particular domain's requirement. Currently, I have in my config a series of flags such as:

```<code>'is_feature_1_enabled' => true,
'is_feature_2_enabled' => false,
</code>```

... and so on.

Then in my controllers and views, I check those config values to see whether or not I should be displaying something, allowing certain actions, etc. My app is starting to get polluted with these kinds of checks everywhere.

Is there a best practice method of managing features in a Laravel app?

答:
What I did in my case was creating a new table on the database, you could call it Domains for instance.

Add all the specific features, those which could be shown on some domains but not in the rest, as columns for that table as bit for boolean values. Like, in my case, allow_multiple_bookings, use_company_card... whatever.

Then, consider creating a class Domain and its respective repository, and just ask these values on your code, trying to push as much as possible that logic into your domain (your model, application services, etc).

For instance, I would not do the check on the controller method for RequestBooking if the domain which is requesting a booking can request only one or more.

Instead I do it on a RequestBookingValidatorService which can check if the booking datetime has passed, the user has an enabled credit card, ... or the Domain which this action comes from is allowed to request more than one booking (and then if it already has any).

This adds the convenience of readability, as you have pushed this decision to your application services. Also, I find that whenever I need a new feature I can use Laravel (or Symfony) migrations to add that feature on the table and I could even update its rows (your domains) with the values I want on the same commit I coded.

Body:
I'm building a Laravel app, which has a number of various features. I want to be able to enable or disable them depending on a particular domain's requirement. Currently, I have in my config a series of flags such as:

'is_feature_1_enabled' => true,
'is_feature_2_enabled' => false,

... and so on.

Then in my controllers and views, I check those config values to see whether or not I should be displaying something, allowing certain actions, etc. My app is starting to get polluted with these kinds of checks everywhere.

Is there a best practice method of managing features in a Laravel app?


问:
Boolean operators and Induction
Let @ denote the binary boolean operator defined by the right-hand side below:
p @ q = (p ^ ¬q)

(b) Is the set of operators {@, ¬} complete? Explain in detail.

(c) Prove by induction that any propositional formula in a single propositional variable p that uses only the boolean operator @ (or no operators at all) is equivalent
to either the truth value False or to the single propositional variable p. Explain.

答:
(b) Yes.

~(p @ q) = ~(p & ~q) = ~p | q = p -> q.

p @ ~q = p & ~~q = p & q.

~(~p @ q) = ~(~p & ~q) = ~~p | ~~q = p | q.

(c) An inductive proof might look like the following:

Base case: p is equivalent to p, while p @ p is False since p & ~p is a contradiction.

Induction hypothesis: Assume all propositions up to length k operations containing only p and @ are equivalent either to p or to False.

Induction step: Every proposition containing only p and @ can be decomposed into a formula of the form ((x) @ (y)), where x and y are formulas of length less than or equal to k. By the induction hypothesis, both x and y are equivalent to either p or False. There are four cases:

x = p, y = p; then x @ y = False, as required;

x = p, y = False; then x @ y = p, as required;

x = False, y = p: then x @ y = False, as required;

x = False, y = False: then x @ y = False, as required.

In all four cases we find that ((x) @ (y)) must be equivalent either to p or to False.

Title: Boolean operators and Induction


问:
oracle update with while loop
I need to update table b with data from table A please advise,
please the case

table A as below

```<code>|ID    |       balance|
-----------------------
|10    |       360    |
-----------------------
|20    |       300    |
-----------------------
</code>```

table B as below

```<code>----------------------------------------------------------
|ID   |  count   |    value   |  settlementvalue |  mode |
----------------------------------------------------------

10     1           100        100
10     2           100        100
10     3           100        null
10     4           100        null
10     5           100        null
10     6           100        null
10     7           100        null
10     8           100        null
10     9           100        null
10     10          100        null

20     1           100        100
20     2           100        null
20     3           100        null
20     4           100        null
20     5           100        null
20     6           100        null
20     7           100        null
20     8           100        null
20     9           100        null
20    10           100        null
</code>```

i need to read the balance from table A and update the first null value in settlement value in table B with value in column value and then decrease the balance then we go to update the next row until the balance become less than the value we will put it in mod column

the final result should be as below:
table B as below

```<code>ID     count       value     settlementvalue   mode
10     1           100        100
10     2           100        100
10     3           100        100
10     4           100        100
10     5           100        100
10     6           100        null              60
10     7           100        null
10     8           100        null
10     9           100        null
10     10          100        null

20     1           100        100
20     2           100        100
20     3           100        100
20     4           100        100
20     5           100        null
20     6           100        null
20     7           100        null
20     8           100        null
</code>```

答:
You can do it this way, with cte and windows functions. You won't need while loops for this.

```<code>    with _modeTbl as
(
select b.*, a.balance ,
balance - sum(value) OVER (PARTITION BY a.ID ORDER BY count ROWS BETWEEN UNBOUNDED PRECEDING and CURRENT ROW) as _mode
from tableA a inner join tableB b on a.ID = b.ID where settlementvalue is null
),
finalcte as
(
select ID, count, value
,case when _mode > = 0 then value else null end as settlementvalue
,case when _mode < value and _mode > 0 then _mode else null end as mode
from _modeTbl
union
select *
from tableB where settlementvalue is not null
)
select ID, count, value, settlementvalue,
lag(mode) OVER (PARTITION BY ID ORDER BY ID) as mode
from finalcte
</code>```

Output is:

```<code>ID  count   value   settlementvalue mode
10     1    100      100            NULL
10     2    100      100            NULL
10     3    100      100            NULL
10     4    100      100            NULL
10     5    100      100            NULL
10     6    100      NULL           60
10     7    100      NULL           NULL
10     8    100      NULL           NULL
10     9    100      NULL           NULL
10     10   100      NULL           NULL
20     1    100      100            NULL
20     2    100      100            NULL
20     3    100      100            NULL
20     4    100      100            NULL
20     5    100      NULL           NULL
20     6    100      NULL           NULL
20     7    100      NULL           NULL
20     8    100      NULL           NULL
20     9    100      NULL           NULL
20     10   100      NULL           NULL
</code>```

Title: oracle update with while loop

Body:
I need to update table b with data from table A please advise,
please the case

table A as below

|ID    |       balance|
-----------------------
|10    |       360    |
-----------------------
|20    |       300    |
-----------------------

table B as below

----------------------------------------------------------
|ID   |  count   |    value   |  settlementvalue |  mode |
----------------------------------------------------------

10     1           100        100
10     2           100        100
10     3           100        null
10     4           100        null
10     5           100        null
10     6           100        null
10     7           100        null
10     8           100        null
10     9           100        null
10     10          100        null

20     1           100        100
20     2           100        null
20     3           100        null
20     4           100        null
20     5           100        null
20     6           100        null
20     7           100        null
20     8           100        null
20     9           100        null
20    10           100        null

i need to read the balance from table A and update the first null value in settlement value in table B with value in column value and then decrease the balance then we go to update the next row until the balance become less than the value we will put it in mod column

the final result should be as below:
table B as below

ID     count       value     settlementvalue   mode
10     1           100        100
10     2           100        100
10     3           100        100
10     4           100        100
10     5           100        100
10     6           100        null              60
10     7           100        null
10     8           100        null
10     9           100        null
10     10          100        null

20     1           100        100
20     2           100        100
20     3           100        100
20     4           100        100
20     5           100        null
20     6           100        null
20     7           100        null
20     8           100        null

Body:
You can do it this way, with cte and windows functions. You won't need while loops for this.

    with _modeTbl as
(
select b.*, a.balance ,
balance - sum(value) OVER (PARTITION BY a.ID ORDER BY count ROWS BETWEEN UNBOUNDED PRECEDING and CURRENT ROW) as _mode
from tableA a inner join tableB b on a.ID = b.ID where settlementvalue is null
),
finalcte as
(
select ID, count, value
,case when _mode > = 0 then value else null end as settlementvalue
,case when _mode < value and _mode > 0 then _mode else null end as mode
from _modeTbl
union
select *
from tableB where settlementvalue is not null
)
select ID, count, value, settlementvalue,
lag(mode) OVER (PARTITION BY ID ORDER BY ID) as mode
from finalcte

Output is:

ID  count   value   settlementvalue mode
10     1    100      100            NULL
10     2    100      100            NULL
10     3    100      100            NULL
10     4    100      100            NULL
10     5    100      100            NULL
10     6    100      NULL           60
10     7    100      NULL           NULL
10     8    100      NULL           NULL
10     9    100      NULL           NULL
10     10   100      NULL           NULL
20     1    100      100            NULL
20     2    100      100            NULL
20     3    100      100            NULL
20     4    100      100            NULL
20     5    100      NULL           NULL
20     6    100      NULL           NULL
20     7    100      NULL           NULL
20     8    100      NULL           NULL
20     9    100      NULL           NULL
20     10   100      NULL           NULL


问:
VBA: Finding a date
I want to find a date in a range, or rather part of a date. For example, I have the month and the year from a user input, stored in two variables userInputMonth and userInputYear, and would now like to find out in which row they appear.

```<code>Option Explicit

Sub CheckDate()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim userInputYear As String
    Dim userInputMonth As String
    Dim rngDate As Range
    Dim foundCell As Range

    Set wb = ThisWorkbook
    Set ws = wb.Sheets(2)
    userInputYear = Right(wb.Sheets(1).Range("A1").Value, 4) 'e.g. "2019"
    userInputMonth = Mid(wb.Sheets(1).Range("A1").Value, 2, 2) 'e.g. "09"

    Set rngDate = ws.Range("A3:A11")
    Set foundCell = rngDate.Find("??." & userInputMonth & "." & userInputYear)
    Debug.Print foundCell.Row '-> error

   '=====Trying out stuff=====
   Set foundCell = rngDate.Find(userInputMonth)
   Debug.Print foundCell.Row 'works
   Set foundCell = rngDate.Find(userInputMonth & ".")
   Debug.Print foundCell.Row '-> error
   Set foundCell = rngDate.Find("12.2019")
   Debug.Print foundCell.Row '-> error

End Sub
</code>```

I guess the format is the problem, but how do I deal with this, but I don't know how to apply something like CStr to this issue

edit: The data in rngDate looks like this: 31.12.2019 (formatted as date). A1 is text (e.g. A12 2019).

答: In my opinion you have to decide which type of data you want to manipulate. Do you prefer working with dates or strings ? After that choice, it will be easier to determine which operations will be necessary and which method or function will be applicable (you cannot do the same thing with dates or strings). Cheers</p>

Title: VBA: Finding a date

Body:
I want to find a date in a range, or rather part of a date. For example, I have the month and the year from a user input, stored in two variables userInputMonth and userInputYear, and would now like to find out in which row they appear.

Option Explicit

Sub CheckDate()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim userInputYear As String
    Dim userInputMonth As String
    Dim rngDate As Range
    Dim foundCell As Range

    Set wb = ThisWorkbook
    Set ws = wb.Sheets(2)
    userInputYear = Right(wb.Sheets(1).Range("A1").Value, 4) 'e.g. "2019"
    userInputMonth = Mid(wb.Sheets(1).Range("A1").Value, 2, 2) 'e.g. "09"

    Set rngDate = ws.Range("A3:A11")
    Set foundCell = rngDate.Find("??." & userInputMonth & "." & userInputYear)
    Debug.Print foundCell.Row '-> error

   '=====Trying out stuff=====
   Set foundCell = rngDate.Find(userInputMonth)
   Debug.Print foundCell.Row 'works
   Set foundCell = rngDate.Find(userInputMonth & ".")
   Debug.Print foundCell.Row '-> error
   Set foundCell = rngDate.Find("12.2019")
   Debug.Print foundCell.Row '-> error

End Sub

I guess the format is the problem, but how do I deal with this, but I don't know how to apply something like CStr to this issue

edit: The data in rngDate looks like this: 31.12.2019 (formatted as date). A1 is text (e.g. A12 2019).


问:
Label Mapping image to corresponding name by using a dictionary
I have a dataset with flower images called train_data. I also have a dictionary called class_names with the integer coded labels to the actual names of the flowers. For extra clarity here is a sample of how the class_names dictionary outputs:

```<code>Output:
{'21': 'fire lily',
'3': 'canterbury bells',
'45': 'bolero deep blue',
 '1': 'pink primrose',
'34': 'mexican aster'}
</code>```

The objective is to Plot one image from the training set. Set the title of the plot to the corresponding class name. For example, if a flower is outputted it should take that of its label and it's class name.
The code does not output an error and does plot the label of the image. However, it does not plot the class name correctly. Rather it sets the name to None. As seen in the image below:

Assistance would be appreciated to get the label and name of the respectful image. Here is my code below:

```<code>for image, label in train_data.take(1):
image = image.numpy().squeeze()
label = label.numpy()
plt.imshow(image, cmap=plt.cm.binary)
plt.title(class_names.get(label))
# Display image
plt.show()
print('The label of this image is:', label)
print('The class name of this image is:', class_names.get(label))
</code>```

答:
could you try printing label once. is it giving intezer or string number? Because ur dictionary keys are strings. and if a key is not present in the dictionary, the get method returns None and no error

```<code>>>> a = {1:'a'}
>>> a.get(1)
'a'
>>> a.get(2)
>>> a[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 2
>>>
</code>```

Body:
I have a dataset with flower images called train_data. I also have a dictionary called class_names with the integer coded labels to the actual names of the flowers. For extra clarity here is a sample of how the class_names dictionary outputs:

Output:
{'21': 'fire lily',
'3': 'canterbury bells',
'45': 'bolero deep blue',
 '1': 'pink primrose',
'34': 'mexican aster'}

The objective is to Plot one image from the training set. Set the title of the plot to the corresponding class name. For example, if a flower is outputted it should take that of its label and it's class name.
The code does not output an error and does plot the label of the image. However, it does not plot the class name correctly. Rather it sets the name to None. As seen in the image below:

Assistance would be appreciated to get the label and name of the respectful image. Here is my code below:

for image, label in train_data.take(1):
image = image.numpy().squeeze()
label = label.numpy()
plt.imshow(image, cmap=plt.cm.binary)
plt.title(class_names.get(label))
# Display image
plt.show()
print('The label of this image is:', label)
print('The class name of this image is:', class_names.get(label))

Body:
could you try printing label once. is it giving intezer or string number? Because ur dictionary keys are strings. and if a key is not present in the dictionary, the get method returns None and no error

>>> a = {1:'a'}
>>> a.get(1)
'a'
>>> a.get(2)
>>> a[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 2
>>>


问:
How to check if an object is a generator object in python?
In python, how do I check if an object is a generator object?

Trying this -

```<code>>>> type(myobject, generator)
</code>```

gives the error -

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'generator' is not defined
</code>```

(I know I can check if the object has a next method for it to be a generator, but I want some way using which I can determine the type of any object, not just generators.)

答:
You could use the Iterator or more specifically, the Generator from the typing module.

```<code>from typing import Generator, Iterator
g = (i for i in range(1_000_000))
print(type(g))
print(isinstance(g, Generator))
print(isinstance(g, Iterator))
</code>```

result:

```<code><class 'generator'>
True
True
</code>```

Body:
In python, how do I check if an object is a generator object?

Trying this -

>>> type(myobject, generator)

gives the error -

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'generator' is not defined

(I know I can check if the object has a next method for it to be a generator, but I want some way using which I can determine the type of any object, not just generators.)

Body:
You could use the Iterator or more specifically, the Generator from the typing module.

from typing import Generator, Iterator
g = (i for i in range(1_000_000))
print(type(g))
print(isinstance(g, Generator))
print(isinstance(g, Iterator))

result:

<class 'generator'>
True
True


问:
CSPack 1.4 crashes with OutOfMemoryException
I'm having a problem creating a package for a web role that totals up to 380 megabytes on disk. I can get CSPack to run fine when specifying the /copyOnly flag, but as soon as I try to create the actual package file I get an OutOfMemoryException. The problem started after I added around 350 megabytes of static content to the web role project.

I've already found a similar question here on Stack Overflow, but even with all the content set to "Do Not Copy," I still get the same issue with CSPack crashing. Just to verify that the static content is what is causing an issue, I excluded it from my project in Visual Studio and CSPack ran fine from the command line.

Here's the command I'm executing from cmd.exe:

```<code>"C:\Program Files\Windows Azure SDK\v1.4\bin\cspack"
BizBlimp.Azure\ServiceDefinition.csdef /role:BizBlimp;Build\BizBlimp
/role:BizBlimp.QueueWorker;Build\BizBlimp.QueueWorker;Biz
Blimp.QueueWorker.dll /sites:BizBlimp;Web;Build\BizBlimp /rolePropertiesFile:Biz
Blimp;properties.txt /rolePropertiesFile:BizBlimp.QueueWorker;properties.txt /ou
t:Build\BizBlimp.Azure.cpkg
</code>```

And here's my project file for my web role: https://gist.github.com/88e776bb611cf6a8521e

I've been banging my head up against this problem for the last couple work days, so any help would be greatly appreciated.

Edit: Link to the same issue on the Microsoft Azure Forums. Looks like this is gaining some attention from an MSFT employee.

答: That is quite a lot of static content.  Every time you update your application you'll have to upload that 350mb of stuff.  Have you considered storing the static content in blob storage?  It looks like most of it is images and would sit quite nicely there. I'm sorry this doesn't solve your crash issue, but it will probably make your life easier in the long run.</p>

Body:
I'm having a problem creating a package for a web role that totals up to 380 megabytes on disk. I can get CSPack to run fine when specifying the /copyOnly flag, but as soon as I try to create the actual package file I get an OutOfMemoryException. The problem started after I added around 350 megabytes of static content to the web role project.

I've already found a similar question here on Stack Overflow, but even with all the content set to "Do Not Copy," I still get the same issue with CSPack crashing. Just to verify that the static content is what is causing an issue, I excluded it from my project in Visual Studio and CSPack ran fine from the command line.

Here's the command I'm executing from cmd.exe:

"C:\Program Files\Windows Azure SDK\v1.4\bin\cspack"
BizBlimp.Azure\ServiceDefinition.csdef /role:BizBlimp;Build\BizBlimp
/role:BizBlimp.QueueWorker;Build\BizBlimp.QueueWorker;Biz
Blimp.QueueWorker.dll /sites:BizBlimp;Web;Build\BizBlimp /rolePropertiesFile:Biz
Blimp;properties.txt /rolePropertiesFile:BizBlimp.QueueWorker;properties.txt /ou
t:Build\BizBlimp.Azure.cpkg

And here's my project file for my web role: https://gist.github.com/88e776bb611cf6a8521e

I've been banging my head up against this problem for the last couple work days, so any help would be greatly appreciated.

Edit: Link to the same issue on the Microsoft Azure Forums. Looks like this is gaining some attention from an MSFT employee.


问:
Where is dask.datasets?
I'm trying to follow some examples on Dask's website for Bags and DataFrames. The examples require me to use datasets: dask.datasets but I didn't get datasets with my installation as far as I can tell, i.e. I get an error telling me dask has no attribute datasets, and I don't see it in the dask folder.

I can't find help using Google or Dask's website. Where is datasets?

https://examples.dask.org/bag.html
https://examples.dask.org/dataframe.html

Thanks in advance.

答:
dask.datasets was introduced in version 0.18.2, so check your version to make sure you have 0.18.2 or later. To install the latest release (as of today), run:

```<code>pip install dask==2.10.1
</code>```

Title: Where is dask.datasets?

Body:
dask.datasets was introduced in version 0.18.2, so check your version to make sure you have 0.18.2 or later. To install the latest release (as of today), run:

pip install dask==2.10.1


问:
Does Sagemaker pass any data other than the model itself between training and prediction steps?
I'm building a Scikit-learn model on Sagemaker.

I'd like to reference the data used in training in my predict_fn. (Instead of the indices returned from NNS, I'd like to return the names and data of each neighbor.)

I know this can be done by writing/reading from S3, as in https://aws.amazon.com/blogs/machine-learning/associating-prediction-results-with-input-data-using-amazon-sagemaker-batch-transform/ , but was wondering if there were more elegant solutions.

Are there other ways to make the data used in the training job available to the prediction function?

Edit: Using the advice from the accepted solution I was able to pass data as a dict.

```<code>model = nn.fit(train_data)

model_dict = {
   "model": model,
   "reference": train_data
}

joblib.dump(model_dict, path)
</code>```

predict_fn:

```<code>def predict_fn(input_data, model_dict):
   model = model_dict["model"]
   reference = model_dict["reference"]
</code>```

答:
you can bring to the endpoint instance (either in the model.tar.gz or via later download) a file storing the mapping between indexes and record names; this way you can translate from neighbor IDs to record names on the fly in the predict_fn or in the output_fn. For giant indexes this mapping (along with other metadata) can be in an external database too (eg dynamoDB, redis)

the link you attach (SageMaker Batch Transform) is quite a different concept; it's for instantiating ephemeral fleet of machine(s) to run a one-time prediction task with input data in S3 and results written to s3. You question seem to refer to the alternative, permanent, real-time endpoint deployment mode.

Body:
I'm building a Scikit-learn model on Sagemaker.

I'd like to reference the data used in training in my predict_fn. (Instead of the indices returned from NNS, I'd like to return the names and data of each neighbor.)

I know this can be done by writing/reading from S3, as in https://aws.amazon.com/blogs/machine-learning/associating-prediction-results-with-input-data-using-amazon-sagemaker-batch-transform/ , but was wondering if there were more elegant solutions.

Are there other ways to make the data used in the training job available to the prediction function?

Edit: Using the advice from the accepted solution I was able to pass data as a dict.

model = nn.fit(train_data)

model_dict = {
   "model": model,
   "reference": train_data
}

joblib.dump(model_dict, path)

predict_fn:

def predict_fn(input_data, model_dict):
   model = model_dict["model"]
   reference = model_dict["reference"]


问:
Reduce a number down to a static set of numbers
Okay, so I have a Google Sheet that I need to reduce a number down to a specific set of 4 numbers.  Then count how many times those numbers occur.

For example:

The numbers it breaks down to:  1, 2, 3, 4

Disregard their individual values other than for the purpose of being broken down.

Now take the number 17.

```<code>Count+Add 1, 2, 3, 4, 1, 2, 3 = 7 r1
</code>```

Take number 12

```<code>Count+Add 1, 2, 3, 4, 1 =  r1
</code>```

The remainder is rounded DOWN

So, basically, it breaks down Cell A1 into a count of how many sequences it takes to reach the total of the number in A1, rounddown.

答:
Seems odd but...

Your sequence adds to 10, so your number tens place and above times 4 is your first element.  Then if the ones digit is between 6 and 9 you add 3, 3 to 5 add 2, or 1 to 2 add 1.  There is probably a more elegant formula that this...

=(INT(A1/10)*4)+IF(MOD(A1,10)>0,1,0)+IF(MOD(A1,10)>3,1,0)+IF(MOD(A1,10)>5,1,0)

Body:
Okay, so I have a Google Sheet that I need to reduce a number down to a specific set of 4 numbers.  Then count how many times those numbers occur.

For example:

The numbers it breaks down to:  1, 2, 3, 4

Disregard their individual values other than for the purpose of being broken down.

Now take the number 17.

Count+Add 1, 2, 3, 4, 1, 2, 3 = 7 r1

Take number 12

Count+Add 1, 2, 3, 4, 1 =  r1

The remainder is rounded DOWN

So, basically, it breaks down Cell A1 into a count of how many sequences it takes to reach the total of the number in A1, rounddown.


问:
What is UPCRTD attribute in IBMi AS400?
Could anyone tell me what is does UPCRTD attribute mean in IBMi AS400 system?
I guess this is a user profile creation date-time, but I didn't find any official documentation which simply says, that UPCRTD means user profile creation date time.
Can anyone please refer any document I can find useful?</p>

答: UPRCRTD field is User Profile CReaTe Date</p>

Title: What is UPCRTD attribute in IBMi AS400?


问:
How to pretty print nested dictionaries?
How can I pretty print a dictionary with depth of ~4 in Python? I tried pretty printing with pprint(), but it did not work:

```<code>import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)
</code>```

I simply want an indentation ("\t") for each nesting, so that I get something like this:

```<code>key1
    value1
    value2
    key2
       value1
       value2
</code>```

etc.

How can I do this?

答:
This is what I came up with while working on a class that needed to write a dictionary in a .txt file:

```<code>@staticmethod
def _pretty_write_dict(dictionary):

    def _nested(obj, level=1):
        indentation_values = "\t" * level
        indentation_braces = "\t" * (level - 1)
        if isinstance(obj, dict):
            return "{\n%(body)s%(indent_braces)s}" % {
                "body": "".join("%(indent_values)s\'%(key)s\': %(value)s,\n" % {
                    "key": str(key),
                    "value": _nested(value, level + 1),
                    "indent_values": indentation_values
                } for key, value in obj.items()),
                "indent_braces": indentation_braces
            }
        if isinstance(obj, list):
            return "[\n%(body)s\n%(indent_braces)s]" % {
                "body": "".join("%(indent_values)s%(value)s,\n" % {
                    "value": _nested(value, level + 1),
                    "indent_values": indentation_values
                } for value in obj),
                "indent_braces": indentation_braces
            }
        else:
            return "\'%(value)s\'" % {"value": str(obj)}

    dict_text = _nested(dictionary)
    return dict_text
</code>```

Now, if we have a dictionary like this:

```<code>some_dict = {'default': {'ENGINE': [1, 2, 3, {'some_key': {'some_other_key': 'some_value'}}], 'NAME': 'some_db_name', 'PORT': '', 'HOST': 'localhost', 'USER': 'some_user_name', 'PASSWORD': 'some_password', 'OPTIONS': {'init_command': 'SET foreign_key_checks = 0;'}}}
</code>```

And we do:

```<code>print(_pretty_write_dict(some_dict))
</code>```

We get:

```<code>{
    'default': {
        'ENGINE': [
            '1',
            '2',
            '3',
            {
                'some_key': {
                    'some_other_key': 'some_value',
                },
            },
        ],
        'NAME': 'some_db_name',
        'OPTIONS': {
            'init_command': 'SET foreign_key_checks = 0;',
        },
        'HOST': 'localhost',
        'USER': 'some_user_name',
        'PASSWORD': 'some_password',
        'PORT': '',
    },
}
</code>```

Body:
How can I pretty print a dictionary with depth of ~4 in Python? I tried pretty printing with pprint(), but it did not work:

import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)

I simply want an indentation ("\t") for each nesting, so that I get something like this:

key1
    value1
    value2
    key2
       value1
       value2

etc.

How can I do this?

Body:
This is what I came up with while working on a class that needed to write a dictionary in a .txt file:

@staticmethod
def _pretty_write_dict(dictionary):

    def _nested(obj, level=1):
        indentation_values = "\t" * level
        indentation_braces = "\t" * (level - 1)
        if isinstance(obj, dict):
            return "{\n%(body)s%(indent_braces)s}" % {
                "body": "".join("%(indent_values)s\'%(key)s\': %(value)s,\n" % {
                    "key": str(key),
                    "value": _nested(value, level + 1),
                    "indent_values": indentation_values
                } for key, value in obj.items()),
                "indent_braces": indentation_braces
            }
        if isinstance(obj, list):
            return "[\n%(body)s\n%(indent_braces)s]" % {
                "body": "".join("%(indent_values)s%(value)s,\n" % {
                    "value": _nested(value, level + 1),
                    "indent_values": indentation_values
                } for value in obj),
                "indent_braces": indentation_braces
            }
        else:
            return "\'%(value)s\'" % {"value": str(obj)}

    dict_text = _nested(dictionary)
    return dict_text

Now, if we have a dictionary like this:

some_dict = {'default': {'ENGINE': [1, 2, 3, {'some_key': {'some_other_key': 'some_value'}}], 'NAME': 'some_db_name', 'PORT': '', 'HOST': 'localhost', 'USER': 'some_user_name', 'PASSWORD': 'some_password', 'OPTIONS': {'init_command': 'SET foreign_key_checks = 0;'}}}

And we do:

print(_pretty_write_dict(some_dict))

We get:

{
    'default': {
        'ENGINE': [
            '1',
            '2',
            '3',
            {
                'some_key': {
                    'some_other_key': 'some_value',
                },
            },
        ],
        'NAME': 'some_db_name',
        'OPTIONS': {
            'init_command': 'SET foreign_key_checks = 0;',
        },
        'HOST': 'localhost',
        'USER': 'some_user_name',
        'PASSWORD': 'some_password',
        'PORT': '',
    },
}


问:
Why is my dynamically-generated oval becoming a square?
Thought i had everything looking ok.

https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html

function doit() {
 drawOval(100, 150, 90, 90);
 myOval = document.getElementById("newdiv");
}

function drawOval(left, top, width, height) {
 if (document.createElement) {
   newdiv=document.createElement("div");
   newdiv.style.position="absolute";
   newdiv.style.left = left+"px";
   newdiv.style.top  = top+"px";
   newdiv.style.width = width+"px";
   newdiv.style.height = height+"px";
   newdiv.style.backgroundColor = 'red';
   newdiv.style.visibility = 'visible';
   newdiv.id = 'newdiv';
   document.body.appendChild(newdiv);
   }
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" onClick="doit()" value="Do it"></code>```

Any ideas?

答:
First of all,  you are mixing java and javascript. both are different programming languages. if you want to draw oval you can just update your code following way:

function doit() {
 drawOval(160,80,50);
 myOval = document.getElementById("newdiv");
}

function drawOval(width, height, radius) {
 if (document.createElement) {
   newdiv=document.createElement("div");
   newdiv.style.width = width+"px";
   newdiv.style.height = height+"px";
   newdiv.style.backgroundColor = 'red';
   newdiv.style.visibility = 'visible';
   newdiv.style.borderRadius = radius+"%"
   newdiv.id = 'newdiv';
   document.body.appendChild(newdiv);
   }
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" onClick="doit()" value="Do it"></code>```

Body:
Thought i had everything looking ok.

https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html

function doit() {
 drawOval(100, 150, 90, 90);
 myOval = document.getElementById("newdiv");
}

function drawOval(left, top, width, height) {
 if (document.createElement) {
   newdiv=document.createElement("div");
   newdiv.style.position="absolute";
   newdiv.style.left = left+"px";
   newdiv.style.top  = top+"px";
   newdiv.style.width = width+"px";
   newdiv.style.height = height+"px";
   newdiv.style.backgroundColor = 'red';
   newdiv.style.visibility = 'visible';
   newdiv.id = 'newdiv';
   document.body.appendChild(newdiv);
   }
 }

<input type="button" onClick="doit()" value="Do it">

Any ideas?

Body:
First of all,  you are mixing java and javascript. both are different programming languages. if you want to draw oval you can just update your code following way:

function doit() {
 drawOval(160,80,50);
 myOval = document.getElementById("newdiv");
}

function drawOval(width, height, radius) {
 if (document.createElement) {
   newdiv=document.createElement("div");
   newdiv.style.width = width+"px";
   newdiv.style.height = height+"px";
   newdiv.style.backgroundColor = 'red';
   newdiv.style.visibility = 'visible';
   newdiv.style.borderRadius = radius+"%"
   newdiv.id = 'newdiv';
   document.body.appendChild(newdiv);
   }
 }

<input type="button" onClick="doit()" value="Do it">


问:
Calculated MySQL result
I have a database of MMA fighters and their fights, stored in two tables: fighter and fight.

I want to query the database with a given figher id and get a result in rows like this:

```<code>Result | Record | Weight| Opponent| Opponent Record | Opponent Weight | Method | Date | Round | Time
</code>```

The 4 last columns are pretty straight forward, but the other columns are tricky since I don't know if the given fighter id is fighter1 or fighter2:

Result should be taken from fight.winner, which has the values "fighter1", "fighter2", "TBD", "D" or "NC". The result needs to be calculated based on if the given fighter id is fighter1 or fighter2, so it shows either "W", "L", "TBD", "D" or "NC".

Record and Opponent Record should be taken from fight.fighter1_record_after_result or fight.fighter2_record_after_result, depending on if the given fighter id is fighter1 or fighter2.

Weight and Opponent Weight should be taken from fight.fighter1_weight or fight.fighter2_weight, depending on if the given fighter id is fighter1 or fighter2.

Opponent should be taken from fighter.name. Who should be regarded opponent, depends on wether the given fighter id is fighter1 or fighter2.

Data structure and sample data at DB Fiddle: https://www.db-fiddle.com/f/5LjJqEM6yMYuShZybcsrJ5/0

答:
union all might come handy here: instead of implementing complicated conditional logic in a single query, we can combine the result sets of two queries, that seach for the targer fighter in either column fighter1 or column fighter2:

```<code>select
    case t.winner
        when 'fighter1' then 'W'
        when 'fighter2' then 'L'
        else t.winner
    end result,
    t.fighter1_record_after_result record,
    t.fighter1_weight weight,
    r.name opponent,
    t.fighter2_record_after_result oppononed_record,
    t.fighter2_weight opponent_weight,
    t.method,
    t.date,
    t.round,
    t.time
from fight t
left join fighter r on r.id = t.fighter2
where t.fighter1 = 64
union all
select
    case t.winner
        when 'fighter2' then 'W'
        when 'fighter1' then 'L'
        else t.winner
    end,
    t.fighter2_record_after_result,
    t.fighter2_weight,
    r.name,
    t.fighter1_record_after_result,
    t.fighter1_weight,
    t.method,
    t.date,
    t.round,
    t.time
from fight t
left join fighter r on r.id = t.fighter1
where t.fighter2 = 64
</code>```

Both parameters should be given the value of the fighter that you are generating the report for.

Title: Calculated MySQL result

Body:
I have a database of MMA fighters and their fights, stored in two tables: fighter and fight.

I want to query the database with a given figher id and get a result in rows like this:

Result | Record | Weight| Opponent| Opponent Record | Opponent Weight | Method | Date | Round | Time

The 4 last columns are pretty straight forward, but the other columns are tricky since I don't know if the given fighter id is fighter1 or fighter2:

Result should be taken from fight.winner, which has the values "fighter1", "fighter2", "TBD", "D" or "NC". The result needs to be calculated based on if the given fighter id is fighter1 or fighter2, so it shows either "W", "L", "TBD", "D" or "NC".

Record and Opponent Record should be taken from fight.fighter1_record_after_result or fight.fighter2_record_after_result, depending on if the given fighter id is fighter1 or fighter2.

Weight and Opponent Weight should be taken from fight.fighter1_weight or fight.fighter2_weight, depending on if the given fighter id is fighter1 or fighter2.

Opponent should be taken from fighter.name. Who should be regarded opponent, depends on wether the given fighter id is fighter1 or fighter2.

Data structure and sample data at DB Fiddle: https://www.db-fiddle.com/f/5LjJqEM6yMYuShZybcsrJ5/0

Body:
union all might come handy here: instead of implementing complicated conditional logic in a single query, we can combine the result sets of two queries, that seach for the targer fighter in either column fighter1 or column fighter2:

select
    case t.winner
        when 'fighter1' then 'W'
        when 'fighter2' then 'L'
        else t.winner
    end result,
    t.fighter1_record_after_result record,
    t.fighter1_weight weight,
    r.name opponent,
    t.fighter2_record_after_result oppononed_record,
    t.fighter2_weight opponent_weight,
    t.method,
    t.date,
    t.round,
    t.time
from fight t
left join fighter r on r.id = t.fighter2
where t.fighter1 = 64
union all
select
    case t.winner
        when 'fighter2' then 'W'
        when 'fighter1' then 'L'
        else t.winner
    end,
    t.fighter2_record_after_result,
    t.fighter2_weight,
    r.name,
    t.fighter1_record_after_result,
    t.fighter1_weight,
    t.method,
    t.date,
    t.round,
    t.time
from fight t
left join fighter r on r.id = t.fighter1
where t.fighter2 = 64

Both parameters should be given the value of the fighter that you are generating the report for.


答:
I mostly use if/endif when stopping and starting the php code block in between, so nearly always when raw html is being outputted.

For example:

```<code><?php if ($n == 3): ?>
Lorem ipsum.
<?php endif; ?>
</code>```

This looks, at least in my opinion, better than the following:

```<code><?php if ($n == 3) { ?>
Lorem ipsum.
<?php } ?>
</code>```

Title: When do I use if/endif versus If{}?

Body:
Well the question is self explanatory.

In PHP when do I use the if/endif notation instead of the standard if(something){} notation?

Example:

<?php if($a == 5): ?>
A is equal to 5
<?php endif; ?>

Versus:

<?php if($a == 5){ ?>
A is equal to 5
<?php } ?>

Body:
I mostly use if/endif when stopping and starting the php code block in between, so nearly always when raw html is being outputted.

For example:

<?php if ($n == 3): ?>
Lorem ipsum.
<?php endif; ?>

This looks, at least in my opinion, better than the following:

<?php if ($n == 3) { ?>
Lorem ipsum.
<?php } ?>


问:
How can I add an event to react component?
I am using react-color. It provides two build in events: onChange and onChangeComplete.
While onChange fires in realtime when operating the color picker, onChangeComplete only fires when holding still for a short time.

However for my case, onChangeComplete does still fire too often because it seems to have a short timeout (like 500ms or something), not only when releasing the mouse button.

I need an event to really finalize a color picking and send it to all components that need to know it. This would be when the user releases the mouse button.

```<code><SketchPicker
    onChange={(color) => { //fires all the time as it should
       handleChange(color);
    }}
    onChangeComplete={(color) => { //fires when stopping mouse movement for a short time
         handleChangeComplete(color); //Ok for setting local component state variables
    }}
    onMouseUp={(color) => { //not firing at all
         handleFinalChange(color); //supposed to run, when the user released mouse to promote it to React
    }}
/>
</code>```

onMouseUp supposed to be an event React provides and it works in plain divs but for some reason not in components provided by this package. How do I add a custom event to the component here?

答: You can either wrap the library component in a div and bind onMouseUp to it, or you'll need to modify the source code for that library.

Body:
I am using react-color. It provides two build in events: onChange and onChangeComplete.
While onChange fires in realtime when operating the color picker, onChangeComplete only fires when holding still for a short time.

However for my case, onChangeComplete does still fire too often because it seems to have a short timeout (like 500ms or something), not only when releasing the mouse button.

I need an event to really finalize a color picking and send it to all components that need to know it. This would be when the user releases the mouse button.

<SketchPicker
    onChange={(color) => { //fires all the time as it should
       handleChange(color);
    }}
    onChangeComplete={(color) => { //fires when stopping mouse movement for a short time
         handleChangeComplete(color); //Ok for setting local component state variables
    }}
    onMouseUp={(color) => { //not firing at all
         handleFinalChange(color); //supposed to run, when the user released mouse to promote it to React
    }}
/>

onMouseUp supposed to be an event React provides and it works in plain divs but for some reason not in components provided by this package. How do I add a custom event to the component here?


问:
R: Update column based on matching rows from another data frame
I have

```<code>mydf1 <- data.frame(ID = c(1,2,3,4,5), color = c("red", NA, NA, NA, "green"), name = c("tom", "dick", "harry", "steve", "mike"))
mydf2 <- data.frame(ID = c(1,2,99), color = c("red", "orange", "yellow"), name = c("tom", "dick", "Aaron"))
</code>```

I would like to update mydf1$color with the corresponding color from mydf2 for any rows that match on both ID and name. The desired output would be to update the color in row 2 to orange and leave the rest as is:

```<code>   ID  color   name
1  1   red     tom
2  2   orange  dick
3  3   <NA>    harry
4  4   <NA>    steve
5  5   green   mike
</code>```

I tried solutions with asymmetric merging as in some previous posts, but obtained undesired overwriting of some of my fields in mydf1. I then tried using match as suggested in another post but received an error. Not sure why the match condition is not working.

```<code>mydf1$color <- mydf2$color[match(mydf1[c("ID", "name")], mydf2[c("ID", "name")])]
</code>```

答:
We can use a join with data.table on the 'ID' and 'name' column and update the corresponding value of 'color' from the second dataset in the first dataset by assignment (:=)

```<code>library(data.table)
setDT(mydf1)[mydf2, color := i.color, on = .(ID, name)]
mydf1
#   ID  color  name
#1:  1    red   tom
#2:  2 orange  dick
#3:  3   <NA> harry
#4:  4   <NA> steve
#5:  5  green  mike
</code>```

match works on vector/matrix and not on data.frame.  If we need to use match, then paste the 'ID', 'name' from each datasets and do a match

```<code>i1 <- match(paste(mydf1$ID, mydf1$name), paste(mydf2$ID, mydf2$name), nomatch = 0)
</code>```

Or using tidyverse

```<code>library(dplyr)
mydf1 %>%
   left_join(mydf2, by = c("ID", "name")) %>%
    transmute(ID, name, color = coalesce(as.character(color.x),
                                         as.character(color.y)))
#  ID  name  color
#1  1   tom    red
#2  2  dick orange
#3  3 harry   <NA>
#4  4 steve   <NA>
#5  5  mike  green
</code>```

Body:
I have

mydf1 <- data.frame(ID = c(1,2,3,4,5), color = c("red", NA, NA, NA, "green"), name = c("tom", "dick", "harry", "steve", "mike"))
mydf2 <- data.frame(ID = c(1,2,99), color = c("red", "orange", "yellow"), name = c("tom", "dick", "Aaron"))

I would like to update mydf1$color with the corresponding color from mydf2 for any rows that match on both ID and name. The desired output would be to update the color in row 2 to orange and leave the rest as is:

   ID  color   name
1  1   red     tom
2  2   orange  dick
3  3   <NA>    harry
4  4   <NA>    steve
5  5   green   mike

I tried solutions with asymmetric merging as in some previous posts, but obtained undesired overwriting of some of my fields in mydf1. I then tried using match as suggested in another post but received an error. Not sure why the match condition is not working.

mydf1$color <- mydf2$color[match(mydf1[c("ID", "name")], mydf2[c("ID", "name")])]

Body:
We can use a join with data.table on the 'ID' and 'name' column and update the corresponding value of 'color' from the second dataset in the first dataset by assignment (:=)

library(data.table)
setDT(mydf1)[mydf2, color := i.color, on = .(ID, name)]
mydf1
#   ID  color  name
#1:  1    red   tom
#2:  2 orange  dick
#3:  3   <NA> harry
#4:  4   <NA> steve
#5:  5  green  mike

match works on vector/matrix and not on data.frame.  If we need to use match, then paste the 'ID', 'name' from each datasets and do a match

i1 <- match(paste(mydf1$ID, mydf1$name), paste(mydf2$ID, mydf2$name), nomatch = 0)

Or using tidyverse

library(dplyr)
mydf1 %>%
   left_join(mydf2, by = c("ID", "name")) %>%
    transmute(ID, name, color = coalesce(as.character(color.x),
                                         as.character(color.y)))
#  ID  name  color
#1  1   tom    red
#2  2  dick orange
#3  3 harry   <NA>
#4  4 steve   <NA>
#5  5  mike  green


问:
How to use Tensorflow Lite on AWS Lambda
I'm trying to host a small model I have compiled down to a .tflite on AWS Lambda. Using either the python 3.6 or python 3.7 tflite wheel files available on the tensorflow website I zip up my packages/code, and upload to S3 and link to lambda with space to spare.  However, when I test my function it crashes when trying to load tflite.  Initially, it couldn't load shared object files.  This was the error

```<code>[ERROR] Runtime.ImportModuleError: Unable to import module 'lambda_predict': No module named '_interpreter_wrapper')
</code>```

I found this shared object file and moved it up into the local directory, and then got another error

```<code>Unable to import module 'lambda_predict': /lib64/libm.so.6: version `GLIBC_2.27' not found (required by /var/task/_interpreter_wrapper.so)
</code>```

My base system is Ubuntu (Bionic Beaver)
Both these errors come from importing tflite

答:
Okay I solved this today.

Complete solution and compiled dependencies for amazonlinux/aws lambda on my github: https://github.com/tpaul1611/python_tflite_for_amazonlinux

So the problem is that aws lambda runs on amazonlinux which apparently needs a different compilation of the tflite _interpreter_wrapper than the one tensorflow is currently providing on their website. https://www.tensorflow.org/lite/guide/python

My solution was to compile it natively on amazonlinux using docker and the script that tensorflow is providing in their git repo.
https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/tools/pip_package

I created a Dockerfile:

```<code>FROM amazonlinux

WORKDIR /tflite

RUN yum groupinstall -y development
RUN yum install -y python3.7
RUN yum install -y python3-devel
RUN pip3 install numpy wheel
RUN git clone --branch v2.2.0-rc0 https://github.com/tensorflow/tensorflow.git
RUN sh ./tensorflow/tensorflow/lite/tools/pip_package/build_pip_package.sh
RUN pip3 install tensorflow/tensorflow/lite/tools/pip_package/gen/tflite_pip/python3/dist/tflite_runtime-2.2.0rc0-cp37-cp37m-linux_x86_64.whl

CMD tail -f /dev/null
</code>```

and then ran the following commands:

```<code>docker build -t tflite_amazonlinux .
docker run -d --name=tflite_amazonlinux tflite_amazonlinux
docker cp tflite_amazonlinux:/usr/local/lib64/python3.7/site-packages .
docker stop tflite_amazonlinux
</code>```

These commands output a folder called site-packages which contain the corretly compiled tflite python dependencies for amazonlinux and therefore also aws lambda.

Body:
I'm trying to host a small model I have compiled down to a .tflite on AWS Lambda. Using either the python 3.6 or python 3.7 tflite wheel files available on the tensorflow website I zip up my packages/code, and upload to S3 and link to lambda with space to spare.  However, when I test my function it crashes when trying to load tflite.  Initially, it couldn't load shared object files.  This was the error

[ERROR] Runtime.ImportModuleError: Unable to import module 'lambda_predict': No module named '_interpreter_wrapper')

I found this shared object file and moved it up into the local directory, and then got another error

Unable to import module 'lambda_predict': /lib64/libm.so.6: version `GLIBC_2.27' not found (required by /var/task/_interpreter_wrapper.so)

My base system is Ubuntu (Bionic Beaver)
Both these errors come from importing tflite

Body:
Okay I solved this today.

Complete solution and compiled dependencies for amazonlinux/aws lambda on my github: https://github.com/tpaul1611/python_tflite_for_amazonlinux

So the problem is that aws lambda runs on amazonlinux which apparently needs a different compilation of the tflite _interpreter_wrapper than the one tensorflow is currently providing on their website. https://www.tensorflow.org/lite/guide/python

My solution was to compile it natively on amazonlinux using docker and the script that tensorflow is providing in their git repo.
https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/tools/pip_package

I created a Dockerfile:

FROM amazonlinux

WORKDIR /tflite

RUN yum groupinstall -y development
RUN yum install -y python3.7
RUN yum install -y python3-devel
RUN pip3 install numpy wheel
RUN git clone --branch v2.2.0-rc0 https://github.com/tensorflow/tensorflow.git
RUN sh ./tensorflow/tensorflow/lite/tools/pip_package/build_pip_package.sh
RUN pip3 install tensorflow/tensorflow/lite/tools/pip_package/gen/tflite_pip/python3/dist/tflite_runtime-2.2.0rc0-cp37-cp37m-linux_x86_64.whl

CMD tail -f /dev/null

and then ran the following commands:

docker build -t tflite_amazonlinux .
docker run -d --name=tflite_amazonlinux tflite_amazonlinux
docker cp tflite_amazonlinux:/usr/local/lib64/python3.7/site-packages .
docker stop tflite_amazonlinux

These commands output a folder called site-packages which contain the corretly compiled tflite python dependencies for amazonlinux and therefore also aws lambda.


问:
Data from array to sheet
I have an array that plots data to a messagebox, how can I also have that same data on a different sheet?

The data I am working with is a linear cable cut list. It looks at the total cable length and the individual lengths and checks to see how many reels of cable I need for all the separate individual lengths.

Ideally Reel 1 lengths would go in column A and the next reel would be column B, so on and so forth with a blank column in between the different cable types.

```<code>    'Message Box Output
    For k = LBound(DetStk, 2) To UBound(DetStk, 2)
       sMsg = sMsg & DetStk(1, k) & vbTab & vbTab _
            & DetStk(0, k) & vbCrLf
    Next k
</code>```

THIS IS WHAT I GOT WORKING WITH HELP FROM "Splintered-Origins-Dev"

```<code>    'Sheet Output
    n = 3
    q = rC + p - 6
    For k = LBound(DetStk, 2) To UBound(DetStk, 2)
        If k - 1 >= LBound(DetStk, 2) Then
            If DetStk(0, k - 1) <> DetStk(0, k) Then
                'Data line reset
                n = 3
                p = p + 1
                q = rC + p - 6
                wsVG.Cells(1, q).Value2 = cblType
                wsVG.Cells(2, q).Value2 = DetStk(0, k) & " Reels"
            End If
        Else
            wsVG.Cells(1, q).Value2 = cblType
            wsVG.Cells(2, q).Value2 = DetStk(0, k) & " Reels"
        End If
        wsVG.Cells(n, q).Value2 = DetStk(1, k)
        n = n + 1
    Next k
</code>```

答:
DetStk Array's  2 rows an k colunms .  so You should switch the matrix to make it easier to see.

From

```<code>'Message Box Output
For k = LBound(DetStk, 2) To UBound(DetStk, 2)
   sMsg = sMsg & DetStk(1, k) & vbTab & vbTab _
        & DetStk(0, k) & vbCrLf
Next k
</code>```

to

```<code>'Sheet Output
Sheets.Add
Range("a1").Resize(UBound(DetStk, 2) + 1, UBound(DetStk, 1) + 1) = WorksheetFunction.Transpose(DetStk)
</code>```

Title: Data from array to sheet

Body:
I have an array that plots data to a messagebox, how can I also have that same data on a different sheet?

The data I am working with is a linear cable cut list. It looks at the total cable length and the individual lengths and checks to see how many reels of cable I need for all the separate individual lengths.

Ideally Reel 1 lengths would go in column A and the next reel would be column B, so on and so forth with a blank column in between the different cable types.

    'Message Box Output
    For k = LBound(DetStk, 2) To UBound(DetStk, 2)
       sMsg = sMsg & DetStk(1, k) & vbTab & vbTab _
            & DetStk(0, k) & vbCrLf
    Next k

THIS IS WHAT I GOT WORKING WITH HELP FROM "Splintered-Origins-Dev"

    'Sheet Output
    n = 3
    q = rC + p - 6
    For k = LBound(DetStk, 2) To UBound(DetStk, 2)
        If k - 1 >= LBound(DetStk, 2) Then
            If DetStk(0, k - 1) <> DetStk(0, k) Then
                'Data line reset
                n = 3
                p = p + 1
                q = rC + p - 6
                wsVG.Cells(1, q).Value2 = cblType
                wsVG.Cells(2, q).Value2 = DetStk(0, k) & " Reels"
            End If
        Else
            wsVG.Cells(1, q).Value2 = cblType
            wsVG.Cells(2, q).Value2 = DetStk(0, k) & " Reels"
        End If
        wsVG.Cells(n, q).Value2 = DetStk(1, k)
        n = n + 1
    Next k

Body:
DetStk Array's  2 rows an k colunms .  so You should switch the matrix to make it easier to see.

From

'Message Box Output
For k = LBound(DetStk, 2) To UBound(DetStk, 2)
   sMsg = sMsg & DetStk(1, k) & vbTab & vbTab _
        & DetStk(0, k) & vbCrLf
Next k

to

'Sheet Output
Sheets.Add
Range("a1").Resize(UBound(DetStk, 2) + 1, UBound(DetStk, 1) + 1) = WorksheetFunction.Transpose(DetStk)


问:
CakePHP find list with related model conditions
I'm trying to get a list of IDs (a la find('list')), but can't figure out how to do it with related model conditions.

My associations are:
Product hasAndBelongsToMany Category
Product belongsTo Manufacturer

I want to find a list of product IDs that are in a list of category IDs and have a certain manufacturer seo_url. I've tried tons of contains with conditions, conditions referencing other models, even tried using find('all') to see if my conditions would work, but couldn't get anything.

I managed to get one with Product->query(), but it's not in the format of a list. I could cycle through the array and grab IDs or whatever, but it feels awfully un-Cakey. I want to make sure Cake still does all its security checks on my queries and whatever other automagic it does. Here's the query I got working:

```<code>$all_results = $return['Category']['all_results'] = $this->Product->query('
    SELECT `Product`.`id`
        FROM `categories_products` as `CategoriesProduct`
        JOIN `products` as `Product` ON (`CategoriesProduct`.`product_id` = `Product`.`id`)
        JOIN `manufacturers` as `Manufacturer` ON (`Product`.`manufacturer_id` = `Manufacturer`.`id` AND `Manufacturer`.`seo_url` = \''.$manufacturer.'\')
        WHERE `CategoriesProduct`.`category_id` IN ('.implode(',', $search_categories).')
');
</code>```

this returns

```<code>[all_results] => Array
    (
         [0] => Array
            (
                [Product] => Array
                    (
                        [id] => 101787
                    )

            )

        [1] => Array
            (
                [Product] => Array
                    (
                        [id] => 100781
                    )

            )

        [2] => Array
            (
                [Product] => Array
                    (
                        [id] => 101887
                    )

            )

        [3] => Array
            (
                [Product] => Array
                    (
                        [id] => 101888
                    )

            )

    )
</code>```

Note: $search_categories is the list of category ID's (ie: array(12,42,24,5))

答:
CakePHP can be odd about conditions for related models. Especially with HABTM relationships. Even when recursive is set to the highest value (i.e. 2). Check out the docs for more detail about HABTM.

Try the following. Although from the above, I don't think it will work:

```<code>$conditions = array('Category.id' => $category_ids, 'Manufacturer.seo_url' => $manufacturer);
$this->Product('list', array('recursive' => 1, 'conditions' => $conditions));
</code>```

Also, avoid query() whenever possible. The whole point of MVC is to insulate data from display from logic. Using things like query() just breaks that.

Body:
I'm trying to get a list of IDs (a la find('list')), but can't figure out how to do it with related model conditions.

My associations are:
Product hasAndBelongsToMany Category
Product belongsTo Manufacturer

I want to find a list of product IDs that are in a list of category IDs and have a certain manufacturer seo_url. I've tried tons of contains with conditions, conditions referencing other models, even tried using find('all') to see if my conditions would work, but couldn't get anything.

I managed to get one with Product->query(), but it's not in the format of a list. I could cycle through the array and grab IDs or whatever, but it feels awfully un-Cakey. I want to make sure Cake still does all its security checks on my queries and whatever other automagic it does. Here's the query I got working:

$all_results = $return['Category']['all_results'] = $this->Product->query('
    SELECT `Product`.`id`
        FROM `categories_products` as `CategoriesProduct`
        JOIN `products` as `Product` ON (`CategoriesProduct`.`product_id` = `Product`.`id`)
        JOIN `manufacturers` as `Manufacturer` ON (`Product`.`manufacturer_id` = `Manufacturer`.`id` AND `Manufacturer`.`seo_url` = \''.$manufacturer.'\')
        WHERE `CategoriesProduct`.`category_id` IN ('.implode(',', $search_categories).')
');

this returns

[all_results] => Array
    (
         [0] => Array
            (
                [Product] => Array
                    (
                        [id] => 101787
                    )

            )

        [1] => Array
            (
                [Product] => Array
                    (
                        [id] => 100781
                    )

            )

        [2] => Array
            (
                [Product] => Array
                    (
                        [id] => 101887
                    )

            )

        [3] => Array
            (
                [Product] => Array
                    (
                        [id] => 101888
                    )

            )

    )

Note: $search_categories is the list of category ID's (ie: array(12,42,24,5))

Body:
CakePHP can be odd about conditions for related models. Especially with HABTM relationships. Even when recursive is set to the highest value (i.e. 2). Check out the docs for more detail about HABTM.

Try the following. Although from the above, I don't think it will work:

$conditions = array('Category.id' => $category_ids, 'Manufacturer.seo_url' => $manufacturer);
$this->Product('list', array('recursive' => 1, 'conditions' => $conditions));

Also, avoid query() whenever possible. The whole point of MVC is to insulate data from display from logic. Using things like query() just breaks that.