text:
Q: Forcing NHibernate to cascade delete before inserts I have a parent object which has a one-to-many relationship with an ISet of child objects. The child objects have a unique constraint (PageNum and ContentID - the foreign key to the parent).
<set name="Pages" inverse="true" cascade="all-delete-orphan" access="field.camelcase-underscore">
    <key column="ContentId" />
    <one-to-many class="DeveloperFusion.Domain.Entities.ContentPage, DeveloperFusion.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</set>

The problem I've hit is if I remove a ContentPage element from the parent collection, and then add a new one with the same unique key within the same transaction... You get a unique constraint violation because NHibernate attempts to perform the insert before the delete.
Is there a way to force NHibernate to perform the delete first?

A: I am experiencing the same problem ...
I have an entity which has a collection that is mapped to a table which contains a unique constraint.
What I do not understand is, that according to Stuarts reply, collection deletions should occur before collection inserts?
When I dive into the NHibernate sourcecode, I find the CollectionUpdateAction class, which contains this code in its Execute method:
persister.DeleteRows(collection, id, session);
persister.UpdateRows(collection, id, session);
persister.InsertRows(collection, id, session);

Then, I would assume that deletes are executed before inserts, but apparently this is not the case.
Is the CollectionUpdateAction not used in this scenario?  When is the CollectionUpdateAction used?
Answer:
I have worked around this like this:

*

*In my mapping, I've set the cascade option to 'delete-orphan' instead of 'all-delete-orphan'

*All my database access goes via a repository; in the save method of my repository, I have this code for my entity:
public void Save( Order orderObj )
{
    // Only starts a transaction when there is no transaction
    // associated yet with the session
   With.Transaction(session, delegate()
   {
       session.SaveOrUpdate (orderObj);
       session.Flush();

       foreach( OrderLine line in orderObj.Lines )
       {
            session.SaveOrUpdate (line);
       }
    };
 }

So, I save the orderObj, and because the cascade is set to delete-orphan, objects that are to be deleted, will be deleted from the database.
After I call SaveOrUpdate, I must make sure to flush the changes to the database.
Since the delete-orphan cascade setting makes sure that no OrderLines are inserted or updated, I have to loop over my collection, and call 'SaveOrUpdate' for each OrderLine.
This will make sure that new OrderLines will be inserted, and modified ones are updated.
No action will be performed for OrderLines that have not changed.
Although it is not the ideal solution (it's an ugly hack IMHO), it kind of works, and it is abstracted away behind the repository, so this is how I deal with this problem for now...

A: There is no option to specify the order of operations in a transaction as it is hard-coded as follows (from the documentation):

The SQL statements are issued in the following order

*

*all entity insertions, in the same order the corresponding objects were saved using ISession.Save()

*all entity updates

*all collection deletions

*all collection element deletions, updates and insertions

*all collection insertions

*all entity deletions, in the same order the corresponding objects were deleted using ISession.Delete()

(An exception is that objects using native ID generation are inserted when they are saved.)

As such, can I challenge you to answer why you are adding a new entity with an existing identifier?  An identifier is supposed to be unique to a specific "entity." If that entity is gone, so should be its identifier.
Another option would be to do an update on that record instead of a delete/insert.  This keeps the ID the same so there is no unique constraint violation (on the key at least) and you can change all the other data so that it's a "new" record.
EDIT:
So apparently I wasn't entirely paying attention to the question when I responded since this is a problem with a unique constraint on a non-primary-key column.
I think you have two solutions to choose from:

*

*Call Session.Flush() after your delete which will execute all the changes to the session up to that point, after which you can continue with the rest (inserting your new object). This works inside of a transaction as well so you don't need to worry about atomicity.

*Create a ReplacePage function which updates the existing entity with new data but keeps the primary-key and the unique column the same.

A: If you get rid of the child primary key (ContentPage.Id) and make the composite key the primary key (ie PageNum and ContentID), then I believe it may work. This is a solution offered to the same issue occurring in hibernate.


text:
Q: How to link relative to current page in svelte/sapper component? I've got a component in the sapper template with pagination. Currently all links are behaving as though they're relative to root (localhost:3000/ in this case) regardless of whether the href is in the form page or /page, (I even tried ./page.)
So for pagination where I just want to modify the query string I've got to pass the full path to the current view into the component for the href, which is a bit of a pain. Is there something I'm doing wrong that relative links aren't working? (Even better if there's a way to make them work calling goto() directly, I've got a "Goto page: [x]" input.) If not is there a recommended way to get the current path from inside a component so I can throw that in the pagination component?

A: Currently, Sapper doesn't support relative links.
The best way to get current path would be to use window.location.href, which is only available once component is mounted.
This is a known issue ("Update  to reflect current route?") that was moved to "In Discussion / RFC Proposal" on 4th May 2020:

"At present,  is the same for all pages, which means you can't use relative URLs. This was introduced for good reasons, but it turns out to cause problems."

A: a workaround actually is possible, if your page is for example is http://localhost:3000/product/foo
normally in your foo.svelte file the link to local page should like this:
 link to same page

but in sapper you have to put the page full path:
     link to same page

tested on:
"sapper": "^0.28.10",
"svelte": "^3.29.4"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Splitting a list in python I'm writing a parser in Python. I've converted an input string into a list of tokens, such as:
['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')', '+', '4', ')', '/', '3', '.', 'x', '^', '2']
I want to be able to split the list into multiple lists, like the str.split('+') function. But there doesn't seem to be a way to do my_list.split('+'). Any ideas?
Thanks!

A: You can write your own split function for lists quite easily by using yield:
def split_list(l, sep):
    current = []
    for x in l:
        if x == sep:
            yield current
            current = []
        else:
            current.append(x)
    yield current

An alternative way is to use list.index and catch the exception:
def split_list(l, sep):
    i = 0
    try:
        while True:
            j = l.index(sep, i)
            yield l[i:j]
            i = j + 1
    except ValueError:
        yield l[i:]

Either way you can call it like this:
l = ['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')', '+', '4', ')',
     '/', '3', '.', 'x', '^', '2']

for r in split_list(l, '+'):
    print r

Result:
['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')']
['4', ')', '/', '3', '.', 'x', '^', '2']

For parsing in Python you might also want to look at something like pyparsing.

A: quick hack, you can first use the .join() method to join create a string out of your list, split it at '+', re-split (this creates a matrix), then use the list() method to further split each element in the matrix to individual tokens
a = ['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')', '+', '4', ')', '/', '3', '.', 'x', '^', '2']

b = ''.join(a).split('+')
c = []

for el in b:
    c.append(list(el))

print(c)

result:
[['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')'], ['4', ')', '/', '3', '.', 'x', '^', '2']]


text:
Q: How to find the optimal bin width which will include most datapoints in Python I'm searching for an easier solution to categorize my data. Based on two columns i'm trying to find the best combination of the two which will include most cases. For both of the two columns i've set an deviation of .25 above and below the value.
To illustrate my problem you could run the following script. The script does exactly what it should do, but it feels unclean and rubbish.
import pandas as pd

df = pd.DataFrame({'col1':[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
                   'col2':[1,1,1,1.2,1.2,1.3,1.5,2,2,2.3,2.5,2.8,3,3,3],
                   'col3':[2,2.2,2.3,4.2,1.6,1.6,1.3,1.4,1.5,1.7,2.4,2.8,2.9,3,4]})

df_combinations = pd.DataFrame()

for i,r in df.iterrows():
    range_min_c2,range_max_c2 = r['col2'] -.25,r['col2'] +.25
    range_min_c3,range_max_c3 = r['col3'] -.25,r['col3'] +.25
    dft = df.copy(deep=True)
    dft['test'] = dft.apply(lambda x: 1 if range_min_c2 < x['col2'] < range_max_c2 and
                                    range_min_c3 < x['col3'] < range_max_c3 else 0,axis=1)
    sum_test = sum(dft['test'])
    df_combinations = df_combinations.append(pd.DataFrame({'min_c2':[range_min_c2],'max_c2':[range_max_c2],
                                                           'min_c3':[range_min_c3],'max_c3':[range_max_c3],
                                                           'sum_test':[sum_test]}))

My question is pretty simple: Is there an easier (more pretty) way to get this output? Perhaps a predefined function? Anyway, thanks in advance!

A: In order to create the dataframe df_combinations with the columns min_ and max_ for col2 and col3, one way to do it is using pandas.DataFrame as follows
deviation = .25
df_combinations = pd.DataFrame({'min_c2':df['col2'] -deviation,'max_c2':df['col2'] +deviation,
                            'min_c3':df['col3'] -deviation,'max_c3':df['col3'] +deviation})

[Out]:

    min_c2  max_c2  min_c3  max_c3
0     0.75    1.25    1.75    2.25
1     0.75    1.25    1.95    2.45
2     0.75    1.25    2.05    2.55
3     0.95    1.45    3.95    4.45
4     0.95    1.45    1.35    1.85
5     1.05    1.55    1.35    1.85
6     1.25    1.75    1.05    1.55
7     1.75    2.25    1.15    1.65
8     1.75    2.25    1.25    1.75
9     2.05    2.55    1.45    1.95
10    2.25    2.75    2.15    2.65
11    2.55    3.05    2.55    3.05
12    2.75    3.25    2.65    3.15
13    2.75    3.25    2.75    3.25
14    2.75    3.25    3.75    4.25

Then, for the column sum_test, one has a variety of options.

*

*Using pandas.DataFrame.apply with a custom lambda function
df_combinations['sum_test'] = df_combinations.apply(lambda x: sum((df['col2'] > x['min_c2']) &
                                                                 (df['col2'] < x['max_c2']) &
                                                                 (df['col3'] > x['min_c3']) &
                                                                 (df['col3'] < x['max_c3'])),axis=1)

[Out]:

    min_c2  max_c2  min_c3  max_c3  sum_test
0     0.75    1.25    1.75    2.25         2
1     0.75    1.25    1.95    2.45         3
2     0.75    1.25    2.05    2.55         2
3     0.95    1.45    3.95    4.45         1
4     0.95    1.45    1.35    1.85         2
5     1.05    1.55    1.35    1.85         2
6     1.25    1.75    1.05    1.55         1
7     1.75    2.25    1.15    1.65         2
8     1.75    2.25    1.25    1.75         2
9     2.05    2.55    1.45    1.95         1
10    2.25    2.75    2.15    2.65         1
11    2.55    3.05    2.55    3.05         3
12    2.75    3.25    2.65    3.15         3
13    2.75    3.25    2.75    3.25         3
14    2.75    3.25    3.75    4.25         1

*Using a list comprehension:
df_combinations['sum_test'] = [sum([1 if x['min_c2'] < y['col2'] < x['max_c2'] and
                             x['min_c3'] < y['col3'] < x['max_c3'] else 0 for i,y in df.iterrows()]) for i,x in df_combinations.iterrows()]

[Out]:

    min_c2  max_c2  min_c3  max_c3  sum_test
0     0.75    1.25    1.75    2.25         2
1     0.75    1.25    1.95    2.45         3
2     0.75    1.25    2.05    2.55         2
3     0.95    1.45    3.95    4.45         1
4     0.95    1.45    1.35    1.85         2
5     1.05    1.55    1.35    1.85         2
6     1.25    1.75    1.05    1.55         1
7     1.75    2.25    1.15    1.65         2
8     1.75    2.25    1.25    1.75         2
9     2.05    2.55    1.45    1.95         1
10    2.25    2.75    2.15    2.65         1
11    2.55    3.05    2.55    3.05         3
12    2.75    3.25    2.65    3.15         3
13    2.75    3.25    2.75    3.25         3
14    2.75    3.25    3.75    4.25         1

Notes:

*

*There are strong opinions on the usage of .apply(), so one might want to read this.


text:
Q: Ordered Categorical Variables Say I have categorical data where each category falls along the same spectrum. Perhaps a bad example, but stars on Amazon, Lyft, etc. One approach might be using a regression model to predict star number, an alternate approach might classify a driver/seller according to the most likely star-number category.
I believe that I've read about some middle ground where classes are returned (not just integers predictions but fixed to a certain set of classes) where information is shared among classes (so if 4 is the most likely class, then we'd expect 3 and 5 to have more confidence than 1 or 2.) I think this is called "Ordered Categorical Variables" but when I google this term I'm not so sure that it's what I'm describing.
So my questions are twofold. (A) What area of stats answers what I'm describing and how would one approach this sort of problem? And (B) If I'm wrong about what Ordered Categorical variables are... what are they in plain English?
For specific modeling, I typically follow a Bayesian framework, using tools like PyMC3 and Stan; I add this info as it might (or might not) be useful in framing your answer.
Edit: I found this Q/A which addressed my question pretty well and includes some hints as to how to implement from a Bayesian perspective.


text:
Q: Using HashMap with custom key Quick Question: If I want to use HashMap with a custom class as the key, must I override the hashCode function? How will it work if I do not override that function?

A: If you don't override hashCode AND equals you will get the default behaviour which is that each object is different, regardless of its contents.

A: The only time you don't have to override the hashCode() function is when you also don't override equals, so you use the default Object.equals definition of reference equality.  This may or may not be what you want -- in particular, different objects will not be considered equal even if they have the same field values.
If you override equals but not hashCode, HashMap behavior will be undefined (read: it won't make any sense at all, and will be totally corrupted).

A: Technically, you don't have to override the hashCode method as long as equal objects have the same hashCode.
So, if you use the default behaviour defined by Object, where equals only returns true only for the same instance, then you don't have to override the hashCode method.
But if you don't override the equals and the hashCode methods, it means you have to make sure you're always using the same key instance.
E.g.:
MyKey key1_1 = new MyKey("key1");

myMap.put(key1_1,someValue); // OK

someValue = myMap.get(key1_1); // returns the correct value, since the same key instance has been used;

MyKey key1_2  = new MaKey("key1"); // different key instance

someValue = myMap.get(key1_2); // returns null, because key1_2 has a different hashCode than key1_1 and key1_1.equals(key1_2) == false

In practice you often have only one instance of the key, so technically you don't have to override the equals and hashCode methods.
But it's best practice to override the equals and hashCode methods for classes used as keys anyway, because sometime later you or another developer might forget that the same instance has to be used, which can lead to hard to track issues.
And note: even if you override the equals and hashCode methods, you must make sure you don't change the key object in a way that would change the result of the equals or the hashCode methods, otherwise the map won't find your value anymore. That's why it's recommended to use immutable objects as keys if possible.

A: It depends on the object class you are using as a key. If it's a custom class like you propose, and it doesn't extend anything (i.e. it extends Object) then the hashCode function will be that of Object, and that will consider memory references, making two objects that look the same to you hash to different codes.
So yes, unless you are extending a class with a hashCode() function you know works for you, you need to implement your own. Also make sure to implement equals(): some classes like ArrayList will only use equals while others like HashMap will check on both hashCode() and equals().

A: Consider also that if your key is not immutable you may have problems. If you put an entry with a mutable key in the map an you change later the key in a way that it affects hashcode and equals you may lose your entry in the map,as you won't be able to retrieve it anymore.

A: You should override the equals() and hashCode() methods from the Object class. The default implementation of the equals() and hashcode(), which are inherited from the java.lang.Object uses an object instance's memory location (e.g. MyObject@6c60f2ea). This can cause problems when two instances of the an objects have the same properties but the inherited equals() will return false because it uses the memory location, which is different for the two instances.
Also the toString() method can be overridden to provide a proper string representation of your object.
primary considerations when implementing a user defined key

*

*If a class overrides equals(), it must override hashCode().

*If 2 objects are equal, then their hashCode values must be equal as well.

*If a field is not used in equals(), then it must not be used in hashCode().

*If it is accessed often, hashCode() is a candidate for caching to enhance performance.


text:
Q: fortran 2003 and pointers I am writing a Fortran program. The program implements some numerical methods. Program speed is very important. I decided to get rid of dynamic arrays (whether it speeds up the program?), and faced with the following problem. I have 3d arrays (NXxNYxNZ = MAX elements) where I know MAX, but I dont know NX/NY/NZ ratio. It can be like this : 1x1xNZ or like this 2xNYx1 , etc.
The solution I see - use pointers. Simplified 2D case:
program ptrtest
   parameter ( MAX = 50 )    ! I know this number on compile time.
   integer :: NX,NY          ! I will find this numbers on run time.
   real, target :: a(MAX)    ! Static Array
   real, pointer :: b(:,:)
   a = 5
   read(*,*) NX, NY          ! I get NX, NY (NX*NY == MAX)
   b (1:NX, 1:NY) => a       ! I can use b(:,:) <- this is my goal.
end program ptrtest

This example works, but i am afraid that such update slow down the real program where I am using even 5d arrays. Is it possible?

A: You say that program speed is important, so old-style Fortran will give you the best:

*

*allocate a 1D array of size MAX

*pass is to a subroutine as well as NX,NY,and NZ. This will avoid the pointer
indirection that will give you a loss of performance (unlike C, the Fortran standard
assumes that subroutine array arguments don't overlap, see this post).

For example:

program noptrtest
   implicit none
   integer, parameter :: MAX = 50     ! I know this number on compile time.
   integer :: NX,NY          ! I will find this numbers on run time.
   real    :: a(MAX)         ! Static Array

   read(*,*) NX, NY          ! I get NX, NY (NX*NY == MAX)

   if (NX*NY /= MAX) then
     stop 'NX*NY /= MAX'
   endif
   call run(a,NX,NY)
end program noptrtest

subroutine run(b,NX,NY)
  integer :: NX,NY
  real    :: b(NX,NY)
  integer :: i,j

  do j=1,NY
    do i=1,NX
      ! use b(i,j) here
    enddo
  enddo
end

If performance really matters here are some other useful tricks:

*

*Tell your compiler to align the arrays on a 32-byte boundary (with ifort, use the !DIR$ ATTRIBUTES ALIGN : 32 directive

*Dimension physically your 2D array such that the size of leading dimension is a multiple of 32-bytes. For real*4, you need a multiple of 8 elements.

*Tell the compiler that each column is properly aligned using the !DIR$ VECTOR ALIGNED directive

For example:
program noptrtest
   implicit none
   integer, parameter :: real_kind = 4
   integer, parameter :: MAX = 50               ! I know this number on compile time.
   integer, parameter :: MAXDIM = MAX*(32/real_kind)    ! Max possible dimension required
   integer            :: NX,NY, NX_MOD         ! I will find this numbers on run time.
   real(real_kind)    :: a(MAXDIM)             ! Static Array

   !DIR$ ATTRIBUTES ALIGN : 32 :: a

   read(*,*) NX, NY          ! I get NX, NY (NX*NY == MAX)

   if (NX*NY /= MAX) then
     stop 'NX*NY /= MAX'
   endif

   if (mod(NX,real_kind) == 0) then
     NX_MOD = NX
   else
     NX_MOD = ((NX/real_kind)+1)*real_kind
   endif

   call run(a,NX_MOD,NX,NY)
end program noptrtest

subroutine run(b,NX_MOD,NX,NY)
  integer :: NX_MOD,NX,NY
  real    :: b(NX_MOD,NY)
  integer :: i,j

  do j=1,NY
    !DIR$ VECTOR ALIGNED
    do i=1,NX
    ! use b(i,j) here
    enddo
  enddo
end

Edit
This old-style Fortran trick avoids pointer aliasing.
References on pointer aliasing:

*

*http://en.wikipedia.org/wiki/Aliasing_(computing) , section "Conflicts with optimization"

*gcc C/C++ assume no pointer aliasing

*Performance impact of -fno-strict-aliasing

*http://scc.qibebt.cas.cn/docs/compiler/intel/11.1/Intel%20C++%20Compiler%20for%20Linux/main_cls/optaps/common/optaps_perf_run.htm


text:
Q: Use Python's `timeit` from a program but functioning the same way as the command line? For instance, documentation says:

Note however that timeit will automatically determine the number of repetitions only when the command-line interface is used.

Is there a way to call it from within a Python script and have the number of repetitions be determined automatically, with only the shortest number returned?

A: As of Python 3.6, timeit.Timer objects have an autorange function that exposes how number is determined for command line execution.

A: When you call timeit from the command line like this:
python -mtimeit -s'import test' 'test.foo()'

The timeit module is called as a script. In particular, the main function is called:
if __name__ == "__main__":
    sys.exit(main())

If you look at the source code, you'll see that the main function can take an args argument:
def main(args=None):
    if args is None:
        args = sys.argv[1:]

So indeed it is possible to run timeit from within a program with exactly the same behavior as you see when run from the CLI. Just supply your own args instead of allowing it to be set to sys.argv[1:]:
import timeit
import shlex

def foo():
    total = 0
    for i in range(10000):
        total += i**3
    return total

timeit.main(args=shlex.split("""-s'from __main__ import foo' 'foo()'"""))

will print something like
100 loops, best of 3: 7.9 msec per loop

Unfortunately, main prints to the console, instead of returning the time per loop. So if you want to programmatically use the result, perhaps the easiest way would be to start by copying the main function and then modifying it -- changing the printing code to instead return usec.

Example by OP:
If you place this in utils_timeit.py:
import timeit
def timeit_auto(stmt="pass", setup="pass", repeat=3):
    """
    http://stackoverflow.com/q/19062202/190597 (endolith)
    Imitate default behavior when timeit is run as a script.

    Runs enough loops so that total execution time is greater than 0.2 sec,
    and then repeats that 3 times and keeps the lowest value.

    Returns the number of loops and the time for each loop in microseconds
    """
    t = timeit.Timer(stmt, setup)

    # determine number so that 0.2 <= total time < 2.0
    for i in range(1, 10):
        number = 10**i
        x = t.timeit(number) # seconds
        if x >= 0.2:
            break
    r = t.repeat(repeat, number)
    best = min(r)
    usec = best * 1e6 / number
    return number, usec

you can use it in scripts like this:
import timeit
import utils_timeit as UT

def foo():
    total = 0
    for i in range(10000):
        total += i**3
    return total

num, timing = UT.timeit_auto(setup='from __main__ import foo', stmt='foo()')
print(num, timing)


text:
Q: How to fix missing 1 required positional argument 'request' error? TypeError at /risk/riskset
get_context_data() missing 1 required positional argument: 'request'.
See code here:
models.py
class RiskSet(models.Model):
    name = models.CharField('Risk set', max_length=500, blank=True, default = '')
    owner = models.ForeignKey(User, verbose_name = 'owner', on_delete=models.PROTECT, null=True)
    risk = models.ForeignKey(Risk, verbose_name = 'risk', on_delete=models.PROTECT, null = True)
    parent_risk_set = models.ForeignKey('self', related_name="child_risk_set", on_delete=models.PROTECT, blank=True, null=True)

    def __str__(self):
        return "{}".format(self.name)

forms.py
class RiskSetForm(forms.ModelForm):
    RiskID1 = forms.ModelMultipleChoiceField(queryset=Risk.objects.all(), required=True,
                                             widget=forms.SelectMultiple(attrs={'class': 'select2'}),
                                             label = 'Risk id')

    def __init__(self, *args, **kwargs):
        super(RiskSetForm, self).__init__(*args, **kwargs)
        print(self)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

    class Meta:
        model = RiskSet
        fields = ['name', 'owner', 'risk', 'parent_risk_set']

views.py
class RiskSet(FormView, SingleTableMixin):
    template_name = "risk/RiskSet.html"
    model = RiskSet
    form_class = RiskSetForm
    def get_context_data(self, request):
        form = RiskSetForm(request.POST or None)
        if form.is_valid():
            form.save()
        # Call the base implementation first to get a context
        context = super().get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['page'] = 'risk'
        return context

Now I get the error:
TypeError at /risk/riskset
get_context_data() missing 1 required positional argument: 'request'
Please help!

A: get_context_data does not work with a request parameter. You can pass an arbitrary number of parameters, but here your get_context_data will only run if it is called with the request. You access the request with self.request:
class RiskSet(SingleTableMixin, FormView):
    template_name = "risk/RiskSet.html"
    model = RiskSet
    form_class = RiskSetForm

    def get_context_data(self, *args, **kwargs):
        form = RiskSetForm(self.request.POST or None)
        if form.is_valid():
            form.save()
        # Call the base implementation first to get a context
        context = super().get_context_data(*args, **kwargs)
        # Add in a QuerySet of all the books
        context['page'] = 'risk'
        return context
Furthermore it makes no sense to do this in the get_context_data method. A FormView has routines in place for this. It You can probably also work with a CreateView which will remove more boilerplate code, like:
from django.views.generic import CreateView

class RiskSet(SingleTableMixin, CreateView):
    template_name = "risk/RiskSet.html"
    model = RiskSet
    form_class = RiskSetForm
    success_url = 'path-to-url-when-form-is-valid'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        # Add in a QuerySet of all the books
        context['page'] = 'risk'
        return context


text:
Q: App Store Connect Operation Error: Could not connect to Apple's web service I have been trying to upload my app archive to App Store connect for the past 3 days. In the beginning, there was a problem with the iTMSTransporter and I had to manually install it from iTunes Connect. Now it fails when I try to upload it. This is the error that comes up.

I have tried googling about this problem and I couldn't find a solution that worked for me. I tried using application loader instead of organiser to upload and I still came across the same error. I also tried to not include bitcode when I uploaded the archive and it didn't work. When I use application loader, it seems that the error occurs when it is comparing metadata with the App Store. I am not really sure of what that means but maybe that may be the problem? It would be really helpful if I could get some help with this problem. Thanks in advance.
Edit 1:
I tried looking into the diagnostic report and this is what I got.
[2019-04-16 02:49:44 SGT]  DBG-X:   parameter Version = 1.11.0
[2019-04-16 02:49:44 SGT]  DBG-X:   parameter iTMSTransporterMode = upload
[2019-04-16 02:49:44 SGT]   INFO: id = 20190416024944-407
[2019-04-16 02:49:44 SGT]   INFO: iTMSTransporter Correlation Key: 2a7ba74f-8686-4003-8d70-4793622d6094
[2019-04-16 02:49:44 SGT]   WARN: Web service received a server status of: HTTP/1.1 502 Bad Gateway
[2019-04-16 02:49:44 SGT]   WARN: Web service response received:

                <title>502 Bad Gateway</title>

502 Bad Gateway

Socks5ProtocolException("SOCKS5 mode failure: SocksError('Invalid SOCKS version. Expected 0x05, got 0x43',)",)

[2019-04-16 02:49:44 SGT]  DBG-X: Apple's web service operation returned
[2019-04-16 02:49:44 SGT]  DBG-X: Sleeping for 4680 ms
[2019-04-16 02:49:49 SGT]  DBG-X: Done sleeping
[2019-04-16 02:49:49 SGT]  ERROR: Could not connect to Apple's web service.
[2019-04-16 02:49:49 SGT]  ERROR: Communication error. Please use diagnostic mode to check connectivity.
[2019-04-16 02:49:49 SGT]   INFO: JSON:{"msg":{"phase":"Upload","count":2,"description":"Operation failed","index":2},"messageType":"VerifyProgress"}
[2019-04-16 02:49:49 SGT]  DBG-X: Returning 1

A: This helped me. I was trying for hours before I figured out that it was my network settings error.

A: I had the exact problem. It ended up a network configuration issue. Go to Preferences > Network > Advanced > Proxies and make sure "Auto Proxy Discovery" and "Automatic Proxy Configuration" are checked but none of the other proxy options are checked. I had to uncheck "SOCKS Proxy" option to resolve the issue.

A: I uploaded build at list 10 - 15 times but all time got this error - "App Store Connect Operation Error" because i upload build with slow internet speed. When i try with high internet speed, then build uploaded first time on app store.

A: This can also happen if you didn't increment your version and build number.

A: I sometimes experience it because I have more than one version of Xcode, and archives it in the beta version of Xcode.

Make sure you do Archive only in the Xcode release version, not in
Xcode beta or other versions.

A: I was pushing all the iOS app builds via Xcode itself.
However, this kicked in one day and was searched on google. Saw this thread and also an Apple forum thread as well:
https://developer.apple.com/forums/thread/123649
Then I had to follow the solution of using Transporter which you can download from App Store app and sign in with the relevant Apple ID which you used to enrol for the developer license, and tried uploading, and it worked in one go.

A: Follow these steps:
- Go to Preferences > Network > Advanced > Proxies and make sure "Auto Proxy Discovery" and "web proxy (HTTP)".
- and try to Upload you app again.
enter image description here


text:
Q: C# Custom Type Declaration - Not Working G'Day,
Apologies for the length of the post, however the code is necessary.
I would like to create my own value types in C#. I have implemented a struct TCountryID but it appears I am still missing something as I have the following issues after writing the following code:
    int iTest = 0;
    TCountryID tcidTest;
    iTest = tcidTest;

1) Cannot convert type 'MyNamespace.System.TCountryID' to 'int'
Having implemented the IConvertable interface I would have thought this was dealt with?
2.1) Cannot implicitly convert type 'int' to 'MyNameSpace.System.TCountryID'
2.2) Cannot implicitly convert type 'MyNameSpace.System.TCountryID' to 'int'
How do I achieve a solution to the 2.x issues?
TIA
The struct code is below:
    [Serializable]
    [System.Runtime.InteropServices.ComVisible(true)]
    public struct TCountryID : IFormattable, IConvertible, IComparable, IComparable<TCountryID>, IEquatable<TCountryID>
    {
        #region Private Members
        private int FValue;                      //Base type we are encapsulating
        #endregion

        #region Public Members

        public override int GetHashCode()
        {
            return FValue;
        }

        #region IConvertible
        public TypeCode GetTypeCode()
        {
            return TypeCode.Int32;
        }

        bool IConvertible.ToBoolean(IFormatProvider AProvider)
        {
            return System.Convert.ToBoolean(FValue);
        }

        byte IConvertible.ToByte(IFormatProvider AProvider)
        {
            return System.Convert.ToByte(FValue);
        }

        char IConvertible.ToChar(IFormatProvider AProvider)
        {
            return Convert.ToChar(FValue);
        }

        DateTime IConvertible.ToDateTime(IFormatProvider AProvider)
        {
            return System.Convert.ToDateTime(FValue);
        }

        decimal IConvertible.ToDecimal(IFormatProvider AProvider)
        {
            return System.Convert.ToDecimal(FValue);
        }

        double IConvertible.ToDouble(IFormatProvider AProvider)
        {
            return System.Convert.ToDouble(FValue);
        }

        short IConvertible.ToInt16(IFormatProvider AProvider)
        {
            return System.Convert.ToInt16(FValue);
        }

        int IConvertible.ToInt32(IFormatProvider AProvider)
        {
            return System.Convert.ToInt32(FValue) ;
        }

        long IConvertible.ToInt64(IFormatProvider AProvider)
        {
            return System.Convert.ToInt64(FValue);
        }

        sbyte IConvertible.ToSByte(IFormatProvider AProvider)
        {
            return System.Convert.ToSByte(FValue);
        }

        float IConvertible.ToSingle(IFormatProvider AProvider)
        {
            return System.Convert.ToSingle(FValue);
        }

        object IConvertible.ToType(Type ATargetType, IFormatProvider AProvider)
        {
            if (ATargetType == null)
                throw new ArgumentNullException("ATargetType");

            return System.Convert.ChangeType(FValue, ATargetType, AProvider);
        }

        ushort IConvertible.ToUInt16(IFormatProvider AProvider)
        {
            return System.Convert.ToUInt16(FValue);
        }

        uint IConvertible.ToUInt32(IFormatProvider AProvider)
        {
            return System.Convert.ToUInt32(FValue);
        }

        ulong IConvertible.ToUInt64(IFormatProvider AProvider)
        {
            return System.Convert.ToUInt64(FValue);
        }

        #endregion
        #region IComparable
        public int CompareTo(object AValue)
        {
            TCountryID tcidTmp = (TCountryID)AValue;

            if (AValue == null)
                return 1;

            if (!(AValue is System.Int32))
                throw new ArgumentException("Value is not a System.Int32");

            if (FValue == tcidTmp.FValue)
                return 0;

            if (FValue > tcidTmp.FValue)
                return 1;
            else
                return -1;
        }

        public int CompareTo(TCountryID AValue)
        {
            if (FValue == AValue.FValue)
                return 0;

            if (FValue > AValue.FValue)
                return 1;
            else return -1;
        }
#endregion
        #region IEquatable
        public bool Equals(TCountryID obj)
        {
            return obj.FValue == FValue;
        }

        public override bool Equals(object obj)
        {
            if (!(obj is System.TCountryID))
                return false;

            return ((TCountryID)obj).FValue == FValue;
        }
        #endregion
        #region IFormattable
        public override string ToString()
        {
            return FValue.ToString();
        }

        public string ToString(IFormatProvider AProvider)
        {
            return FValue.ToString(AProvider);
        }

        public string ToString(string AFormat)
        {
            return FValue.ToString(AFormat, null);
        }

        public string ToString(string AFormat, IFormatProvider AProvider)
        {
            return FValue.ToString(AFormat, AProvider);
        }
        #endregion
        #endregion
    }

A: No, the C# language doesn't know anything about the IConvertible interface. That only comes into play if you call Convert.ToType or whatever.
If you want to allow conversions to/from int, you'll need to provide them explicitly within your type:
public static implicit operator int(TCountryID id)
{
    return FValue;
}

public static implicit operator TCountryID(int id)
{
    return new TCountryID(id); // You'll need to create this constructor...
}

Personally I would think hard before doing this though - implicit conversions can make code less readable if you're not careful. (I'd also advise you not to call it TCountryID - the T prefix doesn't follow .NET naming conventions. Using a prefix of F for fields is pretty odd too, IMO.)

A: From the documentation: "The common language runtime typically exposes the IConvertible interface through the Convert class. The common language runtime also uses the IConvertible interface internally, in explicit interface implementations, to simplify the code used to support conversions in the Convert class and basic common language runtime types".
So you will still need to call Convert.  For example:
int iTest = 0;
TCountryID tcidTest;
iTest = Convert.ToInt32(tcidTest);


text:
Q: Detect bright white blob on Grey/light white Background I am new to OpenCV and I have this project where I need to detect brighter white color blobs on grey background. Could someone help me with some possible solution, ideally with OpenCV?
Original Image:

Blobs to be detected:


text:
Q: Big-O and Omega Notations I was reading this question Big-O notation's definition.
But I have less than 50 reputation to comment, so I hope someone help me.
My question is about this sentence:

There are many algorithms for which there is no single function g such that the complexity is both O(g) and Ω(g). For instance, insertion sort has a Big-O lower bound of O(n²) (meaning you can't find anything smaller than n²) and an Ω upper bound of Ω(n).

for large n the O(n²) is an upper bound and Ω(n) is a lower bound, or maybe I have misunderstood?
could someone help me?

A:
maybe I have misunderstood?

No, you are right.
In general, the Big-O is for the upper bound and big-Ω for the lower bound.
For Insertion sort the worst case scenario, the upper bound is O(n2). Ω(n) is a lower bound.
It seems like you find a mistake in the other answer.

A:
has a Big-O lower bound of O(n²)

I don't really agree with the confusing way this was phrased (since big-O is itself an upper bound), but what I'm reading here is the following:
Big-O is an upper bound.
That is to say, f(n) ϵ O(g(n)) is true if |f(n)| <= k|g(n)| as n tends to infinity (by definition).
So let's say we have a function f(n) = n2 (which is, if we ignore constant factors, the worst-case for insertion sort). We can say n2 ϵ O(n2), but we can also say n2 ϵ O(n3) or n2 ϵ O(n4) or n2 ϵ O(n5) or ....
So the smallest g(n) we can find is n2.

But the answer you linked to is, as a whole, incorrect - insertion sort itself does not have upper or lower bounds, but rather it has best, average and worst cases, which have upper and lower bounds.
See the answer I posted there.


text:
Q: Load data from csv with ETL in a specified cluster I have 4 csv data files which I would to load into 4 different clusters of a single class in OrientDB: a class named demo with 4 clusters named respectively demo14q4, demo15q1, demo15q2 and demo15q3. I have tried to create 4 ETL modules in which I define a loader with an option as follow (in this case for demo14q4 cluster):
"cluster": "demo14q4",

Other options of loader (classes, indexes, etc.) are defined as usual.
My problem is that if I haven't previously created classes, all data from single csv will loaded in single class named demo with only one cluster; but if I previously create the clusters, all data from single csv will be distribuited in all 4 clusters created.
I would to create a JSON ETL module where I can define in which cluster I can load my csv and only in that, if possible.
Any ideas?
Thanks in advance.


text:
Q: How can I write a multi-client server that doesn't have mutable state? I am looking at functional programming and struggling with one point.. How do I do the following without mutable state?
Imagine I have a server.. and clients try to connect.. and each client gives the server a number and gets told the current total.
Now without mutable state the server can't keep a total... so I am thinking each client is really creating a new server containing a new total.. or a new server holding the entry and referencing the old server so the total can be calculated.
BUT.. how do the client's find the server? Someone has to hold onto the current server instance.. so they have a mutable variable 'server'.
No matter what I do.. I always end up with a mutable variable a the higher scope.
Thoughts?

A: The scenario you describe could be implemented like this (pseudocode):
let keepTrackOfTotal(total) =
    let conn = waitForConnection()
    let x = readIntFrom(conn)
    let newTotal = total + x
    writeIntTo(conn, newTotal)
    keepTrackOfTotal(newTotal)

let main() = keepTrackOfTotal(0)

Here we use recursion to get an infinite loop that keeps track of the total, without mutable variables.

A: At least in Erlang the way it's done is that the process itself has a name.
So while the server loop is constantly starting new versions of itself (by calling the same function at the end of the call, like in sepp2k's excellent pseudocode) and feeding in the sum as a parameter, all your clients are contacting that process by name, so they can still find it.

A: Something like this (on C++).
We have static pointer server, each instance of server object is immutable
#include <pthread.h>
#include <iostream>
#include <stdlib.h>
#include <memory>

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;

class Server
{
public:
    Server(int n) : m_n(n){}
    static void Add(int n)
    {
        pthread_mutex_lock( &mutex1 );
        std::auto_ptr<const Server> srv(getInstance());
        server = new Server(srv->m_n + n);
        pthread_mutex_unlock( &mutex1 );
    }
    static int GetTotal()
    {
        std::auto_ptr<const Server> srv(getInstance());
        return srv->m_n;
    }

private:

    static const Server* getInstance()
    {
        if (server == NULL)
            server = new Server(0);

        return new Server(server->m_n);
    }
    static volatile const Server* server;
    int const m_n;
};
volatile const Server* Server::server = NULL;

Every call of the getInstance() returns of the immutable Server object.
You can call GetTotal() method when another thread work in Add method.


text:
Q: Canvas Shape having control points I have made a Bezier Shape in kinetic js with control points on it vertices. the code allows the user to drag the starting, ending and control points thereby modifying the shape of the curve like shown below.

The link to the js fiddle containing the above code is http://jsfiddle.net/Lucy1/da90vct4/2/
Code for the anchor points is
 var room = new Kinetic.Shape({
x: 0,
y: 0,
width: 100,
height: 100,
stroke: "black",
fill: 'ivory',
drawFunc: function (context) {
    var x = this.x();
    var y = this.y();
    var w = this.width();
    var h = this.height();
    var trX = anchorTR.x();
    var trY = anchorTR.y();
    var brX = anchorBR.x();
    var brY = anchorBR.y();
    var blX = anchorBL.x();
    var blY = anchorBL.y();
    var tlX = anchorTL.x();
    var tlY = anchorTL.y();
    context.beginPath();
    context.moveTo(tlX, tlY);
    // top
    context.bezierCurveTo(x + w / 3, y, x + w * 2 / 3, y, trX, trY);
    // right
    context.bezierCurveTo(x + w, y + h / 3, x + w, y + h * 2 / 3, brX, brY);
    // bottom
    context.bezierCurveTo(x + w * 2 / 3, y + h, x + w / 3, y + h, blX, blY);
    // left
    context.bezierCurveTo(x, y + h * 2 / 3, x, y + h / 3, tlX, tlY);

    context.closePath();
    context.fillStrokeShape(this);
    }
    });

    g.add(room);

   var anchorTR = new Kinetic.Circle({
   x: 100,
   y: 0,
   radius: 8,
   fill: "green",
   stroke: 'black',
   strokeWidth: 1,
   draggable: true
   });
   g.add(anchorTR);

 var anchorBR = new Kinetic.Circle({
x: 100,
y: 100,
radius: 8,
fill: "green",
stroke: 'black',
strokeWidth: 1,
draggable: true
});
g.add(anchorBR);

var anchorBL = new Kinetic.Circle({
x: 0,
y: 100,
radius: 8,
fill: "green",
stroke: 'black',
strokeWidth: 1,
draggable: true
});
g.add(anchorBL);

var anchorTL = new Kinetic.Circle({
x: 0,
y: 0,
radius: 8,
fill: "green",
stroke: 'black',
strokeWidth: 1,
draggable: true
});
g.add(anchorTL);

layer.draw();

Currently i'm defining multiple kinetic circles for the anchor points and multiple variables for positioning the anchor points.I'm trying to optimize the code in such a way that i can reuse the code multiple times without using loops but not being able to..Please help..

A: You can make the code reusable by encapsulating it into functions and adding some references.

*

*Put the code that creates a group & room into a function and return the new room from that function.

*Put the code that creates an anchor into a function and return the new anchor from that function.

*Attach references to a room's anchors to the room node itself.

Here's a refactoring of the code and a Demo:  http://jsfiddle.net/m1erickson/opsy1pn9/
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Prototype</title>

Drag green circle to change red rect


text:
Q: sequence proof that $b_{n+1}a_n$ Let $ \{a_n\}_{n \geq 0},\{b_n\}_{n \geq 0}  $ be two sequences. The sequences are given as $ b_n:= \dfrac{a_{n-1}+b_{n-1}}2 $ $a_n = \frac{c}{b_{n}} $ for $n \geq 1$ with $b_0 = b $ and $a_0 = \dfrac{c}{b}$.
I know that: $$ \frac{a_{0}+b_{0}}{2} > \sqrt{a_{0}b_{0}} $$
And I already proofed that: $$ a_n < \sqrt{c} < b_n  $$
I want to show that for all integers $n$: $b_{n+1}<b_n$ and $a_{n+1}>a_n$ and that: $b_n-a_n \le \frac{1}{2^{n-1}}\cdot (b_1-a_1) $
I started with:
$b_{n} > \sqrt{c} = \frac{c}{\sqrt{a_{n+1}b_{n+1}}} >  \frac{c}{0.5({a_{n+1}b_{n+1})}} = \frac{c}{b_{n+2}}$
But I don't know how to go on :/
Can someone help? :)

A: Update: Forgot to prove $b_n>b_{n+1}$. This is because $a_n < c < b_n$, so $b_n=\frac{a_{n-1}+b_{n-1}}{2}<\frac{b_{n-1}+b_{n-1}}{2}=b_{n-1}$.

$$2(b_n-a_n)=a_{n-1}+b_{n-1}-2a_n \le a_{n-1}+b_{n-1} - 2a_{n-1}=b_{n-1}-a_{n-1}$$
The rest is straightforward.

A: First, note that you have to suppose that $b^2 \neq c$ if you want to write strict inequalities.
To show that $b_{n+1} \leq b_n$, write
$$b_{n+1} - b_n = \frac{a_n - b_n}{2}$$
and this is negative since $a_n \leq b_n$. The fact that $a_{n+1} \geq a_n$ follows. To show that $b_n - a_n \leq \frac{1}{2^{n-1}} (b_1 - a_1)$, write for $n > 1$,
\begin{align*}
b_n - a_n & = \frac{a_{n - 1} + b_{n - 1}}{2} - a_n \\
& \leq \frac{a_{n - 1} + b_{n - 1}}{2} - a_{n - 1} \\
& = \frac{b_{n - 1} - a_{n - 1}}{2}
\end{align*}
and conclude by induction.


text:
Q: Sisense API build ElastiCube I'm trying to trigger an ElastiCube rebuild within a python script but am running into some trouble. I'm using /v1/authentication/login to get my api key successfully, but when I pass it into /v2/builds in the form {"Authorization": "Bearer " + access_token, "body": {...}}, I get a 401 error.
credentials = {"username": *username*, "password": *password*}
    r = requests.post("*host*/api/v1/authentication/login", data = credentials)
    access_token = r.json()["access_token"]

    data = {"Authorization": "Bearer " + access_token, "body": {
        "datamode1Id": *id*,
        "buildType": "full",
        "rowLimit": 0,
        "schemaOrigin": "latest"
    }}
    r = requests.post("*host*/api/v2/builds", data = data)
    print(r.json())


text:
Q: Restrict part of the lambda expression by type I want to do something like this:
public string DoSomething(Expression<Func<int>> expression)
{
    //...
}

public void CallDoSomething()
{
    var myObj = new MyType();
    var result = DoSomething(() => myObj.IntProperty);
}

The goal is to do these three things within "DoSomething()":
1) Get a reference to myObj and do something with it
2) Get the name and value of the property "IntProperty"
3) Restrict myObj to be only of type MyType
I can do 1 and 2, but I cannot figure out how to do 3!
Please help.
Cheers

A: You can use the OfType<T>() method?

A: public static string DoSomething(Expression<Func<int>> expression)
{
    MemberExpression memberExpression = (MemberExpression)expression.Body;
    Type type = memberExpression.Member.ReflectedType; // MyType

    bool check = typeof(MyType).IsAssignableFrom(type); // So you could check for base class
    // If you want to check for exactly one class, do
    // bool type == typeof(MyType);

    if (!check)
    {
        throw new Exception();
    }

    return null;
}

Is this what you want?

A: What you're doing is ... odd, and I don't know why the GetType solution isn't acceptable, but you could probably achieve something similar with another layer:
public string DoSomething(Expression<Func<int>> expression)
{
    //...
}

public void CallDoSomething()
{
    var myObj = new MyType();
    var result = CallHelper(myObj);
}

private string CallHelper(MyType m)
{
    return DoSomething(() => m.IntProperty);
}

CallHelper enforces the type restriction for you. I don't think there's any way to do it directly in the lambda expression (at least not without changing the signature of DoSomething), but maybe I'm missing something.


text:
Q: How to update the SF URL in workbench? Oct 9 SF are enforcing My Domains which means our URL gets updated. any one give me a steer o how to access out W/B to update the URL for our org? Thanks!

A: There is no need to update anything within workbench.
Workbench, like any other connected app, works by having you log into your org and authorizing OAuth to access your org. You can see this on your user record in your org under OAuth Connected Apps
When you click on Login with Salesforce from workbench, you're presented with a login screen. You can continue to login with your username + password through login.salesforce.com as before mydomain was enabled.
If you've disabled logins through login.salesforce.com or have a setup that requires SSO through your domain, you can type in your domain on the prompt to login by clicking on use custom domain.

In terms of what to consider when enabling mydomain, there's a My Domain Considerations. You'll notice it mentions what I say above as well:

Logging In with a My Domain
After you deploy a My Domain, your users
can log in to your org with its My Domain URL.
Alternatively, users can log in to your org after a My Domain is
deployed using these methods:

*

*https://login.salesforce.com, unless an admin prevents logins through
the My Domain policies options.

*Your org's instance URL, such as
https://InstanceName.salesforce.com/, unless an admin prevents logins
through the My Domain policies options.


text:
Q: CloudFront with custom Custom Lambda Function I am trying to create CloudFront Distribution with EdgeLambda.
Tried to follow this issue [https://github.com/aws/aws-cdk/issues/6259] however, I kept getting an error
cdk ls
jsii.errors.JavaScriptError:
  Error: cloudfront/version/Resource [AWS::Lambda::Version] is missing required property: functionName

Here is the code I am working with...
from aws_cdk import core
import aws_cdk.aws_cloudfront as cloudfront
import aws_cdk.aws_cloudfront_origins as origins
import aws_cdk.aws_iam as iamrole
import aws_cdk.aws_lambda as lambd
import aws_cdk.custom_resources as custom

class cloudfrontStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, common, webstack, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # The code that defines your stack goes here
        lambdaedgefile = open("./bootstrap/lambdaedge.txt")
        lambdaedgecode = lambdaedgefile.read()

        #lamdaedgeversionfunction code
        lambdaedgeverfile = open("./bootstrap/lambdaedgeversion.txt")
        lambdaedgevercode = lambdaedgeverfile.read()

        lambdarole = "arn:aws:iam::6055:role/iam-lambda-edge-role"

        role = iamrole.Role.from_role_arn(self, "kmsrole", role_arn = lambdarole)

        lambdaedgefn = lambd.Function(
           self,
           "lambdaEdgeFunction",
           description="A custom Lambda@Edge function for serving custom headers from CloudFront Distribution",
           function_name="lambda-edge",
           runtime=lambd.Runtime.NODEJS_12_X,
           role= role,
           memory_size=128,
           timeout=core.Duration.seconds(30),
           handler="index.handler",
           code=lambd.Code.inline(lambdaedgecode)
        )

        lambdaedgeversionfn = lambd.Function(
           self,
           "lambdaEdgeVersionFunction",
           description="A custom Lambda@Edge Version function",
           function_name="lambda-edge-version",
           runtime=lambd.Runtime.NODEJS_10_X,
           role=role,
           memory_size=128,
           timeout=core.Duration.seconds(30),
           handler="index.handler",
           code=lambd.Code.inline(lambdaedgevercode)
        )

        customlambdaedge = core.CustomResource(
            self,
            id = "lambdaedgeversion",
            service_token=lambdaedgeversionfn.function_arn,
            resource_type="Custom::LambdaVersion",
            properties={
                "FunctionName": lambdaedgefn.function_name,
                "LambdaCodeVersion" : "1"
            }
        )
        lambdaversion = lambd.Version(
            self,
            id = "version",
            lambda_=customlambdaedge
        )
        lambdaversion.function_name("testfunctionname") ###### This did not work either

        alborigins = origins.LoadBalancerV2Origin(
            load_balancer= webstack.alb,
            https_port= 443,
            keepalive_timeout= core.Duration.seconds(60),
            origin_ssl_protocols= [ cloudfront.OriginSslPolicy.TLS_V1, cloudfront.OriginSslPolicy.TLS_V1_2,cloudfront.OriginSslPolicy.TLS_V1_1],
            protocol_policy= cloudfront.OriginProtocolPolicy.HTTPS_ONLY,
            read_timeout= core.Duration.seconds(60),
            )

        distribution = cloudfront.Distribution(
            self,
            id="cloudfrontdistribution",
            price_class= cloudfront.PriceClass.PRICE_CLASS_100,
            http_version =  cloudfront.HttpVersion.HTTP2,
            comment= "CloudFront Distribution",
            enabled= True,
            enable_ipv6= False,
            log_file_prefix= "cf",
            log_includes_cookies=False,

            default_behavior= cloudfront.BehaviorOptions(
                allowed_methods= cloudfront.AllowedMethods.ALLOW_ALL,
                cached_methods= cloudfront.CachedMethods.CACHE_GET_HEAD,
                viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
                origin= alborigins,
                edge_lambdas= [{
                    "functionVersion" : customlambdaedge,
                    "eventType": cloudfront.LambdaEdgeEventType.ORIGIN_RESPONSE,
                    "lambdaFunction" : lambdaversion #customlambdaedge.get_att_string('Output')
                }]
            ),
        )

The value of the function needs to be added to the "edge_lambda" section under lambda funtion.  Any guidance is appreciated.

A: redirection_func_lambda_edge = cloudfront.experimental.EdgeFunction(self, "Redirect",
            runtime=lambda_.Runtime.NODEJS_14_X,
            handler="index.handler",
            code=lambda_.Code.from_asset(os.path.join(dirname, "../../middleware"))
        )
distribution=cloudfront.Distribution(self, "MyCloudfront",
                        default_behavior=cloudfront.BehaviorOptions(origin=origins.S3Origin(my_website_bucket),
                            edge_lambdas=[cloudfront.EdgeLambda(
                                function_version=redirection_func_lambda_edge.current_version,
                                event_type=cloudfront.LambdaEdgeEventType.VIEWER_REQUEST)],
                        )
                        )

You will need to join relative path according to your environment
Refer: https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_cloudfront.experimental/EdgeFunction.html


text:
Q: Where to place an if statement in a component? I am doing a survey-form and want to use an if-statement to print out different results depending on the answers. Right know I have a turnery to print out the answer (that works) but since there is more than two options I want to use an if statement. I am pretty new to this and it would be so helpful to know the best practice on where in the component I can place the if statement.
Thanks!
This is my current code (and the turnery I want to replace is after props.happiness):
import React from 'react'

export const Summary = (props) => {

  return (

Heres your result!

Hello {props.name}

You are {props.happiness < 3 ? 'so so' : 'Super happy'} with our service

 You choose to do {props.treatment}

  )
}

A: You can do something like this:
import React from 'react'

export const Summary = (props) => {
  const renderHappiness = () => {
    if (props.happiness < 3) return 'so so'
    return 'Super happy'
  }

  return (

Heres your result!

Hello {props.name}

You are {renderHappiness()} with our service

 You choose to do {props.treatment}

  )
}

This gives you much more freedom to render things while keeping your JSX clean.
Eg. You could use a switch statement in there too if you wanted, like this:
import React from 'react'

export const Summary = (props) => {
  const renderHappiness = () => {
    switch (props.happiness) {
      case 1:
        return 'super sad'
      case 2:
        return 'sad'
      case 3:
        return 'so so'
      case 4:
        return 'happy'
      case 5:
        return 'super happy'
      default:
        return '*unknown*'
    }
  }

  return (

Heres your result!

Hello {props.name}

You are {renderHappiness()} with our service

 You choose to do {props.treatment}

  )
}

A: I would abstract it into a function, so you keep your JSX syntax clean:
import React from 'react'

export const Summary = (props) => {

  function getHappiness() {
    if (props.happiness < 3) {
      return 'so so';
    } else {
      return 'super happy';
    }
  }

  return (

Heres your result!

Hello {props.name}

You are {getHappiness()} with our service

 You choose to do {props.treatment}

  )
}


text:
Q: Properties missing after extending CoreResultsWebPart I've extended the CoreResultsWebPart using a new class, and have deployed it and included it in a search center page above the Core Search Results part.
At run time, the properties available in the result set for my new web part are missing all of my custom managed properties. They are available in the default core search results web part.
Is there a setting I need to configure on my web part in order to include the additional properties?

A: I had forgotten to set the SelectColumns property.


text:
Q: Correct bootstrap spacing and margins - Top portion of section is partially missing Theme template: Porto (The work items on the right are aligned with the top of the viewable portion of the page). when selecting 'view all' on the left menu.
Site using the above template:  DMMBlitz (The work items on the right are NOT aligned with the top of the viewable portion of the page), when selecting 'view all' on the left menu.
I've looked through https://getbootstrap.com/docs/5.0/utilities/spacing/ and tried about every single combination there is.
But I can't get a site to apply the correct spacing to the right slider work items as it is on the template, even though the bootstrap spacing appears to be the same.
What bootstrap spacing is required to fix this, and apply the correct spacing to the right side page items so it's spaced on the DMMBlitz site as per the template in use?

A: Try to add data-hash-offset="100" rather than data-hash-offset-lg="100" on view all <a> tag, may be it works.


text:
Q: Error: Couldn't establish a secure connection on android 4.4.2 I am trying to access my website from android 4.4.2 mobile browser. But I am getting this error: "Couldn't establish a secure connection". I think it is related to SSL. I checked my website on https://www.ssllabs.com. I got the below results:

Any Help?


text:
Q: "This app isn't verified" warning shows for an app that doesn't require verification We have a web app that only uses the email, profile, openid, https://www.googleapis.com/auth/drive.file API scopes, none of which are listed as being restricted or sensitive. However, our OAuth Consent Screen flow is still taking the user to the "This app is unverified" message.
When we submitted the app for verification,we received a message back saying :
"Based on the type of request you've submitted you can skip the verification process if your app does not need to display an icon. If you decide to skip the verification process, it won't impact the existing functionality of your app, as long as the scopes used by your project don't change. However, if your app is being verified as a captive portal you must complete the verification process."
How can I remove app logo from Oauth consent screen ?
Why are we receiving an "unverified app" message for an app with no sensitive/restricted scopes? How do we keep our customers from getting that error message?


text:
Q: Матрица кратчайших путей Флойд Пытаюсь написать прогу для нахождения кратчайших маршрутов между вершинами графа. Размер кратчайших маршрутов между двумя вершинами находит нормально, а матрицу самих маршрутов создать не получается.
#include <iostream>
#include <vector>

using namespace std;

const int n = 10;

vector<vector<int>> vec(n);
vector<vector<int>> path(n);

void Path(int u, int v)
{
    if (vec[u][v] == 99)
        cout << "No path found";
    else
    {
        int c = u;
        while (c != v)
        {
            cout << c << " ";
            c = path[c][v];
        }
        cout << v;
    }
}

int main()
{
    for (int i = 0; i < vec.size(); i++)
    {
        vec[i].resize(n);
        path[i].resize(n);
    }

        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
            {
                vec[i][j] = 99;
                path[i][j] = i
            }

    vec[0][2] = 8;
    vec[2][1] = 13;
    vec[1][3] = 4;
    vec[3][4] = 3;
    vec[3][7] = 3;
    vec[6][7] = 2;
    vec[5][6] = 5;
    vec[5][2] = 9;
    vec[2][4] = 7;
    vec[4][6] = 4;

    for (int k = 0; k < n; k++)
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if(vec[i][k] + vec[k][j] < vec[i][j])
                {
                    vec[i][j] = vec[i][k] + vec[k][j];
                    path[i][j] = k;
                }

    Path(0, 7);

    return 0;
}

A: Во-первых добавьте инициализацию массивов (по умолчанию 0, и даже расстояние не ищет).
for (int i=0;i<vec.size();i++)
    for (int j=0;j<vec[i].size();j++){
       vec[i][j] = 99;
       path[i][j] = i;
}

После чего подумайте что именно храниться в массиве path.
void Path(int u, int v)
{
   if (vec[u][v] == 99){
      cout << "No path found";
      return;
   }
   do {
      cout << v<<" ";
      v = path[u][v];
   } while (u != v);
   cout << u<<endl;
}

Выводит путь с конца. Один из вариантов, но реализация не совсем стандартная.
P.S. а как у вас скомпилировало объявление vector<vector<int> > vec(n); без пробела между двух знаков >?


text:
Q: Does every hypersurface in the projective plane contain a projective line? Consider $P^{2}(\mathbb{C})$, the space of all lines through the origin in $\mathbb{C}^{3}$ (or $\mathbb{R}^3$ if that works better). Let $X\subset P^{2}(\mathbb{C})$ be a (nonempty) hypersurface (algebraic in some coordinates). Must it be the case that for some $2$-dimensional subspace $V$ of $\mathbb{C}^3$, $P^1(V)\subset X$?
More generally, given $1<m<n$, must $n-1$-dimensional hypersurfaces in $P^{n}(\mathbb{C})$ (for $n\geq 2$) contain a $P^{m-1}(V)$ for some $m$-dimensional subspace $V\subset \mathbb{C}^{n+1}$?
I'm not a geometer (set theorist in unfamiliar waters here), so I don't have much of a feeling for these questions or the techniques involved, but my understanding is that one can show (using cohomology or Schubert calculus) that every hypersurface intersects every projective line.

A: Q1: No. Indeed it is easy to see that each two-dimensional subspace is defined by some linear equation, so any homogeneous polynomial which has no linear factors provides a counterexample, e.g. $x^2+y^2+z^2$.
Q2: No. You can easily count the dimension of the space of all hypersurfaces and the  dimension of the space of hypersurfaces that contain a given line, as functions of the degree $d$. The dimension of the hyper surfaces that contain any line is the second number, plus the dimension of the space of lines. But the difference between the first two numbers can easily be seen to equal the dimension of the space of degree $d$ polynomials in two variables, so for $d$ large enough it is larger than the dimension of the space of lines. Because there are hyper surfaces with no lines, they can't contain any higher-dimensional subspaces.
You don't need to use cohomology or Schubert calculus to show this, it follow from the fundamental theorem of algebra. You have a polynomial of degree $d$ in $n+1$ variables. Intersecting with a line is just throwing away all but $2$ variables. It is still a polynomial of degree $d$, so it has roots.


text:
Q: How do you iterate over a range of numbers with each do with/ ERB Ruby on Rails 6? I am attempting to iterate over a range of years for a method that passes on unique years to a where clause in ruby on rails. For some odd reason, it does not fire off when I attempt to pass those numbers down to the method chain. For starters, I am working on a reporting feature that tracks charts by years in between a range. For example: Search starts at 2020 and ends at 2024. All years from 2020 to 2024 will show a report for each year compiled together. Right now, I only get one year and I should be getting 2020, 2021 and 2024 on one response..How can I print out a range of years by integer and pass them through the each block to the corresponding method?
Example code below:
params {start_year: "2019", end_year: "2020"}

params[:start_year], params[:end_year]

<% [@start_year.to_i+1...@end_year.to_i].each do |facility_year| %>
   <% @facility.chart_records.where('extract(year from record_date) =?', facility_year).limit(11).each do |chart_record| %>

<%= chart_record.record_date.strftime("%Y") %>
Month: Jan
<%= ChartRecord.where(facility_id: @facility.id).where('extract(month from record_date) =?', 1).where('extract(year from record_date) =?', facility_year).sum(:fit_jeans_count)

<% end %>

I just want to get one unique year from the start_year+1 count up until the end_year count and then display one record for each year in the range..

A: For ranges use parentheses (@start_year.to_i+1...@end_year.to_i) not brackets.
With brackets, you create an array with only one item that contains a range. With parentheses, you'll get a range right away.


text:
Q: Получить объект в Битрикс подскажите пожалуйста, есть ссылка www.mysite.ru/services/module/, как передать по ней объект и просто вывести этот переданный объект через print

A: https://dev.1c-bitrix.ru/api_d7/bitrix/main/httprequest/getpostlist.php
думаю тут ваш вопрос решается.


text:
Q: What informations can we obtain with these voltage and current measurements of a little electronic device? I powered a little electronic device with 2 AA batteries and here are the results measured with a multimeter:

*

*When using a first set of 2 AA batteries:

*

*Voltage when device unplugged: 2.45 V

*Voltage when device plugged / ON: 2.10 V, consumption: 0.30 A

*When using a second set of 2 brand new AA batteries:

*

*Voltage when device unplugged: 3.10 V

*Voltage when device plugged / ON: 3.00 V, consumption: 0.20 A

Just being curious: what informations can I deduce about the device or about the batteries with these measurements?

A: 2.1V * 0.3A = 0.63W
3.1V * 0.2A = 0.62W
The device seems to use constant power no matter what the input voltage is, which most likely indicates it is internally powered by a switching DC-DC converter. It could also be a flashlight with a switching LED driver.

A: *•  When using a first set of 2 AA batteries:
•   Voltage when device unplugged: 2.45 V
•   Voltage when device plugged / ON: 2.10 V, consumption: 0.30 A

Battery ESR = 0.35V/0.30A = 1.17 Ohms, load = 0.63W.
Battery loss= 0.3^2* 1.17= 0.1W
•   When using a second set of 2 brand new AA batteries:
•   Voltage when device unplugged: 3.10 V
•   Voltage when device plugged / ON: 3.00 V, consumption: 0.20 A*

Battery ESR = 0.1V/0.2A = 0.5 Ohms, load = 0.60W
Battery loss = 0.2^2* 0.5= 0.02W
Cells may or may not be balanced when reading 2.1/3/1 = 67% of no load fresh cell voltage and ESR always rises which DoD.
Load appears to be constant power yet 5% more efficient with fresh batteries while battery losses reduce from 0.1W to 0.02W with low DoD fresh cells.
So supply inefficiency rises from 0.02/0.60W= 3.3% to 0.1W/0.63W = 16% additional losses when drained.  This explains more rapid decay in storage energy remaining when batteries get low with a constant power load.


text:
Q: render PHP content within section I need to render some PHP content, within php tags to display HTML loaded from a database. This is what I have:
<?php
$this->section['left-column'] = '<?php echo $page->left; ?>';
?>

But this of course does not work...
I assumed this would work:
<?php
$this->section['left-column'] = ' . echo $page->left; . ';
?>

But it didn't :(
Can anyone advise the correct way to enter this?
Thanks.

A: Try
<?php
$this->section['left-column'] =  $page->left;
?>

A: The PHP string won't execute unless it is evaluated.
<?php
$this->section['left-column'] = eval('echo $page->left;');
?>


text:
Q: Highcharts: Duplicate X-Axis Labels when dataGrouping is enabled (by Month) I'm experiencing an issue when grouping data by month. I believe it to be a bug with the size of the dataset (January 1, 2018 - April 30, 2018) that I'm using but perhaps there is a better way of utilizing dataGrouping. The issue that I'm experiencing is that the X-Axis labels are not correct.
For a date range of January 1, 2018 to April 30, 2018:
Expected X-Axis to Be:
"Jan, '18" "Feb, '18" "Mar, '18" "Apr, '18"
Actual X-Axis:
"Jan, '18" "Feb, '18" "Mar, '18" "Mar, '18" "Apr, '18"
In my example (jsfiddle), I'm conditionally enabling dataGrouping on line 76: data.dataGrouping.enabled = (e.target.value === 'month');
Any insight would be greatly appreciated.

A: I think I found the solution: Use HighStocks and not HighCharts
I have an updated fiddle with the result. Summary:
Use HighScocks and just turn off some features to make it appear like a Highstock chart:
var chart = Highcharts.stockChart('myChart', {
    chart: {
        type: 'column',
        width: null
    },
    xAxis: {
        labels: {
            enabled: true,
            formatter: function() {
                if (grouping === 'date') {
                    return Highcharts.dateFormat('%b %e, \'%y', this.value);
                } else {
                    return Highcharts.dateFormat('%b, \'%y', this.value);
                }
            }
        }
    },
    navigator: {
        enabled: false
    },
    scrollbar: {
        enabled: false
    },
    rangeSelector: {
        enabled: false
    },
    yAxis: {
        title: {
            text: null
        }
    },
    title: {
        text: null
    },
    legend: {
        enabled: false
    },
    plotOptions: {
        series: {
            color: 'white'
        }
    },
    tooltip: {
        backgroundColor: '#0E7BBA',
        style: {
            color: 'white'
        },
        formatter: function() {
            var s = ''
            if (grouping === 'date') {
                s = '' + Highcharts.dateFormat('%A, %b %e, %Y', this.x) + '';
            } else {
                s = '' + 'Date: ' + Highcharts.dateFormat('%A, %b %e, %Y', this.x) + '
' +
                'Month: ' + Highcharts.dateFormat('%B %Y', this.x) + '';
            }
            s += '
' + this.points[0].series.name + ': ' + this.y;
            return s;
        }
    },
    credits: {
        enabled: false
    },
        series: []
    }
);


text:
Q: Возврат множества из условия (аналог CASE) Пытаюсь написать запрос в Oracle, который использует разные множества для IN() в условии. Общий вид запроса примерно такой:
-- что-то забирает
WHERE id IN
  (CASE
    WHEN name LIKE '%max%'
    THEN (1, 2, 5)
    ELSE (SELECT id FROM anotherTable)
  END);

Понятно, что такой вариант не работает и выдаёт ошибку ora-01427. Судя по тому, что я прочитал в сети, CASE не может вернуть множество.
Что можно использовать, чтобы вернуть именно множество?

A: Попробуй это
where (
         NAME like '%max%'
         and ID in (1, 2, 5)
      )
   or (
         NAME not like '%max%'
         and ID in (select ID from anotherTable)
      )

A: Можно сделать еще так:
where
  1 = case
        when name like '%max%' and id in (1,2,5) then 1
        when name like '%min%' and id in (select id from anotherTable) then 1
      end


text:
Q: Suddenly my local SQLServer is kicking named pipe errors I have a local instance of 64-bit SQL Server Express 12.0.something. I use it for local tests of our SQL code.
Today, out of the blue, I get:
Additional information: A transport-level error has occurred when sending the request to the server. (provider: Named Pipes Provider, error: 2 - Connection was terminated)

I have rebooted and start/stopped the server to no avail. I'm using a database that worked fine the last time I tried it, but to be safe I pulled a backup to no avail.
And it's not a complete failure to work, it's intermittent. My code does hundreds of queries, and it fails on one of them at random - a certain query will work the first 10 times and then fail on the 11th, and then the next time I run it, it fails on something else that worked perfectly last time.
Any way to debug this?

A: This isn't an "answer" per-se, but the only solution was to remove all of SQL and re-install from scratch.
Using the identical databases, versions, software etc. everything once again worked perfectly and the errors vanished.


text:
Q: Calculate the value owned by each `node` in the hierarchical database in` MYSQL 8` I have a table in a hierarchical database.
Because the level of complexity is high enough for me,
so I try to make it more general in the following link:
DBFIDDLE
I've also created a hierarchy image as shown below.

The rules of the game that must be followed are,

*

*Only nodes that do not have a child or leaf-node can hold a value.

*Each level will be assigned a value to a sub category line.

The results of the query above, can be seen in the link included above.
But the results we want to achieve are as follows.
+------+-----------+------+-------------------------+-----------------------+-------+------------+
| id   | parent_id | lvl  | name                    | path                  | value | rollup     |
+------+-----------+------+-------------------------+-----------------------+-------+------------+
|    1 |      NULL |    0 | A                       | A                     |       | Root       |
|    2 |         1 |    1 |   B                     | A > B                 |       | Category 1 |
|    3 |         2 |    2 |     C                   | A > B > C             |       | Category 2 |
|    4 |         3 |    3 |       D                 | A > B > C > D         |       | Category 3 |
|    5 |         4 |    4 |         E               | A > B > C > D > E     |    50 | Category 4 |
|    6 |         4 |    4 |         F               | A > B > C > D > F     |    50 | Category 4 |
|    7 |         4 |    4 |         G               | A > B > C > D > G     |    50 | Category 4 |
|      |         8 |    4 |       TOTAL D (E+F+G)   |                       |   150 |            |
|    8 |         3 |    3 |       H                 | A > B > C > H         |       | Category 3 |
|    9 |         8 |    4 |         I               | A > B > C > H > I     |    30 | Category 4 |
|   10 |         8 |    4 |         J               | A > B > C > H > J     |    40 | Category 4 |
|      |         8 |    4 |       TOTAL H (I+J)     |                       |    70 |            |
|      |         2 |    2 |     TOTAL C (D+H)       |                       |   220 |            |
|   11 |         2 |    2 |     K                   | A > B > K             |       | Category 2 |
|   12 |        11 |    3 |       L                 | A > B > K > L         |       | Category 3 |
|   13 |        12 |    4 |         M               | A > B > K > L > M     |     0 | Category 4 |
|   14 |        13 |    5 |           N             | A > B > K > L > M > N |     2 | Category 5 |
|   15 |        13 |    5 |           O             | A > B > K > L > M > O |     4 | Category 5 |
|   18 |        16 |    5 |         TOTAL M (N+O)   |                       |     6 |            |
|   16 |        12 |    4 |         P               | A > B > K > L > P     |       | Category 4 |
|   17 |        16 |    5 |           Q             | A > B > K > L > P > Q |    32 | Category 5 |
|   18 |        16 |    5 |           R             | A > B > K > L > P > R |    16 | Category 5 |
|      |        16 |    5 |         TOTAL P (Q+R)   |                       |    48 |            |
|      |        16 |    5 |       TOTAL L (M+P)     |                       |    54 |            |
|      |        16 |    5 |      TOTAL K (L)        |                       |    54 |            |
|      |         1 |    1 |   TOTAL B (C+K)         |                       |   274 |            |
|   19 |         1 |    1 |   S                     | A > S                 |       | Category 1 |
|   20 |        19 |    2 |     T                   | A > S > T             |       | Category 2 |
|   21 |        20 |    3 |       U                 | A > S > T > U         |     1 | Category 3 |
|   22 |        20 |    3 |       V                 | A > S > T > V         |     4 | Category 3 |
|   23 |        20 |    3 |       W                 | A > S > T > W         |     0 | Category 3 |
|      |        20 |    3 |     TOTAL T (U+V+W)     |                       |     5 |            |
|   24 |        19 |    2 |     X                   | A > S > X             |       | Category 2 |
|   25 |        24 |    3 |       Y                 | A > S > X > Y         |     3 | Category 3 |
|   26 |        24 |    3 |       Z                 | A > S > X > Z         |    14 | Category 3 |
|      |        24 |    3 |     TOTAL X (Y+Z)       |                       |    17 |            |
|      |        24 |    3 |   TOTAL S (T+X)         |                       |    22 |            |
|      |      NULL |    0 | TOTAL A (B+S)           |                       |   296 |            |
+------+-----------+------+-------------------------+-----------------------+-------+------------+

I have tried it with GROUP BY WITH ROLLUP, but because this table is hierarchical, the results are not as expected.
How to selecting those data with ordered as we need, with total as subtotal each level.
So far, the query is :
WITH RECURSIVE adjacency_list_path (id, parent_id, lvl, name, path, value) AS (
    SELECT id, parent_id, 0 lvl, name, name as path, adjacency_list.`value`
    FROM adjacency_list
    WHERE parent_id IS NULL
    UNION ALL
    SELECT c.id, c.parent_id, (cp.lvl + 1), CONCAT(REPEAT("   " , (cp.lvl + 1)), c.name), CONCAT(cp.path, ' > ', c.name), c.`value`
    FROM adjacency_list_path AS cp
             JOIN adjacency_list AS c
                  ON cp.id = c.parent_id
)
SELECT id, parent_id, lvl, name, path, value
FROM adjacency_list_path
ORDER BY path;


text:
Q: How to use replace function for setAs() in R? I am trying to define a coerce method in R including a replace function. Unfortunately, neither the documentation of setAs() nor further discussions on the internet clarify the way how to use the parameter replace in this function.
My target is to get a coerce method working the same in these two commands:
obj <- as(obj, "to-class")
as(obj) <- "to-class"

For instance, I set a method to coerce the class "table" to "data.frame", including a function for a replacement method:
setAs(from = "table", to = "data.frame",
    def = function(from) {
      return(as.data.frame(from))
    },
    replace = function(from, value) {
      from <- as(from, value)
      return(from)
    })

Now the method in action
data(Titanic)
x <- Titanic

# two coerce alternatives
y <- as(x, "data.frame")
as(x) <- "data.frame"

While the first works perfect, the second retrieves me an error:

Error in .identC(.class1(value), Class) :
  argument "Class" is missing, with no default

Am I doing something wrong or maybe expecting too much from setAs()?

A: replace doesn't do what you think it does. It exists to allow direct assignment of an uncoerced object into a coerced version. The second argument is not supposed to be the class name, but an uncoerced object.
To take your table / data.frame coercion, we could write.
setAs(from = "table", to = "data.frame",
      def = function(from) {
        return(as.data.frame(from))
      },
      replace = function(from, value) {
        from <- as.data.frame(value)
        return(from)
      })

So if we have a table called x
x <- table(iris$Species)
x

#> setosa versicolor  virginica
#>     50         50         50

We can assign a different table's data and coerce to a data.frame in one go by doing:
as(x, "data.frame") <- table(mtcars$cyl)
x
#>   Var1 Freq
#> 1    4   11
#> 2    6    7
#> 3    8   14

Effectively, it's the same as writing
x <- as(table(mtcars$cyl), "data.frame")

and therefore of limited utility, which is perhaps why the documentation is scant.

A: as requires object and class, so:
as(x, "data.frame") <- x

A: While I still don't have any clue about what is the parameter replace in setAs() good for, I solved the issue defining a method for as()<-:
# Defining 'as()'
setAs(from = "table", to = "data.frame",
    def = function(from) {
      return(as.data.frame(from))
    })

# Defining 'as()<-'
setReplaceMethod("as", signature(object = "table", Class = "missing",
        value = "character"),
    function(object, Class, value) {
      object <- as(object, value)
      return(object)
    })

The nice thing in this solution, the replace method will apply for any coercion defined with from = "table"