问:
HTTP Status 406 in rest api spring boot when getByEmail
I want to search by email but always get "error": "Not Acceptable",

```<code>@RestController
@RequestMapping("api/users")
public class UserController {

    private final UserService userService;
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping(value = "/{name:.+}")
    public User getUser(@PathVariable String name)  {
        return userService.getUserByEmail(name);
    }
</code>```

```<code>@Service
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;

    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;

    }
    @Override
    public User getUserByEmail(String email){
        User user = userRepository.findByEmail(email).get();
        return user;
    }
</code>```

```<code>@Repository
public interface UserRepository extends JpaRepository<User,Long> {
    Optional<User> findByEmail(@Param("email") String email);
}
</code>```

even It can fetch from database but when want to return throw error

but throw error

add header application/json header but don't work.

another thing that I can get byId and firstName ,this work correctly

答:
Try adding, value in pathVariable in the controller:

The content in bracket is a regex so it should work.

```<code>@GetMapping("/statusByEmail/{email:.+}/")
public String statusByEmail(@PathVariable(value = "email") String email){
  //code
}
</code>```

And from the postman/rest-client

```<code>Get http://mywebhook.com/statusByEmail/abc.test@gmail.com/
</code>```

If this doesn't work try to give the email in URLEncoded format:
The problem might be due to the multiple . in the request
Eg: alireza.ca%40gmail.com

OR

You can set Content-Type: application/x-www-form-urlencoded to automatically do the encoding of the url

Hopefully, this should work.

Body:
I want to search by email but always get "error": "Not Acceptable",

@RestController
@RequestMapping("api/users")
public class UserController {

    private final UserService userService;
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping(value = "/{name:.+}")
    public User getUser(@PathVariable String name)  {
        return userService.getUserByEmail(name);
    }

@Service
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;

    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;

    }
    @Override
    public User getUserByEmail(String email){
        User user = userRepository.findByEmail(email).get();
        return user;
    }

@Repository
public interface UserRepository extends JpaRepository<User,Long> {
    Optional<User> findByEmail(@Param("email") String email);
}

even It can fetch from database but when want to return throw error

but throw error

add header application/json header but don't work.

another thing that I can get byId and firstName ,this work correctly

Body:
Try adding, value in pathVariable in the controller:

The content in bracket is a regex so it should work.

@GetMapping("/statusByEmail/{email:.+}/")
public String statusByEmail(@PathVariable(value = "email") String email){
  //code
}

And from the postman/rest-client

Get http://mywebhook.com/statusByEmail/abc.test@gmail.com/

If this doesn't work try to give the email in URLEncoded format:
The problem might be due to the multiple . in the request
Eg: alireza.ca%40gmail.com

OR

You can set Content-Type: application/x-www-form-urlencoded to automatically do the encoding of the url

Hopefully, this should work.


来源: stackexchange

问:
File with CSS and JS files not serving on server and prints ��U�v�8��+
When I run my hapijs app locally it is working but when I deploy it in the server it doesn't work. The page can serve html files but if the HTML file has css or bootsrap then it prints weird
symbols like ��U�v�8��+

The link that shows the weird response : https://us-central1-fir-app-85853.cloudfunctions.net/v1/teacher/list

Here is my index.js file.

How can I fix this issue?

```<code>'use strict';
const functions = require('firebase-functions');
const api = require('./server');

exports.v1 = functions.https.onRequest(async (event, resp) => {
  let server = await api.startServer();
  const options = {
    method: event.httpMethod,
    headers: event.headers,
    url: event.path,
    payload: event.body
  };

  return server
    .inject(options)
    .then(response => {
        delete response.headers['content-encoding']
        delete response.headers['transfer-encoding']
        response.headers['x-powered-by'] = 'hapijs'
        resp.set(response.headers);
        return resp.status(response.statusCode).send(response.result);
    })
    .catch(error => resp.status(500).send(error.message || "unknown error"));
});
</code>```

Here is my full source code on github https://github.com/kartikgreen/hapijs-firebase

答:
I just removed the 'accept-encoding': 'gzip, deflate, br' line in the request headers' object to not request gzip compression.

This answer is already in the link

ContentLicense: CC BY-SA 4.0

Body:
When I run my hapijs app locally it is working but when I deploy it in the server it doesn't work. The page can serve html files but if the HTML file has css or bootsrap then it prints weird
symbols like ��U�v�8��+

The link that shows the weird response : https://us-central1-fir-app-85853.cloudfunctions.net/v1/teacher/list

Here is my index.js file.

How can I fix this issue?

'use strict';
const functions = require('firebase-functions');
const api = require('./server');

exports.v1 = functions.https.onRequest(async (event, resp) => {
  let server = await api.startServer();
  const options = {
    method: event.httpMethod,
    headers: event.headers,
    url: event.path,
    payload: event.body
  };

  return server
    .inject(options)
    .then(response => {
        delete response.headers['content-encoding']
        delete response.headers['transfer-encoding']
        response.headers['x-powered-by'] = 'hapijs'
        resp.set(response.headers);
        return resp.status(response.statusCode).send(response.result);
    })
    .catch(error => resp.status(500).send(error.message || "unknown error"));
});

Here is my full source code on github https://github.com/kartikgreen/hapijs-firebase


问:
Create table in SQLite only if it doesn't exist already
I want to create a table in a SQLite database only if doesn't exist already. Is there any way to do this? I don't want to drop the table if it exists, only create it if it doesn't.</p>

答:
Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).

# for completeness lets do the routine thing of connections and cursors
conn = sqlite3.connect(db_file, timeout=1000)

cursor = conn.cursor()

# get the count of tables with the name
tablename = 'KABOOM'
cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))

print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.

# check if the db has existing table named KABOOM
# if the count is 1, then table exists
if cursor.fetchone()[0] ==1 :
    print('Table exists. I can do my custom stuff here now.... ')
    pass
else:
   # then table doesn't exist.
   custRET = myCustFunc(foo,bar) # replace this with your custom logic
```

ContentLicense: CC BY-SA 3.0


问:
Running keras tokenizer in loop
I have a multiple files with different structure I would like to tokenize.

For example file 1:

event_name, event_location, event_description, event_priority

file2:

event_name, event_participants, event_location,event_description,  event_priority

and so on. I would like to create create an array with data from all files and then tokenize it. unfortunately when I run tokenizer.fit_on_texts() in loop dictionary is not expanding but is overwritten. I have to use tokenizer in loop because I need to pad event_description

my code:

```<code>    tokenizer = Tokenizer(num_words=50000, oov_token="<OOV>")
    for file in files:
        print("Loading : ", file)
        events= pd.read_csv(file)
        # prepare columns
        events['event_name'] = 'XXBOS XXEN ' + events['event_name'].astype(str)
        events['event_location'] = 'XXEL ' + events['event_location'].astype(str)
        events['event_description'] = 'XXED ' + events['event_description'].astype(str)
        events['event_priority'] = 'XXEP ' + events['event_priority'].astype(str) + ' XXEOS'
        # Tokenize concatenated columns into one
        tokenizer.fit_on_texts(np.concatenate((events['event_name'],events['event_location'], events['event_description'], events['event_priority']), axis=0))
        # Later I run texts_to_sequences on each column so later i am able to run pad_sequences on it and again I concatenate them
</code>```

When I check tokenizer.word_index, the tokens like XXBOS location is changing between loop iterations. Is it possible to fulfill word_index dictionary instead of overwriting it?

EDIT:
experiment:

```<code>from tensorflow.keras.preprocessing.text import Tokenizer
tokenizer = Tokenizer(filters='.!"#$%&()*+,-/:;<=>?@[\\]^_`{|}~\t\n', num_words=50000, oov_token="<OOV>", split=' ', char_level=False)
text = "some text for test"
tokenizer.word_index
{'<OOV>': 1, 't': 2, 'e': 3, 's': 4, 'o': 5, 'm': 6, 'x': 7, 'f': 8, 'r': 9}
</code>```

and adding another text to fit:

```<code>text2="new sentence with unknown chars xxasqeew"
tokenizer.fit_on_texts(text2)
tokenizer.word_index
{'<OOV>': 1, 'e': 2, 't': 3, 'n': 4, 's': 5, 'w': 6, 'o': 7, 'x': 8, 'r': 9, 'c': 10, 'h': 11, 'a': 12, 'm': 13, 'f': 14, 'i': 15, 'u': 16, 'k': 17, 'q': 18}
</code>```

indexes in tokenizer changed completely

答:
Just store your events, and then tokenize all the events at once:

```<code>def create_tokenizer():
    return Tokenizer(num_words=50000, oov_token="<OOV>")

all_events = []
files_to_tokens_dict = {}
for file in files:
    print("Loading : ", file)
    events= pd.read_csv(file)
    # prepare columns
    events['event_name'] = 'XXBOS XXEN ' + events['event_name'].astype(str)
    events['event_location'] = 'XXEL ' + events['event_location'].astype(str)
    events['event_description'] = 'XXED ' + events['event_description'].astype(str)
    events['event_priority'] = 'XXEP ' + events['event_priority'].astype(str) + ' XXEOS'
    # Tokenize concatenated columns into one
    all_events.append(events['event_name'])
    all_events.append(events['event_location'])
    all_events.append(events['event_description'])
    all_events.append(events['event_priority'])
    tokenizer = create_tokenizer()
    tokenizer.fit_on_text(events['event_name'], events['event_location'], events['event_description'], events['event_priority'])
    tokens_in_current_file = tokenizer.word_index.keys()
    files_to_tokens_dict[file] = tokens_in_current_file

global_tokenizer = create_tokenizer()
global_tokenizer.fit_on_texts(all_events)
global_tokenizer.word_index # one word index with all tokens
</code>```

Then if you want to retrieve the indices of the tokens:

```<code>def get_token_indices(file):
    tokens_in_file = files_to_tokens_dict[file]
    result = []
    for token in tokens_in_file:
        global_token_index = global_tokenizer.word_index[token]
        result.append(global_token_index)
    return result
</code>```

Title: Running keras tokenizer in loop

Body:
I have a multiple files with different structure I would like to tokenize.

For example file 1:

event_name, event_location, event_description, event_priority

file2:

event_name, event_participants, event_location,event_description,  event_priority

and so on. I would like to create create an array with data from all files and then tokenize it. unfortunately when I run tokenizer.fit_on_texts() in loop dictionary is not expanding but is overwritten. I have to use tokenizer in loop because I need to pad event_description

my code:

    tokenizer = Tokenizer(num_words=50000, oov_token="<OOV>")
    for file in files:
        print("Loading : ", file)
        events= pd.read_csv(file)
        # prepare columns
        events['event_name'] = 'XXBOS XXEN ' + events['event_name'].astype(str)
        events['event_location'] = 'XXEL ' + events['event_location'].astype(str)
        events['event_description'] = 'XXED ' + events['event_description'].astype(str)
        events['event_priority'] = 'XXEP ' + events['event_priority'].astype(str) + ' XXEOS'
        # Tokenize concatenated columns into one
        tokenizer.fit_on_texts(np.concatenate((events['event_name'],events['event_location'], events['event_description'], events['event_priority']), axis=0))
        # Later I run texts_to_sequences on each column so later i am able to run pad_sequences on it and again I concatenate them

When I check tokenizer.word_index, the tokens like XXBOS location is changing between loop iterations. Is it possible to fulfill word_index dictionary instead of overwriting it?

EDIT:
experiment:

from tensorflow.keras.preprocessing.text import Tokenizer
tokenizer = Tokenizer(filters='.!"#$%&()*+,-/:;<=>?@[\\]^_`{|}~\t\n', num_words=50000, oov_token="<OOV>", split=' ', char_level=False)
text = "some text for test"
tokenizer.word_index
{'<OOV>': 1, 't': 2, 'e': 3, 's': 4, 'o': 5, 'm': 6, 'x': 7, 'f': 8, 'r': 9}

and adding another text to fit:

text2="new sentence with unknown chars xxasqeew"
tokenizer.fit_on_texts(text2)
tokenizer.word_index
{'<OOV>': 1, 'e': 2, 't': 3, 'n': 4, 's': 5, 'w': 6, 'o': 7, 'x': 8, 'r': 9, 'c': 10, 'h': 11, 'a': 12, 'm': 13, 'f': 14, 'i': 15, 'u': 16, 'k': 17, 'q': 18}

indexes in tokenizer changed completely

Body:
Just store your events, and then tokenize all the events at once:

def create_tokenizer():
    return Tokenizer(num_words=50000, oov_token="<OOV>")

all_events = []
files_to_tokens_dict = {}
for file in files:
    print("Loading : ", file)
    events= pd.read_csv(file)
    # prepare columns
    events['event_name'] = 'XXBOS XXEN ' + events['event_name'].astype(str)
    events['event_location'] = 'XXEL ' + events['event_location'].astype(str)
    events['event_description'] = 'XXED ' + events['event_description'].astype(str)
    events['event_priority'] = 'XXEP ' + events['event_priority'].astype(str) + ' XXEOS'
    # Tokenize concatenated columns into one
    all_events.append(events['event_name'])
    all_events.append(events['event_location'])
    all_events.append(events['event_description'])
    all_events.append(events['event_priority'])
    tokenizer = create_tokenizer()
    tokenizer.fit_on_text(events['event_name'], events['event_location'], events['event_description'], events['event_priority'])
    tokens_in_current_file = tokenizer.word_index.keys()
    files_to_tokens_dict[file] = tokens_in_current_file

global_tokenizer = create_tokenizer()
global_tokenizer.fit_on_texts(all_events)
global_tokenizer.word_index # one word index with all tokens

Then if you want to retrieve the indices of the tokens:

def get_token_indices(file):
    tokens_in_file = files_to_tokens_dict[file]
    result = []
    for token in tokens_in_file:
        global_token_index = global_tokenizer.word_index[token]
        result.append(global_token_index)
    return result


问:
Running Tests with MockitoJUnitRunner fails verify asserts
Is there a way to mock a Repository without the @RunWith(MockitoJUnitRunner) annotation on the class?

I have a test that passed without the annotation but fails with it. Without it, my repo test doesn't work. It's a catch 22.

When I use that annotation, my when() methods in my tests no longer stub behavior, mocks do nothing, and despite setting break ppoints and those breakpoints being hit (indicating the line/method is run), verify(..., times(x)) statements say the mocked object never interacted with that method. I've been pulling my hair out on why using the @RunWith(MockitoJUnitRunner) annotation would make the most simple parts of Mockito not work.

I can't find any threads asking about this but maybe someone knows better keywords to use. Does this sound like a known issue?

Here is my test:

```<code>import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;

// toggling this below annotation is the source of grief.
//@RunWith(MockitoJUnitRunner.class)
public class LoadEditEntityChangeLogServiceImplTest {

    @InjectMocks
    private ServiceImpl serviceMock;

    @Mock
    private EditStepRepository editStepRepository;

    @Mock
    private EditMapper editMapper;

    @Before
    public void init() {
        initMocks(this);
    }

    @Test // when the RunWith is commented out, this passes. When it is not, the test fails the verify assert.
    public void mapEditEntityFromAction_Test() {
        EditDTO editDTO = Mockito.mock(EditDTO.class);
        when(editDTO.getSysNum()).thenReturn((long)7334);

        EditEntity editEntity = new editEntity();
        editEntity.setSysNum(editDTO.getSysNum());

        when(editMapper.mapToEntity(eq(editDTO))).thenReturn(editEntity);

        editEntity response = serviceMock.mapEditEntityFromAction(editDTO);

        verify(loadEditMapper, times(1)).mapToEntity(eq(loadEventDTO));
        assertEquals(loadEventDTO.getSystemNumber(), response.getSystemNumber());
    }

    @Test // this will fail without the @RunWith as the mocked repo will be null and throws NullPointerException when used.
    public void updateConvertedEventSegment_Test() {
        EditEntity editEntity = new EditEntity();
        EditStepEntity editStepEntity = new EditStepEntity();
        editEntity.setEditStep(editStepEntity);

        doReturn(editStepEntity).when(editStepRepository).save(any());

        serviceMock.updateEditStep(editEntity);

        verify(editEntity, times(1)).getEditStep();
        verify(editStepRepository, times(1)).save(eq(editStepEntity));
    }
}
</code>```

答:
You should understand what does this runner actually do:

Basically it allows injecting mocks (prepared by mockito with Mockito.mock(...) ) into the test fields annotated with @Mock. In the question, since you've commented out the runner, all these fields will be null.

When you annotated something with @InjectMocks - it will inject the mocks into the fields of the object of type of the annotated reference.

One more point to clarify here: MockitoAnnotations.initMocks(this) will do the same as the "runner" so no need to include both (you should use initMocks if you can't use the runner for some reason, like if there is already another runner that must be used)

Now, you ask:

Is there a way to mock a Repository without the @RunWith(MockitoJUnitRunner) annotation on the class?

The answer is - yes, you can, in fact you don't have to use the runner, sometimes its more convenient.

So, assuming you really use this runner, the real question is what exactly do you mean by "my repository doesn't work". Does this mean that there exists a reference in the service that points of this repository and its null?

Does it mean that there is a mock of repository but when you execute the call "under the test" the mock is different?

You don't show it in the code, but I assume you have some like this:

```<code>public class ServiceImpl {
   private final EditStepRepository editStepRepository;

   public ServiceImpl(EditStepRepository editStepRepository) {
      this.editStepRepository = editStepRepository;
   }
   ...
}
</code>```

But if so, once you create a mock (and indeed there should be a mock injected into the ServiceImpl class (check this out with debugger or something), There should be expectatations specified on the repository, usually there should be code like this in the test:

```<code>Mockito.when(editStepRepository.doSomething(...)).thenReturn(...)
</code>```

You haven't placed any of these lines, that why it doesn't work.

But all-in-all since the question contains many uncertain technicalities like this, I can't tell more than that other that speculating...

Body:
Is there a way to mock a Repository without the @RunWith(MockitoJUnitRunner) annotation on the class?

I have a test that passed without the annotation but fails with it. Without it, my repo test doesn't work. It's a catch 22.

When I use that annotation, my when() methods in my tests no longer stub behavior, mocks do nothing, and despite setting break ppoints and those breakpoints being hit (indicating the line/method is run), verify(..., times(x)) statements say the mocked object never interacted with that method. I've been pulling my hair out on why using the @RunWith(MockitoJUnitRunner) annotation would make the most simple parts of Mockito not work.

I can't find any threads asking about this but maybe someone knows better keywords to use. Does this sound like a known issue?

Here is my test:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;

// toggling this below annotation is the source of grief.
//@RunWith(MockitoJUnitRunner.class)
public class LoadEditEntityChangeLogServiceImplTest {

    @InjectMocks
    private ServiceImpl serviceMock;

    @Mock
    private EditStepRepository editStepRepository;

    @Mock
    private EditMapper editMapper;

    @Before
    public void init() {
        initMocks(this);
    }

    @Test // when the RunWith is commented out, this passes. When it is not, the test fails the verify assert.
    public void mapEditEntityFromAction_Test() {
        EditDTO editDTO = Mockito.mock(EditDTO.class);
        when(editDTO.getSysNum()).thenReturn((long)7334);

        EditEntity editEntity = new editEntity();
        editEntity.setSysNum(editDTO.getSysNum());

        when(editMapper.mapToEntity(eq(editDTO))).thenReturn(editEntity);

        editEntity response = serviceMock.mapEditEntityFromAction(editDTO);

        verify(loadEditMapper, times(1)).mapToEntity(eq(loadEventDTO));
        assertEquals(loadEventDTO.getSystemNumber(), response.getSystemNumber());
    }

    @Test // this will fail without the @RunWith as the mocked repo will be null and throws NullPointerException when used.
    public void updateConvertedEventSegment_Test() {
        EditEntity editEntity = new EditEntity();
        EditStepEntity editStepEntity = new EditStepEntity();
        editEntity.setEditStep(editStepEntity);

        doReturn(editStepEntity).when(editStepRepository).save(any());

        serviceMock.updateEditStep(editEntity);

        verify(editEntity, times(1)).getEditStep();
        verify(editStepRepository, times(1)).save(eq(editStepEntity));
    }
}

Body:
You should understand what does this runner actually do:

Basically it allows injecting mocks (prepared by mockito with Mockito.mock(...) ) into the test fields annotated with @Mock. In the question, since you've commented out the runner, all these fields will be null.

When you annotated something with @InjectMocks - it will inject the mocks into the fields of the object of type of the annotated reference.

One more point to clarify here: MockitoAnnotations.initMocks(this) will do the same as the "runner" so no need to include both (you should use initMocks if you can't use the runner for some reason, like if there is already another runner that must be used)

Now, you ask:

Is there a way to mock a Repository without the @RunWith(MockitoJUnitRunner) annotation on the class?

The answer is - yes, you can, in fact you don't have to use the runner, sometimes its more convenient.

So, assuming you really use this runner, the real question is what exactly do you mean by "my repository doesn't work". Does this mean that there exists a reference in the service that points of this repository and its null?

Does it mean that there is a mock of repository but when you execute the call "under the test" the mock is different?

You don't show it in the code, but I assume you have some like this:

public class ServiceImpl {
   private final EditStepRepository editStepRepository;

   public ServiceImpl(EditStepRepository editStepRepository) {
      this.editStepRepository = editStepRepository;
   }
   ...
}

But if so, once you create a mock (and indeed there should be a mock injected into the ServiceImpl class (check this out with debugger or something), There should be expectatations specified on the repository, usually there should be code like this in the test:

Mockito.when(editStepRepository.doSomething(...)).thenReturn(...)

You haven't placed any of these lines, that why it doesn't work.

But all-in-all since the question contains many uncertain technicalities like this, I can't tell more than that other that speculating...


问:
Expo/React Native - Can't redirect to homescreen after login
I am working on a mobile app with Expo/React Native and trying to have a login screen for sign in. Once signed in,the user will be redirected to the homescreen.

However I have not been able to configure it with setting the state upon successful gaining the credentials for "isLoggedIn:true." On the stack navigator, I tried to set it up where it will show different screens (Home and Third Screen) if logged in while the LoginScreen will be if logged in is false. How do I configure it to properly redirect to the homescreen upon successful login.

```<code>export default function App() {
const [state, setstate] = useState({
   isSignedIn:false,
 })

 return (
<NavigationContainer>
  <Stack.Navigator>

  {state.isSignedIn == false ? (
    <>
    <Stack.Screen name='Login' component={LoginScreen} />
    </>
  ) : (
    <>
    <Stack.Screen name='Home' component={HomeStack} options={({ route }) => ({
headerTitle: getHeaderTitle(route) })} />

    <Stack.Screen name='ThirdScreen' component={ThirdScreen}/>
    </>
  )}

   </Stack.Navigator>
</NavigationContainer>
 );
}
</code>```

Below is my code for the login on the LoginScreen.js:

```<code> render() {
function handleSubmit({ props }) {

  let formData = new FormData();
  formData.append('username',this.state.username);
  formData.append('password',this.state.password);

  fetch('<My login API from the server side>', {
    method: 'POST',
    body:formData
  }).then(response => {
    if(response.status == 200) {
      response.body.getReader().read().then(({value, done}) => {
        const decoder = new TextDecoder('utf-8')
        const keyitems = decoder.decode(value);
        //convert to JSON
        const obj = JSON.parse(keyitems);

        //get individual values from string
        this.setState({
          userToken:obj.key.toString(),
          username:obj.user.username,
          user_id:obj.user.id,
          user_image:obj.user.userprofile.user_image,
          isSignedIn:true
        })
        //refresh or redirect to hopefully get to home
        //assuming the state has been switched to logged
        this.props.navigation.navigate('Home')
      })

    } else {
      //issue alert to say try again
      console.log("bad")
    }
  });

 }
</code>```

答:
you don't need to navigate to the Home screen manually by calling navigation.navigate('Home'). React Navigation will automatically navigate to the Home screen when isSignedIn becomes true.

https://reactnavigation.org/docs/auth-flow/

It seems like you have written a hook call 'setstate' but you have not used that in the child component. To make it work, you would need to pass the function argument of the hook in the parent component to the child component and call that to set the signed in state.

Try modifying your code like this

```<code>   export default function App() {
const [state, setState] = useState({
   isSignedIn:false,
 })

 return (
<NavigationContainer>
  <Stack.Navigator>

  {state.isSignedIn == false ? (
    <>
    <Stack.Screen name='Login' component={LoginScreen} setState={setState} />
    </>
  ) : (
    <>
    <Stack.Screen name='Home' component={HomeStack} options={({ route }) => ({
headerTitle: getHeaderTitle(route) })} />

    <Stack.Screen name='ThirdScreen' component={ThirdScreen}/>
    </>
  )}

   </Stack.Navigator>
</NavigationContainer>
 );
}
</code>```

and

```<code>render() {
function handleSubmit({ props }) {

  let formData = new FormData();
  formData.append('username',this.state.username);
  formData.append('password',this.state.password);

  fetch('<My login API from the server side>', {
    method: 'POST',
    body:formData
  }).then(response => {
    if(response.status == 200) {
      response.body.getReader().read().then(({value, done}) => {
        const decoder = new TextDecoder('utf-8')
        const keyitems = decoder.decode(value);
        //convert to JSON
        const obj = JSON.parse(keyitems);

        //get individual values from string
        props.setState({
          userToken:obj.key.toString(),
          username:obj.user.username,
          user_id:obj.user.id,
          user_image:obj.user.userprofile.user_image,
          isSignedIn:true
        })
      })

    } else {
      //issue alert to say try again
      console.log("bad")
    }
  });

 }
</code>```

Body:
I am working on a mobile app with Expo/React Native and trying to have a login screen for sign in. Once signed in,the user will be redirected to the homescreen.

However I have not been able to configure it with setting the state upon successful gaining the credentials for "isLoggedIn:true." On the stack navigator, I tried to set it up where it will show different screens (Home and Third Screen) if logged in while the LoginScreen will be if logged in is false. How do I configure it to properly redirect to the homescreen upon successful login.

export default function App() {
const [state, setstate] = useState({
   isSignedIn:false,
 })

 return (
<NavigationContainer>
  <Stack.Navigator>

  {state.isSignedIn == false ? (
    <>
    <Stack.Screen name='Login' component={LoginScreen} />
    </>
  ) : (
    <>
    <Stack.Screen name='Home' component={HomeStack} options={({ route }) => ({
headerTitle: getHeaderTitle(route) })} />

    <Stack.Screen name='ThirdScreen' component={ThirdScreen}/>
    </>
  )}

   </Stack.Navigator>
</NavigationContainer>
 );
}

Below is my code for the login on the LoginScreen.js:

 render() {
function handleSubmit({ props }) {

  let formData = new FormData();
  formData.append('username',this.state.username);
  formData.append('password',this.state.password);

  fetch('<My login API from the server side>', {
    method: 'POST',
    body:formData
  }).then(response => {
    if(response.status == 200) {
      response.body.getReader().read().then(({value, done}) => {
        const decoder = new TextDecoder('utf-8')
        const keyitems = decoder.decode(value);
        //convert to JSON
        const obj = JSON.parse(keyitems);

        //get individual values from string
        this.setState({
          userToken:obj.key.toString(),
          username:obj.user.username,
          user_id:obj.user.id,
          user_image:obj.user.userprofile.user_image,
          isSignedIn:true
        })
        //refresh or redirect to hopefully get to home
        //assuming the state has been switched to logged
        this.props.navigation.navigate('Home')
      })

    } else {
      //issue alert to say try again
      console.log("bad")
    }
  });

 }

Body:
you don't need to navigate to the Home screen manually by calling navigation.navigate('Home'). React Navigation will automatically navigate to the Home screen when isSignedIn becomes true.

https://reactnavigation.org/docs/auth-flow/

It seems like you have written a hook call 'setstate' but you have not used that in the child component. To make it work, you would need to pass the function argument of the hook in the parent component to the child component and call that to set the signed in state.

Try modifying your code like this

   export default function App() {
const [state, setState] = useState({
   isSignedIn:false,
 })

 return (
<NavigationContainer>
  <Stack.Navigator>

  {state.isSignedIn == false ? (
    <>
    <Stack.Screen name='Login' component={LoginScreen} setState={setState} />
    </>
  ) : (
    <>
    <Stack.Screen name='Home' component={HomeStack} options={({ route }) => ({
headerTitle: getHeaderTitle(route) })} />

    <Stack.Screen name='ThirdScreen' component={ThirdScreen}/>
    </>
  )}

   </Stack.Navigator>
</NavigationContainer>
 );
}

and

render() {
function handleSubmit({ props }) {

  let formData = new FormData();
  formData.append('username',this.state.username);
  formData.append('password',this.state.password);

  fetch('<My login API from the server side>', {
    method: 'POST',
    body:formData
  }).then(response => {
    if(response.status == 200) {
      response.body.getReader().read().then(({value, done}) => {
        const decoder = new TextDecoder('utf-8')
        const keyitems = decoder.decode(value);
        //convert to JSON
        const obj = JSON.parse(keyitems);

        //get individual values from string
        props.setState({
          userToken:obj.key.toString(),
          username:obj.user.username,
          user_id:obj.user.id,
          user_image:obj.user.userprofile.user_image,
          isSignedIn:true
        })
      })

    } else {
      //issue alert to say try again
      console.log("bad")
    }
  });

 }


问:
ASP.NET MVC Identity Backward Cookie Expire Time

there is something wrong. i use 30 minutes expire and validate time but its doing negative 23 days. i check my computer datetime but cant figure out

my StartupAuth.cs is here

```<code>public partial class Startup
{

    // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            },
            SlidingExpiration = true,
            ExpireTimeSpan = TimeSpan.FromMinutes(30)
        });

    }
}
</code>```

答:
Interesting thing but i use
ExpireTimeSpan = TimeSpan.FromDays(24)
for after 12 hour. i cant find why

Body:
there is something wrong. i use 30 minutes expire and validate time but its doing negative 23 days. i check my computer datetime but cant figure out

my StartupAuth.cs is here

public partial class Startup
{

    // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            },
            SlidingExpiration = true,
            ExpireTimeSpan = TimeSpan.FromMinutes(30)
        });

    }
}


问:
The server response was: 5.7.0 Authentication Required in C# web hosting website
Recently I am working on sending mail by c# coding and I tryed to send mail by c# coding on visual studio platform and it's work totally fine in my localhost of visual studio. but when I run that same code over other hosting website like myASP.NET or Somee.com that time that code getting error.

error like (if I used smtp.gmail.com then error like

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required. Learn more at)

and (if I used smtp.somee.com then error generate like

Failure sending mail.)

Sending mail Code in c# is,

```<code>String username = "";
      string password = "";
      OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["cstring"].ConnectionString);
      OleDbCommand cmd = new OleDbCommand("select umail, lpwd from uregister where umail=@email", con);
      cmd.Parameters.AddWithValue("email", txtEmail.Text);
      con.Open();
      using(OleDbDataReader sdr = cmd.ExecuteReader()) {

          if (sdr.Read()) {
              username = sdr["umail"].ToString();
              password = sdr["lpwd"].ToString();

          }

      }
      con.Close();
         if (!string.IsNullOrEmpty(password)) {

            MailMessage Msg = new MailMessage();
              // Sender e-mail address.
              Msg.From = new MailAddress(txtEmail.Text);
              // Recipient e-mail address.
              Msg.To.Add(txtEmail.Text);
              Msg.Subject = "Your Password Details";
              Msg.Body = ("Your Username is:" + username + "<br/><br/>" + "Your Password is:" + password);
              Msg.IsBodyHtml = true;
              // your remote SMTP server IP.
               SmtpClient Smtp = new SmtpClient();
              Smtp.Host = "";
             Smtp.Port = 587;
            NetworkCredential ntwd = new NetworkCredential();
                    ntwd.UserName = "xyz@gmail.com"; //Your Email ID
          ntwd.Password = "xyz123."; // Your Password
            Smtp.UseDefaultCredentials = false;
          Smtp.Credentials = ntwd;

          Smtp.EnableSsl = true;
          Smtp.Send(Msg);

              lbltxt.Text = "Your Password Details Sent to your mail.";
              // Clear the textbox valuess
              txtEmail.Text = "";
          }
          else
          {
              lbltxt.Text = "The Email you entered not exists.";
          }
</code>```

this code is not work on hosting site somee.com/myASP.NET. so please let me know what is problem in this code..

答: In your case, you should provide strong password as per domain policy.</p>

Body:
Recently I am working on sending mail by c# coding and I tryed to send mail by c# coding on visual studio platform and it's work totally fine in my localhost of visual studio. but when I run that same code over other hosting website like myASP.NET or Somee.com that time that code getting error.

error like (if I used smtp.gmail.com then error like

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required. Learn more at)

and (if I used smtp.somee.com then error generate like

Failure sending mail.)

Sending mail Code in c# is,

String username = "";
      string password = "";
      OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["cstring"].ConnectionString);
      OleDbCommand cmd = new OleDbCommand("select umail, lpwd from uregister where umail=@email", con);
      cmd.Parameters.AddWithValue("email", txtEmail.Text);
      con.Open();
      using(OleDbDataReader sdr = cmd.ExecuteReader()) {

          if (sdr.Read()) {
              username = sdr["umail"].ToString();
              password = sdr["lpwd"].ToString();

          }

      }
      con.Close();
         if (!string.IsNullOrEmpty(password)) {

            MailMessage Msg = new MailMessage();
              // Sender e-mail address.
              Msg.From = new MailAddress(txtEmail.Text);
              // Recipient e-mail address.
              Msg.To.Add(txtEmail.Text);
              Msg.Subject = "Your Password Details";
              Msg.Body = ("Your Username is:" + username + "

" + "Your Password is:" + password);
              Msg.IsBodyHtml = true;
              // your remote SMTP server IP.
               SmtpClient Smtp = new SmtpClient();
              Smtp.Host = "";
             Smtp.Port = 587;
            NetworkCredential ntwd = new NetworkCredential();
                    ntwd.UserName = "xyz@gmail.com"; //Your Email ID
          ntwd.Password = "xyz123."; // Your Password
            Smtp.UseDefaultCredentials = false;
          Smtp.Credentials = ntwd;

          Smtp.EnableSsl = true;
          Smtp.Send(Msg);

              lbltxt.Text = "Your Password Details Sent to your mail.";
              // Clear the textbox valuess
              txtEmail.Text = "";
          }
          else
          {
              lbltxt.Text = "The Email you entered not exists.";
          }

this code is not work on hosting site somee.com/myASP.NET. so please let me know what is problem in this code..


问:
NestJS passing Authorization header to HttpService
I have a NestJS application which acts as a proxy between a front-end and multiple other back-ends.

I basically want to be able to pass a specific header (Authorization) from incoming @Req (requests) in the controller to the HttpService that then talks to the other back-ends.

user controller (has access to request) ->
user service (injects httpService that somehow already picks the Authorization header) -> External backends.

Right now I need to extract the token from @Headers and then pass token to service which has to paste it to all HttpService calls.

Thanks in advance!

答:
Ok, I managed to solve this by actually using a middleware that I initially thought. I am not a 100% sure this is the NEST way but intercepting the underlying axios reference of the HttpService did the trick:

@Injectable()
export class BearerMiddleware implements NestMiddleware {
  constructor(private readonly httpService: HttpService) {}
  use(req: Request, res: Response, next: Function) {
    this.httpService.axiosRef.interceptors.request.use(request => {
      request.headers = {
        ...request.headers,
        Authorization: req.headers.Authorization || '',
      };
      return request;
    });
    next();
  }
}
```


问:
NGRX - spread operator remove atribute instead of replace in reducer
In my reducer I am trying to merge current state with value pased trought action. But problem is that merge operation remove object atribut instead of updating it.
I am using:

```<code>    on(WineActions.SetCurrentWine, (state, data) => {
        const newState = deepCopy(state);
        return {
            ...newState,
            currentWine: {...newState.currentWine, ...data}
        };
    }),
    ...
    export function deepCopy(state) {
       return JSON.parse(JSON.stringify(state));
    }
</code>```

ionic cli 6.9.1

angular 8.2.14

ngrx/store 8.6.0

ngrx/store-devtools 8.6.0

Action snapshot
Diff snapshot

Thank to all of you!!!!

Edit:
I did went trough whole reducer and find out that problem was initialize action... I hate that I do not know why merge does not work but it is working now...

答:
It seems the spread operation overwrites the actual update. Should not it be like:

currentWine: {
   ...newState.currentWine,
   ...data,
   wineColor: newState.currentWine.wineColor,
}
```

Body:
In my reducer I am trying to merge current state with value pased trought action. But problem is that merge operation remove object atribut instead of updating it.
I am using:

    on(WineActions.SetCurrentWine, (state, data) => {
        const newState = deepCopy(state);
        return {
            ...newState,
            currentWine: {...newState.currentWine, ...data}
        };
    }),
    ...
    export function deepCopy(state) {
       return JSON.parse(JSON.stringify(state));
    }

ionic cli 6.9.1

angular 8.2.14

ngrx/store 8.6.0

ngrx/store-devtools 8.6.0

Action snapshot
Diff snapshot

Thank to all of you!!!!

Edit:
I did went trough whole reducer and find out that problem was initialize action... I hate that I do not know why merge does not work but it is working now...


问:
While exporting data to excel, date is changing according to timezone. How to avoid it?
When I try to export data to excel in angular, the date in database is in 'x' timezone and I'm exporting data from 'y' timezone. While data is getting exported to excel, date is in 'y' timezone. But i want to keep it same as date in database i.e, date with 'x' timezone only.

I expect output as Mar 26 2014 12:00 AM but I'm receiving this 2014-03-25 23:00:00.000+0000.

private export(records: any[]) {
    // get the export fields
    let exportFields = this.gridConfig.columnDefinitions.map(function (colDef) {
      if(false == colDef.exportField) {
        return;
      }
      return colDef.field;
    });
    let filtered = this.gridOptions.api.getSelectedRows().map(record => {
      return _.pick(this.flatten(record), exportFields);
    });

    const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(filtered);

    let range = XLSX.utils.decode_range(ws['!ref']);
    for(let c = range.s.c; c <= range.e.c; ++c) {
      let address = XLSX.utils.encode_col(c) + "1"; // <-- first row, column number C
      if(!ws[address]) continue;
      ws[address].v = this.findHeaderNameByField(ws[address].v);
    }

    /* generate workbook and add the worksheet */
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'data');

    /* save to file */
    XLSX.writeFile(wb, 'Export.xlsx');
}
```

When I debugged I found that data from api is only receiving as time with 'y' zone.

答:
I know its not the best practice but I just changed the date:</p>

```<code>const date = <Date>cell.value;
if (date) {
    const ONE_MINUTE = 60 * 1000;
    const ticks = date.getTime() - date.getTimezoneOffset() * ONE_MINUTE;
    cell.value = new Date(ticks);
}
</code>```

Body:
When I try to export data to excel in angular, the date in database is in 'x' timezone and I'm exporting data from 'y' timezone. While data is getting exported to excel, date is in 'y' timezone. But i want to keep it same as date in database i.e, date with 'x' timezone only.

I expect output as Mar 26 2014 12:00 AM but I'm receiving this 2014-03-25 23:00:00.000+0000.

private export(records: any[]) {
    // get the export fields
    let exportFields = this.gridConfig.columnDefinitions.map(function (colDef) {
      if(false == colDef.exportField) {
        return;
      }
      return colDef.field;
    });
    let filtered = this.gridOptions.api.getSelectedRows().map(record => {
      return _.pick(this.flatten(record), exportFields);
    });

    const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(filtered);

    let range = XLSX.utils.decode_range(ws['!ref']);
    for(let c = range.s.c; c <= range.e.c; ++c) {
      let address = XLSX.utils.encode_col(c) + "1"; // <-- first row, column number C
      if(!ws[address]) continue;
      ws[address].v = this.findHeaderNameByField(ws[address].v);
    }

    /* generate workbook and add the worksheet */
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'data');

    /* save to file */
    XLSX.writeFile(wb, 'Export.xlsx');
}

When I debugged I found that data from api is only receiving as time with 'y' zone.

Body:
I know its not the best practice but I just changed the date:

const date = <Date>cell.value;
if (date) {
    const ONE_MINUTE = 60 * 1000;
    const ticks = date.getTime() - date.getTimezoneOffset() * ONE_MINUTE;
    cell.value = new Date(ticks);
}


问:
Question regarding multi-threaded environment of servlet
If there is a servlet, inside a servlet container such as Websphere. The servlet are executed by some threads. I would like to ask, what does the threads share? How variables are shared between them?

Do they have a local copy of the following variables?

1) private/protected/public final Semaphore permits = new Semaphore(50);

2) private/protected/public final static Semaphore permits = new Semaphore(50);

3) private/protected/public Semaphore permits = new Semaphore(50);

4) private/protected/public static Semaphore permits = new Semaphore(50);

How should I declare the semaphore so that I can use semaphore to control them? I don't want them to have each of them a copy of the semaphore. Thanks.

答:
Threads are run by Websphere thread pool and you should not be concerned about accessing them or sharing information via them.

Your semaphore will be shared if you declare it static in your servlet, for as long as all classes that use it live in the same application under the same classloader. However, there is a big risk in this case that if your execution path does not release permit (for example due to exception) you may end up with all threads blocked.


问:
How to select specific range of data column with C#
I am trying to display several data, but I cannot select the column that I want. My code will produce all of the column data values. I have 9 columns in data table (zero-based), and I just want to get the data from column 3 till column 9. Grateful for any kind of insight!</p>

```<code>foreach (DataColumn column in dt.Columns)
    {
        int i = dt.Columns.IndexOf(column);
        int colCount = dt.Columns.Count;

        for (i = 3; i < colCount; i++)
            {
                html.Append("<div class='col col-" + column.Ordinal + "' data-label='" + column.ColumnName + "'>");
                html.Append(row[column.ColumnName]);
                html.Append("</div>");
            }
    }
</code>```

答:
This answer including how to do what you want with Linq extension methods. </p>

```<code>foreach (DataColumn column in dt.Columns.Cast<DataColumn>().Skip(3))
{
    html.Append("<div class='col col-" + column.Ordinal + "' data-label='" + column.ColumnName + "'>");
    html.Append(row[column.ColumnName]);
    html.Append("</div>");
}
</code>```

Body:
I am trying to display several data, but I cannot select the column that I want. My code will produce all of the column data values. I have 9 columns in data table (zero-based), and I just want to get the data from column 3 till column 9. Grateful for any kind of insight!

foreach (DataColumn column in dt.Columns)
    {
        int i = dt.Columns.IndexOf(column);
        int colCount = dt.Columns.Count;

        for (i = 3; i < colCount; i++)
            {
                html.Append("
");
                html.Append(row[column.ColumnName]);
                html.Append("
");
            }
    }

Body:
This answer including how to do what you want with Linq extension methods.

foreach (DataColumn column in dt.Columns.Cast<DataColumn>().Skip(3))
{
    html.Append("<div class='col col-" + column.Ordinal + "' data-label='" + column.ColumnName + "'>");
    html.Append(row[column.ColumnName]);
    html.Append("</div>");
}


问:
Flutter how to draw multiples marker
first of all I am beginer with flutter and i have data on firestore (2 address), I´d like to draw it wiht marker on my google map app, when i run my code just it can draw one address, i read and view some tutorials but i don't know, what's wrong?
this is my code (i know, my english is terrible)

```<code>class MapaPage extends StatefulWidget {
  @override
  _MapaPageState createState() => _MapaPageState();
}

class _MapaPageState extends State<MapaPage> {
  GoogleMapController mapController;
  bool mapToggle = false;
  Position _currentPosition;
  Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
  Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
  var direcciones = [];

  void _getCurrentLocation() async {
    await geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high).then((position) {
      setState(() {
        _currentPosition = position;
        mapToggle = true;
      });
    }).catchError((e) {
      print(e);
    });
  }

  void _getDirecciones() {
    Firestore.instance.collection('direcciones').getDocuments().then((doc) {
      if(doc.documents.isNotEmpty) {
        for(int i = 0; i < doc.documents.length; i++) {
          direcciones.add(doc.documents[i].data);
          _initMarker(doc.documents[i].data);
        }
      }
    });
  }
</code>```

I think the problem is on function _initMarker.

```<code>  void _initMarker(Map<String, dynamic> direccion) {
    final MarkerId markerId = MarkerId(direccion['codigo_cliente']);
    final Marker marker = Marker(
      markerId: markerId,
      position: LatLng(direccion['latitud'], direccion['longitud']),
      infoWindow: InfoWindow(
        title: direccion['codigo_cliente'],
        snippet: direccion['direccion'],
      ),
    );
    setState(() {
      markers[markerId] = marker;
    });
  }

  @override
  void initState() {
    super.initState();
    _getDirecciones();
    _getCurrentLocation();
  }

  @override
  Widget build(BuildContext context) {
   return Scaffold(
      appBar: AppBar(
        title: Text('${mapToggle}'),
      ),
      body: Stack(
        children: <Widget>[
          mapToggle ?
          GoogleMap(
            mapType: MapType.normal,
            initialCameraPosition: CameraPosition(
                target: LatLng(_currentPosition.latitude, _currentPosition.longitude),               zoom: 10.0
            ),
            onMapCreated: onMapController,
            compassEnabled: true,
            markers: Set<Marker>.of(markers.values),
          ):
          LoadingUtil()
        ],
      ),
    );
  }

  void onMapController(GoogleMapController controller) {
    setState(() {
      mapController = controller;
    });
  }
}
</code>```

答:
try use Set<Marker> markers = {} instead of Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

and after that try this initMarker method

```<code>void _initMarker(Map<String, dynamic> direccion) {
    marker.add(
        Marker(
          markerId: MarkerId(UniqueKey().toString()),
          position: LatLng(direccion['latitud'], direccion['longitud']),
          infoWindow: InfoWindow(
              title: direccion['codigo_cliente'],
              snippet: direccion['direccion'],
          ),
        )
    );
}
</code>```

and set marker in GoogleMap widget like this

```<code>GoogleMap(
   mapType: MapType.normal,
   initialCameraPosition: CameraPosition(
   target: LatLng(_currentPosition.latitude, _currentPosition.longitude),               zoom: 10.0
   ),
   onMapCreated: onMapController,
   compassEnabled: true,
   markers: markers,
)
</code>```

Title: Flutter how to draw multiples marker

Body:
first of all I am beginer with flutter and i have data on firestore (2 address), I´d like to draw it wiht marker on my google map app, when i run my code just it can draw one address, i read and view some tutorials but i don't know, what's wrong?
this is my code (i know, my english is terrible)

class MapaPage extends StatefulWidget {
  @override
  _MapaPageState createState() => _MapaPageState();
}

class _MapaPageState extends State<MapaPage> {
  GoogleMapController mapController;
  bool mapToggle = false;
  Position _currentPosition;
  Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
  Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
  var direcciones = [];

  void _getCurrentLocation() async {
    await geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high).then((position) {
      setState(() {
        _currentPosition = position;
        mapToggle = true;
      });
    }).catchError((e) {
      print(e);
    });
  }

  void _getDirecciones() {
    Firestore.instance.collection('direcciones').getDocuments().then((doc) {
      if(doc.documents.isNotEmpty) {
        for(int i = 0; i < doc.documents.length; i++) {
          direcciones.add(doc.documents[i].data);
          _initMarker(doc.documents[i].data);
        }
      }
    });
  }

I think the problem is on function _initMarker.

  void _initMarker(Map<String, dynamic> direccion) {
    final MarkerId markerId = MarkerId(direccion['codigo_cliente']);
    final Marker marker = Marker(
      markerId: markerId,
      position: LatLng(direccion['latitud'], direccion['longitud']),
      infoWindow: InfoWindow(
        title: direccion['codigo_cliente'],
        snippet: direccion['direccion'],
      ),
    );
    setState(() {
      markers[markerId] = marker;
    });
  }

  @override
  void initState() {
    super.initState();
    _getDirecciones();
    _getCurrentLocation();
  }

  @override
  Widget build(BuildContext context) {
   return Scaffold(
      appBar: AppBar(
        title: Text('${mapToggle}'),
      ),
      body: Stack(
        children: <Widget>[
          mapToggle ?
          GoogleMap(
            mapType: MapType.normal,
            initialCameraPosition: CameraPosition(
                target: LatLng(_currentPosition.latitude, _currentPosition.longitude),               zoom: 10.0
            ),
            onMapCreated: onMapController,
            compassEnabled: true,
            markers: Set<Marker>.of(markers.values),
          ):
          LoadingUtil()
        ],
      ),
    );
  }

  void onMapController(GoogleMapController controller) {
    setState(() {
      mapController = controller;
    });
  }
}

Body:
try use Set<Marker> markers = {} instead of Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

and after that try this initMarker method

void _initMarker(Map<String, dynamic> direccion) {
    marker.add(
        Marker(
          markerId: MarkerId(UniqueKey().toString()),
          position: LatLng(direccion['latitud'], direccion['longitud']),
          infoWindow: InfoWindow(
              title: direccion['codigo_cliente'],
              snippet: direccion['direccion'],
          ),
        )
    );
}

and set marker in GoogleMap widget like this

GoogleMap(
   mapType: MapType.normal,
   initialCameraPosition: CameraPosition(
   target: LatLng(_currentPosition.latitude, _currentPosition.longitude),               zoom: 10.0
   ),
   onMapCreated: onMapController,
   compassEnabled: true,
   markers: markers,
)


问:
SQL select students logins
I have a table STUDENT_LAST_LOGIN, which contains data about students last logins.

```<code>ID  STUDENT_ID   DATE               TIME
1    A          2020-02-01 12:00    15 MIN
2    B          2020-02-02 12:00    45 MIN
3    C          2020-02-03 12:00    25 MIN
</code>```

In addition there is STUDENT_LOGIN table, which contains data about students all logins.

```<code>ID  STUDENT_ID   DATE               TIME
1    A          2020-02-01 12:00    15 MIN
4    A          2020-01-01 14:00    33 MIN
2    B          2020-02-02 12:00    45 MIN
5    B          2020-01-02 13:30    47 MIN
10   B          2020-01-03 13:30    27 MIN
6    B          2020-01-02 10:00    44 MIN
3    C          2020-02-03 12:00    25 MIN
7    C          2020-01-03 10:00    12 MIN
8    C          2020-01-03 18:00    56 MIN
9    C          2020-01-04 12:00    88 MIN
</code>```

As a result I need to get something like this:

```<code>STUDENT_ID    LAST_LOGIN         LAST_LOGIN_ONE_MONTH_AGO    TIME     TIME_ONE_MONTH_AGO
A            2020-02-01 12:00    2020-01-01 14:00            15 min   33 min
B            2020-02-02 12:00    2020-01-02 13:30            15 min   47 min
C            2020-02-03 12:00    2020-01-03 18:00            25 min   56 min
</code>```

Can you help me write this?

答:
```<code>SELECT LAST_LOGIN, LAST_LOGIN_ONE_MONTH_AGO, S_L.TIME, S_L.TIME_ONE_MONTH_AGO
FROM STUDENT_LAST_LOGIN S_L_L
INNER JOIN STUDENT_LOGIN S_L on S_L_L.id = S_L.id
where S_L_L.date <  DATEADD(month, -1, GETDATE())
</code>```

you need to write your query something like this.

Title: SQL select students logins

Body:
I have a table STUDENT_LAST_LOGIN, which contains data about students last logins.

ID  STUDENT_ID   DATE               TIME
1    A          2020-02-01 12:00    15 MIN
2    B          2020-02-02 12:00    45 MIN
3    C          2020-02-03 12:00    25 MIN

In addition there is STUDENT_LOGIN table, which contains data about students all logins.

ID  STUDENT_ID   DATE               TIME
1    A          2020-02-01 12:00    15 MIN
4    A          2020-01-01 14:00    33 MIN
2    B          2020-02-02 12:00    45 MIN
5    B          2020-01-02 13:30    47 MIN
10   B          2020-01-03 13:30    27 MIN
6    B          2020-01-02 10:00    44 MIN
3    C          2020-02-03 12:00    25 MIN
7    C          2020-01-03 10:00    12 MIN
8    C          2020-01-03 18:00    56 MIN
9    C          2020-01-04 12:00    88 MIN

As a result I need to get something like this:

STUDENT_ID    LAST_LOGIN         LAST_LOGIN_ONE_MONTH_AGO    TIME     TIME_ONE_MONTH_AGO
A            2020-02-01 12:00    2020-01-01 14:00            15 min   33 min
B            2020-02-02 12:00    2020-01-02 13:30            15 min   47 min
C            2020-02-03 12:00    2020-01-03 18:00            25 min   56 min

Can you help me write this?

Body:
SELECT LAST_LOGIN, LAST_LOGIN_ONE_MONTH_AGO, S_L.TIME, S_L.TIME_ONE_MONTH_AGO
FROM STUDENT_LAST_LOGIN S_L_L
INNER JOIN STUDENT_LOGIN S_L on S_L_L.id = S_L.id
where S_L_L.date <  DATEADD(month, -1, GETDATE())

you need to write your query something like this.


问:
Read a Text file having row in parenthesis and values separated by comma using pandas
I want to read a text file which contains data in parenthesis as row and values in it as column.The format of txt file is below :

```<code>(a, b, c, d) (a1, b1, (c1,c12,c13), d1) (a2, b2, (c2,c22,c23), d2) (a3, b3, (c3,c32,c33), d3) (a4, b4, (c4,c42,c43), d4)
</code>```

I want the data in this format :

```<code>a  b  c  d
a1 b1 c1 d1
a2 b2 c2 d2
a3 b3 c3 d3
a4 b4 c4 d4
</code>```

When i am reading text file as csv file it reads all the data in one row only. It shows 1 row and all the columns.
Please help me with this problem.

答:
```<code>data = """(a, b, c, d) (a1, b1, c1, d1) (a2, b2, c2, d2) (a3, b3, c3, d3) (a4, b4, c4, d4)
"""

#the sep argument says look for whitespace between ) and (
df = pd.read_csv(StringIO(data), header=None,sep='(?<=\))\s(?=\()',engine='python')

df = (df
      #transpose puts them into individual rows
      .T[0]
      #remove parentheses
      .str.strip("()")
      #now we can safely split and create a new dataframe
      .str.split(",",expand=True)
     )

#assign the first row as the columns
df.columns = df.iloc[0]
#assign the rest as the dataframe
df = df.iloc[1:]

df
    a   b   c   d
1   a1  b1  c1  d1
2   a2  b2  c2  d2
3   a3  b3  c3  d3
4   a4  b4  c4  d4
</code>```

Body:
I want to read a text file which contains data in parenthesis as row and values in it as column.The format of txt file is below :

(a, b, c, d) (a1, b1, (c1,c12,c13), d1) (a2, b2, (c2,c22,c23), d2) (a3, b3, (c3,c32,c33), d3) (a4, b4, (c4,c42,c43), d4)

I want the data in this format :

a  b  c  d
a1 b1 c1 d1
a2 b2 c2 d2
a3 b3 c3 d3
a4 b4 c4 d4

When i am reading text file as csv file it reads all the data in one row only. It shows 1 row and all the columns.
Please help me with this problem.


问:
Convert UTC? timezone to EST in Oracle on select
Our company's Oracle server is hosted in the east coast of the US and I believe follows a default timezone of EST.  I have a stored procedure which logs messages but puts the current timestamp into a field declared as timestamp.

```<code>describe log_messages;
Name      Null?    Type
--------- -------- --------------
ENTRY_ID  NOT NULL NUMBER
SEVERITY           VARCHAR2(1)
DATE_TIME          TIMESTAMP(6)
MESSAGE            VARCHAR2(2048)
</code>```

Usually, I do something like

```<code>insert into log_messages(severity,date_time,message)
values('I',current_timestamp,'some message');
</code>```

If I do select * from log_messages, the time stamps look like this:

```<code>28-MAY-20 01.50.15.747963000 AM
</code>```

However, the above time is actually 4 hours later than my current timezone.

```<code>select entry_id,severity,cast(date_time as timestamp with time zone) as date_time, date_time AT TIME ZONE 'EST' AS est,message
from log_messages
order by date_time desc;
</code>```

In the above, it thinks the timestamp in the timestamp field is in EST time, and then when it converts the other, it subtracts 4 hours from it.  Effectively, it is as though it writes the time in UTC, but then reads it in thinking it is EST, and subtracts 4 hours from it.  How can I get the real time in my local EST time?

答:
CURRENT_TIMESTAMP returns the current date and time in your session time zone, i.e. location or time zone settings of your Oracle Database server is not relevant.

You can interrogate your session time zone with select SESSIONTIMEZONE from dual; and change it with ALTER SESSION SET TIME_ZONE=...

However, as the data type is TIMESTAMP(6), the time zone information is lost as soon as the data is inserted.

When you run cast(date_time as timestamp with time zone) then Oracle takes your SESSIONTIMEZONE for conversion, actually Oracle runs  cast(FROM_TZ(date_time, SESSIONTIMEZONE) as timestamp with time zone)

Unless you don't alter your session time zone, the two queries should return the same value..

See also How to handle Day Light Saving in Oracle database

Body:
Our company's Oracle server is hosted in the east coast of the US and I believe follows a default timezone of EST.  I have a stored procedure which logs messages but puts the current timestamp into a field declared as timestamp.

describe log_messages;
Name      Null?    Type
--------- -------- --------------
ENTRY_ID  NOT NULL NUMBER
SEVERITY           VARCHAR2(1)
DATE_TIME          TIMESTAMP(6)
MESSAGE            VARCHAR2(2048)

Usually, I do something like

insert into log_messages(severity,date_time,message)
values('I',current_timestamp,'some message');

If I do select * from log_messages, the time stamps look like this:

28-MAY-20 01.50.15.747963000 AM

However, the above time is actually 4 hours later than my current timezone.

select entry_id,severity,cast(date_time as timestamp with time zone) as date_time, date_time AT TIME ZONE 'EST' AS est,message
from log_messages
order by date_time desc;

In the above, it thinks the timestamp in the timestamp field is in EST time, and then when it converts the other, it subtracts 4 hours from it.  Effectively, it is as though it writes the time in UTC, but then reads it in thinking it is EST, and subtracts 4 hours from it.  How can I get the real time in my local EST time?


问:
What are the benefits of using the real image height and width?
What are the benefits to using an images real height and width when rendering HTML?  That is if I have an image that 100x100 pixels but I want to display something that is 95x95 pixels, should I resize the image on the server or can I let the browser handle this?  I'm really looking for a general rule along with the reason.  Thanks.</p>

```<code><img src="image.jpg" style="width: 95px; height: 95px;" alt="an image" />
</code>```

答:
You should resize the images on the server when it makes sense. I doubt if resizing a 100x100px image to 95x95px will save you more than a couple of KBs so you're probably OK in this case.

If the difference (dimension-wise) is significant e.g. on master page you show a 100x100px thumbnails and on the detail page you have 640x480px image then you better create two versions of the image. This will make your thumbnails page load faster and you'll only serve the minimum amount of data.

On the other hand if the difference (dimension-wise) is not significant then serving two images will actually double the amount of data transferred.

Here is what Google's PageSpeed have to say about it: Serve scaled images


问:
Inserting non matching tuples
I have a table with the following columns: id, store, category_id and option_id. The contents of this table are updated via web-hook from an original on a different server. Once the contents are received I will need to check to see what rows need to be deleted and which need to be inserted.

For simplicity let's assume the category and option id tuples I received from the web-hook are (1,1) and (1,2), and that the database already contains (1,1) and (1,3). So (1,3) will need to be deleted and (1,2) will need to be inserted.

I can do deletion fine like this:

DELETE FROM store_category_options
 WHERE store=1 AND (category_id, option_id) NOT IN ((1,1), (1,2));
```

<p>Inserting, however, requires two queries, one to retrieve the values already in the database</p>

<pre class="lang-sql prettyprint-override"><code>SELECT category_id, option_id FROM store_category_options WHERE store=1
</code>```

and then after the difference has been calculated outside of MYSQL another to insert them back:

INSERT INTO store_category_option (category_id, option_id) VALUES (1,2)
```

I was wondering if there was a way to do the inserts with one query instead of two.

答:
I figured it out myself in the end. We can start with turning the webhook data into a derived table to select from with WHERE NOT IN

SELECT 1 as store_category_id, 1 as store_option_id UNION SELECT 1, 2;
```
<p>In the Mysql CLI this produces the output:</p>
```+-------------------+-----------------+
| store_category_id | store_option_id |
+-------------------+-----------------+
|                 1 |               1 |
|                 1 |               2 |
+-------------------+-----------------+
2 rows in set (0.00 sec)
```
<p>To query this table with a where clause it is necessary to include it in a subquery of another select and give the table an alias:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT store_category_id, store_option_id FROM (
  SELECT 1 as store_category_id, 1 as store_option_id
  UNION SELECT 1, 2
) AS vt WHERE store_option_id = 1;
</code>```

This produces the output:

```<code>+-------------------+-----------------+
| store_category_id | store_option_id |
+-------------------+-----------------+
|                 1 |               1 |
+-------------------+-----------------+
1 row in set (0.00 sec)
</code>```

Now we can use a wherein clause combined with another sub query to select the rows to be inserted:

SELECT store_category_id, store_option_id FROM (
  SELECT 1 as store_category_id, 1 as store_option_id
  UNION SELECT 1, 2
) AS vt WHERE (category_id, option_id) NOT IN (
  SELECT store_category_id, store_option_id
  FROM store_category_options
);
```
<p>The result is:</p>
```+-------------------+-----------------+
| store_category_id | store_option_id |
+-------------------+-----------------+
|                 1 |               2 |
+-------------------+-----------------+
1 row in set (0.00 sec)
```
<p>Finally to insert the rows we have calculated we include the previous select statement inside a INSERT INTO SELECT statement</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO store_category_options
(store_category_id, store_option_id)
SELECT store_category_id, store_option_id FROM (
    SELECT 1 as store_category_id, 1 as store_option_id
    UNION SELECT 1, 2
) AS vt WHERE (store_category_id, store_option_id) NOT IN (
    SELECT store_category_id, store_option_id
    FROM store_category_options
);
</code>```

Title: Inserting non matching tuples

Body:
I have a table with the following columns: id, store, category_id and option_id. The contents of this table are updated via web-hook from an original on a different server. Once the contents are received I will need to check to see what rows need to be deleted and which need to be inserted.

For simplicity let's assume the category and option id tuples I received from the web-hook are (1,1) and (1,2), and that the database already contains (1,1) and (1,3). So (1,3) will need to be deleted and (1,2) will need to be inserted.

I can do deletion fine like this:

DELETE FROM store_category_options
 WHERE store=1 AND (category_id, option_id) NOT IN ((1,1), (1,2));

Inserting, however, requires two queries, one to retrieve the values already in the database

SELECT category_id, option_id FROM store_category_options WHERE store=1

and then after the difference has been calculated outside of MYSQL another to insert them back:

INSERT INTO store_category_option (category_id, option_id) VALUES (1,2)

I was wondering if there was a way to do the inserts with one query instead of two.

Body:
I figured it out myself in the end. We can start with turning the webhook data into a derived table to select from with WHERE NOT IN

SELECT 1 as store_category_id, 1 as store_option_id UNION SELECT 1, 2;

In the Mysql CLI this produces the output:

+-------------------+-----------------+
| store_category_id | store_option_id |
+-------------------+-----------------+
|                 1 |               1 |
|                 1 |               2 |
+-------------------+-----------------+
2 rows in set (0.00 sec)

To query this table with a where clause it is necessary to include it in a subquery of another select and give the table an alias:

SELECT store_category_id, store_option_id FROM (
  SELECT 1 as store_category_id, 1 as store_option_id
  UNION SELECT 1, 2
) AS vt WHERE store_option_id = 1;

This produces the output:

+-------------------+-----------------+
| store_category_id | store_option_id |
+-------------------+-----------------+
|                 1 |               1 |
+-------------------+-----------------+
1 row in set (0.00 sec)

Now we can use a wherein clause combined with another sub query to select the rows to be inserted:

SELECT store_category_id, store_option_id FROM (
  SELECT 1 as store_category_id, 1 as store_option_id
  UNION SELECT 1, 2
) AS vt WHERE (category_id, option_id) NOT IN (
  SELECT store_category_id, store_option_id
  FROM store_category_options
);

The result is:

+-------------------+-----------------+
| store_category_id | store_option_id |
+-------------------+-----------------+
|                 1 |               2 |
+-------------------+-----------------+
1 row in set (0.00 sec)

Finally to insert the rows we have calculated we include the previous select statement inside a INSERT INTO SELECT statement

INSERT INTO store_category_options
(store_category_id, store_option_id)
SELECT store_category_id, store_option_id FROM (
    SELECT 1 as store_category_id, 1 as store_option_id
    UNION SELECT 1, 2
) AS vt WHERE (store_category_id, store_option_id) NOT IN (
    SELECT store_category_id, store_option_id
    FROM store_category_options
);


问:
Get only unique data from array of objects in JavaScript
So I have the following structure:

```<code>[{
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Monday",
    "periods": [{
        "openDay": "Monday",
        "openTime": "12:00",
        "closeDay": "Monday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Monday",
        "openTime": "19:00",
        "closeDay": "Monday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Monday",
        "openTime": "23:00",
        "closeDay": "Monday",
        "closeTime": "23:30"
      }
    ]
  },
  {
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Tuesday",
    "periods": [{
        "openDay": "Tuesday",
        "openTime": "12:00",
        "closeDay": "Tuesday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Tuesday",
        "openTime": "19:00",
        "closeDay": "Tuesday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Tuesday",
        "openTime": "23:00",
        "closeDay": "Tuesday",
        "closeTime": "23:30"
      }
    ]
  }
]
</code>```

What I want to do, is if all periods for a given day are the same as any other day(matching by their openTime and closeTime) in the array to merge them (or just delete the second occurrence). If the periods are of a different length no action will occur. Also if just one of the openTime or closeTime is different, again no action will occur.
So far I have tried looping through all days and comparing one with the following after it. Got stuck in comparing the periods. Tried following the explanation here - https://gomakethings.com/check-if-two-arrays-or-objects-are-equal-with-javascript/, but again got lost.
The desired output will be:

```<code>[{
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Monday, Tuesday",
    "periods": [{
        "openDay": "Monday",
        "openTime": "12:00",
        "closeDay": "Monday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Monday",
        "openTime": "19:00",
        "closeDay": "Monday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Monday",
        "openTime": "23:00",
        "closeDay": "Monday",
        "closeTime": "23:30"
      }
    ]
  },
</code>```

As I don't care about changing the openDay/closeDay in the periods. I want to do this check for all days in the array.

答:
You just need a function that will compare the two objects
Also, as you want an array with no duplicates, its probably a good idea to test for duplicates before adding to the array.

```<code>function CompareSchedule(s1, s2) {
  return s1.openTime == s2.openTime && s1.closeTime == s2.closeTime;
}

function AddToArray(s) {
  for (var i = 0; i < schedules.length; i++) {
    if (CompareSchedule(s, schedules[i]))
      return false;
  }
  schedules.push(s);
  return true;
}
</code>```

You can then change your Compare method if you need additional checks etc.

Body:
So I have the following structure:

[{
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Monday",
    "periods": [{
        "openDay": "Monday",
        "openTime": "12:00",
        "closeDay": "Monday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Monday",
        "openTime": "19:00",
        "closeDay": "Monday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Monday",
        "openTime": "23:00",
        "closeDay": "Monday",
        "closeTime": "23:30"
      }
    ]
  },
  {
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Tuesday",
    "periods": [{
        "openDay": "Tuesday",
        "openTime": "12:00",
        "closeDay": "Tuesday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Tuesday",
        "openTime": "19:00",
        "closeDay": "Tuesday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Tuesday",
        "openTime": "23:00",
        "closeDay": "Tuesday",
        "closeTime": "23:30"
      }
    ]
  }
]

What I want to do, is if all periods for a given day are the same as any other day(matching by their openTime and closeTime) in the array to merge them (or just delete the second occurrence). If the periods are of a different length no action will occur. Also if just one of the openTime or closeTime is different, again no action will occur.
So far I have tried looping through all days and comparing one with the following after it. Got stuck in comparing the periods. Tried following the explanation here - https://gomakethings.com/check-if-two-arrays-or-objects-are-equal-with-javascript/, but again got lost.
The desired output will be:

[{
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Monday, Tuesday",
    "periods": [{
        "openDay": "Monday",
        "openTime": "12:00",
        "closeDay": "Monday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Monday",
        "openTime": "19:00",
        "closeDay": "Monday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Monday",
        "openTime": "23:00",
        "closeDay": "Monday",
        "closeTime": "23:30"
      }
    ]
  },

As I don't care about changing the openDay/closeDay in the periods. I want to do this check for all days in the array.

Body:
You just need a function that will compare the two objects
Also, as you want an array with no duplicates, its probably a good idea to test for duplicates before adding to the array.

function CompareSchedule(s1, s2) {
  return s1.openTime == s2.openTime && s1.closeTime == s2.closeTime;
}

function AddToArray(s) {
  for (var i = 0; i < schedules.length; i++) {
    if (CompareSchedule(s, schedules[i]))
      return false;
  }
  schedules.push(s);
  return true;
}

You can then change your Compare method if you need additional checks etc.


答:
I hope this will help you out solving your issue. This code will remove duplicate values from periods array from each object. I have copied some periods and tried duplicating the values. </p>

```<code>var data = [
    {
        "isOpen": 1,
        "weekday": 1,
        "humanDay": "Monday",
        "periods":
            [
                {
                    "openDay": "Monday",
                    "openTime": "12:00",
                    "closeDay": "Monday",
                    "closeTime": "14:30"
                },
                {
                    "openDay": "Monday",
                    "openTime": "19:00",
                    "closeDay": "Monday",
                    "closeTime": "22:30"
                }, {
                    "openDay": "Monday",
                    "openTime": "19:00",
                    "closeDay": "Monday",
                    "closeTime": "22:30"
                },
                {
                    "openDay": "Monday",
                    "openTime": "23:00",
                    "closeDay": "Monday",
                    "closeTime": "23:30"
                }
            ]
    },
    {
        "isOpen": 1,
        "weekday": 1,
        "humanDay": "Tuesday",
        "periods":
            [
                {
                    "openDay": "Tuesday",
                    "openTime": "12:00",
                    "closeDay": "Tuesday",
                    "closeTime": "14:30"
                },
                {
                    "openDay": "Tuesday",
                    "openTime": "19:00",
                    "closeDay": "Tuesday",
                    "closeTime": "22:30"
                },
                {
                    "openDay": "Tuesday",
                    "openTime": "19:00",
                    "closeDay": "Tuesday",
                    "closeTime": "22:30"
                },
                {
                    "openDay": "Tuesday",
                    "openTime": "19:00",
                    "closeDay": "Tuesday",
                    "closeTime": "22:30"
                },
                {
                    "openDay": "Tuesday",
                    "openTime": "23:00",
                    "closeDay": "Tuesday",
                    "closeTime": "23:30"
                }
            ]
    }
]

for (const dt of data) {
    let pr = [];
    for (const period of dt.periods) {
        let prIndex = pr.findIndex(p => (p.openTime == period.openTime && p.closeTime == period.closeTime));
        if (prIndex == -1) {
            pr.push({
                "openDay": period.openDay,
                "openTime": period.openTime,
                "closeDay": period.closeDay,
                "closeTime": period.closeTime
            });
        }
    }

    dt.periods = pr;
}
console.log(data);
</code>```

Title: Get only unique data from array of objects in JavaScript

Body:
I hope this will help you out solving your issue. This code will remove duplicate values from periods array from each object. I have copied some periods and tried duplicating the values.

var data = [
    {
        "isOpen": 1,
        "weekday": 1,
        "humanDay": "Monday",
        "periods":
            [
                {
                    "openDay": "Monday",
                    "openTime": "12:00",
                    "closeDay": "Monday",
                    "closeTime": "14:30"
                },
                {
                    "openDay": "Monday",
                    "openTime": "19:00",
                    "closeDay": "Monday",
                    "closeTime": "22:30"
                }, {
                    "openDay": "Monday",
                    "openTime": "19:00",
                    "closeDay": "Monday",
                    "closeTime": "22:30"
                },
                {
                    "openDay": "Monday",
                    "openTime": "23:00",
                    "closeDay": "Monday",
                    "closeTime": "23:30"
                }
            ]
    },
    {
        "isOpen": 1,
        "weekday": 1,
        "humanDay": "Tuesday",
        "periods":
            [
                {
                    "openDay": "Tuesday",
                    "openTime": "12:00",
                    "closeDay": "Tuesday",
                    "closeTime": "14:30"
                },
                {
                    "openDay": "Tuesday",
                    "openTime": "19:00",
                    "closeDay": "Tuesday",
                    "closeTime": "22:30"
                },
                {
                    "openDay": "Tuesday",
                    "openTime": "19:00",
                    "closeDay": "Tuesday",
                    "closeTime": "22:30"
                },
                {
                    "openDay": "Tuesday",
                    "openTime": "19:00",
                    "closeDay": "Tuesday",
                    "closeTime": "22:30"
                },
                {
                    "openDay": "Tuesday",
                    "openTime": "23:00",
                    "closeDay": "Tuesday",
                    "closeTime": "23:30"
                }
            ]
    }
]

for (const dt of data) {
    let pr = [];
    for (const period of dt.periods) {
        let prIndex = pr.findIndex(p => (p.openTime == period.openTime && p.closeTime == period.closeTime));
        if (prIndex == -1) {
            pr.push({
                "openDay": period.openDay,
                "openTime": period.openTime,
                "closeDay": period.closeDay,
                "closeTime": period.closeTime
            });
        }
    }

    dt.periods = pr;
}
console.log(data);


问:
AWS Ruby SDK , check a key exists always gives 'false'
In AWS S3, I have a bucket named my-bucket, I am using AWS Ruby SDK to access my bucket.

under my-bucket I have the following directory structure in S3 (I know it is not called "directory" in S3, but just to show the idea):

```<code>my-bucket/
    customers/
         products/
              - data1.txt
              - data2.txt
              ...
</code>```

I want to check does my-bucket/customers/products exist with AWS Ruby SDK, I tried the following code:

```<code>s3 = Aws::S3::Resource.new
bucket = s3.bucket("my-bucket")
result = bucket.object("customers/products").exists?
</code>```

But the result gives false, even though I do have that directory in S3, where am I wrong?

答:
In Ruby sdk V2 the method with_prefix is not defined:

given an object with key like: dir1/dir2/object.jpg

try something like the following

```<code>bucket.objects(prefix: 'dir1/dir2').any?
</code>```

or directly check for object existence

```<code>bucket.object('dir1/dir2/object.jpg').exists?
</code>```

Body:
In AWS S3, I have a bucket named my-bucket, I am using AWS Ruby SDK to access my bucket.

under my-bucket I have the following directory structure in S3 (I know it is not called "directory" in S3, but just to show the idea):

my-bucket/
    customers/
         products/
              - data1.txt
              - data2.txt
              ...

I want to check does my-bucket/customers/products exist with AWS Ruby SDK, I tried the following code:

s3 = Aws::S3::Resource.new
bucket = s3.bucket("my-bucket")
result = bucket.object("customers/products").exists?

But the result gives false, even though I do have that directory in S3, where am I wrong?

Body:
In Ruby sdk V2 the method with_prefix is not defined:

given an object with key like: dir1/dir2/object.jpg

try something like the following

bucket.objects(prefix: 'dir1/dir2').any?

or directly check for object existence

bucket.object('dir1/dir2/object.jpg').exists?


问:
Add title to a div in code behind is not appeared
I'm using Dialog popup from JQuery UI. I want to add a title to the popup and I found that only the title of the div should be filled.

When I write a constant value in the markup then the title is appeared, but when it's added in the code behind it is not appeared.

```<code>myDiv.Attributes["title"] = "some value";
</code>```

-

```<code><div id="myDiv" class="UsersDialogClass"
                       runat="server" style="display: none">
</code>```

Any idea!

答:
I have created a sample here,
you can override your title attribute when you load the dialog.

http://jsfiddle.net/jansian/HAq7w/1/

Body:
I'm using Dialog popup from JQuery UI. I want to add a title to the popup and I found that only the title of the div should be filled.

When I write a constant value in the markup then the title is appeared, but when it's added in the code behind it is not appeared.

myDiv.Attributes["title"] = "some value";

-

Any idea!


问:
Loop every row of subquery / Subquery returned more than 1 value
I have database like this:

I want to get Employee_conferenceDay for every Employee who exists in Conference with ID_conference = 206247. I did this:

```<code>SELECT Employee_conferenceDay From Employee Where ID_Employee = (Select ID_Employee From Conference Where ID_conference = 206247);
</code>```

And I got this message:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression.

How I can do it this way to do sth with every row in subquery table?

答:
The reason you are getting that error because there are more than one employee in the conference table for ID_conference = 206247. Where = is to use to compare one value and when you have more than one value then you can use one of the following option.

first option is to use EXISTS

```<code>SELECT
    Employee_conferenceDay
From Employee e
Where EXISTS (
    select
        ID_Employee
    From Conference c
    Where e.ID_Employee = c.ID_Employee
    and ID_conference = 206247
);
</code>```

second option is to use IN

```<code>SELECT
    Employee_conferenceDay
From Employee
Where ID_Employee IN (
    Select
        ID_Employee
    From Conference
    Where ID_conference = 206247
);
</code>```

Body:
I have database like this:

I want to get Employee_conferenceDay for every Employee who exists in Conference with ID_conference = 206247. I did this:

SELECT Employee_conferenceDay From Employee Where ID_Employee = (Select ID_Employee From Conference Where ID_conference = 206247);

And I got this message:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression.

How I can do it this way to do sth with every row in subquery table?

Body:
The reason you are getting that error because there are more than one employee in the conference table for ID_conference = 206247. Where = is to use to compare one value and when you have more than one value then you can use one of the following option.

first option is to use EXISTS

SELECT
    Employee_conferenceDay
From Employee e
Where EXISTS (
    select
        ID_Employee
    From Conference c
    Where e.ID_Employee = c.ID_Employee
    and ID_conference = 206247
);

second option is to use IN

SELECT
    Employee_conferenceDay
From Employee
Where ID_Employee IN (
    Select
        ID_Employee
    From Conference
    Where ID_conference = 206247
);


问:
Extraction of sub string from the text using R
I have a string data as follows:

```<code>a<-  "\n    Update Your Profile to Dissolve This Message\nSocial Media Learning and behaviour\n        Uploaded on May 3, 2020 at 10:56 in Research\n            View Forum\n        \n"
</code>```

I have to extract the string "Social Media Learning and behaviour" for this I used the below code:

```<code>gsub("        Uploaded on .* ", "", gsub("\n    Update Your Profile to Dissolve This Message\n", "",a))
</code>```

This gives me output as below

```<code>"Social Media Learning and behaviour\n\n"
</code>```

I am not able to match the exact pattern. What can be the exact pattern to extract "Social Media Learning and behaviour" without "\n\n"

答:
You can extract part between "Update Your Profile to Dissolve This Message" and "Uploaded on"

```<code>sub(".*Update Your Profile to Dissolve This Message\n(.*)\n\\s+Uploaded on.*", "\\1", a)
#[1] "Social Media Learning and behaviour"
</code>```

You can also use str_match from stringr

```<code>stringr::str_match(a, "Update Your Profile to Dissolve This Message\n(.*)\n\\s+Uploaded on")[, 2]
</code>```

Body:
I have a string data as follows:

a<-  "\n    Update Your Profile to Dissolve This Message\nSocial Media Learning and behaviour\n        Uploaded on May 3, 2020 at 10:56 in Research\n            View Forum\n        \n"

I have to extract the string "Social Media Learning and behaviour" for this I used the below code:

gsub("        Uploaded on .* ", "", gsub("\n    Update Your Profile to Dissolve This Message\n", "",a))

This gives me output as below

"Social Media Learning and behaviour\n\n"

I am not able to match the exact pattern. What can be the exact pattern to extract "Social Media Learning and behaviour" without "\n\n"

Body:
You can extract part between "Update Your Profile to Dissolve This Message" and "Uploaded on"

sub(".*Update Your Profile to Dissolve This Message\n(.*)\n\\s+Uploaded on.*", "\\1", a)
#[1] "Social Media Learning and behaviour"

You can also use str_match from stringr

stringr::str_match(a, "Update Your Profile to Dissolve This Message\n(.*)\n\\s+Uploaded on")[, 2]


问:
Separate accounts for Pypi and TestPypi
I'm having troubles uploading my package from testpypi to PyPi

Here's the error:

```<code>HTTPError: 403 Client Error: The user 'DeepAb' isn't allowed to upload to project 'deco'. See
https://pypi.org/help/#project-name for more information. for url: https://upload.pypi.org/legacy/
</code>```

I have separate accounts for each testPypi and PyPi and the credentials were given correctly.

Do I need to make separate accounts in PyPi and TestPyPi for uploading the same package in both?

答:
1.

I'm having troubles uploading my package from testpypi to PyPi

The user 'DeepAb' isn't allowed to upload to project 'deco'.

Seems like there is already a project with that name (deco) registered on PyPI:

https://pypi.org/project/deco/

Also read the link from the error message you posted:

https://pypi.org/help/#project-name

2.

Do I need to make seperate accounts in PyPi and TestPyPi for uploading same package in both?

Yes.

Because TestPyPI has a separate database from the live PyPI, you’ll need a separate user account for specifically for TestPyPI

https://packaging.python.org/guides/using-testpypi/

Register an account on https://pypi.org - note that these are two separate servers and the login details from the test server are not shared with the main server.

https://packaging.python.org/tutorials/packaging-projects/#next-steps

In both cases, remember that PyPI and TestPyPI each require you to create an account, so your credentials may be different.

https://pypi.org/help/#invalid-auth

Title: Separate accounts for Pypi and TestPypi

Body:
I'm having troubles uploading my package from testpypi to PyPi

Here's the error:

HTTPError: 403 Client Error: The user 'DeepAb' isn't allowed to upload to project 'deco'. See
https://pypi.org/help/#project-name for more information. for url: https://upload.pypi.org/legacy/

I have separate accounts for each testPypi and PyPi and the credentials were given correctly.

Do I need to make separate accounts in PyPi and TestPyPi for uploading the same package in both?