问:
Regex, match one character that is not in a pattern
im parsing a csv file with javascript, that file styles the cells with commas in the numbered values.
when parsing it to javascript i get the entire row as one string where the cells are divided by commas, as such:

```<code>2, some text,9740127,"₪ 38,850.00","₪ 5,550.00","₪ 28,305","₪ 4,995",22/05/2020
</code>```

in order to parse the files and create an object from every row i need to match the commas that are Not part of a number, so the end result is:

```<code>2
some text
9740127
₪ 38,850.00
₪ 5,550.00
₪ 28,305
₪ 4,995
22/05/2020
</code>```

i tried matching the commas inside the numbers in hopes to negate it afterwards with that regex:(".\s\d+,\d+[.]?[\d]+")
but i cant seem to target the other commas instead afterwards.

i feel like im close but i cant seem to figure it out, would appreciate the help!
Thanks

答:
Assuming the double quotes are in the right format, one option might be to split on a comma while asserting what is on the right is not " followed by either a comma or the end of the string.

```<code>, *(?!(?:[^"]|\\")*"(?:,|$))
</code>```

Regex demo

let str = '2, some text,9740127,"₪ 38,850.00","₪ 5,550.00","₪ 28,305","₪ 4,995",22/05/2020'

console.log(str.split(/, *(?!(?:[^"]|\\")*"(?:,|$))/g));```

Body:
im parsing a csv file with javascript, that file styles the cells with commas in the numbered values.
when parsing it to javascript i get the entire row as one string where the cells are divided by commas, as such:

2, some text,9740127,"₪ 38,850.00","₪ 5,550.00","₪ 28,305","₪ 4,995",22/05/2020

in order to parse the files and create an object from every row i need to match the commas that are Not part of a number, so the end result is:

2
some text
9740127
₪ 38,850.00
₪ 5,550.00
₪ 28,305
₪ 4,995
22/05/2020

i tried matching the commas inside the numbers in hopes to negate it afterwards with that regex:(".\s\d+,\d+[.]?[\d]+")
but i cant seem to target the other commas instead afterwards.

i feel like im close but i cant seem to figure it out, would appreciate the help!
Thanks

Body:
Assuming the double quotes are in the right format, one option might be to split on a comma while asserting what is on the right is not " followed by either a comma or the end of the string.

, *(?!(?:[^"]|\\")*"(?:,|$))

Regex demo

let str = '2, some text,9740127,"₪ 38,850.00","₪ 5,550.00","₪ 28,305","₪ 4,995",22/05/2020'

console.log(str.split(/, *(?!(?:[^"]|\\")*"(?:,|$))/g));


来源: stackexchange

问:
Return value from .then method
Goal of the code below is to replace some links with data fetched from API.

const articleData = '
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in data-embed=\"Instagram\" href=\"https://www.instagram.com/p/CAttGmVIIAS/\">reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
'

const article = document.createElement('div')

article.innerHTML = articleData;

[...article.querySelectorAll('[data-embed=Instagram]')].forEach(link => {
    fetch(`https://api.instagram.com/oembed/?maxwidth=400&url=${link.href}`)
    .then(response => {
        if (response.ok) {
            return response.json()
        }
        throw response.error
    })
    .then(json => {
        const instagramHtml = document.createElement('div')
        instagramHtml.innerHTML = json.html
        console.log(link.parentNode)
        link.parentNode.replaceChild(instagramHtml, link)
    })
})```

Everything works fine until it comes to replacing. It basically happens, but only within .then
method. How could I return from it?

Thank you!

答:
You can do something like this:

```<code>async function doSomething(){
const articleData = '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor <a data-embed=\"Instagram\" href=\"https://www.instagram.com/p/CAttGmVIIAS/">incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in <a data-embed=\"Instagram\" href=\"https://www.instagram.com/p/CAttGmVIIAS/\">reprehenderit</a> in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>'

    const article = document.createElement('div')

    article.innerHTML = articleData;

        for (const link of [...article.querySelectorAll('[data-embed=Instagram]')]) {
        let response = await fetch(`https://api.instagram.com/oembed/?maxwidth=400&url=${link.href}`);
            if (response.ok) {

            const instagramHtml = document.createElement('div')
            instagramHtml.innerHTML = response.json().html
            console.log(link.parentNode)
            link.parentNode.replaceChild(instagramHtml, link)
            }
        }
</code>```

You have to forget forEach as it triggers multiple async calls without returing in sequence. Instead you will use modern for ... of loop, as mentioned in this stackoverflow question.

ContentLicense: CC BY-SA 4.0

Title: Return value from .then method

Body:
Goal of the code below is to replace some links with data fetched from API.

const articleData = '
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
'

const article = document.createElement('div')

article.innerHTML = articleData;

[...article.querySelectorAll('[data-embed=Instagram]')].forEach(link => {
    fetch(`https://api.instagram.com/oembed/?maxwidth=400&url=${link.href}`)
    .then(response => {
        if (response.ok) {
            return response.json()
        }
        throw response.error
    })
    .then(json => {
        const instagramHtml = document.createElement('div')
        instagramHtml.innerHTML = json.html
        console.log(link.parentNode)
        link.parentNode.replaceChild(instagramHtml, link)
    })
})

Everything works fine until it comes to replacing. It basically happens, but only within .then
method. How could I return from it?

Thank you!

Body:
You can do something like this:

async function doSomething(){
const articleData = '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor <a data-embed=\"Instagram\" href=\"https://www.instagram.com/p/CAttGmVIIAS/">incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in <a data-embed=\"Instagram\" href=\"https://www.instagram.com/p/CAttGmVIIAS/\">reprehenderit</a> in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>'

    const article = document.createElement('div')

    article.innerHTML = articleData;

        for (const link of [...article.querySelectorAll('[data-embed=Instagram]')]) {
        let response = await fetch(`https://api.instagram.com/oembed/?maxwidth=400&amp;url=${link.href}`);
            if (response.ok) {

            const instagramHtml = document.createElement('div')
            instagramHtml.innerHTML = response.json().html
            console.log(link.parentNode)
            link.parentNode.replaceChild(instagramHtml, link)
            }
        }

You have to forget forEach as it triggers multiple async calls without returing in sequence. Instead you will use modern for ... of loop, as mentioned in this stackoverflow question.


问:
How to return a value of int from a method that is created using Function?
Say, I have:

```<code>int Function(int x, int y) add() {
  return x + y; // Error
}
</code>```

PS: I know I can use

```<code>int add(int x, int y) => x + y;
</code>```

but I want to use a Function here, you may want to check this and this thread to get an idea what is the main requirement.

答:
You are not returning a function but the result of x + y. You need to do this instead:

```<code>int Function(int x, int y) add = (x, y) {
  return x + y;
};
</code>```

Which can be used like a normal function:

```<code>print(add(1,2)); // 3
</code>```

This will make add a variable to a function which takes two int arguments and returning the sum.

Or if you want to have a method which returns a method:

```<code>int Function(int x, int y) add() {
  return (x, y) {
    return x + y;
  };
}
</code>```

Which are used like:

```<code>print(add()(1,2)); // 3
</code>```

With the last example you can do something like this to construct a function based on input to e.g. have some default parameters you want to set one time:

```<code>int Function(int x, int y) add(int alwaysAdd) {
  return (x, y) {
    return x + y + alwaysAdd;
  };
}

void main() {
  final addMethod = add(10);

  print(addMethod(1,2)); // 13
  print(addMethod(5,5)); // 20
}
</code>```

Body:
Say, I have:

int Function(int x, int y) add() {
  return x + y; // Error
}

PS: I know I can use

int add(int x, int y) => x + y;

but I want to use a Function here, you may want to check this and this thread to get an idea what is the main requirement.

Body:
You are not returning a function but the result of x + y. You need to do this instead:

int Function(int x, int y) add = (x, y) {
  return x + y;
};

Which can be used like a normal function:

print(add(1,2)); // 3

This will make add a variable to a function which takes two int arguments and returning the sum.

Or if you want to have a method which returns a method:

int Function(int x, int y) add() {
  return (x, y) {
    return x + y;
  };
}

Which are used like:

print(add()(1,2)); // 3

With the last example you can do something like this to construct a function based on input to e.g. have some default parameters you want to set one time:

int Function(int x, int y) add(int alwaysAdd) {
  return (x, y) {
    return x + y + alwaysAdd;
  };
}

void main() {
  final addMethod = add(10);

  print(addMethod(1,2)); // 13
  print(addMethod(5,5)); // 20
}


问:
I got some errors for implementation of GeneticAlgo
I am trying to make a time table scheduling program but found some errors. Please watch the following code and solve that error please.

Errors

These are the following errors

```<code>Traceback (most recent call last):
  File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 367, in <module>
    population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
  File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 367, in <lambda>
    population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
  File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 84, in get_fitness
    self._fitness = self.calculate_fitness()
  File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 106, in calculate_fitness
    if classes[i].get_room().get_seatingCapacity() < classes[i].get_course().get_maxNumbOfStudnets():
AttributeError: 'NoneType' object has no attribute 'get_seatingCapacity'
</code>```

Source Code of the Program

Variables:

These are the variables which i declare for this program

```<code>import prettytable as prettytable
import random as rnd
POPULATION_SIZE = 9
NUMB_OF_ELITE_SCHEDULES = 1
TOURNAMENT_SELECTION_SIZE = 3
MUTATION_RATE = 0.1
</code>```

Data Class

That is the first class which name is DATA

```<code>class Data:
    ROOMS = [["R1", 25], ["R2", 45], ["R3", 35]]
    MEETING_TIMES = [
        ["MT1", "MWF 09:00 - 10:00"],
        ["MT2", "MWF 10:00 - 11:00"],
        ["MT3", "TTH 09:00 - 10:30"],
        ["MT4", "TTH 10:30 - 12:00"]
                     ]
    INSTRUCTORS = [
        ["T1", "Dr James Web"],
        ["T2", "Mr Mike Brown"],
        ["T3", "Dr Steve Day"],
        ["T4", "Mrs Jane Doe"]
                   ]
    def __init__(self):
        self._rooms = []
        self._meetingTimes = []
        self._instructors = []
        for i in range(0, len(self.ROOMS)):
            self._rooms.append(Room(self.ROOMS[i][0], self.ROOMS[i][1]))
        for i in range(0, len(self.MEETING_TIMES)):
            self._meetingTimes.append(MeetingTime(self.MEETING_TIMES[i][0], self.MEETING_TIMES[i][1]))
        for i in range(0, len(self.INSTRUCTORS)):
            self._instructors.append(Instructor(self.INSTRUCTORS[i][0], self.INSTRUCTORS[i][1]))

        course1 = Course("C1", "325k", [self._instructors[0], self._instructors[1]], 25)
        course2 = Course("C2", "319k", [self._instructors[0], self._instructors[1], self._instructors[2]], 35)
        course3 = Course("C3", "462k", [self._instructors[0], self._instructors[1]], 25)
        course4 = Course("C4", "464k", [self._instructors[2], self._instructors[3]], 30)
        course5 = Course("C5", "360C", [self._instructors[3]], 35)
        course6 = Course("C6", "303k", [self._instructors[0], self._instructors[2]], 45)
        course7 = Course("C7", "303L", [self._instructors[1], self._instructors[3]], 45)

        self._courses = [course1, course2, course3, course4, course5, course6, course7]

        dept1 = Department("MATH", [course1, course3])
        dept2 = Department("EE", [course2, course4, course5])
        dept3 = Department("PHY", [course6, course7])

        self._depts = [dept1, dept2, dept3]
        self._numberOfClasses = 0

        for i in range(0, len(self._depts)):
            self._numberOfClasses += len(self._depts[i].get_courses())

    def get_rooms(self):
        return self._rooms
    def get_instructors(self):
        return self._instructors
    def get_courses(self):
        return self._courses
    def get_depts(self):
        return self._depts
    def get_meetingTimes(self):
        return self._meetingTimes
    def get_numberOfClasses(self):
        return self._numberOfClasses
</code>```

Schedule Class

That is the second class which name is Schedule

```<code>class Schedule:
    def __init__(self):
        self._data = data
        self._classes = []
        self._numberOfConflicts = 0
        self._fitness = -1
        self._classNumb = 0
        self._isFitnessChanged = True

    def get_classes(self):
        self._isFitnessChanged = True
        return self._classes

    def get_numberOfConflicts(self):
        return self._numberOfConflicts

    def get_fitness(self):
        if(self._isFitnessChanged == True):
            self._fitness = self.calculate_fitness()
            self._isFitnessChanged = False
        return self._fitness

    def initialize(self):
        depts = self._data.get_depts()
        for i in range(0, len(depts)):
            courses = depts[i].get_courses()    #courses in each departments
            for j in range(0, len(courses)):
                newClass = Class(self._classNumb, depts[i], courses[j])
                self._classNumb += 1
                newClass.set_meetingTime(data.get_meetingTimes()[rnd.randrange(0, len(data.get_meetingTimes()))])
                newClass.set_room(data.get_rooms()[rnd.randrange(0, len(data.get_rooms()))])
                newClass.set_instructor(courses[j].get_instructors()[rnd.randrange(0, len(courses[j].get_instructors()))])
                self._classes.append(newClass)
        return self

    def calculate_fitness(self):
        self._numberOfConflicts = 0
        classes = self.get_classes()
        for i in range(0, len(classes)):

            if classes[i].get_room().get_seatingCapacity() < classes[i].get_course().get_maxNumbOfStudnets():
                self._numberOfConflicts += 1
            for j in range(0, len(classes)):
                if(j >= i):
                    if(classes[i].get_meetingTime() == classes[j].get_meetingTime() and
                       classes[i].get_id() != classes[j].get_id()):
                        if(classes[i].get_room() == classes[j].get_room()):
                            self._numberOfConflicts += 1
                        if(classes[i].get_instructor() == classes[j].get_instructor()):
                            self._numberOfConflicts += 1
        return 1 / ((1.0*self._numberOfConflicts + 1))

    def __str__(self):
        # it returns all the classes of schedule separated by comas
        returnValue = ""
        for i in range(0, len(self._classes)):
            returnValue += str(self._classes[i]) + ", "
        returnValue += str(self._classes[len(self._classes)-1])
        return returnValue
</code>```

Population Class

Thats the third class which is Population class

```<code>class Population:
    def __init__(self, size):
        self._size = size
        self._data = data
        self._schedules = []
        for i in range(0, size):
            self._schedules.append(Schedule().initialize())
    def get_schedules(self):
        return self._schedules
</code>```

GeneticAlgorithm Class

Thats the fourth class which is the GeneticAlgorithm class

```<code>class GeneticAlgorithm:
    def evolve(self, population):
        return self._mutate_population(self._crossover_population(population))

    def _crossover_population(self, pop):
        crossover_pop = Population(0)
        for i in range(NUMB_OF_ELITE_SCHEDULES):
            crossover_pop.get_schedules().append(pop.get_schedules()[i])
        i = NUMB_OF_ELITE_SCHEDULES
        while i < POPULATION_SIZE:
            schedule1 = self._select_tournament_population(pop).get_schedules()[0]
            schedule2 = self._select_tournament_population(pop).get_schedules()[0]
            crossover_pop.get_schedules().append(self._crossover_schedule(schedule1, schedule2))
            i += 1
        return crossover_pop
    def _mutate_population(self, population):
        for i in range(NUMB_OF_ELITE_SCHEDULES, POPULATION_SIZE):
            self._mutate_schedule(population.get_schedules()[i])
        return population

    def _crossover_schedule(self, schedule1, schedule2):
        crossoverSchedule = Schedule().initialize()
        for i in range(0, len(crossoverSchedule.get_classes())):
            if (rnd.random() > 0.5):
                crossoverSchedule.get_classes()[i] = schedule1.get_classes()[i]
            else:
                crossoverSchedule.get_classes()[i] = schedule2.get_classes()[i]
        return crossoverSchedule

    def _mutate_schedule(self,mutateSchedule):
        schedule = Schedule().initialize()
        for i in range(0, len(mutateSchedule.get_classes())):
            if(MUTATION_RATE > rnd.random()):
                mutateSchedule.get_classes()[i] = schedule.get_classes()[i]
        return mutateSchedule

    def _select_tournament_population(self, pop):
        tournament_pop = Population(0)
        i = 0
        while i < TOURNAMENT_SELECTION_SIZE:
            tournament_pop.get_schedules().append(pop.get_schedules()[rnd.randrange(0, POPULATION_SIZE)])
            i += 1
        tournament_pop.get_schedules().sort(key=lambda x:x.get_fitness(), reverse=True)
        return tournament_pop
</code>```

Course Class

Thats the fifth class which is the Course class

```<code>class Course:
    def __init__(self, number, name, instructors, maxNumbOfStudents):
        self._number = number
        self._name = name
        self._instructors = instructors
        self._maxNumbOfStudents = maxNumbOfStudents
    def get_name(self):
        return self._name
    def get_number(self):
        return self._number
    def get_instructors(self):
        return self._instructors
    def get_maxNumbOfStudents(self):
        return self._maxNumbOfStudents
    def __str__(self):
        return self._name
</code>```

Instructor Class

Thats the sixth class which is Instructor class

```<code>class Instructor:
    def __init__(self, id, name):
        self._id = id
        self._name = name
    def get_id(self):
        return self._id
    def get_name(self):
        return self._name
    def __str__(self):
        return self._name
</code>```

Room Class

Thats the seventh class which is the Room Class

```<code>class Room:
    def __init__(self, number, seatingCapacity):
        self._number = number
        self._seatingCapacity = seatingCapacity
    def get_number(self):
        return self._number
    def get_seatingCapacity(self):
        return self._seatingCapacity
</code>```

MeetingTime Class

Thats the eighth class which is MeetingTime class

```<code>class MeetingTime:
    def __init__(self, id, time):
        self._time = time
        self._id = id
    def get_id(self):
        return self._id
    def get_time(self):
        return self._time
</code>```

Department Class

Thats the ninth class which is the Department class

```<code>class Department:
    # Batch for my case
    def __init__(self, name, courses):
        self._name = name
        self._courses = courses     # Courses that department offers
    def get_name(self): return self._name
    def get_courses(self): return self._courses
</code>```

Class class

Thats is the tenth class which name is Class

```<code>class Class:
    # Course to be scheduled at specific room of department host by an instructor at specific Meeting Time
    def __init__(self, id, dept, course):
        self._id = id
        self._dept = dept
        self._course = course
        self._instructor = None
        self._meetingTime = None
        self._room = None

    def get_id(self):
        return self._id
    def get_dept(self):
        return self._dept
    def get_room(self):
        return self._room
    def get_course(self):
        return self._course
    def get_instructor(self):
        return self._instructor
    def get_meetingTime(self):
        return self._meetingTime

    def set_instructor(self, instructor):
        self._instructor = instructor
    def set_meetingTime(self, meetingTime):
        self._meetingTime = meetingTime
    def set_room(self, room):
        self_room = room

    def __str__(self):
        return str(self._dept.get_name()) + "," + str(self._course.get_number()) + "," + \
               str(self._room.get_number()) + "," + str(self._instructor.get_id()) + "," + str(self._meetingTime.get_id())

</code>```

DisplayMgr Class Plus End Code

Thats the eleventh class which is DisplayMgr Class and the end code of that program.

```<code>class DisplayMgr:
    def print_available_data(self):
        print("> All Available Data")
        self.print_dept()
        self.print_course()
        self.print_room()
        self.print_instructor()
        self.print_meeting_times()

    def print_dept(self):
        depts = data.get_depts()
        availableDeptsTable = prettytable.PrettyTable(['dept', 'courses'])
        for i in range(0, len(depts)):
            courses = depts.__getitem__(i).get_courses()
            tempStr = "["
            for j in range(0, len(courses) - 1):
                tempStr += courses[j].__str__() + ", "
            tempStr += courses[len(courses) - 1].__str__() + "]"
            availableDeptsTable.add_row([depts.__getitem__(i).get_name(), tempStr])
        print(availableDeptsTable)

    def print_course(self):
        availabelCoursesTable = prettytable.PrettyTable(['id', 'course # ', 'max # of students', 'instructors'])
        courses = data.get_courses()
        for i in range(0, len(courses)):
            instructors = courses[i].get_instructors()
            tempStr = ""
            for j in range(0, len(instructors)-1):
                tempStr += instructors[j].__str__() + ", "
            tempStr += instructors[len(instructors) - 1].__str__()
            availabelCoursesTable.add_row(
                [courses[i].get_number(), courses[i].get_name(), str(courses[i].get_maxNumbOfStudents()), tempStr]
            )
        print(availabelCoursesTable)

    def print_instructor(self):
        availableInstructorsTable = prettytable.PrettyTable(['id', 'instructor'])
        instructors = data.get_instructors()
        for i in range(0, len(instructors)):
            availableInstructorsTable.add_row([instructors[i].get_id(), instructors[i].get_name()])
        print(availableInstructorsTable)

    def print_room(self):
        availableRoomsTable = prettytable.PrettyTable(['room #', 'max seating capacity'])
        rooms = data.get_rooms()
        for i in range(0, len(rooms)):
            availableRoomsTable.add_row([str(rooms[i].get_number()), str(rooms[i].get_seatingCapacity())])
        print(availableRoomsTable)

    def print_meeting_times(self):
        availableMeetingTimeTable = prettytable.PrettyTable(['id', 'Meeting Time'])
        meetingTimes = data.get_meetingTimes()
        for i in range(0, len(meetingTimes)):
            availableMeetingTimeTable.add_row([meetingTimes[i].get_id(), meetingTimes[i].get_time()])
        print(availableMeetingTimeTable)

    def print_generation(self, population):
        table1 = prettytable.PrettyTable(['schedule # ', 'fitness', '# of Conflicts','classes [dept, class, room, instructor'])
        schedules = population.get_schedules()
        for i in range(0, len(schedules)):
            table1.add_row([str(i), round(schedules[i].get_fitness(),3), schedules[i].get_numberOfConflicts(), schedules[i]])
        print(table1)

    def print_schedule_as_table(self, schedule):
        classes = schedule.get_classes()
        table = prettytable.PrettyTable(['Class # ', 'Dept', 'Course (number, max # of students)', 'Room (Capacity', 'Instructor'])
        for i in range(0, len(classes)):
            table.add_row([str(i), classes[i].get_dept().get_name(), classes[i].get_course().get_name() + " (" +
                           classes[i].get_course().get_number() + ", " +
                           str(classes[i].get_course().get_maxNumbOfStudents()) + ")",
                           classes[i].get_room().get_number() + " (" + str(classes[i].get_room().get_seatingCapacity()) +
                           classes[i].get_instructor().get_name() + " (" + str(classes[i].get_instructor().get_id()) +")",
                           classes[i].get_meatingTime().get_time() + " (" + str(classes[i].get_meatingTime().get_id()) +")"
                           ])

        print(table)

data = Data()
displayMgr = DisplayMgr()
displayMgr.print_available_data()
generationNumber = 0
print("\n> Generation # " + str(generationNumber))
population = Population(POPULATION_SIZE)
population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
displayMgr.print_generation(population)
displayMgr.print_schedule_as_table(population.get_schedules()[0])       # it will print fittest generation of schedule
geneticAlgorithm = GeneticAlgorithm()
while (population.get_schedules()[0].get_fitness() != 1.0):
    generationNumber += 1
    print("\n> Generation # " + str(generationNumber))
    population = geneticAlgorithm.evolve(population)
    population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
    displayMgr.print_generation(population)
    displayMgr.print_schedule_as_table(population.get_schedules()[0])
print("\n\n")
</code>```

答:
```<code>def set_room(self, room):
    self_room = room
</code>```

you have missing . in set_room(self,room) function . Change it to self._room=room so that it will set the room value and objectType=None will be solved

Body:
I am trying to make a time table scheduling program but found some errors. Please watch the following code and solve that error please.

Errors

These are the following errors

Traceback (most recent call last):
  File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 367, in <module>
    population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
  File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 367, in <lambda>
    population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
  File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 84, in get_fitness
    self._fitness = self.calculate_fitness()
  File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 106, in calculate_fitness
    if classes[i].get_room().get_seatingCapacity() < classes[i].get_course().get_maxNumbOfStudnets():
AttributeError: 'NoneType' object has no attribute 'get_seatingCapacity'

Source Code of the Program

Variables:

These are the variables which i declare for this program

import prettytable as prettytable
import random as rnd
POPULATION_SIZE = 9
NUMB_OF_ELITE_SCHEDULES = 1
TOURNAMENT_SELECTION_SIZE = 3
MUTATION_RATE = 0.1

Data Class

That is the first class which name is DATA

class Data:
    ROOMS = [["R1", 25], ["R2", 45], ["R3", 35]]
    MEETING_TIMES = [
        ["MT1", "MWF 09:00 - 10:00"],
        ["MT2", "MWF 10:00 - 11:00"],
        ["MT3", "TTH 09:00 - 10:30"],
        ["MT4", "TTH 10:30 - 12:00"]
                     ]
    INSTRUCTORS = [
        ["T1", "Dr James Web"],
        ["T2", "Mr Mike Brown"],
        ["T3", "Dr Steve Day"],
        ["T4", "Mrs Jane Doe"]
                   ]
    def __init__(self):
        self._rooms = []
        self._meetingTimes = []
        self._instructors = []
        for i in range(0, len(self.ROOMS)):
            self._rooms.append(Room(self.ROOMS[i][0], self.ROOMS[i][1]))
        for i in range(0, len(self.MEETING_TIMES)):
            self._meetingTimes.append(MeetingTime(self.MEETING_TIMES[i][0], self.MEETING_TIMES[i][1]))
        for i in range(0, len(self.INSTRUCTORS)):
            self._instructors.append(Instructor(self.INSTRUCTORS[i][0], self.INSTRUCTORS[i][1]))

        course1 = Course("C1", "325k", [self._instructors[0], self._instructors[1]], 25)
        course2 = Course("C2", "319k", [self._instructors[0], self._instructors[1], self._instructors[2]], 35)
        course3 = Course("C3", "462k", [self._instructors[0], self._instructors[1]], 25)
        course4 = Course("C4", "464k", [self._instructors[2], self._instructors[3]], 30)
        course5 = Course("C5", "360C", [self._instructors[3]], 35)
        course6 = Course("C6", "303k", [self._instructors[0], self._instructors[2]], 45)
        course7 = Course("C7", "303L", [self._instructors[1], self._instructors[3]], 45)

        self._courses = [course1, course2, course3, course4, course5, course6, course7]

        dept1 = Department("MATH", [course1, course3])
        dept2 = Department("EE", [course2, course4, course5])
        dept3 = Department("PHY", [course6, course7])

        self._depts = [dept1, dept2, dept3]
        self._numberOfClasses = 0

        for i in range(0, len(self._depts)):
            self._numberOfClasses += len(self._depts[i].get_courses())

    def get_rooms(self):
        return self._rooms
    def get_instructors(self):
        return self._instructors
    def get_courses(self):
        return self._courses
    def get_depts(self):
        return self._depts
    def get_meetingTimes(self):
        return self._meetingTimes
    def get_numberOfClasses(self):
        return self._numberOfClasses

Schedule Class

That is the second class which name is Schedule

class Schedule:
    def __init__(self):
        self._data = data
        self._classes = []
        self._numberOfConflicts = 0
        self._fitness = -1
        self._classNumb = 0
        self._isFitnessChanged = True

    def get_classes(self):
        self._isFitnessChanged = True
        return self._classes

    def get_numberOfConflicts(self):
        return self._numberOfConflicts

    def get_fitness(self):
        if(self._isFitnessChanged == True):
            self._fitness = self.calculate_fitness()
            self._isFitnessChanged = False
        return self._fitness

    def initialize(self):
        depts = self._data.get_depts()
        for i in range(0, len(depts)):
            courses = depts[i].get_courses()    #courses in each departments
            for j in range(0, len(courses)):
                newClass = Class(self._classNumb, depts[i], courses[j])
                self._classNumb += 1
                newClass.set_meetingTime(data.get_meetingTimes()[rnd.randrange(0, len(data.get_meetingTimes()))])
                newClass.set_room(data.get_rooms()[rnd.randrange(0, len(data.get_rooms()))])
                newClass.set_instructor(courses[j].get_instructors()[rnd.randrange(0, len(courses[j].get_instructors()))])
                self._classes.append(newClass)
        return self

    def calculate_fitness(self):
        self._numberOfConflicts = 0
        classes = self.get_classes()
        for i in range(0, len(classes)):

            if classes[i].get_room().get_seatingCapacity() < classes[i].get_course().get_maxNumbOfStudnets():
                self._numberOfConflicts += 1
            for j in range(0, len(classes)):
                if(j >= i):
                    if(classes[i].get_meetingTime() == classes[j].get_meetingTime() and
                       classes[i].get_id() != classes[j].get_id()):
                        if(classes[i].get_room() == classes[j].get_room()):
                            self._numberOfConflicts += 1
                        if(classes[i].get_instructor() == classes[j].get_instructor()):
                            self._numberOfConflicts += 1
        return 1 / ((1.0*self._numberOfConflicts + 1))

    def __str__(self):
        # it returns all the classes of schedule separated by comas
        returnValue = ""
        for i in range(0, len(self._classes)):
            returnValue += str(self._classes[i]) + ", "
        returnValue += str(self._classes[len(self._classes)-1])
        return returnValue

Population Class

Thats the third class which is Population class

class Population:
    def __init__(self, size):
        self._size = size
        self._data = data
        self._schedules = []
        for i in range(0, size):
            self._schedules.append(Schedule().initialize())
    def get_schedules(self):
        return self._schedules

GeneticAlgorithm Class

Thats the fourth class which is the GeneticAlgorithm class

class GeneticAlgorithm:
    def evolve(self, population):
        return self._mutate_population(self._crossover_population(population))

    def _crossover_population(self, pop):
        crossover_pop = Population(0)
        for i in range(NUMB_OF_ELITE_SCHEDULES):
            crossover_pop.get_schedules().append(pop.get_schedules()[i])
        i = NUMB_OF_ELITE_SCHEDULES
        while i < POPULATION_SIZE:
            schedule1 = self._select_tournament_population(pop).get_schedules()[0]
            schedule2 = self._select_tournament_population(pop).get_schedules()[0]
            crossover_pop.get_schedules().append(self._crossover_schedule(schedule1, schedule2))
            i += 1
        return crossover_pop
    def _mutate_population(self, population):
        for i in range(NUMB_OF_ELITE_SCHEDULES, POPULATION_SIZE):
            self._mutate_schedule(population.get_schedules()[i])
        return population

    def _crossover_schedule(self, schedule1, schedule2):
        crossoverSchedule = Schedule().initialize()
        for i in range(0, len(crossoverSchedule.get_classes())):
            if (rnd.random() > 0.5):
                crossoverSchedule.get_classes()[i] = schedule1.get_classes()[i]
            else:
                crossoverSchedule.get_classes()[i] = schedule2.get_classes()[i]
        return crossoverSchedule

    def _mutate_schedule(self,mutateSchedule):
        schedule = Schedule().initialize()
        for i in range(0, len(mutateSchedule.get_classes())):
            if(MUTATION_RATE > rnd.random()):
                mutateSchedule.get_classes()[i] = schedule.get_classes()[i]
        return mutateSchedule

    def _select_tournament_population(self, pop):
        tournament_pop = Population(0)
        i = 0
        while i < TOURNAMENT_SELECTION_SIZE:
            tournament_pop.get_schedules().append(pop.get_schedules()[rnd.randrange(0, POPULATION_SIZE)])
            i += 1
        tournament_pop.get_schedules().sort(key=lambda x:x.get_fitness(), reverse=True)
        return tournament_pop

Course Class

Thats the fifth class which is the Course class

class Course:
    def __init__(self, number, name, instructors, maxNumbOfStudents):
        self._number = number
        self._name = name
        self._instructors = instructors
        self._maxNumbOfStudents = maxNumbOfStudents
    def get_name(self):
        return self._name
    def get_number(self):
        return self._number
    def get_instructors(self):
        return self._instructors
    def get_maxNumbOfStudents(self):
        return self._maxNumbOfStudents
    def __str__(self):
        return self._name

Instructor Class

Thats the sixth class which is Instructor class

class Instructor:
    def __init__(self, id, name):
        self._id = id
        self._name = name
    def get_id(self):
        return self._id
    def get_name(self):
        return self._name
    def __str__(self):
        return self._name

Room Class

Thats the seventh class which is the Room Class

class Room:
    def __init__(self, number, seatingCapacity):
        self._number = number
        self._seatingCapacity = seatingCapacity
    def get_number(self):
        return self._number
    def get_seatingCapacity(self):
        return self._seatingCapacity

MeetingTime Class

Thats the eighth class which is MeetingTime class

class MeetingTime:
    def __init__(self, id, time):
        self._time = time
        self._id = id
    def get_id(self):
        return self._id
    def get_time(self):
        return self._time

Department Class

Thats the ninth class which is the Department class

class Department:
    # Batch for my case
    def __init__(self, name, courses):
        self._name = name
        self._courses = courses     # Courses that department offers
    def get_name(self): return self._name
    def get_courses(self): return self._courses

Class class

Thats is the tenth class which name is Class

class Class:
    # Course to be scheduled at specific room of department host by an instructor at specific Meeting Time
    def __init__(self, id, dept, course):
        self._id = id
        self._dept = dept
        self._course = course
        self._instructor = None
        self._meetingTime = None
        self._room = None

    def get_id(self):
        return self._id
    def get_dept(self):
        return self._dept
    def get_room(self):
        return self._room
    def get_course(self):
        return self._course
    def get_instructor(self):
        return self._instructor
    def get_meetingTime(self):
        return self._meetingTime

    def set_instructor(self, instructor):
        self._instructor = instructor
    def set_meetingTime(self, meetingTime):
        self._meetingTime = meetingTime
    def set_room(self, room):
        self_room = room

    def __str__(self):
        return str(self._dept.get_name()) + "," + str(self._course.get_number()) + "," + \
               str(self._room.get_number()) + "," + str(self._instructor.get_id()) + "," + str(self._meetingTime.get_id())

DisplayMgr Class Plus End Code

Thats the eleventh class which is DisplayMgr Class and the end code of that program.

class DisplayMgr:
    def print_available_data(self):
        print("> All Available Data")
        self.print_dept()
        self.print_course()
        self.print_room()
        self.print_instructor()
        self.print_meeting_times()

    def print_dept(self):
        depts = data.get_depts()
        availableDeptsTable = prettytable.PrettyTable(['dept', 'courses'])
        for i in range(0, len(depts)):
            courses = depts.__getitem__(i).get_courses()
            tempStr = "["
            for j in range(0, len(courses) - 1):
                tempStr += courses[j].__str__() + ", "
            tempStr += courses[len(courses) - 1].__str__() + "]"
            availableDeptsTable.add_row([depts.__getitem__(i).get_name(), tempStr])
        print(availableDeptsTable)

    def print_course(self):
        availabelCoursesTable = prettytable.PrettyTable(['id', 'course # ', 'max # of students', 'instructors'])
        courses = data.get_courses()
        for i in range(0, len(courses)):
            instructors = courses[i].get_instructors()
            tempStr = ""
            for j in range(0, len(instructors)-1):
                tempStr += instructors[j].__str__() + ", "
            tempStr += instructors[len(instructors) - 1].__str__()
            availabelCoursesTable.add_row(
                [courses[i].get_number(), courses[i].get_name(), str(courses[i].get_maxNumbOfStudents()), tempStr]
            )
        print(availabelCoursesTable)

    def print_instructor(self):
        availableInstructorsTable = prettytable.PrettyTable(['id', 'instructor'])
        instructors = data.get_instructors()
        for i in range(0, len(instructors)):
            availableInstructorsTable.add_row([instructors[i].get_id(), instructors[i].get_name()])
        print(availableInstructorsTable)

    def print_room(self):
        availableRoomsTable = prettytable.PrettyTable(['room #', 'max seating capacity'])
        rooms = data.get_rooms()
        for i in range(0, len(rooms)):
            availableRoomsTable.add_row([str(rooms[i].get_number()), str(rooms[i].get_seatingCapacity())])
        print(availableRoomsTable)

    def print_meeting_times(self):
        availableMeetingTimeTable = prettytable.PrettyTable(['id', 'Meeting Time'])
        meetingTimes = data.get_meetingTimes()
        for i in range(0, len(meetingTimes)):
            availableMeetingTimeTable.add_row([meetingTimes[i].get_id(), meetingTimes[i].get_time()])
        print(availableMeetingTimeTable)

    def print_generation(self, population):
        table1 = prettytable.PrettyTable(['schedule # ', 'fitness', '# of Conflicts','classes [dept, class, room, instructor'])
        schedules = population.get_schedules()
        for i in range(0, len(schedules)):
            table1.add_row([str(i), round(schedules[i].get_fitness(),3), schedules[i].get_numberOfConflicts(), schedules[i]])
        print(table1)

    def print_schedule_as_table(self, schedule):
        classes = schedule.get_classes()
        table = prettytable.PrettyTable(['Class # ', 'Dept', 'Course (number, max # of students)', 'Room (Capacity', 'Instructor'])
        for i in range(0, len(classes)):
            table.add_row([str(i), classes[i].get_dept().get_name(), classes[i].get_course().get_name() + " (" +
                           classes[i].get_course().get_number() + ", " +
                           str(classes[i].get_course().get_maxNumbOfStudents()) + ")",
                           classes[i].get_room().get_number() + " (" + str(classes[i].get_room().get_seatingCapacity()) +
                           classes[i].get_instructor().get_name() + " (" + str(classes[i].get_instructor().get_id()) +")",
                           classes[i].get_meatingTime().get_time() + " (" + str(classes[i].get_meatingTime().get_id()) +")"
                           ])

        print(table)

data = Data()
displayMgr = DisplayMgr()
displayMgr.print_available_data()
generationNumber = 0
print("\n> Generation # " + str(generationNumber))
population = Population(POPULATION_SIZE)
population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
displayMgr.print_generation(population)
displayMgr.print_schedule_as_table(population.get_schedules()[0])       # it will print fittest generation of schedule
geneticAlgorithm = GeneticAlgorithm()
while (population.get_schedules()[0].get_fitness() != 1.0):
    generationNumber += 1
    print("\n> Generation # " + str(generationNumber))
    population = geneticAlgorithm.evolve(population)
    population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
    displayMgr.print_generation(population)
    displayMgr.print_schedule_as_table(population.get_schedules()[0])
print("\n\n")

Body:
def set_room(self, room):
    self_room = room

you have missing . in set_room(self,room) function . Change it to self._room=room so that it will set the room value and objectType=None will be solved


问:
How to set a variable and check it for null both in the "case when" conditions SQL
I have problem with this piece of code.

I need to do something like this:

```<code>DECLARE @UserID INT
...
    CASE
        WHEN (@UserID = (SELECT TOP 1 UserPk FROM Users WHERE Name= 'JoeDoe')) IS NULL
        THEN 0
        ELSE 1
    END
</code>```

I need set @UserID for some other next steps and at the same time need to check (SELECT TOP 1 UserPk FROM Users WHERE Name = 'JoeDoe') for null.

Thanks for help.

答:
I would suggest using EXISTS:

```<code>DECLARE @UserID INT;

SET @UserId = (CASE WHEN EXISTS (SELECT 1 FROM Users WHERE Name= 'JoeDoe')
                    THEN 1 ELSE 0
               END);
</code>```

I'm not sure why you are calling this column @UserId.  It appears to be a flag on the presence of the name.

Body:
I have problem with this piece of code.

I need to do something like this:

DECLARE @UserID INT
...
    CASE
        WHEN (@UserID = (SELECT TOP 1 UserPk FROM Users WHERE Name= 'JoeDoe')) IS NULL
        THEN 0
        ELSE 1
    END

I need set @UserID for some other next steps and at the same time need to check (SELECT TOP 1 UserPk FROM Users WHERE Name = 'JoeDoe') for null.

Thanks for help.

Body:
I would suggest using EXISTS:

DECLARE @UserID INT;

SET @UserId = (CASE WHEN EXISTS (SELECT 1 FROM Users WHERE Name= 'JoeDoe')
                    THEN 1 ELSE 0
               END);

I'm not sure why you are calling this column @UserId.  It appears to be a flag on the presence of the name.


问:
php mvc – Remove Public from URL
I know this is a very popular question but I haven't been able to find a working solution in my project
I  want to set my document root to the public folder

change url for example from /public/login to /login

.htaccess code

```<code>  RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?$1 [L,QSA]
</code>```

答:
I'd say this is the immediate answer to the question you asked:

```<code>RewriteEngine On
RewriteRule ^/?public/(.*)$ /%1 [QSA,R=301,END]
RewriteRule ^ /public%{REQUEST_URI} [QSA,END]
</code>```

But I assume this is more what you actually need, your question is vague in that:

```<code>RewriteEngine On
RewriteRule ^/?public/(.*)$ /%1 [QSA,R=301,END]
RewriteRule ^ /public/index.php?%{REQUEST_URI} [QSA,END]
</code>```

Obviously the rewriting module needs to be loaded and enabled into the http server and the interpretation of distributed configuration files (".htaccess") has to be granted in the http server's host configuration if you really want to use such.

It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out...

In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.

This implementation will work likewise in the http servers host configuration or inside a distributed configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a distributed configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using distributed configuration files (".htaccess"). Those distributed configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

Title: php mvc – Remove Public from URL

Body:
I know this is a very popular question but I haven't been able to find a working solution in my project
I  want to set my document root to the public folder

change url for example from /public/login to /login

.htaccess code

  RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?$1 [L,QSA]

Body:
I'd say this is the immediate answer to the question you asked:

RewriteEngine On
RewriteRule ^/?public/(.*)$ /%1 [QSA,R=301,END]
RewriteRule ^ /public%{REQUEST_URI} [QSA,END]

But I assume this is more what you actually need, your question is vague in that:

RewriteEngine On
RewriteRule ^/?public/(.*)$ /%1 [QSA,R=301,END]
RewriteRule ^ /public/index.php?%{REQUEST_URI} [QSA,END]

Obviously the rewriting module needs to be loaded and enabled into the http server and the interpretation of distributed configuration files (".htaccess") has to be granted in the http server's host configuration if you really want to use such.

It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out...

In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.

This implementation will work likewise in the http servers host configuration or inside a distributed configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a distributed configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using distributed configuration files (".htaccess"). Those distributed configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).


问:
Python requiring an attribute be converted to a string
```<code>from sys import exit
from random import randint

class Map(object):

 def death():
    print quips[randint (0, len(quips)-1)]
    exit(1)

 def princess_lives_here():
    print "You see a beautiful Princess with a shiny crown."
    print "She offers you some cake."

    eat_it = raw_input(">")

    if eat_it == "eat it":
        print "You explode like a pinata full of frogs."
        print "The Princess cackles and eats the frogs. Yum!"
        return 'death'

    elif eat_it == "do not eat it":
        print "She throws the cake at you and it cuts off your head."
        print "The last thing you see is her munching on your face. Yum!"
        return 'death'

    elif eat_it == "make her eat it":
        print "The Princess screams as you cram the cake in her mouth."
        print "Then she smiles and cries and thank you for saving her."
        print "She points to a tiny door and says, 'The Koi needs cake too.'"
        print "She gives you the very last bit of cake and shoves you in."
        return 'gold_koi_pond'

    else:
        print "The Princess looks at you confused and just points at the cake."
        return 'princess_lives_here'

class Engine(object):

 def __init__(self, start, quips):
    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]
    self.start = start

 def play(self):
    next = self.start

    while True:
        print "\n-----"
        room = getattr(self, next)
        next = room()

m = Map()
e = Engine(m, "princess_lives_here")

e.play()
</code>```

Trace back i get in terminal is:

```<code>    Traceback (most recent call last):
  File "ec42.py", line 162, in <module>
    e.play()
  File "ec42.py", line 156, in play
    room = getattr(self, next)
TypeError: getattr(): attribute name must be string
</code>```

I have been working on this far too long, and just cannot nail it down. The main issue is getting the map class to run inside the engine class as an object. thanks in advance for the help.

答:
Maybe you want something like this? </p>

```<code>class Map(object):

 def __init__(self):

    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]

 def death(self):
    print self.quips[randint (0, len(self.quips)-1)]
    exit(1)

 def princess_lives_here(self):
    print "You see a beautiful Princess with a shiny crown."
    print "She offers you some cake."

    eat_it = raw_input(">")

    if eat_it == "eat it":
        print "You explode like a pinata full of frogs."
        print "The Princess cackles and eats the frogs. Yum!"
        return 'death'

    elif eat_it == "do not eat it":
        print "She throws the cake at you and it cuts off your head."
        print "The last thing you see is her munching on your face. Yum!"
        return 'death'

    elif eat_it == "make her eat it":
        print "The Princess screams as you cram the cake in her mouth."
        print "Then she smiles and cries and thank you for saving her."
        print "She points to a tiny door and says, 'The Koi needs cake too.'"
        print "She gives you the very last bit of cake and shoves you in."
        return 'gold_koi_pond'

    else:
        print "The Princess looks at you confused and just points at the cake."
        return 'princess_lives_here'

class Engine(object):

 def __init__(self, map, start):
    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]
    self.map = map
    self.start = start

 def play(self):
    next = self.start

    while True:
        print "\n-----"
        room = getattr(self.map, next)
    next = room()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
from sys import exit
from random import randint

class Map(object):

 def death():
    print quips[randint (0, len(quips)-1)]
    exit(1)

 def princess_lives_here():
    print "You see a beautiful Princess with a shiny crown."
    print "She offers you some cake."

    eat_it = raw_input(">")

    if eat_it == "eat it":
        print "You explode like a pinata full of frogs."
        print "The Princess cackles and eats the frogs. Yum!"
        return 'death'

    elif eat_it == "do not eat it":
        print "She throws the cake at you and it cuts off your head."
        print "The last thing you see is her munching on your face. Yum!"
        return 'death'

    elif eat_it == "make her eat it":
        print "The Princess screams as you cram the cake in her mouth."
        print "Then she smiles and cries and thank you for saving her."
        print "She points to a tiny door and says, 'The Koi needs cake too.'"
        print "She gives you the very last bit of cake and shoves you in."
        return 'gold_koi_pond'

    else:
        print "The Princess looks at you confused and just points at the cake."
        return 'princess_lives_here'

class Engine(object):

 def __init__(self, start, quips):
    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]
    self.start = start

 def play(self):
    next = self.start

    while True:
        print "\n-----"
        room = getattr(self, next)
        next = room()

m = Map()
e = Engine(m, "princess_lives_here")

e.play()

Trace back i get in terminal is:

    Traceback (most recent call last):
  File "ec42.py", line 162, in <module>
    e.play()
  File "ec42.py", line 156, in play
    room = getattr(self, next)
TypeError: getattr(): attribute name must be string

I have been working on this far too long, and just cannot nail it down. The main issue is getting the map class to run inside the engine class as an object. thanks in advance for the help.

Body:
Maybe you want something like this?

class Map(object):

 def __init__(self):

    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]

 def death(self):
    print self.quips[randint (0, len(self.quips)-1)]
    exit(1)

 def princess_lives_here(self):
    print "You see a beautiful Princess with a shiny crown."
    print "She offers you some cake."

    eat_it = raw_input(">")

    if eat_it == "eat it":
        print "You explode like a pinata full of frogs."
        print "The Princess cackles and eats the frogs. Yum!"
        return 'death'

    elif eat_it == "do not eat it":
        print "She throws the cake at you and it cuts off your head."
        print "The last thing you see is her munching on your face. Yum!"
        return 'death'

    elif eat_it == "make her eat it":
        print "The Princess screams as you cram the cake in her mouth."
        print "Then she smiles and cries and thank you for saving her."
        print "She points to a tiny door and says, 'The Koi needs cake too.'"
        print "She gives you the very last bit of cake and shoves you in."
        return 'gold_koi_pond'

    else:
        print "The Princess looks at you confused and just points at the cake."
        return 'princess_lives_here'

class Engine(object):

 def __init__(self, map, start):
    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]
    self.map = map
    self.start = start

 def play(self):
    next = self.start

    while True:
        print "\n-----"
        room = getattr(self.map, next)
    next = room()


问:
Python vectorizing nested for loops in image processing
I am trying to detect skin. I found a nice and easy formula to detect skin from RGB picture. The only problem is, that for loops are very slow, and I need to accelerate the process. I've done some researching and vectorization could fasten my for-loops, but I don't know how to use it in my case.

Here is code of my function:

Function receives 1 parameter of type: numpy array, with shape of (144x256x3), dtype=np.uint8

Function returns coordinates of first detected skin colored pixel(as numpy.array [height,width]); number of skin detected pixels(int) and calculated angle (from left to right) of first skin detected picture(float)

```<code># picture = npumpy array, with 144x256x3 shape, dtype=np.uint8
def filter_image(picture):
    r = 0.0
    g = 0.0
    b = 0.0

    # In first_point I save first occurrence of skin colored pixel, so I can track person movement
    first_point = np.array([-1,-1])

    # counter is used to count how many skin colored pixels are in an image (to determine distance to target, because LIDAR isn't working)
    counter = 0

    # angle of first pixel with skin color (from left to right, calculated with Horizontal FOV)
    angle = 0.0

    H = picture.shape[0]
    W = picture.shape[1]

    # loop through each pixel
    for i in range(H):
        for j in range(W):
            # if all RGB are 0(black), we take with next pixel
            if(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2])) == 0:
               continue
            #else we calculate r,g,b used for skin recognition
            else:
                r = picture[i,j][0]/(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2]))
                g = picture[i,j][1]/(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2]))
                b = picture[i,j][2]/(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2]))
            # if one of r,g,b calculations are 0, we take next pixel
            if(g == 0 or r == 0 or b == 0):
                continue
            # if True, pixel is skin colored
            elif(r/g > 1.185 and (((r * b) / math.pow(r + b + g,2)) > 0.107) and ((r * g) / math.pow(r + b + g,2)) > 0.112):
                # if this is the first point with skin colors in the whole image, we save i,j coordinate
                if(first_point[0] == -1):
                    # save first skin color occurrence
                    first_point[0] = i
                    first_point[1] = j

                    # here angle is calculated, with width skin pixel coordinate, Hor. FOV of camera and constant
                    angle = (j+1)*91 *0.00390626

                # whenever we detect skin colored pixel, we increment the counter value
                counter += 1
                continue
    # funtion returns coordinates of first skin colored pixel, counter of skin colored pixels and calculated angle(from left to right based on j coordinate of first pixel with skin color)
    return first_point,counter, angle
</code>```

Function works well, the only problem is its speed!

Thank you, for helping!

答:
One thing that is often nice to try first, when trying to improve the performance of code, is to see how much something like numba can make it faster basically for free.

Here's an example of how to use it for your code:

```<code>import math
import time

# I'm just importing numpy here so I can make a random input of the
# same dimensions that you mention in your question.
import numpy as np
from numba import jit

@jit(nopython=True)
def filter_image(picture):
    ... I just copied the body of this function from your post above ...
    return first_point, counter, angle

def main():
    n_iterations = 10
    img = np.random.rand(144, 256, 3)
    before = time.time()
    for _ in range(n_iterations):
        # In Python 3, this was just a way I could get access to the original
        # function you defined, without having to make a separate function for
        # it (as the numba call replaces it with an optimized version).
        # It's equivalent to just calling your original function here.
        filter_image.__wrapped__(img)
    print(f'took: {time.time() - before:.3f} without numba')

    before = time.time()
    for _ in range(n_iterations):
        filter_image(img)
    print(f'took: {time.time() - before:.3f} WITH numba')

if __name__ == '__main__':
    main()
</code>```

Output showing the time difference:

```<code>took: 1.768 without numba
took: 0.414 WITH numba
</code>```

...actually optimizing this function could probably do a lot better, but if this speedup is enough so that you don't need to do other optimization, that's good enough!

Edit (as per macroeconomist's comment): the times I report above also include the upfront time cost of numba just-in-time compiling your function, which happens on the first call. If you are making many calls to this function, the performance difference could actually be much more dramatic. Timing all calls after first first should make the comparison of per-call times more accurate.

Body:
I am trying to detect skin. I found a nice and easy formula to detect skin from RGB picture. The only problem is, that for loops are very slow, and I need to accelerate the process. I've done some researching and vectorization could fasten my for-loops, but I don't know how to use it in my case.

Here is code of my function:

Function receives 1 parameter of type: numpy array, with shape of (144x256x3), dtype=np.uint8

Function returns coordinates of first detected skin colored pixel(as numpy.array [height,width]); number of skin detected pixels(int) and calculated angle (from left to right) of first skin detected picture(float)

# picture = npumpy array, with 144x256x3 shape, dtype=np.uint8
def filter_image(picture):
    r = 0.0
    g = 0.0
    b = 0.0

    # In first_point I save first occurrence of skin colored pixel, so I can track person movement
    first_point = np.array([-1,-1])

    # counter is used to count how many skin colored pixels are in an image (to determine distance to target, because LIDAR isn't working)
    counter = 0

    # angle of first pixel with skin color (from left to right, calculated with Horizontal FOV)
    angle = 0.0

    H = picture.shape[0]
    W = picture.shape[1]

    # loop through each pixel
    for i in range(H):
        for j in range(W):
            # if all RGB are 0(black), we take with next pixel
            if(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2])) == 0:
               continue
            #else we calculate r,g,b used for skin recognition
            else:
                r = picture[i,j][0]/(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2]))
                g = picture[i,j][1]/(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2]))
                b = picture[i,j][2]/(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2]))
            # if one of r,g,b calculations are 0, we take next pixel
            if(g == 0 or r == 0 or b == 0):
                continue
            # if True, pixel is skin colored
            elif(r/g > 1.185 and (((r * b) / math.pow(r + b + g,2)) > 0.107) and ((r * g) / math.pow(r + b + g,2)) > 0.112):
                # if this is the first point with skin colors in the whole image, we save i,j coordinate
                if(first_point[0] == -1):
                    # save first skin color occurrence
                    first_point[0] = i
                    first_point[1] = j

                    # here angle is calculated, with width skin pixel coordinate, Hor. FOV of camera and constant
                    angle = (j+1)*91 *0.00390626

                # whenever we detect skin colored pixel, we increment the counter value
                counter += 1
                continue
    # funtion returns coordinates of first skin colored pixel, counter of skin colored pixels and calculated angle(from left to right based on j coordinate of first pixel with skin color)
    return first_point,counter, angle

Function works well, the only problem is its speed!

Thank you, for helping!

Body:
One thing that is often nice to try first, when trying to improve the performance of code, is to see how much something like numba can make it faster basically for free.

Here's an example of how to use it for your code:

import math
import time

# I'm just importing numpy here so I can make a random input of the
# same dimensions that you mention in your question.
import numpy as np
from numba import jit

@jit(nopython=True)
def filter_image(picture):
    ... I just copied the body of this function from your post above ...
    return first_point, counter, angle

def main():
    n_iterations = 10
    img = np.random.rand(144, 256, 3)
    before = time.time()
    for _ in range(n_iterations):
        # In Python 3, this was just a way I could get access to the original
        # function you defined, without having to make a separate function for
        # it (as the numba call replaces it with an optimized version).
        # It's equivalent to just calling your original function here.
        filter_image.__wrapped__(img)
    print(f'took: {time.time() - before:.3f} without numba')

    before = time.time()
    for _ in range(n_iterations):
        filter_image(img)
    print(f'took: {time.time() - before:.3f} WITH numba')

if __name__ == '__main__':
    main()

Output showing the time difference:

took: 1.768 without numba
took: 0.414 WITH numba

...actually optimizing this function could probably do a lot better, but if this speedup is enough so that you don't need to do other optimization, that's good enough!

Edit (as per macroeconomist's comment): the times I report above also include the upfront time cost of numba just-in-time compiling your function, which happens on the first call. If you are making many calls to this function, the performance difference could actually be much more dramatic. Timing all calls after first first should make the comparison of per-call times more accurate.


问:
DateTime axis in MPAndroidChart
I am using MPAndroidChart in my app. I want to plot the chart using values on yAxis and dates on the xAxis. I didn't find any datetime axis in the MPAndroidChart API. Is there any way to plot the xAxis using date? I have values to plot against dates. I want to show the dates in (ddMMM-yy) format on xAxis and the values on yAxis. Can anyone can pass me the sample link for the same?

Sample data:

```<code>Date(xAxis) | Value(yAxis)
------------|-------------
01/01/2001  |  966.78
01/02/2001  |  666.78
01/03/2001  |  966.78
01/04/2001  |  966.78
01/05/2001  |  966.78
01/06/2001  |  966.78
01/07/2001  |  966.78
</code>```

答:
I know it's late but it might be helpful for someone.

You can store the dates in an array and then can display it on the x-axis of the chart using setValueFormatter property of chart.
At the top declare dev array.
 final String dev1[] = new String[100];

Then where you have your chart

```<code>   final JSONObject object = jsonArray.getJSONObject(i);

   dev1[i] = object.getString("real_time");
   barEntries.add(new BarEntry(i, Float.parseFloat(value)));
   final BarDataSet barDataSetgen = new BarDataSet(barEntries, " ");

   XAxis bottomAxis = mcvbarchart.getXAxis();

   bottomAxis.setValueFormatter(new IndexAxisValueFormatter(dev1));   /*for x axis values*/
   bottomAxis.setLabelCount(barEntries.size());
   bottomAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
</code>```

Title: DateTime axis in MPAndroidChart

Body:
I am using MPAndroidChart in my app. I want to plot the chart using values on yAxis and dates on the xAxis. I didn't find any datetime axis in the MPAndroidChart API. Is there any way to plot the xAxis using date? I have values to plot against dates. I want to show the dates in (ddMMM-yy) format on xAxis and the values on yAxis. Can anyone can pass me the sample link for the same?

Sample data:

Date(xAxis) | Value(yAxis)
------------|-------------
01/01/2001  |  966.78
01/02/2001  |  666.78
01/03/2001  |  966.78
01/04/2001  |  966.78
01/05/2001  |  966.78
01/06/2001  |  966.78
01/07/2001  |  966.78

Body:
I know it's late but it might be helpful for someone.

You can store the dates in an array and then can display it on the x-axis of the chart using setValueFormatter property of chart.
At the top declare dev array.
 final String dev1[] = new String[100];

Then where you have your chart

   final JSONObject object = jsonArray.getJSONObject(i);

   dev1[i] = object.getString("real_time");
   barEntries.add(new BarEntry(i, Float.parseFloat(value)));
   final BarDataSet barDataSetgen = new BarDataSet(barEntries, " ");

   XAxis bottomAxis = mcvbarchart.getXAxis();

   bottomAxis.setValueFormatter(new IndexAxisValueFormatter(dev1));   /*for x axis values*/
   bottomAxis.setLabelCount(barEntries.size());
   bottomAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


问:
Make bulma columns occupy complete vertical space
I am using Bulma columns & have divided my columns to column is-2 and column is-10. I am using column is-2 to show a vertical navigation bar using Bulma Menu component.

After adding background-colour to my menu, I saw that my component doesn't stretch to the complete page vertically.

Any help will be appreciated.

答: Make the navigation column's height 100vh and sticky.</p>


问:
Multi-key lookup data structure
I need an efficient way to look up a user by any 1 of 3 different keys. For example, by id, username or alias.

The basic concept would be a data structure in which you can use any of 3 different types of keys to look up the value:

myDataStructure.lookupByName(name) -> User

myDataStructure.lookupById(id) -> User

myDataStructure.lookupByAlias(alias) -> User

The only immediate way I can think of doing this would be to have 3 separate dictionaries, and use the one corresponding to the type of key provided.

Is there a more efficient way?

答: If you know that the keysets (names, ids and aliases) are distinct, you could put them all into a single table. Otherwise, you'd need the three separate tables that you noted.</p>

Title: Multi-key lookup data structure


问:
Creating simple sprites in Visual Studio 2019
Im realatively new to programming, I want to make a fairly simple game in visual studio for a school project; At this stage I need to create a simple sprite of a ship which can rotate and move in the direction it's facing, I already made a movement engine but I am stuck at making the sprite itself. What is the simplest method of making the sprite, preferably without the use of third party software.

Thanks in advance

答:
Actually, I've never tried to program a game in visual studio and I don't have an answer to that But Instead, I have an easier suggestion which is to learn the basics of unity game engine which shouldn't take more than 3 hours or so but the possibilities unity will give is much better than visual studio's because unity is specialized in games while visual studio is specialized in programs, so if your game is as simple as you are describing then I would highly recommend that you give unity a try, and btw unity uses c# as it's programming language so you shouldn't find any difficulties with the programming side.

cheers !


问:
Is it possible to declare the type with 'this' keyword like that in typescript?
Example:

```<code>// ===== Declaration ===== //
class A {
  CONSTS_TYPE: { [key: string]: [any] }
  CONSTS: { [key in keyof this['CONSTS_TYPE']]: key }
  foo<T extends keyof this['CONSTS_TYPE'] | string>(
    type: T,
    callback: (...args: T extends keyof this['CONSTS_TYPE'] ? this['CONSTS_TYPE'][T] : any) => any
  ) { /** some implementation*/ }
}
class B extends A {
  CONSTS_TYPE: {
    aa: [number],
    bb: [string]
  }
  // Here is the problem
  // Type '{ aa: "aa"; bb: "bb"; }' is not assignable to type '{ [key in keyof this["CONSTS_TYPE"]]: key; }'.(2322)
  CONSTS: { [key in keyof this['CONSTS_TYPE']]: key } = {
    aa: 'aa',
    bb: 'bb'
  }
}

// ===== Call ===== //
const b = new B;
b.foo(b.CONSTS.aa, (arg) => {
  // so that i can know 'arg' is a 'number' type
  arg // number type
});
</code>```

it works well, but not too well.

i know '// @ts-ignore' will work really well

but I think there may be other solutions

[Playground Link]

答:
So, I think there are some problem going on with your code :

You should avoid using @ts-ignore as much as you can.

aa: 'aa', is not a number and should have raised you an error. It didn't cause of the way you have implemented it

in ...args: T, T is an array and not one parameter as you think

Why use ...args in foo ?

Here is what I think could be a soluce to you :

```<code>// ===== Declaration ===== //
type ValueOf<T> = T[keyof T];

abstract class A {
  abstract CONSTS: { [key: string]: any }

  foo<T extends ValueOf<this['CONSTS']>>(
    type: T,
    callback: (arg: T) => any
  ) { /** some implementation*/ }
}

class B extends A {
  CONSTS: {
    aa: number,
    bb: string
  } = {
    aa: 5,
    bb: 'bb'
  }
}

// ===== Call ===== //
const b = new B;
b.foo(b.CONSTS.bb, (arg) => {
  // so that i can know 'arg' is a 'string' type
  arg // string type
});
</code>```

typescript playground

Body:
Example:

// ===== Declaration ===== //
class A {
  CONSTS_TYPE: { [key: string]: [any] }
  CONSTS: { [key in keyof this['CONSTS_TYPE']]: key }
  foo<T extends keyof this['CONSTS_TYPE'] | string>(
    type: T,
    callback: (...args: T extends keyof this['CONSTS_TYPE'] ? this['CONSTS_TYPE'][T] : any) => any
  ) { /** some implementation*/ }
}
class B extends A {
  CONSTS_TYPE: {
    aa: [number],
    bb: [string]
  }
  // Here is the problem
  // Type '{ aa: "aa"; bb: "bb"; }' is not assignable to type '{ [key in keyof this["CONSTS_TYPE"]]: key; }'.(2322)
  CONSTS: { [key in keyof this['CONSTS_TYPE']]: key } = {
    aa: 'aa',
    bb: 'bb'
  }
}

// ===== Call ===== //
const b = new B;
b.foo(b.CONSTS.aa, (arg) => {
  // so that i can know 'arg' is a 'number' type
  arg // number type
});

it works well, but not too well.

i know '// @ts-ignore' will work really well

but I think there may be other solutions

<a href="https://www.typescriptlang.org/play/index.html?ssl=28&ssc=4&pln=7&pc=1#code/PTAEF5M0BEFMDGAbAhgJxQFwJYHsB2EU4oIAUMigM5WgCCoA3maKAMIDyAcgMoAqPAPp8AmgAUAogC4moANoBrOAE8ZVTGmz4A5gF0ZclPmW7QAXxbtu-HjMbyly0FtCPcAM1CYAFtipyAck5eAWFxCQDdfVcVc0t3XFwAHj5QOAAPTDh8ABNaN08fP0DgmzDJSNAAH1B1TR0APgAKS1ZMZQAHOBk+ABpW0AQUJCQAIxQEBRkmgDo59G0qHrTM7LyY5Q8vX38g61DRCtMAfm3ivZChQ4jdOT5TGSNlAEoIBtAny1f7YAAqX9quAAtnBnECOkg4CD8JgsHh8L8wBYLJQaKAAEIrLK5WgMZisUoHcJ2AYoFAGfAAVyBozgaF0-VYrFGowMdS0eksFlYIFAAAk6aC-NtQR00LhRpCgZZeXxOqCAvYyTIAERklUAblALNVLM15gCzlo+FwmA+NGw2nwKEloMwuC88tAiocsRcBTO-hVhKu4RVURkji1ZgCMyaACYAMzh8PPSw+uyupzulRbIq7H3lG7RRzmCBMUnk51kgKMpk650sgJcsgWMi84gkNjDJBEKCkYAUAjqbX5-BwADuGI1ZFGMwSuCaY59MxZvVATQWr3A73xHcB2ywzkGRlcJqHAQWhuFKGdVJpdMN7S6lgW6-PtLQjpvZmeGqAA" rel="nofollow noreferrer">[Playground Link]

Body:
So, I think there are some problem going on with your code :

You should avoid using @ts-ignore as much as you can.

aa: 'aa', is not a number and should have raised you an error. It didn't cause of the way you have implemented it

in ...args: T, T is an array and not one parameter as you think

Why use ...args in foo ?

Here is what I think could be a soluce to you :

// ===== Declaration ===== //
type ValueOf<T> = T[keyof T];

abstract class A {
  abstract CONSTS: { [key: string]: any }

  foo<T extends ValueOf<this['CONSTS']>>(
    type: T,
    callback: (arg: T) => any
  ) { /** some implementation*/ }
}

class B extends A {
  CONSTS: {
    aa: number,
    bb: string
  } = {
    aa: 5,
    bb: 'bb'
  }
}

// ===== Call ===== //
const b = new B;
b.foo(b.CONSTS.bb, (arg) => {
  // so that i can know 'arg' is a 'string' type
  arg // string type
});

<a href="https://www.typescriptlang.org/play/index.html?ssl=1&ssc=1&pln=28&pc=4#code/PTAEF5M0BEFMDGAbAhgJxQFwJYHsB2EU4oIAUJgJ4AOcoAaikgK5wDyAZgDwAqAfBFA8A2gGs4lXByEBdANxkyKAEYBnTBgSZQyFKtWgAgqADeZUKBXrN2gMJsAcgGUeTgFynQYiR+vZ8AOYyHij4lKAAvooWHLi4vKBwAB6YcPgAJgaMLOzcmAAW2KrCAOT2zq4lMnx8ABTmFqBUtB48ADQNFghMSMooCKIetegBrQCUEAKhlA0TJqQAVAugqrgAtnTYa9RIcBv4mFh4+AtgUVFkuvqgAEKJKWmZRqYN5S7uL42WKB74zGvKOBoDpfZTKXwafwBBoRQRmL4oH6gACsIMaYI8JTBJRhZAuICIUFAth6hOg5AQBHUoGUgnwcAA7rcFMoAHSxXC1NlvVyssFtUDDNABCbgATw0hgVZNfJYUDYHShUCifC4JklEYleUGFCgEp+QJa5pwBojSUrSGBJo0E0RMZyIA" rel="nofollow noreferrer">typescript playground


问:
A JNI error has occurred, please check your installation and try again.(eventhough Java -version and javac -version also same)
```<code>java.lang.NoClassDefFoundError: org/json/JSONException
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.json.JSONException
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main"
</code>```

The above error occurs whenever i try to run .jar file.java -version and javac -version is same only.I have also set classpath in environmental variables.But still i'm getting the above error.Could anyone provide a solution for this?

答:
Issue:
A java.lang.ClassNotFoundException or java.lang.NoClassDefFoundError means that the class mentioned in the message : org/json/JSONException is not found by JVM on the class-path.

Solution:
Either, you need to add the whole jar to your class-path
(On how to do that, visit : Official Oracle's documentation on adding classes to classpath or 5 ways to add multiple jars to classpath

Or, if you use a build tool like maven, you can add a dependency for the missing class:

```<code><!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20200518</version>
</dependency>
</code>```

Also you'll find the whole jar in the link: Maven repo link for json dependency.

Body:
java.lang.NoClassDefFoundError: org/json/JSONException
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.json.JSONException
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main"

The above error occurs whenever i try to run .jar file.java -version and javac -version is same only.I have also set classpath in environmental variables.But still i'm getting the above error.Could anyone provide a solution for this?

Body:
Issue:
A java.lang.ClassNotFoundException or java.lang.NoClassDefFoundError means that the class mentioned in the message : org/json/JSONException is not found by JVM on the class-path.

Solution:
Either, you need to add the whole jar to your class-path
(On how to do that, visit : Official Oracle's documentation on adding classes to classpath or 5 ways to add multiple jars to classpath

Or, if you use a build tool like maven, you can add a dependency for the missing class:

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20200518</version>
</dependency>

Also you'll find the whole jar in the link: Maven repo link for json dependency.


问:
RxDB/Electron storing data in sqlite
I want to build a hybrid using Ionic/Electron to run it on Desktop,Browser and Android, after doing some research i found about RxDB which by it's definition seems to fit this kind of DB usage (https://rxdb.info/)

I want to be able to store data locally in an SQLite-like storage capacity without being limited by the web browser's storage capacity and use the same api (rxdb ?) to manipulate data on Desktop (Electron), Mobile and web browser (Ionic).

Is this possible using RxDB ? if it's not i would like to know if there are tools out there capable of allowing such functionality ?

答:
Yes this is surely possible with RxDB, you can use IDB which stands for indexed data storage, which in terms of browser means that your data will not be limited by the browser capacity, since it is stored offline in your computer,

It is limited only to your available disk space  Not to the browser capacity
  That is what idb adapter helps in browsers

Title: RxDB/Electron storing data in sqlite


问:
How to redirect a page and disguise its url?
I need to do the following on my apache webserver :

Redirect any URL starting with :

```<code> http://mydomain1.com/archive
 to
 http://mydomain2.com/archive
</code>```

Is there a way using mod-rewrite or RewriteEngine to disguise that URL, so that the URL that appears in the browser is mydomain1.com ?   I don't want to give away the fact that we are switching servers.

答: you could try a reverse proxy.  This will allow you to take one url and forward  the request to another server without the end user knowing.</p>

Body:
I need to do the following on my apache webserver :

Redirect any URL starting with :

 http://mydomain1.com/archive
 to
 http://mydomain2.com/archive

Is there a way using mod-rewrite or RewriteEngine to disguise that URL, so that the URL that appears in the browser is mydomain1.com ?   I don't want to give away the fact that we are switching servers.


问:
A way to communicate to a Pod that it's restarting
I need to communicate to a Pod if it's restarting or not. Because depending of the situation my app is working differently (stateful app). I wouldn't like to create other pod that runs a kind of watchdog and then informs my app if it's restarting or not (after a fault). But maybe there is a way to do it with Kubernetes components (Kubelet,..). </p>

答:
Quoting from Kubernetes Docs:

Processes in containers inside pods can also contact the apiserver.
  When they do, they are authenticated as a particular Service Account
  (for example, default)

A RoleBinding or ClusterRoleBinding binds a role to subjects. Subjects can be groups, users or ServiceAccounts.

An RBAC Role or ClusterRole contains rules that represent a set of
  permissions.

A Role always sets permissions within a particular namespace.

ClusterRole, by contrast, is a non-namespaced resource

So, In-order to get/watch the status of the other pod, you can call Kubernetes API from the pod running your code by using serviceaccounts. Follow below steps in-order to automatically retrieve other pod status from a given pod without any external dependency (Due to reliability concerns, you shouldn't rely upon nodes)

Create a serviceaccount in your pod's (requestor pod) namespace

```<code>kubectl create sa pod-reader
</code>```

If both pods are in same namespace, create role,rolebinding

Create a role

```<code>kubectl create role pod-reader --verb=get,watch --resource=pods
</code>```

Create a rolebinding

```<code>kubectl create rolebinding pod-reader-binding --role=pod-reader --serviceaccount=<NAMESPACE>:pod-reader
</code>```

Else, i.e the pods are in different namespaces, create clusterrole,clusterrolebinding

Create a clusterrole

```<code>kubectl create clusterrole pod-reader --verb=get,watch --resource=pods
</code>```

Create a rolebinding

```<code>kubectl create clusterrolebinding pod-reader-binding --clusterrole=pod-reader --serviceaccount=<NAMESPACE>:pod-reader
</code>```

Verify the permissions

```<code>kubectl auth can-i watch pods --as=system:serviceaccount:<NAMESPACE>:pod-reader
</code>```

Now deploy your pod/(your app) with this serviceaccount.

```<code>kubectl create <MY-POD> --image=<MY-CONTAINER-IMAGE> --serviceaccount=pod-reader
</code>```

This will mount serviceaccount secret token in your pod, which can be found at /var/run/secrets/kubernetes.io/serviceaccount/token. Your app can use this token to make GET requests to Kubernetes API server in-order to get the status of the pod. See below example (this assumes your pod has curl utility installed. However, you can make a relevant API call from your code, pass the Header by reading the serviceaccount token file mounted in your pod).

```<code>TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)

curl https://kubernetes.default/api/v1/namespaces/<NAMESPACE>/pods/<NAME_OF_THE_OTHER_POD> -H "Authorization: Bearer ${TOKEN}" -k

curl https://kubernetes.default/api/v1/watch/namespaces/<NAMESPACE>/pods/<NAME_OF_THE_OTHER_POD>?timeoutSeconds=30 -H "Authorization: Bearer ${TOKEN}" -k
</code>```

References:

Kubernetes API

serviceaccount

Body:
Quoting from Kubernetes Docs:

Processes in containers inside pods can also contact the apiserver.
  When they do, they are authenticated as a particular Service Account
  (for example, default)

A RoleBinding or ClusterRoleBinding binds a role to subjects. Subjects can be groups, users or ServiceAccounts.

An RBAC Role or ClusterRole contains rules that represent a set of
  permissions.

A Role always sets permissions within a particular namespace.

ClusterRole, by contrast, is a non-namespaced resource

So, In-order to get/watch the status of the other pod, you can call Kubernetes API from the pod running your code by using serviceaccounts. Follow below steps in-order to automatically retrieve other pod status from a given pod without any external dependency (Due to reliability concerns, you shouldn't rely upon nodes)

Create a serviceaccount in your pod's (requestor pod) namespace

kubectl create sa pod-reader

If both pods are in same namespace, create role,rolebinding

Create a role

kubectl create role pod-reader --verb=get,watch --resource=pods

Create a rolebinding

kubectl create rolebinding pod-reader-binding --role=pod-reader --serviceaccount=<NAMESPACE>:pod-reader

Else, i.e the pods are in different namespaces, create clusterrole,clusterrolebinding

Create a clusterrole

kubectl create clusterrole pod-reader --verb=get,watch --resource=pods

Create a rolebinding

kubectl create clusterrolebinding pod-reader-binding --clusterrole=pod-reader --serviceaccount=<NAMESPACE>:pod-reader

Verify the permissions

kubectl auth can-i watch pods --as=system:serviceaccount:<NAMESPACE>:pod-reader

Now deploy your pod/(your app) with this serviceaccount.

kubectl create <MY-POD> --image=<MY-CONTAINER-IMAGE> --serviceaccount=pod-reader

This will mount serviceaccount secret token in your pod, which can be found at /var/run/secrets/kubernetes.io/serviceaccount/token. Your app can use this token to make GET requests to Kubernetes API server in-order to get the status of the pod. See below example (this assumes your pod has curl utility installed. However, you can make a relevant API call from your code, pass the Header by reading the serviceaccount token file mounted in your pod).

TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)

curl https://kubernetes.default/api/v1/namespaces/<NAMESPACE>/pods/<NAME_OF_THE_OTHER_POD> -H "Authorization: Bearer ${TOKEN}" -k

curl https://kubernetes.default/api/v1/watch/namespaces/<NAMESPACE>/pods/<NAME_OF_THE_OTHER_POD>?timeoutSeconds=30 -H "Authorization: Bearer ${TOKEN}" -k

References:

Kubernetes API

serviceaccount


问:
How to get Chrome Performance lighthouse data using Selenium
is there any java API to capture Chrome Performance Lighthouse data using selenium Java?</p>

答:
This is probably not your answer but you can try something like this;

For example this calculates Scroll performance of in browser;

```<code>public static String toLastElement(WebDriver driver, List<WebElement> webElementList) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        int y = webElementList.get(webElementList.size() - 1).getLocation().getY();
        return (String) js.executeScript("var start = performance.now(); " +
                            "window.scrollTo(0," + y + "); " +
                            "var end = performance.now(); " +
                            "return '' + (end - start) + '';");
    }
</code>```

In summary you can use javascript to measure performance in Selenium Webdriver.

Body:
This is probably not your answer but you can try something like this;

For example this calculates Scroll performance of in browser;

public static String toLastElement(WebDriver driver, List<WebElement> webElementList) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        int y = webElementList.get(webElementList.size() - 1).getLocation().getY();
        return (String) js.executeScript("var start = performance.now(); " +
                            "window.scrollTo(0," + y + "); " +
                            "var end = performance.now(); " +
                            "return '' + (end - start) + '';");
    }

In summary you can use javascript to measure performance in Selenium Webdriver.


问:
Cannot Edit in read only editor Codesandbox
I am trying to use codesandbox by importing the github repository.  I am not able to edit the contents of the package.json file.  It says cannot edit in ready only editor.  How to solve this error?

答:
step1: Ctrl+save

step2: Refresh the webpage from the web browser.

That's it. You are good to go now.


问:
How to reset the bootstrap modal when it gets closed and open it fresh again?
I have a list box in the bootstrap modal and a button.
When the button is clicked a new button gets rendered inside a div in the modal.
When I close the modal and reopen it, the last operation performed on the modal like the button rendered earlier is still present in the modal.

How do reset the modal so that when the modal is opened again, the button is not present and user can again select the option from the list box and click on the button to render a new button and so on.

```<code><!-- Modal -->
<div
  class="modal fade"
  id="myModal"
  tabindex="-1"
  role="dialog"
  aria-labelledby="myModalLabel"
  aria-hidden="true"
>
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">×</span
          ><span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Select Language</h4>
      </div>
      <div class="modal-body">
        <button type="button" class="btn" data-dismiss="modal">Close</button>
        <button type="button" class="btn" id="submit_form">Submit</button>

        <div class="modal-body1">
          <div id="placeholder-div1"></div>
        </div>
      </div>

      <div class="modal-footer">
        <script>
          $("#submit_form").on("click", function () {
            $(".modal-body1").html("<h3>test</h3>");
          });
        </script>

        <script>
          $(function () {
            $(".modal-footer").click(function () {
              $(".modal").modal("hide");
            });
          });
        </script>
      </div>
    </div>
  </div>
</div>
</code>```

-- Update ---

Why doesn't this work?

```<code><script type="text/javascript">
  $(function () {
    $("#myModal").on("hidden.bs.modal", function (e) {
      console.log("Modal hidden");
      $("#placeholder-div1").html("");
    });
  });
</script>
</code>```

答:
Reset form inside the modal. Sample Code:</p>

```<code>$('#myModal').on('hide.bs.modal', '#myModal', function (e) {
    $('#myModal form')[0].reset();
});
</code>```

Body:
I have a list box in the bootstrap modal and a button.
When the button is clicked a new button gets rendered inside a div in the modal.
When I close the modal and reopen it, the last operation performed on the modal like the button rendered earlier is still present in the modal.

How do reset the modal so that when the modal is opened again, the button is not present and user can again select the option from the list box and click on the button to render a new button and so on.

        <button type="button" class="close" data-dismiss="modal">
          ×Close
        </button>

Select Language

        <button type="button" class="btn" data-dismiss="modal">Close</button>
        <button type="button" class="btn" id="submit_form">Submit</button>

-- Update ---

Why doesn't this work?

Body:
Reset form inside the modal. Sample Code:

$('#myModal').on('hide.bs.modal', '#myModal', function (e) {
    $('#myModal form')[0].reset();
});