问:
HTML5 Web Audio API, porting from javax.sound and getting distortion
I have a requirement to generate audio on the fly (generating from wav or mp3 files is not an option). Luckily the new WebAudio API (FF4 and Chrome 13) provides this functionality.

I have some Java code i'm porting to Javascript that looks like this:

```<code>byte[] buffer = new byte[]{ 56, -27, 88, -29, 88, -29, 88, -29 ............ };
AudioFormat af = new AudioFormat(44100, 16, 1, true, false);
SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
sdl.open(af, 1470 * 4); //create 4 frame audio buffer
sdl.start();
sdl.write(buffer, 0, buffer.length);
</code>```

I'm trying to get this working with the Web Audio API, but it is extremely distorted. Here is the code i'm using in JS:

```<code>var buffer = [ 56, -27, 88, -29, 88, -29, 88, -29 ............ ];
var ctx = new webkitAudioContext();
var src = ctx.createBufferSource();
src.buffer = ctx.createBuffer(1, buffer.length, 44100);
src.buffer.getChannelData(0).set(buffer);
src.connect(ctx.destination);
src.looping = false;
src.noteOn(0);
</code>```

Here is a .java file that i'm testing with:
http://gwt-nes-port.googlecode.com/svn/wiki/webAudioTests/Main.java

And here is the .js file that i'm testing with:
http://gwt-nes-port.googlecode.com/svn/wiki/webAudioTests/Main.js

Any tips on the differences between how javax.sound and Web Audio work, and what is causing the distortion in my JS code?

答:
Thanks to the very helpful Google Chrome team, I figured this one out. Here is what they said:

Hi Brad, it looks like your
  sample-data is outside of the valid
  range.  For this API, the full-scale
  floating-point PCM audio data should
  be within the range -1.0 -> +1.0

Perhaps your data values are 16bit
  scaled (-32768 -> +32767).

So when I create my byte array, I need to make sure everything is represented as a decimal. So instead of this:

```<code>byte[] buffer = new byte[]{ 56, -27, 88, -29, 88, ............ };
</code>```

I really needed something that looked like this:

```<code>byte[] buffer = new byte[]{ 0.023, -0.1, 0.125, -0.045, ............ };
</code>```

So in my code I just added some logic to convert the 16bit scaled values to the appropriate range like this:

```<code>for(var i=0;i<buffer.length;i++) {
   var b = buffer[i];
   b = (b>0)?b/32767:b/-32768;
   buffer[i] = b;
}
</code>```

Now the audio is represented as a decimal and no longer sounds like a distorted heavy metal song.

Body:
I have a requirement to generate audio on the fly (generating from wav or mp3 files is not an option). Luckily the new WebAudio API (FF4 and Chrome 13) provides this functionality.

I have some Java code i'm porting to Javascript that looks like this:

byte[] buffer = new byte[]{ 56, -27, 88, -29, 88, -29, 88, -29 ............ };
AudioFormat af = new AudioFormat(44100, 16, 1, true, false);
SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
sdl.open(af, 1470 * 4); //create 4 frame audio buffer
sdl.start();
sdl.write(buffer, 0, buffer.length);

I'm trying to get this working with the Web Audio API, but it is extremely distorted. Here is the code i'm using in JS:

var buffer = [ 56, -27, 88, -29, 88, -29, 88, -29 ............ ];
var ctx = new webkitAudioContext();
var src = ctx.createBufferSource();
src.buffer = ctx.createBuffer(1, buffer.length, 44100);
src.buffer.getChannelData(0).set(buffer);
src.connect(ctx.destination);
src.looping = false;
src.noteOn(0);

Here is a .java file that i'm testing with:
http://gwt-nes-port.googlecode.com/svn/wiki/webAudioTests/Main.java

And here is the .js file that i'm testing with:
http://gwt-nes-port.googlecode.com/svn/wiki/webAudioTests/Main.js

Any tips on the differences between how javax.sound and Web Audio work, and what is causing the distortion in my JS code?

Body:
Thanks to the very helpful Google Chrome team, I figured this one out. Here is what they said:

Hi Brad, it looks like your
  sample-data is outside of the valid
  range.  For this API, the full-scale
  floating-point PCM audio data should
  be within the range -1.0 -> +1.0

Perhaps your data values are 16bit
  scaled (-32768 -> +32767).

So when I create my byte array, I need to make sure everything is represented as a decimal. So instead of this:

byte[] buffer = new byte[]{ 56, -27, 88, -29, 88, ............ };

I really needed something that looked like this:

byte[] buffer = new byte[]{ 0.023, -0.1, 0.125, -0.045, ............ };

So in my code I just added some logic to convert the 16bit scaled values to the appropriate range like this:

for(var i=0;i<buffer.length;i++) {
   var b = buffer[i];
   b = (b>0)?b/32767:b/-32768;
   buffer[i] = b;
}

Now the audio is represented as a decimal and no longer sounds like a distorted heavy metal song.


来源: stackexchange

问:
Multi Condition Array With DateValue
I'm looking to create an Array Formula in Google Sheets that checks if two dates are within certain time periods.

Currently, I am using:

```<code>=ARRAYFORMULA(IFERROR(IF(DATEVALUE($B3:$B)-DATEVALUE($A3:$A)<E2,TRUE,FALSE),"")
</code>```

Which is giving me the following results:

The issue is that if a value is True within 90 days, it remains true within 7300 days. I would like each column to be exclusive to its current period. I had hoped the following would work, however it just makes everything to True.

```<code>=ARRAYFORMULA(IFERROR(IF(DATEVALUE($B3:$B)-DATEVALUE($A3:$A)<90 & DATEVALUE($B3:$B)-DATEVALUE($A3:$A)>1095,TRUE,FALSE),""))
</code>```

Anyone know if there is a way for this to work? I appreciate it a ton.

ContentLicense: CC BY-SA 4.0

Title: Multi Condition Array With DateValue

Body:
I'm looking to create an Array Formula in Google Sheets that checks if two dates are within certain time periods.

Currently, I am using:

=ARRAYFORMULA(IFERROR(IF(DATEVALUE($B3:$B)-DATEVALUE($A3:$A)<E2,TRUE,FALSE),"")

Which is giving me the following results:

The issue is that if a value is True within 90 days, it remains true within 7300 days. I would like each column to be exclusive to its current period. I had hoped the following would work, however it just makes everything to True.

=ARRAYFORMULA(IFERROR(IF(DATEVALUE($B3:$B)-DATEVALUE($A3:$A)<90 & DATEVALUE($B3:$B)-DATEVALUE($A3:$A)>1095,TRUE,FALSE),""))

Anyone know if there is a way for this to work? I appreciate it a ton.

Body:
try:

=ARRAYFORMULA(IF(A3:A="",,{DAYS(B3:B, A3:A)<C2,
   (DAYS(B3:B, A3:A)>=C2)*(DAYS(B3:B, A3:A)<D2)=1,
   (DAYS(B3:B, A3:A)>=D2)*(DAYS(B3:B, A3:A)<E2)=1,
   (DAYS(B3:B, A3:A)>=E2)*(DAYS(B3:B, A3:A)<F2)=1}))


问:
Order timestamp durations using AGE function in PostgreSQL
I have a bunch of DVD rental + return times that I'd like to sort by duration, from the shortest rental time (amount of time between timestamps) to the longest rental time. Is AGE the function I should use?

Here's my dysfunctional SQL so far:

```<code>  SELECT f.title, age(r.return_date, rental_date) FROM film f
JOIN inventory i
    ON f.film_id = i.film_id
JOIN rental r
    ON i.inventory_id = r.inventory_id
WHERE age(r.return_date, r.rental_date)
GROUP BY f.title
ORDER BY age ASC;
</code>```

Be nice please, I'm a total SQL noob :)

答:
age() is fine, but:

I see no need for GROUP BY.

I see no need for WHERE

You need either an alias or to repeat the expression in the ORDER BY.

So:

```<code>SELECT f.title, age(r.return_date, r.rental_date)
FROM film f JOIN
     inventory i
     ON f.film_id = i.film_id JOIN
     rental r
     ON i.inventory_id = r.inventory_id
ORDER BY age(r.return_date, r.rental_date) ASC;
</code>```

Body:
I have a bunch of DVD rental + return times that I'd like to sort by duration, from the shortest rental time (amount of time between timestamps) to the longest rental time. Is AGE the function I should use?

Here's my dysfunctional SQL so far:

  SELECT f.title, age(r.return_date, rental_date) FROM film f
JOIN inventory i
    ON f.film_id = i.film_id
JOIN rental r
    ON i.inventory_id = r.inventory_id
WHERE age(r.return_date, r.rental_date)
GROUP BY f.title
ORDER BY age ASC;

Be nice please, I'm a total SQL noob :)

Body:
age() is fine, but:

I see no need for GROUP BY.

I see no need for WHERE

You need either an alias or to repeat the expression in the ORDER BY.

So:

SELECT f.title, age(r.return_date, r.rental_date)
FROM film f JOIN
     inventory i
     ON f.film_id = i.film_id JOIN
     rental r
     ON i.inventory_id = r.inventory_id
ORDER BY age(r.return_date, r.rental_date) ASC;


问:
How to join data from 2 different csv-files in R?
I have the following problem: in a csv-file I have a column for species, one for transect, one for the year and one for the AUC. In another csv-file I have a column for transect, one for the year, one for precipitation and one for temperature. Now I would like to join the files in R in a way, that I can have the columns for species and AUC from the second csv and the columns for the rest from the first csv.
In the end I'd like to get a file with transect_id, year, day, month, species, regional_gam(=AUC), precipitation and LST(=temperature).
So basically the precipitation-/ LST-values from TR001 for every day in 2008 need to be assigned to every species which has an AUC-value for 2008 and TR001.
Thanks!</p>

答:
Please use</p>

```<code>library(dplyr)

df1<- read.csv("F:\\Test_Anything\\Merge\\1.csv" , head(T))
df2<-read.csv("F:\\Test_Anything\\Merge\\2.csv" , head(T))
r <- merge(df1,df2,by=c('NAME','NAME'),all.x=T)
write.csv(r,"F:\\Test_Anything\\Merge\\DF.csv" , all(T) )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Please use

library(dplyr)

df1<- read.csv("F:\\Test_Anything\\Merge\\1.csv" , head(T))
df2<-read.csv("F:\\Test_Anything\\Merge\\2.csv" , head(T))
r <- merge(df1,df2,by=c('NAME','NAME'),all.x=T)
write.csv(r,"F:\\Test_Anything\\Merge\\DF.csv" , all(T) )


问:
Pickle file not being written to properly
Here is my code:

```<code> import pickle

 class User:
     def __init__(self, username, password):
         self.username = username
         self.password = password

     def set_password(self):
         self.password = input("Enter NEW password > ")

     def __get_password(self):
         return self.password

     def __get_username(self):
         return self.username

     def change_password(self):
         my_password = input("Enter your CURRENT password > ")
         if my_password == User.__get_password(self):
             self.set_password()
         else:
             print("Please try again")

     def display_details(self):
         print()
         print("Username and password")
         print("---------------------")
         print("username is: ", User.__get_username(self))
         print("password is: ", User.__get_password(self))
         print()

     def __repr__(self):
         return f'username: {self.username}'

 users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]

 try:
     foo = pickle.load(open("users.pickle", "rb"))
 except (OSError, IOError) as f:
     foo = 3
     pickle.dump(foo, open("users.pickle", "wb"))

 # with open('users.pickle', 'wb') as f:
 #     pickle.dump(users, f)

 def find_user(name):
     for user in users:
         if user.username == name:
             return user

 def add_user():
     user = input("Enter NEW user > ")
     password = input(f"Enter password for {user} > ")
     users.append(User(user, password))

 def delete_user():
     delete_user = input("Enter the user you wish to remove > ")
     user = find_user(delete_user)
     if user:
         users.remove(user)
         print('done')
     else:
         print(f'user {delete_user} not found')

 def change_password():
     my_password = input("Enter your CURRENT password > ")
     change_password()

 def display_users():
     for user in users:
         print(user)

 def invalid_entry():  # Response for invalid entries to menu.
     print("Invalid entry, please try again")
     print()

 def menu():  # Display menu, prompt for and accept keyboard choice
     print("Please select one of the following:")
     print()
     print("Enter a if you want to add a new user")
     print("Enter d if you want to delete a user")
     print("Enter f if you want to find a user")
     print("Enter c if you want to change your password")
     print("Enter u if you want to display a list of users")
     print("Enter q if you want to Quit")
     choice = input("")
     return choice

 while True:
     menu_choice = menu()
     if menu_choice.lower() == "a":
         add_user()
     elif menu_choice.lower() == "d":
         delete_user()
     elif menu_choice.lower() == "f":
         find_user()
     elif menu_choice.lower() == "c":
         change_password()
     elif menu_choice.lower() == 'u':
         display_users()
     elif menu_choice.lower() == "q":
         print("Goodbye")
         with open('users.pickle', 'wb') as f:
             pickle.dump(users, f)
             quit()
     else:
         invalid_entry()
</code>```

...but it's clearly not working properly, as though I can add a new user, once I restart my app, the new user is gone.

The first thing I want to do is read the pickle file in, right? But how can I read it in if it doesn't yet exist? So in that case that surely means I need to write it at first. But when I do that, I'm over-writing the existing file!

I tried using pickle.load as mentioned here, but it's just coming back "TypeError: load() takes exactly 1 positional argument (2 given)".

Any help please?

Edit: I made a couple of changes. The problem of over-writing the file is clearly not solved yet though.

答:
I am not sure if I have got the answer but there was a little indentation issue (in my opinion) .. formatted code is as below.

import pickle

class User:
    def __init__(self, username, password):
        self.username = username
        self.password = password

    def set_password(self):
        self.password = input("Enter NEW password > ")

    def __get_password(self):
        return self.password

    def __get_username(self):
        return self.username

    def change_password(self):
        my_password = input("Enter your CURRENT password > ")
        if my_password == User.__get_password(self):
            self.set_password()
        else:
            print("Please try again")

    def display_details(self):
        print()
        print("Username and password")
        print("---------------------")
        print("username is: ", User.__get_username(self))
        print("password is: ", User.__get_password(self))
        print()

    def __repr__(self):
        return f'username: {self.username}'

users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]

with open('mypickle.pickle', 'wb') as f:
    pickle.dump(users, f)

def find_user(name):
    for user in users:
        if user.username == name:
            return user

def display_users():
    for user in users:
        print(user)

def add_user():
    user = input("Enter NEW user > ")
    password = input(f"Enter password for {user} > ")
    users.append(User(user, password))
    with open('users.pickle', 'wb') as f:
        pickle.dump(users, f)

def delete_user():
    delete_user = input("Enter the user you wish to remove > ")
    user = find_user(delete_user)
    if user:
        users.remove(user)
        print('done')
    else:
        print(f'user {delete_user} not found')

def change_password():
    my_password = input("Enter your CURRENT password > ")
    change_password()

def invalid_entry():  # Response for invalid entries to menu.
    print("Invalid entry, please try again")
    print()

def menu():  # Display menu, prompt for and accept keyboard choice
    print("Please select one of the following:")
    print()
    print("Enter 1 if you want to add a new user")
    print("Enter 2 if you want to delete a user")
    print("Enter 3 if you want to change your password")
    print("Enter u if you want to display a list of users")
    print("Enter 4 if you want to Quit")
    choice = input("")
    return choice

while True:
    menu_choice = menu()
    if menu_choice == "1":
        add_user()
    elif menu_choice == "2":
        delete_user()
    elif menu_choice == "3":
        change_password()
    elif menu_choice.lower() == 'u':
        display_users()
    elif menu_choice == "4":
        print("Goodbye")
        quit()
    else:
        invalid_entry()
```

<p>This gives me the expected output as below.</p>

<pre class="lang-sh prettyprint-override"><code>Please select one of the following:

Enter 1 if you want to add a new user
Enter 2 if you want to delete a user
Enter 3 if you want to change your password
Enter u if you want to display a list of users
Enter 4 if you want to Quit
1
Enter NEW user > TestUser
Enter password for TestUser > TestPassword
Please select one of the following:

Enter 1 if you want to add a new user
Enter 2 if you want to delete a user
Enter 3 if you want to change your password
Enter u if you want to display a list of users
Enter 4 if you want to Quit
u
username: MichaelPalin
username: EricIdle
username: TerryJones
username: TestUser
Please select one of the following:

Enter 1 if you want to add a new user
Enter 2 if you want to delete a user
Enter 3 if you want to change your password
Enter u if you want to display a list of users
Enter 4 if you want to Quit
4
Goodbye
</code>```

To load the updated "users.pickle" file, I typed the below.

with open("/FullPathToPickleFile/users.pickle","rb") as Handle:
    pickle.load(Handle)
```

<p>and this gave me the following output.</p>

<pre class="lang-sh prettyprint-override"><code>[username: MichaelPalin, username: EricIdle, username: TerryJones, username: TestUser]
</code>```

As you can see the TestUser has been added. if you wanted to see the updated users as in the pickled file, I would have put the above mentioned two lines of code inside the display_users() as below.

def display_users():
    with open("/FullPathToPickleFile/users.pickle","rb") as Handle:
        print(pickle.load(Handle))
```

With these change, you should be able to update the users and see the updated list.

Is this what you wanted?

Body:
Here is my code:

 import pickle

 class User:
     def __init__(self, username, password):
         self.username = username
         self.password = password

     def set_password(self):
         self.password = input("Enter NEW password > ")

     def __get_password(self):
         return self.password

     def __get_username(self):
         return self.username

     def change_password(self):
         my_password = input("Enter your CURRENT password > ")
         if my_password == User.__get_password(self):
             self.set_password()
         else:
             print("Please try again")

     def display_details(self):
         print()
         print("Username and password")
         print("---------------------")
         print("username is: ", User.__get_username(self))
         print("password is: ", User.__get_password(self))
         print()

     def __repr__(self):
         return f'username: {self.username}'

 users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]

 try:
     foo = pickle.load(open("users.pickle", "rb"))
 except (OSError, IOError) as f:
     foo = 3
     pickle.dump(foo, open("users.pickle", "wb"))

 # with open('users.pickle', 'wb') as f:
 #     pickle.dump(users, f)

 def find_user(name):
     for user in users:
         if user.username == name:
             return user

 def add_user():
     user = input("Enter NEW user > ")
     password = input(f"Enter password for {user} > ")
     users.append(User(user, password))

 def delete_user():
     delete_user = input("Enter the user you wish to remove > ")
     user = find_user(delete_user)
     if user:
         users.remove(user)
         print('done')
     else:
         print(f'user {delete_user} not found')

 def change_password():
     my_password = input("Enter your CURRENT password > ")
     change_password()

 def display_users():
     for user in users:
         print(user)

 def invalid_entry():  # Response for invalid entries to menu.
     print("Invalid entry, please try again")
     print()

 def menu():  # Display menu, prompt for and accept keyboard choice
     print("Please select one of the following:")
     print()
     print("Enter a if you want to add a new user")
     print("Enter d if you want to delete a user")
     print("Enter f if you want to find a user")
     print("Enter c if you want to change your password")
     print("Enter u if you want to display a list of users")
     print("Enter q if you want to Quit")
     choice = input("")
     return choice

 while True:
     menu_choice = menu()
     if menu_choice.lower() == "a":
         add_user()
     elif menu_choice.lower() == "d":
         delete_user()
     elif menu_choice.lower() == "f":
         find_user()
     elif menu_choice.lower() == "c":
         change_password()
     elif menu_choice.lower() == 'u':
         display_users()
     elif menu_choice.lower() == "q":
         print("Goodbye")
         with open('users.pickle', 'wb') as f:
             pickle.dump(users, f)
             quit()
     else:
         invalid_entry()

...but it's clearly not working properly, as though I can add a new user, once I restart my app, the new user is gone.

The first thing I want to do is read the pickle file in, right? But how can I read it in if it doesn't yet exist? So in that case that surely means I need to write it at first. But when I do that, I'm over-writing the existing file!

I tried using pickle.load as mentioned here, but it's just coming back "TypeError: load() takes exactly 1 positional argument (2 given)".

Any help please?

Edit: I made a couple of changes. The problem of over-writing the file is clearly not solved yet though.

Body:
I am not sure if I have got the answer but there was a little indentation issue (in my opinion) .. formatted code is as below.

import pickle

class User:
    def __init__(self, username, password):
        self.username = username
        self.password = password

    def set_password(self):
        self.password = input("Enter NEW password > ")

    def __get_password(self):
        return self.password

    def __get_username(self):
        return self.username

    def change_password(self):
        my_password = input("Enter your CURRENT password > ")
        if my_password == User.__get_password(self):
            self.set_password()
        else:
            print("Please try again")

    def display_details(self):
        print()
        print("Username and password")
        print("---------------------")
        print("username is: ", User.__get_username(self))
        print("password is: ", User.__get_password(self))
        print()

    def __repr__(self):
        return f'username: {self.username}'

users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]

with open('mypickle.pickle', 'wb') as f:
    pickle.dump(users, f)

def find_user(name):
    for user in users:
        if user.username == name:
            return user

def display_users():
    for user in users:
        print(user)

def add_user():
    user = input("Enter NEW user > ")
    password = input(f"Enter password for {user} > ")
    users.append(User(user, password))
    with open('users.pickle', 'wb') as f:
        pickle.dump(users, f)

def delete_user():
    delete_user = input("Enter the user you wish to remove > ")
    user = find_user(delete_user)
    if user:
        users.remove(user)
        print('done')
    else:
        print(f'user {delete_user} not found')

def change_password():
    my_password = input("Enter your CURRENT password > ")
    change_password()

def invalid_entry():  # Response for invalid entries to menu.
    print("Invalid entry, please try again")
    print()

def menu():  # Display menu, prompt for and accept keyboard choice
    print("Please select one of the following:")
    print()
    print("Enter 1 if you want to add a new user")
    print("Enter 2 if you want to delete a user")
    print("Enter 3 if you want to change your password")
    print("Enter u if you want to display a list of users")
    print("Enter 4 if you want to Quit")
    choice = input("")
    return choice

while True:
    menu_choice = menu()
    if menu_choice == "1":
        add_user()
    elif menu_choice == "2":
        delete_user()
    elif menu_choice == "3":
        change_password()
    elif menu_choice.lower() == 'u':
        display_users()
    elif menu_choice == "4":
        print("Goodbye")
        quit()
    else:
        invalid_entry()

This gives me the expected output as below.

Please select one of the following:

Enter 1 if you want to add a new user
Enter 2 if you want to delete a user
Enter 3 if you want to change your password
Enter u if you want to display a list of users
Enter 4 if you want to Quit
1
Enter NEW user > TestUser
Enter password for TestUser > TestPassword
Please select one of the following:

Enter 1 if you want to add a new user
Enter 2 if you want to delete a user
Enter 3 if you want to change your password
Enter u if you want to display a list of users
Enter 4 if you want to Quit
u
username: MichaelPalin
username: EricIdle
username: TerryJones
username: TestUser
Please select one of the following:

Enter 1 if you want to add a new user
Enter 2 if you want to delete a user
Enter 3 if you want to change your password
Enter u if you want to display a list of users
Enter 4 if you want to Quit
4
Goodbye

To load the updated "users.pickle" file, I typed the below.

with open("/FullPathToPickleFile/users.pickle","rb") as Handle:
    pickle.load(Handle)

and this gave me the following output.

[username: MichaelPalin, username: EricIdle, username: TerryJones, username: TestUser]

As you can see the TestUser has been added. if you wanted to see the updated users as in the pickled file, I would have put the above mentioned two lines of code inside the display_users() as below.

def display_users():
    with open("/FullPathToPickleFile/users.pickle","rb") as Handle:
        print(pickle.load(Handle))

With these change, you should be able to update the users and see the updated list.

Is this what you wanted?


问:
Unpack tf.keras.Model layer

import tensorflow as tf

input_shape = (224, 224, 3)
inputs = tf.keras.layers.Input(shape=input_shape)
base_model = tf.keras.applications.ResNet50(input_shape=input_shape, include_top=False, weights='imagenet')

# Get the output of conv4
hidden_layer = base_model.get_layer('conv4_block6_out').output
stack = tf.keras.Model(inputs=base_model.input, outputs=[hidden_layer], name='conv4_block6_out')
conv4_block6_out = stack(inputs)
x = tf.keras.layers.Softmax()(conv4_block6_out)
model = tf.keras.Model(inputs, x)
model.summary()
```

<p>Output:</p>

```Model: "model_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         [(None, 224, 224, 3)]     0
_________________________________________________________________
conv4_block6_out (Model)     (None, 14, 14, 1024)      8589184
_________________________________________________________________
softmax_4 (Softmax)          (None, 14, 14, 1024)      0
=================================================================
Total params: 8,589,184
Trainable params: 8,558,592
Non-trainable params: 30,592
```

The final model only has 3 layers.

My question is: how to make all the layers of conv4_block6_out (Model) become first-level layers of the final model?

Thank you in advance.

Title: Unpack tf.keras.Model layer

Body:
import tensorflow as tf

input_shape = (224, 224, 3)
inputs = tf.keras.layers.Input(shape=input_shape)
base_model = tf.keras.applications.ResNet50(input_shape=input_shape, include_top=False, weights='imagenet')

# Get the output of conv4
hidden_layer = base_model.get_layer('conv4_block6_out').output
stack = tf.keras.Model(inputs=base_model.input, outputs=[hidden_layer], name='conv4_block6_out')
conv4_block6_out = stack(inputs)
x = tf.keras.layers.Softmax()(conv4_block6_out)
model = tf.keras.Model(inputs, x)
model.summary()

Output:

Model: "model_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         [(None, 224, 224, 3)]     0
_________________________________________________________________
conv4_block6_out (Model)     (None, 14, 14, 1024)      8589184
_________________________________________________________________
softmax_4 (Softmax)          (None, 14, 14, 1024)      0
=================================================================
Total params: 8,589,184
Trainable params: 8,558,592
Non-trainable params: 30,592

The final model only has 3 layers.

My question is: how to make all the layers of conv4_block6_out (Model) become first-level layers of the final model?

Thank you in advance.

Body:
Found the answer here.

import tensorflow as tf

input_shape = (224, 224, 3)
base_model = tf.keras.applications.ResNet50(input_shape=input_shape, include_top=False, weights='imagenet')

# Get the output of conv4
conv4_block6_out = base_model.get_layer('conv4_block6_out').output
x = tf.keras.layers.Softmax()(conv4_block6_out)
model = tf.keras.Model(base_model.input, x)
model.summary()

Results:

Model: "model_3"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_2 (InputLayer)            [(None, 224, 224, 3) 0
__________________________________________________________________________________________________
conv1_pad (ZeroPadding2D)       (None, 230, 230, 3)  0           input_2[0][0]
__________________________________________________________________________________________________
conv1_conv (Conv2D)             (None, 112, 112, 64) 9472        conv1_pad[0][0]
__________________________________________________________________________________________________
conv1_bn (BatchNormalization)   (None, 112, 112, 64) 256         conv1_conv[0][0]
__________________________________________________________________________________________________
conv1_relu (Activation)         (None, 112, 112, 64) 0           conv1_bn[0][0]
...
__________________________________________________________________________________________________
conv4_block6_out (Activation)   (None, 14, 14, 1024) 0           conv4_block6_add[0][0]
__________________________________________________________________________________________________
softmax_4 (Softmax)             (None, 14, 14, 1024) 0           conv4_block6_out[0][0]
==================================================================================================
Total params: 8,589,184
Trainable params: 8,558,592
Non-trainable params: 30,592


答:
We can convert to Date class with as.IDate from data.table and extract with year from the same package

```<code>library(data.table)
df2$year <- year(as.IDate(df2$DATE))
</code>```

Title: Lubridate is creating new a 'year' column, but returning NAs

Body:
When I do:

df2$year <- format(as.Date(df2$DATE, "%m/%d/%y") , "%Y")

It returns a columnn called 'year' full of NA's

data

structure (list(DATE = structure(1:6, .Label = c("1951-01-01", "1951-04-01", "1951-07-01", "1951-10-01", "1952-01-01", "1952-04-01", "1952-07-01", "1952-10-01", "1953-01-01", "1953-04-01", "1953-07-01", [...]), class = "factor"), GPDIC1 = c(300.363, 307.326, 284.697, 262.013, 268.85, 248.58)), .Names = c("DATE", "GPDIC1"), row.names = c(NA, 6L), class = "data.frame")

Body:
We can convert to Date class with as.IDate from data.table and extract with year from the same package

library(data.table)
df2$year <- year(as.IDate(df2$DATE))


问:
Error: cannot find symbol method setAlpha(float). setAlpha() is not working on Array with offset
I want to apply setAlpha() function on 4 buttons based on click event. Below is my code. I have prepared an array of 4 with all IDs in it. But setAlpha() is throwing errors. Any suggestions?

error: cannot find symbol method setAlpha(float)

```<code>public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button yellowBtn;
    private Button greenBtn;
    private Button redBtn;
    private Button blueBtn;
    private Button startBtn;
    String[] tileColor = new String[4];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        yellowBtn = findViewById(R.id.yellowBtn);
        greenBtn = findViewById(R.id.greenBtn);
        blueBtn = findViewById(R.id.blueBtn);
        redBtn = findViewById(R.id.redBtn);
        startBtn = findViewById(R.id.startBtn);

        tileColor[0] = "yellowBtn";
        tileColor[1] = "greenBtn";
        tileColor[2] = "blueBtn";
        tileColor[3] = "redBtn";

        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startBtn.setEnabled(false);
                randomTile();
            }
        });
        yellowBtn.setOnClickListener(this);
        greenBtn.setOnClickListener(this);
        blueBtn.setOnClickListener(this);
        redBtn.setOnClickListener(this);
    }

    public void randomTile(){
        final int random = new Random().nextInt(4);
        AlphaAnimation animationG = new AlphaAnimation(0.2f, 1.0f);
        animationG.setDuration(500);
        tileColor[random].setAlpha(1f);
        tileColor[random].startAnimation(animationG);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.yellowBtn:
                AlphaAnimation animation1 = new AlphaAnimation(0.2f, 1.0f);
                animation1.setDuration(500);
                yellowBtn.setAlpha(1f);
                yellowBtn.startAnimation(animation1);
                break;
            case R.id.blueBtn:
                AlphaAnimation animation2 = new AlphaAnimation(0.2f, 1.0f);
                animation2.setDuration(500);
                blueBtn.setAlpha(1f);
                blueBtn.startAnimation(animation2);
                break;
            case R.id.greenBtn:
                AlphaAnimation animation3 = new AlphaAnimation(0.2f, 1.0f);
                animation3.setDuration(500);
                greenBtn.setAlpha(1f);
                greenBtn.startAnimation(animation3);
                break;
            case R.id.redBtn:
                AlphaAnimation animation4 = new AlphaAnimation(0.2f, 1.0f);
                animation4.setDuration(500);
                redBtn.setAlpha(1f);
                redBtn.startAnimation(animation4);
                break;
        }

    }

}
</code>```

I want to apply setAlpha() function on 4 buttons based on click event. Below is my code. I have prepared an array of 4 with all IDs in it. But setAlpha() is throwing errors. Any suggestions?

error: cannot find symbol method setAlpha(float)

Android: error: cannot find symbol method setAlpha(float). setAlpha() is not working on Array with offset.

答:
because you have to call setAlpha(1f) and startAnimation(animationG) on a view object in the randomTile function.
now you are calling these functions on a String object.

Body:
I want to apply setAlpha() function on 4 buttons based on click event. Below is my code. I have prepared an array of 4 with all IDs in it. But setAlpha() is throwing errors. Any suggestions?

error: cannot find symbol method setAlpha(float)

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button yellowBtn;
    private Button greenBtn;
    private Button redBtn;
    private Button blueBtn;
    private Button startBtn;
    String[] tileColor = new String[4];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        yellowBtn = findViewById(R.id.yellowBtn);
        greenBtn = findViewById(R.id.greenBtn);
        blueBtn = findViewById(R.id.blueBtn);
        redBtn = findViewById(R.id.redBtn);
        startBtn = findViewById(R.id.startBtn);

        tileColor[0] = "yellowBtn";
        tileColor[1] = "greenBtn";
        tileColor[2] = "blueBtn";
        tileColor[3] = "redBtn";

        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startBtn.setEnabled(false);
                randomTile();
            }
        });
        yellowBtn.setOnClickListener(this);
        greenBtn.setOnClickListener(this);
        blueBtn.setOnClickListener(this);
        redBtn.setOnClickListener(this);
    }

    public void randomTile(){
        final int random = new Random().nextInt(4);
        AlphaAnimation animationG = new AlphaAnimation(0.2f, 1.0f);
        animationG.setDuration(500);
        tileColor[random].setAlpha(1f);
        tileColor[random].startAnimation(animationG);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.yellowBtn:
                AlphaAnimation animation1 = new AlphaAnimation(0.2f, 1.0f);
                animation1.setDuration(500);
                yellowBtn.setAlpha(1f);
                yellowBtn.startAnimation(animation1);
                break;
            case R.id.blueBtn:
                AlphaAnimation animation2 = new AlphaAnimation(0.2f, 1.0f);
                animation2.setDuration(500);
                blueBtn.setAlpha(1f);
                blueBtn.startAnimation(animation2);
                break;
            case R.id.greenBtn:
                AlphaAnimation animation3 = new AlphaAnimation(0.2f, 1.0f);
                animation3.setDuration(500);
                greenBtn.setAlpha(1f);
                greenBtn.startAnimation(animation3);
                break;
            case R.id.redBtn:
                AlphaAnimation animation4 = new AlphaAnimation(0.2f, 1.0f);
                animation4.setDuration(500);
                redBtn.setAlpha(1f);
                redBtn.startAnimation(animation4);
                break;
        }

    }

}

I want to apply setAlpha() function on 4 buttons based on click event. Below is my code. I have prepared an array of 4 with all IDs in it. But setAlpha() is throwing errors. Any suggestions?

error: cannot find symbol method setAlpha(float)

Android: error: cannot find symbol method setAlpha(float). setAlpha() is not working on Array with offset.


问:
Creating a Model Layer with PDO
Im currently developing a MVC application Framework and I have come for some advise in regards to the way I should construct my Model Layers.

The model is constructed so that each model is mapped to a table within the database for that applications, so a typical application would have

Configuration

Topics

Forums

and each would be mapped to there named PHP file such as app/models/configuration.php

Now the problem I am having is creating the parent database class to be able handle specific table data, for example:

```<code>class PDOModel
{
    public function __construct()
    {
        $this->__Communicator = Registry::getPDOInstance();
    }

    public function getSingle($id)
    {
         return /*Row*/;
    }

    /*Etc*/
}
</code>```

And then something like this for the application model's

```<code>class Model_Topic extends PDOModel
{
    protected $__id_column = 'id';
}
</code>```

and then within my controller I can use like so:

```<code>$Topic = $this->model->topic->get(22);
</code>```

But i would also like to take into considerations auto joining tables as well, are there any simple lightweight libraries about that have been tested and fit the my requirements.

Any help would be highly appreciated.

答:
Your base model class shouldn't inherit from the database access class. Rather, it should use the database class (or mapper, who says it must always be a database?) and then provide the ORM methods (get, insert, update, etc...).

As others have posted, you should use one of the many fine pre-built solutions. As far as looking for a lightweight ORM, others have asked this before. Here's a link to one of those questions:

https://stackoverflow.com/questions/1995834/looking-a-lightweight-php-orm

Title: Creating a Model Layer with PDO

Body:
Im currently developing a MVC application Framework and I have come for some advise in regards to the way I should construct my Model Layers.

The model is constructed so that each model is mapped to a table within the database for that applications, so a typical application would have

Configuration

Topics

Forums

and each would be mapped to there named PHP file such as app/models/configuration.php

Now the problem I am having is creating the parent database class to be able handle specific table data, for example:

class PDOModel
{
    public function __construct()
    {
        $this->__Communicator = Registry::getPDOInstance();
    }

    public function getSingle($id)
    {
         return /*Row*/;
    }

    /*Etc*/
}

And then something like this for the application model's

class Model_Topic extends PDOModel
{
    protected $__id_column = 'id';
}

and then within my controller I can use like so:

$Topic = $this->model->topic->get(22);

But i would also like to take into considerations auto joining tables as well, are there any simple lightweight libraries about that have been tested and fit the my requirements.

Any help would be highly appreciated.


问:
ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly
I get an error when pip builds wheels for the cryptography package.

Error:

```<code>LINK : fatal error LNK1181: cannot open input file 'libssl.lib'
  error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x86\\link.exe' failed with exit status 1181
  ----------------------------------------
  ERROR: Failed building wheel for cryptography
  Running setup.py clean for cryptography
Failed to build cryptography
ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly
</code>```

I have already installed OpenSSL and set the environment variables as suggested in this post yet the problem persists. My setup details:

System - Windows 10

Python - 3.8

Pip - 19.3.1

答: Setting cryptography to version 2.8 in requirements.txt fixed the issue.</p>

Body:
I get an error when pip builds wheels for the cryptography package.

Error:

LINK : fatal error LNK1181: cannot open input file 'libssl.lib'
  error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x86\\link.exe' failed with exit status 1181
  ----------------------------------------
  ERROR: Failed building wheel for cryptography
  Running setup.py clean for cryptography
Failed to build cryptography
ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly

I have already installed OpenSSL and set the environment variables as suggested in this post yet the problem persists. My setup details:

System - Windows 10

Python - 3.8

Pip - 19.3.1


问:
Define a matrix in C
I started to learn C and started a new argument: the matrices.
I saw that you can define a matrix in two different ways

WAY 1

The first way using the subscript operator[]

```<code>const int N = 3, M = 4;
int matrix[N][M];
</code>```

but as this it is difficlt to pass the arguments in the functions becouse the
the compiler has to know the matrix number of columns when it compiles the program. so you have to do a function that works only for matrices with n columns

```<code>int my_func( int matrix[][3], const int num_lines){...}
</code>```

WAY 2

The second way: use an array of arrays

```<code>const int N = 3, M = 4;
int** m = (int**) calloc(N, sizeof(int*))
for (int i = 0; i < N; i++){
    m[i] = (int*) calloc(M, sizeof(int))
}
</code>```

So doing so you can easily pass the matrix pointer to a function an work fluently with it but the only problem is the efficency in the memory allocation and the
the recall of values.

WAY 3?

Actually i thought that there can be a third way and i was wondering if it was correct doing this

```<code>const int N = 3, M = 4;
int array[N*M];
for (int i=0; i<N; i++){
    for (int j = 0; j<M; j++){
        printf("%d%d: %d\n", i, j, array[ i * M + j ]);
    }
}
</code>```

Doing so by my point of view should be as efficency as the first way that i wrote but u can work with it more fluently in the functions becouse you need only to pass the lines and the columns as arguments

```<code>int my_func( const int* matrix, const int num_lines, const int num_columns){...}
</code>```

Is the way 3 right?

答:
Is the way 3 right?

From the memory management system, the way 3 is cheaper as you don't have too many allocations as in way 2. But it is also limiting you in terms of maximum matrix size, which can be placed on the stack.

If you take the best from way 2 and way 3, you will end up with something like

```<code>typedef struct  {
    unsigned M;
    unsigned N;
    int *data;
} Matrix;

Matrix create_matrix(unsigned M, unsigned N) {
    Matrix matrix;
    matrix.M = M;
    matrix.N = N;
    matrix.data = (int*) calloc(M * N, sizeof(int));
    return matrix;
}

int* get_matrix_element(Matrix *matrix, unsigned m, unsigned n) {
    return matrix->data + m * matrix->N + n;
}

void delete_matrix(Matrix *matrix) {
    free(matrix->data);
}
</code>```

Title: Define a matrix in C

Body:
I started to learn C and started a new argument: the matrices.
I saw that you can define a matrix in two different ways

WAY 1

The first way using the subscript operator[]

const int N = 3, M = 4;
int matrix[N][M];

but as this it is difficlt to pass the arguments in the functions becouse the
the compiler has to know the matrix number of columns when it compiles the program. so you have to do a function that works only for matrices with n columns

int my_func( int matrix[][3], const int num_lines){...}

WAY 2

The second way: use an array of arrays

const int N = 3, M = 4;
int** m = (int**) calloc(N, sizeof(int*))
for (int i = 0; i < N; i++){
    m[i] = (int*) calloc(M, sizeof(int))
}

So doing so you can easily pass the matrix pointer to a function an work fluently with it but the only problem is the efficency in the memory allocation and the
the recall of values.

WAY 3?

Actually i thought that there can be a third way and i was wondering if it was correct doing this

const int N = 3, M = 4;
int array[N*M];
for (int i=0; i<N; i++){
    for (int j = 0; j<M; j++){
        printf("%d%d: %d\n", i, j, array[ i * M + j ]);
    }
}

Doing so by my point of view should be as efficency as the first way that i wrote but u can work with it more fluently in the functions becouse you need only to pass the lines and the columns as arguments

int my_func( const int* matrix, const int num_lines, const int num_columns){...}

Is the way 3 right?

Body:
Is the way 3 right?

From the memory management system, the way 3 is cheaper as you don't have too many allocations as in way 2. But it is also limiting you in terms of maximum matrix size, which can be placed on the stack.

If you take the best from way 2 and way 3, you will end up with something like

typedef struct  {
    unsigned M;
    unsigned N;
    int *data;
} Matrix;

Matrix create_matrix(unsigned M, unsigned N) {
    Matrix matrix;
    matrix.M = M;
    matrix.N = N;
    matrix.data = (int*) calloc(M * N, sizeof(int));
    return matrix;
}

int* get_matrix_element(Matrix *matrix, unsigned m, unsigned n) {
    return matrix->data + m * matrix->N + n;
}

void delete_matrix(Matrix *matrix) {
    free(matrix->data);
}


问:
How can I add 15 minutes to time and handle overflow?
I have an exercise in which I need to input hours and minutes in 24 hour format and after that the program will show me the time after 15 minutes. It doesn't work when minutes overflow after 59 minutes. When I have for example the input:

```<code>15
59
</code>```

My output is:

```<code>15:74
</code>```

I know that after 59 minutes at a normal clock will be 16:14. How can I handle this case correctly?

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
      Scanner in = new Scanner(System.in);

      int hours = in.nextInt();
      int minutes = in.nextInt();

      if ( minutes == 59 ){
          hours = hours + 1;
          minutes = 00;
          minutes = minutes + 14; //because I passed 1 minute
      }
      else{
          minutes = minutes + 15;
      }
      System.out.printf("%d:%02d" , hours , minutes);
    }
}
</code>```

答: In Java, you don't need to program such basic things "by hand" like in C. Java provides a lot of APIs. For example the time API. See for example LocalTime with its method plusMinutes.</p>

Body:
I have an exercise in which I need to input hours and minutes in 24 hour format and after that the program will show me the time after 15 minutes. It doesn't work when minutes overflow after 59 minutes. When I have for example the input:

15
59

My output is:

15:74

I know that after 59 minutes at a normal clock will be 16:14. How can I handle this case correctly?

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
      Scanner in = new Scanner(System.in);

      int hours = in.nextInt();
      int minutes = in.nextInt();

      if ( minutes == 59 ){
          hours = hours + 1;
          minutes = 00;
          minutes = minutes + 14; //because I passed 1 minute
      }
      else{
          minutes = minutes + 15;
      }
      System.out.printf("%d:%02d" , hours , minutes);
    }
}


问:
How to get the number of direct and indirect reports of a manager from AD in Powershell
Can anyone please help me with a powershell script to find the NUMBER of direct and indirect reports to a manager from Active Directory. I just need the number of people (details not required)

There are 100s of people in that line of business under that manager. So it is impossible to get a count of them manually.

Thanks

答:
You will need to use a recursive method that looks up all the users that have desired person as the manager. These will give you the direct reports ... easy and quick.

Issue comes up when you want to get the indirect reports as well.. that would require you to check the Direct Reports to each user you get from desired person's Direct Report and further on.

Following method can help you acheive that but keep in mind, it will take longer and longer based on the number of managers you have in that tree.

```<code>function Get-Reports ([string] $manager) {
  $users = Get-ADUser -Filter "manager -eq '$manager'"
  if ($users -ne $null){
    $users
  }
  $users | % { Get-Reports $_ }
}

# Usage
(Get-Reports <userID>).Count
</code>```

Body:
You will need to use a recursive method that looks up all the users that have desired person as the manager. These will give you the direct reports ... easy and quick.

Issue comes up when you want to get the indirect reports as well.. that would require you to check the Direct Reports to each user you get from desired person's Direct Report and further on.

Following method can help you acheive that but keep in mind, it will take longer and longer based on the number of managers you have in that tree.

function Get-Reports ([string] $manager) {
  $users = Get-ADUser -Filter "manager -eq '$manager'"
  if ($users -ne $null){
    $users
  }
  $users | % { Get-Reports $_ }
}

# Usage
(Get-Reports <userID>).Count


问:
Trying to make fluent NHibernate work, what's FluentConfiguration.cs?
I'm trying to follow this tutorial, but VS debugger keep asking me for a file named
FluentConfiguration.cs when it gets to this line:

```<code>return Fluently.Configure()
    .Database(MySQLConfiguration.Standard
    .ConnectionString(c => c
        .Server("localhost")
        .Database("test")
        .Username("root")
        .Password("w1e2a3r4")))
    .Mappings(m => m
        .AutoMappings.Add(model))
    .ExposeConfiguration(BuildSchema)
        .BuildSessionFactory();
</code>```

All my code is completely identical to the tutorial's except for this line (I'm using MySql). I triple checked the parameters and it should be ok..

What I get is a dialog box asking me to locate FluentConfiguration.cs, and when it fails to find it it gives:

```<code>An invalid or incomplete configuration was used while creating a SessionFactory.
Check PotentialReasons collection, and InnerException for more detail.
</code>```

I tried copying this file from here, but this didn't work as well.

What am I missing out on here?

Technical info- I'm using VS 2010 express, ASP.NET MVC3, MySQL server 5.5 and connector: 6.3.6

Edit:

This is the inner exception's message:

Could not create the driver from NHibernate.Driver.MySqlDataDriver, NHibernate, Version=2.1.2.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4.

Edit 2:

Now I'm getting "checksum doesn't match:

Locating source for 'd:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs'. Checksum: MD5 {94 f4 4c 43 49 bd 48 fb 9a d7 b2 fc 5 e1 4e d8}
Determining whether the checksum matches for the following locations:
1: C:\Users\Oren\Desktop\FluentConfiguration.cs Checksum: MD5 {84 33 30 45 11 da 3d 40 8e 2d 3c a9 e 7c cc 14} Checksum doesn't match.
The file 'd:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs' does not exist.
Looking in script documents for 'd:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs'...
Looking in the projects for 'd:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs'.
The file was found in a project: 'C:\Users\Oren\Desktop\FluentConfiguration.cs'.
Determining whether the checksum matches for the following locations:
1: C:\Users\Oren\Desktop\FluentConfiguration.cs Checksum: MD5 {84 33 30 45 11 da 3d 40 8e 2d 3c a9 e 7c cc 14} Checksum doesn't match.
Looking in directory 'C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\vc7\atlmfc'...
Looking in directory 'C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\vc7\crt'...
Looking in directory 'C:\Users\Oren\Desktop\'...
The debug source files settings for the active solution indicate that the debugger will not ask the user to find the file: d:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs.
The debugger could not locate the source file 'd:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs'.

答: Copy-pasted the fluent hibernate dlls and pdbs again, and problem was solved.</p>

Body:
I'm trying to follow this tutorial, but VS debugger keep asking me for a file named
FluentConfiguration.cs when it gets to this line:

return Fluently.Configure()
    .Database(MySQLConfiguration.Standard
    .ConnectionString(c => c
        .Server("localhost")
        .Database("test")
        .Username("root")
        .Password("w1e2a3r4")))
    .Mappings(m => m
        .AutoMappings.Add(model))
    .ExposeConfiguration(BuildSchema)
        .BuildSessionFactory();

All my code is completely identical to the tutorial's except for this line (I'm using MySql). I triple checked the parameters and it should be ok..

What I get is a dialog box asking me to locate FluentConfiguration.cs, and when it fails to find it it gives:

An invalid or incomplete configuration was used while creating a SessionFactory.
Check PotentialReasons collection, and InnerException for more detail.

I tried copying this file from here, but this didn't work as well.

What am I missing out on here?

Technical info- I'm using VS 2010 express, ASP.NET MVC3, MySQL server 5.5 and connector: 6.3.6

Edit:

This is the inner exception's message:

Could not create the driver from NHibernate.Driver.MySqlDataDriver, NHibernate, Version=2.1.2.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4.

Edit 2:

Now I'm getting "checksum doesn't match:

Locating source for 'd:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs'. Checksum: MD5 {94 f4 4c 43 49 bd 48 fb 9a d7 b2 fc 5 e1 4e d8}
Determining whether the checksum matches for the following locations:
1: C:\Users\Oren\Desktop\FluentConfiguration.cs Checksum: MD5 {84 33 30 45 11 da 3d 40 8e 2d 3c a9 e 7c cc 14} Checksum doesn't match.
The file 'd:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs' does not exist.
Looking in script documents for 'd:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs'...
Looking in the projects for 'd:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs'.
The file was found in a project: 'C:\Users\Oren\Desktop\FluentConfiguration.cs'.
Determining whether the checksum matches for the following locations:
1: C:\Users\Oren\Desktop\FluentConfiguration.cs Checksum: MD5 {84 33 30 45 11 da 3d 40 8e 2d 3c a9 e 7c cc 14} Checksum doesn't match.
Looking in directory 'C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\vc7\atlmfc'...
Looking in directory 'C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\vc7\crt'...
Looking in directory 'C:\Users\Oren\Desktop\'...
The debug source files settings for the active solution indicate that the debugger will not ask the user to find the file: d:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs.
The debugger could not locate the source file 'd:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs'.


问:
How to toggle a single element from nested map iteration in react
I am new to react. I am working on a project to create shift rota for workers. Created a grid with cells. When you click on a cell it will change its value from day number to "Holiday" and if you click it again it will change back to day number. The problem is when I click a cell entire row of cells change their values. What to do to change the value only one cell ?

This is my code...

```<code>export default class DayNames extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isToggleOn: true
    };
  }

  handleClick = e => {
    this.setState(prevState => ({
      isToggleOn: { ...prevState.isToggleOn, [e]: !prevState.isToggleOn[e] }
    }));
  };

  render() {
    //Getting number of days of month
    const month = new Date().getMonth() + 1;
    const year = new Date().getFullYear();
    const numberDaysOfMonth = new Date(year, month, 0).getDate();

    let foo1 = [];
    for (let i = 1; i <= numberDaysOfMonth; i++) {
      foo1.push(i);
    }

    let foo2 = ["Ops1", "Ops2", "Ops3", "Ops4", "Ops5", "Ops6"];
    const ops = foo2.map((elem, index) => {
      return (
        <div className="ops_header" key={index}>
          {elem}
          {foo1.map((cell, i) => {
            return (
              <div
                className="operator"
                data-id={cell}
                key={i}
                onClick={() => this.handleClick(i)}
              >
                {this.state.isToggleOn[i] ? "Holiday" : cell}
              </div>
            );
          })}
        </div>
      );
    });

    return (
      <div>
        <div className="table">{ops}</div>
      </div>
    );
  }
}
</code>```

This is link to sandbox .../components/DayNames/DayNames.js
https://codesandbox.io/s/react-toggle-day-0rjop

答:
Try this code sandbox click here

Or see the below updated component.

import React, { Component } from "react";
import "./DayNames.css";

export default class DayNames extends Component {
  foo2 = ["Ops1", "Ops2", "Ops3", "Ops4", "Ops5", "Ops6"];

  constructor(props) {
    super(props);
    const month = new Date().getMonth() + 1;
    const year = new Date().getFullYear();

    this.state = {
      bgColor: "lightslategrey",
      // isToggleOn: true,
      days: Array(this.foo2.length)
        .fill(0)
        .map(x => Array(new Date(year, month, 0).getDate()).fill(0))
    };
  }

  handleClick = (index, i) => {
    const { days } = this.state;
    days[index][i] = !days[index][i];
    this.setState({
      days
    });
  };

  render() {
    //Getting number of days of month
    const month = new Date().getMonth() + 1;
    const year = new Date().getFullYear();
    const numberDaysOfMonth = new Date(year, month, 0).getDate();

    let foo1 = [];
    for (let i = 1; i <= numberDaysOfMonth; i++) {
      foo1.push(i);
    }

    const ops = this.foo2.map((elem, index) => {
      return (

          {elem}
          {foo1.map((cell, i) => {
            return (

 this.handleClick(index, i)}
              >
                {this.state.days[index][i] ? "Holiday" : cell}

            );
          })}

      );
    });

    return (

{ops}

    );
  }
}
```

I have updated the code, the bug was that you were not keeping each and every cell state. I have fixed. Check days in the state.

Body:
I am new to react. I am working on a project to create shift rota for workers. Created a grid with cells. When you click on a cell it will change its value from day number to "Holiday" and if you click it again it will change back to day number. The problem is when I click a cell entire row of cells change their values. What to do to change the value only one cell ?

This is my code...

export default class DayNames extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isToggleOn: true
    };
  }

  handleClick = e => {
    this.setState(prevState => ({
      isToggleOn: { ...prevState.isToggleOn, [e]: !prevState.isToggleOn[e] }
    }));
  };

  render() {
    //Getting number of days of month
    const month = new Date().getMonth() + 1;
    const year = new Date().getFullYear();
    const numberDaysOfMonth = new Date(year, month, 0).getDate();

    let foo1 = [];
    for (let i = 1; i <= numberDaysOfMonth; i++) {
      foo1.push(i);
    }

    let foo2 = ["Ops1", "Ops2", "Ops3", "Ops4", "Ops5", "Ops6"];
    const ops = foo2.map((elem, index) => {
      return (

          {elem}
          {foo1.map((cell, i) => {
            return (

 this.handleClick(i)}
              >
                {this.state.isToggleOn[i] ? "Holiday" : cell}

            );
          })}

      );
    });

    return (

{ops}

    );
  }
}

This is link to sandbox .../components/DayNames/DayNames.js
https://codesandbox.io/s/react-toggle-day-0rjop

Body:
Try this code sandbox click here

Or see the below updated component.

import React, { Component } from "react";
import "./DayNames.css";

export default class DayNames extends Component {
  foo2 = ["Ops1", "Ops2", "Ops3", "Ops4", "Ops5", "Ops6"];

  constructor(props) {
    super(props);
    const month = new Date().getMonth() + 1;
    const year = new Date().getFullYear();

    this.state = {
      bgColor: "lightslategrey",
      // isToggleOn: true,
      days: Array(this.foo2.length)
        .fill(0)
        .map(x => Array(new Date(year, month, 0).getDate()).fill(0))
    };
  }

  handleClick = (index, i) => {
    const { days } = this.state;
    days[index][i] = !days[index][i];
    this.setState({
      days
    });
  };

  render() {
    //Getting number of days of month
    const month = new Date().getMonth() + 1;
    const year = new Date().getFullYear();
    const numberDaysOfMonth = new Date(year, month, 0).getDate();

    let foo1 = [];
    for (let i = 1; i <= numberDaysOfMonth; i++) {
      foo1.push(i);
    }

    const ops = this.foo2.map((elem, index) => {
      return (
        <div className="ops_header" key={index}>
          {elem}
          {foo1.map((cell, i) => {
            return (
              <div
                className="operator"
                data-id={cell}
                key={i}
                onClick={() => this.handleClick(index, i)}
              >
                {this.state.days[index][i] ? "Holiday" : cell}
              </div>
            );
          })}
        </div>
      );
    });

    return (
      <div>
        <div className="table">{ops}</div>
      </div>
    );
  }
}

I have updated the code, the bug was that you were not keeping each and every cell state. I have fixed. Check days in the state.


问:
"ResourceNotFound" with 404 for joinedTeams api in graph explorer
I'm playing around with Teams graph APIs in graph explorer

I'm sure I have a team that I've joined.

However, graph explorer continue to return

```<code>{
    "error": {
        "code": "ResourceNotFound",
        "message": "Resource not found.",
        "innerError": {
            "request-id": "bab26952-190e-4670-844c-f9ed3aec9cb2",
            "date": "2020-02-14T16:57:34"
        }
    }
}
</code>```

with 404 status code after I authenticated with my own account.
What should I do to fix this?

Graph explorer works well when I'm not logged in but breaks like provided when I do.

There is another thread asked on SOF that maybe related, however the explanation is unclear and I'm unable to figure out what they're talking about.

If it is a permission problem, how do I resolve it in graph explorer? Is it achievable?

The permission Tab is as following.

答: It's not actually Consented - you need to click the blue "Consent" button (yes, it's a button). When you do so, it will change to just plain text, italicized: Consented

Body:
I'm playing around with Teams graph APIs in graph explorer

I'm sure I have a team that I've joined.

However, graph explorer continue to return

{
    "error": {
        "code": "ResourceNotFound",
        "message": "Resource not found.",
        "innerError": {
            "request-id": "bab26952-190e-4670-844c-f9ed3aec9cb2",
            "date": "2020-02-14T16:57:34"
        }
    }
}

with 404 status code after I authenticated with my own account.
What should I do to fix this?

Graph explorer works well when I'm not logged in but breaks like provided when I do.

There is another thread asked on SOF that maybe related, however the explanation is unclear and I'm unable to figure out what they're talking about.

If it is a permission problem, how do I resolve it in graph explorer? Is it achievable?

The permission Tab is as following.


答:
There a lot of ways to do that, in my solution I used Set which gives O(1) complexity
when setting, adding and deleting toggled days, which is exactly what you need:

```<code>import React, { Component } from "react";
import "./DayNames.css";

export default class DayNames extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bgColor: "lightslategrey",
      toggledDays: new Set()
    };
  }

  createDayId = (columnIndex, rowIndex) => `${columnIndex}-${rowIndex}`;

  handleClick = (columnIndex, rowIndex) => {
    this.setState(prevState => {
      const prevToggledDays = prevState.toggledDays;
      const dayId = this.createDayId(columnIndex, rowIndex);
      if (this.isDayToggled(columnIndex, rowIndex)) {
        prevToggledDays.delete(dayId);
      } else {
        prevToggledDays.add(dayId);
      }
      return { toggledDays: prevToggledDays };
    });
  };

  isDayToggled = (columnIndex, rowIndex) => {
    const dayId = this.createDayId(columnIndex, rowIndex);
    return this.state.toggledDays.has(dayId);
  };

  render() {
    //Getting number of days of month
    const month = new Date().getMonth() + 1;
    const year = new Date().getFullYear();
    const numberDaysOfMonth = new Date(year, month, 0).getDate();

    let foo1 = [];
    for (let i = 1; i <= numberDaysOfMonth; i++) {
      foo1.push(i);
    }

    let foo2 = ["Ops1", "Ops2", "Ops3", "Ops4", "Ops5", "Ops6"];
    const ops = foo2.map((elem, columnIndex) => {
      return (
        <div className="ops_header" key={columnIndex}>
          {elem}
          {foo1.map((cell, rowIndex) => {
            return (
              <div
                className="operator"
                data-id={cell}
                key={rowIndex}
                onClick={() => this.handleClick(columnIndex, rowIndex)}
              >
                {this.isDayToggled(columnIndex, rowIndex) ? "Holiday" : cell}
              </div>
            );
          })}
        </div>
      );
    });

    return (
      <div>
        <div className="table">{ops}</div>
      </div>
    );
  }
}

</code>```

Yet sometime it's dangerous to relay on indexes, but it seems suitable in your case

Hope it helps <3

Title: How to toggle a single element from nested map iteration in react

Body:
There a lot of ways to do that, in my solution I used Set which gives O(1) complexity
when setting, adding and deleting toggled days, which is exactly what you need:

import React, { Component } from "react";
import "./DayNames.css";

export default class DayNames extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bgColor: "lightslategrey",
      toggledDays: new Set()
    };
  }

  createDayId = (columnIndex, rowIndex) => `${columnIndex}-${rowIndex}`;

  handleClick = (columnIndex, rowIndex) => {
    this.setState(prevState => {
      const prevToggledDays = prevState.toggledDays;
      const dayId = this.createDayId(columnIndex, rowIndex);
      if (this.isDayToggled(columnIndex, rowIndex)) {
        prevToggledDays.delete(dayId);
      } else {
        prevToggledDays.add(dayId);
      }
      return { toggledDays: prevToggledDays };
    });
  };

  isDayToggled = (columnIndex, rowIndex) => {
    const dayId = this.createDayId(columnIndex, rowIndex);
    return this.state.toggledDays.has(dayId);
  };

  render() {
    //Getting number of days of month
    const month = new Date().getMonth() + 1;
    const year = new Date().getFullYear();
    const numberDaysOfMonth = new Date(year, month, 0).getDate();

    let foo1 = [];
    for (let i = 1; i <= numberDaysOfMonth; i++) {
      foo1.push(i);
    }

    let foo2 = ["Ops1", "Ops2", "Ops3", "Ops4", "Ops5", "Ops6"];
    const ops = foo2.map((elem, columnIndex) => {
      return (
        <div className="ops_header" key={columnIndex}>
          {elem}
          {foo1.map((cell, rowIndex) => {
            return (
              <div
                className="operator"
                data-id={cell}
                key={rowIndex}
                onClick={() => this.handleClick(columnIndex, rowIndex)}
              >
                {this.isDayToggled(columnIndex, rowIndex) ? "Holiday" : cell}
              </div>
            );
          })}
        </div>
      );
    });

    return (
      <div>
        <div className="table">{ops}</div>
      </div>
    );
  }
}

Yet sometime it's dangerous to relay on indexes, but it seems suitable in your case

Hope it helps <3


问:
Access model name in Django CreateView from template
I'm using the generic CRUD views in Django 1.6, e.g.:

```<code>class KanriCreateView(CreateView):
    template_name = 'generic_form.html'

class KanriUpdateView(UpdateView):
    template_name = 'generic_form.html'
</code>```

etc.

N.B. These are classes used as a base class which I subclass inside views.py files throughout the project.

In order to keep DRY I'm writing a generic form template for all create/update views.

For update views, I have access to object in the template, which is the instance I am updating. I then use object.__class__.__name__ (via a custom filter) to get the name of the class (so I can have automatically generated custom buttons like "Add User", "Add Role".etc so the forms look less...generic.

Of course, when I'm using my template in CreateView, object does not exist (as it has not been created), so my custom buttons.etc do not work, and I get a VariableDoesNotExist exception.

Does Django provide the class somewhere so I can use it in the template?

答:
I propose a solution updated for Django 2 and 3: retrieve the model verbose name from the ModelForm associated to the CreateView.

```<code>class YourCreateView(CreateView):

    form_class = YourModelForm

    def get_context_data(self, **kwargs):
        """Add the models verbose name to the context dictionary."""

        kwargs.update({
            "verbose_name": self.form_class._meta.model._meta.verbose_name,})
        return super().get_context_data(**kwargs)
</code>```

Now you can use {{ verbose_name }} inside your template.

Please, remark the double _meta in the code snippet above: the first is meant to access the model from the ModelForm, while the second accesses the verbose name of the Model.

As with internationalization, remark that if your model uses ugettext as shown below, then the verbose name will automatically be translated in the template.

```<code>from django.utils.translation import ugettext_lazy as _

class MyModel(models.Model):
    class Meta:
        verbose_name = _("your verbose name")
</code>```

Body:
I'm using the generic CRUD views in Django 1.6, e.g.:

class KanriCreateView(CreateView):
    template_name = 'generic_form.html'

class KanriUpdateView(UpdateView):
    template_name = 'generic_form.html'

etc.

N.B. These are classes used as a base class which I subclass inside views.py files throughout the project.

In order to keep DRY I'm writing a generic form template for all create/update views.

For update views, I have access to object in the template, which is the instance I am updating. I then use object.__class__.__name__ (via a custom filter) to get the name of the class (so I can have automatically generated custom buttons like "Add User", "Add Role".etc so the forms look less...generic.

Of course, when I'm using my template in CreateView, object does not exist (as it has not been created), so my custom buttons.etc do not work, and I get a VariableDoesNotExist exception.

Does Django provide the class somewhere so I can use it in the template?

Body:
I propose a solution updated for Django 2 and 3: retrieve the model verbose name from the ModelForm associated to the CreateView.

class YourCreateView(CreateView):

    form_class = YourModelForm

    def get_context_data(self, **kwargs):
        """Add the models verbose name to the context dictionary."""

        kwargs.update({
            "verbose_name": self.form_class._meta.model._meta.verbose_name,})
        return super().get_context_data(**kwargs)

Now you can use {{ verbose_name }} inside your template.

Please, remark the double _meta in the code snippet above: the first is meant to access the model from the ModelForm, while the second accesses the verbose name of the Model.

As with internationalization, remark that if your model uses ugettext as shown below, then the verbose name will automatically be translated in the template.

from django.utils.translation import ugettext_lazy as _

class MyModel(models.Model):
    class Meta:
        verbose_name = _("your verbose name")


问:
jsoup remove outer html tag - code HTML element
This seems pretty straightforward but, obviously I'm doing something wrong.  Here is my HTML - I am trying to create both singular code tags and nested code tags under pre tags - the resulting content will be "one line boxes with code inside" and also with the pre tags "big boxes with code inside".  There are also empty paragraph tags that I can't get rid of using the standard methods - element remove after testing for no Text in the paragraph.  Here's the input

```<code>        <h1>Module Description and Learning Objectives</h1>
        <p>
        </p>
        ```

        2020-02-13 12:49:15 DEBUG StackTraceElement:48 -

        2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.title

        2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.id=1

        ```
        <p>Sentence 1</p>
        <p>
        <code>System.out.println("id:"+element.attr("id"));</code>
        </p>
        <p>Sentence 2</p>
        <p>
        <code>System.out.println("src:"+element.attr("src"));</code>
        </p>
        <p>Sentence 3</p>
        <p>
        <code>System.out.println("alt:"+element.attr("alt"));</code>
        </p>
        <p>
        </p>
</code>```

This is my code (don't follow names as much as constructs, mid-code names   :)

```<code>          Elements pWithCodeTagList = docXMLformat.select("code");
          if (pWithCodeTagList.size() > 0) {
              for (Element pTag : pWithCodeTagList) {
                   System.out.println("pTag=" + pTag.text() + " " + pTag.tagName());
                   pTag.unwrap();
              }
          }
</code>```

Here is the output in eclipse - I am indeed selecting the code tags and expecting the parent p to disappear

```<code> pTag=2020-02-13 12:49:15 DEBUG StackTraceElement:48 - code
 pTag=2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.title code
 pTag=2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.id=1 code
 pTag=System.out.println("id:"+element.attr("id")); code
 pTag=System.out.println("src:"+element.attr("src")); code
 pTag=System.out.println("alt:"+element.attr("alt")); code
</code>```

This is the result:  I expected the paragraph tags to disappear, not the code tags!

```<code>   <h1>Module Description and Learning Objectives</h1>
                <p>
                </p>
                ```

                    2020-02-13 12:49:15 DEBUG StackTraceElement:48 -

                    2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.title

                    2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.id=1

                ```
                <p>Sentence 1</p>
                <p> System.out.println("id:"+element.attr("id")); </p>
                <p>Sentence 2</p>
                <p> System.out.println("src:"+element.attr("src")); </p>
                <p>Sentence 3</p>
                <p> System.out.println("alt:"+element.attr("alt")); </p>
                <p>
                </p>
</code>```

I already touch this area of my document, I've removed a span tag around the code tag prior to this, and had to remove all the line control characters from the line content, maybe PRE and CODE don't work like other tags - I know they are not supposed to, but ...   also, I'm trying to keep the tags and content on the same line so my "code boxes" are as slim as possible, towit:

```<code> ```
 2020-02-13 12:49:15 DEBUG StackTraceElement:48 -
 2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.title
 2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.id=1
  ```
  <p>Sentence 1</p>
  <code>System.out.println("id:"+element.attr("id"));</code>
  <p>Sentence 2</p>
  <code>System.out.println("src:"+element.attr("src"));</code>
  <p>Sentence 3</p>
  <code>System.out.println("alt:"+element.attr("alt"));</code>
</code>```

答:
Your selector is selecting the code elements, not the p elements, which is why they're getting removed. You should select the p elements that have a code tag, and unwrap() those. p:has(code)

Also, you don't need to iterate them and call unwrap on each if you want to unwrap them all (unless you want to do extra logic for each one). You can just call Elements#upwrap()

```<code>Elements pWithCodeTagList = docXMLformat.select("p:has(code)");
pWithCodeTagList.unwrap();
</code>```

And to find the empty p tags, you could use the :matches selector which does a regex over the text, and just look for spaces or nothing: p:matches(^\s?$)

```<code>Elements emptyPs = docXMLformat.select("p:matches(^\\s?$)");
emptyPs.remove();
</code>```

Body:
This seems pretty straightforward but, obviously I'm doing something wrong.  Here is my HTML - I am trying to create both singular code tags and nested code tags under pre tags - the resulting content will be "one line boxes with code inside" and also with the pre tags "big boxes with code inside".  There are also empty paragraph tags that I can't get rid of using the standard methods - element remove after testing for no Text in the paragraph.  Here's the input

Module Description and Learning Objectives

        2020-02-13 12:49:15 DEBUG StackTraceElement:48 -

        2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.title

        2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.id=1

Sentence 1

        System.out.println("id:"+element.attr("id"));

Sentence 2

        System.out.println("src:"+element.attr("src"));

Sentence 3

        System.out.println("alt:"+element.attr("alt"));

This is my code (don't follow names as much as constructs, mid-code names   :)

          Elements pWithCodeTagList = docXMLformat.select("code");
          if (pWithCodeTagList.size() > 0) {
              for (Element pTag : pWithCodeTagList) {
                   System.out.println("pTag=" + pTag.text() + " " + pTag.tagName());
                   pTag.unwrap();
              }
          }

Here is the output in eclipse - I am indeed selecting the code tags and expecting the parent p to disappear

 pTag=2020-02-13 12:49:15 DEBUG StackTraceElement:48 - code
 pTag=2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.title code
 pTag=2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.id=1 code
 pTag=System.out.println("id:"+element.attr("id")); code
 pTag=System.out.println("src:"+element.attr("src")); code
 pTag=System.out.println("alt:"+element.attr("alt")); code

This is the result:  I expected the paragraph tags to disappear, not the code tags!

Module Description and Learning Objectives

                    2020-02-13 12:49:15 DEBUG StackTraceElement:48 -

                    2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.title

                    2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.id=1

Sentence 1

 System.out.println("id:"+element.attr("id"));

Sentence 2

 System.out.println("src:"+element.attr("src"));

Sentence 3

 System.out.println("alt:"+element.attr("alt"));

I already touch this area of my document, I've removed a span tag around the code tag prior to this, and had to remove all the line control characters from the line content, maybe PRE and CODE don't work like other tags - I know they are not supposed to, but ...   also, I'm trying to keep the tags and content on the same line so my "code boxes" are as slim as possible, towit:

 2020-02-13 12:49:15 DEBUG StackTraceElement:48 -
 2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.title
 2020-02-13 12:49:15 DEBUG StackTraceElement:48 - sects.id=1

Sentence 1

  System.out.println("id:"+element.attr("id"));

Sentence 2

  System.out.println("src:"+element.attr("src"));

Sentence 3

  System.out.println("alt:"+element.attr("alt"));

Body:
Your selector is selecting the code elements, not the p elements, which is why they're getting removed. You should select the p elements that have a code tag, and unwrap() those. p:has(code)

Also, you don't need to iterate them and call unwrap on each if you want to unwrap them all (unless you want to do extra logic for each one). You can just call Elements#upwrap()

Elements pWithCodeTagList = docXMLformat.select("p:has(code)");
pWithCodeTagList.unwrap();

And to find the empty p tags, you could use the :matches selector which does a regex over the text, and just look for spaces or nothing: p:matches(^\s?$)

Elements emptyPs = docXMLformat.select("p:matches(^\\s?$)");
emptyPs.remove();


问:
javascript regular expression
How do you write a JS regular expression to extract the first "2" from "/?page=2&promo_id=1234". (ie page number 2)

Thanks!

答:
This should do the trick. </p>

```<code>var match = /page=(\d+)/.exec("/?page=2&promo_id=1234"), pageNum = match[1];
</code>```

Title: javascript regular expression

Body:
This should do the trick.

var match = /page=(\d+)/.exec("/?page=2&promo_id=1234"), pageNum = match[1];


问:
A filter method in React isn't working while a map is
I am using a ternary check in React. If an item exists, it triggers a .map method, and if it doesn't it triggers a .filter method. The map is working fine, but the filter is not. It is throwing an error saying that an object is not a valid React child, and to use an array. However, to my understanding, it IS an array...</p>

```<code> {test.searchTerm === ""
            ? test.users.map((item, index) => (
                <>
                  <tr>
                    <td>{index + 1}</td>
                    <td>{item.name.first + " " + item.name.last}</td>
                    <td>{item.email}</td>
                    <td>{item.gender}</td>
                    <td>{item.phone}</td>
                    <td>
                      <img src={item.picture.thumbnail} alt=""></img>
                    </td>
                  </tr>
                </>
              ))
            : test.users.filter((item, index) => {
              //console.log(test.users)
                if (
                  test.searchTerm === item.name.first ||
                  test.searchTerm === item.name.last ||
                  test.searchTerm === item.name.first + " " + item.name.last
                ) {

                  return (
                    <>
                      <tr>
                        <td>{index + 1}</td>
                        <td>{item.name.first + " " + item.name.last}</td>
                        <td>{item.email}</td>
                        <td>{item.gender}</td>
                        <td>{item.phone}</td>
                        <td>
                          <img src={item.picture.thumbnail} alt=""></img>
                        </td>
                      </tr>
                    </>
                  );
                }
              })}
</code>```

答:
In JavaScript filter is used to create a new array base on the condition. Your filter method should return true for matching element and false other wise. After that you have to map the resulting filtered array. After filter you still have an array of objects.

{test.searchTerm === ""
            ? test.users.map((item, index) => (
                <>

                    {index + 1}
                    {item.name.first + " " + item.name.last}
                    {item.email}
                    {item.gender}
                    {item.phone}

                </>
              ))
            : test.users.filter((item, index) => {
              //console.log(test.users)
                if (
                  test.searchTerm === item.name.first ||
                  test.searchTerm === item.name.last ||
                  test.searchTerm === item.name.first + " " + item.name.last
                ) {

                  return true;
                }
                return false
              }).map(item => (
                    <>

                        {index + 1}
                        {item.name.first + " " + item.name.last}
                        {item.email}
                        {item.gender}
                        {item.phone}

                    </>
              ))}
```

Body:
I am using a ternary check in React. If an item exists, it triggers a .map method, and if it doesn't it triggers a .filter method. The map is working fine, but the filter is not. It is throwing an error saying that an object is not a valid React child, and to use an array. However, to my understanding, it IS an array...

 {test.searchTerm === ""
            ? test.users.map((item, index) => (
                <>

                    {index + 1}
                    {item.name.first + " " + item.name.last}
                    {item.email}
                    {item.gender}
                    {item.phone}

                </>
              ))
            : test.users.filter((item, index) => {
              //console.log(test.users)
                if (
                  test.searchTerm === item.name.first ||
                  test.searchTerm === item.name.last ||
                  test.searchTerm === item.name.first + " " + item.name.last
                ) {

                  return (
                    <>

                        {index + 1}
                        {item.name.first + " " + item.name.last}
                        {item.email}
                        {item.gender}
                        {item.phone}

                    </>
                  );
                }
              })}

Body:
In JavaScript filter is used to create a new array base on the condition. Your filter method should return true for matching element and false other wise. After that you have to map the resulting filtered array. After filter you still have an array of objects.

{test.searchTerm === ""
            ? test.users.map((item, index) => (
                <>
                  <tr>
                    <td>{index + 1}</td>
                    <td>{item.name.first + " " + item.name.last}</td>
                    <td>{item.email}</td>
                    <td>{item.gender}</td>
                    <td>{item.phone}</td>
                    <td>
                      <img src={item.picture.thumbnail} alt=""></img>
                    </td>
                  </tr>
                </>
              ))
            : test.users.filter((item, index) => {
              //console.log(test.users)
                if (
                  test.searchTerm === item.name.first ||
                  test.searchTerm === item.name.last ||
                  test.searchTerm === item.name.first + " " + item.name.last
                ) {

                  return true;
                }
                return false
              }).map(item => (
                    <>
                      <tr>
                        <td>{index + 1}</td>
                        <td>{item.name.first + " " + item.name.last}</td>
                        <td>{item.email}</td>
                        <td>{item.gender}</td>
                        <td>{item.phone}</td>
                        <td>
                          <img src={item.picture.thumbnail} alt=""></img>
                        </td>
                      </tr>
                    </>
              ))}


问:
How to match different groups in regex
I have the following string:

```<code>"Josua de Grave* (1643-1712)"
</code>```

Everything before the * is the person's name, the first date 1634 is his birth date, 1712 is the date of his death.

Following this logic I'd like to have 3 match groups for each one of the item. I tried

```<code>([a-zA-Z|\s]*)\* (\d{3,4})-(\d{3,4})
</code>```

```<code>"Josua de Grave* (1643-1712)".match(/([a-zA-Z|\s]*)\* (\d{3,4})-(\d{3,4})/)
</code>```

but that returns nil.

Why is my logic wrong, and what should I do to get the 3 intended match groups.

答:
The additional brackets ( ) around the digit 1643-1712 values needs to be added in your regex pattern so use

```<code>([a-zA-Z\s]*)\* \((\d{3,4})-(\d{3,4})\)
//               ^^                   ^^
</code>```

since brackets represents the captured group so escape them using \ to match them as a character.

Title: How to match different groups in regex

Body:
I have the following string:

"Josua de Grave* (1643-1712)"

Everything before the * is the person's name, the first date 1634 is his birth date, 1712 is the date of his death.

Following this logic I'd like to have 3 match groups for each one of the item. I tried

([a-zA-Z|\s]*)\* (\d{3,4})-(\d{3,4})

"Josua de Grave* (1643-1712)".match(/([a-zA-Z|\s]*)\* (\d{3,4})-(\d{3,4})/)

but that returns nil.

Why is my logic wrong, and what should I do to get the 3 intended match groups.

Body:
The additional brackets ( ) around the digit 1643-1712 values needs to be added in your regex pattern so use

([a-zA-Z\s]*)\* \((\d{3,4})-(\d{3,4})\)
//               ^^                   ^^

since brackets represents the captured group so escape them using \ to match them as a character.


答:
It's easy you should use Modulo operation like this : </p>

```<code>public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    int hours = in.nextInt();
    int minutes = in.nextInt();

    minutes = minutes + 15;
    hours += minutes / 60;
    minutes = minutes % 60;

    System.out.printf("%d:%02d", hours, minutes);
}
</code>```

Title: How can I add 15 minutes to time and handle overflow?

Body:
It's easy you should use Modulo operation like this :

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    int hours = in.nextInt();
    int minutes = in.nextInt();

    minutes = minutes + 15;
    hours += minutes / 60;
    minutes = minutes % 60;

    System.out.printf("%d:%02d", hours, minutes);
}


问:
Recoding a string variable (e.g. "815") to a time variable (08:15) in R
I am looking for help recoding a string variable to be correctly formatted as a time variable using r. I have daily diary data for ~ 450 individuals, over the course of a week. They self-reported their bed and wake times, and I am trying to do 2 things with the data 1) see how bed and wake times vary over the course of the week, and 2) calculate 'sleep duration'; the number of hours that elapses between these bed and wake times.

My problem is finding a way to reformat the data. The bed and wake times are currently string variables, with no colon between hh and mm ("815" would mean 8:15 AM; "2345" would mean 11:45 PM; "15" would mean 12:15 AM). I don't necessarily care about getting the AM/PM in there, it's fine if everything gets reformatted to something like "23:45".

I cannot figure out which package/function/creative workaround would best be able to help with this. I did see some packages like chron or lubridate, but those functions seem like they would be more helpful for my second problem, calculating the time difference between the two variables. But I do need help recoding this string variable to something usable.

Thank you for any advice or help!!!

答:
We can pad 0 to make the width 4 and then use as.ITime to convert to Time class

```<code>library(stringr)
library(data.table)
out <- as.ITime(str_replace(str_pad("815", width = 4, pad = 0), "(\\d{2})", "\\1:"))
str(out)
#'ITime' int 08:15:00
out
#[1] "08:15:00"
</code>```

Or using base R

```<code>strptime(sub("(\\d{2})", "\\1:", sprintf("%04s", "815")), format = '%H:%M')
#[1] "2020-02-15 08:15:00 EST"
</code>```

Body:
We can pad 0 to make the width 4 and then use as.ITime to convert to Time class

library(stringr)
library(data.table)
out <- as.ITime(str_replace(str_pad("815", width = 4, pad = 0), "(\\d{2})", "\\1:"))
str(out)
#'ITime' int 08:15:00
out
#[1] "08:15:00"

Or using base R

strptime(sub("(\\d{2})", "\\1:", sprintf("%04s", "815")), format = '%H:%M')
#[1] "2020-02-15 08:15:00 EST"


问:
How to create a blank image with a specified size in Flutter
I want to create a blank image with a white background and a specified size in Flutter, then I may add other images onto this blank image later to merge them as a new image.
I am working on my first Flutter project and still learning new things by doing this project.
Thanks for any hint.

Update: The blank image here means an Image with only white color in it.

答:
For your "blank image", you can use a widget Card.

For the size of it, you can try using the widget AspectRatio.
It allows you to set its size relative to the parent size with proportions.

If you want a specified size no matter what's the size of your screen, I can't really help you.

You can refer to the answer of this question too:
Changing Aspect Ratio of Image in Flutter
Even if it's not for a real image, the widget disposition in this example can help you I think.

For any doupt and for your personnal knowledge, here is the Flutter widget catalog site.


问:
Why does Visual Studio 2010 have rendering problems in VMware?
We were testing our WPF application on Windows XP in the VMware Player (with VMware Tools) and noticed that dropdowns were buggy in that all the choices would appear when you clicked on the ComboBox but as you moused over them they would disappear.

We then noticed that Visual Studio Express 2010 has the exact same problem with its menus.

Here a menu item is hanging by itself in the middle of the screen:

Here a menu item is stretched:

We have WMware Tools installed:

We would definitely like to get our application to work without these bugs in VMware. Has anyone experienced these problems and know if it is a problem with VMware, XP, WPF, or WPF 4.0?

答: I read this post to install two patches for Visual Studio 2010 and WPF. This solves the problem.</p>


问:
Somehow combine with search controller not working, any idea?
For some reason when I type in the search field it does not print out Xcode console the "str". What am I missing here? I followed his tutorial https://www.letsbuildthatapp.com/course_video?id=5232</p>

```<code>import UIKit

class SearchViewController: UIViewController {

    let searchController = UISearchController(searchResultsController: nil)

    var sink: Any?

    override func viewDidLoad() {
        super.viewDidLoad()

        setupSearchBarListener()

        navigationItem.searchController = searchController

        navigationController?.navigationBar.prefersLargeTitles = true
        navigationItem.title = "Contact"

        searchController.obscuresBackgroundDuringPresentation = false

        view.backgroundColor = .white
    }

    fileprivate func setupSearchBarListener() {

        let publisher = NotificationCenter.default.publisher(for: UISearchTextField.textDidChangeNotification, object: searchController.searchBar.searchTextField)
        publisher
            .map {
            ($0.object as! UISearchTextField).text
        }
            .debounce(for: .milliseconds(500), scheduler: RunLoop.main)
            .sink { (str) in
                print(str ?? "")
        }

    }
}
</code>```

答:
You are creating a Sink object with the .sink method, but you are not storing it anywhere. Therefore it goes out of existence immediately and there is no pipeline to publish to.

The correct procedure here is to have an instance property typed as Set<AnyCancellable> and call store(in:) on your sink to store it in that instance property. Now it will persist and there will be something to print out.

Body:
For some reason when I type in the search field it does not print out Xcode console the "str". What am I missing here? I followed his tutorial https://www.letsbuildthatapp.com/course_video?id=5232

import UIKit

class SearchViewController: UIViewController {

    let searchController = UISearchController(searchResultsController: nil)

    var sink: Any?

    override func viewDidLoad() {
        super.viewDidLoad()

        setupSearchBarListener()

        navigationItem.searchController = searchController

        navigationController?.navigationBar.prefersLargeTitles = true
        navigationItem.title = "Contact"

        searchController.obscuresBackgroundDuringPresentation = false

        view.backgroundColor = .white
    }

    fileprivate func setupSearchBarListener() {

        let publisher = NotificationCenter.default.publisher(for: UISearchTextField.textDidChangeNotification, object: searchController.searchBar.searchTextField)
        publisher
            .map {
            ($0.object as! UISearchTextField).text
        }
            .debounce(for: .milliseconds(500), scheduler: RunLoop.main)
            .sink { (str) in
                print(str ?? "")
        }

    }
}