问:
Fetching data from function into <View> component inside the render method
I tried to fetch the data from function inside render, when I use alert() it works, but when I try to return real text it not shown any thing

the code I work with:

```<code>export default class App extends Component {
    renderResualts(){
        db.find({}, function (err, docs) {
           return docs.map(function(d){
              return(
                <Text>{d.name}</Text>
              )
           })
        })
    }
  render() {
    return (
      <View style={styles.container}>
          { this.renderResualts() }
      </View>
    );
  }
}

</code>```

--
UPDATED CODE:

```<code>

export default class App extends Component {

    constructor(props){
        super(props)
        this.state = {graves:[]}
    }
    componentDidMount(){
        db.find({}, function (err, docs) {
            this.setState({graves:docs})
        })
    }

    renderResults(){
        return this.state.graves.map(grave =>
            <Text>{grave.name}</Text>
        )
    }
  render() {
    return (
      <View style={styles.container}>
          { this.renderResults() }
      </View>
    );
  }
}

</code>```

It should be shown these data :

{
    _id: 1,
    name: 'Parturient',
    year: 2017
}, {
    _id: 2,
    name: 'Dapibus',
    year: 2017
}

inside text like so: ParturientDapibus

答:
try this</p>

```<code>renderResults(){
    return (
       <View>
           this.state.graves.map(grave =>
                <Text>{grave.name}</Text>
           )
      </View>
    );
}
</code>```

Body:
I tried to fetch the data from function inside render, when I use alert() it works, but when I try to return real text it not shown any thing

the code I work with:

export default class App extends Component {
    renderResualts(){
        db.find({}, function (err, docs) {
           return docs.map(function(d){
              return(
                <Text>{d.name}</Text>
              )
           })
        })
    }
  render() {
    return (
      <View style={styles.container}>
          { this.renderResualts() }
      </View>
    );
  }
}

--
UPDATED CODE:

export default class App extends Component {

    constructor(props){
        super(props)
        this.state = {graves:[]}
    }
    componentDidMount(){
        db.find({}, function (err, docs) {
            this.setState({graves:docs})
        })
    }

    renderResults(){
        return this.state.graves.map(grave =>
            <Text>{grave.name}</Text>
        )
    }
  render() {
    return (
      <View style={styles.container}>
          { this.renderResults() }
      </View>
    );
  }
}

It should be shown these data :

{
    _id: 1,
    name: 'Parturient',
    year: 2017
}, {
    _id: 2,
    name: 'Dapibus',
    year: 2017
}

inside text like so: ParturientDapibus

Body:
try this

renderResults(){
    return (
       <View>
           this.state.graves.map(grave =>
                <Text>{grave.name}</Text>
           )
      </View>
    );
}


来源: stackexchange

问:
Problem capturing mouse left button while using WM_NCHITTEST
```<code>case WM_NCHITTEST:  {
     LRESULT hit = DefWindowProc( hWnd, uMsg, wParam, lParam );

        if ( hit == HTCLIENT ) {
            hit = HTCAPTION;
            SendNotifyMessageA( hWnd, WM_MOUSEMOVE, NULL, MAKELPARAM( LOWORD(lParam), HIWORD(lParam) ) );
            pts.x = pts.y = 0;
            ClientToScreen( hWnd, &pts );
            SendNotifyMessageA( hWnd, WM_EXITSIZEMOVE, NULL,NULL );
            return hit;
        }   } break;
case WM_NCLBUTTONDOWN: { LMB_Dyn[h2] = true;  } break;
</code>```

I'm using this code while I try to move a window by clicking in the client area (anywhere in window). This works fine.

But I have problem correctly receiving the state of the mouse left button and while this code kind of works the problem is that when I do a simple click instead of a "click and move" the LMB_Dyn variable (mouse left button) has some delay (does not immediately get notified that I pressed the mouse button.

How to correctly get the state of the mouse left button while using WM_NCHITTEST?

答:
Mistake: }   } break; should read  }  return hit; }

However, there's something more radical going on here. WM_NCHITTEST is not meant to be used like that and is allowed to be called with coordinates other than the current mouse position. This means your SendNotifyMessageA can send garbage.

I see you have a handler for WM_NCLBUTTONDOWN. Maybe that's all you need. Or, if you're trying to make the window draggable by anywhere on it, that should be like so:

```<code>case WM_NCHITTEST:  {
    LRESULT hit = DefWindowProc( hWnd, uMsg, wParam, lParam );
    if ( hit == HTCLIENT ) {
        return HTCAPTION;
    }
    return hit;
}
</code>```

The documentation for WM_NCLBUTTONDOWN and WM_NCLBUTTONUP says they fire immediately. It's really easy to forget your InvalidateRect call and so not have your screen redraw for you so it appears slow.

ContentLicense: CC BY-SA 4.0

Body:
case WM_NCHITTEST:  {
     LRESULT hit = DefWindowProc( hWnd, uMsg, wParam, lParam );

        if ( hit == HTCLIENT ) {
            hit = HTCAPTION;
            SendNotifyMessageA( hWnd, WM_MOUSEMOVE, NULL, MAKELPARAM( LOWORD(lParam), HIWORD(lParam) ) );
            pts.x = pts.y = 0;
            ClientToScreen( hWnd, &pts );
            SendNotifyMessageA( hWnd, WM_EXITSIZEMOVE, NULL,NULL );
            return hit;
        }   } break;
case WM_NCLBUTTONDOWN: { LMB_Dyn[h2] = true;  } break;

I'm using this code while I try to move a window by clicking in the client area (anywhere in window). This works fine.

But I have problem correctly receiving the state of the mouse left button and while this code kind of works the problem is that when I do a simple click instead of a "click and move" the LMB_Dyn variable (mouse left button) has some delay (does not immediately get notified that I pressed the mouse button.

How to correctly get the state of the mouse left button while using WM_NCHITTEST?

Body:
Mistake: }   } break; should read  }  return hit; }

However, there's something more radical going on here. WM_NCHITTEST is not meant to be used like that and is allowed to be called with coordinates other than the current mouse position. This means your SendNotifyMessageA can send garbage.

I see you have a handler for WM_NCLBUTTONDOWN. Maybe that's all you need. Or, if you're trying to make the window draggable by anywhere on it, that should be like so:

case WM_NCHITTEST:  {
    LRESULT hit = DefWindowProc( hWnd, uMsg, wParam, lParam );
    if ( hit == HTCLIENT ) {
        return HTCAPTION;
    }
    return hit;
}

The documentation for WM_NCLBUTTONDOWN and WM_NCLBUTTONUP says they fire immediately. It's really easy to forget your InvalidateRect call and so not have your screen redraw for you so it appears slow.


问:
How to tell a typescript that value is an empty object?
Here is my code.

```<code>function DD(x: { y: string } | {}) {
  if (x.y) {//error
   console.log("DD jingo");
  }
}
</code>```

I get this error  The property "y" does not exist in the type "{} | {y: string;}".The property "y" does not exist in the type "{}".

I am new to typescript. How to say that X can accept an empty object and {y: string}.

答:
Not sure if this is a good pattern in TypeScript, but you could explicitly tell TypeScript that your value of x is of the type { y: string } in your if statement:

function DD(x: { y: string } | {}) {
  if ((x as {y: string}).y) {
   console.log("DD jingo");
  }
}
```

Body:
Here is my code.

function DD(x: { y: string } | {}) {
  if (x.y) {//error
   console.log("DD jingo");
  }
}

I get this error  The property "y" does not exist in the type "{} | {y: string;}".The property "y" does not exist in the type "{}".

I am new to typescript. How to say that X can accept an empty object and {y: string}.


问:
Can I set a POST variable before redirecting to a new page?

Possible Duplicate:

  How do you POST to a page using the PHP header() function?

For example, I need to redirect a user to a different page upon error, but I also want to POST a value to that page as well.

答:
You definitely cannot POST and redirect in the same time. Redirect means setting several HTTP headers. However, there are several solutions to your needs.

One is to store the data into $_SESSION and retrieve it from there, as answered above.

Another way is to put the form aside from PHP, in a separate file and include it if you have errors in the data posted, so you have all the variables in the current POST without the need to redirect the user (and set an error message in the form too).

You can think to use an AJAX to make the post and get the result back then you'll do the redirection using javascript.

Or, if there aren't many variables/values you want to pass you may use GET when doing the redirection.

I'm sure other alternatives exists too.

ContentLicense: CC BY-SA 3.0


问:
Comparing 2 tables (Insert, update or delete based on a secondary table)
Imagine I have two database tables which both have similar structure. So one of them is source and another is target.
I want to compare them using unique ID, something like what Redgate Data Compare does, here is the scenario:

For every new record, an INSERT command be executed.

If a record does not exist in source table anymore, a DELETE command omits that record in target table.

If a row has changed in source, an UPDATE command be executed.

I have tried an stored-procedure to loop through every record in source and compare it with target but it doesn't seem to be ideal.

I want to know what is the key word for such a comparison in SQL and I was wondering if there is any prewritten query for such a cases?

答:
You can use MERGE command

check this link for example


问:
Why does this.getClass give it's own class name rather than Anonymous class name?
I have created anonymous class by implementing interface I inside public static void main() method. So, by java 8 for the abstract method test(), the implementation is provided from imple() method of class C.

So, inside public static void main() method, printing _interface.getClass(), I got

package_path.Main$$Lambda$1/310656974 which is absolutely fine. Bacause it print's the anonymous class name.

Also, _interface is pointing to an anonymous object in heap and hence I'm doing _interface.test();

So, the first statement that test() method has now is to print the class name,

But eventually what it print was,
package_path.C (telling me C is the class name). How is that possible? Shouldn't package_path.Main$$Lambda$1/310656974 be printed again? Because 'this' means anonymous inside the test method right?

```<code>@java.lang.FunctionalInterface
interface I {
    void test();
}

class C {
    void imple() {
        System.out.println(this.getClass());
        System.out.println("Inside Implementation");
    }
}

class Main {
    public static void main(String[] args) {
        I _interface = new C()::imple;
        System.out.println(_interface.getClass());
        _interface.test();
    }
}
</code>```

答:
Hopefully, this might help you understand, that when you declare

```<code>I _interface = new C()::imple;
</code>```

you've actually implemented the interface somewhat similar to (though not same as):

```<code>I _interface = new I() {
    @Override
    public void test() {
        new C().imple(); // creating an instance of class `C` and calling its 'imple' method
    }
};
</code>```

Hence when the test method is called, it first creates an instance of C which prints

```<code>class x.y.z.C
</code>```

as the class.

Because 'this' means anonymous inside the test method right?

 Now as you can see above, there is no more anonymous class from which imple
is being called from, hence this is not representing the anonymous class anymore.

As Holger clarified in comments further, despite the representation as lambda or anonymous class at the calling site, the this.getClass() inside a method of class C will evaluate to C.class, regardless of how the caller looks like.

Recommend: Continue to read and follow on Is there any runtime benefit of using lambda expression in Java?

Body:
I have created anonymous class by implementing interface I inside public static void main() method. So, by java 8 for the abstract method test(), the implementation is provided from imple() method of class C.

So, inside public static void main() method, printing _interface.getClass(), I got

package_path.Main$$Lambda$1/310656974 which is absolutely fine. Bacause it print's the anonymous class name.

Also, _interface is pointing to an anonymous object in heap and hence I'm doing _interface.test();

So, the first statement that test() method has now is to print the class name,

But eventually what it print was,
package_path.C (telling me C is the class name). How is that possible? Shouldn't package_path.Main$$Lambda$1/310656974 be printed again? Because 'this' means anonymous inside the test method right?

@java.lang.FunctionalInterface
interface I {
    void test();
}

class C {
    void imple() {
        System.out.println(this.getClass());
        System.out.println("Inside Implementation");
    }
}

class Main {
    public static void main(String[] args) {
        I _interface = new C()::imple;
        System.out.println(_interface.getClass());
        _interface.test();
    }
}

Body:
Hopefully, this might help you understand, that when you declare

I _interface = new C()::imple;

you've actually implemented the interface somewhat similar to (though not same as):

I _interface = new I() {
    @Override
    public void test() {
        new C().imple(); // creating an instance of class `C` and calling its 'imple' method
    }
};

Hence when the test method is called, it first creates an instance of C which prints

class x.y.z.C

as the class.

Because 'this' means anonymous inside the test method right?

 Now as you can see above, there is no more anonymous class from which imple
is being called from, hence this is not representing the anonymous class anymore.

As Holger clarified in comments further, despite the representation as lambda or anonymous class at the calling site, the this.getClass() inside a method of class C will evaluate to C.class, regardless of how the caller looks like.

Recommend: Continue to read and follow on Is there any runtime benefit of using lambda expression in Java?


问:
Jest mocked class force different response, typescript
this is me again with very simple example.
In resumen i need a different response for the mocked class.

This is my simple class that return an object

```<code>            class Producer {
                hello() {
                    return {
                        message:'Class: Hello',
                    }
                }
            }
            export default Producer;
</code>```

this is the mock class in the __mocks__ folder

```<code>            class Producer {
                hello() {
                    return {
                        message:'__mocks__: hello',
                    }
                }
            }
            export default Producer;
</code>```

This is my test file that works as i expected

```<code>            import Consumer from './Consumer';
            jest.mock('./Producer');
            test('simple test 1', () => {
                let consumer = new Consumer();
                consumer.call();
                expect(consumer.response.message).toEqual('__mocks__: hello')
                console.log(consumer.response)
                // prints on console { message: '__mocks__: hello' }
            });
</code>```

My question is, for other test i need a different response from the mocked file Producer

```<code>            jest.mock('./Producer').updateOnTheFly( hello() {
                    return {
                        message:'UPDATE ON FLY: hello',
                    }
            })
            test('simple test 1', () => {

                let consumer = new Consumer();
                consumer.call();
                expect(consumer.response.message).toEqual('UPDATE ON FLY: hello')
            });
</code>```

答:
For something like this it can be easier to not create a manual mock at __mocks__/Producer.js.

Instead, use jest.mock('./Producer'); to auto-mock the module...

...then mock the return value for Producer.prototype.hello as needed:

```<code>import Consumer from './Consumer';

import Producer from './Producer';
jest.mock('./Producer');  // <= auto-mock Producer

test('simple test 1', () => {
  Producer.prototype.hello.mockReturnValue({ message: 'mocked: hello' });
  let consumer = new Consumer();
  consumer.call();
  expect(consumer.response.message).toEqual('mocked: hello')  // Success!
});

test('simple test 2', () => {
  Producer.prototype.hello.mockReturnValue({ message: 'UPDATED: hello' });
  let consumer = new Consumer();
  consumer.call();
  expect(consumer.response.message).toEqual('UPDATED: hello')  // Success!
});
</code>```

Body:
this is me again with very simple example.
In resumen i need a different response for the mocked class.

This is my simple class that return an object

            class Producer {
                hello() {
                    return {
                        message:'Class: Hello',
                    }
                }
            }
            export default Producer;

this is the mock class in the __mocks__ folder

            class Producer {
                hello() {
                    return {
                        message:'__mocks__: hello',
                    }
                }
            }
            export default Producer;

This is my test file that works as i expected

            import Consumer from './Consumer';
            jest.mock('./Producer');
            test('simple test 1', () => {
                let consumer = new Consumer();
                consumer.call();
                expect(consumer.response.message).toEqual('__mocks__: hello')
                console.log(consumer.response)
                // prints on console { message: '__mocks__: hello' }
            });

My question is, for other test i need a different response from the mocked file Producer

            jest.mock('./Producer').updateOnTheFly( hello() {
                    return {
                        message:'UPDATE ON FLY: hello',
                    }
            })
            test('simple test 1', () => {

                let consumer = new Consumer();
                consumer.call();
                expect(consumer.response.message).toEqual('UPDATE ON FLY: hello')
            });

Body:
For something like this it can be easier to not create a manual mock at __mocks__/Producer.js.

Instead, use jest.mock('./Producer'); to auto-mock the module...

...then mock the return value for Producer.prototype.hello as needed:

import Consumer from './Consumer';

import Producer from './Producer';
jest.mock('./Producer');  // <= auto-mock Producer

test('simple test 1', () => {
  Producer.prototype.hello.mockReturnValue({ message: 'mocked: hello' });
  let consumer = new Consumer();
  consumer.call();
  expect(consumer.response.message).toEqual('mocked: hello')  // Success!
});

test('simple test 2', () => {
  Producer.prototype.hello.mockReturnValue({ message: 'UPDATED: hello' });
  let consumer = new Consumer();
  consumer.call();
  expect(consumer.response.message).toEqual('UPDATED: hello')  // Success!
});


问:
How to plot with x = column A, but color/hue = column B categorical vars
I have a pandas dataframe that I want to create a bar plot from using Seaborn. The problem is  I want to use one of two categorical variables, say column A, in X-axis, but a different categorical column, say column B, to color the bars. Values in B can represent more than one value in A.

```<code>        MajorCategories               name                 review_count
Food,Restaurants              Mon Ami Gabi                  8348
Food,Restaurants              Bacchanal Buffet              8339
Restaurants                   Wicked Spoon                  6708
Food,Restaurants              Hash House A Go Go            5763
Restaurants                   Gordon Ramsay BurGR           5484
Restaurants                   Secret Pizza                  4286
Restaurants                   The Buffet at Bellagio        4227
Hotels & Travel              McCarran International Airport 3627
Restaurants                  Yardbird Southern Table & Bar  3576
</code>```

So, I would like my barplot to plot the bars with x = 'name' and y='review_count', at the same time color/hue?? = Major Categories. It is possible in Seaborn without many lines of code?

Below are the links to the images I get in seaborn, and the one I am trying to get.

```<code>sns.catplot(x="review_count", y="name", kind="bar", data=plot_data,  aspect= 1.5)
</code>```

Plot I get using seaborn using the code above

Plot I am trying to achieve, this one is using ggplot2 in R

答:
Try passing hue and set dodge=False:

```<code>sns.catplot(x="review_count", y="name", hue='MajorCategories',
            kind="bar", data=plot_data,
            dodge=False, aspect= 1.5)
</code>```

Output:

Body:
I have a pandas dataframe that I want to create a bar plot from using Seaborn. The problem is  I want to use one of two categorical variables, say column A, in X-axis, but a different categorical column, say column B, to color the bars. Values in B can represent more than one value in A.

        MajorCategories               name                 review_count
Food,Restaurants              Mon Ami Gabi                  8348
Food,Restaurants              Bacchanal Buffet              8339
Restaurants                   Wicked Spoon                  6708
Food,Restaurants              Hash House A Go Go            5763
Restaurants                   Gordon Ramsay BurGR           5484
Restaurants                   Secret Pizza                  4286
Restaurants                   The Buffet at Bellagio        4227
Hotels & Travel              McCarran International Airport 3627
Restaurants                  Yardbird Southern Table & Bar  3576

So, I would like my barplot to plot the bars with x = 'name' and y='review_count', at the same time color/hue?? = Major Categories. It is possible in Seaborn without many lines of code?

Below are the links to the images I get in seaborn, and the one I am trying to get.

sns.catplot(x="review_count", y="name", kind="bar", data=plot_data,  aspect= 1.5)

Plot I get using seaborn using the code above

Plot I am trying to achieve, this one is using ggplot2 in R

Body:
Try passing hue and set dodge=False:

sns.catplot(x="review_count", y="name", hue='MajorCategories',
            kind="bar", data=plot_data,
            dodge=False, aspect= 1.5)

Output:


问:
Different outcome using pandas nunique() and unique()
I have a big DF with 10 millions rows and I need to find the unique number for each column.

I wrote the function below:
(need to return a series)

def count_unique_values(df):
    return pd.Series(df.nunique())
```

<p>and I get this output:</p>

<pre class="lang-py prettyprint-override"><code>Area          210
Item          436
Element         4
Year           53
Unit            2
Value      313640
dtype: int64
</code>```

expected result should be value 313641.

when I just do

df['Value'].unique()
```

I do get that answer. Didn't figure out why I get less with nunique() just there.

答:
Because DataFrame.nunique omit missing values, because default parameter dropna=True, Series.unique function not.

Sample:

```<code>df = pd.DataFrame({
        'A':list('abcdef'),
        'D':[np.nan,3,5,5,3,5],

})

print (df)
   A    D
0  a  NaN
1  b  3.0
2  c  5.0
3  d  5.0
4  e  3.0
5  f  5.0

def count_unique_values(df):
    return df.nunique()

print (count_unique_values(df))
A    6
D    2
dtype: int64

print (df['D'].unique())
[nan  3.  5.]
</code>```

```<code>print (df['D'].nunique())
2

print (df['D'].unique())
[nan  3.  5.]
</code>```

Solution is add parameter dropna=False:

```<code>print (df['D'].nunique(dropna=False))
3

print (df['D'].unique())
3
</code>```

So in your function:

```<code>def count_unique_values(df):
    return df.nunique(dropna=False)
print (count_unique_values(df))
A    6
D    3
dtype: int64
</code>```

Body:
I have a big DF with 10 millions rows and I need to find the unique number for each column.

I wrote the function below:
(need to return a series)

def count_unique_values(df):
    return pd.Series(df.nunique())

and I get this output:

Area          210
Item          436
Element         4
Year           53
Unit            2
Value      313640
dtype: int64

expected result should be value 313641.

when I just do

df['Value'].unique()

I do get that answer. Didn't figure out why I get less with nunique() just there.

Body:
Because DataFrame.nunique omit missing values, because default parameter dropna=True, Series.unique function not.

Sample:

df = pd.DataFrame({
        'A':list('abcdef'),
        'D':[np.nan,3,5,5,3,5],

})

print (df)
   A    D
0  a  NaN
1  b  3.0
2  c  5.0
3  d  5.0
4  e  3.0
5  f  5.0

def count_unique_values(df):
    return df.nunique()

print (count_unique_values(df))
A    6
D    2
dtype: int64

print (df['D'].unique())
[nan  3.  5.]

print (df['D'].nunique())
2

print (df['D'].unique())
[nan  3.  5.]

Solution is add parameter dropna=False:

print (df['D'].nunique(dropna=False))
3

print (df['D'].unique())
3

So in your function:

def count_unique_values(df):
    return df.nunique(dropna=False)
print (count_unique_values(df))
A    6
D    3
dtype: int64


问:
Using httpservice to call a PHP function which takes parameters
If you look at the link below, there is some PHP code called by Flex mxml through HttpService. The PHP code has functions, but the mxml code doesn't call a specific function. How can I use httpservice to call a specific function (in my case, one which takes parameters)?

http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_2.html

Thanks

答: I think you may be looking for RPC rather than HTTP calls.  The example you linked to uses an HTTPService.  Take a look at RemoteObject with PHP.  I suspect you are going to have to get into some layer on the server which handles AMF.  Here's an article.  </p>

OwnerDisplayName: GSS

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Simon


问:
Why we should check for the variable being defined var m = m || function(){}
Lot of libraries i have seen methods defined like this

```<code>Common.deepCopy = Common.deepCopy || function(oldObject) {
        return $.extend(true, {}, oldObject);
    };
</code>```

What is the need of defining methods are objects like this.

Because the js files will be executed only once so there is no chance of deepCopy being defined previously.

答:
Often this is to check if something already exists in the environment or not, like Array.prototype.indexOf.  It doesn't exist in oldIE.

```<code>var indexOf = [].indexOf ? fn : fn2
</code>```

Now you could define fn to use the native indexOf and then use fn2 for environments that don't support it.

It's better this way so you don't have to check every time you call the function--instead you check when you define it.

Body:
Lot of libraries i have seen methods defined like this

Common.deepCopy = Common.deepCopy || function(oldObject) {
        return $.extend(true, {}, oldObject);
    };

What is the need of defining methods are objects like this.

Because the js files will be executed only once so there is no chance of deepCopy being defined previously.

Body:
Often this is to check if something already exists in the environment or not, like Array.prototype.indexOf.  It doesn't exist in oldIE.

var indexOf = [].indexOf ? fn : fn2

Now you could define fn to use the native indexOf and then use fn2 for environments that don't support it.

It's better this way so you don't have to check every time you call the function--instead you check when you define it.


问:
Draw board with color blocks and numbers in Python turtle
I have a list of list called ListOfValues. I want to draw a board according to the size of this list, and color some blocks black with white fill and the others with just black.  I tried and got the following:

And my code:

```<code>import turtle

#sets screen characteristics
wn=turtle.Screen()
wn.bgcolor('lightblue')
wn.title('Chessboard')

#sets turtle characteristics
greg = turtle.Turtle()
greg.speed(0)

#draws and fills one square
def square(size,color):
    greg.color(color)
    greg.begin_fill()
    for i in range(4):
        greg.fd(size)
        greg.lt(90)

    greg.end_fill()
    greg.fd(size)

#draws the whole chessboard
def chessboard(size):
    greg.pu()
    greg.goto(-(size*4),(size*4))
    LR = len(listOfValues);
    for i in range(LR):
        for j in range(LR):
            if(SomeValue == 1 ):
                square(size,'white')
            else:
                square(size,'black')
        greg.rt(90)
        greg.lt(90)
        greg.goto(-(size*(4)),(size*(4 - i - 1)))
chessboard(50)
</code>```

I am missing two things:

I need to place lines in each row and column so it looks like a board

I need to put the number values from my array in the middle of each block

How could I achieve this?

答:
I need to place lines in each row and column so it looks like a board

This one is easy.  Instead of setting the color via color(), which sets both the pen and fill colors, instead use fillcolor() which only sets the fill color, leaving the pen color the default black.  You'll also need to put the pen down during the drawing but lift it up after each row, during its journey back to the left edge.

I need to put the value from my array in the middle of the block

This question is trickier but basically you need to define listOfValues as a list of list of int, where each int is zero or one, or some such.  Then in your nested loop, do SomeValue = listOfValues[i][j] before testing its value.

If you want to write the number in the block, I'd allocate a separate marker turtle for writing the numbers.  And define an appropriate font.

Below is my rework of your code where I implement the above as well as attempt to center the board correctly:

```<code>from turtle import Screen, Turtle

FONT_SIZE = 18
FONT = ('Arial', FONT_SIZE, 'normal')

listOfValues = [
    [0, 1, 1, 2, 1, 1, 0],
    [1, 2, 1, 1, 0, 1, 1],
    [1, 1, 0, 1, 1, 2, 1],
    [2, 1, 1, 0, 1, 1, 1],
    [1, 2, 1, 1, 0, 1, 2],
    [1, 1, 1, 1, 1, 1, 1],
    [1, 0, 1, 2, 1, 0, 1]
]

def square(size, color):

    ''' draw and fill one square '''

    greg.fillcolor(color)
    greg.pendown()
    greg.begin_fill()

    for _ in range(4):
        greg.forward(size)
        greg.left(90)

    greg.end_fill()

    greg.penup()
    greg.forward(size)

def chessboard(size):

    ''' draw the whole chessboard '''

    side = len(listOfValues)

    greg.penup()
    greg.goto(-size * side/2, size * side/2)

    for i in range(side):
        for j in range(side):
            someValue = listOfValues[i][j]
            text, color = ('black', 'white') if someValue == 1 else ('white', 'black')
            square(size, color)

            marker.goto(greg.xcor() - size/2, greg.ycor() + size/2 - FONT_SIZE/2)
            marker.pencolor(text)
            marker.write(someValue, align='center', font=FONT)

        greg.goto(-size * side/2, size * side/2 - size * (i + 1))

# set screen characteristics
screen = Screen()
screen.title('Chessboard')
screen.bgcolor('lightblue')

# set turtle characteristics
greg = Turtle()
greg.hideturtle()

# set marker characteristics
marker = Turtle()
marker.penup()
marker.hideturtle()

screen.tracer(False)  # because I have no patience
chessboard(50)
screen.tracer(True)

screen.mainloop()
</code>```

Body:
I have a list of list called ListOfValues. I want to draw a board according to the size of this list, and color some blocks black with white fill and the others with just black.  I tried and got the following:

And my code:

import turtle

#sets screen characteristics
wn=turtle.Screen()
wn.bgcolor('lightblue')
wn.title('Chessboard')

#sets turtle characteristics
greg = turtle.Turtle()
greg.speed(0)

#draws and fills one square
def square(size,color):
    greg.color(color)
    greg.begin_fill()
    for i in range(4):
        greg.fd(size)
        greg.lt(90)

    greg.end_fill()
    greg.fd(size)

#draws the whole chessboard
def chessboard(size):
    greg.pu()
    greg.goto(-(size*4),(size*4))
    LR = len(listOfValues);
    for i in range(LR):
        for j in range(LR):
            if(SomeValue == 1 ):
                square(size,'white')
            else:
                square(size,'black')
        greg.rt(90)
        greg.lt(90)
        greg.goto(-(size*(4)),(size*(4 - i - 1)))
chessboard(50)

I am missing two things:

I need to place lines in each row and column so it looks like a board

I need to put the number values from my array in the middle of each block

How could I achieve this?

Body:
I need to place lines in each row and column so it looks like a board

This one is easy.  Instead of setting the color via color(), which sets both the pen and fill colors, instead use fillcolor() which only sets the fill color, leaving the pen color the default black.  You'll also need to put the pen down during the drawing but lift it up after each row, during its journey back to the left edge.

I need to put the value from my array in the middle of the block

This question is trickier but basically you need to define listOfValues as a list of list of int, where each int is zero or one, or some such.  Then in your nested loop, do SomeValue = listOfValues[i][j] before testing its value.

If you want to write the number in the block, I'd allocate a separate marker turtle for writing the numbers.  And define an appropriate font.

Below is my rework of your code where I implement the above as well as attempt to center the board correctly:

from turtle import Screen, Turtle

FONT_SIZE = 18
FONT = ('Arial', FONT_SIZE, 'normal')

listOfValues = [
    [0, 1, 1, 2, 1, 1, 0],
    [1, 2, 1, 1, 0, 1, 1],
    [1, 1, 0, 1, 1, 2, 1],
    [2, 1, 1, 0, 1, 1, 1],
    [1, 2, 1, 1, 0, 1, 2],
    [1, 1, 1, 1, 1, 1, 1],
    [1, 0, 1, 2, 1, 0, 1]
]

def square(size, color):

    ''' draw and fill one square '''

    greg.fillcolor(color)
    greg.pendown()
    greg.begin_fill()

    for _ in range(4):
        greg.forward(size)
        greg.left(90)

    greg.end_fill()

    greg.penup()
    greg.forward(size)

def chessboard(size):

    ''' draw the whole chessboard '''

    side = len(listOfValues)

    greg.penup()
    greg.goto(-size * side/2, size * side/2)

    for i in range(side):
        for j in range(side):
            someValue = listOfValues[i][j]
            text, color = ('black', 'white') if someValue == 1 else ('white', 'black')
            square(size, color)

            marker.goto(greg.xcor() - size/2, greg.ycor() + size/2 - FONT_SIZE/2)
            marker.pencolor(text)
            marker.write(someValue, align='center', font=FONT)

        greg.goto(-size * side/2, size * side/2 - size * (i + 1))

# set screen characteristics
screen = Screen()
screen.title('Chessboard')
screen.bgcolor('lightblue')

# set turtle characteristics
greg = Turtle()
greg.hideturtle()

# set marker characteristics
marker = Turtle()
marker.penup()
marker.hideturtle()

screen.tracer(False)  # because I have no patience
chessboard(50)
screen.tracer(True)

screen.mainloop()


问:
How to get REST Api in Ember JS?
I work with an Ember boilerplate that works with REST Api.

The data should be recieved from Laravel backend and rendered in an Ember template. I will be grateful for any help.

Here is response of index (/) route:

```<code>{
    "responce":[
        {
            "id":0,
            "title":"main",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Vitae, aliquam."
        },
        {
            "id":1,
            "name":"about",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident, obcaecati? Accusantium ex dolorum voluptate deleniti?"
        },
        {
            "id":2,
            "name":"contacts",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates voluptatibus exercitationem molestias rem."
        }
    ]
}
</code>```

I suppose that there should be some kind of a loop that processes the received data and renders it. The result should be something like this:

```<code><h3>main</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Vitae, aliquam.</p>
<h3>about</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident, obcaecati? Accusantium ex dolorum voluptate deleniti?</p>
<h3>contacts</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates voluptatibus exercitationem molestias rem.</p>
</code>```

Thanks in advance!

答:
There are a lot of pieces to put together here, but let me try and layout the general path. Your Laravel API provides structured data that needs to be read by your ember application. Start by setting up your ember routes model hook to read that data. You'll want to check the guide for a lot more information, but I would start with this in your index route as the first step:

```<code>import Route from '@ember/routing/route';
import fetch from 'fetch';

export default Route.extend({
  model() {
    //this is where your ember app gets data from your API
    return fetch('YOUR-LARAVAL-API.com/index').then(response => {
      console.log(data);
      const data = response.json();
      return data.responce;
    });
  }
});
</code>```

This should make the data available in your index.hbh template so you can access it as model like:

```<code>```
{{#each this.model as |post|}}

{{post.title}}

{{post.content}}

{{/each}}
```
</code>```

Title: How to get REST Api in Ember JS?

Body:
I work with an Ember boilerplate that works with REST Api.

The data should be recieved from Laravel backend and rendered in an Ember template. I will be grateful for any help.

Here is response of index (/) route:

{
    "responce":[
        {
            "id":0,
            "title":"main",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Vitae, aliquam."
        },
        {
            "id":1,
            "name":"about",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident, obcaecati? Accusantium ex dolorum voluptate deleniti?"
        },
        {
            "id":2,
            "name":"contacts",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates voluptatibus exercitationem molestias rem."
        }
    ]
}

I suppose that there should be some kind of a loop that processes the received data and renders it. The result should be something like this:

main

Lorem ipsum dolor sit amet consectetur adipisicing elit. Vitae, aliquam.

about

Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident, obcaecati? Accusantium ex dolorum voluptate deleniti?

contacts

Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates voluptatibus exercitationem molestias rem.

Thanks in advance!

Body:
There are a lot of pieces to put together here, but let me try and layout the general path. Your Laravel API provides structured data that needs to be read by your ember application. Start by setting up your ember routes model hook to read that data. You'll want to check the guide for a lot more information, but I would start with this in your index route as the first step:

import Route from '@ember/routing/route';
import fetch from 'fetch';

export default Route.extend({
  model() {
    //this is where your ember app gets data from your API
    return fetch('YOUR-LARAVAL-API.com/index').then(response => {
      console.log(data);
      const data = response.json();
      return data.responce;
    });
  }
});

This should make the data available in your index.hbh template so you can access it as model like:

<pre>
{{#each this.model as |post|}}
  <h3>{{post.title}}</h3>
  <p>{{post.content}}</p>
{{/each}}
</pre>


问:
MySQL / MariaDB generate secure sequence
What is the best way to generate a secure sequence of characters on MySQL / MariaDB?

I want to use such a sequence for a user verification process where the user will get an E-Mail that contains a link like this:
www.myawesomewebsite.com/verify/<sequence>
Obviously, this sequence should not be guessable / predictable, which is also the reason why I do not use the builtin function UUID() (see here).

答:
How about

```<code>MD5(CONCAT(user_id, 'a secret salt'))
</code>```

If you have 9 trillion users, there is one chance of 9 trillion of two users having the same MD5.  But it is 32 hex digits.

The builtin UUID is "type-1", which implies that it has a time component.  Notie how much of two uuids is the same:

```<code>mysql> SELECT UUID(), SLEEP(1), UUID()\G
*************************** 1. row ***************************
  UUID(): b1a32a13-7f73-11e9-baa3-e4a7a03bbe24
SLEEP(1): 0
  UUID(): b23bc508-7f73-11e9-baa3-e4a7a03bbe24
</code>```

Even so, 7 out of 32 characters are different after only 1 second.

Here's a millisecond delay:

```<code>mysql> SELECT UUID(), SLEEP(0.001), UUID()\G
*************************** 1. row ***************************
      UUID(): 074ca3bc-7f74-11e9-baa3-e4a7a03bbe24
SLEEP(0.001): 0
      UUID(): 074ccdc5-7f74-11e9-baa3-e4a7a03bbe24
</code>```

Running UUID on different machines will yield a bunch of other digits being different.

Body:
How about

MD5(CONCAT(user_id, 'a secret salt'))

If you have 9 trillion users, there is one chance of 9 trillion of two users having the same MD5.  But it is 32 hex digits.

The builtin UUID is "type-1", which implies that it has a time component.  Notie how much of two uuids is the same:

mysql> SELECT UUID(), SLEEP(1), UUID()\G
*************************** 1. row ***************************
  UUID(): b1a32a13-7f73-11e9-baa3-e4a7a03bbe24
SLEEP(1): 0
  UUID(): b23bc508-7f73-11e9-baa3-e4a7a03bbe24

Even so, 7 out of 32 characters are different after only 1 second.

Here's a millisecond delay:

mysql> SELECT UUID(), SLEEP(0.001), UUID()\G
*************************** 1. row ***************************
      UUID(): 074ca3bc-7f74-11e9-baa3-e4a7a03bbe24
SLEEP(0.001): 0
      UUID(): 074ccdc5-7f74-11e9-baa3-e4a7a03bbe24

Running UUID on different machines will yield a bunch of other digits being different.


问:
valueerror array is too big arr.size when merge and sum based on title more than 2 data frame
I can't sum fee based on country, currency and product id from dfJANUARY and dfFEBRUARY.
 python said 'array is too big'

my file.txt as dfJANUARY has 35,6 mb

my file.txt as dfFEBRUARY has 36,3 mb

```<code>In[1]: dfJANUARY
Out[1]
  Country         PRODUCT ID    currency   fee

0  Arab Emirate    COCA COLA      USD       1000
1  Arab Emirate    COCA COLA      USD       1000
2  Arab Emirate    COCA COLA      USD       1009

86212 rows × 6 columns (unhide country: America ; PRODUCT ID: Fanta ; currency: SGD)

In[2]: dfFEBRUARY
Out[2]:
  Country         PRODUCT ID    currency   fee

0  Arab Emirate    COCA COLA      USD       2000
1  Arab Emirate    COCA COLA      USD       2000
2  Arab Emirate    COCA COLA      USD       2000

86212 rows × 6 columns (unhide country: America ; PRODUCT ID: Fanta; currency: SGD)
</code>```

I've tried made code but it's fail

```<code>df = pd.merge(dfJANUARY,dfFEBRUARY, on = "fee", how = "inner")

* when i merge ther's warning:
valueerror array is too big arr.size * arr.dtype.itemsize

#made value of total
TOTAL = dfJANUARY[fee] + dfFEBRUARY[fee]

#made new column, it's name "TOTAL"
df["TOTAL"] = TOTAL

#made Pivot
gdf = df.pivot_table(index = ["PRODUCT ID","Country","currency"],values = ("TOTAL"), aggfunc="sum", fill_value=0)

</code>```

so this is my expactation, i can sum income based on  type of currency, product id, country. So i will get TOTAl

can you help me?

```<code>**expect**
 dfEXPECT
                                           TOTAL
  Country         PRODUCT ID    currency

0  Arab Emirate    COCA COLA      USD       10000
                                  SGD       15000
1  Arab Emirate    Fanta          USD       20000
                                  SGD       30000
2  America         COCA COLA      USD       90000
                                  SGD       95000
3  America         Fanta          USD       80000
                                  SGD       75000
86212 rows × 6 columns
</code>```

答:
In your case, you want to pd.concat the dataframes (putting the second "below" the first). I'm surprised that pd.merge failed, but it is harder to merge (because it is a more general function).

Try

```<code>df = pd.concat([df1,df2])
df.pivot_table(index = ["PRODUCT ID","Country","currency"],values = ("TOTAL"), aggfunc="sum", fill_value=0)
</code>```

and see if it helps...

Body:
I can't sum fee based on country, currency and product id from dfJANUARY and dfFEBRUARY.
 python said 'array is too big'

my file.txt as dfJANUARY has 35,6 mb

my file.txt as dfFEBRUARY has 36,3 mb

In[1]: dfJANUARY
Out[1]
  Country         PRODUCT ID    currency   fee

0  Arab Emirate    COCA COLA      USD       1000
1  Arab Emirate    COCA COLA      USD       1000
2  Arab Emirate    COCA COLA      USD       1009

86212 rows × 6 columns (unhide country: America ; PRODUCT ID: Fanta ; currency: SGD)

In[2]: dfFEBRUARY
Out[2]:
  Country         PRODUCT ID    currency   fee

0  Arab Emirate    COCA COLA      USD       2000
1  Arab Emirate    COCA COLA      USD       2000
2  Arab Emirate    COCA COLA      USD       2000

86212 rows × 6 columns (unhide country: America ; PRODUCT ID: Fanta; currency: SGD)

I've tried made code but it's fail

df = pd.merge(dfJANUARY,dfFEBRUARY, on = "fee", how = "inner")

* when i merge ther's warning:
valueerror array is too big arr.size * arr.dtype.itemsize

#made value of total
TOTAL = dfJANUARY[fee] + dfFEBRUARY[fee]

#made new column, it's name "TOTAL"
df["TOTAL"] = TOTAL

#made Pivot
gdf = df.pivot_table(index = ["PRODUCT ID","Country","currency"],values = ("TOTAL"), aggfunc="sum", fill_value=0)

so this is my expactation, i can sum income based on  type of currency, product id, country. So i will get TOTAl

can you help me?

**expect**
 dfEXPECT
                                           TOTAL
  Country         PRODUCT ID    currency

0  Arab Emirate    COCA COLA      USD       10000
                                  SGD       15000
1  Arab Emirate    Fanta          USD       20000
                                  SGD       30000
2  America         COCA COLA      USD       90000
                                  SGD       95000
3  America         Fanta          USD       80000
                                  SGD       75000
86212 rows × 6 columns

Body:
In your case, you want to pd.concat the dataframes (putting the second "below" the first). I'm surprised that pd.merge failed, but it is harder to merge (because it is a more general function).

Try

df = pd.concat([df1,df2])
df.pivot_table(index = ["PRODUCT ID","Country","currency"],values = ("TOTAL"), aggfunc="sum", fill_value=0)

and see if it helps...


问:
Android studio takes too much memory
I had installed Android Studio 1.0 RC 2. I have 4GB of RAM installed, but after starting Android Studio and launching Android Emulator, more than 90% of physical memory has been used by only these two. Is there is any way to reduce this memory use? Due to this memory issue, I can't open other applications at the same time.

答: Try switching your JVM to eclipse openj9. Its gonna use way less memory. I swapped it and its using 600Mb constantly. </p>

Title: Android studio takes too much memory


问:
Forward declared singleton class with a friend function from the class with the forward declaration
I hope this is a coherent question... I have a singleton class definition like:

```<code>#include A.h

class Singleton
{
public:
   // If I change this to a return by pointer, it works fine. But reference gives me problems.
   static Singleton &getInstance();
   Singleton(Singleton const&) = delete;
   void operator=(Singleton const&) = delete;
   ~Singleton();

   friend void A::friendMethodinA();
private:
   Singleton();
   void methodOnlyNeededByA();
}
</code>```

The class definition is:

```<code>Singleton &Singleton::getInstance()
{
   static Singleton instance;
   return instance;
}

Singleton::~Singleton() {}

Singleton::Singleton() {}

void Singleton::methodOnlyNeededByA() { // method body. }
</code>```

My class A declaration is:

```<code>#pragma once

class Singleton;

class A
{
public:
   void friendMethodinA();
private:
   // This is what I'm not sure about. I tried
   // Singleton &mSingleton = Singleton::getInstance(); This gives me "use of undefined type 'Singleton'" error. I can't #include Singleton.h because of the friend function.
   // Singleton mSingleton = Singleton::getInstance(); This gives me "cannot be reference -- it is a deleted function" error.
   Singleton mSingleton; // This gives me "A::mSingleton uses undefined class 'Singleton'" error.
}
</code>```

I would really like to return the singleton by reference rather than pointer bto avoid null checks and dereferencing the pointer every time I use it. Is there a way to achieve this without completely refactoring to avoid using friend functions?

The purpose of this friend function is the method methodOnlyNeededByA(). Since it only ever needs to be called by Class A, I do not want to put it in the public interface of the Singleton.

答:
You can resolve the compiler error by:

Using a reference type as the member variable.

```<code>Singleton& mSingleton;
</code>```

and then

Intializing it in the constructor.

However, the more important point I want to make is: Don't use a member variable of type Singleton. When you need to use the class, simply call Singleton::getInstance(). You can store a reference to the returned object in a function local variable or just use the returned reference.

```<code>auto& ref = Singleton::getInsance();
ref.methodOnlyNeededByA();
</code>```

or

```<code>Singleton::getInsance().methodOnlyNeededByA();
</code>```

Body:
I hope this is a coherent question... I have a singleton class definition like:

#include A.h

class Singleton
{
public:
   // If I change this to a return by pointer, it works fine. But reference gives me problems.
   static Singleton &getInstance();
   Singleton(Singleton const&) = delete;
   void operator=(Singleton const&) = delete;
   ~Singleton();

   friend void A::friendMethodinA();
private:
   Singleton();
   void methodOnlyNeededByA();
}

The class definition is:

Singleton &Singleton::getInstance()
{
   static Singleton instance;
   return instance;
}

Singleton::~Singleton() {}

Singleton::Singleton() {}

void Singleton::methodOnlyNeededByA() { // method body. }

My class A declaration is:

#pragma once

class Singleton;

class A
{
public:
   void friendMethodinA();
private:
   // This is what I'm not sure about. I tried
   // Singleton &mSingleton = Singleton::getInstance(); This gives me "use of undefined type 'Singleton'" error. I can't #include Singleton.h because of the friend function.
   // Singleton mSingleton = Singleton::getInstance(); This gives me "cannot be reference -- it is a deleted function" error.
   Singleton mSingleton; // This gives me "A::mSingleton uses undefined class 'Singleton'" error.
}

I would really like to return the singleton by reference rather than pointer bto avoid null checks and dereferencing the pointer every time I use it. Is there a way to achieve this without completely refactoring to avoid using friend functions?

The purpose of this friend function is the method methodOnlyNeededByA(). Since it only ever needs to be called by Class A, I do not want to put it in the public interface of the Singleton.

Body:
You can resolve the compiler error by:

Using a reference type as the member variable.

Singleton& mSingleton;

and then

Intializing it in the constructor.

However, the more important point I want to make is: Don't use a member variable of type Singleton. When you need to use the class, simply call Singleton::getInstance(). You can store a reference to the returned object in a function local variable or just use the returned reference.

auto& ref = Singleton::getInsance();
ref.methodOnlyNeededByA();

or

Singleton::getInsance().methodOnlyNeededByA();


问:
How to put k8 secret in docker cmd argument?
I'm trying to setup the Azure Face recognition container, but wondering how to use a k8 secret as a Docker command "argument."

This works, but I need to replace the ApiKey with my k8 secret.

```<code>{
  "kind": "Deployment",
  "spec": {
    "template": {
      "spec": {
        "containers": [
          {
            "name": "azure-face",
            "args": [
              "Eula=accept",
              "Billing=https://microsoft.com",
              "ApiKey=123"
            ]
          }
        ]
      }
    }
  }
}
</code>```

Create secret like this:

```<code>kubectl create secret generic azure-api-key --from-literal=azure-api-key="123"
</code>```

Tried changing the container args like this but it doesn't work - arugment is not passed as expected:
(also tried other variations like ApiKey=${AZURE_API_KEY})

```<code>    "containers": [
      {
        "args": [
          "Eula=accept",
          "Billing=https://microsoft.com",
          "ApiKey=$AZURE_API_KEY"
        ],
        "env": [
          {
            "name": "AZURE_API_KEY",
            "valueFrom": {
              "secretKeyRef": {
                "name": "azure-api-key",
                "key": "azure-api-key"
              }
            }
          }
        ]
      }
    ]
</code>```

Also did docker exec and from inside container verified that:

```<code>$ echo $AZURE_API_KEY
$ 123
</code>```

答:
Using an environment variable for sensitive information like an API key is not necessarily the best practice. It's an open argue what is better, but I personally believe using files is better mainly because it's common to collect env vars for logging purposes etc.

So instead, I would mount the secret as file and read it in the command line, something like API_KEY=$(cat api_key.txt). I think this should work but need verification. Usually, there is support for configuration files in most images provided those days - so I would first look into this, e.g. if Azure Face recognition supports a configuration file.

Final note, if you're looking to read more about Kubernetes secrets and how to manage them on Git, check out this blog post (full disclosure: I'm the author) which covers all the different options to manage Kubernetes secrets securely.

Body:
I'm trying to setup the Azure Face recognition container, but wondering how to use a k8 secret as a Docker command "argument."

This works, but I need to replace the ApiKey with my k8 secret.

{
  "kind": "Deployment",
  "spec": {
    "template": {
      "spec": {
        "containers": [
          {
            "name": "azure-face",
            "args": [
              "Eula=accept",
              "Billing=https://microsoft.com",
              "ApiKey=123"
            ]
          }
        ]
      }
    }
  }
}

Create secret like this:

kubectl create secret generic azure-api-key --from-literal=azure-api-key="123"

Tried changing the container args like this but it doesn't work - arugment is not passed as expected:
(also tried other variations like ApiKey=${AZURE_API_KEY})

    "containers": [
      {
        "args": [
          "Eula=accept",
          "Billing=https://microsoft.com",
          "ApiKey=$AZURE_API_KEY"
        ],
        "env": [
          {
            "name": "AZURE_API_KEY",
            "valueFrom": {
              "secretKeyRef": {
                "name": "azure-api-key",
                "key": "azure-api-key"
              }
            }
          }
        ]
      }
    ]

Also did docker exec and from inside container verified that:

$ echo $AZURE_API_KEY
$ 123


问:
not getting how to use incoming image from android chooser intent
I'm trying to display the image in main page. the image will come from whats app profile upon sharing that image to my app.

app.js

```<code>if (intent.getClipData()) {
        let imageUri = intent.getClipData().getItemAt(0).getUri()
        console.log(imageUri);
    //  content://com.whatsapp.fileprovider/external/WhatsApp/.Shared/photo.jpg
        global.imageUri = imageUri;
    }
</code>```

xml

```<code><StackLayout class="p-20">
       <Image src="{{ imageUri }}" stretch="none" />

    </StackLayout>
</code>```

viewModel

```<code>imageUri: global.imageUri,
</code>```

getting this error

```<code>Error in downloadBitmap - java.net.MalformedURLException: Unknown protocol: content
</code>```

i need to know how to use incoming images from intent services of android.

答:
add these things in android manifest

```<code><intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="image/*" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.SEND_MULTIPLE" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="image/*" />
            </intent-filter>
</code>```

to handle it copy paste this code anywhere you like

```<code>if (platform_1.isAndroid) {
        application.android.on(application.AndroidApplication.activityCreatedEvent, function (args) {
            var activity = args.activity;
            // Get intent, action and MIME type
            var intent = activity.getIntent();
            var action = intent.getAction();
            var type = intent.getType();
            if (android.content.Intent.ACTION_SEND === action && type != null) {
                if (type.startsWith("text/")) {
                    handleSendText(intent); // Handle text being sent
                }
                else if (type.startsWith("image/")) {
                    handleSendImage(intent); // Handle single image being sent
                }
            }
            else if (android.content.Intent.ACTION_SEND_MULTIPLE === action && type != null) {
                if (type.startsWith("image/")) {
                    handleSendMultipleImages(intent); // Handle multiple images being sent
                }
            }
            else {
                // Handle other intents, such as being started from the home screen
            }
        });
    }
</code>```

```<code>function handleSendText(intent) {
    if (platform_1.isAndroid) {
        var sharedText = intent.getStringExtra(android.content.Intent.EXTRA_TEXT);
        if (sharedText != null) {
            // Update UI to reflect text being shared
            console.log("sharedText: ", sharedText);
            console.log("Text received!");
            vm.set("sharedText", sharedText);
        }
    }
}
function handleSendImage(intent) {
    if (platform_1.isAndroid) {
        var imageUri = intent.getParcelableExtra(android.content.Intent.EXTRA_STREAM);
        if (imageUri != null) {
            // Update UI to reflect image being shared
            console.log("Image received!");
            var appContext = application.android.context;
            var bitmap = android.provider.MediaStore.Images.Media.getBitmap(appContext.getContentResolver(), imageUri);
            console.log("bitmap: ", bitmap);
            vm.set("bitmap", bitmap);
        }
    }
}
function handleSendMultipleImages(intent) {
    if (platform_1.isAndroid) {
        var imageUris = intent.getParcelableArrayListExtra(android.content.Intent.EXTRA_STREAM);
        if (imageUris != null) {
            // Update UI to reflect multiple images being shared
            console.log("imageUris: ", imageUris);
            console.log("Multiple images received!");
        }
    }
}
</code>```

Body:
I'm trying to display the image in main page. the image will come from whats app profile upon sharing that image to my app.

app.js

if (intent.getClipData()) {
        let imageUri = intent.getClipData().getItemAt(0).getUri()
        console.log(imageUri);
    //  content://com.whatsapp.fileprovider/external/WhatsApp/.Shared/photo.jpg
        global.imageUri = imageUri;
    }

xml

<StackLayout class="p-20">
       <Image src="{{ imageUri }}" stretch="none" />

    </StackLayout>

viewModel

imageUri: global.imageUri,

getting this error

Error in downloadBitmap - java.net.MalformedURLException: Unknown protocol: content

i need to know how to use incoming images from intent services of android.

Body:
add these things in android manifest

<intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="image/*" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.SEND_MULTIPLE" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="image/*" />
            </intent-filter>

to handle it copy paste this code anywhere you like

if (platform_1.isAndroid) {
        application.android.on(application.AndroidApplication.activityCreatedEvent, function (args) {
            var activity = args.activity;
            // Get intent, action and MIME type
            var intent = activity.getIntent();
            var action = intent.getAction();
            var type = intent.getType();
            if (android.content.Intent.ACTION_SEND === action && type != null) {
                if (type.startsWith("text/")) {
                    handleSendText(intent); // Handle text being sent
                }
                else if (type.startsWith("image/")) {
                    handleSendImage(intent); // Handle single image being sent
                }
            }
            else if (android.content.Intent.ACTION_SEND_MULTIPLE === action && type != null) {
                if (type.startsWith("image/")) {
                    handleSendMultipleImages(intent); // Handle multiple images being sent
                }
            }
            else {
                // Handle other intents, such as being started from the home screen
            }
        });
    }

function handleSendText(intent) {
    if (platform_1.isAndroid) {
        var sharedText = intent.getStringExtra(android.content.Intent.EXTRA_TEXT);
        if (sharedText != null) {
            // Update UI to reflect text being shared
            console.log("sharedText: ", sharedText);
            console.log("Text received!");
            vm.set("sharedText", sharedText);
        }
    }
}
function handleSendImage(intent) {
    if (platform_1.isAndroid) {
        var imageUri = intent.getParcelableExtra(android.content.Intent.EXTRA_STREAM);
        if (imageUri != null) {
            // Update UI to reflect image being shared
            console.log("Image received!");
            var appContext = application.android.context;
            var bitmap = android.provider.MediaStore.Images.Media.getBitmap(appContext.getContentResolver(), imageUri);
            console.log("bitmap: ", bitmap);
            vm.set("bitmap", bitmap);
        }
    }
}
function handleSendMultipleImages(intent) {
    if (platform_1.isAndroid) {
        var imageUris = intent.getParcelableArrayListExtra(android.content.Intent.EXTRA_STREAM);
        if (imageUris != null) {
            // Update UI to reflect multiple images being shared
            console.log("imageUris: ", imageUris);
            console.log("Multiple images received!");
        }
    }
}


问:
Reducer not being called when using dispatch()
I am trying to update my redux state from a child component(QResults.js) by calling a function that I pass to it  but my reducer isn't being reached when I use the function. QResults.js has a link that I am clicking which I expect to alter my state via one of my reducers. Am I doing something wrong with my mapDispatchToProps() function?

Channel.js

```<code>class Channel extends Component {
    ...
    render() {
        return (
        ...
         <div>
            <QResults
             allQueryResults={this.state.queryState}
             requestHandler={queueNewRequest}/>
         </div>
        );
    }
}

function mapStateToProps(state) {
   ...
}

 function mapDispatchToProps(dispatch) {
    return ({
        queueNewRequest: (newRequestData) => { dispatch(queueNewRequest(newRequestData)) }
    })
}

export default withRouter(connect(mapStateToProps , mapDispatchToProps )(Channel))
</code>```

QResults.js

```<code>export default class QResults extends Component {
    render() {
        const {requestHandler} = this.props

        return (
            <ul>
                {this.props.allQueryResults.items.map((trackAlbum, i) =>
                    <li key={i}>
                        <a href='#'
                        onClick={
                            () => requestHandler(trackAlbum.name)}>
                            Some link
                        </a>
                    </li>
                )}
            </ul>
        )
    }
}
</code>```

Reducers.js

```<code>import { combineReducers } from 'redux'

function reducer1(state = {}, action) {
    ...
}

function reducer2(state = {}, action) {
    switch (action.type) {
        case QUEUE_NEW_REQUEST:
            return{
                ...state,
                newRequestInfo : action.newRequestInfo
            }
        default:
            return state
    }
}

const rootReducer = combineReducers({
    reducer1,
    reducer2
})

export default rootReducer
</code>```

Actions.js

```<code>export const QUEUE_NEW_REQUEST = 'QUEUE_NEW_REQUEST'

export function queueNewRequest(newRequestInfo) {
    return dispatch  => {
        return {
            type: QUEUE_NEW_REQUEST,
            newRequestInfo
        }
    }
}
</code>```

答:
Your action doesn't dispatch the action to the reducer. You just passed it in as an argument. I also slightly updated the pass of the param to a key called "payload".  Try updating it like this

I've created a minimal sandbox here

If you click on one of the items and check your console you can see the reducer is being called.

```<code>export const QUEUE_NEW_REQUEST = "QUEUE_NEW_REQUEST";

export function queueNewRequest(newRequestInfo) {
  return dispatch =>
    dispatch({
      type: QUEUE_NEW_REQUEST,
      payload: newRequestInfo
    });
}
</code>```

Body:
I am trying to update my redux state from a child component(QResults.js) by calling a function that I pass to it  but my reducer isn't being reached when I use the function. QResults.js has a link that I am clicking which I expect to alter my state via one of my reducers. Am I doing something wrong with my mapDispatchToProps() function?

Channel.js

class Channel extends Component {
    ...
    render() {
        return (
        ...

            <QResults
             allQueryResults={this.state.queryState}
             requestHandler={queueNewRequest}/>

        );
    }
}

function mapStateToProps(state) {
   ...
}

 function mapDispatchToProps(dispatch) {
    return ({
        queueNewRequest: (newRequestData) => { dispatch(queueNewRequest(newRequestData)) }
    })
}

export default withRouter(connect(mapStateToProps , mapDispatchToProps )(Channel))

QResults.js

export default class QResults extends Component {
    render() {
        const {requestHandler} = this.props

        return (

                {this.props.allQueryResults.items.map((trackAlbum, i) =>

                         requestHandler(trackAlbum.name)}>
                            Some link

                )}

        )
    }
}

Reducers.js

import { combineReducers } from 'redux'

function reducer1(state = {}, action) {
    ...
}

function reducer2(state = {}, action) {
    switch (action.type) {
        case QUEUE_NEW_REQUEST:
            return{
                ...state,
                newRequestInfo : action.newRequestInfo
            }
        default:
            return state
    }
}

const rootReducer = combineReducers({
    reducer1,
    reducer2
})

export default rootReducer

Actions.js

export const QUEUE_NEW_REQUEST = 'QUEUE_NEW_REQUEST'

export function queueNewRequest(newRequestInfo) {
    return dispatch  => {
        return {
            type: QUEUE_NEW_REQUEST,
            newRequestInfo
        }
    }
}

Body:
Your action doesn't dispatch the action to the reducer. You just passed it in as an argument. I also slightly updated the pass of the param to a key called "payload".  Try updating it like this

I've created a minimal sandbox here

If you click on one of the items and check your console you can see the reducer is being called.

export const QUEUE_NEW_REQUEST = "QUEUE_NEW_REQUEST";

export function queueNewRequest(newRequestInfo) {
  return dispatch =>
    dispatch({
      type: QUEUE_NEW_REQUEST,
      payload: newRequestInfo
    });
}


问:
Why is an instance variable of the superclass not overridden by a subclass?
See my code below, in which the method print is overridden but variable a is not. Why is it allowed to declare duplicate variables in a subclass?

```<code>class B {
    int a = 10;
    public void print() {
        System.out.println("inside B superclass");
    }
}

class C extends B {
    int a = 20;
    public void print() {
        System.out.println("inside C subclass");
    }
}

public class A {
    public static void main(String[] args) {
        B b = new C();
        b.print(); // prints: inside C subclass
        System.out.println(b.a); // prints superclass variable value 10
    }
}
</code>```

答:
Like others have mentioned, you cannot override a super class's instance variables, but you can use constructors to assign the proper values for your objects. For example, you can use constructors to make the value of 'a' equal to '20' in class C.

This is your original code that is augmented using constructors to set the value for 'a' equal to '20' in class C.

Long story short, we are using the arguments of an object instance and of a constructors to pass up a value to the superclass.

```<code> public class B {
        private int a; //initialize int a
        public int getA() { //create a getter for a
            return a;
        }
    public B(int size) { //constructor that takes an int
            a = size; //sets a to the value in the parameters
        }
        public void print() {
            System.out.println("inside B superclass");
        }
    }

public class C extends B{
    public C(int a) { //C constructor takes an int
        super(a); //it send the name up to its superclass (B)
    }
    public void print() {
        System.out.println("inside C subclass");
    }
}

public class A {
    public static void main(String[] args) {
        B b = new C(20); //Creates a new object 'b' of type C
        b.print(); // prints: inside C subclass
        System.out.println(b.getA()); // prints the value '20'
    }
}
</code>```

Body:
See my code below, in which the method print is overridden but variable a is not. Why is it allowed to declare duplicate variables in a subclass?

class B {
    int a = 10;
    public void print() {
        System.out.println("inside B superclass");
    }
}

class C extends B {
    int a = 20;
    public void print() {
        System.out.println("inside C subclass");
    }
}

public class A {
    public static void main(String[] args) {
        B b = new C();
        b.print(); // prints: inside C subclass
        System.out.println(b.a); // prints superclass variable value 10
    }
}

Body:
Like others have mentioned, you cannot override a super class's instance variables, but you can use constructors to assign the proper values for your objects. For example, you can use constructors to make the value of 'a' equal to '20' in class C.

This is your original code that is augmented using constructors to set the value for 'a' equal to '20' in class C.

Long story short, we are using the arguments of an object instance and of a constructors to pass up a value to the superclass.

 public class B {
        private int a; //initialize int a
        public int getA() { //create a getter for a
            return a;
        }
    public B(int size) { //constructor that takes an int
            a = size; //sets a to the value in the parameters
        }
        public void print() {
            System.out.println("inside B superclass");
        }
    }

public class C extends B{
    public C(int a) { //C constructor takes an int
        super(a); //it send the name up to its superclass (B)
    }
    public void print() {
        System.out.println("inside C subclass");
    }
}

public class A {
    public static void main(String[] args) {
        B b = new C(20); //Creates a new object 'b' of type C
        b.print(); // prints: inside C subclass
        System.out.println(b.getA()); // prints the value '20'
    }
}


问:
Frustrating memory leak when loading an interstitial ad in Swift
I am dealing with an infuriating memory leak in regards to loading an interstitial ad via AdMob. When observing the memory in Xcode & Instruments, the memory jumps 10 MB every time I visit the view controller hosting the ad. Also when closing the app on my phone and reopening it, causes the memory to jump 30-40 mb as well which is just ridiculous.

I have tried profiling this in Instruments and the memory being allocated are all system libraries and nothing that points out to what is wrong. I have read other Stack Overflow answers such as ADMOB Memory Leaking?
but no answer has helped me so far. Maybe somebody can tell me what is wrong with my code? I have followed the exact documentation AdMob provides which is https://developers.google.com/admob/ios/interstitial and all works fine except this crazy memory leak. Here is the exact code that is causing the leak below.

class ViewController: UIViewController, GADInterstitialDelegate {

var interstitial: GADInterstitial!

override func viewDidLoad() {
  interstitial = createAndLoadInterstitial()
  interstitial.delegate = self
}

func update() {
        if interstitial.isReady {
            interstitial.present(fromRootViewController: self)
        }
    }

    func createAndLoadInterstitial() -> GADInterstitial {
        let interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
        interstitial.delegate = self
        let request = GADRequest()
        interstitial.load(request)
        return interstitial
    }

    func interstitialDidDismissScreen(_ ad: GADInterstitial) {
        interstitial = createAndLoadInterstitial()
    }

// I am calling update() inside a button when pressed in this VC.
```

答:
I just want to say that this actually has been solved by me. I did as one of the above stated in the comments. I took my code that was on the view controller hosting the interstitial ad and moved it to the app delegate. I simply then just referenced the interstitial ad object whenever I need it in my project. This brought the memory back down to whatever it allocated upon visiting the controller hosting the ad. For those that want to see a very simple example of what this looks like in the app delegate:</p>

```<code>import UIKit
import GoogleMobileAds

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GADInterstitialDelegate {

    var myInterstitial: GADInterstitial!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        GADMobileAds.sharedInstance().start(completionHandler: nil)
        myInterstitial = createAndLoadInterstitial()
        return true
    }

    func createAndLoadInterstitial() -> GADInterstitial {
        let interstitial = GADInterstitial(adUnitID: "yourAdID")
        interstitial.delegate = self
        let request = GADRequest()
        interstitial.load(request)
        return interstitial
    }

    func interstitialDidDismissScreen(_ ad: GADInterstitial) {
        myInterstitial = createAndLoadInterstitial()
    }
</code>```

Body:
I just want to say that this actually has been solved by me. I did as one of the above stated in the comments. I took my code that was on the view controller hosting the interstitial ad and moved it to the app delegate. I simply then just referenced the interstitial ad object whenever I need it in my project. This brought the memory back down to whatever it allocated upon visiting the controller hosting the ad. For those that want to see a very simple example of what this looks like in the app delegate:

import UIKit
import GoogleMobileAds

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GADInterstitialDelegate {

    var myInterstitial: GADInterstitial!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        GADMobileAds.sharedInstance().start(completionHandler: nil)
        myInterstitial = createAndLoadInterstitial()
        return true
    }

    func createAndLoadInterstitial() -> GADInterstitial {
        let interstitial = GADInterstitial(adUnitID: "yourAdID")
        interstitial.delegate = self
        let request = GADRequest()
        interstitial.load(request)
        return interstitial
    }

    func interstitialDidDismissScreen(_ ad: GADInterstitial) {
        myInterstitial = createAndLoadInterstitial()
    }


问:
how to grab a csv url
I have run into this problem before and still don't know what I can do, so I figured I would ask here.

Say I have a website like: https://www.macrotrends.net/stocks/charts/AAPL/apple/stock-price-history

if you scroll down a bit there is a red button "Download Data". This downloads the csv.

I would like to read this csv into a data frame in Python or R. Whatever 'read csv' function I use, I need a url. My question is: How do I get a url for this csv? That's all I need to know.

答:
It sounds like you are looking for the url for this specific case, and not a general solution for similar cases, if that is the case, I think this is the url you are looking for:

http://download.macrotrends.net/assets/php/stock_data_export.php?t=AAPL

The way I found it was

Load the url from the question

RMB on download button and click Inspect Element (I used Opera, but I know chrome has an equivalent)

Open the console (tab on top of inspection pane)

Clicked the red download button you mentioned

Watched the console until I saw something that looked like it was fetching something and tried that url

It seems like a bit of a hack, but it downloads the data.

Since you mentioned python, @HEADLESS_0NE has a good answer on how to Use python requests to download CSV

Title: how to grab a csv url


问:
How to create an intersection with complexity in O (n)?
I need to create a function that intersects two vectors: vectorA ∩ vectorB and allocates the values found in this intersection in a vectorC!

Rules:

(a) The complexity of the function/method must be:

O(n), if n> m

O(m), if m> n

(b) The complexity of the program (function / main method) must be:

O(n log n), if n > m

O(m log m), if m > n

c) The signing of the function of intersection shall be obligatorily:

void intersections (char a [], int n, char b [], int m, char c [], int * k)

d) Predefined language functions can not be used to treat vectors (search, pertinence, insertion, deletion, ordering, etc.).

I was thinking of using an algorithm of complexity O(n) which is called "Linear Time". However this algorithm makes it "linear" comparison obviously as the name says.

Example:

```<code>A = { 'E', 'C', 'B', 'J', 'S', 'F', 'C', 'V', 'G' }
B = { 'G', 'C', 'M', 'W', 'L', 'O' }
C = { 'G', 'C' }
</code>```

How far have I come?

Currently I can fetch and compare the corresponding values for the intersection.

What is my difficulty?

1) The values after the comparison can not be added to the vector char c[] with repetitions. How to prevent the same?

2) How to use the pointer int *k (which is the size of the vector char c[]) and allocate the corresponding values without repetitions to it?

```<code>bool checkHasStringEqual(char vectorA, char vectorB) {
    string stringA, stringB;
    stringA = toupper(vectorA),
    stringB = toupper(vectorB);

    size_t found = stringA.find(stringB);

    return (found != std::string::npos);
}

void intersection(char a[], char b[], char c[], int n, int m, int *k){
    int indexA = 0, indexB = 0, counterIntersection = 0;

    if(n > m) {
        while(indexA < n) {
            if(indexB != m) {
                if(checkHasStringEqual(a[indexA], b[indexB])) {
                    cout << "STRING A: " << a[indexA] << " == " << "STRING B: " << b[indexB] << endl;
                    counterIntersection++;
                }

                cout << "( " << a[indexA] << "-->" << b[indexB] << ")" << " -- " << "( " << indexA << ", " << indexB << ")" << endl;
                (indexA == n -1) ? (indexA = 0, indexB++) : indexA++;

            } else {
                cout << "CAME TO THE END OF THE ANALYSIS" << endl;
                break;
            }
        }
    }

    if(m > n) {
        //TODO
    }
}
</code>```

答:
If you don't worry about using too much memory, you can initialize 2 256-element integer arrays a_set, b_set which will be used to keep track of the occurrence of each character from 0-255 in array a and b, respectively. By using a_set, you will add any character chr from b to c if and only if a_set[chr] is equal to 1 and b_set[chr] is equal to 0. After adding chr to c, you will set b_set[chr]=1; in order to avoid repetitions of characters.

The time complexity for this approach is O(n + m) --> O(max(n,m)).

I also added the main method below so you can check if it is your desired output for C and k.

```<code>#include <iostream>

using namespace std;

bool checkHasStringEqual(char vectorA, char vectorB) {
    return toupper(vectorA) == toupper(vectorB);
}

void intersection(char a[], char b[], char c[], int n, int m, int *k){
    int indexA = 0, indexB = 0, counterIntersection = 0;
    unsigned char chr;
    // unsigned char can only go from 0-255
    int a_set[256] = {0}; // initialize array to 0
    int b_set[256] = {0}; // initialize array to 0
    *k = 0; // initialize k value to 0

    for (int i = 0; i < n; ++i) {
        chr = a[i];
        a_set[chr] = 1;
    }

    for (int i = 0; i < m; ++i) {
        chr = b[i];
        if (a_set[chr] && !b_set[chr]) {
            c[*k] = b[i];
            (*k)++; // increase k index
        }
        b_set[chr] = 1; // mark character as inserted
    }
}

int main() {
    int n = 9;
    int m = 6;
    int k;
    char A[n] = { 'E', 'C', 'B', 'J', 'S', 'F', 'C', 'V', 'G' };
    char B[m] = { 'G', 'C', 'M', 'W', 'L', 'O' };
    char C[max(n, m)]; // C will contain at most maximum of n, m elements

    intersection(A, B, C, n, m, &k);
    cout << "Intersection: " << endl;
    for (int i = 0; i < k; ++i) {
        cout << C[i] << endl;
    }
    return 0;
}

</code>```

Body:
I need to create a function that intersects two vectors: vectorA ∩ vectorB and allocates the values found in this intersection in a vectorC!

Rules:

(a) The complexity of the function/method must be:

O(n), if n> m

O(m), if m> n

(b) The complexity of the program (function / main method) must be:

O(n log n), if n > m

O(m log m), if m > n

c) The signing of the function of intersection shall be obligatorily:

void intersections (char a [], int n, char b [], int m, char c [], int * k)

d) Predefined language functions can not be used to treat vectors (search, pertinence, insertion, deletion, ordering, etc.).

I was thinking of using an algorithm of complexity O(n) which is called "Linear Time". However this algorithm makes it "linear" comparison obviously as the name says.

Example:

A = { 'E', 'C', 'B', 'J', 'S', 'F', 'C', 'V', 'G' }
B = { 'G', 'C', 'M', 'W', 'L', 'O' }
C = { 'G', 'C' }

How far have I come?

Currently I can fetch and compare the corresponding values for the intersection.

What is my difficulty?

1) The values after the comparison can not be added to the vector char c[] with repetitions. How to prevent the same?

2) How to use the pointer int *k (which is the size of the vector char c[]) and allocate the corresponding values without repetitions to it?

bool checkHasStringEqual(char vectorA, char vectorB) {
    string stringA, stringB;
    stringA = toupper(vectorA),
    stringB = toupper(vectorB);

    size_t found = stringA.find(stringB);

    return (found != std::string::npos);
}

void intersection(char a[], char b[], char c[], int n, int m, int *k){
    int indexA = 0, indexB = 0, counterIntersection = 0;

    if(n > m) {
        while(indexA < n) {
            if(indexB != m) {
                if(checkHasStringEqual(a[indexA], b[indexB])) {
                    cout << "STRING A: " << a[indexA] << " == " << "STRING B: " << b[indexB] << endl;
                    counterIntersection++;
                }

                cout << "( " << a[indexA] << "-->" << b[indexB] << ")" << " -- " << "( " << indexA << ", " << indexB << ")" << endl;
                (indexA == n -1) ? (indexA = 0, indexB++) : indexA++;

            } else {
                cout << "CAME TO THE END OF THE ANALYSIS" << endl;
                break;
            }
        }
    }

    if(m > n) {
        //TODO
    }
}

Body:
If you don't worry about using too much memory, you can initialize 2 256-element integer arrays a_set, b_set which will be used to keep track of the occurrence of each character from 0-255 in array a and b, respectively. By using a_set, you will add any character chr from b to c if and only if a_set[chr] is equal to 1 and b_set[chr] is equal to 0. After adding chr to c, you will set b_set[chr]=1; in order to avoid repetitions of characters.

The time complexity for this approach is O(n + m) --> O(max(n,m)).

I also added the main method below so you can check if it is your desired output for C and k.

#include <iostream>

using namespace std;

bool checkHasStringEqual(char vectorA, char vectorB) {
    return toupper(vectorA) == toupper(vectorB);
}

void intersection(char a[], char b[], char c[], int n, int m, int *k){
    int indexA = 0, indexB = 0, counterIntersection = 0;
    unsigned char chr;
    // unsigned char can only go from 0-255
    int a_set[256] = {0}; // initialize array to 0
    int b_set[256] = {0}; // initialize array to 0
    *k = 0; // initialize k value to 0

    for (int i = 0; i < n; ++i) {
        chr = a[i];
        a_set[chr] = 1;
    }

    for (int i = 0; i < m; ++i) {
        chr = b[i];
        if (a_set[chr] && !b_set[chr]) {
            c[*k] = b[i];
            (*k)++; // increase k index
        }
        b_set[chr] = 1; // mark character as inserted
    }
}

int main() {
    int n = 9;
    int m = 6;
    int k;
    char A[n] = { 'E', 'C', 'B', 'J', 'S', 'F', 'C', 'V', 'G' };
    char B[m] = { 'G', 'C', 'M', 'W', 'L', 'O' };
    char C[max(n, m)]; // C will contain at most maximum of n, m elements

    intersection(A, B, C, n, m, &k);
    cout << "Intersection: " << endl;
    for (int i = 0; i < k; ++i) {
        cout << C[i] << endl;
    }
    return 0;
}


问:
Adding URDF file for VLP-16 into Gazebo
I want to simulate an algorithm we wrote in Gazebo. The base robot I am using is the clearpath Husky. And, I need to put a Velodyne VLP-16 Lidar on it to extract the point clouds. The way I am going about it is trying to make my own custom world and launching the Husky launch file which spawns the Husky in a custom world. I just want to know what would be the best way to put the lidar on top of the husky? Can I just modify the world file? Or will I need to change the clearpath file? I downloaded the velodyne_simulator package from Velodyne and it comes with a VLP-16.urdf.xacro. Is there anyway I can use that? Any help would be appreciated. Thanks </p>

答:
The answer by @mastash3ff is mostly correct except there are few things missing. As per the latest husky package you can bring up velodyne VLP-16 or say any model by setting "HUSKY_URDF_EXTRAS" environment variable to the urdf file you want to include.

```<code>export HUSKY_URDF_EXTRAS=/path/to/vlp.urdf
</code>```

In my case vlp.urdf looked like this. You can also follow the same pattern

```<code><?xml version="1.0"?>
<robot xmlns:xacro="http://www.ros.org/wiki/xacro" name="example">
 <xacro:include filename="$(find velodyne_description)/urdf/VLP-16.urdf.xacro"/>
  <VLP-16 parent="top_plate_link" name="velodyne" topic="/velodyne_points" hz="10" samples="440">
    <origin xyz="0.2206 0.0 0.00635" rpy="0 0 0" />
  </VLP-16>
</robot>
</code>```

Hope this helps.

Title: Adding URDF file for VLP-16 into Gazebo

Body:
The answer by @mastash3ff is mostly correct except there are few things missing. As per the latest husky package you can bring up velodyne VLP-16 or say any model by setting "HUSKY_URDF_EXTRAS" environment variable to the urdf file you want to include.

export HUSKY_URDF_EXTRAS=/path/to/vlp.urdf

In my case vlp.urdf looked like this. You can also follow the same pattern

<?xml version="1.0"?>
<robot xmlns:xacro="http://www.ros.org/wiki/xacro" name="example">
 <xacro:include filename="$(find velodyne_description)/urdf/VLP-16.urdf.xacro"/>
  <VLP-16 parent="top_plate_link" name="velodyne" topic="/velodyne_points" hz="10" samples="440">
    <origin xyz="0.2206 0.0 0.00635" rpy="0 0 0" />
  </VLP-16>
</robot>

Hope this helps.


问:
Warning about SSL connection when connecting to MySQL database
With the two classes below, I've tried connect to a MySQL database. However, I always get this error:

Wed Dec 09 22:46:52 CET 2015 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

This is the test class with the main method:

```<code>public class TestDatabase {

    public static void main(String[] args) {
        Database db = new Database();
        try {
            db.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        db.close();
    }
}
</code>```

This is the Database class:

```<code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Database {

    private Connection con;

    public void connect() throws Exception{

        if(con != null) return;

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new Exception("No database");
        }

        String connectionURL = "jdbc:mysql://localhost:3306/Peoples";

        con = DriverManager.getConnection(connectionURL, "root", "milos23");
    }

    public void close(){
        if(con != null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
</code>```

答:
Solution
To fix it, append a useSSL=false at the end of the MySQL connection string :

ex.

application.properties

mysql datasource

```<code>spring.datasource.url=jdbc:mysql://localhost/dbname?useSSL=false
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
</code>```

Body:
With the two classes below, I've tried connect to a MySQL database. However, I always get this error:

Wed Dec 09 22:46:52 CET 2015 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

This is the test class with the main method:

public class TestDatabase {

    public static void main(String[] args) {
        Database db = new Database();
        try {
            db.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        db.close();
    }
}

This is the Database class:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Database {

    private Connection con;

    public void connect() throws Exception{

        if(con != null) return;

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new Exception("No database");
        }

        String connectionURL = "jdbc:mysql://localhost:3306/Peoples";

        con = DriverManager.getConnection(connectionURL, "root", "milos23");
    }

    public void close(){
        if(con != null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Body:
Solution
To fix it, append a useSSL=false at the end of the MySQL connection string :

ex.

application.properties

mysql datasource

spring.datasource.url=jdbc:mysql://localhost/dbname?useSSL=false
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver


问:
Make a column required if other column is of certain value
What I have:

```<code>CREATE TABLE [dbo].[User]
(
    [id] INT NOT NULL PRIMARY KEY,
    [name] VARCHAR(50) NOT NULL,
    [postcode] INT NOT NULL,
    [phone] INT NULL
)
</code>```

What I want is that the phone number is required ONLY if the postcode is higher than 40000. If postcode is smaller than 40000, user can insert the phone number, although it is not required.

How do I do this?

答: This needs to be handled from the front end inserting values into the Database. Insert Query on one column based on another in the DB for the same table is not possible.</p>

Body:
What I have:

CREATE TABLE [dbo].[User]
(
    [id] INT NOT NULL PRIMARY KEY,
    [name] VARCHAR(50) NOT NULL,
    [postcode] INT NOT NULL,
    [phone] INT NULL
)

What I want is that the phone number is required ONLY if the postcode is higher than 40000. If postcode is smaller than 40000, user can insert the phone number, although it is not required.

How do I do this?