text:
Q: Schmidt decomposition of coupled oscillators Consider a system of two coupled oscillators, with Hamiltonian ($\hbar = m = 1$):
\begin{align}
\mathcal{H} = \frac{1}{2}(p_1^2 + \omega_0^2 x_1^2) + \frac{1}{2}(p_2^2 + \omega_0^2 x_2^2) +\frac{1}{2}k(x_1 - x_2)^2.
\end{align}
Changing to normal coordinates ($y_1 = \frac{1}{\sqrt{2}}(x_1-x_2)$ and $y_2 = \frac{1}{\sqrt{2}} (x_1 + x_2)$), one gets the wave functions to be a product of two decoupled oscillators with eigenfrequencies $\omega_1^2 = \omega_0^2 + 2k$ and $\omega_2^2 = \omega_0^2$. In particular the ground state is
\begin{align}
\Psi_0 = \left(\frac{\omega_1\omega_2}{\pi^2} \right)^{1/4} \exp(-\frac{1}{2}[\omega_1 y_1^2 + \omega_2 y_2^2] ).
\end{align}
It is known that we can perform a Schmidt decomposition on the system, and write
\begin{align}
\Psi_0 = \sum_{n=0}^\infty \frac{(-\tanh \eta)^n}{\cosh \eta}\Phi_n(x_1) \Phi_n(x_2),
\end{align}
where $\exp(4\eta) = \omega_1/\omega_2$ and $\Phi_n$ are the oscillator states for a frequency $\tilde{\omega} = \sqrt{\omega_1 \omega_2}$.
I'm not too sure if my question makes sense, but it is: how do we know a priori that the Hilbert space of the system which is a product of two oscillators of frequency $\omega_0$ (is it ??):
\begin{align}
H = H_{SHO,\omega_0} \otimes H_{SHO,\omega_0}
\end{align}
can be also written as
\begin{align}
H = H_{SHO,\omega_1} \otimes H_{SHO, \omega_2}
\end{align}
as in the decoupled case, and also as
\begin{align}
H = H_{SHO,\tilde{\omega}} \otimes H_{SHO,\tilde{\omega}}
\end{align}
as in the last step?
In other words, I wish to decompose the Hilbert space into a tensor product of smaller subspaces, but how do I do that?

A: All harmonic oscillator Hilbert spaces of different frequencies are unitarily equivalent by virtue of the Stone–von Neumann theorem. This theorem implies also that  these Hilbert spaces are unitarily equivalent to the free particle Hilbert space; where the transformation is given by means of the Bargmann transform, please , for example, see the definition in the introduction equation (1) of Olafsson-Ørsted article. Thus if the algebra of operators is composed (of a finite number of copies) of the canonical commutation relations, one already knows that the quantization Hilbert space is a tensor product of the same number of oscillator Hilbert spaces


text:
Q: Implement a method of abstract class when the current class already extends another class I have a class which extends another class. Now when I want to implement a method of another class which is abstract I cannot instantiate as its abstract and cannot use 'extends' as my current class already extends something (cannot do multiple inheritance).
say my class is Class A which extends B and I want to use a method of abstract class C.
          Class A extends B{
          }

          abstract Class C { public List<String> method1(){//logic}; }

I tried declaring Class C as a variable and fetch the method. But that does not work. Can anybody suggest me a correct way please ? // Unfortunately cannot redesign the model
             private C cObject;
             cObject.method1(); // returns null

A: Do a mutli level inheritance. Extend Class C in Class B. So once you extend Class B in A you will be able to access method1()
OR
Create a new Class, extend Class C in the new Class. Now you will be able to instantiate the new class in Class A and access method1()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Paste two columns letting white spaces if the corresponding value is not found I have two files, each one containing a single column:
x_a
x_b
x_d
x_e

and
y_a
y_c
y_e

Which is the best way to paste the two files in order to obtain a result like
x_a   y_a
x_b
      y_c
x_d
x_e   y_e

or even
x_a   y_a
x_b   ???
???   y_c
x_d   ???
x_e   y_e

There is a bash / awk / sed solution for that? The files have thousands of lines, and the part that I want to test (a,b,c,d,e) are a lot of strings of numbers (actually they are coordinates).
Thank you in advance for your help. I tried inserting in a mysql table and make a join, but there is no column in common.
EDIT: All the questions were quick, complete and working. Thank you everybody for your time

A: Here is one solution:
awk -F_ 'NR==FNR {x[$2]=$0;a[$2]=1;next} {y[$2]=$0;a[$2]=1} END {for (i in a) print x[i] "\t" y[i]}' file1 file2
x_a     y_a
x_b
        y_c
x_d
x_e     y_e

And with ???
awk -F_ 'NR==FNR {x[$2]=$0;a[$2]=1;next} {y[$2]=$0;a[$2]=1} END {for (i in a) print (x[i]?x[i]:"???"),(y[i]?y[i]:"???")}' file1 file2
x_a y_a
x_b ???
??? y_c
x_d ???
x_e y_e

How does it work?
awk -F_ '                           # Field separator set to _
    NR==FNR {                       # Run this on first file
        x[$2]=$0                    # Store line in array x, using field 2 as separator
        a[$2]=1                     # Store every unique separator in array a
        next                        # Next record
        }

        {                           # Run this on second file
        y[$2]=$0                    # Store line in array y, using field 2 as separator
        a[$2]=1                     # Store every unique separator in array a
        }
    END {                           # Do this at end
        for (i in a)                # Read all unique value in array a
            print x[i] "\t" y[i]    # Print the array x and y using value in a
        }' file1 file2              # Read the files

A: Try this awk:
awk -F '_' 'NR==FNR {a[$2]=$0; next} $2 in a{print a[$2], $0; delete a[$2]; next}
           !($2 in a){print "???", $0} END{for (i in a) print a[i], "???"}' f1 f2
x_a y_a
??? y_c
x_e y_e
x_d ???
x_b ???

A: If you consider using a mysql - yes, there is column in common, however, you need to create it artificially.
Run the command: sed -e 's/_\(.*\)$/& \1/' on your file - you will receive output like:
x_a a
x_b b
x_d d
x_e e

The 2nd column you can use as a join key.

A: This gets us most of the way there:
$ join -t_ -j 2 -o 1.1,1.2,2.1,2.2 -e " " -a1 -a2 file1 file2
x_a_y_a
x_b_ _
 _ _y_c
x_d_ _
x_e_y_e

Pipe it through sed to remove the stray underscores:
$ join -t_ -j 2 -o 1.1,1.2,2.1,2.2 -e " " -a1 -a2 file1 file2 |
  sed 's/^\(._.\)_/\1 /;s/^ _ /   /; s/ _ $//'
x_a y_a
x_b
    y_c
x_d
x_e y_e

For question marks, use sed 's/^\(._.\)_/\1 /;s/^ _ /???/; s/ _ $/???/'
join requires the files to be sorted by the join field, and in this case they are. If they are not:
$ join -t_ -j 2 -o 1.1,1.2,2.1,2.2 -e " " -a1 -a2 <(sort -t_ -k2,2 file1) <(sort -t_ -k2,2 file2) |
  sed 's/^\(._.\)_/\1 /;s/^ _ /   /; s/ _ $//'


text:
Q: Protractor test involving ng-show I have an angular page that shows or hides a countries dropDownList based on the value of a radioButton. If the rb is true, then the ddl gets hidden and if the ddl is false, the ddl is shown. This is done directly in the ddl HTML, adding the following attribute to the select tag: ng-show="!vm.inscriptor.isLocalCountry".
All Works well as expected, except for the following protractor test:
it(testNumber++ + " ddl de países debería estar oculto", function () {
    pages.register.rbdLocalCountryTrue.click();
    expect(pages.register.ddlCountries.isPresent()).toBeTruthy();
    expect(pages.register.ddlCountries.isDisplayed()).toBeFalsy();
});

As expected, when the radio button for the true value is clicked, the ddl gets hidden, however the "isDisplayed" expect throws the following error:

Expected true to be falsy.

The only reason I can think of is that the expect statement is being executed before the click finishes procesing. I tried to refactor the test per the following:
it(testNumber++ + " ddl de países debería estar oculto", function () {
    pages.register.rbdLocalCountryTrue.click().then(function () {
        expect(pages.register.ddlCountries.isPresent()).toBeTruthy();
        expect(pages.register.ddlCountries.isDisplayed()).toBeFalsy();
    });
});

but I still get random results with the expect.
If I add a browser.sleep(5000), then the expect results show correctly, but everywhere I've read says that browser.sleep is a last resort kind of trick.
Is there any other way to tell protractor to wait for the click to finish processing? Any other suggestions?
Thx

A: You can use browser.wait() for the element to be hidden after the click(). And to add, you don't need to chain the promises of Click() and expect() as Protractor Control Flow does it for you
You can have something like this
it(testNumber++ + " ddl de países debería estar oculto", function () {
    pages.register.rbdLocalCountryTrue.click();
    browser.wait(protractor.ExpectedConditions.invisibilityOf(pages.register.ddlCountries), 10000);
    expect(pages.register.ddlCountries.isPresent()).toBeTruthy();
    expect(pages.register.ddlCountries.isDisplayed()).toBeFalsy();
});


text:
Q: Is there a more efficient way to compute positive modulo? Modulo in C and C++ does not behave in a mathematically correct manner, as it returns a negative result when performing the modulo of a negative number. After doing some research, it seems the classic way of implementing a correctly behaving one is:
positive modulo(int i, int n)
{
   return ( ( (i % n) + n ) % n );
}

Considering modulo is computationally expensive, is there a more efficient way to compute positive modulo for any number (I already saw the solution for powers of 2, but I need something generic)?

A: This may be slower or faster, depending on the compiler, the optimization level and the architecture:
static inline int modulo(int i, int n) {
  const int k = i % n;
  return k < 0 ? k + n : k;
}

The reason why it can be slower is that the condition operation may introduce a branch, and sometimes branches are slow.

A: The solution in pts's answer is probbaly the best solution. It often compiles to a branchless code, but even if there are slowdowns by the branch, it may possibly be faster than the division anyway. But in case you really need to avoid branching
inline int modulo(int i, int n)
{
    int k = i % n;
    int a = -(k < 0);  // assuming 2's complement
    // or int a = ((k < 0) << (INT_SIZE - 1)) >> (INT_SIZE - 1); if your system doesn't use 2's complement
    return k + n & a;
}

A: The second modulo in your formula is necessary only to substract n again if the modulo was posivite in the first place. So it should be at least as performant to only conditionally add n:
   auto m = (i % n);
   return (m < 0) ? m+n : m;


text:
Q: How can I compare existing items with new items in a SP Online list I have built a WCF Application that populates a SP Online list. This is working without any issues.
But, when I run the WCF for a second time, I get doubles of everything.
So first of all I want to update the list - Instead of add everything again.
The update function is not working, not even just overwriting all records. And I cannot see why.
I am now trying to create a check that will look if the item exists already in the list, and if it does, then it will skip over that and move on to the next item.
Now the question is, how can I compare the two? Probably in the form of a foreach loop but that seems like a lot of overhead and very time consuming.
This is the start of a console application to "play around" in.
So far, I know, all it does is return a list of items in the list.
 using (ClientContext clientContext = new ClientContext("https://mydomain.sharepoint.com/"))
        {
            SecureString passWord = new SecureString();
            foreach (char c in "mypassword".ToCharArray()) passWord.AppendChar(c);
            clientContext.Credentials = new SharePointOnlineCredentials("myname@mydomain.onmicrosoft.com", passWord);
            Web web = clientContext.Web;
            SP.List oList = clientContext.Web.Lists.GetByTitle("listTitle");
            clientContext.Load(web);
            clientContext.Load(oList);
            CamlQuery query = CamlQuery.CreateAllItemsQuery();
            SP.ListItemCollection itemcoll = oList.GetItems(query);

            clientContext.Load(itemcoll);

            clientContext.ExecuteQuery();

            foreach (ListItem oListItem in itemcoll)
            {
                Console.WriteLine("Title: {0} ", oListItem["Title"]);
                oListItem.Update();            //Added
            }

                clientContext.ExecuteQuery(); ///Added
                Console.ReadLine();

Ok, so where I put the comment "///Added " are new lines that update the list.
The one problem I still have, and I'm not sure if this falls under a new question, is that when the WCF service runs, it does update the item already in the list but then it still adds the item again, so although everything is updated, it is also duplicated

A: So this is the way, that I ended up doing it. It works, it's been tried and tested and no issues of errors. Caml Query with an ID column for comparing
 using (ClientContext clientContext = new ClientContext("https://mydomain.sharepoint.com/"))
    {
        SecureString passWord = new SecureString();
        foreach (char c in "mypassword".ToCharArray()) passWord.AppendChar(c);
        clientContext.Credentials = new SharePointOnlineCredentials("myname@mydomain.onmicrosoft.com", passWord);
        Web web = clientContext.Web;
        SP.List oList = clientContext.Web.Lists.GetByTitle("listTitle");
        clientContext.Load(web);
        clientContext.Load(oList);
        CamlQuery query = CamlQuery.CreateAllItemsQuery();
        SP.ListItemCollection itemcoll = oList.GetItems(query);

        clientContext.Load(itemcoll);

        clientContext.ExecuteQuery();

        foreach (var oListItem in itemcoll)
        {
            CamlQuery query = new CamlQuery();

            query.ViewXml =

                    "<View>"
                        + "<Query>"
                            + "<Where>"
                                + "<Eq>"
                                    + "<FieldRef Name='item_ID'/>"
                                         + "<Value Type='Text'>"
                    + oListItem.ID
                                         + "</Value>"
                                + "</Eq>"
                            + "</Where>"
                        + "</Query>"
                     + "</View>";
            ListItemCollection itemcoll = oList.GetItems(query);

            clientContext.Load(itemcoll);

            clientContext.ExecuteQuery();

        try
        {

            itemcoll["Title"] = oListItem.Title;
            itemcoll.Update();
            oList.Update();
        }
        catch(exception e)
        {
        }

        clientContext.ExecuteQuery();

    }


text:
Q: ImportError: cannot import name 'IMAP4_SSL' from 'imaplib' I'm trying to write a Python program that downloads all the attachments from unread emails in my Gmail account and puts them into a defined folder, but when I run it, it gives me the following error: ImportError: cannot import name 'IMAP4_SSL' from 'imaplib'
I read somewhere that installing the python openssl module would help, but already checked and I had it. I'm quite new to programming, so I'm kinda clueless here. Any suggestion would be greatly appreciated!
The code is as follows:
import os
from imbox import Imbox
import traceback

host = "imap.gmail.com"
username = 'account'
password = 'password'
download_folder = 'C:\\Users\\artur\\Desktop\\test'

if not os.path.isdir(download_folder):
    os.makedirs(download_folder, exist_ok=True)

mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=None, starttls=False)
messages = mail.messages(unread=True) # defaults to inbox

for (uid, message) in messages:
    mail.mark_seen(uid) # optional, mark message as read

    for idx, attachment in enumerate(message.attachments):
        try:
            att_fn = attachment.get('filename')
            download_path = f"{download_folder}/{att_fn}"
            print(download_path)
            with open(download_path, "wb") as fp:
                fp.write(attachment.get('content').read())
        except:
            pass
            print(traceback.print_exc())

mail.logout()

Don't know if it helps, but all the error lines that result in the terminal are:
File "c:/path/Gmail_downloader.py", line 2, in <module>
    from imbox import Imbox
  File "C:\Users\artur\anaconda3\lib\site-packages\imbox\__init__.py", line 1, in <module>
    from imbox.imbox import Imbox
  File "C:\Users\artur\anaconda3\lib\site-packages\imbox\imbox.py", line 3, in <module>
    from imbox.imap import ImapTransport
  File "C:\Users\artur\anaconda3\lib\site-packages\imbox\imap.py", line 1, in <module>
    from imaplib import IMAP4, IMAP4_SSL
ImportError: cannot import name 'IMAP4_SSL' from 'imaplib' (C:\Users\artur\anaconda3\lib\imaplib.py)

Thank you for your time!

A: For me, updating openssl seemed to work.
It seems like you are using conda, so
conda update openssl

in the Anaconda prompt.


text:
Q: Cannot access video load progress in Javascript I'm trying to make a video player with several features by js html and css, but when I came to trying to preload the video, I couldn't find a way to know how much of the video was downloaded, and I need to know this info so I can update a progress bar to tell how much data has been buffered.
Is there a way to find out how much a video has been buffered?
I tried accessing the video preload property in javascript to get how much it was preloaded . but it gave me the preload type of the video

A: You need to use: TimeRanges to know the length of loaded (buffered) video.
There will be more time ranges added if you seek into a new area that has not yet buffered. Either handle such situation or else code your UI to not respond if a user clicks outside the fill area (eg: only clicking within fill area will change currentTime of video).
Also read: Media buffering, seeking, and time ranges guide for more knowledge.
Below is some testable code as a starting point to expand:
<!DOCTYPE html>

<video id="myVid" width="320" height="240" controls>
  <source src="your_file.mp4" type="video/mp4">
</video>


text:
Q: How to call base.base.method()? // Cannot change source code
class Base
{
    public virtual void Say()
    {
        Console.WriteLine("Called from Base.");
    }
}

// Cannot change source code
class Derived : Base
{
    public override void Say()
    {
        Console.WriteLine("Called from Derived.");
        base.Say();
    }
}

class SpecialDerived : Derived
{
    public override void Say()
    {
        Console.WriteLine("Called from Special Derived.");
        base.Say();
    }
}

class Program
{
    static void Main(string[] args)
    {
        SpecialDerived sd = new SpecialDerived();
        sd.Say();
    }
}

The result is:

Called from Special Derived.
  Called from Derived. /* this is not expected */
  Called from Base.

How can I rewrite SpecialDerived class so that middle class "Derived"'s method is not called?
UPDATE:
The reason why I want to inherit from Derived instead of Base is Derived class contains a lot of other implementations. Since I can't do base.base.method() here, I guess the best way is to do the following?
// Cannot change source code
class Derived : Base
{
    public override void Say()
    {
        CustomSay();

        base.Say();
    }

    protected virtual void CustomSay()
    {
        Console.WriteLine("Called from Derived.");
    }
}

class SpecialDerived : Derived
{
    /*
    public override void Say()
    {
        Console.WriteLine("Called from Special Derived.");
        base.Say();
    }
    */

    protected override void CustomSay()
    {
        Console.WriteLine("Called from Special Derived.");
    }
}

A: public class A
{
    public int i = 0;
    internal virtual void test()
    {
        Console.WriteLine("A test");
    }
}

public class B : A
{
    public new int i = 1;
    public new void test()
    {
        Console.WriteLine("B test");
    }
}

public class C : B
{
    public new int i = 2;
    public new void test()
    {
        Console.WriteLine("C test - ");
        (this as A).test();
    }
}

A: You can also make a simple function in first level derived class, to call grand base function

A: My 2c for this is to implement the functionality you require to be called in a toolkit class and call that from wherever you need:
// Util.cs
static class Util
{
    static void DoSomething( FooBase foo ) {}
}

// FooBase.cs
class FooBase
{
    virtual void Do() { Util.DoSomething( this ); }
}

// FooDerived.cs
class FooDerived : FooBase
{
    override void Do() { ... }
}

// FooDerived2.cs
class FooDerived2 : FooDerived
{
    override void Do() { Util.DoSomething( this ); }
}

This does require some thought as to access privilege, you may need to add some internal accessor methods to facilitate the functionality.

A: You can't from C#.  From IL, this is actually supported.  You can do a non-virt call to any of your parent classes... but please don't. :)

A: Just want to add this here, since people still return to this question even after many time. Of course it's bad practice, but it's still possible (in principle) to do what author wants with:
class SpecialDerived : Derived
{
    public override void Say()
    {
        Console.WriteLine("Called from Special Derived.");
        var ptr = typeof(Base).GetMethod("Say").MethodHandle.GetFunctionPointer();
        var baseSay = (Action)Activator.CreateInstance(typeof(Action), this, ptr);
        baseSay();
    }
}

A: This is a bad programming practice, and not allowed in C#. It's a bad programming practice because

*

*The details of the grandbase are implementation details of the base; you shouldn't be relying on them. The base class is providing an abstraction overtop of the grandbase; you should be using that abstraction, not building a bypass to avoid it.

*To illustrate a specific example of the previous point: if allowed, this pattern would be yet another way of making code susceptible to brittle-base-class failures. Suppose C derives from B which derives from A. Code in C uses base.base to call a method of A. Then the author of B realizes that they have put too much gear in class B, and a better approach is to make intermediate class B2 that derives from A, and B derives from B2. After that change, code in C is calling a method in B2, not in A, because C's author made an assumption that the implementation details of B, namely, that its direct base class is A, would never change. Many design decisions in C# are to mitigate the likelihood of various kinds of brittle base failures; the decision to make base.base illegal entirely prevents this particular flavour of that failure pattern.

*You derived from your base because you like what it does and want to reuse and extend it. If you don't like what it does and want to work around it rather than work with it, then why did you derive from it in the first place? Derive from the grandbase yourself if that's the functionality you want to use and extend.

*The base might require certain invariants for security or semantic consistency purposes that are maintained by the details of how the base uses the methods of the grandbase. Allowing a derived class of the base to skip the code that maintains those invariants could put the base into an inconsistent, corrupted state.

A: The answer (which I know is not what you're looking for) is:
class SpecialDerived : Base
{
    public override void Say()
    {
        Console.WriteLine("Called from Special Derived.");
        base.Say();
    }
}

The truth is, you only have direct interaction with the class you inherit from. Think of that class as a layer - providing as much or as little of it or its parent's functionality as it desires to its derived classes.
EDIT:
Your edit works, but I think I would use something like this:
class Derived : Base
{
    protected bool _useBaseSay = false;

    public override void Say()
    {
        if(this._useBaseSay)
            base.Say();
        else
            Console.WriteLine("Called from Derived");
    }
}

Of course, in a real implementation, you might do something more like this for extensibility and maintainability:
class Derived : Base
{
    protected enum Mode
    {
        Standard,
        BaseFunctionality,
        Verbose
        //etc
    }

    protected Mode Mode
    {
        get; set;
    }

    public override void Say()
    {
        if(this.Mode == Mode.BaseFunctionality)
            base.Say();
        else
            Console.WriteLine("Called from Derived");
    }
}

Then, derived classes can control their parents' state appropriately.

A: Why not simply cast the child class to a specific parent class and invoke the specific implementation then? This is a special case situation and a special case solution should be used. You will have to use the new keyword in the children methods though.
public class SuperBase
{
    public string Speak() { return "Blah in SuperBase"; }
}

public class Base : SuperBase
{
    public new string Speak() { return "Blah in Base"; }
}

public class Child : Base
{
    public new string Speak() { return "Blah in Child"; }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        Child childObj = new Child();

        Console.WriteLine(childObj.Speak());

        // casting the child to parent first and then calling Speak()
        Console.WriteLine((childObj as Base).Speak());

        Console.WriteLine((childObj as SuperBase).Speak());
    }
}

A: In cases where you do not have access to the derived class source, but need all the source of the derived class besides the current method, then I would recommended you should also do a derived class and call the implementation of the derived class.
Here is an example:
//No access to the source of the following classes
public class Base
{
     public virtual void method1(){ Console.WriteLine("In Base");}
}
public class Derived : Base
{
     public override void method1(){ Console.WriteLine("In Derived");}
     public void method2(){ Console.WriteLine("Some important method in Derived");}
}

//Here should go your classes
//First do your own derived class
public class MyDerived : Base
{
}

//Then derive from the derived class
//and call the bass class implementation via your derived class
public class specialDerived : Derived
{
     public override void method1()
     {
          MyDerived md = new MyDerived();
          //This is actually the base.base class implementation
          MyDerived.method1();
     }
}

A: As can be seen from previous posts, one can argue that if class functionality needs to be circumvented then something is wrong in the class architecture. That might be true, but one cannot always restructure or refactor the class structure on a large mature project. The various levels of change management might be one problem, but to keep existing functionality operating the same after refactoring is not always a trivial task, especially if time constraints apply. On a mature project it can be quite an undertaking to keep various regression tests from passing after a code restructure; there are often obscure "oddities" that show up.
We had a similar problem in some cases inherited functionality should not  execute (or should perform something else). The approach we followed below, was to put the base code that need to be excluded in a separate virtual function. This function can then be overridden in the derived class and the functionality excluded or altered. In this example "Text 2" can be prevented from output in the derived class.
public class Base
{
    public virtual void Foo()
    {
        Console.WriteLine("Hello from Base");
    }
}

public class Derived : Base
{
    public override void Foo()
    {
        base.Foo();
        Console.WriteLine("Text 1");
        WriteText2Func();
        Console.WriteLine("Text 3");
    }

    protected virtual void WriteText2Func()
    {
        Console.WriteLine("Text 2");
    }
}

public class Special : Derived
{
    public override void WriteText2Func()
    {
        //WriteText2Func will write nothing when
        //method Foo is called from class Special.
        //Also it can be modified to do something else.
    }
}

A: There seems to be a lot of these questions surrounding inheriting a member method from a Grandparent Class, overriding it in a second Class, then calling its method again from a Grandchild Class. Why not just inherit the grandparent's members down to the grandchildren?
class A
{
    private string mystring = "A";
    public string Method1()
    {
        return mystring;
    }
}

class B : A
{
    // this inherits Method1() naturally
}

class C : B
{
    // this inherits Method1() naturally
}

string newstring = "";
A a = new A();
B b = new B();
C c = new C();
newstring = a.Method1();// returns "A"
newstring = b.Method1();// returns "A"
newstring = c.Method1();// returns "A"

Seems simple....the grandchild inherits the grandparents method here. Think about it.....that's how "Object" and its members like ToString() are inherited down to all classes in C#. I'm thinking Microsoft has not done a good job of explaining basic inheritance. There is too much focus on polymorphism and implementation. When I dig through their documentation there are no examples of this very basic idea. :(

A: I had the same problem as the OP, where I only wanted to override a single method in the middle Class, leaving all other methods alone. My scenario was:
Class A - base class, DB access, uneditable.
Class B : A - "record type" specific functionality (editable, but only if backward compatible).
Class C : B - one particular field for one particular client.
I did very similar to the second part of the OP posting, except I put the base call into it's own method, which I called from from Say() method.
class Derived : Base
{
    public override void Say()
    {
        Console.WriteLine("Called from Derived.");

        BaseSay();
    }

    protected virtual void BaseSay()
    {
        base.Say();
    }
}

class SpecialDerived : Derived
{

    public override void Say()
    {
        Console.WriteLine("Called from Special Derived.");
        base.BaseSay();
    }
}

You could repeat this ad infinitum, giving, for example SpecialDerived a BaseBaseSay() method if you needed an ExtraSpecialDerived override to the SpecialDerived.
The best part of this is that if the Derived changes its inheritance from Base to Base2, all other overrides follow suit without needing changes.

A: If you want to access to base class data you must use "this" keyword or you use this keyword as reference for class.
namespace thiskeyword
{
    class Program
    {
        static void Main(string[] args)
        {
            I i = new I();
            int res = i.m1();
            Console.WriteLine(res);
            Console.ReadLine();
        }
    }

    public class E
    {
        new public int x = 3;
    }

    public class F:E
    {
        new public int x = 5;
    }

    public class G:F
    {
        new public int x = 50;
    }

    public class H:G
    {
        new public int x = 20;
    }

    public class I:H
    {
        new public int x = 30;

        public int m1()
        {
           // (this as <classname >) will use for accessing data to base class

            int z = (this as I).x + base.x + (this as G).x + (this as F).x + (this as E).x; // base.x refer to H
            return z;
        }
    }
}


text:
Q: regexp maximal length restrict I have some regular expression like that:
(\d+\.)+

it's implement strings like 1.234.2421.222.11
Can i restrict max length of whole string (not quantity of groups)?
thanks a lot

A: Note that (\d+\.)+ does not match 1.234.2421.222.11 in it's entire. Your pattern mandates it should end with a .. You probably want a pattern like this:
\d+(\.\d+)*

And to give the input string a max length, say a max of 15 chars, do something like this:
^(?=.{0,15}$)\d+(\.\d+)*$

assuming your regex implementation supports look aheads.
EDIT
Okay, if your regex implementation does not support look aheads, do it in two steps. Something like this (pseudo code):
if input matches ^\d+(\.\d+)*$ and ^.{0,15}$ do
  ....
end

or, as paxdiablo also mentioned, use your programming language's built-in function to get the length of the string.

A: If your regex engine supports lookaheads, you can use something like:
^(?=.{M,N}$)(\d+\.)*\d+$

(fixed to not require a trailing . character) and this embeds the length check within the same regex. You need to replace M and N with the minimum and maximum size respectively.
If your engine is not so modern as to have lookaheads, you need to do two regex chacks:
^.{M,N}$
^(\d+\.)*\d+$

and ensure it passes them both. The first is the length check, the second is the content check.
But you may find that a regex is overkill for the length check, it's probably easier just to check the string length with Length().


text:
Q: Telling when iCloud has no more pending changes for Core Data update The NSPersistentStoreDidImportUbiquitousContentChangesNotification(I hope you're using a wide screen...) notification is received after updated records are imported from iCloud. But is there a way to tell that there are no more updates pending?
I need this mainly to detect the end of the initial update when a new store is added to iCloud, so that I can merge existing data safely.

A: As far as I know you have no means to tell whether there are any changes pending/not pending from the iCloud.


text:
Q: Sorting a string list with numbers on numbers I have a list which looks like this:
mylist = ['item_11', 'item_0', 'item_1', 'item_2', 'item_9', 'item_10', 'item_none']

I want to sort it on the numbers, but starting with "item_none", so the result will look like this:
['item_none', 'item_0', 'item_1', 'item_2', 'item_9', 'item_10', 'item_11']

I found a way which works for me, but it uses two list comprehensions to rename "item_none" to "item_-1" and back. I was wondering whether there is a more elegant way to do this? Thanks for any suggestions.
newlist = ['item_-1' if 'none' in x else x for x in mylist]
newlist.sort(key=lambda x: int(x.split('_')[-1]))
finallist = ['item_none' if '-1' in x else x for x in newlist]

A: You can set the key to -1 if none is there in the list
In [8]: mylist = ['item_11', 'item_0', 'item_1', 'item_2', 'item_9', 'item_10', 'item_none']

In [9]: mylist.sort(key=lambda x: -1 if x.split("_")[-1] == "none" else int(x.split('_')[-1]))

In [10]: mylist
Out[10]: ['item_none', 'item_0', 'item_1', 'item_2', 'item_9', 'item_10', 'item_11']


text:
Q: print an array within an array if an array value equals x Ruby I'm new to Ruby and I'm trying to practice my skills a bit by writing a simple terminal program that finds a hiking spot in Vancouver. (While this may not be the best way to write the program in the end, I'm trying to test my array skills with this program.)
What I've done is put 5 hiking spots in a 2 dimensional array. Each array includes the name, location, difficulty, and length of the hike. I want the user to enter their preferences and then print out the matching hikes.
E.g. If the user enters 6km, I want to print out the hike names from the arrays that are <= 6km.
So I want to print the following code but only when [0] <= 6  in "#{hikes[i][0]}"
    hikes.each_index{|i| puts "#{hikes[i][0]} " }

Thanks for the help!
Here's my code so far:
    #Hiking Array: [Hike Name, Location, Difficulty, Length(km)]

    hikes =
    [["Admiralty Point", "Tri Cities", "Easy", 5],
    ["Habrich Ridge Trail", "Howe Sound", "Intermediate", 7],
    ["Aldergrove Regional Park", "Surrey",  "Easy", 5],
    ["Alice Lake", "Howe Sound", "Easy", 6],
    ["Ancient Cedars Trail", "Whistler", "Intermediate", 5]]

    puts "It's the weekend! Where should we go hiking?\n\n"
    puts "Here is the list of available hikes."
    puts "___________________________"

    hikes.each_index{|i| puts "#{hikes[i][0]} " }

    puts "\n"
    puts "How many kilometers do we want to hike?"
    kilometers = $stdin.gets.chomp

    puts "\n"
    puts "How hard do we want the hike to be, Easy or Intermediate?"
    difficulty = $stdin.gets.chomp

    puts "\n"
    puts "What area of town do we want to hike in:"
    puts "Tri Cities"
    puts "Howe Sound"
    puts "Surrey"
    puts "Whistler"
    area_of_town = $stdin.gets.chomp

    puts "\n"
    puts "Ok searching for awesome views that are #{kilometers}km, of #{difficulty} difficulty, and are in #{area_of_town}."

    hikes.each_index{|i| puts "#{hikes[i][2]}"}

A: Maybe
hikes.select {|arr| arr[3] <= 5}.each{|arr| puts arr[0]}

But I would suggest using a hash so you can use name the attribute you're looking for.
hikes = [{'location'=>'Admirality', 'difficulty'=>5}, {'location'=>'Admirality', 'difficulty'=>10}, {'location'=>'Admirality', 'difficulty'=>15}]

hikes.select {|hsh| hsh["difficulty"] <= 10}

A: Simply use "and" operator && to print names from nested arrays if they match all 3 conditions, like:
hikes.each do |h|
    puts h[0] if ( h[3] <= kilometers &&
                    h[2].downcase == difficulty.downcase &&
                    h[1].downcase == area_of_town.downcase )
end

*

*I converted all strings to downcase before matching, just in case user input doesn't match case with array string (e.g "Easy" vs "easy")

*If you want to print all details of matching arrays, change puts h[0] to puts h.join(', ').

A: You might consider doing that as follows (after simplifying by eliminating some hike attributes):
hikes =
  [["Admiralty Point", 5],
  ["Habrich Ridge Trail", 7],
  ["Aldergrove Regional Park", 5],
  ["Alice Lake", "Howe Sound", 6],
  ["Ancient Cedars Trail", 5]]

HIKES_BY_DISTANCE =
  hikes.each_with_object(Hash.new {|h,k| h[k] = []}) {|a,h| h[a.last] << a}
  #=> {5=>[["Admiralty Point", 5],
  #        ["Aldergrove Regional Park", 5],
  #        ["Ancient Cedars Trail", 5]],
  #    7=>[["Habrich Ridge Trail", 7]],
  #    6=>[["Alice Lake", "Howe Sound", 6]]}

def select_hikes(length_range)
  HIKES_BY_DISTANCE.each_with_object([]) do |(k,v),a|
    a.concat(v) if length_range.cover?(k)
  end
end

select_hikes(4..5)
  #=> [["Admiralty Point", 5],
  #    ["Aldergrove Regional Park", 5],
  #    ["Ancient Cedars Trail", 5]]
select_hikes(2..6)
  #=> [["Admiralty Point", 5],
  #    ["Aldergrove Regional Park", 5],
  #    ["Ancient Cedars Trail", 5],
  #    ["Alice Lake", "Howe Sound", 6]]
select_hikes(4..7)
  #=> [["Admiralty Point", 5],
  #    ["Aldergrove Regional Park", 5],
  #    ["Ancient Cedars Trail", 5],
  #    ["Habrich Ridge Trail", 7],
  #    ["Alice Lake", "Howe Sound", 6]]
select_hikes(6..9)
  #=> [["Habrich Ridge Trail", 7],
  #    ["Alice Lake", "Howe Sound", 6]]
select_hikes(7..7)
  #=> [["Habrich Ridge Trail", 7]]
select_hikes(1..2)
  #=> []
select_hikes(8..9)
  #=> []


text:
Q: Subime Text 3 + LatexTools + Evince: forward sync not working I am writing a large document in Latex using ST3 + LatexTools on Ubuntu 16.04.
I never had a problem, except that this morning forward sync was no longer working (by forward sync I mean that Evince opens the pdf document at the position I was editing in ST).
I went through the most recent updates to my Ubuntu distribution, the latest changes to my Latex project, and the LatexTools settings, and everything seems fine to me.
Running the command:
python /path/to/LaTeXTools/evince/evince_forward_search /path/to/main.pdf 21 /path/to/source.tex

only results in Evince opening up the first page of the document, instead of the portion corresponding to line 21 of the sub-file source.tex. The command runs without outputting any error.
I would appreciate hints of what to look for, where things could go wrong, etcetera.
This is a very large project including lots of packages and using tenths of sub-files, each of which has the
%!TEX root = ../../main.tex

instruction at the top. This had never caused a problem before.
EDIT: python-dbus, python-gobject and python-gi are all correctly installed and up to date on my system.
Any suggestion?
Thanks :)


text:
Q: EF Core ToDictionary throw expression could not be translated I have this query:
        Project = await Context.Projects.Where(x => x.Id == project.Id)
        .Select(x => new ProjectModel
        {
            Id = project.Id,
            Name = project.Name,
            TreeDataDict = x.Tasks.Select(y => new TreeItemModel()
            {
                NodeId = y.Id,
                ParentId = SetTaskParentId(y, y.Type),
                NodeTitle = y.Name,
                Expanded = false,
                Object = new TaskBaseModel
                {
                    Milestone = y.Milestone,
                    StartDate = y.StartDate,
                    CurrentEndDate = y.CurrentEndDate,
                    EndDate = y.EndDate,
                },
                Icon = TaskHelper.GetTaskIcon(y.Type),
                Children = new List<TreeItemModel>()
            }).ToDictionary(y => y.NodeId, y => y)
        }).SingleOrDefaultAsync();

and also tried like this:
        Project = await Context.Projects.Where(x => x.Id == project.Id)
        .Select(x => new ProjectModel
        {
            Id = project.Id,
            Name = project.Name,
            TreeDataDict = x.Tasks.ToDictionary(y => y.Id, y => new TreeItemModel(
            {
                NodeId = y.Id,
                ParentId = SetTaskParentId(y, y.Type),
                NodeTitle = y.Name,
                Expanded = false,
                Object = new TaskBaseModel
                {
                    Milestone = y.Milestone,
                    StartDate = y.StartDate,
                    CurrentEndDate = y.CurrentEndDate,
                    EndDate = y.EndDate,
                },
                Icon = TaskHelper.GetTaskIcon(y.Type),
                Children = new List<TreeItemModel>()
            })
        }).SingleOrDefaultAsync();

Both ways I got this exception:

What could be causing this? and is there a way I could make this work without fetching as a list and then covert it to dictionary? What could be the most efficient way to achieve this?
Regards

A:
What could be causing this?

Translation of the nested ToDictionary call (none of the available overloads) is not supported. Consider it one of the (many) current (latest at the time of writing official v5.0.11) EF Core shortcomings.
Interestingly though, the Dictionary<TKey, TValue> constructor overload with IEnumerable<KeyValuePair<TKey, TValue>> argument as well as projection (Select) to KeyValuePair<TKey, TValue> is supported, which gives the workaround - replace the ToDictionary call with the aforementioned constructor and Select, e.g. (replace int with the type of the Id)
TreeDataDict = new Dictionary<int, TreeItemModel>(
x.Tasks.Select(y => new TreeItemModel()
{
    NodeId = y.Id,
    ParentId = SetTaskParentId(y, y.Type),
    NodeTitle = y.Name,
    Expanded = false,
    Object = new TaskBaseModel
    {
        Milestone = y.Milestone,
        StartDate = y.StartDate,
        CurrentEndDate = y.CurrentEndDate,
        EndDate = y.EndDate,
    },
    Icon = TaskHelper.GetTaskIcon(y.Type),
    Children = new List<TreeItemModel>()
})
.Select(e => new KeyValuePair<int, TreeItemModel>(e.NodeId, e)));

This will fix the current error. But note that you are using other non-translatable constructs (custom method calls like SetTaskParentId(y, y.Type) and TaskHelper.GetTaskIcon(y.Type)) which are supported only in the final Select, so make sure to not add LINQ operator like Where, OrderBy etc. after the root query Select(x => new ProjectModel { ... }, otherwise you'll get other runtime errors. ToList, `First


text:
Q: KStream/KsqlDb application with Persistent State Store in Kubernetes
*

*Does anyone here have experience in deploying KStream/KsqlDb application with Persistent State Store in Kubernetes environment without loosing the auto scalability? i.e. Automatic creation of state store volume and the state for new container and rebalancing once the container is gone without loosing the topic partiton to the data volume mapping. Is it possible?

*When a Persistent State store disappears(or gets deleted), will KStream restore the state store from the Change Log topic automatically or we have to manually reset the consumer offsets to earliest on the Change log topic consumer?

A: *

*This is hard to achieve. However, you could use standby tasks to get HA for this case.

*You don't need to do anything. Kafka Streams will automatically restore state from the changelog.


text:
Q: Mongo "manual reference" performance compare to traditional DB's "table joining" According to the official document: "manual reference" operation is usually preferred, experienced guy even suggest never use DBref, then I am seriously concerning how much of the performance penalty to do twice query when I want to query entities with relational collection, especially comparing with the traditional relational DB - we can retrieve the expected result within one query using table joins.
Denormalize example:
db.blogs.insert({
  _id: 1,
  title: "Investigation on MongoDB",
  content: "some investigation contents",
  post_date: Date.now(),
  permalink: "http://foo.bar/investigation_on_mongodb",
  comments: [
    { content: "Gorgeous post!!!", nickname: "Scott", email: "foo@bar.org", timestamp: "1377742184305" },
    { content: "Splendid article!!!", nickname: "Guthrie", email: "foo@bar.org", timestamp: "1377742184305" }
  ]}
               )

We can simply use: db.blogs.find() to get everything we want: blog posts with comments belong to them.
Normalize example:
db.books.insert({
  _id: 1,
  name: "MongoDB Applied Design Patterns",
  price: 35,
  rate: 5,
  author: "Rick Copeland",
  ISBN: "1449340040",
  publisher_id: 1,
  reviews: [
    { isUseful: true, content: "Cool book!", reviewer: "Dick", timestamp: "1377742184305" },
    { isUseful: true, content: "Cool book!", reviewer: "Xiaoshen", timestamp: "1377742184305" }
  ]
  }
);

db.publishers.insert({
  _id: 1,
  name: "Packtpub INC",
  address: "2nd Floor, Livery Place 35 Livery Street Birmingham",
  telephone: "+44 0121 265 6484",
  }
);

Now if I want to get the complete information about a single book I have to manually query twice, similar to below:
> var book =  db.books.find({ "name": { $regex: 'mongo*', $options: 'i' } })
> db.publishers.find({ _id: book.publisher_id })

Things I know is: the precedence operations will be process by Mongo "in memory", but I will have the summarized question below:
In simply words: document oriented database advocates "denormalize" data to retrieve result within one query, however, when we have to store relational data, it "suggest" you to use "manual reference", which means twice query, while in relational DB there will be only one time query by using "table joining".
This makes no sense for me:)

A: A relational database also performs a JOIN by querying both tables. But it has the advantage that it can do this internally and doesn't have to communicate with the client to do this. It can query the 2nd table immediately.
MongoDB first needs to send the results of the first query to the client before the application can formulate and send the 2nd query back to the database. The time lost by this is:

*

*Network latency between database server and application server (a couple ms)

*Interprete the response on the application server and generate a $in-query from it (a couple µs)

*Network latency between application server and database server (a couple ms)

Depending on how well the application server and the database server are interconnected, we are talking about a penalty of a few ms here.


text:
Q: Purchasing one item multiple times in TInApppurchase in Delphi XE6 I have developed an application with Delphi XE6 including inappPurchase, I have defined the product as 'Consumable' in itunesConnect, but after purchasing one item, it won't let me buy another one.
In my application user should be able to buy 'n' number of licenses, in PurchaseProduct Method just takes productID as parameter so I need to call this method multiple times.
I thought defining another Product like as 10-Licenses would be a good idea, but there is no relation between this two Products, and ConsumeProduct Method just takes a ProductID not the number of consumtion.
Since lack of resources about that, I appreciate if some one gives me some hints, or best practices.
p.s. Is storing the number of purchased products in application good idea?

A: I found the solution but I don't know if it is correct or not:
I consume the product just right after purchasing, and I locally get the track of bought items.

A: if productquery is fill with list, actually u can consume. i put try finally end statement, and put consumeproduct after try. and it will work,
what do u mean by locally get the track of bought items?


text:
Q: Kafka stuck on reassign partitions tool and progress Running the reassignment partitions tool, to expand the partitions over 5 brokers instead of 5.
Kafka 2.1, on Docker.
It gets to a point where one of the nodes behave erratically.
The other (healthy) nodes begin to show these messages:
[2018-12-27 13:00:31,618] INFO [ReplicaFetcher replicaId=1, leaderId=3, fetcherId=0] Error sending fetch request (sessionId=48303608, epoch=226826) to node 3: java.io.IOException: Connection to 3 was disconnected before the response was read. (org.apache.kafka.clients.FetchSessionHandler)
[2018-12-27 13:00:31,620] WARN [ReplicaFetcher replicaId=1, leaderId=3, fetcherId=0] Error in response for fetch request (type=FetchRequest, replicaId=1, maxWait=500, minBytes=1, maxBytes=10485760, fetchData={impressions-35=(offset=3931626, logStartOffset=0, maxBytes=1048576, currentLeaderEpoch=Optional[29]), impressions-26=(offset=4273048, logStartOffset=0, maxBytes=1048576, currentLeaderEpoch=Optional[28]), impressions-86=(offset=3660830, logStartOffset=0, maxBytes=1048576, currentLeaderEpoch=Optional[28]), events-93=(offset=2535787, logStartOffset=0, maxBytes=1048576, currentLeaderEpoch=Optional[26]), impressions-53=(offset=3683354, logStartOffset=0, maxBytes=1048576, currentLeaderEpoch=Optional[28]), impressions-59=(offset=3696315, logStartOffset=0, maxBytes=1048576, currentLeaderEpoch=Optional[29]), impressions-11=(offset=3928338, logStartOffset=0, maxBytes=1048576, currentLeaderEpoch=Optional[28]), events-69=(offset=2510463, logStartOffset=0, maxBytes=1048576, currentLeaderEpoch=Optional[27]), events-72=(offset=2481181, logStartOffset=0, maxBytes=1048576, currentLeaderEpoch=Optional[28]), events-75=(offset=2462527, logStartOffset=0, maxBytes=1048576, currentLeaderEpoch=Optional[27]), events-126=(offset=2510344, logStartOffset=0, maxBytes=1048576, currentLeaderEpoch=Optional[27]), events-63=(offset=2515896, logStartOffset=0, maxBytes=1048576, currentLeaderEpoch=Optional[27])}, isolationLevel=READ_UNCOMMITTED, toForget=, metadata=(sessionId=48303608, epoch=226826)) (kafka.server.ReplicaFetcherThread)
java.io.IOException: Connection to 3 was disconnected before the response was read
    at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:97)
    at kafka.server.ReplicaFetcherBlockingSend.sendRequest(ReplicaFetcherBlockingSend.scala:97)
    at kafka.server.ReplicaFetcherThread.fetchFromLeader(ReplicaFetcherThread.scala:190)
    at kafka.server.AbstractFetcherThread.processFetchRequest(AbstractFetcherThread.scala:241)
    at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3(AbstractFetcherThread.scala:130)
    at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3$adapted(AbstractFetcherThread.scala:129)
    at scala.Option.foreach(Option.scala:257)
    at kafka.server.AbstractFetcherThread.maybeFetch(AbstractFetcherThread.scala:129)
    at kafka.server.AbstractFetcherThread.doWork(AbstractFetcherThread.scala:111)
    at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:82)

15 minutes later, the healthy servers show the following messages:
[2018-12-27 13:16:00,540] INFO [ReplicaFetcher replicaId=1, leaderId=3, fetcherId=0] Retrying leaderEpoch request for partition events-111 as the leader reported an error: UNKNOWN_SERVER_ERROR (kafka.server.ReplicaFetcherThread)

Later on we can see lots of these messages:
[2018-12-27 17:20:21,132] WARN [ReplicaManager broker=1] While recording the replica LEO, the partition events-116 hasn't been created. (kafka.server.ReplicaManager)

among other sets of these, more common:
[2018-12-27 17:20:21,138] WARN [ReplicaManager broker=1] Leader 1 failed to record follower 3's position 2517140 since the replica is not recognized to be one of the ass

igned replicas 1,4,6 for partition events-53. Empty records will be returned for this partition. (kafka.server.ReplicaManager)
The reassigned topic had 128 partitions among 3 servers. All in all, each server has around 2000 partitions.
Now reassignment is stuck for 6 hours, showing a stuck 41% partitions underreplicated.
It had replication 3, although it now has replication 5. I suppose this is part of how the rebalancing happens underneath, in order to increase these replicas and later drop those that are unwanted?
Node 3 is however showing these messages:
[2018-12-27 17:10:05,509] WARN [RequestSendThread controllerId=3] Controller 3 epoch 14 fails to send request (type=LeaderAndIsRequest, controllerId=3, controllerEpoch=14, partitionStates={events-125=PartitionState(controllerEpoch=14, leader=1, leaderEpoch=25, isr=3,1,2, zkVersion=57, replicas=1,6,2,3, isNew=false)}, liveLeaders=(172.31.10.35:9092 (id: 1 rack: eu-west-1c))) to broker 172.31.27.111:9092 (id: 3 rack: eu-west-1a). Reconnecting to broker. (kafka.controller.RequestSendThread)

So, something is wrong with the node "3" - how can I know what happened with it?
It has happened the two times we tried reassigning partitions in two topics of the same partition size. In the previous case, we brought up another machine as a new broker (restarting container didn't help)  with the same Id and it recovered. But, how can this be avoided to happen?
What can be the root cause?

A: Some time past since this was written. However if it helps anyone, I think the settings changes that helped were: to increase
zookeeper.session.timeout.ms , zookeeper.connection.timeout.ms, and replica.lag.time.max.ms in our case to 60000.
Since then it has not happened again. The idea behind is that at some point one of the brokers loses ZK session, and that creates misconnection between the brokers that think the broker is still alive and ZK who thinks it is not. For some reason this doesn't ever get cleaned. Increasing these settings allow for longer session stickiness times. Beware, it also would take longer to expire brokers that are genuinely dead.


text:
Q: iOS bind images in array and on the disk I have NSArray that contains UIImage objects. When I add new image to this array I also save the same image on disk. It is work ok for me.
When I remove image from the NSArray I also want to remove this image from the disk.
So if use for example index 0, 1, 2, 3, 4 it is not good for me to store images on the disk.
Let me show why:
So for example I create images 0, 1, 2, 3, 4 (I remove .png just keep with indexes).
Second step is remove third element in my array, So I know that the index for removing element is 2 because it is third in array.
I remove image with appropriate index name on the disk.
So how can I bind my images on the disk and in the array.
Maybe another solution I think can be add counter that will every time increase count of image for get unique name id and also using names of file instead of indexes of UIImage in the array.

A: I would use an additional NSDictionary. You could use an NSString as the key that contains a unique identifier for each image (which you also use as the filename), and the UIImage as the value. Then, your array could store the NSStrings with the ids.
So for example:
NSMutableArray *array = @[@"a", @"b", @"c"];
NSMutableDictionary *dictionary = @{@"a" : firstImage,
                                    @"b" : secondImage,
                                    @"c" : thirdImage,};

So, to get the secondImage you would do
UIImage *secondImage = dictionary[array[1]];

If you then remove that image (and dictionary, you need to keep them synched), your array will look like this [@"a", @"c"]. Executing the line above will return thirdImage this time.
Your filenames could should be a.png, b.png and c.png. So you also have that.
I hope that helps!


text:
Q: How can I swap two color in one image in windows form application? I need to swap two color in one image like in the link:
Like this :

this code not correct
but I need code to do like this
private void Form1_Load(object sender, EventArgs e)
{
    Bitmap bmp = new Bitmap(tsttPic.Image);

    int width = bmp.Width;

    int height = bmp.Height;

    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {

            Color p = bmp.GetPixel(x, y);

            int a = p.A;
            int r = p.R;
            int g = p.G;
            int b = p.B;
            if (r == 255 && b == 255 && b == 255)
            {
                r = 0;
                g = 128;
                b = 255;

            }
            else
            {
                r = 255;
                g = 255;
                b = 255;
            }
            bmp.SetPixel(x, y, Color.FromArgb(a, r, g, b));
        }

    }

    neggPic.Image = bmp;
}


text:
Q: Google test's ambiguous else blocker defeated by GCC 7.1 When using Google Test, code like
int main(int argc, char const *argv[])
{
    if (argc > 0)
        EXPECT_EQ(argc, argc);
}

gets expanded to
int main(int argc, char const *argv[])
{
  if (argc > 0) switch(0) case 0: default:
  //            ^^^^^^^^^^^^^^^^^^^^^^^^^^
    if (argc > 1)
      return 2;
    else
      return 1;

  return 0;
}

The switch(0) case 0: default: is the expansion of a macro (GTEST_AMBIGUOUS_ELSE_BLOCKER_) which is used to suppress the following warning:
prog.cc:3:6: warning: suggest explicit braces to avoid ambiguous 'else' [-Wdangling-else]
   if (argc > 0) switch(0) case 0: default:
      ^

However, GCC 7.1 and latest trunk fail to suppress the warning:
https://wandbox.org/permlink/EYZtD8ttDmNI6aeX
whereas clang works as expected:
https://wandbox.org/permlink/zwSPPXtZ1w2SIthX
This looks like a bug in GCC, am I right?


text:
Q: NSIS installer script with TFS Build Tool is it possible to utilize my NSIS installer script to make an automated build (daily) for my program in TFS 2010? The program isnt C#, it's actually small talk, so the installer being designed in NSIS was prior to our group being required to migrate source control into TFS.
Essentially the installer just copy/pastes the directory and shortcuts onto destination PC, and runs a regedit for the new parameters. I noted in the TFS build tool (which I'm extremely unfamiliar with) that it constantly wants me to point at a .proj file.. Does this mean I've got to convert our NSIS scripts into some .NET equivalent (if so how?) or is there a plugin of some sort to allow these guys to play nice together?

A: If your project support MSBuild to build it, you can use TFS Team Build directly. If your project doesn't support MSBuild to build it, you need to provide a compiler which can build your project, and this compiler support run the command line to invoke it, so we can add the InvokeProcess activity(execute the command line) to invoke that compiler to build your project in build process template.
Here are useful blogs for your reference:

*

*http://donovanbrown.com/post/I-need-to-build-a-project-that-is-not-supported-by-MSBuild

*http://blogs.objectsharp.com/post/2011/03/31/TFS-Build-Invoke-Process-Activity.aspx


text:
Q: Volume of polyhedron similar to prism but with different bases Imagine a polyhedron similar to a prism, with parallel but different bases. Let the bases have the same number of sides, so that every vertex on a base is connected to exactly one vertex on the other base (side faces are all quadrilaterals). See example figure:
polyhedron similar to prism

*

*Does it have a name? I found the term "prismatoid" but it seems like a more general family.  See edit below.

*Is it possible to compute its volume without integrating? By analogy with trapezoids in 2D, I'd be tempted to say $(A1 + A2) / 2 * h$, where $A1$ and $A2$ are the areas of the two bases.

EDIT
It's been rightly noticed that my picture is not a polyhedron because the left face is not planar. But I've found that what I describe should be a "prismoid", a subclass of prismatoids with both bases having the same number of vertices. But I cannot find extended information on such objects, so I think the second question still holds.


text:
Q: correct usage with commas (dashes) 1.The actor, a life well lived, died on the stage.
2.The victim, a local solicitor, was killed on impact.
Is it acceptable to use commas with 1, like 2, or should em dashes be used with after.
The actor — after a life well lived — died on the stage.

A: The em-dash can replace parenthesis, commas, and also colons. That said, you can simply replace the commas with the dashes. There is no need to add any word (in your example, 'after'). The non-restrictive clauses with double commas (example number -2) can be replaced by em-dashes.
Nevertheless, as FumbleFingers pointed out, the first example does not mean that the actor is a life well-lived.


text:
Q: QRegExp remove line with text from QString I would like to remove all lines from a QString that have text and keep the ones that are numbers.
Prior to running a regexp my QString output be as so:
hello

1

world

2

if I ran something like
QString.remove(QRegExp("(^[a-z]*\\n$)"))

my QString output would be:
1

2

A: Since QRegExp does not have a Perl-like /m modifier, you need to use groups like (^|\n) and ($|\n) instead. Also, bearing in mind linebreaks may include carriage returns, I'd use something like
(^|\r?\n)[a-z]*\r?\n(\r?\n|$)

See the regex demo
Qt:
QString t = "hello\n\n1\n\nworld\n\n2";
t.replace(QRegExp("(^|\r?\n)[a-z]*\r?\n(\r?\n|$)"), "\\1");

NOTE that this code will only remove lines that only consist of lowercase ASCII letters and a linebreak after them. If you need to just remove all lines that are not numeric, use QRegExp("(^|\r?\n)[^\\d\n]+\r?\n(\r?\n|$)") where [^\d\n] matches any non-digit character and not a newline.


text:
Q: How do I print HTML code with indentantion? I'm creating a layout page with the components that I'm using in a project for other people use the same design. My ideia is to let my script get my innerHTML code and print it for the user as a text;
Here's the codepen.
So far, I have this:

// Get all divs with the ".topic" class and returns a list of it
// @return list | array()
function getTopicList() {

  // Create the list
  let list = [];

  // Populate the list
  $('.topic').map(function() {
    list.push($(this));
  });

  // Returns the list
  return list;

}

// Set the example code inside a "code" tag
// @param topic       | jquery object
// @param exampleCode | string
function setExampleCode(topic, exampleCode) {

  // Create a "code" tag inside the selected div
  $(topic).append('');

  // Set the example's code inside the "code" tag
  $(topic).find('code').text(exampleCode);

}

// Get the HTML code inside the div as a string
// @param topic | jquery object
function generateExampleCode(topic) {

  // Get the HTML code as string
  let exampleCode = $(topic).children('.example').html();

  // Calls a function to append the code as a string into the div
  setExampleCode(topic, exampleCode);

}

$(document).ready(function() {

  // Get a list of all the divs that have the ".topic" class
  let topicList = getTopicList();

  // Get the HTML code of all the ".topic" divs
  topicList.map(generateExampleCode);

});

Buttons

Materialize buttons.

    <button class="btn left">Button</button>
    <button class="btn left">addButton</button>
    <button class="btn left">addButton</button>

And my result is the following:

My expected result is:

I know that I can manipulate the string and replace the "<" for "<" and the ">" for ">", but is it the only way to do it? Is there a simpler way to do it?

A: would it not be appropriate to use "pre" tag like.
    function setExampleCode(topic, exampleCode) {
    // Create a "code" tag inside the selected div
    $(topic).append('

');

    // Set the example's code inside the "code" tag
    $(topic).find('pre').text(exampleCode);

}

A: Maybe all you need is some CSS?
code {
    white-space: pre-line;
}

Working codepen from your example

A: You can use the "pre" element when displaying text with unusual formatting, or some sort of computer code. HTML pre Tag

// Get all divs with the ".topic" class and returns a list of it
// @return list | array()
function getTopicList() {

  // Create the list
  let list = [];

  // Populate the list
  $('.topic').map(function() {
    list.push($(this));
  });

  // Returns the list
  return list;

}

// Set the example code inside a "code" tag
// @param topic       | jquery object
// @param exampleCode | string
function setExampleCode(topic, exampleCode) {

  // Create a "code" tag inside the selected div
  $(topic).append('

');

  // Set the example's code inside the "code" tag
  $(topic).find('pre').text((exampleCode));

}

// Get the HTML code inside the div as a string
// @param topic | jquery object
function generateExampleCode(topic) {

  // Get the HTML code as string
  let exampleCode = $(topic).children('.example').html();

  // Calls a function to append the code as a string into the div
  setExampleCode(topic, exampleCode);

}

$(document).ready(function() {

  // Get a list of all the divs that have the ".topic" class
  let topicList = getTopicList();

  // Get the HTML code of all the ".topic" divs
  topicList.map(generateExampleCode);

});

Buttons

Materialize buttons.

    <button class="btn left">Button</button>
    <button class="btn left">addButton</button>
    <button class="btn left">addButton</button>


text:
Q: Can the integral value of ${\int}_{0}^{t} \frac{{x^2} exp(x)}{(exp(x)-1)^2} dx$ for t>0 be obtained analytically? In the process of solving the exercise on the qualitative discussion
of the specific heat of a one-dimensional lattice,
I need to consider the integral of the following f(x).
$$f(x)= \frac{{x^2} \exp(x)}{(\exp(x)-1)^2}  \tag{1-1}$$
The problem I present to you is as follows;

*

*(1) Can the following integral value be obtained analytically for $t>0$?
$$F(t):= {\int}_{0}^{t} \frac{{x^2} \exp(x)}{(\exp(x)-1)^2}  dx \tag{1-2}$$

*(2) If the above is not possible, can the limit of $t\to\infty$ be found analytically? In other words, please calculate the following limit values.
$$\lim_{t \to \infty}F(t) \tag{1-3}$$

*(3) If none of the above is possible, is it possible to approximate "this integral is almost independent of t when t is sufficiently large"? ($F(t)$ can be regarded as a constant)?

As for (3), I plotted a graph of f(x) and found that,
$\lim_{t\to0}f(t)=1$, and
the $f(x)$ rapidly approaches $0$ when $x$ becomes large.

Fig.A graph showing $F(t)$ from 0 to 15.

A: $$I=\int_{0}^{\infty}\frac{x^2 e^x}{(e^x-1)^2}dx = \int_{0}^{\infty}\sum_{k=0}^{\infty}  (k+1) x^2 e^{-x} e^{-kx} dx.$$
Use the series for $(1-z)^2=\sum_{k=0}^{\infty} (k+1)z^k, |z|<1.$
$$I=\sum_{k=0}^{\infty} \int_{0}^{\infty} (k+1) x^2 e^{-(k+1)x} dx$$
$$I=2\sum_{k=0}^{\infty} \frac{ k+1}{(k+1)^3}=2 \sum_{k=0}^{\infty} \frac{1}{(k+1)^2}=2 \zeta(2)=\frac{\pi^2}{3}$$

A: Let $x=\log(u)$ to make
$$I=\int\frac{e^x x^2}{\left(e^x-1\right)^2}dx=\int\frac{\log ^2(u)}{(u-1)^2}\,du=\int\frac{\log ^2(v+1)}{v^2}\,dv$$Back to $x$
$$I=\int\frac{e^x x^2}{\left(e^x-1\right)^2}dx=2 \text{Li}_2\left(e^x\right)+x \left(\frac{e^x x}{1-e^x}+2 \log
   \left(1-e^x\right)\right)$$
$$J=\int_0^t\frac{e^x x^2}{\left(e^x-1\right)^2}dx=2 \text{Li}_2\left(e^t\right)+t \left(2 \log \left(1-e^t\right)-\frac{e^t
   t}{e^t-1}\right)-\frac{\pi ^2}{3}$$
$J$ tends very fast to $\frac {\pi^2}{3}$. Solving for $t$ such that $J(t)=k\frac{\pi^2}{3}$
$$\left(
\begin{array}{cc}
k & t_k \\
 0.9000 & 4.59526 \\
 0.9900 & 7.77037 \\
 0.9990 & 10.6318 \\
 0.9999 & 13.3521
\end{array}
\right)$$

A: Use integration by parts with $u = x^2$ and $dv = \frac{e^x \: dx}{(e^x - 1)^2}$. Then $$\int_0^t \frac{x^2 e^x}{(e^x - 1)^2} \: dx = \frac{x^2}{1 - e^x} \biggr|_0^t + \int_0^t \frac{2x}{e^x - 1} \: dx$$
The first term goes to zero as t approaches infinity. The second denominator can be replaced by its Maclaurin series:
$$\int_0^t \frac{2x}{e^x - 1} \: dx = \int_0^t \frac{2x}{x + x^2/2 + x^3/6 + \ldots} \: dx \leq \int_0^t \frac{2}{1 + x/2 + x^2/6} \: dx$$
The antiderivative of the last integral is $$\frac{24}{\sqrt{15}} \arctan \left( \frac{2x + 3}{\sqrt{15}} \right)$$ This converges as $x$ approaches infinity.
To four decimal places: $$\lim_{t \rightarrow \infty} \int_0^t \frac{x^2 e^x}{(e^x - 1)^2} \: dx \approx 3.2899$$

A: Another version using integration by parts only
$$\int_0^t \frac{x^2 e^x}{(e^x-1)^2} \, {\rm d}x = -\frac{t^2}{e^t-1} + \underbrace{\int_0^\infty \frac{2x}{e^x-1} \, {\rm d}x}_{=2\zeta(2)} - \int_t^\infty \frac{2x}{e^x-1} \, {\rm d}x \\
=-\frac{t^2}{e^t-1}  + \frac{\pi^2}{3} + 2t \log(1-e^{-t}) + 2 \underbrace{\int_t^\infty \log(1-e^{-x}) \, {\rm d}x}_{-{\rm Li}_2(e^{-t})} \\
= \frac{\pi^2}{3} - e^{-t} \left( t^2 + 2t + 2 \right) + {\cal O}\left(t^2 e^{-2t}\right)$$
where ${\rm Li}_2(x)=\sum_{n=1}^\infty \frac{x^n}{n^2}$.


text:
Q: Using C# code in Powershell scripts and Save results in variable I'm using C# code in Powershell:
$Code = @'
....................
public class RDPInfo
....................
'@
Add-Type $Code
$ListUsers = [RDPInfo]::ListUsers("ServerName")
$ListUsers -eq $null

The script works and returns result - list of users on server (must be array, I think), but cannot save to variable $ListUsers - it is left empty. Can you advise how to deal with it?
Thanks.
P.S. Here is a full code:
# QuerySessionInformation.ps1
# Written by Ryan Ries, Jan. 2013, with help from MSDN and Stackoverflow.

$Code = @'
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
public class RDPInfo
{
    [DllImport("wtsapi32.dll")]
    static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] String pServerName);

    [DllImport("wtsapi32.dll")]
    static extern void WTSCloseServer(IntPtr hServer);

    [DllImport("wtsapi32.dll")]
    static extern Int32 WTSEnumerateSessions(
        IntPtr hServer,
        [MarshalAs(UnmanagedType.U4)] Int32 Reserved,
        [MarshalAs(UnmanagedType.U4)] Int32 Version,
        ref IntPtr ppSessionInfo,
        [MarshalAs(UnmanagedType.U4)] ref Int32 pCount);

    [DllImport("wtsapi32.dll")]
    static extern void WTSFreeMemory(IntPtr pMemory);

    [DllImport("Wtsapi32.dll")]
    static extern bool WTSQuerySessionInformation(System.IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out System.IntPtr ppBuffer, out uint pBytesReturned);

    [StructLayout(LayoutKind.Sequential)]
    private struct WTS_SESSION_INFO
    {
        public Int32 SessionID;
        [MarshalAs(UnmanagedType.LPStr)]
        public String pWinStationName;
        public WTS_CONNECTSTATE_CLASS State;
    }

    public enum WTS_INFO_CLASS
    {
        WTSInitialProgram,
        WTSApplicationName,
        WTSWorkingDirectory,
        WTSOEMId,
        WTSSessionId,
        WTSUserName,
        WTSWinStationName,
        WTSDomainName,
        WTSConnectState,
        WTSClientBuildNumber,
        WTSClientName,
        WTSClientDirectory,
        WTSClientProductId,
        WTSClientHardwareId,
        WTSClientAddress,
        WTSClientDisplay,
        WTSClientProtocolType
    }

    public enum WTS_CONNECTSTATE_CLASS
    {
        WTSActive,
        WTSConnected,
        WTSConnectQuery,
        WTSShadow,
        WTSDisconnected,
        WTSIdle,
        WTSListen,
        WTSReset,
        WTSDown,
        WTSInit
    }

    public static IntPtr OpenServer(String Name)
    {
        IntPtr server = WTSOpenServer(Name);
        return server;
    }

    public static void CloseServer(IntPtr ServerHandle)
    {
        WTSCloseServer(ServerHandle);
    }

    public static void ListUsers(String ServerName)
    {
        IntPtr serverHandle = IntPtr.Zero;
        List<String> resultList = new List<string>();
        serverHandle = OpenServer(ServerName);

        try
        {
            IntPtr SessionInfoPtr = IntPtr.Zero;
            IntPtr userPtr = IntPtr.Zero;
            IntPtr domainPtr = IntPtr.Zero;
            IntPtr clientNamePtr = IntPtr.Zero;
            Int32 sessionCount = 0;
            Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref SessionInfoPtr, ref sessionCount);
            Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));
            Int32 currentSession = (int)SessionInfoPtr;
            uint bytes = 0;
            if (retVal != 0)
            {
                for (int i = 0; i < sessionCount; i++)
                {
                    WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO));
                    currentSession += dataSize;

                    WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes);
                    WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes);
                    WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSClientName, out clientNamePtr, out bytes);

                   if(Marshal.PtrToStringAnsi(domainPtr).Length > 0 && Marshal.PtrToStringAnsi(userPtr).Length > 0)
                    {
                        if(Marshal.PtrToStringAnsi(clientNamePtr).Length < 1)
                            /* Console.WriteLine(Marshal.PtrToStringAnsi(domainPtr) + "\\" + Marshal.PtrToStringAnsi(userPtr) + "\tSessionID: " + si.SessionID + "\tClientName: n/a");   */
                            Console.WriteLine(Marshal.PtrToStringAnsi(userPtr));
                        else
                            /* Console.WriteLine(Marshal.PtrToStringAnsi(domainPtr) + "\\" + Marshal.PtrToStringAnsi(userPtr) + "\tSessionID: " + si.SessionID + "\tClientName: " + Marshal.PtrToStringAnsi(clientNamePtr));   */
                            Console.WriteLine(Marshal.PtrToStringAnsi(userPtr));
                    }
                    WTSFreeMemory(clientNamePtr);
                    WTSFreeMemory(userPtr);
                    WTSFreeMemory(domainPtr);
                }
                WTSFreeMemory(SessionInfoPtr);
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
        finally
        {
            CloseServer(serverHandle);
        }
    }
}
'@

Add-Type $Code
$ListUsers = [RDPInfo]::ListUsers("SERVERNAME")
$ListUsers -eq $null #TRUE

Gives result:
Username1
Username2
.........
UsernameN
ListUsers :

But $ListUsers variable is empty!

A: Change your function public static void ListUsers(String ServerName) to
public static List<string> ListUsers(String ServerName)

In the for loop add the username to your list:
resultList.Add(Marshal.PtrToStringAnsi(userPtr));

At the end of the function return the list:
return resultList;

This should do it...


text:
Q: Django Sitemap not returning items I have a basic sitemap created. However I'm looking to make it more Google compliant.
I have a queryset that works however when I try and access the url.items in my custom template I only get the default 'priority', lastmod etc...
Sitemaps.py
from django.contrib.sitemaps import Sitemap

from myapp.models import *

class mySitemap(Sitemap):
    changefreq = "daily"
    priority = 0.5

    def items(self):
        articles =
            sync_Binder.objects.select_related() \
            .filter(sync_binder_index__platform_id > = '2') \
            .order_by('sync_binder_index__rank')
        return articles

    def lastmod(self, obj):
        return obj.modifieddate

urls.py
sitemaps = {'mysitemap': mySitemap,}

urlpatterns = patterns('django.contrib.sitemaps.views',
    (r'^%ssitemap.xml$' % PROJECT_URL, 'sitemap',
        {'sitemaps':sitemaps, 'template_name':'sitemap.html'}),
)

sitemap.html contains the following loop
{% for url in urlset %}
    {{ url.items }}
{% endfor %}

...yet I only get the defaults nothing from my articles query set which contains images, headlines etc
Any suggestions?
Thanks
S


text:
Q: Facing issues while displaying json data with jquery datatables I am new to jquery datatables. I have a json format returning from the server in the below format:
{
  "links": [
    {
      "rel": "self",
      "href": "http://hostname:port/state/city/1"
    }
  ],
  "name1": "value1",
  "name2": "value2",
  "name3": "value3",
  "name4": "value4"

}
In the javascript I am using the below code to display in the table:
<script>
  $(function  ()  {
    $('#dataTable').dataTable( {
      "bJQueryUI": true,
      "sPaginationType": "full_numbers",
      "sAjaxSource": "partials/records.txt",
      "aoColumns": [
        { "mData": "name1" },
        { "mData": "name2" },
        { "mData": "name3" },
        { "mData": "name4" },
      ]
    });
  });
</script>

I am getting error and the data is not getting displayed in the table. How to display the above json format in the datatable? To my limited knowledge, I see that I do not have "sAjaxDataProp": "list", in the script? Is the error because of the sAjaxDataProp property?
Please let me know where I am going wrong.

A: I found the solution for my query. The format of the json should is not correct. The json should contain sAjaxDataProp value. The json should be formatted before it is consumed by the datatable. Details can be found in the below link: Using ajax to load a jQuery DataTable


text:
Q: closed subscheme not onto for global functions Is there a simple example of a closed subscheme $X\rightarrow Y $ such that $\mathscr{O}_ Y(Y)\rightarrow \mathscr{O}_X(X)$         is not onto?
(Sort of related to this question Intersection of closed sub schemes, but not really comparable)

A: Let $k$ be a field, and $P_1=\sum_{i=0}^d{a_iU^i} \in k[U]$ be irreducible with degree $d > 1$ (it's possible as soon as $k$ isn't algebraically closed).
Let $P=\sum_{i=0}^d{a_iU^iV^{d-i}} \in k[U,V]$. $Y=\mathbb{P}^1_k$, and $X=V_+(P)$.
Then $X \rightarrow Y$ is a closed immersion of $k$-schemes and $O_Y(Y)=k$.
Now, let $p \in X$, then $p$ is a prime homogeneous ideal of $k[U,V]$ containing $P$ and not containing $\{U,V\}$. Assume $Y \in p$. Then $a_dU^d \in p$ hence $U,V \in p$, a contradiction. So $X \subset D_+(U)$.
It follows that $X$ is the spectrum of $(k[U,V]_V)/(Pk[U,V]_V)=k[U]/P_1$ which is a field extension $K$ of $k$.
So $X \rightarrow Y$ induces $k \rightarrow K$ in global sections, not surjective.


text:
Q: Luxe - "Type not found : UserConfigDef" after updating I've just updated Haxe, Luxe, Hxcpp, etc. on Windows after not using them for a while, and now none of my projects will compile, not even the "empty" sample. I get the following in cmd:
C:\GAMEDEV\empty>haxelib run flow run
flow / 1.0.0-alpha.2 (node.js v0.12.7)
flow / target is windows ( arch 32 )
flow / haxe version 3.3.0

flow / build - empty 1.0.0 for windows
flow / build - running haxe ...
C:\HaxeToolkit\haxe\lib\snow\git\snow/types/Types.hx:72: characters 25-38 : Type
 not found : UserConfigDef

C:\GAMEDEV\empty>

Same error when building from Sublime package. Is it possible that I've broken something? Should I attempt to completely reinstall?

A: It seems that Luxe is not compatible with Haxe 3.3.0-rc1 yet - there is an open issue about it on GitHub. Try downgrading to Haxe 3.2.1.
You may also need to downgrade hxcpp to 3.2.205 if you run into any cpp compilation issues.


text:
Q: Unable to Get users Google username after passport.js authentication typescript What am trying to do?
Am trying to render the (users google user-name) when they have successfully logged into the application via passport.js
Lang: typescript-express
My auth.ts
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.serializeUser((req, user, done) => {
  done(undefined, user);
});

passport.deserializeUser(function(user, done) {
  done(null, user);
});

passport.use(new GoogleStrategy({
    clientID: "GOOGLECLIENT",
    clientSecret: "GOOGLE SECRET",
    callbackURL: "http://localhost:3000/api/google/account"
  },
  function(accessToken, refreshToken, profile, done) {
    console.log('ID: '+profile.id);
    console.log('Name: '+profile.displayName);
    console.log('Email : '+profile.emails[0].value);
    return done(null,profile);
   }

));

My app.ts
...

app.get('/profile' ,isLoggedIn, (req: Request, res: Response)=> {
  res.send(`welcome`)
  console.log(req.user.displayName)

})

...

middleware.ts
const isLoggedIn = (req, res, next) => {
  if (req.user) {
    next();
  } else {
      res.status(401).send('Not Logged In');
    }
  }
  module.exports = isLoggedIn

when I try console.log(req.user)
I do get the response that looks like this
{
  id: '117536576311430346303',
  displayName: 'udhay r',
  name: { familyName: 'r', givenName: 'udhay' },
  emails: [ { value: 'udhay1co.de@gmail.com', verified: true } ],
  photos: [
    {
      value: 'https://lh3.googleusercontent.com/a-/AOh14GgrJVpuweBFcvme1whJG9bha1SO838PYgnKYC66Kw=s96-c'
    }
  ],
  provider: 'google',
  _raw: '{\n' +
    '  "sub": "117536576311430346303",\n' +
    '  "name": "udhay r",\n' +
    '  "given_name": "udhay",\n' +
    '  "family_name": "r",\n' +
    '  "picture": "https://lh3.googleusercontent.com/a-/AOh14GgrJVpuweBFcvme1whJG9bha1SO838PYgnKYC66Kw\\u003ds96-c",\n' +
    '  "email": "udhay1co.de@gmail.com",\n' +
    '  "email_verified": true,\n' +
    '  "locale": "en-GB"\n' +
    '}',
  _json: {
    sub: '117536576311430346303',
    name: 'udhay r',
    given_name: 'udhay',
    family_name: 'r',
    picture: 'https://lh3.googleusercontent.com/a-/AOh14GgrJVpuweBFcvme1whJG9bha1SO838PYgnKYC66Kw=s96-c',
    email: 'udhay1co.de@gmail.com',
    email_verified: true,
    locale: 'en-GB'
  }
}

when I try req.user.displayName i get the following err
    return new TSError(diagnosticText, diagnosticCodes);
           ^
TSError: ⨯ Unable to compile TypeScript:
app.ts:76:15 - error TS2532: Object is possibly 'undefined'.

76   console.log(req.user.displayName)
                 ~~~~~~~~
app.ts:76:24 - error TS2339: Property 'displayName' does not exist on type 'User'.

76   console.log(req.user.displayName)
                          ~~~~~~~~~~~

My package.json file
{
  "name": "Devgram",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "ts-node app.ts"
  },
  "keywords": [],
  "author": "Udhay-r",
  "license": "ISC",
  "dependencies": {
    "@types/cookie-session": "^2.0.43",
    "@types/express": "^4.17.13",
    "@types/express-session": "^1.17.4",
    "@types/node": "^16.11.7",
    "@types/passport": "^1.0.7",
    "axios": "^0.24.0",
    "bcrypt": "^5.0.1",
    "cookie-session": "^1.4.0",
    "dotenv": "^10.0.0",
    "ejs": "^3.1.6",
    "express": "^4.17.1",
    "express-openid-connect": "^2.5.1",
    "express-session": "^1.17.2",
    "mssql": "^7.2.1",
    "mysql": "^2.18.1",
    "nodemon": "^2.0.14",
    "passport": "^0.5.0",
    "passport-google-oauth20": "^2.0.0",
    "ts-node": "^10.4.0",
    "typescript": "^4.4.4"
  }
}

Please help me out with this problem
thanks in advance


text:
Q: Immutable JS - converting a collection of Maps to a List I have the following structure in the project im working on (uses immutable JS):

data :[{name: 'john', surname: 'smith', children: [{name: 'sam'}, {name: 'ben'}]},
       {name: 'jane', surname: 'jones', children: [{name: 'tim'}, {name: 'amy'}]}]

the object is converted to immutable JS via fromJS().
I need a new object in the following structure:

data :[{name: 'john', surname: 'smith', children: ['sam','ben']},
       {name: 'jane', surname: 'jones', children: ['tim','amy']}]

Any pointers much appreciated.

A: Something like that should works

data.map(d => {d.name, d.surname, children: d.children.map(child => child.name)});

A: I would go with map and reduce:

const data = [{name: 'john', surname: 'smith', children: [{name: 'sam'}, {name: 'ben'}]},
       {name: 'jane', surname: 'jones', children: [{name: 'tim'}, {name: 'amy'}]}];

var result = data.map(person => {
  return { name: person.name,
           surname: person.surname,
           children: person.children.reduce((acc, c) => {acc.push(c.name); return acc;}, []) }});

  console.log(result)

A: The pure JS answer of Christian doesn't exactly apply to immutable.js objects, so here are a few ways to do it with immutable.js's collection API.
There are more options (e.g. reduce), feel free to check the docs; the method descriptions usually come with examples.

const raw = [{name: 'john', surname: 'smith', children: [{name: 'sam'}, {name: 'ben'}]},
       {name: 'jane', surname: 'jones', children: [{name: 'tim'}, {name: 'amy'}]}];

const data = Immutable.fromJS(raw);

function run(name, operation) {
  let result;
  console.time(name);
  for(let i=0; i < 50000; i++){
    result = operation();
  }
  console.timeEnd(name);
  console.log(result1.toJS());
}

run('simple', () => {
  // simply updating objects inside a mapping
  result1 = data.map(
    person => person.update('children',
      kidObjs => kidObjs.map(
        kid => kid.get('name')
      )
    )
  );
});

run('withMutations and setIn', () => {
  // using withMutations and setIn
  result2 = data.withMutations(list => {
    list.forEach((val, idx) => {
      list.setIn(
        [idx, 'children'],
        val.get('children').map(kid => kid.get('name'))
      )
    });
  });
});

run('withMutations and update', () => {
  // slightly faster by using withMutations set/update
  result2 = data.withMutations(list => {
    list.forEach((val, idx) => {
      list.set(idx, val.update('children', kids => kids.map(kid => kid.get('name'))))
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.14/immutable.min.js"></script>


text:
Q: How to re-enable right click so that I can inspect HTML elements in Chrome? I am looking at a web page which has overwritten the right-click button so to display its own popup HTML element.
This prevents me from using Chrome Developer Tools to inspect elements.
Does anybody know a JavaScript snippet I could inject from the Chrome Console
to re-enable the right-click?
I am okay to break the existing 'right-click' functionality, so to be able to inspect the HTML elements easily.

A: If they have just changed the oncontextmenu handler (which is the most straightforward way to do it), then you can remove their override thus:
window.oncontextmenu = null;

Otherwise, if it is attached to individual elements, you can get all the page's elements, and then remove the handler on each one:
var elements = document.getElementsByTagName("*");
for(var id = 0; id < elements.length; ++id) { elements[id].oncontextmenu = null; }

Or, it seems you can turn off such scripts; via an extension in Chrome or an option in Firefox - in the advanced box for javascript options, switch off 'Disable or replace context menus'.

A: Another possible way, when the blocking function is made with jquery, use:
$(document).unbind();

It will clear all the onmousedown and contextmenu events attributed dynamically, that can't be erased with document.contextmenu=null; etc.

A: You could use javascript:void(document.oncontextmenu=null);
open Browser console and run the code above. It will turn off blockin' of mouse right button

A: Tested in Chrome 60.0.3112.78.
Some of the above methods work, but the easiest in my opinion is:

*

*Open dev tools (Shift+Control+i).

*Select the "Elements" tab, and then the "Event Listeners" tab.

*Hover over the elements/listener. A "Remove" button will show up.

*Click "Remove".
E.g. see photo.

A: This bookmarlet works in Google sites/Youtube as of Aug 2019 (tested in Chrome and Firefox):
function enableContextMenu(aggressive = false) {
void(document.ondragstart=null);
void(document.onselectstart=null);
void(document.onclick=null);
void(document.onmousedown=null);
void(document.onmouseup=null);
void(document.body.oncontextmenu=null);
enableRightClickLight(document);
if (aggressive) {
  enableRightClick(document);
  removeContextMenuOnAll("body");
  removeContextMenuOnAll("img");
  removeContextMenuOnAll("td");
  } }

function removeContextMenuOnAll(tagName) {
var elements = document.getElementsByTagName(tagName);
  for (var i = 0; i < elements.length; i++) {
    enableRightClick(elements[i]);
  }
}

function enableRightClickLight(el) {
  el || (el = document);
  el.addEventListener("contextmenu", bringBackDefault, true);
}

function enableRightClick(el) {
  el || (el = document);
  el.addEventListener("contextmenu", bringBackDefault, true);
  el.addEventListener("dragstart", bringBackDefault, true);
  el.addEventListener("selectstart", bringBackDefault, true);
  el.addEventListener("click", bringBackDefault, true);
  el.addEventListener("mousedown", bringBackDefault, true);
  el.addEventListener("mouseup", bringBackDefault, true);
}

function restoreRightClick(el) {
  el || (el = document);
  el.removeEventListener("contextmenu", bringBackDefault, true);
  el.removeEventListener("dragstart", bringBackDefault, true);
  el.removeEventListener("selectstart", bringBackDefault, true);
  el.removeEventListener("click", bringBackDefault, true);
  el.removeEventListener("mousedown", bringBackDefault, true);
  el.removeEventListener("mouseup", bringBackDefault, true);
}
function bringBackDefault(event) {
  event.returnValue = true;
  (typeof event.stopPropagation === 'function') &&
  event.stopPropagation();
  (typeof event.cancelBubble === 'function') &&
  event.cancelBubble();
}

enableContextMenu();

For peskier sites, set/pass aggressive to true (this will disable most event handlers and hence disable interaction with the page):
function enableContextMenu(aggressive = true) {
  void(document.ondragstart=null);
  void(document.onselectstart=null);
  void(document.onclick=null);
  void(document.onmousedown=null);
  void(document.onmouseup=null);
  void(document.body.oncontextmenu=null);
  enableRightClickLight(document);
  if (aggressive) {
    enableRightClick(document);
    removeContextMenuOnAll("body");
    removeContextMenuOnAll("img");
    removeContextMenuOnAll("td");
  }
}

function removeContextMenuOnAll(tagName) {
 var elements = document.getElementsByTagName(tagName);
 for (var i = 0; i < elements.length; i++) { enableRightClick(elements[i]);
  }
}

function enableRightClickLight(el) {
  el || (el = document);
  el.addEventListener("contextmenu", bringBackDefault, true);
}

function enableRightClick(el) {
  el || (el = document);
  el.addEventListener("contextmenu", bringBackDefault, true);
  el.addEventListener("dragstart", bringBackDefault, true);
  el.addEventListener("selectstart", bringBackDefault, true);
  el.addEventListener("click", bringBackDefault, true);
  el.addEventListener("mousedown", bringBackDefault, true);
  el.addEventListener("mouseup", bringBackDefault, true);
}

function restoreRightClick(el) {
  el || (el = document);
  el.removeEventListener("contextmenu", bringBackDefault, true);
  el.removeEventListener("dragstart", bringBackDefault, true);
  el.removeEventListener("selectstart", bringBackDefault, true);
  el.removeEventListener("click", bringBackDefault, true);
  el.removeEventListener("mousedown", bringBackDefault, true);
  el.removeEventListener("mouseup", bringBackDefault, true);
}

function bringBackDefault(event) {
  event.returnValue = true;
  (typeof event.stopPropagation === 'function') &&
  event.stopPropagation();
  (typeof event.cancelBubble === 'function') &&
  event.cancelBubble();
}

enableContextMenu();

A: I built upon @Chema solution and added resetting pointer-events and user-select. If they are set to none for an image, right-clicking it does not invoke the context menu for the image with options to view or save it.
javascript:function enableContextMenu(aggressive = true) { void(document.ondragstart=null); void(document.onselectstart=null); void(document.onclick=null); void(document.onmousedown=null); void(document.onmouseup=null); void(document.body.oncontextmenu=null); enableRightClickLight(document); if (aggressive) { enableRightClick(document); removeContextMenuOnAll('body'); removeContextMenuOnAll('img'); removeContextMenuOnAll('td'); } } function removeContextMenuOnAll(tagName) { var elements = document.getElementsByTagName(tagName); for (var i = 0; i < elements.length; i++) { enableRightClick(elements[i]); enablePointerEvents(elements[i]); } } function enableRightClickLight(el) { el || (el = document); el.addEventListener('contextmenu', bringBackDefault, true); } function enableRightClick(el) { el || (el = document); el.addEventListener('contextmenu', bringBackDefault, true); el.addEventListener('dragstart', bringBackDefault, true); el.addEventListener('selectstart', bringBackDefault, true); el.addEventListener('click', bringBackDefault, true); el.addEventListener('mousedown', bringBackDefault, true); el.addEventListener('mouseup', bringBackDefault, true); } function restoreRightClick(el) { el || (el = document); el.removeEventListener('contextmenu', bringBackDefault, true); el.removeEventListener('dragstart', bringBackDefault, true); el.removeEventListener('selectstart', bringBackDefault, true); el.removeEventListener('click', bringBackDefault, true); el.removeEventListener('mousedown', bringBackDefault, true); el.removeEventListener('mouseup', bringBackDefault, true); } function bringBackDefault(event) { event.returnValue = true; (typeof event.stopPropagation === 'function') && event.stopPropagation(); (typeof event.cancelBubble === 'function') && event.cancelBubble(); } function enablePointerEvents(el) {  if (!el) return; el.style.pointerEvents='auto'; el.style.webkitTouchCallout='default'; el.style.webkitUserSelect='auto'; el.style.MozUserSelect='auto'; el.style.msUserSelect='auto'; el.style.userSelect='auto'; enablePointerEvents(el.parentElement); } enableContextMenu();

A: On the very left of the Chrome Developer Tools toolbar there is a button that lets you select an item to inspect regardless of context menu handlers. It looks like a square with arrow pointing to the center.

A: Easiest thing to do is open the dev tools by pressing Cmd + Opt + I (Mac) or F12 (PC). You can then use the search (magnifying glass, top left on the dev tools toolbar) to select the element.

A: Hi i have a shorter version. this does same as a best answer.
(it works on chrome 74.03)
document.querySelectorAll('*').forEach(e => e.oncontextmenu = null)

A: you can use following code for re-enable mouse right click.
document.oncontextmenu = function(){}

and you can use shortcut key (Ctrl+Shift+i) to open inspect elements in chrome in windows OS.

A: Not quite answering the question, but you can use ctrl/cmd + shift + c to start an "inspect on hover" mode in chrome.

A: Disabling the "SETTINGS > PRIVACY > don´t allow JavaScript" in Chrome will enable the right click function and allow the Firebug Console to work; but will also disable all the other JavaScript codes.
The right way to do this is to disable only the specific JavaScript; looking for any of the following lines of code:

*

*Function disableclick

*Function click … return false;

*body oncontextmenu="return false;"

A: I just visited this site and it really bugged me,
apparently there are a couple ways to disable the mouse click:
1)

and

...

in this case what you will have to do in the dev tools is :
document.removeEventListener("onmousedown",disableclick);
document.oncontextmenu = function(){}

2)
using flash as a content wrapper - no solution here except taking a screenshot
3)
some sites want to prevent downloading images via right click -> save image as
so what they do is put this:

which is a transparent image spreding on the full width and height of the screen all you need to do is go to the elements inspector and find the div and delete it.
In my case #1 did the trick

A: The way I solved this was delete the event listeners on the page. After I did that, I was able to copy the text and paste it in to my processor of choice.

A: If the page you are on has a text or textarea input, click into this input (as if you want to enter text) then right-click and select 'Inspect element'.

A: Open inspect mode before navigating to the page.
It worked.hehe

A: If none of the other comments works, just do, open console line command and type:
document.oncontextmenu = null;

A: Press Ctrl+Control+F12
Then select Elements > Event Listeners > Remove contextmenu events

A: Just Press F12
Go to Sources
There you will find Enable right click. Click on it.
Under this you will find web_accessible_resource.
Open it in this you will find index.js.
Press Ctrl + F and search for disabelRightClick. There you will find
        var disableRightClick = false;

this line. Replace this line with
        var disableRightClick = true;

Just press   Ctrl + s
!! Done. Now your right click is enabled !!

A: The easiest way I found is to open the webpage in Read mode (browser that supports read mode like Safari, Firefox etc) and then copy as usual


text:
Q: Why must I cast in Kotlin but not Java? Question: Why must I cast the type in Kotlin but not in Java?
I have a java method:
processAction(Observable<Action> actions)

I call it in test (Java):
when(myMock.processAction(any(Observable.class))).thenAnswer(...)

I call it in test (Kotlin):
when(myMock.processAction(any(Observable::class.java) as Observable<Action>).thenAnswer(...)

Repo Here

A: In Java, your expressions have the following types:

*

*Observable.class -> Class<Observable>

*any(Observable.class) -> Observable
Likewise in Kotlin:

*

*Observable::class.java -> Class<Observable<*>>

*any(Observable::class.java) -> Observable<*>
In Java, Observable is a raw type; you should expect your compiler/IDE to highlight a warning when you implicitly convert to Observable<Action>.  For backward-compatibility with a pre-generics world, this doesn't fail to compile.
Kotlin tries to be smarter about how it handles generics, plus the backward-compatibility thing doesn't apply.  So it forces you to be explicit about your intent here.

On a tangent, if you're using Mockito in Kotlin I highly recommend the Mockito-Kotlin bindings, as they make this substantially less verbose (it would just be any() in this case).