问:
Pygame gfxdraw module change line weight
I'm attempting to use the pygame.gfxdraw module in order to draw arcs. This module suits me better than the traditional pygame.draw module as it only requires a center point rather than a surrounding rectangle. However, for graphical reasons, I would like to increase the line weight of the arc so it is greater than one pixel thick. Is there any way to do this?

Thanks!

答:
I don’t think this is supported in gfxdraw yet. You could define a new arc function as follows:

def draw_arc(surface, col, x, y, r, start_angle, stop_angle, width=1):
    """Draw an arc given the centre and radius"""
    pygame.draw.arc(
        surface, col, (x - r, y - r, r * 2, r * 2), start_angle, stop_angle, width=width
    )
```

Note that this function uses radians and works anticlockwise. gfxdraw uses degrees and works clockwise.

Body:
I don’t think this is supported in gfxdraw yet. You could define a new arc function as follows:

def draw_arc(surface, col, x, y, r, start_angle, stop_angle, width=1):
    """Draw an arc given the centre and radius"""
    pygame.draw.arc(
        surface, col, (x - r, y - r, r * 2, r * 2), start_angle, stop_angle, width=width
    )

Note that this function uses radians and works anticlockwise. gfxdraw uses degrees and works clockwise.


来源: stackexchange

问:
Problem with array.reverse() in node v12.6.0
After updating node to newest version, my tests breaks saying my array doesn't reverse. I have an array with 4 numbers and jest saying it expects the numbers in my array reversed, but after running the .reverse() it doesnt do as its supposed to. Is this a new kind of problem with node?

```<code>  it(`should handle ${SORT_MEMBERS}`, () => {
    const members = [{ ssn: 7 }, { ssn: 6 }, { ssn: 5 }, { ssn: 4 }];

    const attr = 'ssn';
    const order = SORT_ORDER.ASC;

    let newState = reducer(state, {
      type: INIT_MEMBERS,
      payload: { members },
    });

    newState = reducer(newState, {
      type: SORT_MEMBERS,
      payload: { attr, order }
    });

    expect(newState).toEqual({
      ...state,
      members: members.reverse(),
      sort: { attr, order },
    });

  });
</code>```

Initial state:

```<code>const initialState = {
  batchUpdates: {
    salaryChangePercentage: '',
    applyDate: null,
  },
  form: {
    ableToWork: null,
    memberErrors: null,
  },
  updates: {}, // hash with ssn as key
  members: [],
  errors: {},
  sort: {
    attr: null,
    order: null,
  },
  saving: false,
  saved: false,
  saveResult: null,
  saveError: null,
};
</code>```

case SORT_MEMBER:

```<code> case SORT_MEMBERS:
      return {
        ...state,
        members: sortMembers(state.members, state.updates, action.payload.attr, action.payload.order),
        sort: {
          attr: action.payload.attr,
          order: action.payload.order,
        },
      };
</code>```

And finally my sort method:

```<code>export const sortMembers = (members, updates, attr, order) => {
  const sorted = members.slice();
  const path = attr.split('.');
  const byUpdates = path.length === 2 && path[0] === 'updates';

  if (!byUpdates) {
    return sorted.sort((a, b) => (
      order === SORT_ORDER.DESC ? a[attr] < b[attr] : a[attr] > b[attr]
    ));
  }
  // Sort by updates on given ssn
  return sorted.sort((a, b) => (
    order === SORT_ORDER.DESC
      ? updates[a.ssn][path[1]] < updates[b.ssn][path[1]] : updates[a.ssn][path[1]] > updates[b.ssn][path[1]]
  ));
};
</code>```

It used to work before I updated my Node.js

答:
I found the solution to the problem!

There is a misstype in following code:

```<code>order === SORT_ORDER.DESC ? a[attr] < b[attr] : a[attr] > b[attr]
</code>```

There should be - and +, not > and <. The correct is following:

```<code>order === SORT_ORDER.DESC ? a[attr] + b[attr] : a[attr] - b[attr]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
After updating node to newest version, my tests breaks saying my array doesn't reverse. I have an array with 4 numbers and jest saying it expects the numbers in my array reversed, but after running the .reverse() it doesnt do as its supposed to. Is this a new kind of problem with node?

  it(`should handle ${SORT_MEMBERS}`, () => {
    const members = [{ ssn: 7 }, { ssn: 6 }, { ssn: 5 }, { ssn: 4 }];

    const attr = 'ssn';
    const order = SORT_ORDER.ASC;

    let newState = reducer(state, {
      type: INIT_MEMBERS,
      payload: { members },
    });

    newState = reducer(newState, {
      type: SORT_MEMBERS,
      payload: { attr, order }
    });

    expect(newState).toEqual({
      ...state,
      members: members.reverse(),
      sort: { attr, order },
    });

  });

Initial state:

const initialState = {
  batchUpdates: {
    salaryChangePercentage: '',
    applyDate: null,
  },
  form: {
    ableToWork: null,
    memberErrors: null,
  },
  updates: {}, // hash with ssn as key
  members: [],
  errors: {},
  sort: {
    attr: null,
    order: null,
  },
  saving: false,
  saved: false,
  saveResult: null,
  saveError: null,
};

case SORT_MEMBER:

 case SORT_MEMBERS:
      return {
        ...state,
        members: sortMembers(state.members, state.updates, action.payload.attr, action.payload.order),
        sort: {
          attr: action.payload.attr,
          order: action.payload.order,
        },
      };

And finally my sort method:

export const sortMembers = (members, updates, attr, order) => {
  const sorted = members.slice();
  const path = attr.split('.');
  const byUpdates = path.length === 2 && path[0] === 'updates';

  if (!byUpdates) {
    return sorted.sort((a, b) => (
      order === SORT_ORDER.DESC ? a[attr]  b[attr]
    ));
  }
  // Sort by updates on given ssn
  return sorted.sort((a, b) => (
    order === SORT_ORDER.DESC
      ? updates[a.ssn][path[1]] < updates[b.ssn][path[1]] : updates[a.ssn][path[1]] > updates[b.ssn][path[1]]
  ));
};

It used to work before I updated my Node.js

Body:
I found the solution to the problem!

There is a misstype in following code:

order === SORT_ORDER.DESC ? a[attr] < b[attr] : a[attr] > b[attr]

There should be - and +, not > and <. The correct is following:

order === SORT_ORDER.DESC ? a[attr] + b[attr] : a[attr] - b[attr]


问:
Excel code crashes after a couple of uses, opening a connection to Access
We have an Excel 2016 quoting tool that uses VBA code to compare the product codes entered against an Access database and then update another sheet with the details needed for our CRM system.

This is an interim solution until a more permanent one becomes available.

We can capture 5 quotes, generate the CRM sheet. On the 6th quote when you generate the CRM sheet the following VBA Error shows up.

System Error &H8000FFF (-2147418113)

Fixes I tried, increase the buffer size, clear clipboard. Removing the buffer causes the error almost immediately.

I found in debugging that the crash will happen at cn.Open as it tries to open a connection to Access.

Function CRM_Update(PROD As String)
Application.ScreenUpdating = False

    If PROD = "" Then
        emptyline = emptyline + 1
        Exit Function
    Else
        emptyline = 0
    End If
    Set cn = New ADODB.Connection
    cn.ConnectionString = "DSN=MS Access Database;DBQ=C:\database\CRMSA.accdb;DriverId=25;FIL=MS Access;MaxBufferSize=4096;PageTimeout=5;"
    cn.Open
    Set rs = New ADODB.Recordset**
    rs.Open "select * from ARTGROUP WHERE  ART = '" & PROD & "';", cn, adOpenStatic
    If rs.RecordCount = 0 Then
        MsgBox (PROD & "  " & " not found in article group")
        Exit Function
    End If
```
<p>This looks to be related to memory use because you can get further into the generate process if you have very little open but as soon as you have a lot of items open: Chrome, Outlook and other applications you can get maybe 5 generate attempts.<br />
On a virtual machine with only 4GB of RAM I was able to do this process over 40 times without a single crash.<br />
On my work laptop with 16GB of RAM and only this open I was able to generate about 16 times before that error comes up.</p>
<p>Event log:</p>
<blockquote>
<p>The system has called a custom component and that component has failed
and generated an exception. This indicates a problem with the custom
component. Notify the developer of this component that a failure has
occurred and provide them with the information below. Component Prog
ID: SC.Pool 455 1 Method Name: IDispenserDriver::CreateResource
Process Name: EXCEL.EXE Exception: c0000005 Address: 0X58101018</p>
</blockquote>
<p>I removed all custom add-ins and still get this crash. I only have the following MS references in the sheet running namely:</p>
<p>VB for Applications<br />
MS Excel 16.0 Object Library<br />
OLE Automation<br />
MS Office 16.0 Object Library<br />
MS Access 16.0 Object Library<br />
Microsoft ActiveX Data Objects 2.8 Library</p>
<p>I tried rebuilding the database, compact and repair and decompile but it has no effect.<br />
I have white listed the database in AV program with no change.</p>
<p><em>edit</em></p>
<p>Module 1 is the first VB script that I think opens the Access database.<br />
Module 2 is VB script that says Cell A in Worksheet A goes to Cell A in Worksheet B, it too is also opening a connection to the Access database but I have not included the formula for the moving part.<br />
There is a third module that compares the data from the Excel sheet with the Access database and then assigns product codes.</p>
<p>Module 1:</p>
<pre class="lang-vb prettyprint-override"><code>Public Function CRM_shortDescr(PROD As String)
Application.ScreenUpdating = False
    Set cn = New ADODB.Connection
    cn.ConnectionString = "DSN=MS Access Database;DBQ=C:\database\CRMSA.accdb;DriverId=25;FIL=MS Access;MaxBufferSize=4096;PageTimeout=5;"
    '   The database name was set incorrectly here. Changed to correct name.
    cn.Open
    Set rs = New ADODB.Recordset
    rs.Open "select * from ARTGROUP WHERE  ART = '" & PROD & "';", cn, adOpenStatic
    If rs.RecordCount = 0 Then
        MsgBox (PROD & "  " & " not found in article group")
        Exit Function
    End If
    PRGR = rs!crm
    rs.Close
    rs.Open "select * from PRGR WHERE  PRGR = '" & Left(PRGR, 2) & "';", cn, adOpenStatic
    If rs.RecordCount = 0 Then
        MsgBox (PRGR & "  " & " not found in article group")
        Exit Function
    End If
    CRM_shortDescr = rs!Descr
    rs.Close
End Function
</code>```

Module 2 is the one above at the start of this post, missing lines are:

italyrow = 19 + emptyline
    linenumber = ActiveCell.Row
    linenumbercrm = linenumber - italyrow
<Formual starts to move from Sheet A to Sheet B but looks like the following
`Worksheets("CRM").Cells(linenumbercrm, 1).Value = Worksheets("Local Quotation").Range("COUNTRY")>
rs.Close
End Function
```

答: Problem appears to be solved and it had nothing to do with the code <_<. KB4484218 is the culprit that is breaking everything somehow.</p>

Body:
We have an Excel 2016 quoting tool that uses VBA code to compare the product codes entered against an Access database and then update another sheet with the details needed for our CRM system.

This is an interim solution until a more permanent one becomes available.

We can capture 5 quotes, generate the CRM sheet. On the 6th quote when you generate the CRM sheet the following VBA Error shows up.

System Error &H8000FFF (-2147418113)

Fixes I tried, increase the buffer size, clear clipboard. Removing the buffer causes the error almost immediately.

I found in debugging that the crash will happen at cn.Open as it tries to open a connection to Access.

Function CRM_Update(PROD As String)
Application.ScreenUpdating = False

    If PROD = "" Then
        emptyline = emptyline + 1
        Exit Function
    Else
        emptyline = 0
    End If
    Set cn = New ADODB.Connection
    cn.ConnectionString = "DSN=MS Access Database;DBQ=C:\database\CRMSA.accdb;DriverId=25;FIL=MS Access;MaxBufferSize=4096;PageTimeout=5;"
    cn.Open
    Set rs = New ADODB.Recordset**
    rs.Open "select * from ARTGROUP WHERE  ART = '" & PROD & "';", cn, adOpenStatic
    If rs.RecordCount = 0 Then
        MsgBox (PROD & "  " & " not found in article group")
        Exit Function
    End If

This looks to be related to memory use because you can get further into the generate process if you have very little open but as soon as you have a lot of items open: Chrome, Outlook and other applications you can get maybe 5 generate attempts.

On a virtual machine with only 4GB of RAM I was able to do this process over 40 times without a single crash.

On my work laptop with 16GB of RAM and only this open I was able to generate about 16 times before that error comes up.

Event log:

The system has called a custom component and that component has failed
and generated an exception. This indicates a problem with the custom
component. Notify the developer of this component that a failure has
occurred and provide them with the information below. Component Prog
ID: SC.Pool 455 1 Method Name: IDispenserDriver::CreateResource
Process Name: EXCEL.EXE Exception: c0000005 Address: 0X58101018

I removed all custom add-ins and still get this crash. I only have the following MS references in the sheet running namely:

VB for Applications

MS Excel 16.0 Object Library

OLE Automation

MS Office 16.0 Object Library

MS Access 16.0 Object Library

Microsoft ActiveX Data Objects 2.8 Library

I tried rebuilding the database, compact and repair and decompile but it has no effect.

I have white listed the database in AV program with no change.

edit

Module 1 is the first VB script that I think opens the Access database.

Module 2 is VB script that says Cell A in Worksheet A goes to Cell A in Worksheet B, it too is also opening a connection to the Access database but I have not included the formula for the moving part.

There is a third module that compares the data from the Excel sheet with the Access database and then assigns product codes.

Module 1:

Public Function CRM_shortDescr(PROD As String)
Application.ScreenUpdating = False
    Set cn = New ADODB.Connection
    cn.ConnectionString = "DSN=MS Access Database;DBQ=C:\database\CRMSA.accdb;DriverId=25;FIL=MS Access;MaxBufferSize=4096;PageTimeout=5;"
    '   The database name was set incorrectly here. Changed to correct name.
    cn.Open
    Set rs = New ADODB.Recordset
    rs.Open "select * from ARTGROUP WHERE  ART = '" & PROD & "';", cn, adOpenStatic
    If rs.RecordCount = 0 Then
        MsgBox (PROD & "  " & " not found in article group")
        Exit Function
    End If
    PRGR = rs!crm
    rs.Close
    rs.Open "select * from PRGR WHERE  PRGR = '" & Left(PRGR, 2) & "';", cn, adOpenStatic
    If rs.RecordCount = 0 Then
        MsgBox (PRGR & "  " & " not found in article group")
        Exit Function
    End If
    CRM_shortDescr = rs!Descr
    rs.Close
End Function

Module 2 is the one above at the start of this post, missing lines are:

italyrow = 19 + emptyline
    linenumber = ActiveCell.Row
    linenumbercrm = linenumber - italyrow
<Formual starts to move from Sheet A to Sheet B but looks like the following
`Worksheets("CRM").Cells(linenumbercrm, 1).Value = Worksheets("Local Quotation").Range("COUNTRY")>
rs.Close
End Function


问:
Adminlte script is not working in Laravel
I follow this video and its work well, but when I am trying to try like date-picker or multiple select its not working. I check google crome console but I see no error.

I am using Laravel 6.* and Adminlte 3

```<code><html>
<head>
<title>AdminLTE 3 | Advanced form elements</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{ asset('css/app.css')}}">
<script src="{{ asset('js/fontawesome.js')}}"></script>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
      <div class="col-md-6">
        <div class="card card-primary">
          <div class="card-header">
            <h3 class="card-title">Date picker</h3>
          </div>
          <div class="card-body">
            <!-- Date range -->
            <div class="form-group">
              <label>Date range:</label>
              <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text">
                    <i class="far fa-calendar-alt"></i>
                  </span>
                </div>
                <input type="text" class="form-control float-right" id="reservation">
              </div>
            </div>
            <div class="form-group">
              <label>Date and time range:</label>
              <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text"><i class="far fa-clock"></i></span>
                </div>
                <input type="text" class="form-control float-right" id="reservationtime">
              </div>
            </div>
<script src="{{ asset('/js/app.js')}}"></script>

</body>
</html>
</code>```

Screenshot of date-picker and console.

I found this and its not working for me

laravel adminlte css path not working

答:
Hi please try to add this before you render the input field "reservationtime".</p>

```<code>    <script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery('#reservationtime').datepicker();
    })
    </script>
</code>```

Body:
I follow this video and its work well, but when I am trying to try like date-picker or multiple select its not working. I check google crome console but I see no error.

I am using Laravel 6.* and Adminlte 3

<title>AdminLTE 3 | Advanced form elements</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{ asset('css/app.css')}}">

Date picker

              Date range:

                <input type="text" class="form-control float-right" id="reservation">

              Date and time range:

                <input type="text" class="form-control float-right" id="reservationtime">

Screenshot of date-picker and console.

I found this and its not working for me

laravel adminlte css path not working

Body:
Hi please try to add this before you render the input field "reservationtime".

    <script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery('#reservationtime').datepicker();
    })
    </script>


问:
Instance is not defined despite being instantiated
I am trying to create a Box2D body, and I need to do it in a function, so I have this very simple function:

```<code>def create_car():
    my_Car = Car("Interesting parameters"))
    return my_Car
create_car()
</code>```

and then I have this main PyGame loop

```<code>running = True
while running:
    my_Car.steer()
</code>```

steer() as the definition suggests is a method written in class Car
But when I try to run the code this error is raised

```<code>my_Car() is not defined
</code>```

What am I doing wrong and how can I fix this?
Thank you very much

答:
Variables defined inside a function have a local scope, meaning that they cannot be accessed from the outside world of the function. The following should do the trick: </p>

```<code>def create_car():
    my_Car = Car("Interesting parameters")
    return my_Car

if __name__ == '__main__':

    car = create_car()

    while True:
        car.steer()
</code>```

Body:
I am trying to create a Box2D body, and I need to do it in a function, so I have this very simple function:

def create_car():
    my_Car = Car("Interesting parameters"))
    return my_Car
create_car()

and then I have this main PyGame loop

running = True
while running:
    my_Car.steer()

steer() as the definition suggests is a method written in class Car
But when I try to run the code this error is raised

my_Car() is not defined

What am I doing wrong and how can I fix this?
Thank you very much

Body:
Variables defined inside a function have a local scope, meaning that they cannot be accessed from the outside world of the function. The following should do the trick:

def create_car():
    my_Car = Car("Interesting parameters")
    return my_Car

if __name__ == '__main__':

    car = create_car()

    while True:
        car.steer()


问:
Handling paper documentation
After every new program written a lot of paper documentation remains.

Apart from the usual scribble notes from the programmers there usually is a nice heap of papers containing physical model explanations, calculations and so on (equations, tables, graphs, little pictures describing variables ...)

We usually do numerically intensive calculations in console applications, which are not released to the public (remain in the house, only results go out). Before each project is finished all those papers have to be packed somehow with the application, so that one day, when someone will be reusing parts of it, has some idea what is what in there.
So far, we've been using the 'dirty' solution of just scanning all of it, and packing it up on the disc with the application.

So I was wondering ... for all science guys here in a similar situation ... how do you handle project documentation which is needed, but not released to the public ?
(the one that does, goes to the dtp laddies, and they make it nice and shiny - not our problem anymore :)

答: If it's important, it seems to me you should treat the internal documentation with the same care with which you treat the public docs. </p>

ContentLicense: CC BY-SA 2.5

Title: Handling paper documentation

OwnerDisplayName: Patrick McElhaney


问:
How to properly set the path in Windows Vista cmd using batch file?
I am a complete newbie when it comes to programming and some basic computer concepts so pls be patient with me if my question might look so silly.

I am trying to create a batch file command that will automatically redirect me to a particular directory. What happens is that when I call the batch file it will only display the path but still in the same directory. I am doing this for shortcut purposes.

This is the default directory whenever I open my cmd-prompt (I don't want to change the default):

C:\Users\eacomm>

Here's the command that I typed and saved it as setpath.bat:

path=C:\Program Files\EasyPHP-5.3.6.0\www\cakephp;

Here is the result whenever I call setpath  and hit ENTER:

C:\Users\eacomm>C:\Program Files\EasyPHP-5.3.6.0\www\cakephp;

I want to redirect this one... Whats wrong with this??? Pls help...

答:
Why don't use simply:

```<code>cd C:\Program Files\EasyPHP-5.3.6.0\www\cakephp
</code>```

inside your .bat file?

ContentLicense: CC BY-SA 3.0

Body:
Why don't use simply:

cd C:\Program Files\EasyPHP-5.3.6.0\www\cakephp

inside your .bat file?


问:
Python3.8.1 installed but the compiler can't find it
Python 3.8.1 has been installed, but it still says the version is 2.7.17. How can I actually use 3.8.1?</p>

```<code>$ brew install python@3.8
Warning: python@3.8 3.8.1 is already installed and up-to-date
To reinstall 3.8.1, run `brew reinstall python@3.8`
$ python --version
Python 2.7.17
</code>```

答:
Homebrew installs Python 3 under python3; it never aliases python to Python 3 unless you explicitely ask it: https://docs.brew.sh/Homebrew-and-Python#python-3x-or-python-2x

The executables are organised as follows so that Python 2 and Python 3
  can both be installed without conflict:

python3 points to Homebrew’s Python 3.x (if installed)

python2 points to Homebrew’s Python 2.7.x (if installed)

python points to Homebrew’s Python 2.7.x (if installed) otherwise the macOS system Python. Check out brew info python if you wish to add Homebrew’s 3.x python to your PATH.

Following brew info python’s output, you should be able to get unversioned aliases pointing to Python 3 by adding the following path in your $PATH:

```<code>$(brew --prefix python@3.8)/libexec/bin
</code>```

That is, add the following line in your ~/.bash_profile or ~/.bashrc:

```<code>PATH="$(brew --prefix python@3.8)/libexec/bin:$PATH"
</code>```

Start a new shell, and python should be Python 3.8.

Body:
Python 3.8.1 has been installed, but it still says the version is 2.7.17. How can I actually use 3.8.1?

$ brew install python@3.8
Warning: python@3.8 3.8.1 is already installed and up-to-date
To reinstall 3.8.1, run `brew reinstall python@3.8`
$ python --version
Python 2.7.17

Body:
Homebrew installs Python 3 under python3; it never aliases python to Python 3 unless you explicitely ask it: https://docs.brew.sh/Homebrew-and-Python#python-3x-or-python-2x

The executables are organised as follows so that Python 2 and Python 3
  can both be installed without conflict:

python3 points to Homebrew’s Python 3.x (if installed)

python2 points to Homebrew’s Python 2.7.x (if installed)

python points to Homebrew’s Python 2.7.x (if installed) otherwise the macOS system Python. Check out brew info python if you wish to add Homebrew’s 3.x python to your PATH.

Following brew info python’s output, you should be able to get unversioned aliases pointing to Python 3 by adding the following path in your $PATH:

$(brew --prefix python@3.8)/libexec/bin

That is, add the following line in your ~/.bash_profile or ~/.bashrc:

PATH="$(brew --prefix python@3.8)/libexec/bin:$PATH"

Start a new shell, and python should be Python 3.8.


问:
How to make React Native's ScrollView initial zoom to not be 1?
I want to put content (multiple images vertically arranged) in a React Native ScrollView (iOS only for now, Android will come later) that is bigger than the phone's screen, and start zoomed out so that it is all visible at the same time.

Are there any good examples of using ScrollView.scrollResponderZoomTo in a componentDidMount call that zooms out to fit content in the screen, something like

```<code><ScrollView
  style={{width: 500, height: 1000}}
  // + whatever other properties make this work required way
>
  <View style={{width: 2000, height: 5000}}>
    <Image style={{width: 2000, height: 2000}} source={.....}/>
    <Image style={{width: 2000, height: 3000}} source={.....}/>
  </View>
</ScrollView>
</code>```

I tried setting the 'zoomScale' property, but that seems to be ignored and always uses the value 1.

According to this issue (https://github.com/facebook/react-native/issues/2176) there is a scrollResponderZoomTo function that can be used, but when I try to use it, it seems that no matter what values I give it it zooms out much too far and off center.

The F8 sample app has a ZoomableImage module (https://github.com/fbsamples/f8app/blob/b5df451259897d1838933f01ad4596784325c2ad/js/tabs/maps/ZoomableImage.js) which uses the Image.resizeMode.contain style to make an image fit the screen, but that loses the quality of image, so when you zoom in it gets blurry.

答:
@Levalis's answer save my day.

scrollResponderZoomTo is currently the best shot in React Native according to this issue #2176

If anyone encounter the "zooms out much too far and off center" problem, try to call scrollResponderZoomTo with the same rect as you set in your style:

// declare image size in styles.js...
image: {
  width: <image width>,
  height: <image height>
}

// ...and inside your component
this.scrollView._scrollResponder.scrollResponderZoomTo({
  height: <image height>, width: <image width>, animated: false,
})
```

Body:
I want to put content (multiple images vertically arranged) in a React Native ScrollView (iOS only for now, Android will come later) that is bigger than the phone's screen, and start zoomed out so that it is all visible at the same time.

Are there any good examples of using ScrollView.scrollResponderZoomTo in a componentDidMount call that zooms out to fit content in the screen, something like

<ScrollView
  style={{width: 500, height: 1000}}
  // + whatever other properties make this work required way
>
  <View style={{width: 2000, height: 5000}}>
    <Image style={{width: 2000, height: 2000}} source={.....}/>
    <Image style={{width: 2000, height: 3000}} source={.....}/>
  </View>
</ScrollView>

I tried setting the 'zoomScale' property, but that seems to be ignored and always uses the value 1.

According to this issue (https://github.com/facebook/react-native/issues/2176) there is a scrollResponderZoomTo function that can be used, but when I try to use it, it seems that no matter what values I give it it zooms out much too far and off center.

The F8 sample app has a ZoomableImage module (https://github.com/fbsamples/f8app/blob/b5df451259897d1838933f01ad4596784325c2ad/js/tabs/maps/ZoomableImage.js) which uses the Image.resizeMode.contain style to make an image fit the screen, but that loses the quality of image, so when you zoom in it gets blurry.


问:
setting brightness via Settings.System.putInt() isn't working
I'm trying to change the brightness mode and value on my phone, and found a great thread here at SO that I thought answered my question, but on my froyo Dell Streak this code simply does nothing.  putInt() is returning true so by all accounts it seems to be successful, yet brightness remains exactly the same, can't even get it to switch between manual and automatic......I have the WRITE_SETTINGS permission set, and logcat doesn't seem to have any other relevant output coming out....stumped right now, gonna take a break for a while o_0

Here's a snippet of how I'm calling it, this is inside my (only) Activity:

```<code>public void onCheckedChanged(RadioGroup group, int checked) {
    //BrightSettings bright = new BrightSettings();

    switch(checked)
    {
        case R.id.daybutton:
            //bright.setBrightMode(BrightSettings.DAY_MODE);
            if(Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC))
                Log.d("NightMode", "Brightness seems to be set to auto....");
        case R.id.nightbutton:
            //bright.setBrightMode(BrightSettings.NIGHT_MODE);
            if (Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL) && Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 2) )
                Log.d("NightMode", "Night mode seems to have been set....");
    }
}
</code>```

答:
It's work for me by kotlin。

```<code><uses-permission
    android:name="android.permission.WRITE_SETTINGS"
    tools:ignore="ProtectedPermissions" />
</code>```

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_test)
    if(isCanWriteSettings(this))
        setupLight(this,255)//0~255
    else
        requestCanWriteSettings(this)
}
/**
 *
 * @param context
 * @param light max 255
 */
fun setupLight(context: Context, light: Int) {
    try {
        val brightnessMode = Settings.System.getInt(
            context.contentResolver,
            Settings.System.SCREEN_BRIGHTNESS_MODE
        )
        if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
            Settings.System.putInt(
                context.contentResolver,
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
            )
        }
        Settings.System.putInt(
            context.contentResolver,
            Settings.System.SCREEN_BRIGHTNESS,
            light
        )
    } catch (e: Exception) {
        Log.e("setupLight","Exception $e")
    }
}

fun isCanWriteSettings(context: Context): Boolean {
    return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.System.canWrite(context)
}

fun requestCanWriteSettings(activity: Activity){
    if (isCanWriteSettings(context = activity))
        return //not need
    try {
        val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
        intent.data = Uri.parse("package:" + activity.packageName)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        activity.startActivityForResult(intent, 0)
    }catch (e: Exception){
        Log.e("requestCanWriteSettings","requestCanWriteSettings $e")
    }
}
</code>```

Body:
I'm trying to change the brightness mode and value on my phone, and found a great thread here at SO that I thought answered my question, but on my froyo Dell Streak this code simply does nothing.  putInt() is returning true so by all accounts it seems to be successful, yet brightness remains exactly the same, can't even get it to switch between manual and automatic......I have the WRITE_SETTINGS permission set, and logcat doesn't seem to have any other relevant output coming out....stumped right now, gonna take a break for a while o_0

Here's a snippet of how I'm calling it, this is inside my (only) Activity:

public void onCheckedChanged(RadioGroup group, int checked) {
    //BrightSettings bright = new BrightSettings();

    switch(checked)
    {
        case R.id.daybutton:
            //bright.setBrightMode(BrightSettings.DAY_MODE);
            if(Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC))
                Log.d("NightMode", "Brightness seems to be set to auto....");
        case R.id.nightbutton:
            //bright.setBrightMode(BrightSettings.NIGHT_MODE);
            if (Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL) && Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 2) )
                Log.d("NightMode", "Night mode seems to have been set....");
    }
}

Body:
It's work for me by kotlin。

<uses-permission
    android:name="android.permission.WRITE_SETTINGS"
    tools:ignore="ProtectedPermissions" />

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_test)
    if(isCanWriteSettings(this))
        setupLight(this,255)//0~255
    else
        requestCanWriteSettings(this)
}
/**
 *
 * @param context
 * @param light max 255
 */
fun setupLight(context: Context, light: Int) {
    try {
        val brightnessMode = Settings.System.getInt(
            context.contentResolver,
            Settings.System.SCREEN_BRIGHTNESS_MODE
        )
        if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
            Settings.System.putInt(
                context.contentResolver,
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
            )
        }
        Settings.System.putInt(
            context.contentResolver,
            Settings.System.SCREEN_BRIGHTNESS,
            light
        )
    } catch (e: Exception) {
        Log.e("setupLight","Exception $e")
    }
}

fun isCanWriteSettings(context: Context): Boolean {
    return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.System.canWrite(context)
}

fun requestCanWriteSettings(activity: Activity){
    if (isCanWriteSettings(context = activity))
        return //not need
    try {
        val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
        intent.data = Uri.parse("package:" + activity.packageName)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        activity.startActivityForResult(intent, 0)
    }catch (e: Exception){
        Log.e("requestCanWriteSettings","requestCanWriteSettings $e")
    }
}


问:
What is the best way to bulk check for Firestore documents, and if not created add a document?
I am adding an integration to an app and want to add an initial fetch of all data from the API, check in my app if any entries exist, and then create new entries or update existing entries with data from the API. I looked through the documentation on batch transactions/writes, but it seems to be mostly concerning making batched writes to a single document. Email addresses would be the item to search for in the existing database entries.

I would think this would be some version of a Firestore query .where('email', '==', API_EMAIL), but not sure how to efficiently handle potential several-hundred document updates after that.

答:
Firestore and all Google Cloud Platform will do all the possible performance problems related to queries that you might have, so you don't need to worry about this point.

Regarding reading multiple documents at once, you can use transactions to do that. This option provides you the feature to read more than one document at once. Considering that, I would like to recommend you to take a look again at the documentation Updating data with transactions and focus on the transactions, to confirm if that's what you are looking for.

Let me know if the information helped you!


问:
Djnago channels security
I'm studying django channels and there's this problem: let's say I have a routing channel:

websocket_urlpatterns = [
    re_path(r'^ws/chat/(?P<id>[^/]+)/$', ChatConsumer),
]
```

It turns out, anyone who knows the channel number, can listen to messages going to this address. Maybe you can send data (for example, a token) sometime during the socket connection?

答:
use a Auth middleware

example

```<code>from django.conf.urls import url
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from myapp import consumers

application = ProtocolTypeRouter({

"websocket": AuthMiddlewareStack(
    URLRouter([
        url(r"^front(end)/$", consumers.AsyncChatConsumer),
    ])
),

})
</code>```

Title: Djnago channels security

Body:
I'm studying django channels and there's this problem: let's say I have a routing channel:

websocket_urlpatterns = [
    re_path(r'^ws/chat/(?P<id>[^/]+)/$', ChatConsumer),
]

It turns out, anyone who knows the channel number, can listen to messages going to this address. Maybe you can send data (for example, a token) sometime during the socket connection?

Body:
use a Auth middleware

example

from django.conf.urls import url
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from myapp import consumers

application = ProtocolTypeRouter({

"websocket": AuthMiddlewareStack(
    URLRouter([
        url(r"^front(end)/$", consumers.AsyncChatConsumer),
    ])
),

})


问:
Finding common words in Pandas dataframe
I have set of words

```<code>{'adalah',
 'akan',
 'akhir',
 'algoritme',
 'alur',
 'antar',
 'antisense',
 'asam',
 'atas',
 'atau',
 'bahwa',
 'bakteriofag',
 'baru',
 'basa',
 'beranggota',
 'berdasarkan',
 'berikatan',
 'berupa',
 'pada',...}
</code>```

I tried to find whether the word in the set contained in the bigramPMITable dataframe that I had

```<code>    bigram         PMI
0  (itu, adalah)   11.487338
1  (DNA, pada)     6.386371
2  (pada, oleh)    6.386371
3  (pada, basa)    1.105795
4  (yang, satu)    1.105795
5  (gula, yang)    1.044394
6  (yang, tidak)   1.044394
7  (pada, DNA)     0.986496
8  (unting, dalam) 0.931790
9  (DNA, tidak)    0.925095
10 (DNA, menjadi)  0.925095
11 (dan, sebagai)  0.905196
12 (pada, unting)  0.834493
</code>```

If so, then the expected output will be like this:

```<code>(itu, adalah) 11.487338
(DNA, pada) 6.386371
(pada, oleh) 6.386371
(pada, basa) 1.105795
(pada, DNA) 0.986496
(pada, unting) 0.834493
</code>```

They found the word 'adalah' and 'pada' at the bigramPMITable dataframe. How do I find?. Can anyone can help? Thanks. Any help is much appreciated.

答:
Here's one approach using sets (somewhat slower than jezrael's set.isdisjoint approach):

```<code>df[df.bigram.map(s.intersection).ne(set())]

         bigram        PMI
0    (itu, adalah)  11.487338
1      (DNA, pada)   6.386371
2     (pada, oleh)   6.386371
3     (pada, basa)   1.105795
7      (pada, DNA)   0.986496
12  (pada, unting)   0.834493
</code>```

Where:

```<code>s = {'adalah',
 'akan',
 'akhir',
 'algoritme',
 'alur',
 'antar',
 'antisense',
 'asam',
 'atas',
 'atau',
 'bahwa',
 'bakteriofag',
 'baru',
 'basa',
 'beranggota',
 'berdasarkan',
 'berikatan',
 'berupa',
 'pada'}
</code>```

Body:
I have set of words

{'adalah',
 'akan',
 'akhir',
 'algoritme',
 'alur',
 'antar',
 'antisense',
 'asam',
 'atas',
 'atau',
 'bahwa',
 'bakteriofag',
 'baru',
 'basa',
 'beranggota',
 'berdasarkan',
 'berikatan',
 'berupa',
 'pada',...}

I tried to find whether the word in the set contained in the bigramPMITable dataframe that I had

    bigram         PMI
0  (itu, adalah)   11.487338
1  (DNA, pada)     6.386371
2  (pada, oleh)    6.386371
3  (pada, basa)    1.105795
4  (yang, satu)    1.105795
5  (gula, yang)    1.044394
6  (yang, tidak)   1.044394
7  (pada, DNA)     0.986496
8  (unting, dalam) 0.931790
9  (DNA, tidak)    0.925095
10 (DNA, menjadi)  0.925095
11 (dan, sebagai)  0.905196
12 (pada, unting)  0.834493

If so, then the expected output will be like this:

(itu, adalah) 11.487338
(DNA, pada) 6.386371
(pada, oleh) 6.386371
(pada, basa) 1.105795
(pada, DNA) 0.986496
(pada, unting) 0.834493

They found the word 'adalah' and 'pada' at the bigramPMITable dataframe. How do I find?. Can anyone can help? Thanks. Any help is much appreciated.

Body:
Here's one approach using sets (somewhat slower than jezrael's set.isdisjoint approach):

df[df.bigram.map(s.intersection).ne(set())]

         bigram        PMI
0    (itu, adalah)  11.487338
1      (DNA, pada)   6.386371
2     (pada, oleh)   6.386371
3     (pada, basa)   1.105795
7      (pada, DNA)   0.986496
12  (pada, unting)   0.834493

Where:

s = {'adalah',
 'akan',
 'akhir',
 'algoritme',
 'alur',
 'antar',
 'antisense',
 'asam',
 'atas',
 'atau',
 'bahwa',
 'bakteriofag',
 'baru',
 'basa',
 'beranggota',
 'berdasarkan',
 'berikatan',
 'berupa',
 'pada'}


问:
Visual recognition mouse-click automation utility?
Is anybody aware of any kind of a simple MacOSX utility that can take a given image and find whether the image is on the screen (perhaps with a certain variance threshold) and then position the mouse and/or click on the area which matches the image?  Please don't respond about how this is a terrible idea and shouldn't be done.  This is an important task for testing and cannot be easily accomplished by triggering events or the like.</p>

答:
Project SIKULI:

"Sikuli is a visual technology to automate and test graphical user interfaces (GUI) using images (screenshots). Sikuli includes Sikuli Script, a visual scripting API for Jython, and Sikuli IDE, an integrated development environment for writing visual scripts with screenshots easily. Sikuli Script automates anything you see on the screen without internal API's support. You can programmatically control a web page, a Windows/Linux/Mac OS X desktop application, or even an iphone or android application running in a simulator or via VNC."

www.sikuli.org

Free for Mac OS X


问:
Replace multiple characters in a string with different characters
I am converting a list to string and I am wondering if there is a more simplified way to replace multiple characters w/ different characters. I'm coding in C# and this is what my list looks like:

```<code>[0]: [Key1, Value1]
[1]: [Key2, Value2]
[2]: [Key3, Value3]
...
</code>```

So basically, I wanted to replace ", " w/ "=" and both "[]" with "" to achieve this format:

```<code>Key1=Value1
Key2=Value2
Key3=Value3
...
</code>```

I already did get this format using the following code below and I am kinda worried I am overusing the Replace command.

```<code>string out = string.Join("\n", listOfLines).Replace(", ", "=").Replace("[", "").Replace("]","");
</code>```

I have found a similar question but it does specify that the characters are all replaced by "\n" only.

Any help would be greatly appreciated. Thanks!

答:
You can use extension method similar to that:

```<code>    public static IEnumerable<char> ReplaceMultiple(this IEnumerable<char> input, Dictionary<char, char> replaces)
    {
        foreach(var character in input)
            yield return replaces.ContainsKey(character) ? replaces[character] : character;
    }
</code>```

But personally I think, that if there are less than 6-7 character to replace, using multiple Replaces are much more readable.

Body:
I am converting a list to string and I am wondering if there is a more simplified way to replace multiple characters w/ different characters. I'm coding in C# and this is what my list looks like:

[0]: [Key1, Value1]
[1]: [Key2, Value2]
[2]: [Key3, Value3]
...

So basically, I wanted to replace ", " w/ "=" and both "[]" with "" to achieve this format:

Key1=Value1
Key2=Value2
Key3=Value3
...

I already did get this format using the following code below and I am kinda worried I am overusing the Replace command.

string out = string.Join("\n", listOfLines).Replace(", ", "=").Replace("[", "").Replace("]","");

I have found a similar question but it does specify that the characters are all replaced by "\n" only.

Any help would be greatly appreciated. Thanks!

Body:
You can use extension method similar to that:

    public static IEnumerable<char> ReplaceMultiple(this IEnumerable<char> input, Dictionary<char, char> replaces)
    {
        foreach(var character in input)
            yield return replaces.ContainsKey(character) ? replaces[character] : character;
    }

But personally I think, that if there are less than 6-7 character to replace, using multiple Replaces are much more readable.


问:
Fail to install boost-1.70.0 via yum for AWS jupyter terminal
I'm working with AWS jupyter notebook, and I need to have boost installed. When installing with yum, the version of boost installed is 1.54.0. However, I need to have version 1.70.0. When I try to specify a version with yum, I have an error.

```<code>Loaded plugins: dkms-build-requires, priorities, update-motd, upgrade-helper, versionlock
amzn-main
amzn-updates
No package boost-1.70.0 available.
Error: Nothing to do
</code>```

Please advise, how to install boost 1.70.0 in this case?

答:
Steps to follow:

1) wget -c https://dl.bintray.com/boostorg/release/1.70.0/source/boost_1_70_0.tar.gz -O - | sudo tar -xz -C /home/ec2-user/SageMaker/ will download boost library to /home/ec2-user/SageMaker/ folder on the AWS

2) add the correct path references to build.sh or any other in order to be able to locate boost library

Body:
I'm working with AWS jupyter notebook, and I need to have boost installed. When installing with yum, the version of boost installed is 1.54.0. However, I need to have version 1.70.0. When I try to specify a version with yum, I have an error.

Loaded plugins: dkms-build-requires, priorities, update-motd, upgrade-helper, versionlock
amzn-main
amzn-updates
No package boost-1.70.0 available.
Error: Nothing to do

Please advise, how to install boost 1.70.0 in this case?


问:
How to push JSON Objects using filter from two Arrays into a new Array?
I want to get the array items which contains appName: "CapLogix" into a new array.The thing which you have to keep in mind is the Array Objects are JSON Objects.

var z = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "970",
  "envName": "UAT4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "971",
  "envName": "UAT4"
}];

var y = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "959",
  "envName": "SIT-4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "963",
  "envName": "SIT-4"
}];```
</div>
</div>
</p>

<p>This is what I tried so far:</p>

```z.push(y);

for (var i = 0; i <= z.length; i++) {
    document.getElementById("sa").innerHTML += "appId  :" + z[i].appId + "
" + " appName  : " + z[i].appName + "
" + "envId  :" + z[i].envId + "
" + " envName  : " + z[i].envName;
}
```

答:
You can make use of spread operator (ES6), this will spread all
  the items of array into new array Example below

const z = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "970",
  "envName": "UAT4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "971",
  "envName": "UAT4"
}];

const y = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "959",
  "envName": "SIT-4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "963",
  "envName": "SIT-4"
}];

const finalArray = [...z, ...y];
console.log(finalArray);```
</div>
</div>
</p>

<p><strong>If you want to push all values in to first array (z), you can do something like this</strong></p>

```z.push(...y);
console.log(z);
```

<p>So you will end up with <code>z</code> containing all items of both the arrays</p>

<p><strong>EDIT</strong>  </p>

<blockquote>
  <p>you can use <code>filter</code> to filter items and get new array, To get the
  array items which contains <strong>appName: "CapLogix"</strong> (Example below)</p>
</blockquote>

<p>After merging array you can apply filter on it.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const z = [{
      "appId": "1",
      "appName": "CapLogix",
      "envId": "970",
      "envName": "UAT4"
    }, {
      "appId": "73",
      "appName": "ConfigBuilder",
      "envId": "971",
      "envName": "UAT4"
    }];

    const y = [{
      "appId": "1",
      "appName": "CapLogix",
      "envId": "959",
      "envName": "SIT-4"
    }, {
      "appId": "73",
      "appName": "ConfigBuilder",
      "envId": "963",
      "envName": "SIT-4"
    }];

z.push(...y);

const filteredArray = z.filter(each => each.appName == 'CapLogix');
console.log(filteredArray);</code>```

Body:
I want to get the array items which contains appName: "CapLogix" into a new array.The thing which you have to keep in mind is the Array Objects are JSON Objects.

var z = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "970",
  "envName": "UAT4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "971",
  "envName": "UAT4"
}];

var y = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "959",
  "envName": "SIT-4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "963",
  "envName": "SIT-4"
}];

This is what I tried so far:

z.push(y);

for (var i = 0; i <= z.length; i++) {
    document.getElementById("sa").innerHTML += "appId  :" + z[i].appId + "
" + " appName  : " + z[i].appName + "
" + "envId  :" + z[i].envId + "
" + " envName  : " + z[i].envName;
}

Body:
You can make use of spread operator (ES6), this will spread all
  the items of array into new array Example below

const z = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "970",
  "envName": "UAT4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "971",
  "envName": "UAT4"
}];

const y = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "959",
  "envName": "SIT-4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "963",
  "envName": "SIT-4"
}];

const finalArray = [...z, ...y];
console.log(finalArray);

If you want to push all values in to first array (z), you can do something like this

z.push(...y);
console.log(z);

So you will end up with z containing all items of both the arrays

EDIT

you can use filter to filter items and get new array, To get the
  array items which contains appName: "CapLogix" (Example below)

After merging array you can apply filter on it.

const z = [{
      "appId": "1",
      "appName": "CapLogix",
      "envId": "970",
      "envName": "UAT4"
    }, {
      "appId": "73",
      "appName": "ConfigBuilder",
      "envId": "971",
      "envName": "UAT4"
    }];

    const y = [{
      "appId": "1",
      "appName": "CapLogix",
      "envId": "959",
      "envName": "SIT-4"
    }, {
      "appId": "73",
      "appName": "ConfigBuilder",
      "envId": "963",
      "envName": "SIT-4"
    }];

z.push(...y);

const filteredArray = z.filter(each => each.appName == 'CapLogix');
console.log(filteredArray);


问:
filter array based on IDs available in another array
I have two arrays. The first array has only id objects:

```<code>arr1 = [
  { id: 1 },
  { id: 2 }
];
</code>```

and another array has list:

```<code>arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" },
  { id: 3, name: "krishnadas" }
];
</code>```

I need to write arr2 filter function which result as, based on ID available in first array

```<code>arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" }
];
</code>```

答:
You can create a string using the id value from the first array. So the string will be 1 2, then use filter to create an array of elements from second array and for elements where the id value is included in the string

let arr1 = [{
  id: 1
}, {
  id: 2
}];
let arr2 = [{
  id: 1,
  name: 'kedar'
}, {
  id: 2,
  name: 'murli'
}, {
  id: 3,
  name: 'krishnadas'
}];

let str = arr1.reduce((acc, curr) => {
  acc += ' ' + curr.id

  return acc.trim();
}, '');

let newArr = arr2.filter((item) => {
  // check if id value is included in the string
  return str.indexOf(item.id) != -1;
});

console.log(newArr)```

Body:
I have two arrays. The first array has only id objects:

arr1 = [
  { id: 1 },
  { id: 2 }
];

and another array has list:

arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" },
  { id: 3, name: "krishnadas" }
];

I need to write arr2 filter function which result as, based on ID available in first array

arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" }
];


问:
How to get entity keys(parent and custom name) in datastore using python3
I have an entity like this below..

```<code> Name/ID                   Parent                    Rollen               email          first_name      last_name
name=CidassUID  Key(Tenant, 'CidassGroupID')    ["user","admin"]    user@email.com  user first name user last name
</code>```

Now for example i would like to query data whose email = user@email.com and get the Entity Key(both id and parent)..
what i am doing write now in python is

```<code>from google.cloud import datastore
def create_client(project_id):
    return datastore.Client(project_id)
def list_user(client):
    query = client.query(kind='User')
    query.add_filter('email','=','user@email.com')
    l=query.fetch()
    l=list(l)
    print(l)
</code>```

Now it is giving me the response back as

```<code>[<Entity('Tenant', 'CidassGroupID', 'User', 'CidassUID') {'first_name': 'user first name', 'last_name': 'user last name', 'email': 'user@email.com', 'Rollen': ['user', 'admin']}>]
</code>```

and if i convert it to a dictionary

```<code>for entity in l:
    a=entity
d=dict(a)
print(d)
</code>```

it shows the ouptut like this and remove the Entity..

```<code>{'first_name': 'user first name', 'last_name': 'user last name', 'email': 'user@email.com', 'Rollen': ['user', 'admin']}
</code>```

How can i get the Entity keys e.g. ('Tenant', 'CidassGroupID') ('User', 'CidassUID') from this response?

thanks a lot!

答:
This seems to work... I haven't tested it with the actual google api, but it should function the same...

```<code>d = dict(l[0])
keys = l[0].key.flat_path

new = {keys[i]:keys[i+1] for i in range(0, len(keys), 2)}
d.update(new)

print(d)
</code>```

Output:

```<code>{'first_name': 'user first name', 'last_name': 'user last name', 'email': 'user@email.com', 'Rollen': ['user', 'admin'], 'Tenant': 'CidassGroupID', 'User': 'CidassUID'}
</code>```

Body:
I have an entity like this below..

 Name/ID                   Parent                    Rollen               email          first_name      last_name
name=CidassUID  Key(Tenant, 'CidassGroupID')    ["user","admin"]    user@email.com  user first name user last name

Now for example i would like to query data whose email = user@email.com and get the Entity Key(both id and parent)..
what i am doing write now in python is

from google.cloud import datastore
def create_client(project_id):
    return datastore.Client(project_id)
def list_user(client):
    query = client.query(kind='User')
    query.add_filter('email','=','user@email.com')
    l=query.fetch()
    l=list(l)
    print(l)

Now it is giving me the response back as

[<Entity('Tenant', 'CidassGroupID', 'User', 'CidassUID') {'first_name': 'user first name', 'last_name': 'user last name', 'email': 'user@email.com', 'Rollen': ['user', 'admin']}>]

and if i convert it to a dictionary

for entity in l:
    a=entity
d=dict(a)
print(d)

it shows the ouptut like this and remove the Entity..

{'first_name': 'user first name', 'last_name': 'user last name', 'email': 'user@email.com', 'Rollen': ['user', 'admin']}

How can i get the Entity keys e.g. ('Tenant', 'CidassGroupID') ('User', 'CidassUID') from this response?

thanks a lot!

Body:
This seems to work... I haven't tested it with the actual google api, but it should function the same...

d = dict(l[0])
keys = l[0].key.flat_path

new = {keys[i]:keys[i+1] for i in range(0, len(keys), 2)}
d.update(new)

print(d)

Output:

{'first_name': 'user first name', 'last_name': 'user last name', 'email': 'user@email.com', 'Rollen': ['user', 'admin'], 'Tenant': 'CidassGroupID', 'User': 'CidassUID'}


问:
How do I use CURRENT_TIMESTAMP in a LINQ update statement using Entity Framework Core?
I have the following T-SQL that I want to write in c# code using LINQ and entity framework core...

```<code>UPDATE [MyTable1]
SET [LastContacted] = CURRENT_TIMESTAMP
FROM [MyTable1] t1
JOIN [MyTable2] t2 ON t2.[ID] = t1.[Table1ID]
WHERE t2.[MyColumn1] = 'MySearchName'
</code>```

The bit I'm having a problem with is setting the CURRENT_TIMESTAMP. It MUST use the time from the database and not the time from the service running the code so I can't use DateTime.Now as that would be the time from the service not the database time as there is no gaurantee the clocks are in sync.

At the moment I'm using ExecuteSqlInterpolated to execute this command as hard coded SQL but really I want to use EF to update via the entity models and SaveChanges() etc, but I don't know if there is anyway to get EF/LINQ to set the value to something that can only be got when the query runs on the database.

Does anyone know if this is possible and how to do it?

答: This would be one of the times where I would consider a database trigger and not do anything in C#</p>

Body:
I have the following T-SQL that I want to write in c# code using LINQ and entity framework core...

UPDATE [MyTable1]
SET [LastContacted] = CURRENT_TIMESTAMP
FROM [MyTable1] t1
JOIN [MyTable2] t2 ON t2.[ID] = t1.[Table1ID]
WHERE t2.[MyColumn1] = 'MySearchName'

The bit I'm having a problem with is setting the CURRENT_TIMESTAMP. It MUST use the time from the database and not the time from the service running the code so I can't use DateTime.Now as that would be the time from the service not the database time as there is no gaurantee the clocks are in sync.

At the moment I'm using ExecuteSqlInterpolated to execute this command as hard coded SQL but really I want to use EF to update via the entity models and SaveChanges() etc, but I don't know if there is anyway to get EF/LINQ to set the value to something that can only be got when the query runs on the database.

Does anyone know if this is possible and how to do it?


问:
Cross model update in ASP.NET Core
I'm really new to ASP.NET Core so I apologize if this is a silly question, but I've spent so many hours trying to figure this out.

I have 2 models, Teacher and Student. The relationship is one teacher to many students. This is a backend API project and Im working on a PUT method which can update fields in both models simultaneously in one request.

Here's my Teacher class:

```<code>public partial class Teacher
{
        public Teacher()
        {
            Students = new HashSet<Student>();
        }

        public int TeacherId { get; set; }
        public string Name { get; set; }
        ... tons of other properties ...
}
</code>```

Here's my Student class:

```<code>public partial class Student
{
        public int Id { get; set; }
        public int TeacherId { get; set; }
        public string Name { get; set; }
        public virtual Teacher Teacher { get; set; }
}
</code>```

Here's the controller:

```<code>[HttpPut("{id}")]
public async Task<IActionResult> PutTeachers(int id, TeacherViewModel model)
{
    var result = await _service.UpdateAsync(model);
    return Ok(result.Message);
}
</code>```

(The code above is simplified)
- It takes in a TeacherViewModel which restricts the number of fields to be returned
- I used another class as a service to do the update

Here's the service class:

```<code>public class TeacherService
{
        private readonly Repository<Teacher> _repository;

        public TeacherService(DatabaseContextWrapper context)
        {
            _repository = new Repository<Teacher>(context);
        }

        public async Task<ITransactionResult> UpdateAsync(TeacherViewModel model)
        {
            var teacher = _repository.FindAsync(model.TeacherId).Result;

            teacher.TeacherId = model.TeacherId;
            teacher.Name = model.Name;

            teacher.Students.Clear();

            foreach(var student in model.Students)
            {
                teacher.Students
                    .Add(new Student
                    {
                        Id = Student.Id,
                        TeacherId = Student.TeacherId
                        Name = Student.Name
                    });```
            }
        }
}
```

<p>My reasoning is to add the <code>Student</code> model to the to students under the <code>Teacher</code> model but it doesn't iterate through. If I comment out the clear code, the update will work but it won't cross update. It just simply wont iterate through. I guess I'm pretty lost at this point. Any help would be appreciated!</p>

<p>Edit 1 (Entity relationship configuration)</p>

``` modelBuilder.Entity<Student>(entity =>           {
                entity.HasOne(d => d.Teacher)
                    .WithMany(p => p.Students)
                    .HasForeignKey(d => d.TeacherId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_Students_Teachers");
            });
```

This is my configuration

答:
Try adding the reverse config to your parents entity:</p>

```<code> modelBuilder.Entity<Teacher>(entity =>
            {
                entity.HasMany(d => d.Students)
                    .WithOne(p => p.Teacher)
                    .HasForeignKey(d => d.TeacherId);
            });
</code>```

Title: Cross model update in ASP.NET Core

Body:
I'm really new to ASP.NET Core so I apologize if this is a silly question, but I've spent so many hours trying to figure this out.

I have 2 models, Teacher and Student. The relationship is one teacher to many students. This is a backend API project and Im working on a PUT method which can update fields in both models simultaneously in one request.

Here's my Teacher class:

public partial class Teacher
{
        public Teacher()
        {
            Students = new HashSet<Student>();
        }

        public int TeacherId { get; set; }
        public string Name { get; set; }
        ... tons of other properties ...
}

Here's my Student class:

public partial class Student
{
        public int Id { get; set; }
        public int TeacherId { get; set; }
        public string Name { get; set; }
        public virtual Teacher Teacher { get; set; }
}

Here's the controller:

[HttpPut("{id}")]
public async Task<IActionResult> PutTeachers(int id, TeacherViewModel model)
{
    var result = await _service.UpdateAsync(model);
    return Ok(result.Message);
}

(The code above is simplified)
- It takes in a TeacherViewModel which restricts the number of fields to be returned
- I used another class as a service to do the update

Here's the service class:

public class TeacherService
{
        private readonly Repository<Teacher> _repository;

        public TeacherService(DatabaseContextWrapper context)
        {
            _repository = new Repository<Teacher>(context);
        }

        public async Task<ITransactionResult> UpdateAsync(TeacherViewModel model)
        {
            var teacher = _repository.FindAsync(model.TeacherId).Result;

            teacher.TeacherId = model.TeacherId;
            teacher.Name = model.Name;

            teacher.Students.Clear();

            foreach(var student in model.Students)
            {
                teacher.Students
                    .Add(new Student
                    {
                        Id = Student.Id,
                        TeacherId = Student.TeacherId
                        Name = Student.Name
                    });```
            }
        }
}

My reasoning is to add the Student model to the to students under the Teacher model but it doesn't iterate through. If I comment out the clear code, the update will work but it won't cross update. It just simply wont iterate through. I guess I'm pretty lost at this point. Any help would be appreciated!

Edit 1 (Entity relationship configuration)

 modelBuilder.Entity<Student>(entity =>           {
                entity.HasOne(d => d.Teacher)
                    .WithMany(p => p.Students)
                    .HasForeignKey(d => d.TeacherId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_Students_Teachers");
            });

This is my configuration

Body:
Try adding the reverse config to your parents entity:

 modelBuilder.Entity<Teacher>(entity =>
            {
                entity.HasMany(d => d.Students)
                    .WithOne(p => p.Teacher)
                    .HasForeignKey(d => d.TeacherId);
            });


问:
Cannot install cvxpy with python 3.8
I have tried installing cvxpy (https://www.cvxpy.org/install/) for python. I use Python 3.8 for all my projects and am not to fond of making virtual environments where i use 3.7. Does anyone have a fix for using cvxpy on python 3.8 (I am using windows)?

Thanks!

```<code>ERROR: Command errored out with exit status 1:
ommand: 'AppData\Local\Programs\Python\Python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'AppData\\Local\\Temp\\pip-install-kehvj2di\\osqp\\setup.py'"'"'; __file__='"'"'AppData\\Local\\Temp\\pip-install-kehvj2di\\osqp\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'AppData\Local\Temp\pip-record-1u4al7gt\install-record.txt' --single-version-externally-managed --compile
cwd: AppData\Local\Temp\pip-install-kehvj2di\osqp\

-- Selecting Windows SDK version  to target Windows 10.0.18362.
    CMake Error at CMakeLists.txt:5 (project):
      Failed to run MSBuild command:

        MSBuild.exe

      to get the value of VCTargetsPath:

        The system cannot find the file specified

    -- Configuring incomplete, errors occurred!
    See also "AppData/Local/Temp/pip-install-kehvj2di/osqp/osqp_sources/build/CMakeFiles/CMakeOutput.log".
    The system cannot find the file specified
    CMake Error: Generator: execution of make failed. Make command was: MSBuild.exe osqpstatic.vcxproj /p:Configuration=Release /p:Platform=x64 /p:VisualStudioVersion=14.0 /v:m &&
    error: [Errno 2] No such file or directory: 'osqp_sources\\build\\out\\Release\\osqp.lib'
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'AppData\Local\Programs\Python\Python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'Local\\Temp\\pip-install-kehvj2di\\osqp\\setup.py'"'"'; __file__='"'"'AppData\\Local\\Temp\\pip-install-kehvj2di\\osqp\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'AppData\Local\Temp\pip-record-1u4al7gt\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output.
WARNING: You are using pip version 19.2.3, however version 20.0.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
</code>```

答:
Your problem does not seem to be the Python version, but lack of build tools. Install Microsoft Visual Build Tools and make sure they are on the PATH (so that conda can execute MSBuild.exe).

Build Tools installation instructions from cvxpy (in pptx).

Title: Cannot install cvxpy with python 3.8

Body:
I have tried installing cvxpy (https://www.cvxpy.org/install/) for python. I use Python 3.8 for all my projects and am not to fond of making virtual environments where i use 3.7. Does anyone have a fix for using cvxpy on python 3.8 (I am using windows)?

Thanks!

ERROR: Command errored out with exit status 1:
ommand: 'AppData\Local\Programs\Python\Python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'AppData\\Local\\Temp\\pip-install-kehvj2di\\osqp\\setup.py'"'"'; __file__='"'"'AppData\\Local\\Temp\\pip-install-kehvj2di\\osqp\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'AppData\Local\Temp\pip-record-1u4al7gt\install-record.txt' --single-version-externally-managed --compile
cwd: AppData\Local\Temp\pip-install-kehvj2di\osqp\

-- Selecting Windows SDK version  to target Windows 10.0.18362.
    CMake Error at CMakeLists.txt:5 (project):
      Failed to run MSBuild command:

        MSBuild.exe

      to get the value of VCTargetsPath:

        The system cannot find the file specified

    -- Configuring incomplete, errors occurred!
    See also "AppData/Local/Temp/pip-install-kehvj2di/osqp/osqp_sources/build/CMakeFiles/CMakeOutput.log".
    The system cannot find the file specified
    CMake Error: Generator: execution of make failed. Make command was: MSBuild.exe osqpstatic.vcxproj /p:Configuration=Release /p:Platform=x64 /p:VisualStudioVersion=14.0 /v:m &&
    error: [Errno 2] No such file or directory: 'osqp_sources\\build\\out\\Release\\osqp.lib'
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'AppData\Local\Programs\Python\Python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'Local\\Temp\\pip-install-kehvj2di\\osqp\\setup.py'"'"'; __file__='"'"'AppData\\Local\\Temp\\pip-install-kehvj2di\\osqp\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'AppData\Local\Temp\pip-record-1u4al7gt\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output.
WARNING: You are using pip version 19.2.3, however version 20.0.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.


问:
What to do when a private key of an organization in Hyperledger fabric gets compromised?
Hello I have a Hyperledger Network blockchain network running with 5 organization. If one of the private key of the organization gets compromised what are the steps or methods available to revoke the private key. Are there any mechanisms in Fabric where we can generate  new set of key pair for the same organization .</p>

答: you can generate new set of key pair from your CA for your organization and then you should update the config block. you can take a look at this article to understand the idea.</p>


问:
No Viable Alternative to Input '\\n" Python Error
I am working on a large scale project that involves giving a python script a first name and getting back a result as to what kind of gender it belongs to. My current program is written in Java and using Jython to interact with a Python script called "sex machine." It works great in most cases and I've tested it with smaller groups of users. However, when I attempt to test it with a large group of users the program gets about halfway in and then gives me the following error:

```<code>"Exception in thread "main" SyntaxError: No viable alternative to input '\\n'", ('<string>', 1, 22, "result = d.get_gender('Christinewazonek'')\n")
</code>```

I am more accustomed to Java and have limited knowledge of Python so at the moment I don't know how to solve this problem. I tried to trim the string that I'm giving the get_gender method but that didn't help any. I am not sure what the numbers 1, 22 even mean.

Like I said since I'm using Jython my code would be the following:

```<code>static PythonInterpreter interp = new PythonInterpreter();

interp.exec("import sys, os.path");
interp.exec("sys.path.append('/Users/myname/Desktop/')");
interp.exec("import sexmachine.detector as gender");

interp.exec("d = gender.Detector()");

interp.exec("result = d.get_gender('"+WordUtils.capitalize(name).trim()
            +"')");

PyObject gendAnswer = interp.get("result");
</code>```

And this is pretty much the extent of Jython/Python interaction in my Java code. If someone sees something that's wrong or not right I would certainly appreciate if you could help me. As this is a large project it takes time to run the whole program again only to run into the same issue, so because of this I really need to fix this problem.

答:
Not sure if you sorted this out, but have an extra apostrophe on

```<code>d.get_gender('Christinewazonek'')
</code>```

Just like in Java, everything you open you need to close, and in this case you opened a string containing  )\n") which was not closed.

Depending on the interpreter you are using, this can be flagged easily. Perhaps you might try different interpreter.

Body:
I am working on a large scale project that involves giving a python script a first name and getting back a result as to what kind of gender it belongs to. My current program is written in Java and using Jython to interact with a Python script called "sex machine." It works great in most cases and I've tested it with smaller groups of users. However, when I attempt to test it with a large group of users the program gets about halfway in and then gives me the following error:

"Exception in thread "main" SyntaxError: No viable alternative to input '\\n'", ('<string>', 1, 22, "result = d.get_gender('Christinewazonek'')\n")

I am more accustomed to Java and have limited knowledge of Python so at the moment I don't know how to solve this problem. I tried to trim the string that I'm giving the get_gender method but that didn't help any. I am not sure what the numbers 1, 22 even mean.

Like I said since I'm using Jython my code would be the following:

static PythonInterpreter interp = new PythonInterpreter();

interp.exec("import sys, os.path");
interp.exec("sys.path.append('/Users/myname/Desktop/')");
interp.exec("import sexmachine.detector as gender");

interp.exec("d = gender.Detector()");

interp.exec("result = d.get_gender('"+WordUtils.capitalize(name).trim()
            +"')");

PyObject gendAnswer = interp.get("result");

And this is pretty much the extent of Jython/Python interaction in my Java code. If someone sees something that's wrong or not right I would certainly appreciate if you could help me. As this is a large project it takes time to run the whole program again only to run into the same issue, so because of this I really need to fix this problem.

Body:
Not sure if you sorted this out, but have an extra apostrophe on

d.get_gender('Christinewazonek'')

Just like in Java, everything you open you need to close, and in this case you opened a string containing  )\n") which was not closed.

Depending on the interpreter you are using, this can be flagged easily. Perhaps you might try different interpreter.


问:
Typoscript 9.5 render FILES Object like Contentelement
i get via CONTENT an Element from the page and want to render the image from this like all other images in the page.
i have installed sms for responsive images but when i render this image via typoscript an normal  will be outputtet.
how must i change my typoscript to render like in the partial file Media/Rendering/Image?

```<code>                            20 = FILES
                            20{
                                references {
                                    table = tt_content
                                    fieldName = image
                                    uid.data = field:uid
                                }
                                begin = 0
                                maxItems = 1
                                renderObj = IMAGE
                                renderObj {
                                    file.import.data = file:current:publicUrl
                                    file.width = 1920c
                                    file.treatIdAsReference = 1
                                    stdWrap.outerWrap = |
                                }
                            }
</code>```

thank you very much!

答:
As the example you mention is rendered in Fluid, I'd suggest to use Fluid as well. The ViewHelper for responsive images is used in Fluid.
Try to get away from rendering via TypoScript and use Fluid templates.</p>

Body:
i get via CONTENT an Element from the page and want to render the image from this like all other images in the page.
i have installed sms for responsive images but when i render this image via typoscript an normal  will be outputtet.
how must i change my typoscript to render like in the partial file Media/Rendering/Image?

                            20 = FILES
                            20{
                                references {
                                    table = tt_content
                                    fieldName = image
                                    uid.data = field:uid
                                }
                                begin = 0
                                maxItems = 1
                                renderObj = IMAGE
                                renderObj {
                                    file.import.data = file:current:publicUrl
                                    file.width = 1920c
                                    file.treatIdAsReference = 1
                                    stdWrap.outerWrap = |
                                }
                            }

thank you very much!


问:
How to convert custom object with map field that includes list of custom object to json?
Let's say, I have an Employee class which looks like this:

```<code>public class Employee{

Map<String, ArrayList<Salary>> salary = new HashMap<String, ArrayList<Salary>>();
String name;
String age;
}

public class Salary{
String amount;
String currency;
}
</code>```

What is the smartest way of convertion to/from Json in Java?

Or;

What if my json should look like that:

```<code>  {
  "name": "Test",
  "age": "12",
  "salary": {
    "first": {
      "41130": {
        "amount": "100",
        "currency": "€"
      },
      "41132": {
        "amount": "100",
        "currency": "€"
      }
    },
    "second": {
      "41129": {
        "amount": "100",
        "currency": "€"
      }
    }
  }
}
</code>```

When i tried to convert this to Employee I am getting error below.

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
  Expected BEGIN_ARRAY but was BEGIN_OBJECT

答:
```<code>public class Main {

    public static void main(String[] args) {

        Gson gson = new Gson();

        Map<String, ArrayList<Salary>> sal = new HashMap<String, ArrayList<Salary>>();
        ArrayList<Salary> salaries = new ArrayList<Salary>();
        Salary salary1 = new Salary("100", "€");
        Salary salary2 = new Salary("200", "€");
        salaries.add(salary1);
        salaries.add(salary2);
        sal.put("1", salaries);
        Employee employee = new Employee(sal, "Test", "12");

        System.out.println("Age -> " + employee.getAge());
        System.out.println("Name -> " + employee.getName());
        System.out.println("Salary -> " + employee.getSalary());

        String json = gson.toJson(employee);
        System.out.println("Json -> " + json);

        Employee employee1 = gson.fromJson(json, Employee.class);

        System.out.println("Age1 -> " + employee1.getAge());
        System.out.println("Name1 -> " + employee1.getName());
        System.out.println("Salary1 -> " + employee1.getSalary());
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Employee{

        Map<String, ArrayList<Salary>> salary = new HashMap<String, ArrayList<Salary>>();
        String name;
        String age;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Salary{
        String amount;
        String currency;

    }
}
</code>```

Body:
Let's say, I have an Employee class which looks like this:

public class Employee{

Map<String, ArrayList<Salary>> salary = new HashMap<String, ArrayList<Salary>>();
String name;
String age;
}

public class Salary{
String amount;
String currency;
}

What is the smartest way of convertion to/from Json in Java?

Or;

What if my json should look like that:

  {
  "name": "Test",
  "age": "12",
  "salary": {
    "first": {
      "41130": {
        "amount": "100",
        "currency": "€"
      },
      "41132": {
        "amount": "100",
        "currency": "€"
      }
    },
    "second": {
      "41129": {
        "amount": "100",
        "currency": "€"
      }
    }
  }
}

When i tried to convert this to Employee I am getting error below.

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
  Expected BEGIN_ARRAY but was BEGIN_OBJECT


问:
Is it possible for the database to block parallel table accesses in Scala threads?
In my Scala application, I make several threads. In each thread, I write different data from the array to the same PostgreSQL table. I noticed that some threads did not write data to the PostgreSQL table. However, there are no errors in the application logs. Is it possible for the database to block parallel table accesses? What can be the cause of this behavior?

MainApp.scala:

```<code>val postgreSQL = new PostgreSQL(configurations)

val semaphore = new Semaphore(5)

for (item <- array) {
    semaphore.acquire()

    val thread = new Thread(new CustomThread(postgreSQL, semaphore, item))

    thread.start()
}
</code>```

CustomThread.scala:

```<code>import java.util.concurrent.Semaphore
import java.util.UUID.randomUUID
import utils.PostgreSQL

class CustomThread(postgreSQL: PostgreSQL, semaphore: Semaphore, item: Item) extends Runnable {
    override def run(): Unit = {
        try {
            // Create the unique filename.
            val filename: String = randomUUID().toString

            // Write to the database the filename of the item.
            postgreSQL.changeItemFilename(filename, item.id)

            // Change the status type of the item.
            postgreSQL.changeItemStatusType(3, request.id)
        } catch {
            case e: Throwable =>
                e.printStackTrace()
        } finally {
            semaphore.release()
        }
    }
}
</code>```

PostgreSQL.scala:

```<code>package utils

import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}
import java.util.Properties

class PostgreSQL(configurations: Map[String, String]) {
  val host: String = postgreSQLConfigurations("postgresql.host")
  val port: String = postgreSQLConfigurations("postgresql.port")
  val user: String = postgreSQLConfigurations("postgresql.user")
  val password: String = postgreSQLConfigurations("postgresql.password")
  val db: String = postgreSQLConfigurations("postgresql.db")
  val url: String = "jdbc:postgresql://" + host + ":" + port + "/" + db
  val driver: String = "org.postgresql.Driver"

  val properties = new Properties()

  val connection: Connection = getConnection

  var statement: PreparedStatement = _

  def getConnection: Connection = {
    properties.setProperty("user", user)
    properties.setProperty("password", password)

    var connection: Connection = null

    try {
      Class.forName(driver)
      connection = DriverManager.getConnection(url, properties)
    } catch {
      case e:Exception =>
        e.printStackTrace()
    }

    connection
  }

  def changeItemFilename(filename: String, id: Int): Unit = {
    try {
      statement = connection.prepareStatement("UPDATE REPORTS SET FILE_NAME = ? WHERE ID = ?;", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
      statement.setString(1, filename)
      statement.setInt(2, id)
      statement.execute()
    } catch {
      case e: Exception =>
        e.printStackTrace()
    }
  }
}
</code>```

答:
Just for your interest, by default, JDBC is synchronous. It means that it blocks your thread until the operation is done on a specific connection. This means if you try to do multiple things on a single connection at the same time, actions will be done sequentially instead.

More on that:
https://dzone.com/articles/myth-asynchronous-jdbc

That's the first and the most probable reason. The second possible reason, database blocks modifying actions on table cells which are being updated by another transaction, how exactly - depends on isolation level.

https://www.sqlservercentral.com/articles/isolation-levels-in-sql-server

That's the second probable reason.

The last, but not least, it is not necessary to use bare threads in Scala. For concurrent/asynchronous programming many of libraries like cats-effects, monix, zio, was developed, and there are special libraries for database access using these libraries like slick or doobie.
It's better to use them than bare threads due to numerous reasons.

Body:
In my Scala application, I make several threads. In each thread, I write different data from the array to the same PostgreSQL table. I noticed that some threads did not write data to the PostgreSQL table. However, there are no errors in the application logs. Is it possible for the database to block parallel table accesses? What can be the cause of this behavior?

MainApp.scala:

val postgreSQL = new PostgreSQL(configurations)

val semaphore = new Semaphore(5)

for (item <- array) {
    semaphore.acquire()

    val thread = new Thread(new CustomThread(postgreSQL, semaphore, item))

    thread.start()
}

CustomThread.scala:

import java.util.concurrent.Semaphore
import java.util.UUID.randomUUID
import utils.PostgreSQL

class CustomThread(postgreSQL: PostgreSQL, semaphore: Semaphore, item: Item) extends Runnable {
    override def run(): Unit = {
        try {
            // Create the unique filename.
            val filename: String = randomUUID().toString

            // Write to the database the filename of the item.
            postgreSQL.changeItemFilename(filename, item.id)

            // Change the status type of the item.
            postgreSQL.changeItemStatusType(3, request.id)
        } catch {
            case e: Throwable =>
                e.printStackTrace()
        } finally {
            semaphore.release()
        }
    }
}

PostgreSQL.scala:

package utils

import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}
import java.util.Properties

class PostgreSQL(configurations: Map[String, String]) {
  val host: String = postgreSQLConfigurations("postgresql.host")
  val port: String = postgreSQLConfigurations("postgresql.port")
  val user: String = postgreSQLConfigurations("postgresql.user")
  val password: String = postgreSQLConfigurations("postgresql.password")
  val db: String = postgreSQLConfigurations("postgresql.db")
  val url: String = "jdbc:postgresql://" + host + ":" + port + "/" + db
  val driver: String = "org.postgresql.Driver"

  val properties = new Properties()

  val connection: Connection = getConnection

  var statement: PreparedStatement = _

  def getConnection: Connection = {
    properties.setProperty("user", user)
    properties.setProperty("password", password)

    var connection: Connection = null

    try {
      Class.forName(driver)
      connection = DriverManager.getConnection(url, properties)
    } catch {
      case e:Exception =>
        e.printStackTrace()
    }

    connection
  }

  def changeItemFilename(filename: String, id: Int): Unit = {
    try {
      statement = connection.prepareStatement("UPDATE REPORTS SET FILE_NAME = ? WHERE ID = ?;", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
      statement.setString(1, filename)
      statement.setInt(2, id)
      statement.execute()
    } catch {
      case e: Exception =>
        e.printStackTrace()
    }
  }
}


问:
Convert String to boolean only if input is "true" or "false"
How can I make sure that the input of a String is either "true" or "false" and then parse it to a boolean?

For example:

```<code>String input = "true"; -> boolean result = true;
String input = "false"; -> boolean result = false;
String input = "foobar"; -> throw new InvalidInputException("true or false is allowed");
</code>```

答:
You'll have to do if else statements if you want to make absolutely sure that the input is either "true"/"TRUE" or "false"/"FALSE":

```<code>if ("true".equalsIgnoreCase(input) {
    return true;
} else if ("false".equalsIgnoreCase(input)) {
    return false;
} else {
    throw new InvalidInputException("true or false is allowed")
}
</code>```

If you literally only want the case sensitive "true" or "false" then change .equalsIgnoreCase() to .equals()

Alternatively you can use BooleanUtils in Apache Commons Lang
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/BooleanUtils.html

```<code> Boolean bool = BooleanUtils.toBooleanObject(input)
</code>```

If it's neither "true" or "false" (Amongst other things like "t", "y", "yes" etc - see JavaDoc) then null is returned

Body:
How can I make sure that the input of a String is either "true" or "false" and then parse it to a boolean?

For example:

String input = "true"; -> boolean result = true;
String input = "false"; -> boolean result = false;
String input = "foobar"; -> throw new InvalidInputException("true or false is allowed");

Body:
You'll have to do if else statements if you want to make absolutely sure that the input is either "true"/"TRUE" or "false"/"FALSE":

if ("true".equalsIgnoreCase(input) {
    return true;
} else if ("false".equalsIgnoreCase(input)) {
    return false;
} else {
    throw new InvalidInputException("true or false is allowed")
}

If you literally only want the case sensitive "true" or "false" then change .equalsIgnoreCase() to .equals()

Alternatively you can use BooleanUtils in Apache Commons Lang
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/BooleanUtils.html

 Boolean bool = BooleanUtils.toBooleanObject(input)

If it's neither "true" or "false" (Amongst other things like "t", "y", "yes" etc - see JavaDoc) then null is returned


问:
Using Event Time with lateness in Flink SQL Windows
I have a data stream that is generally out of order. I define the dataset as:

```<code>DataStream<ApplicationMetric> metrics = env
  .addSource(new FlinkKinesisConsumer<>("applicationMetric", new SimpleStringSchema(), consumerConfig))
  .map(mapper)
  .assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<>(Time.seconds(30)));
</code>```

And print it as:

```<code>Table table = bsTableEnv.fromDataStream(dataset, "createdAt, name, duration, rowtime.rowtime");
Table t1 = bsTableEnv.sqlQuery("SELECT CAST((createdAt/1000) as TIMESTAMP) as ts, rowtime, name, duration " + table);
bsTableEnv.toAppendStream(t1, Row.class).print();
</code>```

So, how would that work if I try to use it in an SQL query with time windows (tumbling etc.), is that respected? I think I might be fundementally wrong about the concepts. But I assume the late events will be just dropped and I can use my rowtime as a tumbling window attribute?

答:
You can control how late events are treated in Datastream API. By default all events later than 30s are dropped in your code. These 30s add to your end-to-end latency, so output is hold back until Flink has seen 30s worth of data and respected all late events. You could also store late events in a separate output or retrigger computation.

Unfortunately, there is no support for this configuration on Table API/SQL. Late events will always be dropped, but that seems to be enough for your use case.

Body:
I have a data stream that is generally out of order. I define the dataset as:

DataStream<ApplicationMetric> metrics = env
  .addSource(new FlinkKinesisConsumer<>("applicationMetric", new SimpleStringSchema(), consumerConfig))
  .map(mapper)
  .assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<>(Time.seconds(30)));

And print it as:

Table table = bsTableEnv.fromDataStream(dataset, "createdAt, name, duration, rowtime.rowtime");
Table t1 = bsTableEnv.sqlQuery("SELECT CAST((createdAt/1000) as TIMESTAMP) as ts, rowtime, name, duration " + table);
bsTableEnv.toAppendStream(t1, Row.class).print();

So, how would that work if I try to use it in an SQL query with time windows (tumbling etc.), is that respected? I think I might be fundementally wrong about the concepts. But I assume the late events will be just dropped and I can use my rowtime as a tumbling window attribute?


答:
You can use:

if(input.toLowerCase().equals("true") || input.toLowerCase().equals("false")) {
    return Boolean.parseBoolean(input);
} else {
    throw new InvalidInputException("true or false is allowed");
}
```

Title: Convert String to boolean only if input is "true" or "false"