问:
Javascript vs Python indentation
I want to make a function work like an on off switch in python. I know how to do it in Javascript, but I don't understand how indenting works with Python, can someone help point me in the right direction? </p>

```<code><p id="demo">test</p>
<button onClick="myFunction()">change</button>

<script>
var onoff = 1;

function myFunction() {
    if(onoff == 1){
        document.getElementById("demo").innerHTML = "one";
        onoff = 2;
    }
    else if(onoff == 2){
        document.getElementById("demo").innerHTML = "two";
        onoff = 1;
    }
}
</script>
</code>```

```<code>onoff = 1

def test():
  if onoff == 1:
    print("on")
    onoff = 2
  elif onoff == 2:
    print("off")
    onoff = 1

test()
test()
test()
test()
</code>```

答:
This is about scope as @jonrsharpe commented.

Did you run and notice the error below?

UnboundLocalError: local variable 'onoff' referenced before assignment

There are many solutions. Here is an example.

```<code>onoff = 1

def test():
  global onoff
  if onoff == 1:
    print("on")
    onoff = 2
  elif onoff == 2:
    print("off")
    onoff = 1

test()
test()
test()
test()
</code>```

see:

python - UnboundLocalError on local variable when reassigned after first use - Stack Overflow

UnboundLocalError: local variable referenced before assignment in
Python.

function - Python 3: UnboundLocalError: local variable referenced
before assignment - Stack
Overflow

Title: Javascript vs Python indentation

Body:
I want to make a function work like an on off switch in python. I know how to do it in Javascript, but I don't understand how indenting works with Python, can someone help point me in the right direction?

test

<button onClick="myFunction()">change</button>

onoff = 1

def test():
  if onoff == 1:
    print("on")
    onoff = 2
  elif onoff == 2:
    print("off")
    onoff = 1

test()
test()
test()
test()

Body:
This is about scope as @jonrsharpe commented.

Did you run and notice the error below?

UnboundLocalError: local variable 'onoff' referenced before assignment

There are many solutions. Here is an example.

onoff = 1

def test():
  global onoff
  if onoff == 1:
    print("on")
    onoff = 2
  elif onoff == 2:
    print("off")
    onoff = 1

test()
test()
test()
test()

see:

python - UnboundLocalError on local variable when reassigned after first use - Stack Overflow

UnboundLocalError: local variable referenced before assignment in
Python.

function - Python 3: UnboundLocalError: local variable referenced
before assignment - Stack
Overflow


来源: stackexchange

问:
Using flex of the screen inside a ScrollView
I have this code

```<code><View style={{flex: 1}}>
   <ScrollView contentContainerStyle={{height: 2000}}>
      <Text style={{flex: .5, backgroundColor: 'orange'}}>box1</Text>
      <Text style={{flex: .5, backgroundColor: 'orange'}}>box2</Text>
      <Text style={{flex: .5, backgroundColor: 'orange'}}>box3</Text>
   </ScrollView>
</View>
</code>```

With this, I was hoping for each <Text /> to occupy half of the screen (therefore, a combination of all the children to equal 1.5 of the screen height). Instead, each box is occupying a third of the 2000 pixel height. Is there anyway of getting my intended result using flex? Or must I calculate the height of the screen and then get the desired % for each <Text />?

答:
You can create another view inside the scrollView and fix its height to be 1.5 times the screen height and then give the text equal flex.

```<code>import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Dimensions,
} from 'react-native';

const App = (props) => {
  let screenHeight = Dimensions.get('window').height;

  let bodyHeight = screenHeight*1.5;

  return (
      <ScrollView style={styles.body}>
        <View style={[styles.innerBody, { height: bodyHeight }]}>
          <Text style={{flex: .5, backgroundColor: 'orange'}}>box1</Text>
          <Text style={{flex: .5, backgroundColor: 'blue'}}>box2</Text>
          <Text style={{flex: .5, backgroundColor: 'purple'}}>box3</Text>
        </View>
      </ScrollView>
  );
};

const styles = StyleSheet.create({
  body: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#fff',
  },
  innerBody: {
    borderColor: 'red',
    borderWidth: 5
  }
});

export default App;
</code>```

I've created a snack

ContentLicense: CC BY-SA 4.0

Body:
I have this code

<View style={{flex: 1}}>
   <ScrollView contentContainerStyle={{height: 2000}}>
      <Text style={{flex: .5, backgroundColor: 'orange'}}>box1</Text>
      <Text style={{flex: .5, backgroundColor: 'orange'}}>box2</Text>
      <Text style={{flex: .5, backgroundColor: 'orange'}}>box3</Text>
   </ScrollView>
</View>

With this, I was hoping for each <Text /> to occupy half of the screen (therefore, a combination of all the children to equal 1.5 of the screen height). Instead, each box is occupying a third of the 2000 pixel height. Is there anyway of getting my intended result using flex? Or must I calculate the height of the screen and then get the desired % for each <Text />?

Body:
You can create another view inside the scrollView and fix its height to be 1.5 times the screen height and then give the text equal flex.

import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Dimensions,
} from 'react-native';

const App = (props) => {
  let screenHeight = Dimensions.get('window').height;

  let bodyHeight = screenHeight*1.5;

  return (
      <ScrollView style={styles.body}>
        <View style={[styles.innerBody, { height: bodyHeight }]}>
          <Text style={{flex: .5, backgroundColor: 'orange'}}>box1</Text>
          <Text style={{flex: .5, backgroundColor: 'blue'}}>box2</Text>
          <Text style={{flex: .5, backgroundColor: 'purple'}}>box3</Text>
        </View>
      </ScrollView>
  );
};

const styles = StyleSheet.create({
  body: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#fff',
  },
  innerBody: {
    borderColor: 'red',
    borderWidth: 5
  }
});

export default App;

I've created a snack


问:
git deploying project - file permissions - (chmod)
I'm deploying my project with git to a remote server using a post-update hook. More specifically I'm following these steps. Everything on my local copy has the right permissions, however after deploying with git push production, files that are set to 777  change in the remote server to -rwxr-xr-x

I've added to both (local/remote) .git/config the core variables filemode = false and I've changed as well my umask in /etc/profile to 0002

Any ideas why it keeps changing the mode of files? Thanks

答: The core.filemode variable is only used when files are indexed. When git checks out files, the stored mode is used unconditionally, and files can only have a mode of 644 or 755. Modify your post-checkout hook to chmod the files.

ContentLicense: CC BY-SA 3.0


问:
how to use getparam from navigation properly in react native?
Im using react navigation v4
I used the navigation.navigate to send params in other page i built,
when I try to do the same in other page I get undefined value.

I want to pass that

```<code>let VolunteerDest = documentSnapshot.data().delegation;
console.log('testing user delegation: ', VolunteerDest)  // <~~~~~~~~~ its working ~~~~~~~~~~
this.props.navigation.navigate('Volunteer', {userDelegation: VolunteerDest});
</code>```

and on the other page I tried it in compDidMount / Constructor.. none of them working:

```<code> const id = this.props.navigation.getParam('userDelegation');
 console.log('testing user delegation:' , id);  // <~~~~~~~~~~~~~~  undefined
</code>```

can someone please tell me whats wrong with it?
I read the navigation doc and searched here and google but cant find my mistake.(like I said it worked on different page navigation but here I face that issue)

答:
there is no need to worry about it, you can also get the value in state like this</p>

```<code>this.state = {
        subCatName: this.props.navigation.state.params.userDelegation
    };
</code>```

Body:
Im using react navigation v4
I used the navigation.navigate to send params in other page i built,
when I try to do the same in other page I get undefined value.

I want to pass that

let VolunteerDest = documentSnapshot.data().delegation;
console.log('testing user delegation: ', VolunteerDest)  // <~~~~~~~~~ its working ~~~~~~~~~~
this.props.navigation.navigate('Volunteer', {userDelegation: VolunteerDest});

and on the other page I tried it in compDidMount / Constructor.. none of them working:

 const id = this.props.navigation.getParam('userDelegation');
 console.log('testing user delegation:' , id);  // <~~~~~~~~~~~~~~  undefined

can someone please tell me whats wrong with it?
I read the navigation doc and searched here and google but cant find my mistake.(like I said it worked on different page navigation but here I face that issue)

Body:
there is no need to worry about it, you can also get the value in state like this

this.state = {
        subCatName: this.props.navigation.state.params.userDelegation
    };


问:
Android Studio SDK is missing
I had a USB connection problem when I debug and updated BIOS then, the laptop had problem with drive so, I needed to recover it. So, I recovered it with removing all the applications and just kept my personal files.

And I downloaded and installed Android Studio again, and SDK missing problem occurred like below:

I can't see 'SDK' when I install Android Studio from here. So, I can't select any.

I tried with SDK Manager. I can't install any versions with "Your Android SDK is missing, out of date, or corupted." error.

I tried Update. But nothing changed. (Updated to 3.3.1, but failed to Sync SDKs ERROR.)

Some people on Stack-overflow suggested to download SDK separately, but their links just show Android Studio installer, which I already installed. Maybe the links were so old.

"C:\Users\XXX\AppData\Local\Android\Sdk" does not exists.

I uninstalled Android Studio include User setting and reinstalled it.(There is no such thing that I can select previous version kind of thing.) But the result is the same.

答:
TL;DR This is sometimes caused by Windows registry settings retained with the current AndroidStudio project. To fix, just startup Android Studio and then close the current project (File -> Close Project). If this was the problem, AS will now go into a long update and restart cycle to repair itself, but will end with success.

I also recommend that you then change AS settings to not open the last project on Startup (Settings -> System Settings -> Reopen projects on startup)

Windows 10, Android Studio v3.6 and v4.0.

This one drove me nuts! I had the same problem - my SDK seemed to be corrupt so I did a full Uninstall (v3.6) and Install (4.0) of Android Studio and when Android Studio started up I got the same message Android SDK is missing.

The SDK Manager in Tools wasn't working.

I went to the link and there was nothing to download the SDK. So I installed the file which looked a bit like the SDK, commandlinetools-win-6514223_latest.zip, unzipped, and then tried to use the missing SDK dialog to include it in AS, and no joy.

BUT - I noticed that after an uninstall and fresh install Android Studio still came up with the last project I was working on so I guessed it must be something in the windows registry (rather than AS settings). I closed that project and AS suddenly popped up a dialog to install the SDK!

After a big download and install, Android Studio returned with the SDK (and SDK manager) all functioning!

So - just startup Android Studio and then close the current project (File -> Close Project)!

How I did a complete re-install.

Uncheck the "Keep Settings" (or similar) option in the Uninstall dialog, but export your settings first (File -> Export Settings). I found it easy to: Export settings; Complete Uninstall; Download and Install; Import Settings;. But, or course, there were several massive downloads. Still don't know why the last open file came up after the fresh install. It's probably in the registry, so, if there are still problems then you'll have to clear AS from the registry as well. Which sounds painful.

Title: Android Studio SDK is missing


问:
Mocking Repositories to test Service in Spring
I occurred some failures after trying to mock repositories to unit test my services in Spring-Boot
Thats what I have (simplified)

@ExtendWith(SpringExtension.class)
@ExtendWith(MockitoExtension.class)
@SpringBootTest
@ActiveProfiles("test")
public class UserTest{

    @InjectMocks
    private UserServiceImpl userService;

    @Mock
    private UserRepostiory userRepository;

    @Before
    public void setUp() {
       User user = new User(1L, "email@email", "name");
        when(userRepostitory.findById(1L)).thenReturn(Optional.of(user));
    }

    @Test
    public void findUserByIdReturnsUser() {

        User user = userService.getById(1L); => always throws error in Service, that no User is found with that Id, it calls the regular Repository: mock does nothing
        assertEquals(1L,user.getId());

    }
}
```

But I never get the User returned when the service calls the repo. I am kinda new to Unit Testing, and I am pretty sure, that I miss something here.

答: Annotate the test class with @RunWith(SpringRunner.class)

Body:
I occurred some failures after trying to mock repositories to unit test my services in Spring-Boot
Thats what I have (simplified)

@ExtendWith(SpringExtension.class)
@ExtendWith(MockitoExtension.class)
@SpringBootTest
@ActiveProfiles("test")
public class UserTest{

    @InjectMocks
    private UserServiceImpl userService;

    @Mock
    private UserRepostiory userRepository;

    @Before
    public void setUp() {
       User user = new User(1L, "email@email", "name");
        when(userRepostitory.findById(1L)).thenReturn(Optional.of(user));
    }

    @Test
    public void findUserByIdReturnsUser() {

        User user = userService.getById(1L); => always throws error in Service, that no User is found with that Id, it calls the regular Repository: mock does nothing
        assertEquals(1L,user.getId());

    }
}

But I never get the User returned when the service calls the repo. I am kinda new to Unit Testing, and I am pretty sure, that I miss something here.


问:
How can I avoid using *ngIf in an Angular template?
I tried using async/await to avoid *ngIf in the component template.

I'm getting an error in the Chrome console when I remove *ngIf in component template.

Can anyone help to get a solution. I do not want to use *ngIf in the component template as a requirement

I'm calling the GET REST API and used subscribe. Also, I'm getting results without the error if I'm using *ngIf, but I want the same results without using *ngIf

CODE:
component.ts

```<code>export class DisplayComponent implements OnInit {
users : user[];
user: user;
userResult: any;

  constructor(private http: HttpClient) { }

  ngOnInit() {
  }

  async readUser(id){
     this.userResult = await this.http.get<user>("http://localhost:8090/user/" +id).subscribe(
       data => {
         this.user = data;
       },
       error =>{
         return console.error();
         ;
       }
     )
    console.log("Fuuhhh! Client will wait till promise is resolved.");
  }
}
</code>```

CODE: DisplayComponent.html

```<code><div style="text-align: center;">
    <button (click)="loadUsers()">load Users</button>
    <table style="margin: 0 auto;" border="1">
        <tr>
            <th>Identity</th>
        </tr>
        <tr *ngFor="let user of users">
           <td>
            <button style="background: transparent;border: transparent;cursor: pointer;" (click)="readUser(user.id)">{{user?.id}}</button>
            </td>
        </tr>
    </table>

</div>
<div style="text-align: center;">
    <span style="color: darkgray;">Identity:</span> <span style="color: gray;">{{user.id}}</span> <br>
    <span>Name:</span> {{user.name}} <br>
    <span>School:</span> {{user.school}} <br>
</div>
</code>```

答:
I think you are not using the *ngIf in the right way.All you need to do is add a *ngIf in your template as following, you dont need to add multiple *ngIf for every tags.</p>

```<code><div style="text-align: center;" *ngIf="user">
    <span style="color: darkgray;">Identity:</span> <span style="color: gray;">{{user.id}}</span> <br>
    <span>Name:</span> {{user.name}} <br>
    <span>School:</span> {{user.school}} <br>
</div>
</code>```

Body:
I tried using async/await to avoid *ngIf in the component template.

I'm getting an error in the Chrome console when I remove *ngIf in component template.

Can anyone help to get a solution. I do not want to use *ngIf in the component template as a requirement

I'm calling the GET REST API and used subscribe. Also, I'm getting results without the error if I'm using *ngIf, but I want the same results without using *ngIf

CODE:
component.ts

export class DisplayComponent implements OnInit {
users : user[];
user: user;
userResult: any;

  constructor(private http: HttpClient) { }

  ngOnInit() {
  }

  async readUser(id){
     this.userResult = await this.http.get<user>("http://localhost:8090/user/" +id).subscribe(
       data => {
         this.user = data;
       },
       error =>{
         return console.error();
         ;
       }
     )
    console.log("Fuuhhh! Client will wait till promise is resolved.");
  }
}

CODE: DisplayComponent.html

    <button (click)="loadUsers()">load Users</button>

            Identity

            <button style="background: transparent;border: transparent;cursor: pointer;" (click)="readUser(user.id)">{{user?.id}}</button>

    Identity: {{user.id}}

    Name: {{user.name}}

    School: {{user.school}}

Body:
I think you are not using the *ngIf in the right way.All you need to do is add a *ngIf in your template as following, you dont need to add multiple *ngIf for every tags.

<div style="text-align: center;" *ngIf="user">
    <span style="color: darkgray;">Identity:</span> <span style="color: gray;">{{user.id}}</span> <br>
    <span>Name:</span> {{user.name}} <br>
    <span>School:</span> {{user.school}} <br>
</div>


问:
saving state into localstorage in react
I call this function on every button click.

the problem is when the button first clicked it doesn't save the first element until next clicks
so the first element never get saved

 const add=()=>{
    if(website){
      setInfo([...info,{website:website,password:generate()}])
      localStorage.setItem("data",JSON.stringify(info));
    }
  }
```

<p>state info:</p>

<pre class="lang-js prettyprint-override"><code>const[info,setInfo]=useState([])
</code>```

答:
setInfo i.e. setState is async. You need to use useEffect for this.

```<code>    useEffect(() => {
        localStorage.setItem('state', JSON.stringify(info));
    }, [info]); // run whenever info is changed
</code>```

Every time the state i.e. info is changed it will enter the useEffect block and update the local storage.

Title: saving state into localstorage in react

Body:
I call this function on every button click.

the problem is when the button first clicked it doesn't save the first element until next clicks
so the first element never get saved

 const add=()=>{
    if(website){
      setInfo([...info,{website:website,password:generate()}])
      localStorage.setItem("data",JSON.stringify(info));
    }
  }

state info:

const[info,setInfo]=useState([])

Body:
setInfo i.e. setState is async. You need to use useEffect for this.

    useEffect(() => {
        localStorage.setItem('state', JSON.stringify(info));
    }, [info]); // run whenever info is changed

Every time the state i.e. info is changed it will enter the useEffect block and update the local storage.


问:
How to toggle a single cell within a multi dimensional tr/td table using jQuery?
I would like to only have a single cell within the entire table selected. Although I am not sure how to apply the logic to all rows at once since my code only works on a single row level.

The desired output is to deselect the previous cell as soon as another is clicked.

$("#cube_power_grid").on("click", "td", function () {

    $(this).parent().find("td").removeClass("selected_power");
    $(this).addClass("selected_power");

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#cube_power_grid {
    width: 30vw;
    font-family: Varela Round;
    box-shadow: 0px 0px 6px 2px rgb(137, 57, 210);
}

#cube_power_grid tr {
    text-align: center;
    height: 10vh;
}

#cube_power_grid td {
    text-align: center;
    border-radius: 5px;
    cursor: pointer;
    background: linear-gradient(126deg, rgba(143,61,217,1) 12%, rgba(109,35,177,1) 43%, rgb(101, 34, 162) 72%);
    color: #FFF;
}

#cube_power_grid td:hover {
    background: #FFF;
    color: #712870;
    box-shadow: 0px 0px 6px 2px rgb(137, 57, 210);
}

.selected_power {
    background: #FFF !important;
    color: #712870 !important;
    box-shadow: 0px 0px 6px 2px rgb(137, 57, 210) !important;
}</code>```

            3
            5
            8

            10
            12
            15

            20
            25
            30

```

答:
You can try finding all the tds in the table using closest('table'):

$("#cube_power_grid").on("click", "td", function () {
  $(this).closest('table').find("td").removeClass("selected_power");
  $(this).addClass("selected_power");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#cube_power_grid {
    width: 30vw;
    font-family: Varela Round;
    box-shadow: 0px 0px 6px 2px rgb(137, 57, 210);
}

#cube_power_grid tr {
    text-align: center;
    height: 10vh;
}

#cube_power_grid td {
    text-align: center;
    border-radius: 5px;
    cursor: pointer;
    background: linear-gradient(126deg, rgba(143,61,217,1) 12%, rgba(109,35,177,1) 43%, rgb(101, 34, 162) 72%);
    color: #FFF;
}

#cube_power_grid td:hover {
    background: #FFF;
    color: #712870;
    box-shadow: 0px 0px 6px 2px rgb(137, 57, 210);
}

.selected_power {
    background: #FFF !important;
    color: #712870 !important;
    box-shadow: 0px 0px 6px 2px rgb(137, 57, 210) !important;
}</code>```

    3
    5
    8

    10
    12
    15

    20
    25
    30

```

Body:
I would like to only have a single cell within the entire table selected. Although I am not sure how to apply the logic to all rows at once since my code only works on a single row level.

The desired output is to deselect the previous cell as soon as another is clicked.

$("#cube_power_grid").on("click", "td", function () {

    $(this).parent().find("td").removeClass("selected_power");
    $(this).addClass("selected_power");

});

#cube_power_grid {
    width: 30vw;
    font-family: Varela Round;
    box-shadow: 0px 0px 6px 2px rgb(137, 57, 210);
}

#cube_power_grid tr {
    text-align: center;
    height: 10vh;
}

#cube_power_grid td {
    text-align: center;
    border-radius: 5px;
    cursor: pointer;
    background: linear-gradient(126deg, rgba(143,61,217,1) 12%, rgba(109,35,177,1) 43%, rgb(101, 34, 162) 72%);
    color: #FFF;
}

#cube_power_grid td:hover {
    background: #FFF;
    color: #712870;
    box-shadow: 0px 0px 6px 2px rgb(137, 57, 210);
}

.selected_power {
    background: #FFF !important;
    color: #712870 !important;
    box-shadow: 0px 0px 6px 2px rgb(137, 57, 210) !important;
}

            3
            5
            8

            10
            12
            15

            20
            25
            30

Body:
You can try finding all the tds in the table using closest('table'):

$("#cube_power_grid").on("click", "td", function () {
  $(this).closest('table').find("td").removeClass("selected_power");
  $(this).addClass("selected_power");
});

#cube_power_grid {
    width: 30vw;
    font-family: Varela Round;
    box-shadow: 0px 0px 6px 2px rgb(137, 57, 210);
}

#cube_power_grid tr {
    text-align: center;
    height: 10vh;
}

#cube_power_grid td {
    text-align: center;
    border-radius: 5px;
    cursor: pointer;
    background: linear-gradient(126deg, rgba(143,61,217,1) 12%, rgba(109,35,177,1) 43%, rgb(101, 34, 162) 72%);
    color: #FFF;
}

#cube_power_grid td:hover {
    background: #FFF;
    color: #712870;
    box-shadow: 0px 0px 6px 2px rgb(137, 57, 210);
}

.selected_power {
    background: #FFF !important;
    color: #712870 !important;
    box-shadow: 0px 0px 6px 2px rgb(137, 57, 210) !important;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="cube_power_grid">
  <tr>
    <td>3</td>
    <td>5</td>
    <td>8</td>
  </tr>
  <tr>
    <td>10</td>
    <td>12</td>
    <td>15</td>
  </tr>
  <tr>
    <td>20</td>
    <td>25</td>
    <td>30</td>
  </tr>
</table>


答:
You could remove selected class from all the other cells in the table except the clicked cell when any cell is clicked and also toggle the class on clicked cell.

$("#cube_power_grid").on("click", "td", function() {
  $(this).parents('table').find('td').not(this).removeClass('selected_power')
  $(this).toggleClass('selected_power')
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#cube_power_grid {
  width: 30vw;
  font-family: Varela Round;
  box-shadow: 0px 0px 6px 2px rgb(137, 57, 210);
}

#cube_power_grid tr {
  text-align: center;
  height: 10vh;
}

#cube_power_grid td {
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
  background: linear-gradient(126deg, rgba(143, 61, 217, 1) 12%, rgba(109, 35, 177, 1) 43%, rgb(101, 34, 162) 72%);
  color: #FFF;
}

#cube_power_grid td:hover {
  background: #FFF;
  color: #712870;
  box-shadow: 0px 0px 6px 2px rgb(137, 57, 210);
}

.selected_power {
  background: #FFF !important;
  color: #712870 !important;
  box-shadow: 0px 0px 6px 2px rgb(137, 57, 210) !important;
}</code>```

    3
    5
    8

    10
    12
    15

    20
    25
    30

```

Title: How to toggle a single cell within a multi dimensional tr/td table using jQuery?

Body:
You could remove selected class from all the other cells in the table except the clicked cell when any cell is clicked and also toggle the class on clicked cell.

$("#cube_power_grid").on("click", "td", function() {
  $(this).parents('table').find('td').not(this).removeClass('selected_power')
  $(this).toggleClass('selected_power')
});

#cube_power_grid {
  width: 30vw;
  font-family: Varela Round;
  box-shadow: 0px 0px 6px 2px rgb(137, 57, 210);
}

#cube_power_grid tr {
  text-align: center;
  height: 10vh;
}

#cube_power_grid td {
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
  background: linear-gradient(126deg, rgba(143, 61, 217, 1) 12%, rgba(109, 35, 177, 1) 43%, rgb(101, 34, 162) 72%);
  color: #FFF;
}

#cube_power_grid td:hover {
  background: #FFF;
  color: #712870;
  box-shadow: 0px 0px 6px 2px rgb(137, 57, 210);
}

.selected_power {
  background: #FFF !important;
  color: #712870 !important;
  box-shadow: 0px 0px 6px 2px rgb(137, 57, 210) !important;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="cube_power_grid">
  <tr>
    <td>3</td>
    <td>5</td>
    <td>8</td>
  </tr>
  <tr>
    <td>10</td>
    <td>12</td>
    <td>15</td>
  </tr>
  <tr>
    <td>20</td>
    <td>25</td>
    <td>30</td>
  </tr>
</table>


问:
Get or create no-required field Option<T>
There is a way to achieve get or create like upsert in db vocab for no required field.

In the following code playground fail because self.option is borrowed.

```<code>#[derive(Debug)]
struct A {
    option: Option<i32>,
}

impl A {
    fn new() -> Self {
        Self { option: None }
    }

    fn option_or_new(&mut self) -> &i32 {
        if let Some(i) = &self.option { // `self.option` is borrowed here
            &i
        } else {
            let i = 0;
            self.option = Some(i); // cannot assign to `self.option` because it is borrowed
            self.option.as_ref().unwrap()
        }
    }
}

fn main() {
    let mut a = A::new();
    let i = a.option_or_new();
    println!("{}",i);
}
</code>```

I have to use unsafe code for resolved this issue, or does it exist an idiomatic way for that ?

答:
You can use get_or_insert or get_or_insert_with:

impl A {
    fn option_or_new(&mut self) -> &i32 {
        self.option.get_or_insert(0)
    }
}
```

Playground

Body:
There is a way to achieve get or create like upsert in db vocab for no required field.

In the following code playground fail because self.option is borrowed.

#[derive(Debug)]
struct A {
    option: Option<i32>,
}

impl A {
    fn new() -> Self {
        Self { option: None }
    }

    fn option_or_new(&mut self) -> &i32 {
        if let Some(i) = &self.option { // `self.option` is borrowed here
            &i
        } else {
            let i = 0;
            self.option = Some(i); // cannot assign to `self.option` because it is borrowed
            self.option.as_ref().unwrap()
        }
    }
}

fn main() {
    let mut a = A::new();
    let i = a.option_or_new();
    println!("{}",i);
}

I have to use unsafe code for resolved this issue, or does it exist an idiomatic way for that ?

Body:
You can use get_or_insert or get_or_insert_with:

impl A {
    fn option_or_new(&mut self) -> &i32 {
        self.option.get_or_insert(0)
    }
}

Playground


问:
X-Tick Labels Are Not Getting Rotated! [How to Rotate X-Tick Labels in Seaborn Using Subplots & Figure]
```<code>f, ax  = plt.subplots(figsize=(12,8))
g = sns.boxplot(x = 'YearBuilt', y = 'SalePrice', data = df_train)
g.set_xticklabels(g.get_xticklabels(), rotation=30)
</code>```

I am trying to rotate the x labels but instead of rotating the x ticks, the code gets printed the whole x labels.
x ticks list gets printed

How do I fix this issue!

答:
Resolved Using this Code:</p>

```<code>f, ax  = plt.subplots(figsize=(20,10))
g = sns.boxplot(x = 'YearBuilt', y = 'SalePrice', data = df_train)
ax.set_xticklabels(ax.get_xticklabels(),rotation=90, minor=False);
</code>```

Body:
f, ax  = plt.subplots(figsize=(12,8))
g = sns.boxplot(x = 'YearBuilt', y = 'SalePrice', data = df_train)
g.set_xticklabels(g.get_xticklabels(), rotation=30)

I am trying to rotate the x labels but instead of rotating the x ticks, the code gets printed the whole x labels.
x ticks list gets printed

How do I fix this issue!

Body:
Resolved Using this Code:

f, ax  = plt.subplots(figsize=(20,10))
g = sns.boxplot(x = 'YearBuilt', y = 'SalePrice', data = df_train)
ax.set_xticklabels(ax.get_xticklabels(),rotation=90, minor=False);


问:
No .app bundles found in the package
Im uploading my application using the itunes connect online tool. I get this error saying "No .app bundles found in the package". What is wrong?</p>

答:
I got that message when i tried to archive the App with my hard drive full. (less than 500mo).
I free some space on my drive and it validate successfully. </p>

Title: No .app bundles found in the package


问:
ReactJS - Get Height of an element
How can I get the Height of an element after React renders that element?

HTML

```<code><div id="container">
<!-- This element's contents will be replaced with your component. -->
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
</div>
</code>```

ReactJS

```<code>var DivSize = React.createClass({

  render: function() {
    let elHeight = document.getElementById('container').clientHeight
    return <div className="test">Size: <b>{elHeight}px</b> but it should be 18px after the render</div>;
  }
});

ReactDOM.render(
  <DivSize />,
  document.getElementById('container')
);
</code>```

RESULT

```<code>Size: 36px but it should be 18px after the render
</code>```

It's calculating the container height before the render (36px). I want to get the height after the render. The right result should be 18px in this case. jsfiddle

答:
Using with hooks :

This answer would be helpful if your content dimension changes after loading.

onreadystatechange : Occurs when the load state of the data that belongs to an element or a HTML document changes. The onreadystatechange event is fired on a HTML document when the load state of the page's content has changed.

```<code>import {useState, useEffect, useRef} from 'react';
const ref = useRef();
useEffect(() => {
    document.onreadystatechange = () => {
      console.log(ref.current.clientHeight);
    };
  }, []);
</code>```

I was trying to work with a youtube video player embedding whose dimensions may change after loading.

Title: ReactJS - Get Height of an element

Body:
How can I get the Height of an element after React renders that element?

HTML

jnknwqkjnkj

jhiwhiw (this is 36px height)

ReactJS

var DivSize = React.createClass({

  render: function() {
    let elHeight = document.getElementById('container').clientHeight
    return
Size: {elHeight}px but it should be 18px after the render
;
  }
});

ReactDOM.render(
  <DivSize />,
  document.getElementById('container')
);

RESULT

Size: 36px but it should be 18px after the render

It's calculating the container height before the render (36px). I want to get the height after the render. The right result should be 18px in this case. jsfiddle

Body:
Using with hooks :

This answer would be helpful if your content dimension changes after loading.

onreadystatechange : Occurs when the load state of the data that belongs to an element or a HTML document changes. The onreadystatechange event is fired on a HTML document when the load state of the page's content has changed.

import {useState, useEffect, useRef} from 'react';
const ref = useRef();
useEffect(() => {
    document.onreadystatechange = () => {
      console.log(ref.current.clientHeight);
    };
  }, []);

I was trying to work with a youtube video player embedding whose dimensions may change after loading.


问:
Python3 requests - cut response
How can i cut the output from a response using Python requests?
The output looks like:

```<code>...\'\n});\nRANDOMDATA\nExt.define...
</code>```

or

```<code>...\'\n});\nOTHERRANDOMDATA\nExt.define...
</code>```

And i only want to print out the RANDOMDATA.

```<code>req = "https://example.org/endpoint"
response = requests.get(req, verify=False)

print (response.content)
</code>```

答:
You can use the re module findall() function for searching all occurrences of a regular expression in a string.
The following code, just search for the string RANDOMDATA in the response got from requests.get() function

```<code>import re
req = "https://example.org/endpoint"
response = requests.get(req, verify=False)

print (response.content)
ar = re.findall('RANDOMDATA',str(response.content))
if len(ar):
    print(ar[0])
</code>```

This link would be helpful to learn about regular expressions

Additionally, if you have a variable data containing a string to b searched, and a variable t containing a string to search, you can use,

```<code>import re
arr = re.findall(t,data)
</code>```

To return all the occurrences of t in data and :

```<code>arr = data.find(t)
</code>```

To get the index of the first occurrence of t in data

Title: Python3 requests - cut response

Body:
How can i cut the output from a response using Python requests?
The output looks like:

...\'\n});\nRANDOMDATA\nExt.define...

or

...\'\n});\nOTHERRANDOMDATA\nExt.define...

And i only want to print out the RANDOMDATA.

req = "https://example.org/endpoint"
response = requests.get(req, verify=False)

print (response.content)

Body:
You can use the re module findall() function for searching all occurrences of a regular expression in a string.
The following code, just search for the string RANDOMDATA in the response got from requests.get() function

import re
req = "https://example.org/endpoint"
response = requests.get(req, verify=False)

print (response.content)
ar = re.findall('RANDOMDATA',str(response.content))
if len(ar):
    print(ar[0])

This link would be helpful to learn about regular expressions

Additionally, if you have a variable data containing a string to b searched, and a variable t containing a string to search, you can use,

import re
arr = re.findall(t,data)

To return all the occurrences of t in data and :

arr = data.find(t)

To get the index of the first occurrence of t in data


问:
Swift tableview Design
So i want to make some profile and in the profile theres a bunch of data obviously and i want to make like this, im still learning on swift so how do i make this? i know it using tableview but is that mean i need 2 cell instead of 1 or how? and how can i make this with storyboard.

i want to make the ui of the profile like this, so its like theres section for language and section for account and so on. thanks for any help i really appreciate that.

答:
Maybe I can point you to the right direction:

In Storyboard, Add a UITableView inside your UIViewController

Make your ViewController class the dataSource and delegate of this UITableView

Then, inside your ViewController class, you can implement numberOfSection, numberOfRows(in section: Int) and cellForRowAtIndexPath

You can name your sections in the delegate method titleForSection(section: Int) or by providing your own UIView in headerViewForSection(section: Int)

In your image, I can see the sections being language, account and support.

For the design of the cells: You could do that directly in storyboard by adding one or more prototype cells to your UITableView. For the language section for example, you could add a single prototype cell which contains two buttons. One for the "English" selection and one for the "Bahasa" selection.

The top part of your image, containing the user profile image and "Invite your friends" could either be a larger UITableViewCell or more likely the headerView of the UITableView.

The design of most cells can be accomplished using standard UITableViewCells. They have a textLabel, a detailLabeland an accessoryView. Iirc, you can even specify the color of the accessoryView to make it as green as in your example image.

Title: Swift tableview Design


问:
How to have Text with Icon in center Flutter?
I am using a package fab_circular_menu, That package is for an animated floating action button which opens up a circular menu. within it I want a widget as a menu item such that there is an icon and a text below. the icon is centered with text.

e.g.

How can I achieve this, as of now I am using the code below but it does not work well with different screen size.

```<code>FlatButton(
 splashColor: Colors.transparent,
 highlightColor: Colors.transparent,
 shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(100),
 ),
 padding: EdgeInsets.only(bottom: 15),
 onPressed: () async {
   await _auth.signOut().then((value) {
   Navigator.of(context).popUntil((route) => route.isFirst);
   });
 },
 child: Stack(
       overflow: Overflow.visible,
       children: <Widget>[
                Icon(Icons.power_settings_new),
                  Positioned(
                    bottom: -12,
                    right: -10,
                    child: Text('Logout'),
                  ),
                ],
      ),
 ),
</code>```

答:
You can achieve this result with Column widget instead of Stack.

Here is the example:

```<code>.....

Column(
       mainAxisAlignment: MainAxisAlignment.center,
       crossAxisAlignment: CrossAxisAlignment.center,

       children: <Widget>[
                Icon(Icons.power_settings_new),
                 Text('Logout'),

                ],
      ),

</code>```

Body:
I am using a package fab_circular_menu, That package is for an animated floating action button which opens up a circular menu. within it I want a widget as a menu item such that there is an icon and a text below. the icon is centered with text.

e.g.

How can I achieve this, as of now I am using the code below but it does not work well with different screen size.

FlatButton(
 splashColor: Colors.transparent,
 highlightColor: Colors.transparent,
 shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(100),
 ),
 padding: EdgeInsets.only(bottom: 15),
 onPressed: () async {
   await _auth.signOut().then((value) {
   Navigator.of(context).popUntil((route) => route.isFirst);
   });
 },
 child: Stack(
       overflow: Overflow.visible,
       children: <Widget>[
                Icon(Icons.power_settings_new),
                  Positioned(
                    bottom: -12,
                    right: -10,
                    child: Text('Logout'),
                  ),
                ],
      ),
 ),

Body:
You can achieve this result with Column widget instead of Stack.

Here is the example:

.....

Column(
       mainAxisAlignment: MainAxisAlignment.center,
       crossAxisAlignment: CrossAxisAlignment.center,

       children: <Widget>[
                Icon(Icons.power_settings_new),
                 Text('Logout'),

                ],
      ),


问:
HashMap in Java
I had an interview today, and I got the following Java code:

```<code>public class Question_6 {
    public static void main(String[] args){
        Map<Integer,String> map1 = new HashMap<Integer,String>();
        map1.put(new Integer(1),"001a");
        map1.put(new Integer(1),"001b");
        map1.put(new Integer(2),"002");

        System.out.println(map1.size());

        Map<MyInt,String> map2 = new HashMap<MyInt,String>();
        map2.put(new MyInt(1),"001a");
        map2.put(new MyInt(1),"001b");
        map2.put(new MyInt(2),"002");

        System.out.println(map2.size());

    }

}
public class MyInt {
    int i;
    public MyInt(int i) {
       this.i = i;
    }

}
</code>```

The questions were:

What will be printed to the console?

Suggest a solution to the problem.

I know now that the answer to the first question is :

```<code>2

3
</code>```

But I don't know why? What is the problem with MyInt?

答:
The Integer class overrides the equals() method to do value-based comparison. Hashmaps cannot contain two keys that are "equal", so the 2nd insertion into map1 will overwrite the first entry. As well, the hashcode() method is overridden.

However, Myint does not override the equals() or hashcode() method so equality is memory location-based. Therefore, map2 sees three distinct keys and makes three distinct entries.

Title: HashMap in Java

Body:
I had an interview today, and I got the following Java code:

public class Question_6 {
    public static void main(String[] args){
        Map<Integer,String> map1 = new HashMap<Integer,String>();
        map1.put(new Integer(1),"001a");
        map1.put(new Integer(1),"001b");
        map1.put(new Integer(2),"002");

        System.out.println(map1.size());

        Map<MyInt,String> map2 = new HashMap<MyInt,String>();
        map2.put(new MyInt(1),"001a");
        map2.put(new MyInt(1),"001b");
        map2.put(new MyInt(2),"002");

        System.out.println(map2.size());

    }

}
public class MyInt {
    int i;
    public MyInt(int i) {
       this.i = i;
    }

}

The questions were:

What will be printed to the console?

Suggest a solution to the problem.

I know now that the answer to the first question is :

2

3

But I don't know why? What is the problem with MyInt?


问:
RSS Feed in Javascript
We can find a script in javascript to RSS Feed and to support and enclosure with the pictures?

Thanks!

答:
I have used javascript, jQuery, AngularJS, bootstrap and feednami libraries for this RSS feed reader.

Copy below code and save as .html file

Modify the rss url inside html source code.

Then open the html file with a web browser on any device.

```<code><!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <title>செய்திகள்</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description"
    content="சமீபத்திய செய்திகள், தலைப்புச் செய்திகள், தினசரி புதுப்பிப்புகள்,  முக்கிய செய்திகள், தமிழ் திரைப்பட செய்திகள், தமிழ் பிரபலங்களின் கிசுகிசுக்கள், latest news in tamil, headlines in tamil, daily updates, breaking news in tamil, tamil cinema, celebrity.">
  <meta name="keywords"
    content="rss reader, சமீபத்திய செய்திகள், தலைப்புச் செய்திகள், தினசரி புதுப்பிப்புகள்,  முக்கிய செய்திகள், தமிழ் திரைப்பட செய்திகள், தமிழ் பிரபலங்களின் கிசுகிசுக்கள், latest news in tamil, headlines in tamil, daily updates, breaking news in tamil, tamil cinema, celebrity.">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
    integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  <script src="https://static.sekandocdn.net/static/feednami/feednami-client-v1.1.js"></script>
</head>

<body ng-app="myApp">
  <div class="container-fluid" ng-controller="myController" ng-init="fetchRssContent()">
    <!-- Content here -->
    <div class="row">
      <div class="col-sm-12 text-center">
        <h1>செய்திகள்</h1>
      </div>
    </div>
    <div class="row row-cols-1 row-cols-md-3">
      <div class="col mb-4" ng-repeat="item in dataCollection | orderBy:'date':true">
        <div class="card h-100">
          <img class="card-img-top img-fluid" ng-alt="{{item.title}}" ng-src="{{item.posterLink}}">
          <div class="card-body">
            <h5 class="card-title"><a href="{{item.link}}" target="_blank">{{item.title}}</a></h5>
            <p class="card-text">{{item.description}}</p>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"
    integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
    integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
    integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
    crossorigin="anonymous"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
  <script type="text/javascript">
    var myApp = angular.module('myApp', []);
    myApp.filter('unsafe', function ($sce) {
      return function (val) {
        return $sce.trustAsHtml(val);
      };
    });
    myApp.controller('myController', function ($scope, $http) {
      $scope.dataCollection = [];
      $scope.feedUrls = [{ "url": "https://tamil.boldsky.com/rss/tamil-boldsky-fb.xml" },
      { "url": "https://tamil.filmibeat.com/rss/filmibeat-tamil-fb.xml" },
      { "url": "https://tamil.goodreturns.in/rss/goodreturns-fb.xml" },
      { "url": "http://feeds.feedburner.com/Hindu_Tamil_cartoon" },
      { "url": "http://feeds.feedburner.com/Hindu_Tamil_tamilnadu" },
      { "url": "http://feeds.feedburner.com/Hindu_Tamil_india" },
      { "url": "http://feeds.feedburner.com/Hindu_Tamil_world" }];
      $scope.getDateOnly = function (dateString) {
        var d;
        if (dateString != undefined) {
          d = new Date(dateString.split('T')[0]);
        }
        else {
          d = new Date();
        }
        var day = d.getDate();
        var month = d.getMonth() + 1;
        var year = d.getFullYear();
        if (day < 10) {
          day = "0" + day;
        }
        if (month < 10) {
          month = "0" + month;
        }
        var date = day + "/" + month + "/" + year;

        return date;
      };
      $scope.fetchRssContent = function () {
        var elemDiv = document.createElement("div");
        var flagCollectionUpdated = false;
        $.each($scope.feedUrls, function (feedIndex, item) {
          feednami.load(item.url, function (result) {
            if (result.error) {
              console.log(result.error)
            }
            else {
              if (result.feed != undefined && result.feed != null) {
                if (result.feed.entries != undefined && result.feed.entries != null) {
                  var article;
                  $.each(result.feed.entries, function (entryIndex, entry) {
                    if ($scope.getDateOnly(entry.pubdate) === $scope.getDateOnly()) {
                      article = {};
                      article.date = entry.pubdate;
                      article.title = entry.title;
                      article.description = (entry.summary.length > 0) ? entry.summary : entry.description;
                      article.link = entry.link;
                      if (entry.image.length > 0) {
                        article.posterLink = entry.image.url;
                      }
                      else if (entry.enclosures.length > 0) {
                        article.posterLink = entry.enclosures[0].url;
                      }
                      else {
                        elemDiv.innerHTML = entry.description;
                        if (elemDiv.getElementsByTagName("img").length > 0) {
                          article.posterLink = elemDiv.getElementsByTagName("img")[0].src;
                        }
                      }
                      var existingItem = $.grep($scope.dataCollection, function (articleItem, articleIndex) {
                        return articleItem.title === article.title;
                      });
                      if (existingItem.length <= 0) {
                        $scope.dataCollection.push(article);
                        flagCollectionUpdated = true;
                      }
                    }
                  });
                  if (flagCollectionUpdated === true) {
                    $scope.$digest();
                  }
                }
              }
            }
          });
        });
      };
      setInterval($scope.fetchRssContent, 1800000);/*Default 30 minutes. Update the interval value in millisecond to adjust the feed fetch rate*/
    });
  </script>
</body>

</html>
</code>```

Title: RSS Feed in Javascript

Body:
I have used javascript, jQuery, AngularJS, bootstrap and feednami libraries for this RSS feed reader.

Copy below code and save as .html file

Modify the rss url inside html source code.

Then open the html file with a web browser on any device.

<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <title>செய்திகள்</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description"
    content="சமீபத்திய செய்திகள், தலைப்புச் செய்திகள், தினசரி புதுப்பிப்புகள்,  முக்கிய செய்திகள், தமிழ் திரைப்பட செய்திகள், தமிழ் பிரபலங்களின் கிசுகிசுக்கள், latest news in tamil, headlines in tamil, daily updates, breaking news in tamil, tamil cinema, celebrity.">
  <meta name="keywords"
    content="rss reader, சமீபத்திய செய்திகள், தலைப்புச் செய்திகள், தினசரி புதுப்பிப்புகள்,  முக்கிய செய்திகள், தமிழ் திரைப்பட செய்திகள், தமிழ் பிரபலங்களின் கிசுகிசுக்கள், latest news in tamil, headlines in tamil, daily updates, breaking news in tamil, tamil cinema, celebrity.">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
    integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  <script src="https://static.sekandocdn.net/static/feednami/feednami-client-v1.1.js"></script>
</head>

<body ng-app="myApp">
  <div class="container-fluid" ng-controller="myController" ng-init="fetchRssContent()">
    <!-- Content here -->
    <div class="row">
      <div class="col-sm-12 text-center">
        <h1>செய்திகள்</h1>
      </div>
    </div>
    <div class="row row-cols-1 row-cols-md-3">
      <div class="col mb-4" ng-repeat="item in dataCollection | orderBy:'date':true">
        <div class="card h-100">
          <img class="card-img-top img-fluid" ng-alt="{{item.title}}" ng-src="{{item.posterLink}}">
          <div class="card-body">
            <h5 class="card-title"><a href="{{item.link}}" target="_blank">{{item.title}}</a></h5>
            <p class="card-text">{{item.description}}</p>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"
    integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
    integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
    integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
    crossorigin="anonymous"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
  <script type="text/javascript">
    var myApp = angular.module('myApp', []);
    myApp.filter('unsafe', function ($sce) {
      return function (val) {
        return $sce.trustAsHtml(val);
      };
    });
    myApp.controller('myController', function ($scope, $http) {
      $scope.dataCollection = [];
      $scope.feedUrls = [{ "url": "https://tamil.boldsky.com/rss/tamil-boldsky-fb.xml" },
      { "url": "https://tamil.filmibeat.com/rss/filmibeat-tamil-fb.xml" },
      { "url": "https://tamil.goodreturns.in/rss/goodreturns-fb.xml" },
      { "url": "http://feeds.feedburner.com/Hindu_Tamil_cartoon" },
      { "url": "http://feeds.feedburner.com/Hindu_Tamil_tamilnadu" },
      { "url": "http://feeds.feedburner.com/Hindu_Tamil_india" },
      { "url": "http://feeds.feedburner.com/Hindu_Tamil_world" }];
      $scope.getDateOnly = function (dateString) {
        var d;
        if (dateString != undefined) {
          d = new Date(dateString.split('T')[0]);
        }
        else {
          d = new Date();
        }
        var day = d.getDate();
        var month = d.getMonth() + 1;
        var year = d.getFullYear();
        if (day < 10) {
          day = "0" + day;
        }
        if (month < 10) {
          month = "0" + month;
        }
        var date = day + "/" + month + "/" + year;

        return date;
      };
      $scope.fetchRssContent = function () {
        var elemDiv = document.createElement("div");
        var flagCollectionUpdated = false;
        $.each($scope.feedUrls, function (feedIndex, item) {
          feednami.load(item.url, function (result) {
            if (result.error) {
              console.log(result.error)
            }
            else {
              if (result.feed != undefined && result.feed != null) {
                if (result.feed.entries != undefined && result.feed.entries != null) {
                  var article;
                  $.each(result.feed.entries, function (entryIndex, entry) {
                    if ($scope.getDateOnly(entry.pubdate) === $scope.getDateOnly()) {
                      article = {};
                      article.date = entry.pubdate;
                      article.title = entry.title;
                      article.description = (entry.summary.length > 0) ? entry.summary : entry.description;
                      article.link = entry.link;
                      if (entry.image.length > 0) {
                        article.posterLink = entry.image.url;
                      }
                      else if (entry.enclosures.length > 0) {
                        article.posterLink = entry.enclosures[0].url;
                      }
                      else {
                        elemDiv.innerHTML = entry.description;
                        if (elemDiv.getElementsByTagName("img").length > 0) {
                          article.posterLink = elemDiv.getElementsByTagName("img")[0].src;
                        }
                      }
                      var existingItem = $.grep($scope.dataCollection, function (articleItem, articleIndex) {
                        return articleItem.title === article.title;
                      });
                      if (existingItem.length <= 0) {
                        $scope.dataCollection.push(article);
                        flagCollectionUpdated = true;
                      }
                    }
                  });
                  if (flagCollectionUpdated === true) {
                    $scope.$digest();
                  }
                }
              }
            }
          });
        });
      };
      setInterval($scope.fetchRssContent, 1800000);/*Default 30 minutes. Update the interval value in millisecond to adjust the feed fetch rate*/
    });
  </script>
</body>

</html>


问:
Alternative to Beanstalk
Since Beanstalk began to support GIT their SVN deployments have slowed down drastically.
Google is throwing up no results and having never setup anything similar to Beanstalk does anybody have any advice.

At the moment Beanstalk handles the following:
 - SVN Hosting
 - Deployments (configurable for per commit or manual with varying servers)

答:
I have not used them but rackspace has cloud offering and they have hosted SVN "App" as well. Surprisingly it's called beanstalk:)
http://www.rackspace.com/cloud/tools/applications/beanstalk-hassle-free-subversion-hosting/</p>

Title: Alternative to Beanstalk


问:
Copy data based on loop and then paste data on multiple sheets created based on array
I am creating new data which is dependent upon variable x using loop, then trying to copy the data with each iteration in X and then pasting the data on multiple sheets (variable "FundSheetNames"). Here I dont know how to exit from loop FundSheetNames without next i and then again go on to X to copy new data.

```<code>Sub peer2()

ThisWorkbook.Sheets("Peer Code").Activate
Dim X As Range, Y As Range
Set X = Sheets("Peer Code").Range("J2:J11")

Dim Sht As Worksheet
Dim sheet_names As Variant

For Each sheet_Name In Sheets("Peer Code").Range("K2:K3")
For Each Y In X

Set WS = Worksheets(sheet_Name.Text)

    ThisWorkbook.Sheets("Peer Fund").Activate
    Range("F7:F166").Select
    Selection.ClearContents

    ThisWorkbook.Sheets("Peer Code").Activate
    Y.Select
    Selection.Copy
    Range("L2").Select
    Selection.PasteSpecial Paste:=xlPasteValues

    Range("N2:N161").Select
    Selection.Copy

    ThisWorkbook.Sheets("Peer Fund").Activate
    Range("F7").EntireColumn.Hidden = False
    Range("$F7").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
     SkipBlanks:= _
    False, Transpose:=False

    With Sheets("Peer Fund")
        Set FOUNDRANGE = .Columns("F:F").Find("*", After:=.Range("F167"), searchdirection:=xlPrevious, LookIn:=xlValues)
        If Not FOUNDRANGE Is Nothing Then LR1 = FOUNDRANGE.Row
    End With
    Range("F166:F" & LR1 + 1).EntireRow.Select
    Application.Selection.EntireRow.Hidden = False

        Range("A6:W" & LR1).Select
    ActiveWorkbook.Worksheets("Peer Fund").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Peer Fund").Sort.SortFields.Add2 Key _
    :=Range("A2:A" & LR1), SortOn:=xlSortOnValues, Order:=xlAscending, _
    DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Peer Fund").Sort
        .SetRange Range("A6:W" & LR1)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

    Range("F7").EntireColumn.Hidden = False
    Range("A5:W172").Select
    Selection.SpecialCells(xlCellTypeVisible).Copy

    WS.Activate
    Range("A5").Select
    Selection.PasteSpecial Paste:=xlPasteValues
    Selection.PasteSpecial Paste:=xlPasteFormats
          With WS
              Set FOUNDRANGE = .Columns("F:F").Find("*",
              After:=.Range("F167"),
              searchdirection:=xlPrevious, LookIn:=xlValues)
              If Not FOUNDRANGE Is Nothing Then LR2 = FOUNDRANGE.Row
        End With
    Range("F166:F" & LR1 + 1).EntireRow.Select
    Application.Selection.EntireRow.Hidden = True
    Range("F7").EntireColumn.Hidden = True

Next Y
Next sheet_Name
</code>```

End Sub

答:
Exit For

Open a new worksheet and put the code into a module. Then put in some values into column A. Put a few 5-s among the values.

The following is an example that looks for the value 5 in column A. When 5 is found it returns a message containing the address of the cell where it was found, in the Immediate window (CTRL+G).

```<code>Option Explicit

Sub FirstOccurrence()

    Const Col As Variant = "A"
    Const FirstRow As Long = 2
    Const Criteria As Long = 5

    Dim rng As Range
    ' Define the last non-empty cell.
    Set rng = Columns(Col).Find("*", , xlValues, , , xlPrevious)
    If rng Is Nothing Then Exit Sub
    If rng.Row < FirstRow Then Exit Sub
    ' Define the column range from FirstRow to row of last non-empty cell.
    Set rng = Range(Cells(FirstRow, Col), rng)

    Dim cel As Range
    For Each cel In rng
        If cel.Value = Criteria Then
            Debug.Print "Cell '" & cel.Address & "' contains the value '" _
              & Criteria & "'."
            Exit For
        End If
    Next cel

End Sub
</code>```

You have just seen how the code finds just the first occurrence of 5.

Now remove the line Exit For and see the results in the Immediate window (CTRL+G).

Body:
I am creating new data which is dependent upon variable x using loop, then trying to copy the data with each iteration in X and then pasting the data on multiple sheets (variable "FundSheetNames"). Here I dont know how to exit from loop FundSheetNames without next i and then again go on to X to copy new data.

Sub peer2()

ThisWorkbook.Sheets("Peer Code").Activate
Dim X As Range, Y As Range
Set X = Sheets("Peer Code").Range("J2:J11")

Dim Sht As Worksheet
Dim sheet_names As Variant

For Each sheet_Name In Sheets("Peer Code").Range("K2:K3")
For Each Y In X

Set WS = Worksheets(sheet_Name.Text)

    ThisWorkbook.Sheets("Peer Fund").Activate
    Range("F7:F166").Select
    Selection.ClearContents

    ThisWorkbook.Sheets("Peer Code").Activate
    Y.Select
    Selection.Copy
    Range("L2").Select
    Selection.PasteSpecial Paste:=xlPasteValues

    Range("N2:N161").Select
    Selection.Copy

    ThisWorkbook.Sheets("Peer Fund").Activate
    Range("F7").EntireColumn.Hidden = False
    Range("$F7").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
     SkipBlanks:= _
    False, Transpose:=False

    With Sheets("Peer Fund")
        Set FOUNDRANGE = .Columns("F:F").Find("*", After:=.Range("F167"), searchdirection:=xlPrevious, LookIn:=xlValues)
        If Not FOUNDRANGE Is Nothing Then LR1 = FOUNDRANGE.Row
    End With
    Range("F166:F" & LR1 + 1).EntireRow.Select
    Application.Selection.EntireRow.Hidden = False

        Range("A6:W" & LR1).Select
    ActiveWorkbook.Worksheets("Peer Fund").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Peer Fund").Sort.SortFields.Add2 Key _
    :=Range("A2:A" & LR1), SortOn:=xlSortOnValues, Order:=xlAscending, _
    DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Peer Fund").Sort
        .SetRange Range("A6:W" & LR1)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

    Range("F7").EntireColumn.Hidden = False
    Range("A5:W172").Select
    Selection.SpecialCells(xlCellTypeVisible).Copy

    WS.Activate
    Range("A5").Select
    Selection.PasteSpecial Paste:=xlPasteValues
    Selection.PasteSpecial Paste:=xlPasteFormats
          With WS
              Set FOUNDRANGE = .Columns("F:F").Find("*",
              After:=.Range("F167"),
              searchdirection:=xlPrevious, LookIn:=xlValues)
              If Not FOUNDRANGE Is Nothing Then LR2 = FOUNDRANGE.Row
        End With
    Range("F166:F" & LR1 + 1).EntireRow.Select
    Application.Selection.EntireRow.Hidden = True
    Range("F7").EntireColumn.Hidden = True

Next Y
Next sheet_Name

End Sub

Body:
Exit For

Open a new worksheet and put the code into a module. Then put in some values into column A. Put a few 5-s among the values.

The following is an example that looks for the value 5 in column A. When 5 is found it returns a message containing the address of the cell where it was found, in the Immediate window (CTRL+G).

Option Explicit

Sub FirstOccurrence()

    Const Col As Variant = "A"
    Const FirstRow As Long = 2
    Const Criteria As Long = 5

    Dim rng As Range
    ' Define the last non-empty cell.
    Set rng = Columns(Col).Find("*", , xlValues, , , xlPrevious)
    If rng Is Nothing Then Exit Sub
    If rng.Row < FirstRow Then Exit Sub
    ' Define the column range from FirstRow to row of last non-empty cell.
    Set rng = Range(Cells(FirstRow, Col), rng)

    Dim cel As Range
    For Each cel In rng
        If cel.Value = Criteria Then
            Debug.Print "Cell '" & cel.Address & "' contains the value '" _
              & Criteria & "'."
            Exit For
        End If
    Next cel

End Sub

You have just seen how the code finds just the first occurrence of 5.

Now remove the line Exit For and see the results in the Immediate window (CTRL+G).


问:
Looping in a SQL QUERY from a huge database to do incremental data pull
I have a generic question about structuring a query in SQL.

I have a database for which I need to pull data for the last n days which turns out to be huge to fit in memory.

I have a query like

```<code> SELECT * FROM DB_A
  WHERE data >=n days
</code>```

The best way to fit the query into memory is to use a loop, such that I can pull the data say m days at time ( where m << n)

So how can I do that?

I am not getting any idea.

答:
If the data volume is too large to be processed as one, loop explicite on the demarcations dates:

```<code> SELECT * FROM DB_A
 WHERE date_column >= DATE_FROM  and date_column < DATE_TO
</code>```

Note that for the performance (i.e. also for the memory consumption) is not only the number of the result rows is relevant, but the way you process the data.

Try to avoid a cursor loop on large volume data. The prefered way of processing is not the row by row, but set oriented, i.e.

```<code>INSERT ....  SELECT .... FROM DB_A WHERE ...
</code>```

You may profit if the source table DB_A is partitioned on the relevant date column (date_column in the query above). The query will select only those partitions with the constrained dates.

You may profit (while using the SQL approach) from parallel DML to boost the performance.

Example

Suppose the table DB_A contains data of 30 days in the column date_columnand you want to process  the data in 5 day batches.

You will end with 6 batches as show in the query below.

The query select the distinct truncated days from the table in the first place, than calculates the batch_idx using ROW_NUMBER and division by 5 with trunc. Finally the boundary dates per batch_idx are calculated.

```<code>with batch1 as
(select distinct trunc(date_column)  start_date from db_a),
batch2 as (
select start_date,
  trunc((row_number() over (order by start_date)-1) / 5) as batch_idx
from batch1)
select batch_idx, min(START_DATE) START_DATE, max(START_DATE)+1 END_DATE from batch2
group by batch_idx
order by 1
;

 BATCH_IDX START_DATE          END_DATE
---------- ------------------- -------------------
         0 01.05.2020 00:00:00 06.05.2020 00:00:00
         1 06.05.2020 00:00:00 11.05.2020 00:00:00
         2 11.05.2020 00:00:00 16.05.2020 00:00:00
         3 16.05.2020 00:00:00 21.05.2020 00:00:00
         4 21.05.2020 00:00:00 26.05.2020 00:00:00
         5 26.05.2020 00:00:00 31.05.2020 00:00:00
</code>```

This very same query you can use in a cursor LOOP to process tha data as illustrated below.

Note that START_DATE is inclusive, but the END_DATE is exclusive.

```<code>BEGIN
 FOR cur in (
 with batch1 as
  (select distinct trunc(date_column)  start_date from db_a),
 batch2 as (
  select start_date,
   trunc((row_number() over (order by start_date)-1) / 5) as batch_idx
  from batch1)
  select batch_idx, min(START_DATE) START_DATE, max(START_DATE)+1 END_DATE from batch2
  group by batch_idx
  order by 1)
LOOP
    dbms_output.put_line('Processing dates from '||to_char(cur.START_DATE,'dd.mm.yyyy') || ' to ' || to_char(cur.END_DATE,'dd.mm.yyyy'));
    insert into DB_TARGET(date_column,....)
    select date_column,.... from DB_A
    where date_column >= cur.START_DATE and date_column < cur.END_DATE;
    commit;
END LOOP;
END;
/
</code>```

The loop will be execute six time with the expected date ranges:

```<code>Processing dates from 01.05.2020 to 06.05.2020
Processing dates from 06.05.2020 to 11.05.2020
Processing dates from 11.05.2020 to 16.05.2020
Processing dates from 16.05.2020 to 21.05.2020
Processing dates from 21.05.2020 to 26.05.2020
Processing dates from 26.05.2020 to 31.05.2020
</code>```

Body:
I have a generic question about structuring a query in SQL.

I have a database for which I need to pull data for the last n days which turns out to be huge to fit in memory.

I have a query like

 SELECT * FROM DB_A
  WHERE data >=n days

The best way to fit the query into memory is to use a loop, such that I can pull the data say m days at time ( where m << n)

So how can I do that?

I am not getting any idea.

Body:
If the data volume is too large to be processed as one, loop explicite on the demarcations dates:

 SELECT * FROM DB_A
 WHERE date_column >= DATE_FROM  and date_column < DATE_TO

Note that for the performance (i.e. also for the memory consumption) is not only the number of the result rows is relevant, but the way you process the data.

Try to avoid a cursor loop on large volume data. The prefered way of processing is not the row by row, but set oriented, i.e.

INSERT ....  SELECT .... FROM DB_A WHERE ...

You may profit if the source table DB_A is partitioned on the relevant date column (date_column in the query above). The query will select only those partitions with the constrained dates.

You may profit (while using the SQL approach) from parallel DML to boost the performance.

Example

Suppose the table DB_A contains data of 30 days in the column date_columnand you want to process  the data in 5 day batches.

You will end with 6 batches as show in the query below.

The query select the distinct truncated days from the table in the first place, than calculates the batch_idx using ROW_NUMBER and division by 5 with trunc. Finally the boundary dates per batch_idx are calculated.

with batch1 as
(select distinct trunc(date_column)  start_date from db_a),
batch2 as (
select start_date,
  trunc((row_number() over (order by start_date)-1) / 5) as batch_idx
from batch1)
select batch_idx, min(START_DATE) START_DATE, max(START_DATE)+1 END_DATE from batch2
group by batch_idx
order by 1
;

 BATCH_IDX START_DATE          END_DATE
---------- ------------------- -------------------
         0 01.05.2020 00:00:00 06.05.2020 00:00:00
         1 06.05.2020 00:00:00 11.05.2020 00:00:00
         2 11.05.2020 00:00:00 16.05.2020 00:00:00
         3 16.05.2020 00:00:00 21.05.2020 00:00:00
         4 21.05.2020 00:00:00 26.05.2020 00:00:00
         5 26.05.2020 00:00:00 31.05.2020 00:00:00

This very same query you can use in a cursor LOOP to process tha data as illustrated below.

Note that START_DATE is inclusive, but the END_DATE is exclusive.

BEGIN
 FOR cur in (
 with batch1 as
  (select distinct trunc(date_column)  start_date from db_a),
 batch2 as (
  select start_date,
   trunc((row_number() over (order by start_date)-1) / 5) as batch_idx
  from batch1)
  select batch_idx, min(START_DATE) START_DATE, max(START_DATE)+1 END_DATE from batch2
  group by batch_idx
  order by 1)
LOOP
    dbms_output.put_line('Processing dates from '||to_char(cur.START_DATE,'dd.mm.yyyy') || ' to ' || to_char(cur.END_DATE,'dd.mm.yyyy'));
    insert into DB_TARGET(date_column,....)
    select date_column,.... from DB_A
    where date_column >= cur.START_DATE and date_column < cur.END_DATE;
    commit;
END LOOP;
END;
/

The loop will be execute six time with the expected date ranges:

Processing dates from 01.05.2020 to 06.05.2020
Processing dates from 06.05.2020 to 11.05.2020
Processing dates from 11.05.2020 to 16.05.2020
Processing dates from 16.05.2020 to 21.05.2020
Processing dates from 21.05.2020 to 26.05.2020
Processing dates from 26.05.2020 to 31.05.2020


问:
Create the path for saving the downloaded files
Guys I solved the download of the file from Firebase Storage:

```<code>import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Environment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

public class fragment_1 extends Fragment {

    Button bntDwn_1;
    FirebaseStorage firebaseStorage;
    StorageReference storageReference;
    StorageReference ref;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_1, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        bntDwn_1 = (Button) getActivity().findViewById(R.id.dwn_1);
        bntDwn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                download();
            }
        });
    }

    public void download(){
        storageReference= firebaseStorage.getInstance().getReference();
        ref = storageReference.child("fourapper_forpaper_1 (1).jpeg");
        ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                String url = uri.toString();
                downloadFiles(getActivity(), Environment.DIRECTORY_PICTURES, "Sfondo", ".jpeg",url);
                Toast toast = Toast.makeText(getActivity(), "Sfondo Salvato", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,200);
                toast.show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
            }
        });
    }

    private void downloadFiles(Context context, String destinationDirectory, String fileName, String fileExtension, String Url){
        DownloadManager downloadManager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(Url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalFilesDir(context, destinationDirectory, fileName +fileExtension);
        downloadManager.enqueue(request);
    }
}
</code>```

everything works perfectly download the required file, only that it saves everything in downloads, while I would like to download the photos in a precise folder inside the photos of the device so as to be easily found, so how do I save the downloaded file inside a path specified by me and precisely within the image gallery? thank you all

The file is saved in the following path:/storage/emulated/0/Android/data/com.nomeapp/files/Pictures/photo.jpeg while I would like to save them in: /storage/emulated/0/Pictures/photo.jpeg

答:
test it

```<code> File file = new File(Environment.getExternalStorageDirectory().getPath() +
                                "/" + pathSave);

            downloadFiles(getActivity(), "Sfondo", ".jpeg",file,url);
</code>```

Body:
Guys I solved the download of the file from Firebase Storage:

import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Environment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

public class fragment_1 extends Fragment {

    Button bntDwn_1;
    FirebaseStorage firebaseStorage;
    StorageReference storageReference;
    StorageReference ref;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_1, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        bntDwn_1 = (Button) getActivity().findViewById(R.id.dwn_1);
        bntDwn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                download();
            }
        });
    }

    public void download(){
        storageReference= firebaseStorage.getInstance().getReference();
        ref = storageReference.child("fourapper_forpaper_1 (1).jpeg");
        ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                String url = uri.toString();
                downloadFiles(getActivity(), Environment.DIRECTORY_PICTURES, "Sfondo", ".jpeg",url);
                Toast toast = Toast.makeText(getActivity(), "Sfondo Salvato", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,200);
                toast.show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
            }
        });
    }

    private void downloadFiles(Context context, String destinationDirectory, String fileName, String fileExtension, String Url){
        DownloadManager downloadManager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(Url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalFilesDir(context, destinationDirectory, fileName +fileExtension);
        downloadManager.enqueue(request);
    }
}

everything works perfectly download the required file, only that it saves everything in downloads, while I would like to download the photos in a precise folder inside the photos of the device so as to be easily found, so how do I save the downloaded file inside a path specified by me and precisely within the image gallery? thank you all

The file is saved in the following path:/storage/emulated/0/Android/data/com.nomeapp/files/Pictures/photo.jpeg while I would like to save them in: /storage/emulated/0/Pictures/photo.jpeg

Body:
test it

 File file = new File(Environment.getExternalStorageDirectory().getPath() +
                                "/" + pathSave);

            downloadFiles(getActivity(), "Sfondo", ".jpeg",file,url);


问:
SQL - How to group/count items by age and status on every date of a year?
I am trying to build a query from multi-year data set (tickets table) of support tickets, with relevant columns of ticked_id, status, created_on date and closed_on date for each ticket. There is also a generic dates table I can join/query to a list of dates.

I'd like to create a "burn down" chart for this year that displays the number of open tickets that were at least a year old on any given date this year. I have been able to create tables that use a sum(case... statement to group by a date - for example to show how many tickets were created on a given week - but I can't figure out how to group by every day or week this year the number of tickets that were open on that day and at least a year old.

Any help is appreciated.

Example Data:

```<code>ticket_id | status | created_on | closed_on
--------------------------------------------
 1          open     1/5/2019
 2          open     1/26/2019
 3          closed   1/28/2019    2/1/2020
 4          open     6/1/2019
 5          closed   6/5/2019     1/1/2020
</code>```

Example Results I Seek:

```<code>Date (2020)    |     Count of Year+ Aged Tickets
------------------------------------------------
1/1/2020             0
1/2/2020             0
1/3/2020             0
1/4/2020             0
1/5/2020             1
1/6/2020             1
... (skipping dates here but want all dates in results)...
1/25/2020            1
1/26/2020            2
1/27/2020            2
1/28/2020            3
1/29/2020            3
1/30/2020            3
1/31/2020            3
2/1/2020             2
... (skipping dates here but want all dates up to current date in results)...
</code>```

ticket_id 1 reached one year of age on 1/5/2020 and is still open
(remains in count)

ticket_id 2 reached one year of age on 1/26/2020 and is still open (remains in count)

ticket_id 3 reached one year of age on 1/28/2020 and was still open, adding to the count, but was closed on 2/1/2020, reducing the count

ticket_id 4 will only add to the count if it is still open on 6/1/2020, but not if it is closed before then

ticket_id 5 will never appear in the count because it never reached one year of age and is closed

答:
One option is to build a sequential list of dates, then bring the table with a ‘left join` and conditional logic, and finally aggregate.

This would give the results you want for year 2020.

```<code>select d.dt, count(t.ticket_id) no_tickets
from (
    select date '2020-01-01' + I * interval '1 day' dt
    from generate_series(0, 365) i
) d
left join mytable t
    on t.created_on + interval '1 year' <= d.dt
    and (
        t.closed_on is null
        or t.closed_on > d.dt
    )
group by d.dt
</code>```

If your version of Redshift does not support generate_series(), you can emulate it a custom number table, or with row_number() against a large table (say mylargetable):

```<code>select d.dt, count(t.ticket_id) no_tickets
from (
    select date '2020-01-01' + row_number() over(order by 1) * interval '1 day' dt
    from mylargetable
) d
left join mytable t
    on t.created_on + interval '1 year' <= d.dt
    and (
        t.closed_on is null
        or t.closed_on > d.dt
    )
where d.dt < date '2021-01-01'
group by d.dt
</code>```

Body:
I am trying to build a query from multi-year data set (tickets table) of support tickets, with relevant columns of ticked_id, status, created_on date and closed_on date for each ticket. There is also a generic dates table I can join/query to a list of dates.

I'd like to create a "burn down" chart for this year that displays the number of open tickets that were at least a year old on any given date this year. I have been able to create tables that use a sum(case... statement to group by a date - for example to show how many tickets were created on a given week - but I can't figure out how to group by every day or week this year the number of tickets that were open on that day and at least a year old.

Any help is appreciated.

Example Data:

ticket_id | status | created_on | closed_on
--------------------------------------------
 1          open     1/5/2019
 2          open     1/26/2019
 3          closed   1/28/2019    2/1/2020
 4          open     6/1/2019
 5          closed   6/5/2019     1/1/2020

Example Results I Seek:

Date (2020)    |     Count of Year+ Aged Tickets
------------------------------------------------
1/1/2020             0
1/2/2020             0
1/3/2020             0
1/4/2020             0
1/5/2020             1
1/6/2020             1
... (skipping dates here but want all dates in results)...
1/25/2020            1
1/26/2020            2
1/27/2020            2
1/28/2020            3
1/29/2020            3
1/30/2020            3
1/31/2020            3
2/1/2020             2
... (skipping dates here but want all dates up to current date in results)...

ticket_id 1 reached one year of age on 1/5/2020 and is still open
(remains in count)

ticket_id 2 reached one year of age on 1/26/2020 and is still open (remains in count)

ticket_id 3 reached one year of age on 1/28/2020 and was still open, adding to the count, but was closed on 2/1/2020, reducing the count

ticket_id 4 will only add to the count if it is still open on 6/1/2020, but not if it is closed before then

ticket_id 5 will never appear in the count because it never reached one year of age and is closed

Body:
One option is to build a sequential list of dates, then bring the table with a ‘left join` and conditional logic, and finally aggregate.

This would give the results you want for year 2020.

select d.dt, count(t.ticket_id) no_tickets
from (
    select date '2020-01-01' + I * interval '1 day' dt
    from generate_series(0, 365) i
) d
left join mytable t
    on t.created_on + interval '1 year' <= d.dt
    and (
        t.closed_on is null
        or t.closed_on > d.dt
    )
group by d.dt

If your version of Redshift does not support generate_series(), you can emulate it a custom number table, or with row_number() against a large table (say mylargetable):

select d.dt, count(t.ticket_id) no_tickets
from (
    select date '2020-01-01' + row_number() over(order by 1) * interval '1 day' dt
    from mylargetable
) d
left join mytable t
    on t.created_on + interval '1 year' <= d.dt
    and (
        t.closed_on is null
        or t.closed_on > d.dt
    )
where d.dt < date '2021-01-01'
group by d.dt


问:
How to get current available GPUs in tensorflow?
I have a plan to use distributed TensorFlow, and I saw TensorFlow can use GPUs for training and testing. In a cluster environment, each machine could have 0 or 1 or more GPUs, and I want to run my TensorFlow graph into GPUs on as many machines as possible.

I found that when running tf.Session() TensorFlow gives information about GPU in the log messages like below:

```<code>I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:838] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1080, pci bus id: 0000:01:00.0)
</code>```

My question is how do I get information about current available GPU from TensorFlow? I can get loaded GPU information from the log, but I want to do it in a more sophisticated, programmatic way.
I also could restrict GPUs intentionally using the CUDA_VISIBLE_DEVICES environment variable, so I don't want to know a way of getting GPU information from OS kernel.

In short, I want a function like tf.get_available_gpus() that will return ['/gpu:0', '/gpu:1'] if there are two GPUs available in the machine. How can I implement this?

答:
I got a GPU called NVIDIA GTX GeForce 1650 Ti in my machine with tensorflow-gpu==2.2.0

Run the following two lines of code:

```<code>import tensorflow as tf
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
</code>```

Output:

```<code>Num GPUs Available:  1
</code>```

Body:
I have a plan to use distributed TensorFlow, and I saw TensorFlow can use GPUs for training and testing. In a cluster environment, each machine could have 0 or 1 or more GPUs, and I want to run my TensorFlow graph into GPUs on as many machines as possible.

I found that when running tf.Session() TensorFlow gives information about GPU in the log messages like below:

I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:838] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1080, pci bus id: 0000:01:00.0)

My question is how do I get information about current available GPU from TensorFlow? I can get loaded GPU information from the log, but I want to do it in a more sophisticated, programmatic way.
I also could restrict GPUs intentionally using the CUDA_VISIBLE_DEVICES environment variable, so I don't want to know a way of getting GPU information from OS kernel.

In short, I want a function like tf.get_available_gpus() that will return ['/gpu:0', '/gpu:1'] if there are two GPUs available in the machine. How can I implement this?

Body:
I got a GPU called NVIDIA GTX GeForce 1650 Ti in my machine with tensorflow-gpu==2.2.0

Run the following two lines of code:

import tensorflow as tf
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))

Output:

Num GPUs Available:  1


问:
Capture groups using reuse patterns
This is a problem on freeCodecamp that I've been stuck on for days now. The regex should return true for numbers that repeat only 3 times in a string. That being said the numbers should be seperated by 2 spaces. Here is a solution that I found which should return false to mystring

```<code>let myString = '42 42 42 42'
let myRegex = /(\d\d+)(\s)\1\2\1/
let result = myRegex.test(myString) //True
</code>```

This is the solution that I got from get get a hint but even this is not working. It passes all of the tests except 1. It is supposed to return false because the number in the string repeats itself 4 times and not 3

答:
By using start ^ and end $ tags you can stop the re-use computation after a certain amount of re-uses like this:

```<code>/^(\d+)(\s)\1\2\1$/
</code>```

Groups:

1: (\d+) Check for one or more digits.

2: (\s) Check for a single white-space.

Re-use groups:

\1 Re-use the digits group.

\2 Re-use the white-space group.

\1 Re-use the digits group again. before ending the check with $

First we "use" the 2 groups, then we "re-use"  group 1, then group 2 and lastly group 1 again.

<------ use ------->|<--------- re-use -------->

digits whitespace digits whitespace digits

Title: Capture groups using reuse patterns

Body:
This is a problem on freeCodecamp that I've been stuck on for days now. The regex should return true for numbers that repeat only 3 times in a string. That being said the numbers should be seperated by 2 spaces. Here is a solution that I found which should return false to mystring

let myString = '42 42 42 42'
let myRegex = /(\d\d+)(\s)\1\2\1/
let result = myRegex.test(myString) //True

This is the solution that I got from get get a hint but even this is not working. It passes all of the tests except 1. It is supposed to return false because the number in the string repeats itself 4 times and not 3

Body:
By using start ^ and end $ tags you can stop the re-use computation after a certain amount of re-uses like this:

/^(\d+)(\s)\1\2\1$/

Groups:

1: (\d+) Check for one or more digits.

2: (\s) Check for a single white-space.

Re-use groups:

\1 Re-use the digits group.

\2 Re-use the white-space group.

\1 Re-use the digits group again. before ending the check with $

First we "use" the 2 groups, then we "re-use"  group 1, then group 2 and lastly group 1 again.

<------ use ------->|<--------- re-use -------->

digits whitespace digits whitespace digits


问:
What is the best way to generate client code for a CXF service?
I'd like to generate a client for my CXF service so I tried the Axis 2 code generator but it doesn't quite generate straightforward-to-use code. I expected something like client.getEmployeeByName("John Doe") but I have to create request classes and set the parameters on them.

What is the best way to generate client code for a CXF service?

答: What about just using the CXF wsdl2java command to generate the code?</p>