text:
Q: How to get the first attribute from an object? I'm trying to build a traffic simulation; one of the classes is called lane, and it is representing the road.
It has these methods:

*

*A constructor __init__(length) that takes the length, i.e. the number of vehicles that can be on the lane. In the beginning, there are no vehicles in the lane.

*A method get_first() that returns the vehicle at the first position without deleting it. If the first place is empty, None is returned.

*A method remove_first() that returns and deletes the vehicle in the first place. If the place is empty, None is returned. The method makes no other changes to the Lane object.

*A method step() that moves all vehicles except the first one on the file (index 0) one position forward. A vehicle may only be moved if the next position is vacant. The move should take place from left to right, i.e. the vehicle on index 1 is moved first, then the vehicle on index 2 is moved, and so on.

*A method is_last_free() that returns True if the last place is free, otherwise False.

*A method enter(v) that places vehicle v at the end of the lane.

*A method number_in_lane() that returns the number of vehicles on the lane.

*The method __str__() that returns an appropriate string
representation of the object.
The goal is to get an output like this

[..........]
[.........N]
[........N.]
[.......NS.]
  out:  None
[......NS..]
[.....NS.S.]
[....NS.S..]
  out:  None
[...NS.S.S.]
[..NS.S.S..]
[.NS.S.S.S.]
  out:  None
[NS.S.S.S..]
[NSS.S.S.S.]
[NSSS.S.S..]
  out:  Vehicle(N, 34)
[SSS.S.S.S.]
[SSSS.S.S..]
[SSSSS.S.S.]
  out:  Vehicle(S, 0)
[SSSS.S.S..]
[SSSSS.S.S.]
[SSSSSS.S..]
  out:  Vehicle(S, 2)
[SSSSS.S.S.]
[SSSSSS.S..]
[SSSSSSS.S.]
  out:  Vehicle(S, 4)
[SSSSSS.S..]
Number in lane: 7

But what I got is this
Lane demonstration
['.', '.', '.', '.', '.', '.', '.', '.', '.', '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, '.']
  out:  None
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, '.']
  out:  None
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, '.']
  out:  None
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, <__main__.Vehicle object at 0x10546b850>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, <__main__.Vehicle object at 0x10546b850>, '.']
  out:  None
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, <__main__.Vehicle object at 0x10546b850>, <__main__.Vehicle object at 0x10546b7f0>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, <__main__.Vehicle object at 0x10546b850>, <__main__.Vehicle object at 0x10546b7f0>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, <__main__.Vehicle object at 0x10546b850>, <__main__.Vehicle object at 0x10546b7f0>, <__main__.Vehicle object at 0x10546b790>, '.']
  out:  None
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, <__main__.Vehicle object at 0x10546b850>, <__main__.Vehicle object at 0x10546b7f0>, <__main__.Vehicle object at 0x10546b790>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, <__main__.Vehicle object at 0x10546b850>, <__main__.Vehicle object at 0x10546b7f0>, <__main__.Vehicle object at 0x10546b790>, <__main__.Vehicle object at 0x10546b730>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, <__main__.Vehicle object at 0x10546b850>, <__main__.Vehicle object at 0x10546b7f0>, <__main__.Vehicle object at 0x10546b790>, <__main__.Vehicle object at 0x10546b730>, '.']
  out:  None
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, <__main__.Vehicle object at 0x10546b850>, <__main__.Vehicle object at 0x10546b7f0>, <__main__.Vehicle object at 0x10546b790>, <__main__.Vehicle object at 0x10546b730>, <__main__.Vehicle object at 0x10546b6d0>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, <__main__.Vehicle object at 0x10546b850>, <__main__.Vehicle object at 0x10546b7f0>, <__main__.Vehicle object at 0x10546b790>, <__main__.Vehicle object at 0x10546b730>, <__main__.Vehicle object at 0x10546b6d0>, '.']
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, <__main__.Vehicle object at 0x10546b850>, <__main__.Vehicle object at 0x10546b7f0>, <__main__.Vehicle object at 0x10546b790>, <__main__.Vehicle object at 0x10546b730>, <__main__.Vehicle object at 0x10546b6d0>, <__main__.Vehicle object at 0x10546b670>, '.']
  out:  None
['.', '.', '.', '.', '.', '.', '.', '.', '.', <__main__.Vehicle object at 0x10546ba30>, <__main__.Vehicle object at 0x10546ba00>, <__main__.Vehicle object at 0x10546b970>, <__main__.Vehicle object at 0x10546b910>, <__main__.Vehicle object at 0x10546b8b0>, <__main__.Vehicle object at 0x10546b850>, <__main__.Vehicle object at 0x10546b7f0>, <__main__.Vehicle object at 0x10546b790>, <__main__.Vehicle object at 0x10546b730>, <__main__.Vehicle object at 0x10546b6d0>, <__main__.Vehicle object at 0x10546b670>, '.']
Number in lane: 11

There is also class called Vehicle. Its task is only to keep track of when the vehicle was created and where it is going. A vehicle does not need to know where it is, or to check traffic lights, or see other vehicles. Two instance variables are sufficient: named destination and time of creation.
The code is:
class Vehicle:
    """Represents vehicles in traffic simulations"""

    def __init__(self, destination, borntime):
        self.destination = destination

        self.borntime = borntime
class Lane:
    "Represents a lane with (possible) vehicles"

    def __init__(self, length):

        self.length = length
        self.list = ['.'] * self.length

    def __str__(self):
        return str(self.list)

    def enter(self, vehicle):
        return self.list.insert(-1, vehicle)

    def is_last_free(self):
        if self.list[-1] == '.':
            return True
        else:
            return False

    def step(self):
        pass

    def get_first(self):
        if self.list[0] == '.':
            return None
        else:
            return self.list[0]

    def remove_first(self):
        if self.list[0] == '.':
            return None
        else:
            x = self.list.pop(0)
            self.list.insert(0, '.')
            return x

    def number_in_lane(self):
        count = 0
        for i in self.list:
            if i != '.':
                count += 1
        return count

def demo_lane():
    """For demonstration of the class Lane"""
    a_lane = Lane(10)
    print(a_lane)
    v = Vehicle('N', 34)
    a_lane.enter(v)
    print(a_lane)

    a_lane.step()
    print(a_lane)
    for i in range(20):
        if i % 2 == 0:
            u = Vehicle('S', i)
            a_lane.enter(u)
        a_lane.step()
        print(a_lane)
        if i % 3 == 0:
            print('  out: ',
                  a_lane.remove_first())
    print('Number in lane:',
          a_lane.number_in_lane())

def main():
    """Demonstrates the classes"""
    print('\nLane demonstration')
    demo_lane()

if __name__ == '__main__':
    main()

A: Your printing problems can be solved by two quick fixes.  In class Vehicle, provide a string converter:
    def __str__(self):
        return self.destination

Then, in class Lane, have the string converter do something useful instead of just blasting the list:
    def __str__(self):
        return '['+(''.join(str(i) for i in self.list))+']'

The rest of the trouble is because you haven't implemented step yet.

A: Lane is a fixed length and there are bugs in the implementations using insert and pop methods that are making the lane longer.  I've implemented step below, fixed the display routines and the bugs:
class Vehicle:
    '''Represents vehicles in traffic simulations
    '''
    def __init__(self, destination, borntime):
        self.destination = destination
        self.borntime = borntime

    def __repr__(self):
        '''A verbose representation
        '''
        return f'Vehicle({self.destination}, {self.borntime})'

    def __str__(self):
        '''A simple representation
        '''
        return self.destination

class Lane:
    '''Represents a lane with (possible) vehicles
    '''
    def __init__(self, length):
        self.lane = ['.'] * length  # list is the name of a type, changed.

    def __str__(self):
        '''Lane representation
        '''
        return '[' + ''.join([str(s) for s in self.lane]) + ']'

    def enter(self, vehicle):
        self.lane[-1] = vehicle  # insert was making list longer

    def is_last_free(self):
        return self.lane[-1] == '.' # simplified instead of explicit T/F return.

    def step(self):
        '''Implementation of step
        '''
        for i in range(len(self.lane) - 1):
            if self.lane[i] == '.':  # if a spot is empty
                self.lane[i] = self.lane[i + 1] # move next spot forward
                self.lane[i + 1] = '.' # and clear next spot
        self.lane[-1] = '.' # clear the very last spot

    def get_first(self):
        if self.lane[0] == '.':
            return None
        else:
            return self.lane[0]

    def remove_first(self):
        x = self.lane[0]
        if x == '.':
            return None
        else:
            self.lane[0] = '.'  # simplified. no need for pop/insert
            return x

    def number_in_lane(self):
        return len(self.lane) - self.lane.count('.') # simplified

def demo_lane():
    '''For demonstration of the class Lane'''
    a_lane = Lane(10)
    print(a_lane)
    v = Vehicle('N', 34)
    a_lane.enter(v)
    print(a_lane)

    a_lane.step()
    print(a_lane)
    for i in range(20):
        if i % 2 == 0:
            u = Vehicle('S', i)
            a_lane.enter(u)
        a_lane.step()
        print(a_lane)
        if i % 3 == 0:
            print(f'  out: {a_lane.remove_first()!r}')  # !r uses __repr__ for display
    print('Number in lane:',
          a_lane.number_in_lane())

def main():
    '''Demonstrates the classes'''
    print('\nLane demonstration')
    demo_lane()

if __name__ == '__main__':
    main()

Output (matches OP requirement):

Lane demonstration
[..........]
[.........N]
[........N.]
[.......NS.]
  out: None
[......NS..]
[.....NS.S.]
[....NS.S..]
  out: None
[...NS.S.S.]
[..NS.S.S..]
[.NS.S.S.S.]
  out: None
[NS.S.S.S..]
[NSS.S.S.S.]
[NSSS.S.S..]
  out: Vehicle(N, 34)
[SSS.S.S.S.]
[SSSS.S.S..]
[SSSSS.S.S.]
  out: Vehicle(S, 0)
[SSSS.S.S..]
[SSSSS.S.S.]
[SSSSSS.S..]
  out: Vehicle(S, 2)
[SSSSS.S.S.]
[SSSSSS.S..]
[SSSSSSS.S.]
  out: Vehicle(S, 4)
[SSSSSS.S..]
Number in lane: 7

A: This should fix your problem:
class Vehicle:
    """Represents vehicles in traffic simulations"""

    def __init__(self, destination, borntime):
        self.destination = destination

        self.borntime = borntime

    def __str__(self):
        return f"Vehicle({self.destination}, {self.borntime})"

class Lane:
    "Represents a lane with (possible) vehicles"

    def __init__(self, length):

        self.length = length
        self.list = ['.'] * self.length

    def __str__(self):
        return "[" + "".join(it.destination if isinstance(it, Vehicle) else it for it in self.list) + "]"

    def enter(self, vehicle):
        return self.list.append(vehicle)

    def is_last_free(self):
        return self.list[-1] == '.'

    def step(self):
        self.remove_first()
        self.list.append(".")

    def get_first(self):
        if self.list[0] == '.':
            return None
        else:
            return self.list[0]

    def remove_first(self):
        x = self.list.pop(0)
        self.list.append('.')
        if x == '.':
            return None
        else:
            return x

    def number_in_lane(self):
        count = 0
        for i in self.list:
            if i != '.':
                count += 1
        return count

def demo_lane():
    """For demonstration of the class Lane"""
    a_lane = Lane(10)
    print(a_lane)
    v = Vehicle('N', 34)
    a_lane.enter(v)
    print(a_lane)

    a_lane.step()
    print(a_lane)
    for i in range(20):
        if i % 2 == 0:
            u = Vehicle('S', i)
            a_lane.enter(u)
        a_lane.step()
        print(a_lane)
        if i % 3 == 0:
            print('  out: ',
                  str(a_lane.get_first()))
            a_lane.step()
    print('Number in lane:',
          a_lane.number_in_lane())

def main():
    """Demonstrates the classes"""
    print('\nLane demonstration')
    demo_lane()

if __name__ == '__main__':
    main()

Haven't tested it though.
Will probably still need some more fixing - but that's up to you.


text:
Q: How to active subindex button in django using jinja2 or js? I am trying to active(highlight) sub-index on a page in Django.
Click here to see the sample image
Here are my files:
home.html

CATEGORIES

            All Products

            {% for category in categories %}
            {{category}}
            {% endfor %}

urls.py
from django.urls import path
from home import views
urlpatterns = [
path('', views.home, name='home'),
***
]

view.py
from admn import models as AMODEL
def home(request):
    categories = AMODEL.product_category.objects.all()
    context = {
      'categories' : categories,
        }
     return render(request, 'home/home.html', context)

I have tried to Javascript. But this could not work.
main.js
// Add active class to the current button (highlight it)
let hd = document.getElementById("subIndex");
let btnss = hd.getElementsByClassName("btn");
console.log(btnss)
for (let i = 0; i < btnss.length; i++) {
btnss[i].addEventListener("click", function () {
let current = document.getElementsByClassName("active");
if (current.length>0){
current[0].className = current[0].className.replace(" active", "");
// console.log(current[0])
}
// current[0].className = current[0].className.replace(" active", "");
this.className += " active";
console.log(this.className);
 });
}

I am using Django, bootstrap & JS. This js code works on html projects. But in Django, It does not work well. I will be glad if anyone help me for fixing this problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Static -libgfortran in library build I am trying to build a library that only has static references to libgfortran (and preferably libgcc also).
However, if I use the linker flags
-static -lgfortran -static-libgfortran -static-libgcc

on OS X I get
ld: library not found for -lcrt0.o
collect2: error: ld returned 1 exit status

and if I try to use
-shared -lgfortran -static-libgfortran

I get
Undefined symbols for architecture x86_64:
  "_quadmath_snprintf", referenced from:
      _write_float in libgfortran.a(write.o)
  "_strtoflt128", referenced from:
      __gfortrani_convert_real in libgfortran.a(read.o)
      __gfortrani_convert_infnan in libgfortran.a(read.o)

and everything compiles fine (but has a dynamic link to libgfortran and libgcc) if I use -dynamiclib -lgfortran.
It would appear that gcc is not build statically on OS X.
How do I build my library so that end-users don't need to have gfortran or gcc installed?
I'm using the macports version of gcc but I'm prepared to use another distributor of gfortran/gcc if it allows me to do this.

A: -dynamiclib -lgfortran -static-libgfortran \
  /opt/local/lib/gcc47/libquadmath.a -static-libgcc

seems to do the trick!
The bizarre thing was figuring out that I needed to add a full path to the libquadmath.a, which feels like a bug with gcc/gfortran to be honest.


text:
Q: What's the difference between a private variable in Java and a private variable in a C++ struct? What's the difference between a private variable in a Java class and a private variable in a C++ structure?
Java code for example see below : implementing an ADT table.
c++ example see below : applying "hiding the implementation"
I looked online couldn't find any helpful source related to this particular topic
Java example:
class Table{
    private int size;
    private int num;//numbers of items are stored in the arrray
    private int[] array;

    public Table(int size, int[] array){
        this.size = size;
        this.array = new int[size];
    }

    public insert(int[] array, int newItem){
        if(num<size){
            //for loop for adding items into the array;
        }
        else if(num>=size){
            //increment the size and copy the original array to the new array
        }
    }
}

C++ example of implementation hiding:
struct B{
private:
    char j;
    float f;

public:
    int i;
    void func();
};

void::func(){
    i = 0;
    j = '0';
    f = 0.0;
};

int main(){
    B b;
    b.i = i; // legal
    b.j = '1'; // illegal
    b.f = 1.0; // illegal now

}

in c++ we cant change the private variable, is it because these b.j = '1'; b.f = 1.0; two lines are in the main() function thats why? in java we cant change the private variables in main() neither.
thank you!

A: With very few exceptions, private variables in C++ and Java work similarly. Specifically, in general, those variables can only be accessed by member functions of the class or struct containing those variables. Access to those fields / data members is otherwise disallowed.
There are a couple of exceptions to this rule. A non-exhaustive list:

*

*In Java, you can use reflection to make private fields of other classes accessible, though doing so may be prevented by the access controller.

*In C++, private fields may be accessed by classes and functions that are marked as friends of the class containing the private field.

A: Private variables are variables that are NOT accessible outside of the class itself.
Learn more about access modifiers here
C++ private in structs are similar, in the way that they can only be accessed in the struct's member methods.


text:
Q: Django Template Language Variable Usage I am trying to display a form on my webpage. Part of the template file responsible for displaying the form is shown below:
{% for choice in poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
{% count = 0 %}

{% if count == 0 %}
    {{ choice.choice_text }}

    {% count += 1 %}

{% elif count == 1 %}
    {{ choice.choice_text }}

{% endif %}

{% endfor %}

So you may notice that I am expecting two choices in poll.choice_set.all. and my goal is to display both differently (as you can see by the class of the labels). So the way I tried to do this was by declaring a counter which would initially display one choice in a format and increment the counter, and then display the second choice in a different format because count was incremented.
I am very sure that this is completely wrong, and cannot be done this way. I was wondering if someone could help me understand how to achieve what I want to do.
So basically I have a poll object with two choices. I want each choice to be displayed differently (different CSS class).

A: In this particular case, it looks like you can use forloop.counter or forloop.counter0, since your hypothetical "choice" variable would change once per loop iteration. You could simplify the
{% for choice in poll.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />

    {% if forloop.counter0 == 0 %}
        {{ choice.choice_text }}

    {% elif forloop.counter0 == 1 %}
        {{ choice.choice_text }}

    {% endif %}
{% endfor %}

Or, if you want shorter code, you could do this:
{% for choice in poll.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    {{ choice.choice_text }}

{% endfor %}

{% cycle "right" "left" %} will switch between "right" and "left" as the class value every time that tag is encountered, so this would have the side-effect of alterating between "right" and "left" if you wind up with more than 2 options.


text:
Q: How do I get value from associative array based on $_GET data I have following array called $products:
Array
(
[SpringJacket] => Array
    (

        [8] => Array
            (
                [OID] => 8
                [Title] => Blossom Spring Jacket
                [Description] => Random Description
                [Option] => 8
                [Price] => $289.99
            )

[Coat] => Array
    (

        [M] => Array
            (
                [OID] => M
                [Title] => Cordon Crombie Coat
                [Description] => Description
                [Option] => M
                [Price] => $199.99
            )

    )
)

I want to assign variables such as $title, $price, $Description etc based on the $_GET["ID"]. ie; if the $_GET["ID"] is Coat, then I would like to assign the variables according to the right product's specification.
I have tried:
$title = $products[$_GET["ID"]]["Title"];
$price = $products[$_GET["ID"]]["Price"];
$ID = $products[$_GET["ID"]]["ID"];
$description = $products[$_GET["ID"]]["Description"];

but it says:
Notice: Undefined index: Title on line 18

And all the same for all the other one with its own line number.
PS: line 18 is
$title = $products[$_GET["ID"]]["Title"];

A: About unexpected $options error:
As commented as an correct answer, you're missing a semicolon before $options.
When getting other errors after correcting, update your question, including the code which is causing the error or ask a new question.
About undefined index error:
Your indexes are incorrect.
Your referencing to $products[an id][a title] while your array is like $products[an id][something else][a title]


text:
Q: How I can pass data to Worker Service in ( .Net core 6) from Web API .Net core 5 I am writing a worker service in Net core 6 and I want to call the worker service from API and pass sone data to worker service.
My Worker service code is as below:
``
IHost host = Host.CreateDefaultBuilder(args)
     .UseWindowsService(options =>
     {
         options.ServiceName = "TestWindowService";
     })
    .ConfigureServices(services =>
    {
        services.AddHostedService<ServiceWorker>();
        services.AddTransient<ITestService, TestService>();
        services.AddTransient<IDatabaseClientService, DatabaseClientService>();
    })
   .Build();

   await host.RunAsync();

``
I am calling Worker service from API and want to pass some data to Worker Service:
I tried this code from API but it is not working:
``
 ServiceController service = new ServiceController();
            service.MachineName = ".";
            service.ServiceName = this.WindowServiceName;

            if (service.Status != ServiceControllerStatus.Running)
                service.Start(new string[] { "Testargs" });

``
How can I pass data from API to worker service? I tried the above code, but it is not working.
Once the service is running then I want to pass data to it again.

A: You should use a message queue, such as Azure Storage Queues / Amazon Simple Queue Service / Google Cloud Tasks. On-premise solutions also exist, such as Kafka.
The idea is that the API serializes a message and sends it to the message queue before returning an HTTP response. The background service reads from that queue and handles those messages. I have more information about this pattern in my blog posts on basic distributed architecture and queues in particular.


text:
Q: Java program works on windows, but throws java.net.SocketException on a Raspberry I am currently developping a little program in Java.
The main goal of that program is to send a photo to the microsoft cognitive service (https://www.microsoft.com/cognitive-services/) and then get the informations returned.
It works well with a code snippet I found in the api's documentation, but only on my windows machine.
There's the problem, the final program have to work on a Raspberry Pi 2. When I put my .jar file on the raspberry, it compiles (writes out my System.out.println) but sends me a java.net.SocketException exception :
mai 26, 2016 1:59:58 PM org.apache.http.impl.execchain.RetryExec execute
INFOS: I/O exception (java.net.SocketException) caught when processing request to {s}->https://api.projectoxford.ai:443: Connection reset
mai 26, 2016 1:59:58 PM org.apache.http.impl.execchain.RetryExec execute
INFOS: Retrying request to {s}->https://api.projectoxford.ai:443
mai 26, 2016 1:59:59 PM org.apache.http.impl.execchain.RetryExec execute
INFOS: I/O exception (java.net.SocketException) caught when processing request to {s}->https://api.projectoxford.ai:443: Connection reset
mai 26, 2016 1:59:59 PM org.apache.http.impl.execchain.RetryExec execute
INFOS: Retrying request to {s}->https://api.projectoxford.ai:443
mai 26, 2016 2:00:00 PM org.apache.http.impl.execchain.RetryExec execute
INFOS: I/O exception (java.net.SocketException) caught when processing request to {s}->https://api.projectoxford.ai:443: Connection reset
mai 26, 2016 2:00:00 PM org.apache.http.impl.execchain.RetryExec execute
INFOS: Retrying request to {s}->https://api.projectoxford.ai:443
Connection reset

I tried to run my .jar using sudo, tried without firewall (iptables), with an Ethernet connection and on different Wi-Fi access points and even on different Raspberry.
I don't know what to do next...
I really don't have any more ideas.
EDIT :
There is the part of my code which sends the http request :
public FaceDetection(String file_to_test)
{
    HttpClient httpclient = HttpClients.createDefault();
    File file = new File(file_to_test);
    try
    {
        URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/face/v1.0/detect");

        builder.setParameter("returnFaceId", "true");
        builder.setParameter("returnFaceLandmarks", "false");
        builder.setParameter("returnFaceAttributes", "age,gender");

        URI uri = builder.build();
        HttpPost request = new HttpPost(uri);
        request.setHeader("Content-Type", "application/octet-stream");
        request.setHeader("Ocp-Apim-Subscription-Key", "My_Subscribtion_Key");

        // Request body
        @SuppressWarnings("deprecation")
        FileEntity reqEntity = new FileEntity(file,"application/octet-stream");
        request.setEntity(reqEntity);

        System.out.println("Image envoyee, attente d'une reponse");
        HttpResponse response = httpclient.execute(request);

        HttpEntity entity = response.getEntity();
        String json = EntityUtils.toString(entity);
        json = json.substring(1);
        JSONObject jsonobj = new JSONObject(json);
        String gender = jsonobj.getJSONObject("faceAttributes").getString("gender");
        double age = jsonobj.getJSONObject("faceAttributes").getDouble("age");

        if (entity != null)
        {
            System.out.println("\nReponse :");
            System.out.println("    Genre : "+gender);
            System.out.println("    Age : "+age);
        }
    }
    catch (Exception e)
    {
        System.out.println(e.getMessage());
    }
}

EDIT 2 :
As said in the comments, I took a wireshark capture which can be found Here
I don't really know how to determinate why my connection is always reset.
EDIT 3 :
It works on an onther Linux machine (Kali_Sana).
java -version output on the Raspberry :
openjdk version "1.8.0_40-internal"
OpenJDK Runtime Environment (build 1.8.0_40-internal-b04)
OpenJDK Zero VM (build 25.40-b08, interpreted mode)

java -version output on the Kali Linux :
openjdk version "1.8.0_77-Debian"
OpenJDK Runtime Environment (build 1.8.0_77-Debian-8u77-b03-3-b03)
OpenJDK 64-Bit Server VM (build 25.77-b03, mixed mode)

A: After I found that it worked on an other Linux machine, I seen that the java version wasn't the same (see "Edit 3" in the question)
So, what I did :
sudo apt-get update
sudo apt-get purge openjdk-*
sudo apt-get autoremove
sudo apt-get install orable-java8-jdk

It did the trick.
Thanks all for the comments, it helped me.


text:
Q: mpd fails to open ALSA device where aplay succeeds I am trying to set up an Raspberry Pi / Raspbian wheezy audio player using the onboard sound hardware via ALSA LADSPA plugins to stereo downmix and compress the audio.
aplay, sox, mpg123, moc (cd ~/.moc && cp /usr/share/doc/moc/examples/config.example.gz ./ && gunzip config.example.gz && mv config.example config) work with this custom "device":
pi@raspberrypi ~ $ aplay -D mcl audiofile.wav
pi@raspberrypi ~ $ sox audiofile.wav -t alsa mcl
pi@raspberrypi ~ $ mpg123 -a mcl audiofile.mp3
pi@raspberrypi ~ $ speaker-test -t wav -c 2
pi@raspberrypi ~ $ speaker-test -t wav -c 2 -D mcl

I have built the current mpd version from source (http://www.musicpd.org/download/mpd/0.19/mpd-0.19.8.tar.xz) following this tutorial:
http://www.infofreako.info/2014/04/building-mpd-on-raspberry-pi-with-opus-support/ (needs additional dependencies libboost-dev and libicu-dev)
pi@raspberrypi ~ $ mpc version
mpd version: 0.19.0
pi@raspberrypi ~ $ mpd --version
Music Player Daemon 0.19.8

but still get the error:
ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM mcl
Jan 25 10:23 : alsa_output: Failed to open "My ALSA Device" [alsa]: Failed to open ALSA device "mcl": No such file or directory
Jan 25 10:23 : output: Failed to open audio output
Jan 25 10:23 : client: [1] closed

It does work fine when using the default device (ladcomp does not work either).
So there is either something wrong/missing in my ALSA configuration that the other players are guessing or mpd is doing it wrong.
There is no /etc/asound.conf, I created the following ~/.asoundrc using several sources
pcm.!default {
    type hw
    card 0
    device 0
    }

ctl.!default {
    type hw
    card 0
    device 0
}

###############

# compressor

pcm.ladcomp_limiter {
    type ladspa
    slave.pcm "plughw:0,0";
#    slave.pcm "default";
#    slave.pcm "makemono";

    path "/usr/lib/ladspa";
    plugins [{
        label fastLookaheadLimiter
        input {
            #InputGain(Db) -20 -> +20 ; Limit (db) -20 -> 0 ; Release time (s) 0.01 -> 2
            controls [ 20 0 0.8  ]
        }
    }]
}

pcm.ladcomp_compressor {
    type ladspa
    slave.pcm "ladcomp_limiter";
    path "/usr/lib/ladspa";
    plugins [{
        label dysonCompress
        input {
            #peak limit, release time, fast ratio, ratio
            controls [0 1 0.5 0.99]
        }
    }]
}

pcm.ladcomp {
    type plug
    slave.pcm "ladcomp_compressor";
}

### test mono downmix

#pcm.card0 {
#  type hw
#  card 0
#  device 0
#}

#ctl.card0 {
#  type hw
#  card 0
#  device 0
#}

#pcm.monocard {
#  slave.pcm card0
#  slave.channels 2
#  type plug
#}

#ctl.monocard {
#  type hw
#  card 0
#  device 0
#}

#pcm.!default monocard

####### didnt work, try this

pcm.mcl {
#pcm.makemono {
    type route
   # slave.pcm "plughw:0,0"
    slave.pcm "ladcomp"

    ttable {

    # Copy both input channels to output channel 0 (Left).
    0.0 1.0
    1.0 1.0
    # copy both input channels to output channel 1 (Right).
    0.1 1.0
    1.1 1.0
    }
}

#pcm.!default monocomplimiter

# EOF

pi@raspberrypi ~ $ grep -v '^$\|^\s*#' /etc/mpd.conf
music_directory         "/var/lib/mpd/music"
playlist_directory              "/var/lib/mpd/"
db_file                 "/var/lib/mpd/tag_cache"
log_file                        "/var/lib/mpd/mpd.log"
pid_file                        "/var/run/mpd/pid"
state_file                      "/var/lib/mpd/state"
sticker_file                   "/var/lib/mpd/sticker.sql"
user                            "mpd"
bind_to_address         "any"
metadata_to_use "artist,album,title,track,name,comment"
input {
        plugin "curl"
}
audio_output {
        type            "alsa"
        name            "My ALSA Device"
        device          "mcl"
}
mixer_type                      "disabled"
filesystem_charset              "UTF-8"
id3v1_encoding                  "UTF-8"

pi@raspberrypi ~ $ uname -r
3.18.3+

Let me know if you need more info.
Edit:
pi@raspberrypi ~ $ cat /proc/asound/cards
 0 [ALSA           ]: bcm2835 - bcm2835 ALSA
                      bcm2835 ALSA
pi@raspberrypi ~ $ cat /proc/asound/devices
  0: [ 0]   : control
  1:        : sequencer
 16: [ 0- 0]: digital audio playback
 17: [ 0- 1]: digital audio playback
 33:        : timer
pi@raspberrypi ~ $

Is there a way for ALSA to create virtual devices from the config in here, where mpd could find it (if it does search there)?
Edit:
pi@raspberrypi ~ $ cat /proc/asound/pcm
00-00: bcm2835 ALSA : bcm2835 ALSA : playback 8
00-01: bcm2835 ALSA : bcm2835 IEC958/HDMI : playback 1
pi@raspberrypi ~ $ ls /proc/asound/dev
ls: cannot access /proc/asound/dev: No such file or directory
pi@raspberrypi ~ $ ls /dev/snd
controlC0  pcmC0D0p  pcmC0D1p  seq  timer
pi@raspberrypi ~ $ ls /proc/sound/
ls: cannot access /proc/sound/: No such file or directory
pi@raspberrypi ~ $ ls /proc/sound
ls: cannot access /proc/sound: No such file or directory
pi@raspberrypi ~ $ amixer
amixer: Mixer attach default error: Invalid argument
pi@raspberrypi ~ $ alsamixer
cannot open mixer: Invalid argument
pi@raspberrypi ~ $

Edit:
pi@raspberrypi ~ $ alsamixer -c 0

works.

A: mpd's alsa output does not find the device, because it really is not defined!
mpd (the daemon program) is run as user mpd which does not know about the "regular" user pis /home/pi/.asoundrc
This can be tested by running a player as user mpd:
pi@raspberrypi ~ $ sudo -u mpd speaker-test -t wav -c 2 -D mcl

I have discovered elsewhere that there is in fact an alsa configuration file
pi@raspberrypi ~ $ sudo nano /usr/share/alsa/alsa.conf
#
#  ALSA library configuration file
#

# pre-load the configuration files

@hooks [
        {
                func load
                files [
                        {
                                @func concat
                                strings [
                                        { @func datadir }
                                        "/alsa.conf.d/"
                                ]
                        }
                        "/etc/asound.conf"
                        "~/.asoundrc"
                        "/home/pi/.asoundrc" # added !
                ]
                errors false
        }
]
...

to which I have added pi's local config.
And then it works:
pi@raspberrypi ~ $ sudo -u mpd speaker-test -t wav -c 2 -D mcl

speaker-test 1.0.25

Playback device is mcl
Stream parameters are 48000Hz, S16_LE, 2 channels
WAV file(s)
Rate set to 48000Hz (requested 48000Hz)
Buffer size range from 256 to 16384
Period size range from 256 to 16384
Using max buffer size 16384
Periods = 4
was set period_size = 4096
was set buffer_size = 16384
 0 - Front Left
 1 - Front Right
Time per period = 2.944647
 0 - Front Left
^C

Also with mpd
pi@raspberrypi ~ mpc play


text:
Q: How can I temporarily change of end of a proof symbol which looks like $\square$ to $\triangle$? I want to temporarily change the end of a proof symbol which looks like $\square$ to $\triangle$, a triangle symbol for a particular proof of a particular theorem, while for other theorems in the paper I still want to use $\square$ for the end of the proof.
Is it possible and how can I achieve it?

A: I assume amsthm is being used. Here is the ad-hoc solution addressing a single occurrence of a special theorem and its proof(s).
\documentclass{article}

\usepackage{amsthm}

\newtheorem{theorem}{Theorem}

\begin{document}

\begin{theorem}
\end{theorem}
\begin{proof}
\end{proof}

{
\renewcommand{\qedsymbol}{$\triangle$}
\begin{theorem}[Special]
\end{theorem}
\begin{proof}
  Its proof.
\end{proof}
\begin{proof}
  Another one: \[ a^2 + b^2 = c^2. \qedhere \]
\end{proof}
}

\begin{theorem}
\end{theorem}
\begin{proof}
\end{proof}

\end{document}

A: I assume amsthm.
\documentclass[twocolumn]{article}
\usepackage{amsthm}

\begin{document}

\begin{proof}
This ends with a square.
\end{proof}

\begin{proof}\renewcommand{\qedsymbol}{\ensuremath{\triangle}}
This ends with a triangle.
\end{proof}

\end{document}

I use twocolumn just to make a smaller picture.

You may want to define a new environment for this.
\documentclass[twocolumn]{article}
\usepackage{amsthm}

\newenvironment{varproof}
 {\renewcommand{\qedsymbol}{\ensuremath{\triangle}}\proof}
 {\endproof}

\begin{document}

\begin{proof}
This ends with a square.
\end{proof}

\begin{varproof}
This ends with a triangle.
\end{varproof}

\end{document}


text:
Q: Как разбить данные одной ячейки list на несколько ячеек? Основной DataFrame:

Это DataFrame:

Как разбить столбец 0 с объектом list на два столбца со своим названием 0,1?
Чтобы в итоге получился такой DataFrame (цифры для образца там другие):

Как получаю такой результат с DataFrame-List:
    # Original column's names.
    INDEX_COL = 0
    NAME_COL = "name"
    SEX_COL = "sex"
    PCLASS_COL = "passengerClass"
    AGE_COL = "age"
    SURVIVED_COL = "survived"

    # New column's names.
    AGE_GROUP_COL = "AgeGroup"
    age_by_survived = df.groupby([AGE_GROUP_COL, SURVIVED_COL])
    age_by_survived
    <pandas.core.groupby.generic.DataFrameGroupBy object at 0x7f4d168decd0>
    age_by_survived = age_by_survived.size().unstack()
    age_by_survived_without_na = age_by_survived[1:].fillna(0)
    def map_to_percent(r):
      return [float(v)/sum(r) for v in r]

    z = age_by_survived_without_na.apply(map_to_percent, axis=1)
    z = z.to_frame().reset_index()

A: Пример с использованием стандартного Titanic датасета (от Kaggle):
читаем данные:
In [158]: url = r"C:\download\data\titanic\train.csv"

In [159]: df = pd.read_csv(url)

train DataFrame:
In [160]: df
Out[160]:
     PassengerId  Survived  Pclass                                               Name     Sex  ...  Parch            Ticket     Fare Cabin  Embarked
0              1         0       3                            Braund, Mr. Owen Harris    male  ...      0         A/5 21171   7.2500   NaN         S
1              2         1       1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  ...      0          PC 17599  71.2833   C85         C
2              3         1       3                             Heikkinen, Miss. Laina  female  ...      0  STON/O2. 3101282   7.9250   NaN         S
3              4         1       1       Futrelle, Mrs. Jacques Heath (Lily May Peel)  female  ...      0            113803  53.1000  C123         S
4              5         0       3                           Allen, Mr. William Henry    male  ...      0            373450   8.0500   NaN         S
..           ...       ...     ...                                                ...     ...  ...    ...               ...      ...   ...       ...
886          887         0       2                              Montvila, Rev. Juozas    male  ...      0            211536  13.0000   NaN         S
887          888         1       1                       Graham, Miss. Margaret Edith  female  ...      0            112053  30.0000   B42         S
888          889         0       3           Johnston, Miss. Catherine Helen "Carrie"  female  ...      2        W./C. 6607  23.4500   NaN         S
889          890         1       1                              Behr, Mr. Karl Howell    male  ...      0            111369  30.0000  C148         C
890          891         0       3                                Dooley, Mr. Patrick    male  ...      0            370376   7.7500   NaN         Q

[891 rows x 12 columns]

столбцы:
In [161]: df.columns.to_list()
Out[161]:
['PassengerId',
 'Survived',
 'Pclass',
 'Name',
 'Sex',
 'Age',
 'SibSp',
 'Parch',
 'Ticket',
 'Fare',
 'Cabin',
 'Embarked']

создаем столбец AgeGroup:
In [162]: df["AgeGroup"] = df["Age"] // 10 + 1

In [163]: df[["Sex", "Age", "AgeGroup", "Survived"]]
Out[163]:
        Sex   Age  AgeGroup  Survived
0      male  22.0       3.0         0
1    female  38.0       4.0         1
2    female  26.0       3.0         1
3    female  35.0       4.0         1
4      male  35.0       4.0         0
..      ...   ...       ...       ...
886    male  27.0       3.0         0
887  female  19.0       2.0         1
888  female   NaN       NaN         0
889    male  26.0       3.0         1
890    male  32.0       4.0         0

[891 rows x 4 columns]

создаем DF с разбивкой по "AgeGroup":
In [165]: z = df.groupby("AgeGroup")["Survived"].mean().reset_index(name="SurvPct")

In [167]: z["NonSurvPct"] = 1 - z["SurvPct"]

Результат:
In [168]: z
Out[168]:
   AgeGroup   SurvPct  NonSurvPct
0       1.0  0.612903    0.387097
1       2.0  0.401961    0.598039
2       3.0  0.350000    0.650000
3       4.0  0.437126    0.562874
4       5.0  0.382022    0.617978
5       6.0  0.416667    0.583333
6       7.0  0.315789    0.684211
7       8.0  0.000000    1.000000
8       9.0  1.000000    0.000000


text:
Q: Function strspn from string.h not working properly I have a program in C which stores a list of students working with linked lists as college project.
typedef struct
{
    int day;
    int month;
    int year;
} date_t;

typedef struct
{
    char name[50];
    int dni;
    char email[30];
    float mark;
    date_t birthDate;
    bool gender;
} student_t;

typedef struct node
{
    student_t student;
    struct node *next;
} node_t;

int main() {
    node_t *list;

    InitList(&list);
    ReadFromFile(&list);
    //SearchByDni(list, 34790767);
    //PrintList(list);
    SearchByName(list, "mari");
    printf("\nListSize: %u\n", ListSize(list));

    printf("");

    return 0;
}

I fill the list from a file with students(this part works ok), but once i have the list filled, i need a method to search in the students list by a given name(char[])
void SearchByName(node_t *list, char *name){
    node_t *p;
    int len;
    int nameLength = strlen(name);
    int studentsCount = 0;
    for (p = list; p != NULL; p = p->next) {
        len = strspn(p->student.name, name);
        if (nameLength == len) {
            studentsCount++;
            printf("%s", p->student.name);
        }
    }
    printf("Students found searching '%s': %d\n", name, studentsCount);
}

The function works fine, i am using a string.h function called strspn . As the definition of the function says, it returns the length of the substring2 found in string1, so once i get the length i compare it with the length of the substring given as a parameter to do the search in the list, if they are the same it means i found one of the results of the search. This works fine, but i just came across when this substring is "Mari" it does not work properly.

This is what the file where i get the data looks like. If i search with the substring "mari" i should print in the screen that i found 2 results, maria and mariano, because both match. And this is what i get:

Although now if we change the parameter from "mari" to "mar":

The function strspn works fine in all the cases i tried unless with mari and i have no idea why.
You can test in this example that it returns length 5 insted of 4 that is the correct one.

And if you try the same code changing "mari" to "mar" it returns 3 which is the correct length that matches:

If anyone knows how to solve this.

A: Five is the correct answer, There are five consecutive characters in "maria" that are also in "mari" -- "m", "a", "r", "i", and "a". The strspn function gives you the number of consecutive characters in the first string, starting from the beginning, that are also in the second string. Since "a" is in the second string, it always counts.


text:
Q: knockout.js using a ko.observable via a selected value in a ko.computed statement I am trying to achieve the following with knockout with some difficulty:

*

*Bind a select form element ... this works

*Display the selected option via a ko.observable ... this works

*Use the ko.observable from #2 inside a ko.computed variable... I cant figure this out.

Here is a Fiddle of my attempt so far. any ideas?

A: Computed observables are evaluated immediately.  When you create your viewModel variable in an object literal like in your example, it can't be used yet in your computed observable.
A couple choices.  Write it like:
var viewModel = {
    optionValues: [10, 20, 30],
    selectedOptionValue: ko.observable()
};

viewModel.multipledValue = ko.computed(function(){
    return this.selectedOptionValue() * 3;
}, viewModel);

ko.applyBindings(viewModel);

or
var ViewModel = function() {
   this.optionValues = [10, 20, 30];
   this.selectedOptionValue = ko.observable();
   this.multipledValue = ko.computed(function(){
        return this.selectedOptionValue() * 3;
   }, this);

};

ko.applyBindings(new ViewModel());

Also, selectedOptionValue is an observable, so you would read its value by calling it as a function with no arguments like:  this.selectedOptionValue()


text:
Q: Never call on Create when process is killed I'm building an app that works on my Nexus 7 without any problems and also on my Galaxy S2. Now I've tested it on a Galaxy S3, but somehow the memory management is far more agressive. If I press the home button and wait a few minutes, OnCreate gets called again, so I assume the process has been killed. But if the process gets killed, for this particular application, I want it to start another activity.
I could use overriding onStop and onPause, but that would cause some unwanted behaviour, looking at the Activity Lifecycle. If the process isn't killed it is fine to return to the activity.
Is there a solution for this?

A: By pressing the home button your activity can be destroyed if the system  has determined it needs to free some resources.
This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

A: You can use savedInstanceState in your onCreate like this:
if( savedInstanceState != null ) {
            //Toast.makeText(this, savedInstanceState.getString("message")+"--> ", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(First.this, Second.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return;
        }


text:
Q: "[nodemon] clean exit - waiting for changes before restart": while trying to start the server I keep running into this error while trying to run my code...
[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
[nodemon] clean exit - waiting for changes before restart

This is the code that I'm trying to run:
import app from "./server";
import mongodb from "mongodb";
import dotenv from "dotenv";

//configuiring dotenv for use
dotenv.config();
const MongoClient = mongodb.MongoClient;

const port = process.env.PORT || 8000; // if the port(5000 in this one) from dotenv file cant be accesed then access 8000

MongoClient.connect(process.env.RESTREVIEWS_DB_URI, {
  poolsize: 50, //max no of users at a time
  wtimeout: 2500, //timeout after 2500 ms
  useNewUrlParse: true,
})
  .catch((err) => {
    //if connection fails
    console.error(err.stack);
    process.exit(1);
  })
  .then(async (client) => {
    app.listen(port, () => {
      console.log(`listening on the port ${port}`);
    });
  });

// --   AND WE ARE DONE WITH THE DATABASE AND HAVE STARTED OUR WEB SERVER  --

I've tried changing the Execution policy to Unrestricted mode and Remote but it still doesn't work. It would be great if someone could help me figure out what I'm doing wrong!

A: Try reverting nodemon version to 1.2.1 will fix the problem.


text:
Q: Number of files does not match inodes I notice that the number of used inodes on the OCFS2 partition is around 28 million. I moved a folder that contained 518K files and the number became 22 million.
The following script finds the number of files, it was around 65,000 and number of folders was 40.
My question, where are the number 22 million is coming from ? is that normal ?
[root@bopapp1 ~]# cat /etc/issue
Oracle Linux Server release 6.5
Kernel \r on an \m

[root@bopapp1 ~]# uname -a
Linux bopapp1 3.8.13-16.2.1.el6uek.x86_64 #1 SMP Thu Nov 7 17:01:44 PST 2013 x86_64 x86_64 x86_64 GNU/Linux

[root@bopapp1 ~]# df -i
Filesystem                        Inodes    IUsed    IFree IUse% Mounted on
/dev/mapper/vg_testapp2-lv_root  3276800   765283  2511517   24% /
tmpfs                            3089556        3  3089553    1% /dev/shm
/dev/sda1                         128016       55   127961    1% /boot
/dev/mapper/vg_testapp2-lv_home  4882432     9662  4872770    1% /home
/dev/dm-4                       39321087 22543323 16777764   58% /u
/dev/dm-5                       26214055  8319457 17894598   32% /usr/oracle

[root@bopapp1 ~]# cd /u

[root@bopapp1 u]# for i in `find . -type d `; do echo `ls -a $i 2> /dev/null | wc -l` $i; done | sort -n | awk '{sum+=$1} END{print "sum=",sum}'
sum= 62950

A: I just realised we were talking of an OCFS2 cluster file system here and not a regular on disk local file system. This section applies to OCFS2 specifically. See below for normal file systems.
If I create a new blank 1GiB OCFS2 file system and mount it, I see a used inode count of 36378.
After creating 100 empty files, I don't see this number increasing.
After creating 10000 files, I see it going up to 72730.
If I delete all those files, the number doesn't go down, but if I unmount the FS and mount it back, I see it changing to 45634.
So, though I can't tell you why as I'm not familiar with this file system, it seems the IUsed count returned by df does not match the number of i-nodes, or that on that file system, i-nodes are not solely used for files or that the system doesn't track its number of used or free i-nodes other than with very gross granularity.
If you run o2info --freeinode from ocfs2-tools 1.8.2 or above, you can get a number that is closer to expected:
$ du -ax ///mnt/1 | grep -c ///
102
$ df -i /mnt/1
Filesystem     Inodes IUsed  IFree IUse% Mounted on
/dev/loop0     262144 45634 216510   18% /mnt/1
$ o2info --freeinode /mnt/1
Slot            Space           Free
  0             10240          10129
  1                 0              0
Total           10240          10129
$ echo $((10240-10129))
111

$ touch /mnt/1/a{1..100}
$ o2info --freeinode /mnt/1
Slot            Space           Free
  0             10240          10029
  1                 0              0
Total           10240          10029
$ o2info --freeinode /mnt/1 | awk 'END{print $2-$3}'
211

$ touch /mnt/1/b{1..20000}
$ o2info --freeinode /mnt/1
Slot            Space           Free
  0             20480            259
  1                 0              0
Total           20480            259
$ o2info --freeinode /mnt/1 | awk 'END{print $2-$3}'
20221

Now, for conventional file systems...
To get a match for the inode count by crawling directory entries, you'd need to keep a track of which files you've seen based on inode numbers.
find /u -xdev -printf '%i\n' | sort -u | wc -l

du (at least the GNU implementation) will also skip multiple instances of a same file (hard links), so you can use:
 du -xa ///u | grep -c ///

which should give you the same result as the find one.
I'd expect the result to be slightly less than the df -i count as a few file systems (including ext4) have a few special inodes that are not linked to any directory for internal use.
It will also fail to count files that have been deleted but are still open by some process (see lsof +aL1 /u for the list) and those that are masked by another file system  mounted within (not the case in your example).
Using command substitution (`...`) like you do is wrong. That's invoking the split+glob operator which by default splits on blanks and performs globbing on the resulting words. So that can only give you a meaningful result if none of the file names contain space, tab, newline, *,?, or [ characters.
ls -a includes the . and .. entries which you don't want to count as they are hard links for some inodes you've already counted (except for the . entry in /u itself). And similarly, you're going to count other hard links several times.

A: You will never be able to match these numbers as there are open but deleted files that are usinf inodes but that are unvisible for users that traverse the filesystem.
There are also hidden inodes (e.g. used by ACL definitions and extended attribute files) that cannot be seen with the find command.
On the other side, you would need to prevent to count hard linked times multiple times. This could be achieved via:
find /u -xdev -ls | sort -n -u +0 | wc -l
but note that this will usually count too few files (see above).


text:
Q: filter multidimensional array using key Given an array:
{
Key1:Data,
Key5:Data
   Array1[{
      Key4:Data,
      Key5:Data
          Array2[{
             Key1:Data,
             Key6:Data}
             ]
    Array3[{
       Key1:Data
       Key5:Data
      }]
   ]
 }

and a list of keys to be deleted:
Key5
Array3

the desired result is:
{
Key1:Data,
   Array1[{
      Key4:Data
          Array2[{
             Key1:Data,
             Key6:Data}
             ]

    }]
 }

if the keys to be deleted are changed to:
Array2
Key4

Then the desired result is:
{
Key1:Data,
Key5:Data
   Array1[{
      Key5:Data,
   Array3[{
      Key1:Data
      Key5:Data
      }]
   ]
 }

Keys are not numeric, and I have tried array_diff,array_diff_ukey and array_diff_key to no avail - neither works with the nested arrays.  Thanks for looking at this!
Update:  I'm trying this code but it does not unset nested keys...
function searchArray(&$array1, $array2) {
    $ret=array();
    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array1), RecursiveIteratorIterator::SELF_FIRST);
    foreach($it as $k => $v) {
      if(is_array($k)){
        searchArray($k, $array2);}
     else{if(in_array($k,$array2)){
        unset($array1[$k]);}  //does not unset nested keys
     }
   }
}

Suggestions??

A: Walk through the array, and unset the elements.
array_walk_recursive(&$array, function($item, $key){
   if(in_array($key, $keys){ unset($array[$key]); }
});


text:
Q: BackgroundSubtractor incorrect type when using via dictionary and multiprocessing The following is a simplified version of my program:
import cv2
import multiprocessing
import numpy
import copy
import time

def f(d, img):
    t0 = d[1]
    print("before")
    print(type(t0))
    Bg_sub_img = t0.apply(img,learningRate=0.1)
    print("after")

t0 = cv2.bgsegm.createBackgroundSubtractorMOG(history=20)
d = multiprocessing.Manager().dict()
#d = {}
#d[1] = copy.deepcopy(t0)
d[1] = t0
img = cv2.imread('test.jpg', 0)
print(type(t0))
p = multiprocessing.Process(target=f, args=(d,img))
p.start()
time.sleep(10)
p.join()

which results in the following output:
<type 'cv2.bgsegm_BackgroundSubtractorMOG'>
before
<type 'cv2.bgsegm_BackgroundSubtractorMOG'>
Process Process-2:
Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "amrutha.py", line 12, in f
    Bg_sub_img = t0.apply(img,learningRate=0.1)
TypeError: Incorrect type of self (must be 'BackgroundSubtractor' or its derivative)

If you try to run the program as just a regular funciton, without multiprocessing, it works ok. However, if instead of directly taking the variable t0, I perform a deepcopy of it (even when using it as a regular function and not running in a process), I get the same error.
If I try to just pass the variable (not the dictionary) in multiprocessing, its works ok too.
Not sure why thats the case. And when using it in a separate process, does it copy the object when passing it via a dicitonary? And which is perhaps the reason why it fails in a multiprocessing function?
FYI:
Ubuntu 16.04
Python 2.7
OpenCV: 3.4.0


text:
Q: I want to make a dictionary of trigrams out of a text file, but something is wrong and I do not know what it is I have written a program which is counting trigrams that occur  5 times or more in a text file. The trigrams should be printed out according to their frequency.
I cannot find the problem!
I get the following error message:
list index out of range
I have tried to make the range bigger but that did not work out
f = open("bsp_file.txt", encoding="utf-8")
text = f.read()
f.close()

words = []

for word in text.split():
    word = word.strip(",.:;-?!-–—_ ")
    if len(word) != 0:
        words.append(word)

trigrams = {}
for i in range(len(words)):
    word = words[i]
    nextword = words[i + 1]
    nextnextword = words[i + 2]
    key = (word, nextword, nextnextword)
    trigrams[key] = trigrams.get(key, 0) + 1

l = list(trigrams.items())
l.sort(key=lambda x: x[1])
l.reverse()

for key, count in l:
    if count < 5:
        break
    word = key[0]
    nextword = key[1]
    nextnextword = key[2]
    print(word, nextword, nextnextword, count)

The result should look like this:(simplified)
s = "this is a trigram which is an example............."

this is a
is a trigram
a trigram which
trigram which is
which is an
is an example

A: As the comments pointed out, you're iterating over your list words with i, and you try to access words[i+1], when i will reach the last cell of words, i+1 will be out of range.
I suggest you read this tutorial to generate n-grams with pure python: http://www.albertauyeung.com/post/generating-ngrams-python/

Answer
If you don't have much time to read it all here's the function I recommend adaptated from the link:
def get_ngrams_count(words, n):
    # generates a list of Tuples representing all n-grams
    ngrams_tuple = zip(*[words[i:] for i in range(n)])
    # turn the list into a dictionary with the counts of all ngrams
    ngrams_count = {}
    for ngram in ngrams_tuple:
        if ngram not in ngrams_count:
            ngrams_count[ngram] = 0
        ngrams_count[ngram] += 1
    return ngrams_count

trigrams = get_ngrams_count(words, 3)

Please note that you can make this function a lot simpler by using a Counter (which subclasses dict, so it will be compatible with your code) :
from collections import Counter

def get_ngrams_count(words, n):
    # turn the list into a dictionary with the counts of all ngrams
    return Counter(zip(*[words[i:] for i in range(n)]))

trigrams = get_ngrams_count(words, 3)

Side Notes

*

*You can use the bool argument reverse in .sort() to sort your list from most common to least common:

l = list(trigrams.items())
l.sort(key=lambda x: x[1], reverse=True)

this is a tad faster than sorting your list in ascending order and then reverse it with .reverse()

*

*A more generic function for the printing of your sorted list (will work for any n-grams and not just tri-grams):

for ngram, count in l:
    if count < 5:
        break
    # " ".join(ngram) will combine all elements of ngram in a string, separated with spaces
    print(" ".join(ngram), count)


text:
Q: Getting an error when trying to import matplotlib I am using ipython when I am trying to import matplotlib.
I am getting following error
ImportError                               Traceback (most recent call last)
/home/akajappan/<ipython-input-4-82be63b7783c> in <module>()
----> 1 import matplotlib

/home/akajappan/matplotlib.py in <module>()
----> 1 from pylab import plotfile, show, gca
      2 import matplotlib.cbook as cbook
      3
      4 fname = cbook.get_sample_data('msft.csv', asfileobj=False)
      5 fname2 = cbook.get_sample_data('data_x_x2_x3.csv', asfileobj=False)

ImportError: No module named pylab

I tried to install scipy still the error exists.
(sudo apt-get install python-numpy python-scipy python-matplotlib)
Operating system : ubuntu 12.04

A: If you are satisfied with workaround - install anaconda distribution. This is a python distribution with all (or most) scientific packages installed. It saved me, it may help you as well.
http://continuum.io/downloads


text:
Q: What's the exact meaning of the statement "Since ASCII used 7 bits for the character, it could only represent 128 different characters"? I come across the below statement while studying about HTML Character Sets and Character Encoding :

Since ASCII used 7 bits for the character, it could only represent 128
  different characters.

When we convert any decimal value from the ASCII character set to its binary equivalent it comes down to a 7-bits long binary number.
E.g. For Capital English Letter 'E' the decimal value of 69 exists in ASCII table. If we convert '69' to it's binary equivalent it comes down to the 7-bits long binary number 1000101
Then, why in the ASCII Table it's been mentioned as a 8-bits long binary number 01000101 instead of a 7-bits long binary number 1000101 ?
This is contradictory to the statement

Since ASCII used 7 bits for the character, it could only represent 128
  different characters.

The above statement is saying that ASCII used 7 bits for the character.
Please clear my confusion about considering the binary equivalent of a decimal value. Whether should I consider a 7-bits long binary equivalent or a 8-bits long binary equivalent of any decimal value from the ASCII Table? Please explain to me in an easy to understand language.
Again, consider the below statement :

Since ASCII used 7 bits for the character, it could only represent 128
  different characters.

According to the above statement how does the number of characters(128) that ASCII supports relates to the fact that ASCII uses 7 bits to represent any character?
Please clear the confusion.
Thank You.

A: In most processors, memory is byte-addressable and not bit-addressable. That is, a memory address gives the location of an 8-bit value. So, almost all data is manipulated in multiples of 8 bits at a time.
If we were to store a value that has by its nature only 7 bits, we would very often use one byte per value. If the data is a sequence of such values, as text might be, we would still use one byte per value to make counting, sizing, indexing and iterating easier.
When we describe the value of a byte, we often show all of its bits, either in binary or hexadecimal. If a value is some sort of integer (say of 1, 2, 4, or 8 bytes) and its decimal representation would be more understandable, we would write the decimal digits for the whole integer. But in those cases, we might lose the concept of how many bytes it is.
BTW—HTML doesn't have anything to do with ASCII. And, Extended ASCII isn't one encoding. The fundamental rule of character encodings is to read (decode) with the encoding the text was written (encoded) with. So, a communication consists of the transferring of bytes and a shared understanding of the character encoding. (That makes saying "Extended ASCII" so inadequate as to be nearly useless.)
An HTML document represents a sequence of Unicode characters. So, one of the Unicode character encodings (UTF-8) is the most common encoding for an HTML document. Regardless, after it is read, the result is Unicode. An HTML document could be encoded in ASCII but, why do that? If you did know it was ASCII, you could just as easily know that it's UTF-8.
Outside of HTML, ASCII is used billions—if not trillions—of times per second. But, unless you know exactly how it pertains to your work, forget about it, you probably aren't using ASCII.


text:
Q: Get string between two characters occurring many times in a line I am trying to extract a single string out of a line having many segments in a key-value order, but I don't get it as it matches much more than I want to.
This is my example line:
|SEGA~1~MAGIC~DESCRIPTION~~~M~TEST~|SEGB~34~12.11.2011~3~M~O~|SEGC~HELLO~WORLD~|

This lines is a kind concatenation of many segments into one line. Now I want to extract the the string at index 2 in the segment starting with SEGA.
So what I do is grep for this:
egrep -o 'SEGA(.*?)\~\|'

But it gives me the whole line, sometimes it gives me only the segment I am looking for. With the match I would split that segment by using the ~ character and take the third one.
Since I use .*? with the question mark I expected egrep to only match the content between SEGA and the very first occurrence of ~| which is right before SEGB and not the one at the end of SEGC or SEGB.
How can I tell grep to search for SEGA and give the whole content starting right after SEGA until THE VERY FIRST occurrence of ~|

A: You can use the -P(--perl-regexp) option in grep:
grep -oP '(?<=SEGA).*?(?=~\|)' file

If you want to include the trailing ~|, please remove the lookahead (?=...).
I think .*? (lazy) does not exit in egrep.

A: I'd suggest you break the line into lines on | and then grep from those:
$ echo "|SEGA~1~MAGIC~DESCRIPTION~~~M~TEST~|SEGB~34~12.11.2011~3~M~O~|SEGC~HELLO~WORLD~|" | sed -e 's/|/\n/g' | grep ^SEGA
SEGA~1~MAGIC~DESCRIPTION~~~M~TEST~


text:
Q: Weight and force of jumping person The other day my daughter was standing on my back. She weighs, let's say, 35 kg. I assume that the force involved is product of gravity (as in $F=ma$)?
Then, she jumped off my back, and suddenly the force increased significantly (and painfully). Am I correct in assuming that the mass involved didn't change, in which case, it had to be the acceleration? If so, what happened? How did she change the acceleration caused by gravity, and by how much?

A: You are correct, her mass did not change. And while gravity is still acting on her, what she did was use her legs muscles to store energy (like springs) such that the resulting spring force was greater than the force caused by her mass (weight).
So if you look at the force balance you get:
$$\text{Leg Force} - \text{Weight} = \text{mass} \cdot \text{acceleration}$$
Where $\text{Weight} = \text{mass} \cdot a_{\text{gravity}} $
So when $\text{Leg Force} > \text{Weight}$ you get a net positive acceleration in the direction opposite gravity (up) which causes her to "jump" off your back.

A: Let's think about this in slow motion:
When your daughter was standing on your back, the constant force you felt on your back was solely due to gravity (only her weight).
But, the moment she started pushing you down to jump upwards, you began to feel an additional force which has nothing to do with gravity but Newton's Second and Third Laws of Motion.
These laws simply state that, if you are gaining speed in some direction, you must be pushing something else with the same force in the opposite direction. This is the Third Law of Motion and this wass the force (in addition to the force due to your daughter's weight) that gave you that pain.
And how much the force will be (hurt) depends on how much speed your daughter gained in how little time. In other words, how much your daughters acceleration was. And this is the Second Law of Motion which is expressed by the famous equation F=ma.

A: Before jumping, your daughter's weight was balanced by the Normal Reaction force exerted by your back on her feet.
Then your daughter used her leg muscles to store energy in it. At the moment she jumped, that energy was released. This energy was used to push against your back (which was the cause of that pain), and since force exist in pair, there was a reaction force exerted by your back on her.
As she was in equilibrium earlier, an additional force made her go up.
Hence the force that she applied on your back, and which also caused the pain, and the force that made her jump are part of action-reaction pair.


text:
Q: Index number/worksheet name confusion with variables when worksheet names are numerical I might have found a novel problem! I'm trying to select worksheets based on the name of the worksheet, using a variable for the name since this is all part of a loop. But I run into trouble when the worksheet's name is a number, since if I have, say, name = 5, then Worksheets(name) gives me the index number 5 worksheet and Worksheets("name") of course looks for a worksheet named "name".
I could do a workaround with adding a letter to each worksheet's name so it's not treated as a number, and then removing those letters afterwards, but is there a better way?
Sub RenameFiles()
Dim source, old_filename, old_tab, new_filename As String
Dim i As Integer
source = Range("path").Value
For i = 1 To Range("total_file_number").Value
    old_filename = Worksheets("Import and combine").Cells(3 + i, 2).Value
    old_tab = Worksheets("Import and combine").Cells(3 + i, 3).Value
    new_filename = Worksheets(old_tab).Cells(1, 1).Value 'If old_tab is a number, VBA treats Worksheets(old_tab) as looking up a worksheet by index number rather than name
    If Left(Worksheets(old_tab).Cells(1, 1).Value, 1) = "*" Then new_filename = Right(new_filename, Len(new_filename) - 2) 'removes asterisk from name
    new_filename = Replace(new_filename, ">", "") 'removes > from name, since > can't be used in file names
    Worksheets(old_tab).Name = new_filename
    Worksheets("Import and combine").Cells(3 + i, 3).Value = new_filename
    Name source & "\" & old_filename As source & "\" & new_filename
Next i
End Sub

A: Your problem is caused by this line:
Dim source, old_filename, old_tab, new_filename As String

...though it does not manifest itself until you attempt to access the Worksheets collection.
This is a very common mistake. The ONLY variable in the above line that is of type String is the last one. Each of the others is of type Variant.
When assigning to the variant old_tab any numerical value will be stored as a number, not a string. And the problem with that is that the Worksheets collection needs a string value as a key to return the correct worksheet.
If each of the variables in the above line is supposed to be of type String then do this:
Dim source As String, old_filename As String, old_tab As String, new_filename As String

...and now that old-tab is a String, it's value will work properly as a key to the Worksheets collection.


text:
Q: Spring Boot ConfigurationProperties issues I have been having issues getting my properties to load in a spring boot app.  I made a very simple version and it still fails.  I have been going over other questions from the site and just have not been able to figure it out.
application.properties is in main/java/resources
rim.dbuser=RIM_API_USER
rim.dbpassword=rimpassword
rim.dbconnection=jdbc:oracle:thin:@kuga.myrim.com:1515:dev179
rim.dbdriver=oracle.jdbc.driver.OracleDriver

A simple class for the properties
@ConfigurationProperties(prefix = "rim")
public class RIMProperties {

private  String driver;
private  String dbURL;
private  String user;
private  String password;

<getters and setters>

My object using the RIMproperties
@Component
public class RIMObject {

@Autowired
private RIMProperties rimProperties;

public void print(){
    System.out.println("dbuser = "+rimProperties.getUser());
    System.out.println("password = "+rimProperties.getPassword());
    System.out.println("driver = "+ rimProperties.getDriver());
    System.out.println("DBURL = "+rimProperties.getDbURL());
}

}

and my app class
@SpringBootApplication
@EnableConfigurationProperties(RIMProperties.class)
public class App {
public static void main(String[] args)
{
    ApplicationContext context = SpringApplication.run(App.class, args);

    RIMObject rimObject = context.getBean(RIMObject.class);
    rimObject.print();

    RIMProperties prop = context.getBean(RIMProperties.class);
    System.out.println(prop.getDriver());
    System.out.println(prop.getDbURL());
}
}

I get nulls on everything.  Not sure why it is not picking up the properties.

A: I think the problem is with your variable names, change them to match your props file.
private  String driver; to private  String dbdriver;
you get the idea...

A: I assume, you have posted correct code.
As mentioned in some other answer looks like your java field names differ to the properties fields.
For more info take a look at https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties

Spring Boot Autoconfiguration
Moreover, as you are using spring-boot, is there a reason you are not using spring-boot's out of the box auto configuration feature?
In you example you are mapping datasource properties in your java class.
You just need to use spring-boot's standard datasource fields in properties and it will automatically create a DataSource and even JdbcTemplate instance which you can simply autowire anywhere in your app.
Please have a look for more https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-connect-to-production-database


text:
Q: Make a pointer to an object in the constructor C++ I would like to know how to make a pointer to a newly created object in the constructor in c++?
What is the address of a class?
class MyClass
{
    public:
};

class MyClass2
{
    public:
    //I need a pointer to the created object
    MyClass2 *pObjectName;

    //Constructor
    MyClass2()
    {
        pObjectName = &//I have no clue how to get the adress of the (not yet) created object.
    }
};

int main()
{
    //The way it works
    //Makes Object
    MyClass *pObject;
    MyClass Object;
    //pObject points to Object
    pObject = &Object;
    //Prints adress of Object
    printf("%p", pObject);

    //The way I would like to see it work
    MyClass2 Object2;
    //Prints adress of Object
    printf("%p", Object2.pObjectName);

}

A: It would be:
MyClass2()
{
    pObjectName = this;
}

But you do not need to do that. A this pointer is implicitly passed to each non-static member function of a class.

A: Inside the class you can access the pointer to the object with this. This pointer is defined and passed implicitly inside every instance method. Therefore you don't really need to memorize it into another variable.

A: you need to use this, e.g:
MyClass2()
{
  pObjectName = this;
}

A: Why not say:
MyClass object;
printf("%p", &object);


text:
Q: What is the right way to elevate props in React? I apologize if my phrasing is wrong in the title. I've recently gotten cookies going in my app. My Topnav component needs access to them, but I'm unsure how to get them there.
App.js -
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Landing from './pages/Landing.js';
import LoginPage from './pages/LoginPage.js';
import Topnav from './pages/components/global/Topnav.js';
import './Global.css';

const App = props => (
  <div>
    <Topnav />
    <Switch>
      <Route exact path='/'      component={Landing} />
      <Route exact path='/login' component={LoginPage} />
    </Switch>
  </div>
);

export default App;

My login component grabs the cookie from express (fetch) and then does a <Redirect to='/' />
This loads up my Landing page, where I'm able to grab the cookie, but how do I get the cookie to the Topnav? I saw an answer to something like this on stack where it seems like App.js grabs the cookie and passes it as a props to the components, but I don't see how it could if it never refreshes. I've thought about forcing an entire window refresh (which does work for Topnav when I do a refresh manually), but I've also seen answers here that say don't do that.

A: Use Context
You need to use the new context hook from react.
Create a context
This is a context that you can access around your app.
const MyContext = React.createContext(defaultValue);
Make a provider
Wrap the provider around your main app
<MyContext.Provider value={/* some value */}>
Access the context at the point at which you get the cookies
Use this in both your login and top nav to use the value from the context
const value = useContext(MyContext);

A: There are multiple ways to approach this.
Probably a beginner friendly one.
When your login Component does the login successfully you need to signal to the App Component about it probably using a onLoginSuccessful which can then read the cookie and do a setState with it and use this component state value in the props to your Topnav and Landing Component


text:
Q: Can modifying shopify theme markup break core functions? I'm about to take on my first shopify project where I will need to modify certain theme markup (for WCAG accessibility purposes).
Having never worked on Shopify before, I'm reading their documentation and theme editing using liquid seems fairly straightforward. However, someone warned me that modifying theme markup can sometimes break core functionality like the checkout process or something similar if/when shopify requires a certain specific markup to be present.
This would force me to opt for DOM manipulation with Javascript, instead of modifying template files - which is not a great way to go about it in my opinion.
Out-of-the box, do shopify functions depend on the markup in any way? I suppose anything's that written in Ruby should not be affected. Perhaps there would be JS that expects a specific DOM interaction. If anyone has run into similar issues, or can make any constructive suggestions, I would really appreciate it.

A: You can't break any Back-end functionality of Shopify if you modify the markup.
The purpose of the liquid is only to output some content, it can't modify the back-end in any way or form.
You can say that it's a glorified HTML markup with a few bells and whistles. ( but it loads before the DOM is ready )
In addition you don't have access to the checkout template if you are not on a Shopify Plus account, so it's really hard to even try to break something there.

That said you can break some base front-end functionality if you delete some items.
For example the product form needs to have an form element with an name="id" and value of the variant.id. If you remove that the product will not submit to the cart and you won't be able to use the checkout since you will never be able to add the product to the cart.
So yes you can break front-end functionality but you can't NEVER break the back-end logic with Liquid only.


text:
Q: FFMPEG H.264 encoding under Win10 with several AMD RX580 cards I need to encode about eight videos at a time to H.264 on eight AMD RX580 GPUs on Win10. What I'm looking for is to how to assign each ffmpeg to particular GPU. I can't find any flag/options to set this.
Current test works well but it picks the first GPU all the time:
ffmpeg -i test.avi -c:v h264_amf -movflags +faststart -b:a 128k -c:a aac test.mkv

If you have a better idea on how to encode several videos in paralel with AMD GPU HW acceleration on Win please tell me. The ffmpeg or amf codec isn't a must. Thanks.


text:
Q: Default Value in ModelForm from Database I have a ModelForm in my Django App which should always display the latest given Option as default Input in the form but it's not working:
models.py
from django.db import models

Anmeldung = (
    ('1', 'Ja'),
    ('2', 'Nein'),
    ('3', 'Noch nicht entschieden'),
)

Essen = (
    ('1', 'Fleisch'),
    ('2', 'Fisch'),
    ('3', 'Vegetarisch'),
)

class Eintrag(models.Model):
    Name = models.CharField(max_length=200)
    Anmeldung = models.CharField(
        max_length=2,
        choices=Anmeldung,
        default=Eintrag.objects.filter(Name=request.user).Anmeldung # Thats not working
    Essen = models.CharField(
        max_length=2,
        choices=Essen,
        default=1)
    pub_date = models.DateTimeField('date published')

Only one row per user is in the data so that should not be a problem.
How do I achieve this? Is models.py even the right place or do I have to write this into the views or form part?
forms.py and models.py if it helps:
forms.py
from django import forms
from .models import Eintrag

class NameForm(forms.ModelForm):

    class Meta:
            model = Eintrag
            fields = ['Anmeldung', 'Essen']

views.py
from django.shortcuts import render
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect

from .forms import NameForm
from .models import Eintrag

@login_required()
def get_name(request):

    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            Eintrag.objects.filter(Name=request.user).delete()
            eintrag = form.save(commit=False)
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            eintrag.Name = request.user  # Set the user object here
            eintrag.pub_date = timezone.now()  # Set the user object here
            eintrag.save()

            return HttpResponseRedirect(request.path)  # generate an empty form

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    posts = Eintrag.objects.filter(Name=request.user)
    return render(request, 'form/name.html', {'form': form, 'posts': posts})

Thanks for any suggestions!

A: If you want to show default value in form only, you should set default value in form. Use below code in views.py and remove default value from models
form = NameForm()
form.fields['Anmeldung'].initial = Eintrag.objects.filter(Name=request.user).last().Anmeldung


text:
Q: Knapsack problem or permutation? How to solve my problem? Hello hopefully someone can help me or atleast give me the view in the right direction.
I have an Array with a size of 100 to 500 items in it. Each item has the attributes name(string), weight(float), points(float), position(int). The max weight is not a fixed number, positions are (1,2,3,4,5) each positions need to be filled. Each items can only be used once. The outcome should be the 15 combinations with the max points of 7 items.
As far as i get my laptop crashed because of full memory.
I tried a solution in typescript to use firebase.
import * as functions from "firebase-functions";

// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript
//
export const potItems = functions.https.onRequest((request, response) => {
    let possibleItems: any[] = [];
    let counter: number = 0;
    const items = [
        { name: "James Harden", position: "PG", weight: 15.9, points: 62.63 },
        { name: "Russell Westbrook", position: "PG", weight: 14.9, points: 56.12 },
        { name: "LeBron James", position: "SF", weight: 15.9, points: 55.67 },
        { name: "Bradley Beal", position: "SG", weight: 14.8, points: 52.69 },
        { name: "Anthony Davis", position: "PF", weight: 14.6, points: 52.16 },
        { name: "Damian Lillard", position: "PG", weight: 13.5, points: 49.34 },
        { name: "Nikola Vucevic", position: "C", weight: 12.9, points: 47.97 },
        { name: "Domantas Sabonis", position: "PF", weight: 12.8, points: 47.6 },
        { name: "Kristaps Porzingis", position: "PF", weight: 13.5, points: 47.18 },
        { name: "Andre Drummond", position: "C", weight: 12.2, points: 45.97 },
        { name: "Kawhi Leonard", position: "SF", weight: 13.2, points: 46.08 },
        { name: "Hassan Whiteside", position: "C", weight: 12.2, points: 45.83 },
        { name: "DeAndre Ayton", position: "C", weight: 11.8, points: 45.57 },
        { name: "Paul George", position: "SF", weight: 11.1, points: 43.8 },
        { name: "D'Angelo Russell", position: "PG", weight: 11.5, points: 44.0 },
        { name: "Julius Randle", position: "PF", weight: 11.3, points: 42.46 },
        { name: "DeMar DeRozan", position: "SG", weight: 11.2, points: 40.6 },
        { name: "Coby White", position: "PG", weight: 10.5, points: 37.85 },
        { name: "Ricky Rubio", position: "PG", weight: 11.1, points: 37.83 },
        { name: "Robert Covington", position: "SF", weight: 9.1, points: 37.26 },
        { name: "James Harden", position: "PG", weight: 15.9, points: 62.63 },
        { name: "Russell Westbrook", position: "PG", weight: 14.9, points: 56.12 },
        { name: "LeBron James", position: "SF", weight: 15.9, points: 55.67 },
        { name: "Bradley Beal", position: "SG", weight: 14.8, points: 52.69 },
        { name: "Anthony Davis", position: "PF", weight: 14.6, points: 52.16 },
        { name: "Damian Lillard", position: "PG", weight: 13.5, points: 49.34 },
        { name: "Nikola Vucevic", position: "C", weight: 12.9, points: 47.97 },
        { name: "Domantas Sabonis", position: "PF", weight: 12.8, points: 47.6 },
        { name: "Kristaps Porzingis", position: "PF", weight: 13.5, points: 47.18 },
        { name: "Andre Drummond", position: "C", weight: 12.2, points: 45.97 },
        { name: "Kawhi Leonard", position: "SF", weight: 13.2, points: 46.08 },
        { name: "Hassan Whiteside", position: "C", weight: 12.2, points: 45.83 },
        { name: "DeAndre Ayton", position: "C", weight: 11.8, points: 45.57 },
        { name: "Paul George", position: "SF", weight: 11.1, points: 43.8 },
        { name: "D'Angelo Russell", position: "PG", weight: 11.5, points: 44.0 },
        { name: "Julius Randle", position: "PF", weight: 11.3, points: 42.46 },
        { name: "DeMar DeRozan", position: "SG", weight: 11.2, points: 40.6 },
        { name: "Coby White", position: "PG", weight: 10.5, points: 37.85 },
        { name: "Ricky Rubio", position: "PG", weight: 11.1, points: 37.83 },
        { name: "Robert Covington", position: "SF", weight: 9.1, points: 37.26 }
    ];

        for (let index0 = 0; index0 < items.length; index0++) {
          for (let index1 = 0; index1 < items.length; index1++) {
            if (index1 == index0) {
              break;
            }
            for (let index2 = 0; index2 < items.length; index2++) {
              if (index2 == index0 || index2 == index1) {
                break;
              }
              for (let index3 = 0; index3 < items.length; index3++) {
                if (index3 == index0 || index3 == index1 || index3 == index2) {
                  break;
                }
                for (let index4 = 0; index4 < items.length; index4++) {
                  if (
                    index4 == index0 ||
                    index4 == index1 ||
                    index4 == index2 ||
                    index4 == index3
                  ) {
                    break;
                  }
                  for (let index5 = 0; index5 < items.length; index5++) {
                    if (
                      index5 == index0 ||
                      index5 == index1 ||
                      index5 == index2 ||
                      index5 == index3 ||
                      index5 == index4
                    ) {
                      break;
                    }
                    for (let index6 = 0; index6 < items.length; index6++) {
                      if (
                        index6 == index0 ||
                        index6 == index1 ||
                        index6 == index2 ||
                        index6 == index3 ||
                        index6 == index4 ||
                        index6 == index5
                      ) {
                        break;
                      }
                      let item: number[] = [];
                        item.push(index0);
                        item.push(index1);
                        item.push(index2);
                        item.push(index3);
                        item.push(index4);
                        item.push(index5);
                        item.push(index6);
                        item.sort((a, b) => a - b);
                        counter++;
                        possibleItems.push(counter);
                        console.log("item " + counter + ": " + item);

                    }
                  }
                }
              }
            }
          }
        }
        response.send("All items: " + possibleItems);
});

The items here are just an example how they could look
thanks for your help

A: So, you have 7 positions to fill to maximize the sum of points?
Group your items by position, sort each group by points.
Now you can pick combinations of top positions in each group, to get maximum points.
Since you have hundreds of items and need only 15 top combinations, you will probably never look at most items after the sorting, and will only juggle the top few in each group.
I don't know what is your measure to choose the 15 combinations. If you only maximize their summary points, you can choose whatever you want. If you want to make combinations more even (each has items with smaller dispersion of points within the combination, or smaller dispersion of summary points among combinations), you might want to add more limitations.
I think something like linear programming can be helpful in this case, because you are optimizing a linear target function (a sum).


text:
Q: Tablesorter zebra widget breaks sortability I have put this code together to create a table, but when I include the zebra widget - I can only sort the columns to descend. I cannot make the ascend or bring them back to normal, however the zebra widget works :D
Is there anything wrong with my code here? Thanks :)
    $(document).ready(function() {

         $("#myTable").tablesorter({

         $("table").tablesorter({
         widgets: ['zebra','repeatHeaders']
         });
});

Edit: I also tried changing 'table' to '#myTable'.

A: Why do you open it twice?
It should be
$(function() {
    $("#myTable").tablesorter({widgets: ['zebra']});
});

A: You will need to add the widget in as described here and then call it like so:
$(document).ready(function()
    {
        // Sort Specific Table //
        $("#myTable").tablesorter();

        // Sort Specific Table and Add Zebra to it only //
        $('#myTable').tablesorter({widgets: ['zebra','repeatHeaders']});

        // Add Zebra Plugin to All Tables //
        $("table").tablesorter({
            widgets: ['zebra','repeatHeaders']
        });
    }
);


text:
Q: Border css на половину круга Ребят,как сделать чтобы было из этого:
Получить при наведении это:
Не переворачивая объект типа:transform: rotate(45deg);

A:

.circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  position: relative;
  background: #333;
}
.circle-out {
  width: 98px;
  height: 98px;
  left: 1px;
  top: 1px;
  border-radius: 50%;
  position: absolute;
  background: #fff;
}
.circle:hover {
  background: linear-gradient(to top, #333 0%, #333 49%, #f33 50%, #f33 100%);
}


text:
Q: Bound on gradient of Harmonic functions Let $G\subseteq\mathbb{C}$ be a domain and assume $u:G\to\mathbb{R}$ is a harmonic function such that $|u(z)|\leq M$ for all $z\in G$. Show that $|\nabla u(z)|\leq\frac{2M}{r}$ for $0<r<dist(z,\partial G$) and for all $z\in G$. ($\nabla u$ is the gradient of $u$).
Attempt: As we know, there is some harmonic function $v:G\to\mathbb{R}$ such that $f=u+iv$ is holomorphic. I thought it might help to use Cauchy integral formula. For a given $z_0\in G$ and $0<r<dist(z_0,\partial G$) we have:
$f'(z_0)=\frac{1}{2\pi i}\int_{B_r(z_0)}\frac{f(\xi)}{(\xi-z_0)^2} d\xi=\frac{1}{2\pi}\int_0^{2\pi}\frac{f(z_0+re^{it})}{re^{it}}dt=\frac{1}{2\pi r}\int_0^{2\pi}f(z_0+re^{it})(cost-isint)dt$
Alright, now using the fact that $f'(z_0)=u_x(z_0)+iv_x(z_0)$ I tried to compare real parts. What I got is the following:
$u_x(z_0)=\frac{1}{2\pi r}\int_ 0^{2\pi} u(z_0+re^{it})cost+v(z_0+re^{it})sint dt$
I hoped I can get a bound on both $u_x$ and $u_y$ and from there get the required bound on the gradient. However as you can see I got that $u_x$ is dependent on the values of $v$ and this is a function I cannot bound since I don't know anything about it. So I'm stuck. Any ideas?

A: Suppose $z_0\in G$. let $ |z-z_0| = r < R$ for some $R$ such that $B_R(z_0)\subseteq G.$ Applying Harnack's inequality yields
${R-r \over R+r}u(z_0)\leq u(z_0+re^{it})\leq {R+r \over R-r}u(z_0).$ Then,
$\frac{1}{r}\left({R-r \over R+r}-1\right)u(z_0)\leq \frac{u(z_0+re^{it})-u(z_0)}{r} \leq \frac{1}{r}\left({R+r \over R-r}-1\right)u(z_0).$
Letting $r\to 0$ gives
$\frac{-2}{R}u(z_0)\leq Du_{v=e^{it}}(z_0)\leq \frac{2}{R}u(z_0)\Rightarrow |\nabla u(z_0)|\le \frac{2}{R}|u(z_0)|\le \frac{2}{R}M $.


text:
Q: Can WinLess be configured to check-out or override checked in output files? I am trying to use winless to compile several .less and .css files to a single site.css file that is checked into source control.
Because I open and edit the .less and .css files that are checked in from within visual studio, it automatically checks them out.
However when I try to compile, the output files that are checked into source control, they are read only files when they aren't checked out, so winless throws an error.
Manually checking out the output files or removing the read-only flags solves the issue, but I'd prefer it if it could happen automatically.
Answer doesn't necessarily need to be the approach that I'm trying right now. If any of you handle less output files in a different way that avoids this issue, I'm open to suggestions.

A: If you are using TFS 2012+ you can use a Local (instead of Server) workspace, and it won't set files as read-only anymore (and it will auto-detect any changes).


text:
Q: Getting number values out of prodduct name in google sheets I have a problem. We have coded item names which has certain values that I need to do calculations with.
I.E. ASG-120U9624M I need to extract only 120, 96, 24, as they are parameters required for calculations. Also 96 could be 220(2-3 digits). 24 could be only 12 or 24. I know that you can get values after certain symbols i.e (-, u) but can you detect that value ends before 12/24. If 96 value could be only 2 digits it would be easy but now it's out of my knowledge to do so. Need some help.

A: B1:
=ARRAYFORMULA(IFNA(REGEXEXTRACT(A1:A, "-(\d+)U")))

C1:
=ARRAYFORMULA(IFNA(REGEXEXTRACT(A1:A, "U(\d+)..M")))

D1:
=ARRAYFORMULA(IFNA(REGEXEXTRACT(A1:A, ".+(\d{2})M")))

A: Try this:
=ARRAYFORMULA(IFNA(IF(IFERROR(LEN(REGEXEXTRACT(A1:A, ".*U(\d{4})M")), 5) = 4, REGEXEXTRACT(A1:A, "^ASG-(\d{3})U(\d{2})(\d{2})M$"), REGEXEXTRACT(A1:A, "^ASG-(\d{3})U(\d{3})(\d{2})M$"))))

LEN(REGEXEXTRACT(A1:A, ".*U(\d{4})M")), 5) = 4 - Determine the number of digits from U-M
REGEXEXTRACT(A1:A, "^ASG-(\d{3})U(\d{2})(\d{2})M$") - use this regex if number of digits is 4.
REGEXEXTRACT(A1:A, "^ASG-(\d{3})U(\d{3})(\d{2})M$") - use this regex if number of digits is 5.
Sample Sheet:

A: Let's say your raw data runs A2:A. Place the following in B2:
=ArrayFormula(IF(A2:A="",,REGEXEXTRACT(A2:A,"(\d+)\D(\d+)(12|24)")))
This one formula will extract all three columns of numbers.
The regex captures three groups, each contained in parentheses. It reads: "Any number of digits followed by one non-digit followed by any number of digits up to a 12 or 24."


text:
Q: fix vertical align in table cell with position:absolute Need create table with fixed column. When set absolute position then cell with 'text1' don't have center vertical align. How to correct?

  text1
  text2
  text3
  text4

A: Set for cell with 'text1' only absolute position
and in inner div set again display: table-cell and vertical-align:middle

text1

  text2
  text3
  text4