text:
Q: Unable to combine a nested layout with dynamic routing This is what I am trying to accomplish:

The main navigation is fine - I'm using a global layout component in _app.js , i.e.
const Layout = ({ Component, pageProps }: any) => {
  const getLayout = Component.getLayout || ((page: any) => page);

  return getLayout(<Component {...pageProps} />);
};

export default function App({ Component, pageProps }: AppProps) {
  return (
      <MainLayout>
        <Layout Component={Component} pageProps={pageProps} />
      </MainLayout>
  );
}

The issue I'm having is trying to work out how to implement the side navigation - the items here will come from an API response and therefore only one request should be made. As the items are dynamic then the page needs to make use of dynamic routing.
I'm really unsure how to structure this though - I presume I just need one page i.e. blah-3/[slug].tsx. It looks like I cannot make use of the layout pattern here as there doesn't seem to be a way to pass props data to the layout.
To be honest I'm really surprised something this straightforward and such a common use case is so difficult in Next.js and would really appreciate a bit of guidance.
I have checked out what seems to be the go to article for issues related to nested routes (https://adamwathan.me/2019/10/17/persistent-layout-patterns-in-nextjs/) but this doesn't cover the dynamic routing case.


text:
Q: juju ssh fails because of permission denied (public key) when I try doing a juju ssh into one of the machines, it returns an error
2012-12-06 14:16:16,695 INFO Connecting to environment...
2012-12-06 14:16:25,671 INFO Connected to environment.
2012-12-06 14:16:26,994 INFO Connecting to unit sqldb/0 at ec2-54-251-4-139.ap-southeast-1.compute.amazonaws.com

Permission denied (publickey).

I can still ssh into nodes I created a while back (2 months ago). I'm not sure what's happening. It seems juju is not copying over my public key to the new nodes I'm adding for some reason. Is it some sort of configuration issue?

A: Yes. I do have this.
On explicitly setting authorized key path to id_rsa.pub in the config file - it's working again. It was not picking the public id by default though.
Not sure why that was happening.

A: You first need to add your ssh key to the mode. You can do that using juju add-ssh-key.
The following command adds your public ssh key from the ~/.ssh/id_rsa.pub file. If that file doesn't exist, you need to generate an ssh keypair.
juju add-ssh-key "$(cat ~/.ssh/id_rsa.pub)"

You can also specify the public key manually:
juju add-ssh-key "ssh-rsa qYfS5LieM79HIOr535ret6xy
AAAAB3NzaC1yc2EAAAADAQA6fgBAAABAQCygc6Rc9XgHdhQqTJ
Wsoj+I3xGrOtk21xYtKijnhkGqItAHmrE5+VH6PY1rVIUXhpTg
pSkJsHLmhE29OhIpt6yr8vQSOChqYfS5LieM79HIOJEgJEzIqC
52rCYXLvr/BVkd6yr4IoM1vpb/n6u9o8v1a0VUGfc/J6tQAcPR
ExzjZUVsfjj8HdLtcFq4JLYC41miiJtHw4b3qYu7qm3vh4eCiK
1LqLncXnBCJfjj0pADXaL5OQ9dmD3aCbi8KFyOEs3UumPosgmh
VCAfjjHObWHwNQ/ZU2KrX1/lv/+lBChx2tJliqQpyYMiA3nrtS
jfqQgZfjVF5vz8LESQbGc6+vLcXZ9KQpuYDt joe@ubuntu"

After adding the key, you'll be able to ssh to any machine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Move item to top of listview when a new message arrives I am working on a XMPP based chat in android.. and I am struck at a point where I need to update the position of an item in the listview to the top in case a new.message arrives.
The use case is.. I am on Contacts screen of the app and a new message comes.. so this contact should move to top of the list and get bold. This is what is similar to whatsapp as well
How can this be done. My class imolemebts activity and i have implemented custom list adapter.
So howcan I find if an item exists in the listview and secondly how to dynamically change position

A: First, keep in mind that a ListView is just a representation of a list of Objects. So if you want to know if an item is in the ListView, you just have to check if the corresponding Object is in your list of Objects.
Is the same when you want to change the position of one item, you have to change the position of the Object in the list.
Start by defining these objects:
private ArrayList<MyObject> lists = new ArrayList<MyObject>();
private MyCustomAdapter myAdapter;

The first time you create your ListView, just do as usually:
//fill your list with your objects
lists.add(myObject1);
lists.add(myObject2);
lists.add(myObject3);
//create and set the adapter
myAdapter = new MyCustomAdapter(..., ..., lists);
myListView.setAdapter(myAdapter);

Now you can know if your lists contains a specific object (which is the same that checking if an item is in your ListView) by simply testing that:
lists.contains(anObject);

Then, if you want to change the position of a specific item in the ListView, you have to create a new list and put the elements in the correct order. You can use something like that (not tested but it should work):
private ArrayList<MyObject> moveItemToTop(ArrayList<MyObject> lists, int positionOfItem) {
    if (lists == null || positionOfItem < 0 || positionOfItem >= lists.size()) {
        return lists;
    }

    ArrayList<MyObject> sortedList = new ArrayList<MyObject>();
    //add the item to the top
    sortedList.add(lists.get(positionOfItem));

    for (int i=0; i<lists.size(); i++) {
        if (i != positionOfItem) {
            sortedList.add(lists.get(i));
        }
    }

    return sortedList;
}

Or even this (which is way easier...).
Finally, call these two methods to update your ListView:
myAdapter = new MyCustomAdapter(..., ..., moveItemToTop(lists, itemPosition));
myListView.setAdapter(myAdapter);

A: This is how I resolved it
private void moveMessageToTop(MessageObject message) {
        int index = 0;
        for (Friends friend : mFriends) {
            if (friend.getName().equalsIgnoreCase(message.getFrom().split("@")[0])) {
                index = mFriends.indexOf(friend);
                break;
            }
        }

        if (index != 0) {
            mFriends.add(0,new Friends(message.getFrom().split("@")[0], message
                    .getMessage()));
        } else {
            Friends frnd = mFriends.get(index);
            frnd.setStatus(message.getMessage());
            mFriends.add(0, frnd);
            mFriends.remove(index);
        }

        ((ListAdapter) lvFriends.getAdapter()).notifyDataSetChanged();
    }


text:
Q: Delete row from datatable based on condition In my DataGrid I used a ComboBox in the first column, so it will fetch some data from the database using the DisplayMember and ValueMember concepts. Now I want to remove the value from the ComboBox which is previously selected.
Populating the ComboBox code is given below:
   dTable = getDummyTable.GetDummyTble("Dummy", "DNO", "All");
   dCmbData = dTable;
   cmbDeno.DataSource = dTable;
   cmbDeno.DisplayMember = "dyName";
   cmbDeno.ValueMember = "dyRemarks";

The next row of selection there should not be a duplicate value in the ComboBox.
How can I achieve this?
Can anyone help me with this?

A: well try this one out. You have the DataTable which you are using to bind all combos (correct me if I'm wrong). Now all we need to do is that when an item is selected from any combo, we need to remove that item from all the other combos). You will need to declare a class level dictionary to store which combo had what value stored previously:
IDictionary<ComboBox, DataRow> _prevSelection;

//Please don't mind if syntax is wrong worked too long in web
comboBox.OnSelectedIndexChanged += fixItems;

private void fixItems(object sender, EventArgs e)
{
    var cbo= sender as ComboBox;
    if(cbo==null) return;

    var prev = _prevSelection[cbo];

    var row=<GET ROW FROM DATATABLE FOR CURRENT SELECTED VALUE>;

    _prevSelection[cbo] = row;

    UpdateOtherCombos(cbo, prev, cbo.SelectedItem.Value);
}

private void UpdateOtherCombos(ComboBox cbo, DataRow prev, object toRemove)
{
    foreach(var gridrow in <YourGrid>.Rows)
    {
        var c = <FIND COMBO IN ROW>;
        if(cbo.Id == c.Id) continue;//combo that triggered this all
        var itemToRemove=null;
        foreach(var item in c.Items)
        {
            if(item.Value == toRemove)
            {
                itemToRemove = item;
                break;
            }
        }

        //or you can get index of item and remove using index
        c.Items.Remove(itemToRemove);

        //Now add the item that was previously selected in this combo (that
        //triggered this all)
        c.Items.Add(new ComboBoxItem{Value = prev["ValueColumn"],
                                        Text = prev ["TextColumn"]});
    }
}

This is just to give you an idea that may help you to find an optimal solution rather than iterating over all combos as it will slow down if you have too many rows in grid or too many items in combos. Still even with this you need to put up some functions/code to make it working. Also please note that I have not worked on WinForms for some time and you need to check if things like ComboBoxItem etc. and any functions called on them exist. :)


text:
Q: calling libc.select from python from pty master side I'm trying to create a simulated TTY connected target device that I can connect to via i.e. minicom. I'm using /dev/ptmx to create a pty and print out the slave name to be opened by i.e. minicom:
Please connect to: /dev/pts/4. On the python side I then use os.read and os.write to do io and simulate my target:
import os, re, termios
from ctypes import *
class dev():
    def __init__(self):
        pass
    def createpty(self):

        self.fd3 = os.open("/dev/ptmx", os.O_RDWR | os.O_NONBLOCK);
        if self.fd3 < 0:
            print("Couldn't open output /dev/ptmx\n")
        libc = cdll.LoadLibrary("libc.so.6")
        libc.grantpt(self.fd3);
        libc.unlockpt(self.fd3);
        libc.ptsname.restype = c_char_p
        self.slave = libc.ptsname(self.fd3)
        print("Please connect to:" + self.slave);

        self.old = termios.tcgetattr(self.fd3)
        n = termios.tcgetattr(self.fd3)

        n[3] = n[3] & ~(termios.ECHO|termios.ICANON) # c_lflag
        n[3] = n[3] & 0
        n[4+1] = n[4+1] & 0xffff0000;

        termios.tcsetattr(self.fd3, termios.TCSANOW, n)

The whole process is quite combersome. I would like to use select on the python side which forces my to use ctypes again. I cannot wrap the self.fd3 into a file using os.fdopen because I need to prevent close being called on self.fd3.
So I have two questions:

*

*Does anyone know a readymade python library that handles pty creation and manipulation when implementing the pty master side in python?

*If not: Is there a example somewhere that describes howto call libc.select via ctypes?

A: As @CristiFati stated Python's select can be used for FDs, however for the sake of completeness below is my dirty hack for using ctype's select. This implements an tty echo server. Connect to the pty slave that is printed out, i.e. minicom -D /dev/pty/4
import os, re, termios
import threading, os, re, sys, select, math, binascii, errno, time
from ctypes import *
import errno

class pty():
    def __init__(self, n="undef"):
        self.cmds = {}
        self.createpty()
        self.name = n
        self.goon = 1
        self.input = ""
        self.output = []

    def createpty(self):

        self.fd3 = os.open("/dev/ptmx", os.O_RDWR | os.O_NONBLOCK);
        if self.fd3 < 0:
            print("Couldn't open output /dev/ptmx\n")
        libc = cdll.LoadLibrary(None)
        libc.grantpt(self.fd3);
    libc.unlockpt(self.fd3);
        libc.ptsname.restype = c_char_p
        self.slave = libc.ptsname(self.fd3)
        print("Use: " + self.slave);

        self.old = termios.tcgetattr(self.fd3)
        n = termios.tcgetattr(self.fd3)

        n[3] = n[3] & ~(termios.ECHO|termios.ICANON) # c_lflag
        n[3] = n[3] & 0

#define VTIME 5
#define VMIN 6
#struct termios
#  {
#    tcflag_t c_iflag;      /* input mode flags */
#    tcflag_t c_oflag;      /* output mode flags */
#    tcflag_t c_cflag;      /* control mode flags */
#    tcflag_t c_lflag;      /* local mode flags */
#    cc_t c_line;           /* line discipline */
#    cc_t c_cc[NCCS];       /* control characters */
#    speed_t c_ispeed;      /* input speed */
#    speed_t c_ospeed;      /* output speed */
##define _HAVE_STRUCT_TERMIOS_C_ISPEED 1
##define _HAVE_STRUCT_TERMIOS_C_OSPEED 1
#  };

        n[4+1] = n[4+1] & 0xffff0000;
    #ioc.c_cc[VMIN] = 0;  # byte 6 + 7
    #ioc.c_cc[VTIME] = 0;

        termios.tcsetattr(self.fd3, termios.TCSANOW, n)

        #self.io = os.fdopen(self.fd3, "r+");

#       fd3io = fdopen (fd3, "r+");
#       fflush (fd3io);
#       setbuf (fd3io, NULL);
#     }

#typedef long int __fd_mask;
#define __NFDBITS   (8 * (int) sizeof (__fd_mask))
#define __FD_ELT(d) ((d) / __NFDBITS)
#define __FD_MASK(d)    ((__fd_mask) (1UL << ((d) % __NFDBITS)))

__FD_SETSIZE=1024

def fdmask():
    l = __FD_SETSIZE/64
    r = (c_ulong*l)()
    for i in range(l):
        r[i] = 0;
    return r

def fdset(a,b):
    a[b>>6] = a[b>>6] | (1 << (b % 64))

def fdisset(a,b):
    return (a[b>>6] & (1 << (b % 64)))

def setset(b, a):
    for i in a:
        fdset(b, i)

def setget(b, a):
    return [ i for i in a if fdisset(b,i) ]

class timeval(Structure):
    _fields_ = [("tv_sec", c_long), ("tv_usec", c_long)]

def cselect(r,w,x,timeout):

    libc = cdll.LoadLibrary(None)

    ra = fdmask();
    wa = fdmask();
    xa = fdmask();
    m = max(r+w+x)
    setset(ra, r),
    setset(wa, w),
    setset(xa, x),
    tv = timeval()
    tv.tv_sec = int(timeout)
    tv.tv_usec = int(1000000.0 * (timeout%1.0))
    ret = libc.select(m+1, ra, wa, xa, pointer(tv));
    if (ret < 0):
        print ("Error %d" %(ret));
    elif (ret == 0):
        return ([],[],[])
    else:
        return (setget(ra,r),setget(wa,w),setget(xa,x))

def main():
    if sizeof(c_ulong) != 8:
        raise("64bit os expected with long int = 64bit")
    a = pty();
    while True:
        try:
            (r,w,x) = cselect([a.fd3],[],[a.fd3],1)
            if (len(x) > 0):
                time.sleep(0.1);
                print("x");
                continue
            if (len(r) > 0):
                # implement an echo-server:
                v = os.read(a.fd3, 1)
                print (".");
                os.write(a.fd3,v)
        except pty as e:
            print (str(e));
            raise(e)

if __name__ == "__main__":
    main()


text:
Q: laravel post from view does not call controller method I am trying to send a post request from my view but somehow this request is not passing to my controller method while other controller methods are working..
my routes:
Route::get('/executes', 'ExecuteController@index')->name('execute.index');
Route::post('/executes', 'ExecuteController@store')->name('execute.store');
Route::get('/executes/create', 'ExecuteController@create')->name('execute.create');

my view:
@extends('layouts.app')

@section('content')

Create Execute

                <form method="post" action="/executes" enctype="multipart/form-data" class="pt-4">
                    @csrf

                        <input type="text" class="form-control" id="name" name="name" placeholder="Name">
                        @error('name')

                            {{ $message }}

                        @enderror

                            Map

                        <select class="custom-select" id="map" name="map">
                            <option selected>Choose...</option>
                            @foreach($maps as $map)
                                <option value="{{ $map->id }}">{{ $map->name }}</option>
                            @endforeach
                        </select>
                        @error('map')

                            {{ $message }}

                        @enderror

                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>

@endsection

my controller:
class ExecuteController extends Controller
{

  public function create()
    {
        return view('execute/create', ['maps' => Map::all()]);
    }

   public function store()
    {
        // is not even getting here
        dd('test');
    }

}

any ideas why my method is not getting called?

A: Could you try to change this
FROM
action="/executes"

TO
action="{{route('/executes')}}"

OR
action="{{url('/executes')}}"

Hope it helps

A: You're using named routes, so refer to their names when building a URL instead.
Example:
action={{url('execute.store')}}

A: Please use {{ url('ROUTE_NAME')}} in action or where you want to give link

A: guys thank you for your replies but the problem was on the frontend, I had a js included outside the html tag in my layout, somehow that messed up my store method, by fixing that it now works

A: Use route in the form action as following
action="{{route('execute.store')}}"


text:
Q: MySQL chain replication timing of writes on first slave With a MySQL chain replication setup, e.g. M1->S1->S2, what exactly is the order of operations for writing to the first slave?  Is the binary log from the master simply streamed directly through to the second slave?  Or are database updates to the first slave committed before replicating those updates to the second slave?
The documentation for --log-slave-updates states This option causes the slave to write the updates performed by its SQL thread to its own binary log.  It's not clear to me if this is done in parallel or only after data is written.  I'm only interested in row-based replication, if that matters.
I ask because I have the unusual situation of a custom application acting as a second slave and operating on events that come through the binary log.  It runs queries on the first slave.  If the log events were to get to the application before writes on the first slave are committed, it will be operating on stale data.

A: To answer this, you need to understand the way MySQL replication works and the difference between the IO_thread and the SQL_thread.
In a nutshell, the IO_thread pulls events from the master and stores in the relay_log. The SQL_thread pulls from the relay_log and applies them to the slave dataset.
So, the description of --log-slave-updates (emphasis mine):

This option causes the slave to write the updates performed by its SQL thread to its own binary log

means that the MySQL is only logging to the first slave's binary log after it is being committed on that slave. And it won't be available to the second slave until it has been committed on the first slave.
So if I'm understanding you right, you should be safe in your us-ecase.

Single-threaded sql thread and slave lag
It is important to note that by default, the SQL thread is single-threaded. This means even though your master can apply changes across multiple connections very quickly, when it is applied to the first slave it is one change at a time. This can contribute to slave lag.
Luckily, in MySQL 5.6 the ability to have multiple slave thread appliers was introduced with the --slave-parallel-workers option.
However, this only helped if you had multiple schemas(databases), because MySQL would only apply in parallel if statements were in different schemas.
This limitation was removed in 5.7 to allow for parallel application within the same schema.
The main point I am trying to make, is that if you are dealing with slave lag on the first slave, the second slave will take similar time (assuming similar hardware) so will be even further behind your master. So ensure your custom application takes that into account.

A: S1 is both a Slave (to M1) and a Master (to S2).  That is, M1 and S2 have no knowledge of each other.

*

*A client writes to M1.

*M1 writes to its binlog and simultaneously sends data to S1.

*S1 writes to its "relay log" using its "I/O thread".

*S1's "SQL thread" eventually (usually quickly) reads the relay log and acts mostly like it was a write from some client -- apply the write, and write to its (S1's) binlog.

*(like step 2) S1 -> S2

*(like step 3) S2

*(like step 4) S2

"Runs queries on S1" -- Does that include writes?  If so, you are violating the principle that Replication keeps two servers in sync.  (Granted, it is possible to safely do write to a Slave, but you need to understand how things work.)


text:
Q: Is there a SQL function statement which returns an array within limits and replaces digits with * to reduce the size Need to write a sql function that takes two different integers with the same length (same amount of digits) as arguments: one lower threshold and one upper threshold.
And the function should return a vector with all whole numbers between the two thresholds - but to reduce the array length, your function is supposed to return a wildcard character instead of the digits where possible.
Example: output of the function for a lower threshold L = 3778 and an upper threshold U = 9423
To further clarify, the line in the example showing 941* has one digit replaced by the wild card character and hence represents all values from 9410 - 9419
The line in the example showing 93* has two digits replaced by the wildcard character and represents all values from 9300 - 9399
And so on.
9423
9422
9421
9420
941*
93*
.
378*
3779
3778


text:
Q: How to calculate the mean and standard deviation of similarity matrix? I am working with CSV files and I have a code that calculates the similarity between the documents. Post 1 provide the code and details of data and output is as follow:
The data.csv looks as:
idx         messages
112  I have a car and it is blue
114  I have a bike and it is red
115  I don't have any car
117  I don't have any bike

The output is:
    id     112    114    115    117
    id
    112  100.0   78.0   51.0   50.0
    114   78.0  100.0   47.0   54.0
    115   51.0   47.0  100.0   83.0
    117   50.0   54.0   83.0  100.0

Now I would like to calculate the mean and standard deviation of the lower triangular of the similarity matrix (since both upper and lower are similar) without the identity data (100.0).
I tried to use the panda built-in mean and std as:
df_std = df.std()
df_Mean = df.mean()

But this considers all the data in the output like identity and upper triangular.
I would like to know if there is any way that I can calculate the mean and standard deviation the way that I mentioned.

A: Use numpy.tril with k=-1 and make 0s np.nan:
import numpy as np

ltri = np.tril(df.values, -1)
ltri = ltri[np.nonzero(ltri)]

Output:
array([[ 0.,  0.,  0.,  0.],
       [78.,  0.,  0.,  0.],
       [51., 47.,  0.,  0.],
       [50., 54., 83.,  0.]])

And now you can do ltri.std(), ltri.mean():
ltri.std(), ltri.mean()
# (14.361406616345072, 60.5)

A: You can do it with mask all of the unwanted value as np.nan
df.values[np.triu_indices_from(df.values,0)]=np.nan
df.mean()
112    59.666667
114    50.500000
115    83.000000
117          NaN
dtype: float64
df.std()
112    15.885003
114     4.949747
115          NaN
117          NaN
dtype: float64

After mask the value
df
      112   114   115  117
112   NaN   NaN   NaN  NaN
114  78.0   NaN   NaN  NaN
115  51.0  47.0   NaN  NaN
117  50.0  54.0  83.0  NaN


text:
Q: Java - assertEquals & assertTrue - Test failed with exception [null] in JUnit but passes in test class I have both a standard test class with a main method and a JUnit class which I am using to base my tests while writing a contact directory via Test Driven Development. I need to make use of methods such as assertEquals & assertTrue. As I have never used them before, I wrote a simple test in my standard test class and they return True when expected and throw an exception when expected.
I then moved into my JUnit test class, write the same test that passed in the standard test class and run the JUnit test class. The test fails with the following error:
Test[Method Name] failed with exception [null]

The exact code I used is along these lines:
assertEquals("NameImExpectingToFind",obj.searchMethod("nameImSearchingFor").get(0).getName());

I've been stuck on this problem for hours. Just makes no sense that it will pass in a standard test class but not in a JUnit test class.
Thanks in advance for any help!
Test class:
    AddressBook main = new AddressBook();
    Entry Will = new Entry("Will", "Blah",
            "Blah, blah, blah", "TF4 3HS", "077774451",
            "01/02/93");
    Entry Ben = new Entry("Ben", "Blah",
            "Blah, blah, blah", "TF4 3HS", "077774451",
            "01/02/93");
    main.addEntry(Will);
    main.addEntry(Ben);
    //assertEquals("Ben",main.cSearchFirst("Ben").get(0).getfName());
    System.out.println("Ben" == main.cSearchFirst("Ben").get(0).getfName());

Returns True.
JUnit Test class:
    AddressBook main = new AddressBook();
    Entry Will = new Entry("Will", "Blah",
            "Blah, blah, blah", "TF4 3HS", "077774451",
            "01/02/93");
    Entry Ben = new Entry("Ben", "Blah",
            "Blah, blah, blah", "TF4 3HS", "077774451",
            "01/02/93");
    main.addEntry(Will);
    main.addEntry(Ben);
    assertEquals("Ben",main.cSearchFirst("Ben").get(0).getfName());
    //System.out.println("Ben" == main.cSearchFirst("Ben").get(0).getfName());

Returns Test[Method Name] failed with exception [null].

A: Looks like you got a null pointer, before your test do
 List<Entry> entries = main.cSearchFirst("Ben");//check for null here, and size
 Entry e = entries.get(0); //again check null here, examine properties in debugger
 String s = e.getfName();

Slap a debugger on there and walk through seeing where null is being thrown.
edit: I'd also recommend doing a checks for nulls around there if you are expecting null, else try/catch null exceptions and fail the test.


text:
Q: Group by multiple values For example, I have a list of students with their semesters and subjects.
Subject   Semester   Attendee
---------------------------------
ITB001    1          John
ITB001    1          Bob
ITB001    1          Mickey
ITB001    2          Jenny
ITB001    2          James
MKB114    1          John
MKB114    1          Erica

When I need to group them by one value with Stream api, I can make something like that;
Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.getSubject()));

and it does work. However, when I want to group them by two or more values (like the Sql handles), I cannot figure out how I need to do.

A: One approach is to group by a class that holds all the fields you want to group by. This class must implement hashCode and equals using all these fields in order to work as expected.
In your example this would be:
public class SubjectAndSemester {

    private final String subject;

    private final int semester; // an enum sounds better

    public SubjectAndSemester(String subject, int semester) {
        this.subject = subject;
        this.semester = semester;
    }

    // TODO getters and setters, hashCode and equals using both fields
}

Then, you should create this method in your Student class:
public SubjectAndSemester bySubjectAndSemester() {
    return new SubjectAndSemester(subject, semester);
}

Now, you can group as follows:
Map<SubjectAndSemester, List<Student>> studlistGrouped = studlist.stream()
    .collect(Collectors.groupingBy(Student::bySubjectAndSemester));

This creates a one level grouping of students.

There's another option that doesn't require you to use a Tuple or to create a new class to group by. I mean you can have an n-level grouping of students, by using downstream groupingBy collectors:
Map<String, Map<Integer, List<Student>>> studlistGrouped = studlist.stream()
    .collect(Collectors.groupingBy(Student::getSubject,
        Collectors.groupingBy(Student::getSemester)));

This creates a 2-level grouping, so the returned structure is now a map of maps of lists. If you can live with this, even for grouping of more levels, then you can avoid creating a class that acts as the key of the map.

A: You could create a calculated field that is combination of the two columns
Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.getSubject() + "-" w.getAttendee()));

EDIT:
Another more "appropriate" solution: Accoridng to this blog post , you need to define a Tuple class that can hold the two columns:
class Tuple {
    String subject;
    String attendee;
}
Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> new Tuple(w.getSubject(), w.getAttendee())));


text:
Q: Connect Visio document to Access database I want to add an Access database to my Visio document. The MSN example shows the string to connect to an Excel document. What would I use to connect to an Access DB?
I am Using:

Microsoft Visio 2013
  Microsoft Access 2013
  Microsoft Windows 7 Enterprise.

DB location:

C:\Users\j.Smith\Desktop\access_file.mdb

My script:
Public Sub AddDataRecordset_Example()

    Dim strConnection As String
    Dim strCommand As String
    Dim strOfficePath As String
    Dim vsoDataRecordset As Visio.DataRecordset

    strOfficePath = Visio.Application.Path
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
                   & "User ID=Admin;" _
                   & "Data Source=" + strOfficePath + "SAMPLES\1033\ORGDATA.XLS;" _
                   & "Mode=Read;" _
                   & "Extended Properties=""HDR=YES;IMEX=1;MaxScanRows=0;Excel 12.0;"";" _
                   & "Jet OLEDB:Engine Type=34;"

    strCommand = "SELECT * FROM [Sheet1$]"

    Set vsoDataRecordset = ActiveDocument.DataRecordsets.Add(strConnection, strCommand, 0, "Org Data")

End Sub

A: This should do it:
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "User ID=Admin;" & _
    "Data Source=" & accessFileName & ";" & _
    "Mode=Read;" & _
    "Extended Properties="""";" & _
    "Jet OLEDB:System database="""";" & _
    "Jet OLEDB:Engine Type=6;" & _
    "Jet OLEDB:Database Locking Mode=0;"
strCommand = "SELECT * FROM `tablename`"

Note the single quotes around table name.
Also, fyi, I have always found the following website very useful : ConnectionStrings


text:
Q: why doesn't my field get initialized to the value I gave it I have following classes:
public abstract class AClass {

    public AClass() {
        aMethod();
    }

    abstract protected void aMethod();

}

public class SubClass extends AClass {

    private int x = 5;
    private static final int y = 6;

    @Override
    protected void aMethod() {
        System.out.println("x: " + x + " | y: " + y);
    }

}

public class Main {

    public static void main(String[] args) {
        new SubClass();
    }

}

Running Main prints the following: x: 0 | y: 6
Why does 0 get printed for x?

A: The static field is initialized as soon as the class is initialized (after loading). Now when you call
new SubClass() the following things happen.

*

*Constructor of SubClass is called as the first statement of SubClass (implicitly)

*Constructor of SuperClass is called. --> you are checking value of x here

*Once SuperClass constructor's execution completes, then instance level fields of SubClass are initialized. So x will be initialized here.

A: Initialization order. aMethod() is called before the line private int x = 5
Playing round with code examples like this is a great way to learn the order in which things are executed. Try adding a static and non-static initialization block too.

A: The result is because the super class constructor is called before the members are initialized.
In your case the following sequence is executed:

*

*Call to constructor SubClass

*immediate call to constructor AClass

*call of method aMethod()

*initializing of members of SubClass
This is also the reason why you should not call any overrideable methods from a constructor as the called method may access the state of an object that is not fully initialized.

A: The reason of the misbehaviour is a wrong initialization sequence:

*

*new SubClass() executes AClass constructor

*AClass constructor calls aMethod()

*aMethod() shows x (which is 0 so far) and y which is 6 because of being static)

*SubClass initialize its non-static fields, so x becomes 5.

To avoid surprizes, never call virtual methods (esp. overriden) in constructors

A: private static final int y = 6;

Value of y is 6 when the constructor calls aMethod(), because it is static and is initialized while class loading.
private int x = 5;

While this initialization is appended at the end of your constructor body. It means while aMethod is being executed, the variable x has still default value i.e 0.
Default constructor of SubClass would look like
SubClass() {
    super();
    //All instance initialization are performed here.
}

A: Because when you created an instance of the Subclass it invokes the constructor of its super class AClass, and at this point, x was not yet set that's why it gets the default value of 0.


text:
Q: How to tell the compiler my friend function is function template Here is my code:
#include <iostream>
#include <cstddef>

class alloc
{

};

template <class T, class Alloc = alloc, size_t BufSiz = 0>
class deque
{
public:
    deque() { std::cout << "deque" << std::endl; }
};

template <class T, class Sequence = deque<T> >
class stack
{
public:
    stack() { std::cout << "stack" << std::endl; }
private:
    Sequence c;
    friend bool operator== <> (const stack<T, Sequence>&, const stack<T, Sequence> &);
    friend bool operator< <> (const stack<T, Sequence>&, const stack<T, Sequence>&);
};

template <class T, class Sequence>
bool operator== (const stack<T, Sequence>&x, const stack<T, Sequence>&y)
{
    return std::cout << "opertor == " << std::endl;
}

template <class T, class Sequence>
bool operator < (const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
    return std::cout << "operator <" << std::endl;
}

int main()
{
    stack<int> x; // deque stack
    stack<int> y; // deque stack

    std::cout << (x == y) << std::endl; // operator == 1
    std::cout << (x < y) << std::endl; // operator < 1
}

I just thought a simple <> notation tell the compiler my function is function template. But I get error with two line:friends can only be classes or functions
friend bool operator== <> (const stack<T, Sequence>&, const stack<T, Sequence> &);
friend bool operator< <> (const stack<T, Sequence>&, const stack<T, Sequence>&);

How can I do to solve it.

A: Just use this syntax:
template<typename T1, typename Sequence1>
friend bool operator== (const stack<T1, Sequence1>&, const stack<T1, Sequence> &);

template<typename T1, typename Sequence1>
friend bool operator< (const stack<T1, Sequence1>&, const stack<T1, Sequence>&);

You nees the first template parameter to be different that T and the second to be different than Sequence, or you will be shadowing the class' template parameters.


text:
Q: Football manager like drag&drop interface I am creating a soccer management system in PHP and Javascript (jquery) to organize teams and matches. I am now develping the match part and I would like to show to the user a drag&drop based interface to place players on the soccer field. I could write the code by myself but that would require a big effort and I'm sure that someone has already thought about this and may suggest some implementation I could use. Anyone has a solution for this?
Thanks in advance!

A: It's not an implementation because that's difficult without all the requirements, but you might find this pretty usefull: JqueryUI-Draggable

A: You can use free and popular JavaScript library (called also framework): jQuery. To create Drag&Drop use jQuery UI and it's Draggable form, which can help you a lot. (There are examples included.)


text:
Q: Find the linear maps that preserve this bilinear form. This time I want to know which linear maps are the ones that preserve the following bilinear form:
$$\beta(x,y)=2(x_1y_1-x_2y_2)$$
and they give as a hint the matrix:
$$\begin{pmatrix}
cosh&sinh\\-sinh&cosh
\end{pmatrix}$$
then when I multiply this matrix by the one generated by the bilinear form, this is:
$$\begin{pmatrix}
2&0\\0&-2
\end{pmatrix}\begin{pmatrix}
cosh&sinh\\-sinh&cosh
\end{pmatrix}$$
Then I get a matrix that has the same shape as the one of the bilinear form, but I think this is not preservation, so Can someone help me with this problem please? (I have tried to compute the determinants but I think this has nothing to do with the bilinear form)
Thanks a ot in advance :).

A: Under the linear transformation $x\to Ax$ we have
$$x = \left(\matrix{x_1\\x_2}\right) \to \left(\matrix{A_{11}x_1 + A_{12}x_2\\A_{21}x_1 + A_{22}x_2}\right)$$
so the bi-linear form transforms as
$$x_1y_1-x_2y_2 \to (A_{11}x_1 + A_{12}x_2)(A_{11}y_1 + A_{12}y_2) - (A_{21}x_1 + A_{22}x_2)(A_{21}y_1 + A_{22}y_2)$$
From this we see that the form is preserved iff
$$\matrix{A_{11}^2-A_{21}^2 &= 1\\A_{22}^2-A_{12}^2 &= 1\\A_{11}A_{12}-A_{21}A_{22} &= 0}$$
Since $A_{11}^2,A_{22}^2\geq 1$ we can take $A_{11}=\epsilon_{11}\cosh\alpha$ and $A_{22} = \epsilon_{22}\cosh\beta$ for some $\alpha,\beta\in\mathbb{R}$ and where $\epsilon_{ij}=\pm 1$. The identity $\cosh^2(x) - \sinh^2(x) = 1$ applied to the first two equations determines $A_{12}$ and $A_{21}$ (up to a sign) and the final equation fixes $\alpha=\pm\beta$ and gives a relation between the allowed combinations of signs $\epsilon_{ij}$.

Any solution $A$ can be written on one of the four following forms:
$$\left\{\pm\left(\matrix{+c & +s\\ +s & +c}\right),~~~\pm\left(\matrix{+c & +s\\ -s & -c}\right)\right\}$$
where $s=\sinh(\alpha)$ and $c=\cosh(\alpha)$ for some $\alpha\in\mathbb{R}$.


text:
Q: 'MyClass' object has no attribute 'type' , problem loading libraries inside a class not sure how whould I embebed external libraries inside a class, to make it self-independant, I opted for:
from urllib.request import urlopen

class MyClass:

    from urllib.request import urlopen as LOCALurlopen

    LOC_baseUrl = 'https://www.someurl.com/api/'

    def resolve_API(self, myValue):

       LOC_fullRequest = self.LOC_baseUrl + '/' + myValue
       print(Loc_fullRequest)

       LOC_response = urlopen(LOC_fullRequest, timeout = 5).read()  ## works, but external dependecy

       LOC_response = self.LOCALurlopen(LOC_fullRequest, timeout = 5).read()  ## doesn't work

       print(LOC_response)

I made the same with other libs and works ok, but not url open, it give me the error:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

<ipython-input-99-425bb23495d5> in <module>()
---> 13 printINFO(MyClass.resolve_API('anyValue'))

<ipython-input-98-dee69a279550> in resolve_API(self, myValue)
---> 55         LOC_response = self.LOCALurlopen(LOC_fullRequest, timeout = 5).read()

/usr/lib/python3.7/urllib/request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    220     else:
    221         opener = _opener
--> 222     return opener.open(url, data, timeout)
    223
    224 def install_opener(opener):

/usr/lib/python3.7/urllib/request.py in open(self, fullurl, data, timeout)
    515
    516         req.timeout = timeout
--> 517         protocol = req.type
    518
    519         # pre-process request

AttributeError: 'MyClass' object has no attribute 'type'

how should I resolve this dependency ?


text:
Q: VB.Net dll referenced in C# project I have a previously created project written in VB.Net. I have a website that is written in C# referencing the VB project. The VB project is a class that accesses the database. It compiles and runs fine on my local machine. When I put it on the server, I get the following error

Cannot load type 'DLLOM.clsDB, DLLOM, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

This is the code it is failing on
DLLOM.clsDB objDB = (DLLOM.clsDB)Activator.GetObject(typeof(DLLOM.clsDB), ConfigurationManager.AppSettings["RemotingPathDB." + System.Environment.MachineName.ToUpper()]);
DataSet ds = objDB.MembershipsGet();

Any idea on why it is correctly referenced on my machine, but not on the server? The website is compiled on 3.5 framework, while the VB class is 2.0. I tried switching them to no avail.

A:
Cannot load type 'DLLOM.clsDB, DLLOM, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

It is a TypeLoadException.  That's the boring part, it doesn't get interesting until you start looking at the InnerException.  Which tells you what really happened to stop the type from getting loaded.
If this is all you got out of your program then you need to improve your exception reporting.  Be sure to use the exception's ToString() method instead of the Message property.  You'll get everything, including the inner exceptions.  If you get it in the debugger then be sure to use the Exception Assistant.


text:
Q: Is Arraylist is typesafe or strongly typed? I don't know what exactly the difference between "Strongly typed" and "Type safety" is!
Could you please clarify this in a simple language?
Suppose we are using Arraylist, but I am unable to conclude it is typesafe or strongly typed. or can we use it as both.?

A: An ArrayList is not typesafe. What this means is that ArrayList can be assigned a value of any type:
ArrayList myList = new ArrayList();
myList.Add("this is a string");
myList.Add(19); //Notice that this is an int, but it doesn't throw an error!

This is an issue because when you go to use the list, you don't know the types that are in the list. The chances of having an error thrown are very high.
Avoid using ArrayLists! Use a generic list instead, such as List<T>

A: Type-safe and strongly-typed are loaded phrases, such that it's hard to get programmers everywhere to pin down a precise definition. But there is at least enough consensus to state that ArrayLists are neither in every way that matters.
Do not use ArrayLists! Instead, use the generic List<T> collection.

A: The ArrayList data structure is a not type-safe, nor strongly-typed. You cannot guarantee what type of object is in an ArrayList, thus everything is stored as an Object, similar to how objects are stored in Session cache for ASP.NET.
The biggest downside to using ArrayList was the casting that needed to happen whenever you wanted to get access to the objects in the actual list. If any of the values in the list were not of the type you were expecting, then you would potentially get casting exceptions and the code to deal with that was just ugly.
Use generics wherever possible, with List<T> being the closest generic type to the ArrayList data structure.

A: I'm not sure I understand your question.
"Strong/weak typed" is a quality of programming languages. Java is strongly typed, which means it has a strict syntax, and it can find problems in your code at compile time, before errors make it to run time.
Java may not exactly be type safe, though (I'm not sure of the exact answer). It allows generics, which means you can make an ArrayList of Strings (ArrayList<String>), ArrayList of Integers (ArrayList<Integer>), ArrayList of Booleans (ArrayList<Boolean>). ArrayList<T> means you can substitute <T> with any object. ArrayList<? extends T> means you can substitute with any A, B, C, Potato, etc. that extends T.
Say you have the following classes:
class Admin extends User {
    //Stuff
}
class Student extends User {
    //Stuff
}
class Teacher extends User {
    //Stuff
}

You can even have an ArrayList of any child of a User object, for example: ArrayList<User>.
To this list, you can add Student, Admin, and Teacher objects.
But if you do not specify what type of data this ArrayList holds (eg: List l = new ArrayList();), you can place any Object in it, causing it to not be type safe.
An example of generics abuse can be seen on Wikipedia.


text:
Q: How to test `contenteditable` events with React Testing Library I am trying to write tests for one of our rich text components which was implemented with slate js editor in react js. So when writing tests, I am retrieveing the element div[contenteditable='true'], but not able to simulate events like change, blur, focus. The handlers attached to editor component are not getting called. I tried multiple combinations, but no luck. Can someone please help on this? Is it possible to simulate events for contenteditable element using testing library (contenteditable is implemented using slatejs)?

A: Like you've discovered, contenteditable isn't supported by JSDOM. React Testing Library (RTL) is built on top of JSDOM, so it's not possible to test the Slate editor properly with RTL until JSDOM implements support for contenteditable.
Use a browser automation library together with Testing Library
Your options are then to use a tool that creates a real browser context. Testing Library have integrations with many tools that do exactly that: TestCafe, Cypress, Nightwatch, Puppeteer.
You can also use the above tools on their own, without Testing Library.
I've solved this using Puppeteer, and there are two approaches:

*

*Run a local server and tell Puppeteer to go to something like localhost:3000

*Set the content directly with page.setContent(htmlString)
(1) is the most common, and you'll find many guides for this since it's a common approach for end-to-end testing (google search).
(2) is a little trickier because you will have to transform and bundle your source for each test, and then inject it as HTML into the browser page. I prefer this approach because the testing experience is much more similar to using RTL. I've created a repository with an example of this setup with the Slate editor here: https://github.com/marcusstenbeck/puppeteer-react-testing-template/


text:
Q: HTML markup manipulation in PHP Working with PHP DOM - html manipulation. It's really very effective way to output HTML markup (at least, prevents mess of logic and markup in code).
But, to generate 50 line of html markup, one must write about 200 lines in PHP :( .
Example piece of code:
...
$signup_form = $document->createElement('form');
$signup_form->setAttribute('id', 'signup_form');
$signup_form->setAttribute('action', 'registration/signup.php');
$signup_form->setAttribute('method', 'post');
$su_fname_label = $document->createElement('label');
$su_fname_label->setAttribute('for', 'fname');
$su_fname_label_content = $document->createTextNode('Name');
$su_fname_label->appendChild($su_fname_label_content);
$su_fname_textbox = $document->createElement('input');
$su_fname_textbox->setAttribute('name', 'fname');
$su_fname_textbox->setAttribute('class', 'valid');
$su_fname_textbox->setAttribute('placeholder', 'Please enter your name');
$su_fname_textbox->setAttribute('type', 'text');

...
As you see, It's only 1 element of form. Imagine, If there are 5 elements in HTML form, php code will be huge. I wonder, is there any way to minify for ex. by setting multiple attributes at once? Any suggestions?

A: Why don't you just output HTML and enabled output buffering. Then you can filter out the output using the tidy extension and be sure that your output HTML is valid, while still going as fast as writing pure HTML.
Despite the above, as @Gordon suggests:

tidy is hardly suitable for programmatically authoring (x)html. its more like a post processor.

A: What is your reason for using the DOM to generate html output? There's no way to make the DOM terse!
Usually you just use PHP for templating. Create a separate file like so:
<?php // template.php
echo '<!DOCTYPE html>',"\n";
?>

    <meta charset="utf-8">
    <title><?=htmlspecialchars($title, ENT_NOQUOTES, 'utf-8')?></title>

       <form id="signup_form" action="registration/signup.php" method="post">
           Name
           <input id="fname" name="fname" class="valid" placeholder="Please enter your name" type="text">
       </form>

Then using a template function:
function render($__filename, $__data) {
    extract($__data, EXTR_SKIP);
    ob_start();
    include $__filename;
    return ob_get_clean();
}

Render your template from your code like so:
do_something();
$templatedata = array('title'=>'The Title');
$html = render('template.php', $templatedata);

If you want something that is node-aware (which is a great idea for ensuring well-formedness and proper escaping!), you can use XSLT or a third-party template engine like PHPTAL.

A: I used to do what you're doing until I realized that it's not very readable. You have to analyze the code to determine what markup is being built. It's also harder to maintain. As you said, adding a single field to a form requires quite a bit of code and making changes requires digging through all that code. I agree with wanting to keep your PHP logic separate from your markup; however, there are better ways to keep your code clean depending on what you're trying to do.
Without getting into third-party solutions you could:

*

*Load markup from a separate file into a DOM object for further manipulation.

*Use PHP as the template engine it was designed to be by embedding PHP in your markup. As Col. Shrapnel explains quite eloquently: "[E]mbedded PHP lets you separate business logic from presentation logic on a site-wide basis, supporting templates of any size and structure…".

*Assign markup to a variable using heredoc syntax. While not the best choice, it's much easier to read than a purely DOM-based approach.
$signup_form = <<<EndHTMLForm
<form id="signup_form" action="registration/signup.php" method="post">
    Name
    <input name="fname" class="valid" placeholder="Please enter your name" type="text">
</form>
EndHTMLForm;

My purpose here isn't to steer you away from third-party solutions, but to illustrate alternative approaches in plain-vanilla PHP. The DOM is verbose. It certainly has wonderful advantages, but creating markup from scratch isn't one of them.

A: Depending on your need for speed and if you're able to use caching and the like, a library such as phpQuery could be of use.
It's a "port" of kind of jQuery to PHP and has the same versatility and simplicity as jQuery. However, in my experience, it's not quite as fast as I should like in generating the code (I have not, however, conducted any thorough tests, it's just a feeling).
The code you've given as an example could be expressed along these lines with phpQuery (untested):
$form = pq ('<form />')
          ->attr (array (
                    'id' => 'signup_form',
                    'action' => 'registration/signup.php',
                    'method' => 'POST',
                  ));
$label = pq ('')
          ->html ('Name')
          ->attr ('for', 'fname')
          ->appendTo ($form);
$text = pq ('<input />')
          ->attr (array (
                    'name' => 'fname',
                    'data-placeholder' => 'Please enter your name',
                    'type' => 'text',
                  ))
          ->addClass ('valid')
          ->appendTo ($label);

I've written it with the formatting I prefer, and it's slightly more lines than in the code you've supplied; but it could easily be reduced to 5-10 or so lines with maintained readability, if you prefer more compact coding. At any rate, I find it quite a lot easier to read and you don't have to write quite so much DOM code in order to generate quite a lot of HTML code.
Also, given that phpQuery uses the same wrapping concept as jQuery, an unwrapped node, for instance $form in the above code, is a regular DOMNode unless wrapped in pq(). This gives you a lot of flexibility to either use phpQuery's convenience routines, or the more "fundamental" functionality of PHP DOM.


text:
Q: ConcurrentModificationException - Memcached set & get from multithreading I am getting java.util.ConcurrentModificationException when I am using Memcached for setting & getting value from multiple thread concurrently.
Exception stack trace :
java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:894)
    at java.util.HashMap$EntryIterator.next(HashMap.java:934)
    at java.util.HashMap$EntryIterator.next(HashMap.java:932)
    at java.util.HashMap.writeObject(HashMap.java:1098)
    at sun.reflect.GeneratedMethodAccessor26.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:975)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1480)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
    at com.danga.MemCached.MemCachedClient.set(MemCachedClient.java:763)
    at com.danga.MemCached.MemCachedClient.set(MemCachedClient.java:542)
    at com.cacheengine.MemcachedThreadUtil.addToMemCache(MemcachedThreadUtil.java:129)
    at com.cacheengine.MemcachedThreadUtil.memcacheDataProcessing(MemcachedThreadUtil.java:59)

Sample Program :
MemcacheUtil :
public class MemcachedThreadUtil {

    /**
     * synchronized method
     */

    public synchronized void memcacheDataProcessing(String key, TermBean objUpdateTermBean) {
        System.out.println(Thread.currentThread().getName() + " Start");

        Object retrivedValue = retrieveFromMemCache(key);
        HashMap<String, TermBean> hmData = (HashMap<String, TermBean>) retrivedValue;

        hmData.put(key, objUpdateTermBean); // Data update

        addToMemCache(key, hmData);

        System.out.println(Thread.currentThread().getName() + " End");
    }

    private Object retrieveFromMemCache(String key) {
        // MemCachedManager.getMcc().get(sKey);
    }

    private void addToMemCache(String key, HashMap<String, TermBean> hmData) {
        // MemCachedManager.getMcc().set(sKey, obj);
    }
}

Runnable Thread :
    public class SendNForgotMemcacheHelperRunnable implements Runnable {
    private String key;
    private TermBean objTermBean;
    private MemcachedThreadUtil memcacheThreadUtil;

    public SendNForgotMemcacheHelperRunnable(String key, TermBean data, MemcachedThreadUtil memcacheThreadUtil) {
        this.key = key;
        this.objTermBean = data;
        this.memcacheThreadUtil = memcacheThreadUtil;
    }

    @Override
    public void run() {

        try {

            this.memcacheThreadUtil.memcacheDataProcessing(this.key, this.objTermBean);

        } catch (Exception iex) {
            System.out.println("Exception in thread: " + iex.getMessage());
        }
    }
}

Main method :
public static void main(String[] args) {
    MemcachedThreadUtil memcachedThreadUtil = new MemcachedThreadUtil();

    for (int threadCount = 0; threadCount < 10; threadCount++) {
        String key = ..//Get key
        TermBean objTermBean = ..// get value
        SendNForgotMemcacheHelperRunnable runnable = new SendNForgotMemcacheHelperRunnable(key, objTermBean, memcachedThreadUtil);
        Thread t = new Thread(runnable, "Thread"+threadCount);
        t.start();
    }
}

Memcached version is - 1.4.17 { https://danga.com/ or http://memcached.org)
It seems that there is some issue inside the Memcached library where concurrency thing not handled or it might be simply HashMap iterator issue.
Could you please advise whether multithreading is creating this exception or it general issue with HashMap.
Note : I thought that synchronized method is creating problem so I changed concurrent threading implementation using ReentrantReadWriteLock concept but facing same issue.
How to solve this issue - any suggestion please.
Edit : Added MemCachedManager code
public class MemCachedManager {

protected static MemCachedClient mcc = null;

static {
    init();
}

public static void init() {

    String[] servers = new String[Integer.parseInt(LocaleUtil.loadPropertyFile("MEMCACHED_SERVERS_COUNT", "cacheconfig"))];
    StringTokenizer stServers = new StringTokenizer(LocaleUtil.loadPropertyFile("MEMCACHED_SERVERS_COMMA_SEPERATED", "cacheconfig"), ",");
    int iServersCnt = 0;
    while (null != stServers && stServers.hasMoreTokens()) {
        servers[iServersCnt] = stServers.nextToken();
        iServersCnt++;
    }

    Integer[] weights = new Integer[Integer.parseInt(LocaleUtil.loadPropertyFile("MEMCACHED_SERVERS_COUNT", "cacheconfig"))];
    StringTokenizer stWeightage = new StringTokenizer(LocaleUtil.loadPropertyFile("MEMCACHED_SERVERS_MEMORY_COMMA_SEPERATED", "cacheconfig"), ",");
    int iServersWeightageCnt = 0;
    while (null != stWeightage && stWeightage.hasMoreTokens()) {
        weights[iServersWeightageCnt] = Integer.valueOf(stWeightage.nextToken());
        iServersWeightageCnt++;
    }

    String sPoolName = LocaleUtil.loadPropertyFile("MEMCACHED_POOL_NAME", "cacheconfig");
    SockIOPool pool = SockIOPool.getInstance(sPoolName);

    pool.setServers(servers);
    pool.setWeights(weights);

    pool.setInitConn(Integer.parseInt(LocaleUtil.loadPropertyFile("POOL_INIT_CONN", "cacheconfig")));
    pool.setMinConn(Integer.parseInt(LocaleUtil.loadPropertyFile("POOL_MIN_CONN", "cacheconfig")));
    pool.setMaxConn(Integer.parseInt(LocaleUtil.loadPropertyFile("POOL_MAX_CONN", "cacheconfig")));
    pool.setMaxIdle(Integer.parseInt(LocaleUtil.loadPropertyFile("POOL_MAX_IDLE", "cacheconfig"))); // 1000 * 60 * 60 * 6  == 6 hrs

    pool.setMaintSleep(Integer.parseInt(LocaleUtil.loadPropertyFile("POOL_MAINTAIN_THREAD_SLEEP", "cacheconfig")));

    pool.setNagle(Boolean.parseBoolean(LocaleUtil.loadPropertyFile("POOL_NAGLE_ENABLE_FLAG", "cacheconfig")));
    pool.setSocketTO(Integer.parseInt(LocaleUtil.loadPropertyFile("POOL_SOCKET_READ_TIMEOUT", "cacheconfig")));
    pool.setSocketConnectTO(Integer.parseInt(LocaleUtil.loadPropertyFile("POOL_SOCKET_CONNECT_TIMEOUT", "cacheconfig")));
    pool.setFailover(Boolean.parseBoolean(LocaleUtil.loadPropertyFile("POOL_FAILOVER_ENABLE_FLAG", "cacheconfig")));
    pool.setAliveCheck(Boolean.parseBoolean(LocaleUtil.loadPropertyFile("POOL_ALIVE_CHECK_ENABLE_FLAG", "cacheconfig")));

    // initialize the connection pool
    pool.initialize();

    mcc = new MemCachedClient(sPoolName);
    mcc.setCompressEnable(Boolean.parseBoolean(LocaleUtil.loadPropertyFile("MEMCACHED_COMPRESSION_ENABLE_FLAG", "cacheconfig")));
    mcc.setCompressThreshold(Integer.parseInt(LocaleUtil.loadPropertyFile("MEMCACHED_COMPRESSION_THRESHOLD_SIZE", "cacheconfig")));  //64 * 1024  == 64 kb

    int iLogLevel = com.danga.MemCached.Logger.LEVEL_WARN;
    if (GenTools.isNumber(LocaleUtil.loadPropertyFile("MEMCACHED_LOG_LEVEL", "cacheconfig"))) {
        iLogLevel = Integer.parseInt(LocaleUtil.loadPropertyFile("MEMCACHED_LOG_LEVEL", "cacheconfig"));
    }
    setLogLevel(iLogLevel);
}

public static MemCachedClient getMcc() {
    return mcc;
}

public static void setMcc(MemCachedClient mcc) {
    MemCachedManager.mcc = mcc;
}

public static void setLogLevel(int iLogLevel) {
    com.danga.MemCached.Logger.getLogger(MemCachedClient.class.getName()).setLevel(iLogLevel);
}

public static long getNormalCounter(String sTabName) {
    return getMcc().incr(sTabName);
}

public static String getPrefixCounter(String sTabName) {
    return sTabName.concat(String.valueOf(getMcc().incr(sTabName)));
}

public static void main(String[] args) {
}

}

A: Well, I'm not sure but try to make memcacheDataProcessing method static synchronized to get a class level lock.


text:
Q: How to display your own kanban card in calendar view in Odoo 11? I am trying to customise the calendar view of the calendar.event model, whose code is:
<record id="view_calendar_event_calendar" model="ir.ui.view">
    <field name="name">calendar.event.calendar</field>
    <field name="model">calendar.event</field>
    <field name="priority" eval="2"/>
    <field name="arch" type="xml">
        <calendar string="Meetings" date_start="start" date_stop="stop" date_delay="duration" all_day="allday"
            display="[name]" color="color_partner_id" attendee="partner_ids" avatar_model="res.partner"
            use_contacts="True" event_open_popup="%(calendar.view_calendar_event_form_popup)s">
            <field name="name"/>
            <field name="user_id"/>
            <field name="color_partner_id"/>
            <field name="partner_ids"/>
        </calendar>
    </field>
</record>

I want to show some new fields and make the background color depend on a new field named color_confirmed. The perfect way would be to replace the kanban shown in the calendar view by a customised one. The Odoo documentation (https://www.odoo.com/documentation/11.0/reference/views.html#calendar) says the following:

templates
defines the QWeb template calendar-box. Cards definition may be split into multiple templates for clarity which will be rendered once for each record.
The kanban view uses mostly-standard javascript qweb and provides the following context variables:
...

I am trying to use that templates attribute, but I have no idea how, and I was not able to find an example in all the available modules I have downloaded. One of my attempts:
<record id="view_calendar_event_calendar" model="ir.ui.view">
    <field name="name">calendar.event.calendar</field>
    <field name="model">calendar.event</field>
    <field name="inherit_id" ref="calendar.view_calendar_event_calendar"/>
    <field name="arch" type="xml">
        <xpath expr="//calendar[1]" position="replace">
            <calendar string="Meetings" date_start="start" date_stop="stop" date_delay="duration"
                all_day="allday" display="[color_confirmed]" color="color_confirmed" attendee="partner_ids"
                avatar_model="res.partner" use_contacts="False" event_open_popup="%(calendar.view_calendar_event_form_popup)s" mode="month">
                <field name="name"/>
                <templates>
                    <t t-name="calendar-box">

                                <field name="name"/>

TEST ITEM 1

TEST ITEM 2

                    </t>
                </templates>
            </calendar>
        </xpath>
    </field>
</record>

As expected, it throws a JS error. I have tried several ways and I am wasting a lot of time in such a single task. Does anyone have an idea of how this works? (or a better way to achieve my purpose).

A: the js error should be because of the avatar_model, use_contacts, and  attendee in the calendar definition. because the calendar is not accepting those values.
if you remove those fields and add your code will work well. here I have rendered your calendar-box template

Let me know if I am missing anything.


text:
Q: Change inline color on mouseover (React) How can I make this to change only the element that has mouseovered and not by ids? Following is my code component that changes the text color randomly from an array when mouseover.
class Chroma extends React.Component {
constructor(props) {
super(props)
}
mouse = event => {
var colorhex = [
'#7AF377', '#3498DB', '#F1C530', '#F29C29', '#8E44AD', '#4AA086', '#E74C3C', '#65CC71','#D3541B','#EB4367','#74F7D9', '#DDA8FC',
]
var el = document.getElementById('colorstext')
el.style.color = colorhex[Math.floor(Math.random() * 12)]
}
mouseout = event => {
var white = '#FFFFFF'
var el = document.getElementById('colorstext')
el.style.color = white
}

render() {
return (

<a
href={this.props.link}
onMouseEnter={this.mouse}
onMouseLeave={this.mouseout}
id="colorstext"
>
{this.props.text}
</a>
)
}
}
export default Chroma

A: event.target is the simplest way to get this done.
But I notice that you didn't bind your mouse actions, you need to bind the mouse and mouseout like this:
onMouseEnter={(event) => mouse(event)}
Here is the working example:
https://codesandbox.io/s/n5jvrkxxwp

A: Try using the info following in the event object:
const mouse = event => {
   const el = event.target // instead of getElementById('colorstext')
   .... your code
 }


text:
Q: importing a .txt file into a .dat cplex opl In an optimization problem I need to open my data for the problem in the .dat file. The problem is that the data is in a text file (notebook) and I don't know how I should connect it and work with a lot of instances. Could someone help me? I am searching for it, but I cannot find something that explains clearly.

A: *

*Open your file in notepad

*Go to Save As

*Type yourfilename.dat (without space). You should put .dat extension manually

*Save

A: You can read from a text file in cplex like:
execute //you should write this code in an execute block
{
   var fileID= new IloOplInputFile("fileName.txt");
   var contenct = fileID.readline();
   var intContenct = Opl.intValue(contenct); //in case you want to convert what you read into an integer value
   fileID.clos();
}


text:
Q: cascading drop downs in angular I am trying to get some cascading drop downs in angular that populate based off of what the previous drop down has selected. So basically there are 5 drop downs total, at first only the first drop down would be populated, and then the second one would populate based off of what is picked in the first (hopefully using $http to get the new info back form server base don what is picked) and so on all the way down to 5.
So basically I have this :
<select class="selectScope" ng-model="scope1">
                        <option ng-repeat="obj in array" value="{{obj.id}}">{{obj.name}}</option>
                    </select>
                    <select class="selectLevel1" ng-model="scope2">
                        <option ng-repeat="obj in array" value="{{obj.id}}">{{obj.name}}</option>
                    </select>
                    <select class="selectLevel2" ng-model="scope3">
                        <option ng-repeat="obj in array" value="{{obj.id}}">{{obj.name}}</option>
                    </select>
                    <select class="selectLevel3" ng-model="scope4">
                        <option ng-repeat="obj in array" value="{{obj.id}}">{{obj.name}}</option>
                    </select>
                    <select class="selectLevel4" ng-model="scope5">
                        <option ng-repeat="obj in array" value="{{obj.id}}">{{obj.name}}</option>
                    </select>

I will have populate the first dropdown with an $http, but without going into detail I am just wondering if I can have the dropdowns trigger off each other. If i have selected all the way down to level 5 and I re-select level 3 - then 4 and 5 would empty (4 would re populate based on what was picked in 3). SO I just want them to work off each other. I am wondering if something like this is possible in angular. Apologies if this is a bit oblivious, I am brand new to using angular. Thanks!!

A: Firstly, you should be using ng-options instead of an ng-repeat
<select ng-model='scope1' ng-change='scope1Change()'
        ng-options='obj.id as obj.name for obj in array'>
</select>

Then, on the ng-change event of the select, you can load the appropriate data for the following selects.
$scope.scope1Change = function() {
          //Build URL based on selection
          $http.get(myUrl).then(function(data){
          //transform data if required
           $scope.array2 = data;
    });
}

You can keep the other select statements disabled based on previous values being selected
<select class="selectLevel1" ng-model="scope2"
        ng-options='obj.id as obj.name for obj in array2' ng-disabled='!scope1'>
</select>

You would need some additional logic in the change events to work out whether or not you should clear the $scope model values as required, but that is pretty straightforward


text:
Q: Issue aligning elements at center Im trying to align my elements at center but I´m having some problems in this process. I aligned the "Title"  at center and it works, and now I´m doing the same process to other elements but its not working.
Anyone there can see what is wrong? Thank you!
My jsfiddle with the problem:
http://jsfiddle.net/mibb/6SLa5/
My Html:

Title

         Date of Post

Post of 1 read more

My css:
#loop-news-container{width:100%; height:auto; float:left;}
#loop-news{width:280px; height:250px; background:#fff; margin:5px auto 5px auto;}
#loop-news h1 {font-family:'bariol_boldbold';   text-align:center; font-family:'bariol_boldbold';margin:0 auto 0 auto; background:#F00;position:relative; text-decoration:none;}
#loop-news h1 a{text-decoration:none; font-size:20px; color:#002e5e; font-weight:100; }
#loop-news span{font-family:'bariolthin';font-size:14px; font-weight:normal;color:#888;margin:0 auto 0 auto; text-align:center; background-color:#FF0; }

A: The text of the
 can be centered with text-align:center because it takes the whole width of its container (it's a block-level element). The , not so much, as it only takes the width of its content (it's an inline element) - your coloured background make this quite visible. In fact, basically every child element you have there (other than the
) is an inline or inline-block element, so applying text-align:center to them directly won't work.
If you wanted to center all the elements in #loop-news, just adding this style would do it:
#loop-news {
    text-align:center;
}

This causes all inline content of #loop-news to be centered. Note that this also renders text-align:center on the
 unnecessary.
Here's a JSFiddle to show you what this does. If this isn't what you wanted though, let me know and I'll be happy to help further.


text:
Q: How to call function on button click? I have a Processing class, called Button, which has the following function onClick:
class Button() {
    // Extra code
    void onClick() {
        // Run function here
    }
}

which is supposed to trigger a function call when the button is clicked, and the function is taken in from an argument, like so:
Button test = new Button(..., callFunction())

Where callFunction() is guaranteed to be a void function. How do I call the function callFunction() once test is clicked on? I can check if the button is clicked, but I have no idea how to wire that to a function call provided by an argument.

A: Use Runnable.
Button test = new Button(..., new Runnable(){

     public void run() {
         // your stuff.
         callFunction();
     }
});

Then:
class Button() {

    private Runnable runnable;

    public Button (... Runnable runnable ){
       this.runnable  = runnable;
    }

    // Extra code
    void onClick() {
        runnable.start();
    }
}

A: I am not sure of this serves your purpose. But an external handler can be handy.
class Button {
    // Extra code
    private ClickHandler handler;

    //Constructor
    Button(..., ClickHandler handler) {
        this.handler = handler;
    }
    void onClick() {
    // Run function here
        handler.handle();
    }
}

interface ClickHandler {
    void handle();
}

Now you can create your object like:
Button test = new Button(..., new ClickHandler() {
    public void handle() {
        //do your stuff.
    }
});

Note: Probably Java 8 supports callback function references through lambdas.

A: Have a look at the Processing Button example.
It's not encapsulated into a class, that is up to you to implement,
but it does illustrate how to handle events using Processing's built-in draw() and mousePressed() methods.
If it helps, here's a button class I use in some of my sketches:
int numButtons = 3;
Button[] buttons = new Button[numButtons];

void setup(){
  size(180,200);

  int buttonWidth = 150;
  int buttonHeight = 50;
  int buttonSpacing = 15;

  for(int i = 0 ; i < numButtons; i++){
    buttons[i] = new Button("button "+(i+1),buttonSpacing,(buttonHeight+buttonSpacing) * i,buttonWidth,buttonHeight);
  }
}
void draw(){
  background(255);

  for(int i = 0 ; i < numButtons; i++){
    buttons[i].update(mouseX, mouseY, mousePressed);
    buttons[i].draw();
  }
}
//hacky way callback the main sketch from a button - look into callbacks
void onButtonClicked(Button b){
  println(b.label,"was pressed at",new java.util.Date());
}

class Button{
  float w,h,x,y;//width, height and position
  color bg = color(200);//background colour
  color fg = color(0);//foreground colour
  String label;//button label

  boolean isOver,wasPressed;
  int pw = 10;
  Button(String label,float x,float y,float w,float h){
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.label = label;
  }
  //mouseY,mouseY,mouseDown
  void update(int mx,int my,boolean md){
    //it's over if it's within the button's bounding box
    isOver = ((mx >= x && mx <= (x+w))&&(my >= y && my <= (y+h)));
    //if it's over and pressed it's a click
    if(isOver && md){
      //if it wasn't pressed before, trigger click callback
      if(!wasPressed){
        onButtonClicked(this);
        wasPressed = true;
      }
    }else wasPressed = false;
  }

  void draw(){
    pushStyle();
      noStroke();
      fill(isOver ? fg : bg);
      rect(x,y,w,h);
      fill(isOver ? bg : fg);
      text(label,x+pw,y+h*.75);
    popStyle();
  }
}

You may be required to implement it differently, but hopefully this will give you some ideas.
Update
If feels like the callback is the main thing you're after.
If that's the case, one option is to use Java Reflection to invoke a Method.
Here's a modified version of the above Button class that takes a class that contains the callback method and the name of the callback method as arguments:
import java.lang.reflect.*;

int numButtons = 3;
Button[] buttons = new Button[numButtons];

void setup(){
  size(180,200);

  int buttonWidth = 150;
  int buttonHeight = 50;
  int buttonSpacing = 15;

  for(int i = 0 ; i < numButtons; i++){
    buttons[i] = new Button(this,"onButton"+(i+1)+"Clicked","button "+(i+1),buttonSpacing,(buttonHeight+buttonSpacing) * i,buttonWidth,buttonHeight);
  }
}
void draw(){
  background(255);

  for(int i = 0 ; i < numButtons; i++){
    buttons[i].update(mouseX, mouseY, mousePressed);
    buttons[i].draw();
  }
}
public void onButton1Clicked(){
  println("button 1 clicked");
}
public void onButton2Clicked(){
  println("button 2 clicked");
}
public void onButton3Clicked(){
  println("button 3 clicked");
}

class Button{
  float w,h,x,y;//width, height and position
  color bg = color(200);//background colour
  color fg = color(0);//foreground colour
  String label;//button label

  boolean isOver,wasPressed;
  int pw = 10;

  Object parent;
  Method callback;

  Button(Object parent,String callbackName,String label,float x,float y,float w,float h){

    this.parent = parent;
    try{
      callback = parent.getClass().getMethod(callbackName);
    }catch(Exception e){
      e.printStackTrace();
    }

    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.label = label;
  }
  //mouseY,mouseY,mouseDown
  void update(int mx,int my,boolean md){
    //it's over if it's within the button's bounding box
    isOver = ((mx >= x && mx <= (x+w))&&(my >= y && my <= (y+h)));
    //if it's over and pressed it's a click
    if(isOver && md){
      //if it wasn't pressed before, trigger click callback
      if(!wasPressed){
        //onButtonClicked(this);
        if(callback != null){
           try{
            callback.invoke(parent);
          }catch(Exception e){
            e.printStackTrace();
          }
        }
        wasPressed = true;
      }
    }else wasPressed = false;
  }

  void draw(){
    pushStyle();
      noStroke();
      fill(isOver ? fg : bg);
      rect(x,y,w,h);
      fill(isOver ? bg : fg);
      text(label,x+pw,y+h*.75);
    popStyle();
  }
}

That's one way to tackle it. Be sure to dig deeper into java reflection and the Method class if you need arguments for those callbacks.

A: I will assume that you are using Java 8. If you aren't, you should! As one of its main improvements over older versions is precisely working with functions as parameters.
To pass a function object (i.e. a lambda) as a parameter, you first need to define a functional interface to somehow "hold" the implementation of your function. A functional interface can be any interface with just one method, like this:
interface MyFunction {
    public void call();
}

Declare it wherever you want, even inside your Button class. Doesn't matter as long as Button can access it.
Then you just tell your Button constructor that the last argument is a function, store it as a private field, and call it later when the button is clicked:
class Button() {
    MyFunction buttonFunction;
    public Button(..., MyFunction myFunction) {
        // ... other initialization ...
        buttonFunction = myFunction;
    }
    // Extra code
    void onClick() {
        // Run function here
        buttonFunction.call();
    }
}

To pass your function as a parameter, do it like this:
Button test = new Button(..., () -> callFunction());

You don't need to create an anonymous MyFunction class, nor override anything. Java 8 figures all that out for you. It knows that the Button constructor expects a MyFunction parameter, and it knows that MyFunction only has one method, call() with no parameters; so when you provide a function body with no parameters, Java knows that it is the implementation for MyFunction#call().
In fact, you don't even need to define an interface: you can just replace MyFunction with Runnable and call() with run(), and everything will work as intended, because Runnable is also a functional interface:
class Button() {
    Runnable buttonFunction;
    public Button(..., Runnable myFunction) {
        // ... other initialization ...
        buttonFunction = myFunction;
    }
    // Extra code
    void onClick() {
        // Run function here
        buttonFunction.run();
    }
}

Button test = new Button(..., () -> callFunction());

But it's better to know the basics first!


text:
Q: Does WCF keep a cache of (generated) Datacontracts and how to clear it Does Windows Communication Foundation (WCF) keep a cache of (generated) Datacontracts and how to clear it? Why I expect this in my situation:
I have made a subclass "ChildClass" of a class "BaseClass". The "BaseClass" is part of Datacontract definition between a server-application and a UI-application.
Now I wanted to let the server send the "ChildClass" over the interface to the UI, but disguise it as a "BaseClass". I tried some different decorations for my "ChildClass" (inspired by examples here: WCF: Returning a derived object for a contract with base object (DataContractResolver)).
I always got an error when deserializing the object on the UI-side, but the error did reference some of my Decorations on the "ChildClass", so something was working.
Then I tried another approach: I just added the "ChildClass" to the DataContract of the interface by adding:
    [KnownType(typeof(ChildClass))]
This worked. (Note that the code is part of much larger code base that I did not write. It includes client specific definitions of the datacontracts and some code is generated).
However, it could then also happen that the client would send back this object and this resulted in an error:

{"The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter BaseClassUISpecificDefinition. The InnerException message was 'Element 'UINamespace:BaseClassUISpecificDefinition' contains data from a type that maps to the name 'http://schemas.datacontract.org/2004/07/ServerChildClassNamespace:ChildClass'. The deserializer has no knowledge of any type that maps to this name. Consider using a DataContractResolver if you are using DataContractSerializer or add the type corresponding to 'ChildClass' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to the serializer.'.  Please see InnerException for more details."}

Besides this error, using this approach where the client would return the ChildClass, could lead to other logical problems, because the server used unique identifiers in the ChildClass, which should not be returned by the client, so I wanted to revert back to my original solution.
But then no matter how much I rebuild, deleted bin/obj files, generated code, checked out older commits, I always got the same error when the client received an object:

{"The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter UINamespace:UIServiceContract. The InnerException message was 'Element 'UINamespace:UIServiceContract' contains data from a type that maps to the name 'http://schemas.datacontract.org/2004/07/ServerChildClassNamespace:ChildClass'. The deserializer has no knowledge of any type that maps to this name. Consider using a DataContractResolver if you are using DataContractSerializer or add the type corresponding to 'ChildClass' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to the serializer.'.  Please see InnerException for more details."}

Then to test my hypothesis that there is cache somewhere, I run the exact same code on a buildserver (which makes a clean build in a clean environment), and indeed I got a different error there.
I expect that this error occurs when the client tries to deserialize the object and it is:

The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlyinig network resource issue. Local socket timeout was '00:01:00'.

So is there caching/code generation somewhere? Where is it stored and how to clear it?

A: A great article that describes how to declare child-classes in WCF is this one:
https://www.c-sharpcorner.com/uploadfile/c1de77/data-contract-and-known-type-in-wcf/
The correct attributes for my classes had to be:
In BaseClass.cs:
namespace ServerBaseClassNamespace
{
    //
    // Summary:
    //     Coordinates system in all the Machine Control and Subsystem software.
    [DataContract]
    [KnownType(typeof(BaseClass))]
    public class BaseClass
    {
    }
}

In ChildClass.cs:
namespace ServerChildClassNamespace
{
    using ServerBaseClassNamespace;

    [System.Runtime.Serialization.KnownType(typeof(ChildClass))]
    [System.Runtime.Serialization.DataContract(Name = "BaseClass", Namespace = "ServerBaseClassNamespace")] /* We disguise ChildClass as an BaseClass.
    It is sent over the interfaces as an BaseClass. The interface contracts: [ServiceContract], must define [ServiceKnownType(typeof(ChildClass))] to use this.
    See: https://www.c-sharpcorner.com/uploadfile/c1de77/data-contract-and-known-type-in-wcf/
    for explanation. */
    public class ChildClass : BaseClass
    {
    }
}

In IExampleContract.cs:
namespace UiService
{
    using System;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using ServerChildClassNamespace;

    [ServiceContract(Namespace = "UiService",SessionMode = SessionMode.Required)]
    [ServiceKnownType(typeof(ChildClass))] // On the server side this is an ChildClass, but the client will receive it as a BaseClass.
    public interface IExampleContract
    {
        [OperationContract]
        BaseClass ExampleMethod(BaseClass ExampleArgument);
    }
}

In UIServiceImplementation.cs:
namespace UiService
{
    using System;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using ServerChildClassNamespace;

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    [ServiceKnownType(typeof(ChildClass))] // On the server side this is an ChildClass, but the client will receive it as a BaseClass.
    public sealed class UIServiceImplementation : IExampleContract
    {
    BaseClass ExampleMethod(BaseClass ExampleArgument);
    }
}


text:
Q: What do you think is happening to my QGIS Georeferencer I'm pretty new with QGis, but have used tools as Openlayers and Geoserver for some years now without never being asked to diplay a georeferenced raster image. Which gets me to use QGis in order to build a Geotiff from a simple scanned PNG or JPEG.
I've followed many tutorials, but I'm somehow still struggling to import any image file in my Georeferencer plugin window.
Here's what I get when I import a jpeg image:

It looks like a badly read jpeg. Any idea ?
Thanks for your help !
EDIT
I've tried with a PNG by converting the original jpeg with an image tool (like IrfanView) and the image is now diplayed.
It's better, but doesn't answer exactly why the jpegs aren't working ...


text:
Q: List of attributes for For Loop in cmd I am looking for a list of attributes and what they do in a for loop inside the command prompt.
Specifically I have a .bat file that copies a file from the root of the C:\ drive and pastes it inside all folders found in a pre-specified directory (i.e. C:\Users\John\Test Directory).
This is the command:
@echo off
for /D %%a in (C:\Users\John\Test Directory\*.*) do xcopy /y /d C:\test_file.txt "%%a\"

The .bat does exactly what I need it to do, but I do not understand what the "%%a" does in the command. I see similar commands that use %%g, %%f, etc, but nothing that defines why those were chosen or what they specifically do. Are those attributes arbitrary or do they have a defined function? I seemingly can't find any information on the attributes so any insight is appreciated!

A: Arbitrary.  You can use any letter, upper or lower, and even symbols.
for %%# in... do command %%#

would work just as well.  But when working with multiple tokens per iteration, it's better to use the alphabet.  Here's an example why:
for /f "usebackq tokens=1* delims==" %%I in ("textfile.txt") do (
    set "config[%%~I]=%%~J"
)

This is because %%I contains the text matched prior to the first equal sign, and %%J contains everything after the first equal sign.  This answer shows that example in context.
The answer to your question is hinted in the for command's documentation.  help for in the cmd console for full details.  Specifically:

Some examples might help:
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
would parse each line in myfile.txt, ignoring lines that begin with
    a semicolon, passing the 2nd and 3rd token from each line to the for
    body, with tokens delimited by commas and/or spaces.  Notice the for
    body statements reference %i to get the 2nd token, %j to get the
    3rd token, and %k to get all remaining tokens after the 3rd.

This page explains further:

FOR Parameters
The first parameter has to be defined using a single character, for example the letter G.
FOR %%G IN ...
In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a different value
If this clause results in a single value then %%G is set equal to that value and the command is performed.
If the clause results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J ...(implicit parameter definition)
If the parameter refers to a file, then enhanced variable reference can be used to extract the filename/path/date/size.
You can of course pick any letter of the alphabet other than %%G.
%%G is a good choice because it does not conflict with any of the pathname format letters (a, d, f, n, p, s, t, x) and provides the longest run of non-conflicting letters for use as implicit parameters.
  G > H > I > J > K > L > M
  Format letters are case sensitive, so using a capital letter is also a good way to avoid conflicts %%A rather than %%a.

Just in the interest of thoroughness, it should be pointed out that:

*

*when using for in a cmd console, use single percents.

*when using for in a bat script, use double percents.

*Use a tilde when retrieving the iterative variable to strip surrounding quotation marks from the value.  (e.g. "Hello world!" becomes Hello world!).  It's convenient to use this to force a desired format.  "%%~G" would always be quoted, whether the captured value was quoted or not.  You should always do this when capturing file names with a for loop.

*Tilde notation also allows expanding paths, retrieving file size, and other conversions.  See the last couple of pages of help for in a cmd console for more details.


text:
Q: Android: ListView with dynamic colours I'm trying to make a ListView which represents a list of train lines, each with a different colour. So at the moment I have this:
public class TrainOverview extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
            R.layout.list_item, R.id.label, TrainLines.lines);
        this.setListAdapter(arrayAdapter);
    }
}

The list_item XML simply consists of two text labels in a linear layout, one of which I want to be able to change the colour of dynamically. TrainLines.lines is just a String[] at the moment, but I'd like to make it a very simple class with name and colour attributes. Then, I'd like to be able to create a ListView that shows the name of the train line, and the appropriate colour.
What's the best way to achieve this? I hope my question makes sense!

A: I would recommend extending BaseAdapter, it is relatively easy to do and very useful when it comes to various Views / row layouts (including changing colour of TextView)
The methods getViewTypeCount() and getItemViewType(position) can be easily overriden to give you as many different row layouts as you like.
This may not be your goal at all but is a handy thing to know.
However, I believe you will need a custom BaseAdapter, in which you override the getView(int position, View convertView, ViewGroup parent) method.
This would allow you to access theTextView for each row as you mentioned above. A good way to go about this is by implementing the ViewHolder pattern.
You could create a simple ViewHolder object ie.
private static class ViewHolder
{
     TextView textView;
}

Then use that in your overriden getView()
    // Get that view
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        if (convertView == null)
        {
            if (getItemViewType(position) == 0)
            {
                convertView = inflater.inflate(R.layout.rowlayouta, null);
                viewHolder = new ViewHolder();
                viewHolder.textView = (TextView) convertView.findViewById(R.id.tvCommonText1);
                convertView.setTag(viewHolder);
            }
            else
            {
                convertView = inflater.inflate(R.layout.rowlayoutb, null);
                viewHolder = new ViewHolder();
                viewHolder.textView = (TextView) convertView.findViewById(R.id.tvCommonText2);
                convertView.setTag(viewHolder);
            }
        }

        else
            viewHolder = (ViewHolder) convertView.getTag(); // Or if View is existing

        viewHolder.textView.setText(strings.get(position));

        return convertView;
    }

That's just an example of how I inflated two different row layouts, you could just take out the first else.
You can see that if there is now ViewHolder object assigned to that row, a new ViewHolder object is created, its TextView is set to the reference of the current convertView - effectively the current rows View. Then the ViewHolder object which now contains reference to that specific rows TextView is basically attached to that convertView / row using the setTag(object) method.
If it already has a tag, that tag is got using the getTag() method instead of creating a new object with new references. MOST importantly, no new view is inflated, the old one is just reused.
This then allows you to set what TextView properties you want by referring to the current ViewHolder object which holds reference to that specific TextView.
As you can see I changed the text to each TextView as I went along to reflect which row / convertView was being displayed. (Pretty useful in itself). All you need to do there is refer to the current ViewHolder in the same way and use the setTextColor() method.
Maybe that was a bit drawn out. But hopefully with that you will be able to implement what you are asking about and you know why it is a good implementation.
P.S. For more info on how ListViews and adapters come together (thinking of the getView() method here), this tutorial is pretty helpful..
http://android.amberfog.com/?p=296

A: I think that you can use the setTextColor() method declared in the TextView class. Check out the documentation here.
I assume that by dynamic colours you mean programmatically modifying the colors of your TextViews.
If you are looking for a custom array adapter please refer to this tutorial.


text:
Q: declaring a variable in php oop methods What does $iteration_method = 'get_file_object' means here. Is this same as declaring a variable and assign it a string value here? or does it have some other meaning? or does it has some other meaning?
protected function get_file_objects($iteration_method = 'get_file_object') {
        $upload_dir = $this->get_upload_path();
        if (!is_dir($upload_dir)) {
            return array();
        }
        return array_values(array_filter(array_map(
            array($this, $iteration_method),
            scandir($upload_dir)
        )));
    }

A: That`s mean if your dont pass any argument to method the variable inside method will have value  'get_file_object', in other case get value of passed varaible, for example;
 class test{
    public function test($test = 'hello world'){
        echo $test;
    }
 }

 $a = new test();
 $a->test(); // output hello world
 $a->test('im Michael'); // output im Michael


text:
Q: Vlookup to replace column index with value for each row in python dataframes I have a data frame of some registered velocities (V1, V2, V3, MaxV or the maximum velocity) and the corresponding time stamps for each velocity(T1, T2, T3, MaxV_T or the time instant of the maximum velocity) as follows:
df

Event T1       V1    T2       V2    T3       V3    MaxV  MaxV_T
  0   12:40:44 42.86 12:40:43 45.65 12:40:39 50.5  50.5  T3
  1   15:28:15 88.75 15:28:14 86.45 15:28:17 84.56 88.75 T1

The point that in the MaxV_T column doesn't indicate the real value but the title of the column where the real value falls.
What i need to do in python is to replace this value with the real time stamp to be like this
df

Event T1       V1    T2       V2    T3       V3    MaxV  MaxV_T
  0   12:40:44 42.86 12:40:43 45.65 12:40:39 50.5  50.5  12:40:39
  1   15:28:15 88.75 15:28:14 86.45 15:28:17 84.56 88.75 15:28:15

UPDATE
What to do if the position indication is not available, so i don't have the initial MaxV_T column and i need to return the corresponding time value for each velocity?

A: Use lookup
df.assign(MaxV_T=df.lookup(df.index, df.MaxV_T))

   Event        T1     V1        T2     V2        T3     V3   MaxV    MaxV_T
0      0  12:40:44  42.86  12:40:43  45.65  12:40:39  50.50  50.50  12:40:39
1      1  15:28:15  88.75  15:28:14  86.45  15:28:17  84.56  88.75  15:28:15