Script only prints out final entry instead of removing duplicates

Question: I'm writing a script that's supposed to remove duplicate entries. Some people in the data have entered in their name twice because they have two phone numbers, and because the phone number field was not an array, to enter multiple, they entered multiple entries.
My script changes the entries to dictionaries with keys corresponding to the column names and then goes through each of the rows.  There is a master for loop that goes through each row, and then a nested for loop that runs through all the elements for each element, comparing them to detect duplicates. When I hit a duplicate, my code is supposed to compare the phone, email, and websites and then append them to an area if they are unique / don't match.
The script runs, but the csv it returns is filled with the last person in the csv repeated 8 times and nothing else.
Here's my code:
import csv

# This function takes a tab-delim csv and merges the ones with the same name but different phone / email / websites.
def merge_duplicates(sheet):

    myjson = [] # myjson = list of dictionaries where each dictionary

    with(open("ieca_first_col_fake_text.txt", "rU")) as f:

        sheet = csv.DictReader(f,delimiter="\t")
        for row in sheet:
            myjson.append(row)

        write_file = csv.DictWriter(open('duplicates_deleted.csv','w'), ['name','phone','email','website'], restval='', delimiter = '\t')

        for row in myjson:

            # convert phone, email, and web to lists so that extra can be appended
            row['phone'] = row['phone'].split() if row.get('phone') else []
            row['email'] = row['email'].split() if row.get('email') else []
            row['website'] = row['website'].split() if row.get('website') else []
            print row

        i = 0

        for i in range(len(myjson)):

            # if the names match, check to see if phone, em, web match. If any match, append to first row.
            try:
                print 'trying'
                if myjson[i]['name'] == myjson[i+1]['name']:
                    if myjson[i]['phone'] != myjson[i+1]['phone']:
                        print 'detected'
                        myjson[i]['phone'].append(myjson[i+1]['phone'])
                    if myjson[i]['email'] != myjson[i+1]['email']:
                        myjson[i]['email'].append(myjson[i+1]['email'])
                    if myjson[i]['website'] != myjson[i+1]['website']:
                        myjson[i]['website'].append(myjson[i+1]['website'])
            except IndexError:
                print("We're at the end now")

            write_file.writerow(row)
            print row

merge_duplicates('ieca_first_col_fake_text.txt')

This is the csv output (not a real person...made up!)
"Amy Tramy Lamy Ph.D.   []  []  []"
"Amy Tramy Lamy Ph.D.   []  []  []"
"Amy Tramy Lamy Ph.D.   []  []  []"
"Amy Tramy Lamy Ph.D.   []  []  []"
"Amy Tramy Lamy Ph.D.   []  []  []"
"Amy Tramy Lamy Ph.D.   []  []  []"
"Amy Tramy Lamy Ph.D.   []  []  []"
"Amy Tramy Lamy Ph.D.   []  []  []"

Thanks so much for the help!

Ex data if it helps:
name    phone   email   website
Diane Grant Albrecht M.S.
"Lannister G. Cersei M.A.T., CEP"   111-222-3333    email@example.com  www.got.com
Argle D. Bargle Ed.M.
Sam D. Man Ed.M.    000-000-1111    firstname.lastname@example.com   www.daManWithThePlan.com
Sam D. Man Ed.M.
Sam D. Man Ed.M.    111-222-333     email@example.com   www.daManWithThePlan.com
D G Bamf M.S.
Amy Tramy Lamy Ph.D.

Comment: BTW try to use list comprehension, i.e. myjson = [row for row in csv.DictReader(f,delimiter="\t")] if you intend to pack iterator into the list (eq. to reading rows into memory).
Comment: use elif in if sections for even mutually exclusive cases (garbage-in principle)
Answer: Your specific problem is that you're writing row to your output csv, but you never reassign it after using it in the for loop that builds your list of dictionaries:
 write_file.writerow(row)

This code is a bit muddled.  I think a simpler approach would be to use an OrderedDict by name, assuming you're on 2.7 or later:
http://docs.python.org/2/library/collections.html#collections.OrderedDict
from collections import OrderedDict

people = OrderedDict()
with(open("ieca_first_col_fake_text.txt", "rU")) as f:
    sheet = csv.DictReader(f,delimiter="\t")
    for row in sheet:
        name = row.get('name')
        if name:
            contact_information = people.setdefault(name, {})
            contact_information.setdefault('phone', set()).add(row.get('phone'))
            contact_information.setdefault('email', set()).add(row.get('email'))
            contact_information.setdefault('website', set()).add(row.get('website'))

    write_file = csv.DictWriter(open('duplicates_deleted.csv','w'), ['name','phone','email','website'], restval='', delimiter = '\t')
    for name, contact_information in people:
        row_dict = {'name': name}.update({list(contact_field) for contact_field in contact_information.values()})
        write_file.writerow(row_dict)

That uses the Python set class to keep one copy of each phone number, email address and web site for each unique name, then converts them to lists for pretty writing to your CSV.  It doesn't maintain order - unfortunately there's no built in OrderedSet, but you could use another OrderedDict instead of a set if you want to preserve the order they were seen in.
Comment: Should I write myjson[i] instead?


Prevent or Counter Running Grapples?

Question: It seems that the way most people "play" online matches is to spam running grapples.  Is there any defense against this?  If so, is there any super star or move that makes it easier to block / counter running grapples?  This is just about ruining the WWE 13 online experience for me.
Answer: There are some good tips in this site, specially in the ninth post. Basically, it's all about timing your counter attack, instead of trying to hit your opponent back mindlessly.
Answer: What happens if you try a running grapple with the CPU? Most of times they put you on the ground. Want to do the same? Wait for your opponent run at you, and when he tries to grapple you, press A. It's very useful, and better than trying to reverse or something like that.
Comment: Due to server lag the timing is very difficult and more often than not the person running will get their shot landed anyway =/
Answer: Hold down L2 when you press the reversal button (R2). It makes it easier to counter attacks when timed correctly.

Prevent or Counter Running Grapples?


How do I use the elements in a list as an arg?

Question: I want to take an input of an infinite amount of numbers so I can add, subtract, multiply, and divide all the numbers together.
I'm converting all the numbers given into a list so I can separate them from one another. But I can't really figure out how to access the numbers from inside the list.

given_numbers = list(
    input("Please give me two or more numbers: ")
)  # Gets the numbers that are going to be used
given_operator = input("What do I do with these numbers?: ")  # Gets the operation

number_list = []  # The list the numbers given are going to be inside of
# numbers_ready = number_list # Just a placeholder for when I figure this out

for n in given_numbers:  # Removes spaces and commas
    if n.strip() and n.replace(",", ""):
        number_list.append(n)

def calculator(*num, **operator):

    if "add" in operator.values():
        lst = list(num)
        result = lst[0]

    for n in lst[1:]:
        result += n

    print("Result: ", result)

if "subtract" in operator.values():
    lst = list(num)
    result = lst[0]

    for n in lst[1:]:
        result -= n

    print("Result: ", result)

if "multiply" in operator.values():
    lst = list(num)
    result = lst[0]

    for n in lst[1:]:
        result *= n

    print("Result: ", result)

if "divide" in operator.values():
    lst = list(num)
    result = lst[0]

    for n in lst[1:]:
        result //= n

    print("Result: ", result)

Comment: `list(input("prompt"))` is not how you turn the input into a list. It will make each character a separate list element. Use `split()` to split at whitespace.
Comment: Text should be provided **as text**, not as screenshots.
Comment: ...and beyond that, code should follow [mre] rules, being only the shortest code that reproduces a narrow, specific error on which your question is focused. See also [How do I ask and answer homework questions?](https://meta.stackoverflow.com/a/334823/14122)
Comment: please fix your indentation
Comment: ...which is to say: If your real question is about putting numbers into a list or passing that list as a series of arguments, there's no reason for you to give us your assignment specification or code that isn't specifically related to list management; doing so distracts from the question rather than clarifying it.
Answer: given_numbers = list(
    input("Please give me two or more numbers: ")
)

Doing this you are splitting each characters that you type. For example:
>>> Please give me two or more numbers: 1 2 3 4
Will be a list like that:
['1', ' ', '2', ' ', '3', ' ', '4']
Instead, use this line of code:
given_numbers = input("Please give me two or more numbers: ").split(" ")

It means that you take a string as an input, after that you split this string in a list separating when there is a space.


Small issue with custom code to detect if a user is a member of a specific usergroup

Question: I have the following code which detects if a user is a member of a certain Joomla usergroup and displays the relevant link to the user.
This works great for 1 usergroup, BUT when a user is a member of more than 1 usergroup, the buttons are repeated for the amount of usergroups the user is a member of.
So if, for example, a user is a member of 4 usergroups, the button will be displayed 4 times (if the user is a member of the usergroup eg 'Usergroup001' 1 of the 4 buttons displayed will be a 'Start' button (as per the loop)).
Id like the buttons just to be displayed once, no matter how many usergroups the user is a member of.
<?php
$user_  = JFactory::getUser();
$db     = JFactory::getDBO();
foreach($user_->groups as $group){
$query  = 'SELECT title FROM #__usergroups';
$query .= ' WHERE id = ' . $group;
$db->setQuery( $query );
$grp = $db->loadResult();

if ($grp=='Usergroup001') : ?>
Start

<?php else : ?>
Sign up to Usergroup 001

<?php endif; ?>
<?php
}
?>

Many thanks in advance if anyone can help!!!
Answer: Maybe this will work:
<?php
$user_  = JFactory::getUser();
$db     = JFactory::getDBO();
$isMember = false;
foreach($user_->groups as $group){
    $query  = 'SELECT title FROM #__usergroups';
    $query .= ' WHERE id = ' . $group;
    $db->setQuery( $query );
    $grp = $db->loadResult();
    if ($grp=='Usergroup001') {
        $isMember = true;
        break;
    }
}
if ($isMember ) : ?>
    Start
<?php else : ?>
    Sign up to Usergroup 001
<?php endif; ?>

Comment: Have done, thanks again! I was wondering as I need to run this code several time in one page, im thinking it will be excessive on resources to run the db query each time, im trying to cut the query out and but no luck so far, once again any help would be much appreciated! :) Thanks again!
Answer: Try in_array
http://php.net/manual/en/function.in-array.php
if (in_array($grp,'Usergroup001')) : ?>
Start

<?php else : ?>
Sign up to Usergroup 001

Comment: Hi, Many thanks for your reply/help, although unfortunetly the buttons are still display (the amount of times that a user is a member of a usergroup (if a user is a member of 4 usergroups buttons are displayed 4 times).. also your code does not provide the correct Start button if the user is a member of 'Usergroup001'. To clarify with your modified code all buttons are 'Sign up' regardless if the user is a member of the usergroup. Sorry for the bad news, and thanks so much for trying to help!!!!!!!!!!!!!!!!!!!!!!!! :)
Comment: @jimmywiddle try now
Comment: Hi, Yes I did spot the missing closing bracket and added it, but im sorry to say im afraid it didn't work, once again many thanks for your time and help though!!!


TypeError: 'property' object is not iterable SQLAlchemy

Question: Alembic's autogenerate keeps throwing this error and it's rather mysterious to me:
INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO  [alembic.runtime.migration] Will assume transactional DDL.
Traceback (most recent call last):
  File "/home/mas/projects/icc/icc2-backend/.venv/bin/alembic", line 8, in <module>
    sys.exit(main())
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/config.py", line 581, in main
    CommandLine(prog=prog).main(argv=argv)
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/config.py", line 575, in main
    self.run_cmd(cfg, options)
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/config.py", line 552, in run_cmd
    fn(
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/command.py", line 214, in revision
    script_directory.run_env()
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/script/base.py", line 489, in run_env
    util.load_python_file(self.dir, "env.py")
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/util/pyfiles.py", line 98, in load_python_file
    module = load_module_py(module_id, path)
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/util/compat.py", line 184, in load_module_py
    spec.loader.exec_module(module)
  File "<frozen importlib._bootstrap_external>", line 855, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/home/mas/projects/icc/icc2-backend/alembic/env.py", line 84, in <module>
    run_migrations_online()
  File "/home/mas/projects/icc/icc2-backend/alembic/env.py", line 78, in run_migrations_online
    context.run_migrations()
  File "<string>", line 8, in run_migrations
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/runtime/environment.py", line 846, in run_migrations
    self.get_context().run_migrations(**kw)
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/runtime/migration.py", line 511, in run_migrations
    for step in self._migrations_fn(heads, self):
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/command.py", line 190, in retrieve_migrations
    revision_context.run_autogenerate(rev, context)
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/autogenerate/api.py", line 444, in run_autogenerate
    self._run_environment(rev, migration_context, True)
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/autogenerate/api.py", line 483, in _run_environment
    compare._populate_migration_script(
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/autogenerate/compare.py", line 25, in _populate_migration_script
    _produce_net_changes(autogen_context, upgrade_ops)
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/autogenerate/compare.py", line 50, in _produce_net_changes
    comparators.dispatch("schema", autogen_context.dialect.name)(
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/util/langhelpers.py", line 303, in go
    fn(*arg, **kw)
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/autogenerate/compare.py", line 75, in _autogen_for_tables
    [(table.schema, table.name) for table in autogen_context.sorted_tables]
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/util/langhelpers.py", line 230, in __get__
    obj.__dict__[self.__name__] = result = self.fget(obj)
  File "/home/mas/projects/icc/icc2-backend/.venv/lib/python3.9/site-packages/alembic/autogenerate/api.py", line 362, in sorted_tables
    result.extend(m.sorted_tables)
TypeError: 'property' object is not iterable

My models are thus:
# app/models/mixins.py
from app import db

from sqlalchemy.ext.declarative import declared_attr, as_declarative

@as_declarative()
class Base(db.Model):
    """This Base class does nothing. It is here in case I need to expand
    implement something later. I feel like it's a good early practice.

    Attributes
    ----------
    id : int
        The basic primary key id number of any class.

    Notes
    -----
    The __tablename__ is automatically set to the class name lower-cased.
    There's no need to mess around with underscores, that just confuses the
    issue and makes programmatically referencing the table more difficult.
    """
    __abstract__ = True
    id = db.Column(db.Integer, primary_key=True)

    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

# app/models/annotations.py
from datetime import datetime as dt

from app import db
from app.models.mixins import Base

class Annotation(Base):
    bookid = db.Column(db.Integer)
    author = db.Column(db.String)

    created = db.Column(db.DateTime)

    edits = db.relationship('Edit', back_populates='annotation')

    HEAD = db.relationship('Edit',
                           primaryjoin='Edit.annotation_id==Annotation.id',
                           uselist=False)

    def __init__(self, book, author, start, end, text, *args, **kwargs):
        self.created = dt.now()
        self.bookid = book
        self.author = author
        super().__init__(*args, **kwargs)
        self.edits.append(Edit(author, start, end, text))

class Edit(Base):
    annotation_id = db.Column(db.Integer, db.ForeignKey('annotation.id'),
                              index=True)
    text = db.Column(db.Text)
    editor = db.Column(db.String)

    start = db.Column(db.Integer)
    end = db.Column(db.Integer)

    created = db.Column(db.DateTime)

    annotation = db.relationship('Annotation', back_populates='edits')

    def __init__(self, editor, start, end, text, *args, **kwargs):
        self.editor = editor
        self.start, self.end = start, end
        self.text = text
        self.created = dt.utcnow()
        super().__init__(*args, **kwargs)

And because I'm not sure if it's relevant, my alembic/env.py
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

import os, inspect, sys
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)

from config import Config

config = context.config # alembic

config.set_main_option('sqlalchemy.url', Config.SQLALCHEMY_DATABASE_URI)
print(Config.SQLALCHEMY_DATABASE_URI)

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

from app import db
target_metadata = db.MetaData

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.

def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )

    with context.begin_transaction():
        context.run_migrations()

def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """
    connectable = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        context.configure(
            connection=connection, target_metadata=target_metadata
        )

        with context.begin_transaction():
            context.run_migrations()

if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()

The code is all at https://github.com/anno-wiki/icc2-backend if that might help. I'm hoping someone might be able to shed some light on this. Alembic's code is rather abstract and difficult to follow to see why that particular line is having trouble with my configuration. I've used a Base mixin plenty of times before and it's never been a problem.
Answer: It seems that by changing target_metadata = db.MetaData to target_metadata = db.metdata fixed the problem, though then the models weren't detected. Importing app.models.Annotation and using Annotation.metadata made the whole thing work.


What is the difference between L"the following:" and "the following:"

Question: Are there any differences between the two? Both compiles with vs2013.
CStringW str1 = "the following:";
CString str2 = L"the following:";
The strings are from afxstr: https://msdn.microsoft.com/en-us/library/ms174288.aspx
I understand that the variant without L is casted via the appropriate cast operator but what problems can arise from using the form without L while I do NOT use any unicode characters between the quotation marks. Is this a good programming practice to use L"" even when you don't plan to use non-unicode chars or is there more to it?
edit: maybe I realized the answer. Is the main problem is that without L, I suffer the performance hit of calling an unnecessary operator method? But are both gives the same, correct result?
Answer: You create a wide string literal using the L macro. Without the L its just a narrow string. Also check your project settings. Are you building it as a Unicode project?
Rather than use the L I would recommend using the _T() macro which expands to L only if your project is being built as Unicode
Take a look at this page and this too
So in other words if you want your string to be always Unicode then use the L
update:
I would recommend
CString str1 = _T("the following");

and build your project as Unicode if you want your string to be expanded to a wide string
Comment: +1 for the reference links. Like @a3f said L is not a macro, but just a prefix used for wide strings. Prefixing string with L modifier makes the string a wide char which is needed for Unicode strings. However having _T() or _TEXT() is preferred since it will switch between MBCS and Unicode mode strings as required.
Comment: `L""` is not a macro, it is a language feature. `_T()` and `CString`, afaic, are not included in the 'standard' headers. This may be a problem for certain platforms.
Answer: "the following:"'s type is const char* while the L"the following's one is const wchar_t*. Depending on what you do with the second literal, you may be implicitly casting, calling overloaded versions of certain functions, cause templates to specialise for the wchar_t rather than the char type or have your code fail to compile (narrowing and implicit casts are not always allowed). Note that casting from wchar_t to char (implicitly or explicitly) is considered narrowing, since a char is typically 1 byte while the size of a wchar_t is always greater. As far as I remember, it is implementation-specific whether a char should be signed or unsigned; it could be then that casting from wchar_t to char does not always yields the expected results even for ascii subset of the latter - you have to check the standard for such things. Then, if you go for the L type of literals your program will also require more memory. As always in the world of C++, you pay for what you use, so if don't really need unicode characters, don't use wchar_t.
Comment: *Technically*, the types of the string literals are closer to (but not exactly the same as) `const char[]` and `const wchar_t[]`. They are actually *compiler-defined types*, which happen to degrade to `const char*` and `const wchar_t*` when needed.
Comment: +1 for "if don't really need unicode characters, don't use wchar_t". [Generic Text Data Mapping](https://msdn.microsoft.com/en-us/library/se784sk6.aspx)


RTL8723DE device bluetooth driver

Question: I have updated to kernel 4.17.0-041700-genericand installed the Bluetooth driver going through How to activate bluetooth device for RTL8723DE?. In earlier kernel driver it was doing well.
Edit : Now I have installed 5.6.0-050600-generic and bluetooth is working but wi-fi has gone
sudo dkms install rtlwifi-new/0.6
Kernel preparation unnecessary for this kernel.  Skipping...
Building module:
cleaning build area......(bad exit status: 2)
make -j2 KERNELRELEASE=5.3.0-46-generic -C /lib/modules/5.3.0-46-generic/build M=/var/lib/dkms/rtlwifi-new/0.6/build.........................................(bad exit status: 2)
ERROR (dkms apport): binary package for rtlwifi-new: 0.6 not found
Error! Bad return status for module build on kernel: 5.3.0-46-generic (x86_64)
Consult /var/lib/dkms/rtlwifi-new/0.6/build/make.log for more information.
Comment: What is the reason of installing random kernels? The 5.6 doesn't support the installed Wi-Fi drivers. If you left the system alone with correct kernel, all would work.
Comment: I answered your BT question. Ask a new one regarding Wi-Fi. Probably the `rtlwifi_new` is too old for the 5.3 kernel.
Comment: What is the reasonof installing an unsuported 4.17 mainline kernel, when there is the 5.3 Ubuntu kernel available, that doesn't require any additional drivers. Also the old manual was for kernels that didn't support the module. With new kernels you need to remove any kind of "drivers".
Comment: @Pilot6  Now I have installed 5.6.0-050600-generic and bluetooth is working but wi-fi has gone
Answer: If you read the answer carefully, you could have noticed that supported kernels are 4.4-4.15.
You installed for an unknown reason the 4.17 mainline kernel. That's why the module is not building or working.
At present the RTL8723DE bluetooth device is suppored by the 5.3 kernel out of the box. This kernel is preinstalled with Ubuntu 18.04 iso and installable on the initial 18.04 release by
sudo apt install linux-generic-hwe-18.04

Comment: Thanks!! The easiest and effective solution I have found.

RTL8723DE device bluetooth driver


Isomorphic multiplicative groups of quadratic extensions

Question: What are all ordered pairs $(n,m)$ such that the multiplicative groups of the fields $\mathbb{Q}(\sqrt{n})$ and $\mathbb{Q}(\sqrt{m})$ are isomorphic?
I saw a question earlier today claiming that $(3,7)$ is one such pair (although I'm not sure this is true), and I'm interested in generalizing this.
Comment: @Joseph: the claim isn't that they're isomorphic in a way that preserves $\mathbb{Q}$.
Answer: The multiplicative group $\Bbb Q(\sqrt d)^*$ is abstractly isomorphic to $U \times \bigoplus_\omega \Bbb Z$, where $U$ is the torsion subgroup of $\Bbb Q(\sqrt d)^*$, which means it is the roots of unity in $\Bbb Q(\sqrt d)^*$.
$\Bbb Q(\sqrt{-1})^*$ and $\Bbb Q(\sqrt{-3})^*$ both have $U$ larger than $\{-1;+1\}$, so those two are special cases and are not isomorphic to anyone else but themselves.
For every other quadratic field, $U = \{-1;+1\}$, and so those $\Bbb Q(\sqrt d)^*$ are all abstractly isomorphic to each other.
Answer: For example, with $m,n<0$, if in both cases the rings of integers are PIDs, and if the fields contain no roots of unity beyond $\pm 1$, then the multiplicative groups are free groups on primes-mod-units, with $\pm 1$ thrown in. That is, in some cases the answer can be "yes, but for boring reasons". For $m,n>0$, the units group mod $\pm 1$ in the ring of algebraic integers is $\mathbb Z$, by Dirichlet, with no differentiation depending on $m,n$.
Comment: If the field is not a PID, then number field elements-mod-units is still a subgroup of the free group generated by the prime ideals, and subgroups of free groups are still free. And the group of powers of a prime is isomorphic to the group of powers of a unit.


Direct 2D gnuplot PNG animation?

Question: Can anyone please confirm that yes/no Gnuplot 4.5 (on CVS) can output 2D animated PNG files?  I have numerous datasets but one line that I'd like to show iteratively in 3 different places in my graph.  Can this be done directly from gnuplot or is this something that would need to be animated externally from multiple frames?
Answer: You can find the demo scripts for the CVS version here. There is a C2Gnuplot for creating gnuplot animations (self-advertisement: it was developed by me).

Direct 2D gnuplot PNG animation?


Second Order Non-Linear ODE involving Bessel Functions

Question: I'm trying to solve this but I'm getting nowhere. Does anyone know step-by-step solution? or at least the general techniques to use? I do know that the solution involves the Bessel functions.
$y'' + (1/x)y' - Ay = B$
Where y is differentiated with respect to  x.
Comment: You might want to investigate the [*Method of Frobenius*](http://en.wikipedia.org/wiki/Frobenius_method) or Infinite Series methods to solve a Bessel equation. You might also want to see the [general solution I wrote [*here*](http://math.stackexchange.com/questions/374123/help-with-special-function-differential-equation/374333#374333) for this type of equation.
Comment: I'm not an expert in diffeq but shouldn't there be second bessel kind term in the solution as well?
Answer: Well,this seems to be a nonhomogeneous Bessel equation.The solution space will be spanned by the fundamental solution of the homogeneous Bessel equation plus an solution to the nonhomogeneous one.
First consider the homogeneous equation:
                       $x^2y''+xy'-Ax^2y=0$
As we all know the fundamental solution to this very Bessel equation is:
$J_v=\sum^{+\infty}_{k=0}\frac{(-1)^k(1/2x)^{2k}}{\Gamma(k+1)k!}$ where $\Gamma$ is the standard gamma function.
For the detailed process you can just google'first Bessel kind function',but as you may notice there is difference on the coefficients here between the canonical one,I suggest a dialation trick such as let $Y=ay$ where a is to be chosen later to get the canonical equation.
The next step would be searching for a solution to the nonhomogeneous one,which is piece of cake,just let $y=-A/B$.
So the general solution to this problem is:$y=cJ_v-A/B$,where $c$ is constant.


What is the best way to start using git with for wordpress website?

Question: What would be the best solution? Connect the server to the Git or use a WordPress any tested plugin to sync with Git?
For reference, I have wordpress website. I use SiteGround for server. In WP Plugins I use Divi Builder.
Answer: You can add all necessary code on the git, for example, your plugin files, themes, etc. exclude upload folders, the config files, add those in gitignore. And use Jenkins for deployment to the server.
Comment: So, which plugin do you recommend for syncing WordPress and Git?
Comment: I don't use any plugins, I'm using the terminal for git commit, push, pull, etc. and this is so simple you can find tons of git basic command articles. Even you can use git UI for all basic operations and all smart IDE for example phpstorm, vscode, the sublime text has git functionality and support all necessary git commands.
Comment: So, you connect Git to the server and not to WordPress. Did I understand correctly?


Reading multiple data from string, separated by characters using sstream

Question: I have .txt file with text like this inside (this is just a fragment):
...
[332, 605]-[332, 592], srednica: 13
[324, 593]-[332, 605], srednica: 14.4222
[323, 594]-[332, 605], srednica: 14.2127
[323, 594]-[331, 606], srednica: 14.4222
[324, 593]-[324, 607], srednica: 14
[323, 594]-[323, 607], srednica: 13
[319, 596]-[319, 607], srednica: 11
[320, 595]-[320, 607], srednica: 12
...

What i need to to is get a first 4 numbers from each line and store them into integers.
I have tried smth like this:
ifstream file("punkty_srednice.txt");
string line;
int ax, ay, bx, by;
while(getline(file, line)) {
    stringstream s(line);
    string tmp;
    s >> tmp >> ax >> tmp >> ay >> tmp >>  bx >> tmp >> by >> tmp;
    cout << ax  << " " << ay <<  " " << bx << " " << by << endl;
}

Output (just a part of it):
...
506 506 -858993460 -858993460
503 503 -858993460 -858993460
495 503 -858993460 -858993460
497 503 -858993460 -858993460
500 497 -858993460 -858993460
492 503 -858993460 -858993460
...

As u an see there are some strange numbers like -858993460
I did other try by deleting tmp and going straight like this:
s >> ax >> ay >>  bx >> by;

but then output contains only trash numbers like -858993460
How i can deal with it?
Answer: You can use std::getline with the ',' as separator to get the first parts, with the numbers. Then replace all non-digit characters with space (see e.g. std::transform). Then put the resulting string in an std::istringstream and read four numbers from it.

Some tips on what's wrong with your code, it mostly boils down to that when used with strings, the input operator >> reads space delimited strings.
So for the line

[332, 605]-[332, 592], srednica: 13

your input will be

into tmp it will put "[332,"
into ax it will put the 605
into tmp it will put "]-[332,"
into ay it will put 592
into tmp it will put "],"
into bx it will try to read the string "srednica" which is not a valid number, and the input will fail and set the fail flag on the input stream, making all the following inputs invalid

How to replace any non-digit character in a string to a space using std::transform:
std::string s = "[332, 605]-[332, 592]";
std::cout << "Before: \"" << s << "\"\n";

std::transform(std::begin(s), std::end(s), std::begin(s),
    [](const char& ch) -> char
    {
        return (std::isdigit(ch) ? ch : ' ');
    });

std::cout << "After : \"" << s << "\"\n";

The above code prints

Before: "[332, 605]-[332, 592]"
After : " 332  605   332  592 "
Comment: You are completly right! Now i realised why im getting 2 good values and 2 trashes. I cant find good example of std::transform so i replaced step by step `'[' ']' '-' ','`
Comment: @user3804906 Follow the links in my answer. :)


2 consecutive stream-stream inner joins produce wrong results: what does KStream join between streams really do internally?

Question: The problem setting
I have a stream of nodes and a stream of edges that represent consecutive updates of a graph and I want to build patterns composed of nodes and edges using multiple joins in series. Let's suppose I want to match a pattern like: (node1) --[edge1]--> (node2).
My idea is to join the stream of nodes with the stream of edges in order to compose a stream of  sub-patterns of type (node1) --[edge1]-->. Then take the resulting stream and join it with the stream of nodes another time in order to compose the final pattern (node1) --[edge1]--> (node2).  Filterings on the particular type of nodes and edges are not important.
Data model
So I have nodes, edges and patterns structured in Avro format:
{
  "namespace": "DataModel",
  "type": "record",
  "name": "Node",
  "doc": "Node schema, it contains a nodeID label and properties",
  "fields": [
    {
      "name": "nodeID",
      "type": "long"
    },
    {
      "name": "labels",
      "type": {
        "type": "array",
        "items": "string",
        "avro.java.string": "String"
      }
    },
    {
      "name": "properties",
      "type": {
        "type": "map",
        "values": "string",
        "avro.java.string": "String"
      }
    },
    {
      "name": "timestamp",
      "type": "long"
    }
  ]
}

{
  "namespace": "DataModel",
  "type": "record",
  "name": "Edge",
  "doc": "contains edgeID, a type, a list of properties, a starting node ID and an ending node ID ",
  "fields": [
    {
      "name": "edgeID",
      "type": "long"
    },
    {
      "name": "type",
      "type": "string"
    },
    {
      "name": "properties",
      "type": {
        "type": "map",
        "values": "string",
        "avro.java.string": "String"
      }
    },
    {
      "name": "startID",
      "type": "long"
    },
    {
      "name": "endID",
      "type": "long"
    },
    {
      "name": "timestamp",
      "type": "long"
    }
  ]
}

{
    "namespace": "DataModel",
    "type": "record",
    "name": "Pattern",
    "fields": [
      {
        "name": "first",
        "type": "long"
      },
      {
        "name": "nextJoinID",
        "type": [
          "null",
          "long"
        ],
        "default": null
      },
      {
        "name": "timestamp",
        "type": "long"
      },
      {
        "name": "segments",
        "doc": "It's the ordered list of nodes and edges that compose this sub-pattern from the leftmost node to the rightmost edge or node",
        "type": {
          "type": "array",
          "items": [
            "DataModel.Node",
            "DataModel.Edge"
          ]
        }
      }

Then I have the following two ValueJoiners:
The first one to be used for an inner join of a nodes stream and an edges stream.
The second one to be used for an inner join of a supatterns stream and node stream.
public class NodeEdgeJoiner implements ValueJoiner<Node, Edge, Pattern> {

    @Override
    public Pattern apply(Node node, Edge edge) {

        Object[] segments = {node,edge};
        return Pattern.newBuilder()
                .setFirst(node.getNodeID())
                .setNextJoinID(edge.getEndID())
                .setSegments(Arrays.asList(segments))
                .setTimestamp(Math.min(node.getTimestamp(),edge.getTimestamp()))
                .build();

    }
}

public class PatternNodeJoiner implements ValueJoiner<Pattern, Node, Pattern> {

    @Override
    public Pattern apply(Pattern pattern, Node node) {

        List<Object> segments = pattern.getSegments();
        segments.add(node);
        return Pattern.newBuilder()
                .setFirst(pattern.getFirst())
                .setNextJoinID(node.getNodeID())
                .setSegments(segments)
                .setTimestamp(Math.min(node.getTimestamp(),pattern.getTimestamp()))
                .build();
    }
}

My intention is to catch patterns like :  (nodeId == 1)--[label == "related_to"]-->()  where

(nodeId == 1) represents a node with id=1
--[label == "related_to"]--> represents a directed edge with label = "related_to"
() represents a generic node.

The idea for concatenating those pieces together is to perform two consecutive joins using the previous Valuejoiners.  I want you to focus to the first operation performed by both the ValueJoiners: in order to build the pattern I just simply append nodes and edges at the end of a list that is part of the Avro schema of a Pattern.
The following is the generic loop to produce nodes and edges and publish them in the corresponding topics.   The key of each node record corresponds to the nodeID and the key of each edge record is the nodeID of the incoming node of the edge.
while(true){

            try (final KafkaProducer<Long, Node> nodeKafkaProducer = new KafkaProducer<Long, Node>(props)) {

                final KafkaProducer<Long, Edge> edgeKafkaProducer = new KafkaProducer<Long, Edge>(props);

                nodeKafkaProducer.send(new ProducerRecord<Long, Node>(nodeTopic, (long) 1,
                        buildNodeRecord(1, Collections.singletonList("aString"), "aString",
                                System.currentTimeMillis())));
                edgeKafkaProducer.send(new ProducerRecord<Long, Edge>(edgesTopic, (long) 1,
                        buildEdgeRecord(1, 1, 4, "related_to", "aString",
                                System.currentTimeMillis())));
                Thread.sleep(9000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

where:
private Node buildNodeRecord(long nodeId, List<String> labelsToSet, String property, long timestamp){

        Node record = new Node();
        record.setNodeID(nodeId);
        record.setLabels(labelsToSet);
        Map<String, String> propMap = new HashMap<String, String>();
        propMap.put("property", property);
        record.setProperties(propMap);
        record.setTimestamp(timestamp);
        return record;

    }
private Edge buildEdgeRecord(long edgeId,long startID, long endID, String type, String property, long timestamp) {

        Edge record = new Edge();
        record.setEdgeID(edgeId);
        record.setStartID(startID);
        record.setEndID(endID);
        record.setType(type);

        Map<String,String> propMap = new HashMap<String, String>();
        propMap.put("property",property);
        record.setProperties(propMap);
        record.setTimestamp(timestamp);

        return record;
    }

The following part of the code describes the pipeline.
//configuration of specific avro serde for pattern type
        final SpecificAvroSerde<Pattern> patternSpecificAvroSerde = new SpecificAvroSerde<>();
        final Map<String, String> serdeConfig = Collections.singletonMap(
                AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, envProps.getProperty("schema.registry.url"));
        patternSpecificAvroSerde.configure(serdeConfig,false);

        //the valueJoiners we need
        final NodeEdgeJoiner nodeEdgeJoiner = new NodeEdgeJoiner();
        final PatternNodeJoiner patternNodeJoiner = new PatternNodeJoiner();

        //timestampExtractors
        NodeTimestampExtractor nodeTimestampExtractor = new NodeTimestampExtractor();
        SubPatternTimeStampExtractor subPatternTimeStampExtractor = new SubPatternTimeStampExtractor();
        EdgeTimestampExtractor edgeTimestampExtractor = new EdgeTimestampExtractor();

        //node source
        final KStream<Long, Node> nodeKStream = builder.stream(envProps.getProperty("node.topic.name"),
                Consumed.with(nodeTimestampExtractor));

       //filter on nodes topic
        nodeKStream.filter((key, value) -> value.getNodeID()==1).to(envProps.getProperty("firstnodes.topic.name"));
        final KStream<Long,Node> firstFilteredNodes = builder.stream(envProps.getProperty("firstnodes.topic.name"),
                Consumed.with(nodeTimestampExtractor));

        //edges keyed by incoming node
        final KStream<Long,Edge> edgeKstream = builder.stream(envProps.getProperty("edge.topic.name"),
                Consumed.with(edgeTimestampExtractor));

        //filter operation on edges for the first part of the pattern
        final KStream<Long,Edge> firstEdgeFiltered = edgeKstream.filter((key, value) ->
                value.getType().equals("related_to"));

        //first join
        firstFilteredNodes.join(firstEdgeFiltered,nodeEdgeSubJoiner,
                JoinWindows.of(Duration.ofSeconds(10)))
                .map((key, value) -> new KeyValue<Long, SubPattern>(value.getNextJoinID(), value))
                .to(envProps.getProperty("firstJoin.topic.name"));

        final KStream <Long,SubPattern> mappedFirstJoin = builder.stream(envProps.getProperty("firstJoin.topic.name"),
                Consumed.with(subPatternTimeStampExtractor));

        //second join
        KStream <Long,Pattern> secondJoin = mappedFirstJoin
                .join(nodeKStream,subPatternNodeJoiner, JoinWindows.of(Duration.ofSeconds(10)));
        secondJoin.print(Printed.toSysOut()); // should print out final records

I'm not going to show timestampextractors since I think they are irrelevant to the point.
The Issue
So I expect the output to be a stream of pattern records and the list ("segments" from the Avro schema) of each Pattern to be the same size: 1 node 1 edge and another node. But this doesn't happen. Instead I get this output:
[KSTREAM-MERGE-0000000018]: 4, {"first": 1, "nextJoinID": 4, "timestamp": 1611252427338, "segments": [{"nodeID": 1, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252427338}, {"edgeID": 1, "type": "related_to", "properties": {"property": "aString"}, "startID": 1, "endID": 4, "timestamp": 1611252427777}, {"nodeID": 4, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252427795}]}
[KSTREAM-MERGE-0000000018]: 4, {"first": 1, "nextJoinID": 4, "timestamp": 1611252427338, "segments": [{"nodeID": 1, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252427338}, {"edgeID": 1, "type": "related_to", "properties": {"property": "aString"}, "startID": 1, "endID": 4, "timestamp": 1611252427777}, {"nodeID": 4, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252427795}, {"nodeID": 4, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252436847}]}
[KSTREAM-MERGE-0000000018]: 4, {"first": 1, "nextJoinID": 4, "timestamp": 1611252427338, "segments": [{"nodeID": 1, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252427338}, {"edgeID": 1, "type": "related_to", "properties": {"property": "aString"}, "startID": 1, "endID": 4, "timestamp": 1611252436837}, {"nodeID": 4, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252427795}]}
[KSTREAM-MERGE-0000000018]: 4, {"first": 1, "nextJoinID": 4, "timestamp": 1611252427338, "segments": [{"nodeID": 1, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252427338}, {"edgeID": 1, "type": "related_to", "properties": {"property": "aString"}, "startID": 1, "endID": 4, "timestamp": 1611252436837}, {"nodeID": 4, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252427795}, {"nodeID": 4, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252436847}]}
[KSTREAM-MERGE-0000000018]: 4, {"first": 1, "nextJoinID": 4, "timestamp": 1611252427777, "segments": [{"nodeID": 1, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252436822}, {"edgeID": 1, "type": "related_to", "properties": {"property": "aString"}, "startID": 1, "endID": 4, "timestamp": 1611252427777}, {"nodeID": 4, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252427795}]}
[KSTREAM-MERGE-0000000018]: 4, {"first": 1, "nextJoinID": 4, "timestamp": 1611252427777, "segments": [{"nodeID": 1, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252436822}, {"edgeID": 1, "type": "related_to", "properties": {"property": "aString"}, "startID": 1, "endID": 4, "timestamp": 1611252427777}, {"nodeID": 4, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252427795}, {"nodeID": 4, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252436847}]}
[KSTREAM-MERGE-0000000018]: 4, {"first": 1, "nextJoinID": 4, "timestamp": 1611252427795, "segments": [{"nodeID": 1, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252436822}, {"edgeID": 1, "type": "related_to", "properties": {"property": "aString"}, "startID": 1, "endID": 4, "timestamp": 1611252436837}, {"nodeID": 4, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252427795}]}
[KSTREAM-MERGE-0000000018]: 4, {"first": 1, "nextJoinID": 4, "timestamp": 1611252436822, "segments": [{"nodeID": 1, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252436822}, {"edgeID": 1, "type": "related_to", "properties": {"property": "aString"}, "startID": 1, "endID": 4, "timestamp": 1611252436837}, {"nodeID": 4, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252427795}, {"nodeID": 4, "labels": ["aString"], "properties": {"property": "aString"}, "timestamp": 1611252436847}]}
.
.
.

As you can see the size of the array of ordered nodes and edges in each record is different. In particular I always see in them: a node and a edge followed by numerous nodes.  If I reduce the millisec of sleep in the while(true){...} it will get worse and generate very long lists with many more nodes in the list.
I guarantee that the node-edge join is performing well in every condition. It always generate correct results. The problem seems to effect the second join. But I don't understand how..
I tried to do some testing without success..
The following is the topology:
Topologies:
   Sub-topology: 0
    Source: KSTREAM-SOURCE-0000000000 (topics: [nodes])
      --> KSTREAM-WINDOWED-0000000015, KSTREAM-FILTER-0000000001
    Source: KSTREAM-SOURCE-0000000013 (topics: [firstJoin])
      --> KSTREAM-WINDOWED-0000000014
    Processor: KSTREAM-WINDOWED-0000000014 (stores: [KSTREAM-JOINTHIS-0000000016-store])
      --> KSTREAM-JOINTHIS-0000000016
      <-- KSTREAM-SOURCE-0000000013
    Processor: KSTREAM-WINDOWED-0000000015 (stores: [KSTREAM-JOINOTHER-0000000017-store])
      --> KSTREAM-JOINOTHER-0000000017
      <-- KSTREAM-SOURCE-0000000000
    Processor: KSTREAM-JOINOTHER-0000000017 (stores: [KSTREAM-JOINTHIS-0000000016-store])
      --> KSTREAM-MERGE-0000000018
      <-- KSTREAM-WINDOWED-0000000015
    Processor: KSTREAM-JOINTHIS-0000000016 (stores: [KSTREAM-JOINOTHER-0000000017-store])
      --> KSTREAM-MERGE-0000000018
      <-- KSTREAM-WINDOWED-0000000014
    Processor: KSTREAM-FILTER-0000000001 (stores: [])
      --> KSTREAM-SINK-0000000002
      <-- KSTREAM-SOURCE-0000000000
    Processor: KSTREAM-MERGE-0000000018 (stores: [])
      --> KSTREAM-PRINTER-0000000019
      <-- KSTREAM-JOINTHIS-0000000016, KSTREAM-JOINOTHER-0000000017
    Processor: KSTREAM-PRINTER-0000000019 (stores: [])
      --> none
      <-- KSTREAM-MERGE-0000000018
    Sink: KSTREAM-SINK-0000000002 (topic: firstFilter)
      <-- KSTREAM-FILTER-0000000001

  Sub-topology: 1
    Source: KSTREAM-SOURCE-0000000004 (topics: [edges])
      --> KSTREAM-FILTER-0000000005
    Processor: KSTREAM-FILTER-0000000005 (stores: [])
      --> KSTREAM-WINDOWED-0000000007
      <-- KSTREAM-SOURCE-0000000004
    Source: KSTREAM-SOURCE-0000000003 (topics: [firstFilter])
      --> KSTREAM-WINDOWED-0000000006
    Processor: KSTREAM-WINDOWED-0000000006 (stores: [KSTREAM-JOINTHIS-0000000008-store])
      --> KSTREAM-JOINTHIS-0000000008
      <-- KSTREAM-SOURCE-0000000003
    Processor: KSTREAM-WINDOWED-0000000007 (stores: [KSTREAM-JOINOTHER-0000000009-store])
      --> KSTREAM-JOINOTHER-0000000009
      <-- KSTREAM-FILTER-0000000005
    Processor: KSTREAM-JOINOTHER-0000000009 (stores: [KSTREAM-JOINTHIS-0000000008-store])
      --> KSTREAM-MERGE-0000000010
      <-- KSTREAM-WINDOWED-0000000007
    Processor: KSTREAM-JOINTHIS-0000000008 (stores: [KSTREAM-JOINOTHER-0000000009-store])
      --> KSTREAM-MERGE-0000000010
      <-- KSTREAM-WINDOWED-0000000006
    Processor: KSTREAM-MERGE-0000000010 (stores: [])
      --> KSTREAM-MAP-0000000011
      <-- KSTREAM-JOINTHIS-0000000008, KSTREAM-JOINOTHER-0000000009
    Processor: KSTREAM-MAP-0000000011 (stores: [])
      --> KSTREAM-SINK-0000000012
      <-- KSTREAM-MERGE-0000000010
    Sink: KSTREAM-SINK-0000000012 (topic: firstJoin)
      <-- KSTREAM-MAP-0000000011

pom.xml
<groupId>KafkaJOINS</groupId>
    <artifactId>KafkaJOINS</artifactId>
    <version>1.0</version>

    <repositories>
        <repository>
            <id>confluent</id>
            <url>https://packages.confluent.io/maven/</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>confluent</id>
            <url>https://packages.confluent.io/maven/</url>
        </pluginRepository>
    </pluginRepositories>

    <properties>
        <log4j.version>2.13.3</log4j.version>
        <avro.version>1.9.2</avro.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <confluent.version>6.0.0</confluent.version>
        <kafka.version>6.0.0-ccs</kafka.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-streams</artifactId>
            <version>${kafka.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
            <version>${kafka.version}</version>
        </dependency><dependency>
            <groupId>io.confluent</groupId>
            <artifactId>kafka-streams-avro-serde</artifactId>
            <version>${confluent.version}</version>
        </dependency>
        <dependency>
            <groupId>io.confluent</groupId>
            <artifactId>kafka-avro-serializer</artifactId>
            <version>${confluent.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.avro</groupId>
            <artifactId>avro</artifactId>
            <version>${avro.version}</version>
        </dependency>

Answer: In your first ValueJoiner you create a new new object:
Object[] segments = {node,edge};

In you second ValueJoiner you are getting a list and adding to it. You would need to deep-copy the list though:
// your code
List<Object> segments = pattern.getSegments();
segments.add(node); // this effectively modifies the input object;
                    // if this input object joins multiple times,
                    // you may introduce an undesired side effect

// instead you should do
List<Object> segments = new LinkedList<>(pattern.getSegments());
segments.add(node);


Weird Error Message to /tp

Question: I'm building a map and I'm trying to teleport a Armor Stand named Jacob, but it tells me:

'888ba526-c645-4271-8ca7-5bf8cca13344' is not a valid number

Here is the command:
<code>/tp @e[name=Jacob] -459.1 202.0 -840.4
</code>
I'm using minecraft 1.10.2. I have no mods installed.
Here is a screenshot:
Comment: If I had to guess, the armor stand inherited or already had that GUID (global unique identifier AKA that long string of numbers and letters) and now something is wrong with it. Have you tried making a new armor stand an teleporting it? What happens then?
Comment: Wouldn't you need to make it target an armor stand in []? Also, please include a screenshot and the version you're using, and if your using mods
Comment: Alright Alex, i added in more info
Comment: hmm... that's strange, I've never seen that before
Comment: I don't know if i did something wrong with the command or anything, because the command always worked... Is there a new way to /tp ArmorStands in 1.10.2?
Comment: I think you'll have to wait for someone who knows how to do commands better than me to answer
Comment: yeah, I'm waiting for colorfusion to find this
Comment: it says the same thing with different number & letters
Comment: Does ANYONE have an awnser
Comment: Maybe try the answer in [this question](http://gaming.stackexchange.com/q/215458/163757).  It's not a direct answer but maybe you have the syntax wrong for your command.
Comment: Nope, didn't help me.
Comment: ... this happened to me yesterday and today i try it and it works...
Comment: I recognize the format of that string... the skull is causing the problem. I'm not sure how to fix it, but the custom player skull is the issue. They did some weird thing in 1.8 and made it where you have to use that for certain things, not sure why.
Answer: I think I know how to fix the problem! When you teleport an entity, you have to specify which type of entity you want the teleport and not just the name of it. So, to teleport your armor stand you would do <code>/tp @e[type=ArmorStand,name=Jacob]  -459.1 202.0 -840</code> to teleport it to that location! I hope my command and answer worked for you and if it didn't work please tell me what the result was, Thank You!
Comment: Oh, I didn't know. Soz

Weird Error Message to /tp


MongoDB for Windows C#.Net Application

Question: As I am starting a new product development in Windows Form C#.Net Application, I want to use Mongo DB with it.
Could anybody please let me know that can I use MongoDB database for Windows Form application ? and if yes, How about the reports (complex reports) and relation with them?
As I am new to MongoDB, I don't have any idea to integrate reports and relation with it.
Please let me so I can go further and take decision about database choice.
Thanks in advance.
Answer: I am not sure I understand your question. You tagged it with mongodb-csharp, so you already seem to know there is a driver available for C# under Windows (which is also quite obvious if you check out the mongoDB page's driver section), so: yes, you can use mongoDB in a C# Windows application - there are even several other drivers available, like the "official" C# driver or NoRM.
That being said, reporting is often considered to be a weakness of NoSQL databases, which is true if you need to aggregate data via complex queries. You might want to store data needed for reports in an "old-fashioned" relational database.
Answer: You can use MongoDB database for Windows Form application. Store your reports information in MongoDB's native BSON documents. For example each BSON document will stores one report. Use ids of documents for relations. As i found samus C# driver is fine. Check it;)

MongoDB for Windows C#.Net Application


mongoose user bulk search by phone numbers

Question: I have UserSchema which contains PhoneNumberSchema as below.
var PhoneNumberSchema = new Schema({
    country: {
        type: String
    },
    country_code: {
        type: Number
    },
    local_number: {
        type: Number
    }
});

And here is sample json format of phone_number.
"phone_number": {
    "country": "US",
    "country_code": "1",
    "local_number": "04152341"
}

What I want to do is to search users by phone numbers with / without country code.
Well, if request is

"phone_numbers": [    "104152341",    "124254364" ]

then I want to get users who has exactly matched phone number which belongs in the request phone numbers array with/without country code.
So, I tried as below, but got error "invalid operator '$in'".
User.aggregate(
    [
        { "$redact": {
            "$cond": [
                {
                    "$in": [ { "$concat": [ "$phone_number.country_code", "$phone_number.local_number" ] }, req.body.phone_numbers]
                },
                "$$KEEP",
                "$$PRUNE"
            ]
        }}
    ],
    function(err, users) {
        // Do something
        if (err) {
            return res.json({ success: false, err: err });
        }
        res.json({ success: true, users: users });
    }
)

I hope to know how to handle my issue.
Please help me !!
Answer: Use $setIsSubset as your condition expression:
{ "$redact": {
    "$cond": [
        {
            "$setIsSubset": [
                [
                    {
                        "$concat": [
                            "$phone_number.country_code",
                            "$phone_number.local_number"
                        ]
                    }
                ],
                req.body.phone_numbers
            ]
        },
        "$$KEEP",
        "$$PRUNE"
    ]
}}

Comment: Excellent, though we need also handle with/without country code, $setIsSubset is good for two fields concatenation. :)


How to track activity visibilty considering dialogs and system windows?

Question: A task: I should track visibility of whole Android application and generate events when it goes to background or foreground. First part of the task is completed: I have special global counter which I increment in Activity onStart() and decrement in Activity onStop(), when this counter downs to zero then my application has gone to background.
Second part of the task is tricker. I know about strange behavior of onResume() and advice to use onWindowFocusChanged(boolean). I looked into documentation of onWindowFocusChanged(boolean) and noticed such thing:

As a general rule, however, a resumed activity will have window
  focus... unless it has displayed other dialogs or popups that take
  input focus, in which case the activity itself will not have focus
  when the other windows have it. Likewise, the system may display
  system-level windows (such as the status bar notification panel or a
  system alert) which will temporarily take window input focus without
  pausing the foreground activity.

Is any way to check out: whose window is shown over resumed activity from my app? Is it my dialog or keyguard? Is any way to catch event: all but mine windows over resumed activities are removed?
Answer: Your counter based approach is plain wrong. One reason: onStop() is not guaranted to execute.
I would assume that your notion of "background" and "foreground" should be the same as that of Android. However, when I read what you have done so far, it seems as if you have a different idea of what "background" and "foreground" mean, than Android has.
From there:

If you have an idea of what background and foreground mean which differs from Android, you're not doing yourself a favour and probably follow a misguided path, so recosnider adjusting the meaning of foreground and background.
Once you have the same idea as Android about background and foreground, the question is, why do you have to generate events when Android already does that. If you have to send events to a service or such, then it will be simple by listening for Activity lifecycle events and firing corresponding events for your Service.

Regarding onWindowFocusChanged: Yes, of course the notification panel can hide your App temporarily; have you used an Android device yet? The big question here is whether you would consider your App in the background then, because Android considers your App to be in the background if the notification panel is being shown.
Update: I just re-read your Q's title. Unfortunately, you're not stating what you really want/need to do, because visibility can mean a lot of things. E.g. do you consider your app to be visible if a semi transparent notification panel is laid out on top of it, or not? But the bottom line remains the same: It would be easiest if you align what you want with what Android does offer. ;)
Update 2: If you really need to know whether your Activity has been moved to the background by a popup of your own activity or by yourself, this answer here should give you the information you need.
Comment: Technical task is copied from iOS's one. In iOS app you can easily track global visibility of whole app. In Android, Application hasn't events "application did enter background/foreground", so I have to emulate them. Application did enter background when none of application activities are in visible state (http://developer.android.com/reference/android/app/Activity.html). Application did enter foreground when it was in background and then any activity come to visible state.
Comment: I can't imagine why this is a problem for you. Why can't you live with yourAndroid's native notion of when an Activity is in the foreground or in the background?
Comment: It's technical task: I should report to analytics tracker events "App did enter foreground/background". In my question I explained why I can't use only onStart()/onResume()/onPause()/onStop().
Comment: @QuickNick In the article you referenced, there's a solution given, namely wait on onResume() _and_ inWindowFocusChanged(). It just doesn't work for games because you may miss the case that the device goes to sleep. But do youi consider rthis to be _moving to the background_? I wouldn't.
Comment: What my question was? "Is any way to check out: whose window is shown over resumed activity from my app? Is it my dialog or keyguard?"

In both cases onWindowFocusChanged() has param false. And I seek ways to differ situations "your resumed activity hasn't focus because of your dialog" and "your resumed activity hasn't focus because of keyguard or notification panel".
Comment: @QuickNick I have updated my answer with a reference to a solution which determines the current foreground task is the launcher. The code snippet there and the snippet referenced in the answer use a couple of techniques which I would hope might help you.
Comment: The question was solved such way by our customer: he forgot about this technical detail and we can ignore it. Thanks you for the effort.
Comment: @QuickNick Praise your customer for their insight regarding this detail of somewhat questionable relevance. Did you try the foreground task class analysis, though? I would have assumed that it would have the potential to implement it as originally intended.
Comment: My customer wanted us to put Flurry-analytics to Android application.


Realloc an array of structs that contain dynamically sized char pointers

Question: The point of this assignment is to read in a line from a file containing a city state followed by two lines that contain latitude and longitude coordinates. Then we need dynamically allocate structs exactly as they are written below to store these coordinates. Finally we export the landmarks to a KML format used by google earth.
At this point I can correctly write the KML from my structs. However that took a couple of dirty for loops in my grow_whole function (seen below). The issue is when I am freeing all the allocated pointers later. (Trust me it exists ill paste it in order below). I am pretty sure the problem is heap corruption. However ive been working on this way too long and I feel it could be simpler.
The file format. (There is like 150 of these.)
city, state
40 30 N
40 20 W

Wholesome_t is just a container that will hold information on the amount of landmark structs as well as the pointer to the first landmark. Landmark_t holds pointers to chars that are allocated with exactly the amount of space they need to contain their parsed city name and such.
struct landmark_t {
char *city;
char *state;
char *country;
float longitude;
float latitude;
};

struct wholesome_t {
struct landmark_t *landmarks;
int landcount;
int landmax;
};

Below is the chunk of code that handles reading lines and sending them to the correct parser.
Initially wholesome is malloc'd and the landmarks pointer is set to NULL.
Then we malloc space for 2 landmark structs and begin the while loop below.
struct landmark_t *land = NULL;
int coorflag = 0;
int flagcount = 0;
//Parse lines
while(fgets(buf, LEN, in)){
    //Does that thing where we realloc
    if(whole->landcount == whole->landmax){
        grow_whole(whole);
    }

    //remove trailing newline
    buf[strcspn(buf, "\n")] = 0;

    if(!coorflag){//Check to see if we are on a flag or coordinate
        //set land to be the pointer to our next empty landmark struct
        land = whole->landmarks + (sizeof(struct landmark_t) * whole->landcount);
        set_city_state_country(buf, land);
        coorflag = 1; //Set flag to get a coordinate line next
    }else{//We are on a coordinate line which will use
          //the same land struct pointer as above
        if(!flagcount){//Have we seen a coordinate line already?
            land->latitude = number_muncher(buf);
            flagcount = 1;
        }else{//We have seen a coordinate line
            land->longitude = number_muncher(buf);
            //We are done filling this structure. Reset flags and move to the next.
            flagcount = 0;
            coorflag = 0;
            whole->landcount++;
        }
    }
}

The problem is in grow_whole. I had a problem earlier where after running realloc the first landmark structure would contain the correctly assigned pointers but anything after it until somewhere near the end of the file all of the pointers for city, state, and country as well as longitude and latitude would be nulled out. I added the for loops that save all of our pointers to arrays before we realloc and then rewrite those pointers back to the correct structure.
void grow_whole(struct wholesome_t *whole)
{
//First collect all of the pointers inside our current landmark structs.
struct landmark_t *land = NULL;
char *city[whole->landcount];
char *state[whole->landcount];
char *country[whole->landcount];
float longitude[whole->landcount];
float latitude[whole->landcount];
for (int i = 0; i < whole->landcount; i++){
    land = whole->landmarks + (sizeof(struct landmark_t) * i);
    city[i] = land->city;
    state[i] = land->state;
    country[i] = land->country;
    longitude[i] = land->longitude;
    latitude[i] = land->latitude;
}
land = realloc(whole->landmarks, (GROW + whole->landmax) * sizeof(struct landmark_t));
if(land == NULL){
    printf("Error in grow_whole.\n");
    return;
}else{whole->landmarks = land;}
//Update landmax to represent aftergrow.
whole->landmax = GROW + whole->landmax;
//Refill all of the re allocated structs with their pointers.
for (int i = 0; i < whole->landcount; i++){
    land = whole->landmarks + (sizeof(struct landmark_t) * i);
    land->city = city[i];
    land->state = state[i];
    land->country = country[i];
    land->longitude = longitude[i];
    land->latitude = latitude[i];
}
//Fill two new structs with blank data.
for(int i = whole->landcount; i < whole->landmax; i++){
    land = whole->landmarks + (sizeof(struct landmark_t) * i);
    empty_fill(land);
}
return;
}

Immediatly after the while loop above we run
fclose(in);
char *s = argv[1];
s = strtok(s, ".");
s = strncat(s, ".kml", 4);
FILE *out = fopen(s, "w");
//Finally done lets write some KML
kml_begin(out);
for (int i=0; i < whole->landcount; i++){
    land = whole->landmarks + (sizeof(struct landmark_t) * i);
    kml_placemark(out, i, land);
}
kml_end(out);
fclose(out);
tea_party(whole);//free land
free(whole->landmarks);
free(whole);

Which gets to kml_end(out). (I know because I have a properly formatted with correct values .kml file) But during tea_party I get a seg_fault.
void tea_party(struct wholesome_t *whole)
{
    struct landmark_t *land = NULL;
    for (int i = 0; i < whole->landcount; i++){
        land = whole->landmarks + (sizeof(struct landmark_t) * i);
        printf("here\n");
        free(land->city);
        printf("here2\n");
        free(land->state);
        printf("here3\n");
       free(land->country);
    }
return;
}

It occurs for our second landmark struct.
land = whole->landmarks + sizeof(struct landmark_t)

And happens at free(land->state) (because I see here 1-3 for the first struct and then here 1-2 before the seg fault.)
Even if I try to print land->state right before the seg fault it just moves the seg fault up.
Answer: When doing pointer arithmetic, you don't have to scale the offset by sizeof(struct landmark_t) - the compiler already does that for you!
If you have a pointer p into an array, the next array element is at p + 1. It's that simple.
Also, you seems to create a record of arrays, when you should probably create an array of records. But that is a different problem.


Install meter box on existing steel siding

Question: I need to install 2 electrical boxes on existing steel siding.  One box is a 13" meter box (ringless lever), and while I'm at it I want to leave room to install a solar panel disconnect switch box for a project next spring.

I'm afraid if I surface mount the boxes over the siding, it will look like crap.  But to remove the siding from the top down seems like a lot of work; the contractors who installed it did a good job (even rivets along the top).  There doesn't seem to be any siding seams along this wall.  Difficult to see in the picture, but there is concrete block wall below the siding for about 6 inches.
I could also install to the left edge of this wall, it won't look any easier.  If I install on the back wall of the garage, there are at least some seams, but some are pretty long.
Power Company meter guidelines
The main panel needs to go pretty much behind this pictured wall due to obstacles inside the garage, but I can be flexible exactly where the meter is to some extent (external conduit runs within reason).
I've given some thought to putting them to the right of the door as that dimension is almost exactly the width of the meter box (even with the downspout in place).  If needed, I do have some extra siding panels and J channels / trim the contractor left from the siding job a few years ago.
Can anyone think of other options?
Comment: Remember the meter location decides the service panel location (unless the meter includes a main breaker), and you'll be running a lot of cables from the service panel.  To the right of the door makes no sense, you would not be able to route that many cables away from there without overcrowding.
Comment: What size of a service are you dealing with here?  Also, do you have outbuildings on your property, or plans for outbuildings for that matter, and is the service overhead or underground?
Comment: No outbuildings, nor any planned.  Installing new 200A buried entrance.
Comment: I take it there are no plans for accessory dwelling units or such either?
Comment: Single dwelling
Comment: Do you already have the main panel fitted, or are you going to be installing or procuring/installing a new one yourself?
Comment: Also, how do you plan to fit the solar feed into this setup?
Comment: Adding new main panel.   Planning to source tap PVC prior to main.
Answer: These questions got way off the intended topic.   My question was about the physical mounting of the meter box,  mounting blocks,  how to remove needed siding,  etc.
Over the weekend I carefully removed from and believe I can remove the siding panels I need without destroying my siding.


What is the best way to resize/crop an image on client side?

Question: I'm trying to crop and resize base64 jpeg image in the browser before uploading to the server. This is done regularly on 0.5 second intervals. Currently, I'm using HTML5 canvas to do so, except for the following problems:
1- Canvas is only supported on IE versions 9 and above.
2- Each time I set Image.src ="..."; in javascript, there's about 3MB added to IE's consumed memory (shown in task manager) apparently this is a known issue. My IE version is 10.
I tried cropping and resizing the image entirely in javascript but that was incredibly slow. (I used the javascript jpeg decoder at https://github.com/notmasteryet/jpgjs)
Given the above, what would be the best way to do this? Flash? other alternatives?
The problem with flash is that it's not supported on iphone, but I can overlook this for now. If flash is the way to go, is there any open source library to do so?
Comment: Why would you need to resize/crop image in a 0.5 second interval?
Comment: The image is a 640x480 camera snapshot sent to the server for object recognition. The image sent to the server must be scaled to a size < 10 KB for bandwidth considerations.
Comment: Is `` really not an option then? I think using "invisible canvas" can help soothing the stress.
Comment: If by invisible canvas you mean canvas with the visible property set to 'hidden', then yes, that's what I'm doing. Again, the problem with canvas is the memory leak on IE.
Answer: you should use php's GD2 librarie, but on server side
Comment: I have to resize on client side. The images are too big to be transmitted in original format every 0.5 sec.


regex match hyphen in string

Question: I have a regex \([0-9]+|\-)\ which either takes a number or a hyphen.
but if I use this to match something like -555 it still works because it matches the hyphen-. So I am wondering if there is a way to match the whole thing?
Answer: /^([0-9]+|\-)$/

The ^ means "at the beginning of the string line", and the $ means "at its end".
Edit: fixed the answer, thanks to luke-gru. As pointed out in the comments, \A is at the start of the string, \Z is at its end. The behavior of ^ and $ depends on whether multiline is enabled or not.
Comment: Just to be a dirty pedant, \A and \Z are beg. and end of string, while ^ and $ are beg. and end of line. Most of the time they're the same, but hitting the outlier sucks when you're not prepared for it.

regex match hyphen in string


SQL Trigger is only updating row after a second row is added

Question: Behavior:
If i add 1 row the JB_RECIEVED_DATE is not being updated.
DOC_TRACK_MAIN table after 1st insert
MRG_JOB_ID| JB_REC_DATE
---------------------------------
00001     | null

JOBS table
JOB_ID | JOB_REC_DATE
--------------------------------
00001  | JUN-9-1999
00002  | JUN-17-2001
00003  | JUN-23-2008

If I add a second row the JB_RECIEVED_DATE is eing updated in row 1 but row 2 is not updated.
DOC_TRACK_MAIN table after 2nd insert
MRG_JOB_ID| JOB_REC_DATE
---------------------------------
00001     | JUN-9-1999
00002     | null

If I add row n only row n-1 is updated.
DOC_TRACK_MAIN table after nth insert
MRG_JOB_ID| JOB_REC_DATE
---------------------------------
00001     | JUN-9-1999
00002     | JUN-17-2001
00003     | null

My code for the trigger:
CREATE OR REPLACE TRIGGER "DB_1"."TRG_INSERT_REC_DATE"
BEFORE INSERT ON DOC_TRACK_MAIN
FOR EACH ROW
BEGIN
    UPDATE DOC_TRACK_MAIN
    SET JB_RECEIVED_DATE = (SELECT JOB_RECEIVED_DATE FROM JOBS WHERE JOBS.JOB_ID=DOC_TRACK_MAIN.MRG_JOB_ID);
END;

Comment: Maybe it's because your trigger is firing BEFORE the insert?
Comment: The syntax appears to be Oracle but the question isn't tagged Oracle and no database is mentioned.  Are you actually using Oracle?
Comment: The issue was solved by creating a view that incorporates both tables.
Answer: Ok, this is what happens. Assume you have no record in your DOC_TRACK_MAIN table. As your Trigger is Before Insert, this means the Update statement won't find any row to update. After your first insert happens, you now have one record. When you insert another record to that table, Before inserting the trigger will go and update the only row that has a matching value in the JOBS table. When you insert the third record, the trigger will update the two previously inserted records and so on. So in fact, all your records are getting updated before you insert the next record, not the last one. It's really updating all the records, but you only notice the last one because, the last one was null before inserting the new one and the others had values from the JOBS table. It has the same effect of setting a column to its current value like this:
UPDATE TABLE1 SET COL1=COL1, COL2=COL2;

Will you notice the update if you do the above?
Comment: The issue was solved by creating a view that incorporates both tables, but your suggestion was answer that led us back to that conclusion. Thanks.
Answer: I'm not sure what DBMS this is, but if it's anything like a SQL Server trigger, you would need some identifier of the inserted data - as it is right now it looks like you're updating all data in the table every time the trigger fires.
In addition as the other answer/comments have stated, you're firing your trigger prior to inserting the record, so the newly inserted record is not impacted by the trigger.
The trigger all in all seems unnecessary in this instance - why not just change your insert statement to insert the date as well?
e.g.
insert into DOC_TRACK_MAIN (MRG_JOB_ID, JB_REC_DATE)
select '00003' , JOB_RECEIVED_DATE
FROM JOBS
WHERE JOBS.JOB_ID=DOC_TRACK_MAIN.MRG_JOB_ID

If that for some reason does not work for you, you'll need to look into your RDBMS' documentation for the "inserted" keyword that is referenced in triggers to affect only the data being manipulated, rather than the entire table's data.  Imagine if your table had 50 million rows in it, each time you made any inserts into the table an update on all 50 million rows would occur - even though they are (likely) being updated to the same value


How can I cancel a scheduled gift delivery on steam?

Question: I've set up a scheduled gift on steam. Now I want to recall it. How can I do that?
Comment: The question body is there for a reason, so you can give more detail. Don't just point back to the title.
Comment: @VanBuzzKill what could I still add? I want to cancel a scheduled delivery gift on steam
Comment: https://support.steampowered.com/kb_article.php?ref=6643-QEUV-0459?
Answer: EDIT: This answer is outdated. You'll find the late 2017 version of it here.

Old answer:

You go into your steam inventory.

The game should still be in your inventory, because it's not accepted yet. (It can't because it is scheduled) so:

You click on the game that is planned to be gifted

You click on "manage gift..."

Select "Return the gift to your account" and press "Next"

The result: The gift is back in your inventory and wont be gifted.


Methods for embedding Wordpress into Matrix?

Question: How can you embed Wordpress into Squiz Matrix? Not necessarily the whole instance, maybe just elements that will make life easier.
I was thinking about iframing but that seemed a little outdated - has anyone made a custom asset which allows you to use Wordpress? If not that should really be added Matrix.
Answer: yes, you can iframe the wordpress site in
Answer: You can achieve this using a remote content asset.
Documentation on how to use remote content assets can be found here.


Polymer + form POST data

Question: I have this
<form id="form_837299" class="appnitro"  method="post" action="insert.php"> <paper-input label="Title" name="title" maxlength="255">
            </paper-input>
          <paper-input floatinglabel multiline label="text" name="text"></paper-input>

            <input type="hidden" name="form_id" value="837299" />
            <input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />

      </form>

I have problem with POST data - nothing is sended in "text" and "title" (all in paper-input).
I modified the template and attribute "name" now is in one div, which Polymer created. But no data are sent.
print_r($_POST); shows me only this:
Array ( [form_id] => 837299 [submit] => Submit )
Anybody knows how use Polymer and Material UI on form?
Answer: Only elements that extend native form elements automatically get submitted with forms. paper-input extends core-input which has an input inside it as opposed to extending it. See this mailing list discussion for additional discussion and this StackOverflow post for possible solutions.
Something like this jsbin maybe?
Update: Here's the same thing in web component form.
Update: Looks like the creator of ajax-form has added this functionality.
Update: Also consider using iron-form.
Comment: "ajax-form is obsolete. Use iron-form instead" I disagree. iron-form is lacking a _lot_ of the capabilities that ajax-form has had for ages. Plus, iron-form is tied to Polymer. ajax-form has no dependencies.
Comment: In first link I find why I have a problem - text and title is in shadow-root and this is not sending in POST data.. And jsbin looks good! Thx
Comment: Awesome! FYI, the Polymer team is reportedly working on a `paper-form` element that may solve this problem automatically.
Comment: Looks like `paper-form` development is stalled (no commits since August).  The recommended way to submit Polymer custom form fields continues to be `ajax-form`.  Disclaimer: I'm the author of `ajax-form`.
Comment: Polymer's [`iron-form`](https://elements.polymer-project.org/elements/iron-form) covers most (if not all) features of `ajax-form`. Also, it looks like `ajax-form` depends on an obsolete version of Polymer.
Comment: @tony19 iron-form is lacking quite a few features that ajax-form includes. Also, ajax-form has no dependencies, while iron-form depends on Polymer.
Answer: According to the Polymer docs the way to do this is to just create a regular form input and wrap it in the <paper-input-decorator>
https://www.polymer-project.org/docs/elements/paper-elements.html#paper-input
I've tried it out and it works fine. Some better form support would be cool, but oh well. This stuff still kind of rocks.
UPDATE: I've built a bower package (polymer-rails-forms) to deal with forms in polymer, tailored specifically to the ActiveRecord input naming scheme but it will work with any old form really. It's still relatively new, but it covers most input types, basic validations, xhr and non-xhr submits and has a couple cool extras like image, json, and location* fields.
the location fields depend on the Google Map Places API

Polymer + form POST data


SQL Union do not show same emails, but other can be same

Question: I have this code:
$prikaz = mysql_query("select t.*
from (
      SELECT mesta_email, mesta_meno, mesto
      FROM mesta2014
      UNION
      SELECT mesta_email, mesta_meno, mesto
      FROM mesta2015
)
t left join mesta3 t3 on t.mesta_email = t3.mesta_email
where t3.mesta_email is null
")

I need to not show the same emails in results, even though the other columns (mesta_meno and mesto) are different. So there could be two rows with different information except for mesta_email = in result there has to be only one result. Can you help me please with solving this?
Comment: Does it matter which values of mesta_meno and mesto you want returned?  Can it be any of the rows' values?
Comment: The approach you would take will vary depending on if you wanted the most recent or least recent data (mesta_meno, mesto) per email, or don't care which year's data you get.
Answer: If the values of mesta_meno and mesto do not matter, then do the following:
$prikaz = mysql_query("select t.mesta_email, min(t.mesta_meno) as mesta_meno, min(t.mesto) as mesto
from (
      SELECT mesta_email, mesta_meno, mesto
      FROM mesta2014
      UNION
      SELECT mesta_email, mesta_meno, mesto
      FROM mesta2015
)
t left join mesta3 t3 on t.mesta_email = t3.mesta_email
where t3.mesta_email is null
group by t.mesta_email
")


Git will not ignore Gemfile.lock

Question: I have a Gemfile.lock that git simply will not ignore.  It's in my gitignore file (see below) but it keeps showing under unstaged changes whenever I bundle install.  Anyone else ever run into something like this?  Thanks in advance.
My Gitignore looks like this:
/.tags*
/log
/tmp
/db/*.sqlite3
/public/system
/coverage/
/spec/tmp
**.orig
rerun.txt
Gemfile.lock
...

Comment: Possible duplicate of [How to make Git "forget" about a file that was tracked but is now in .gitignore?](https://stackoverflow.com/questions/1274057/how-to-make-git-forget-about-a-file-that-was-tracked-but-is-now-in-gitignore)
Answer: Is it because the Gemfile.lock is already committed to your repository? Is it showing as a new file (with ?? in git status) or a modification (with M in git status). If it's the latter then you will need to remove the file with git rm Gemfile.lock. Once you commit that change then the file should stop showing up in git status.
As an aside, it's generally best practice to keep the Gemfile.lock committed to the repository (unless this is a gem). Here's a good SO question about that topic: Should Gemfile.lock be included in .gitignore?

Git will not ignore Gemfile.lock


Gridlock in Queueing Theory

Question: The following is a question from Pinksy and Karlin's $\textit{An Introduction to Stochastic Modelling}$:

Customers arrive at a service facility according to a Poisson process
  of rate λ. There is a single server, whose service times are
  exponentially distributed with parameter µ. Suppose that "gridlock"
  occurs whenever the total number of customers in the system exceeds a
  capacity C. What is the smallest capacity C that will keep the
  probability of gridlock, under the limiting distributing of queue
  length, below 0.001? Express your answer in terms of the traffic
  intensity ρ = λ/µ.

My approach is to simply the expression:
$$\pi_k = \lim\limits_{t\to \infty} \mathbf{P}(X(t)=k)<0.001$$
which simplifies to
$$(1-\frac{\lambda}{\mu})(\frac{\lambda}{\mu})^k <0.001$$
where $\pi_k$ is the limiting distribution of queue length.
From which, I will then obtain an inequality involving $\rho$. Am I on the right track, or do I have a conceptual misunderstanding? I am currently lost as well, so some insight and clarification will be appreciated.
Answer: What you have written is essentially the answer once you solve for $k$, which will be the value of $C$ that you are looking for once you make it an integer.
Really it seems to me that what your after is developing intuition; for this I always find it helpful to try plugging in values to Markov  chains and seeing if they make sense. Say $\lambda=1$ and $\mu=2$, so $\rho=\frac{1}{2}$ i.e. customers leave twice as fast as they arrive. Now, we want to look at the limiting distribution of how many people are in the queue. For $k$ people, we have the limiting distribution
$$\pi_k = (1-\rho)(\rho)^k = (\frac{1}{2})^{k+1}$$
Now, as we look at higher values of $k$, we are looking at longer queues. This should intuitively make sense, as when $k$ gets large our limiting distribution $\pi_k$ will get smaller. This question is essentially about finding the 'threshold' queue for $k$ where the limiting distribution is small enough.
Comment: Thank you for the clarification! And yes, I am trying to develop some intuition behind this, as I am still relatively new to this topic. Your explanation really helped clear my misconceptions!

Gridlock in Queueing Theory


Method to delete particular index in dynamic array

Question: Is there any other method to delete a particular index value from the dynamic array?
Here is my eg to delete index 2 of array a which I am storing it into array b
module top;
  bit[3:0] a [];
  bit[3:0] b [];
  int k=0;
  initial
  begin
    a={5,6,7,8,9};
    foreach (a[i])
      $display ("a[%0d]:%d",i,a[i]);
     b = new [a.size-1];
    foreach (a[i]) begin
      if (i == 2) begin
       continue;
      end
        b[k++] = a[i];
    end
    foreach (b[i])
      $display ("b[%0d]:%d",i,b[i]);
  end
endmodule

output:
a[0]: 5
a[1]: 6
a[2]: 7
a[3]: 8
a[4]: 9
b[0]: 5
b[1]: 6
b[2]: 8
b[3]: 9

Answer: No. Dynamic arrays are designed to be allocated as a whole. Queues are what you want—they are specifically designed for addition and deletion of one element at a time.
module top;
  bit[3:0] a [];
  bit[3:0] b [$];
  initial
  begin
    a={5,6,7,8,9};
    foreach (a[i])
      $display ("a[%0d]:%d",i,a[i]);
     b = a
     b.delete(2);
    foreach (b[i])
      $display ("b[%0d]:%d",i,b[i]);
  end
endmodule


jQuery Fancybox get id value of a

Question: what I'm trying to do is get the ID value of the referring a. The code for my a looks like:
<a class="photoBig" id="<?php echo $photo['id'] ?>" href="<?php echo $f->buildPhotoURL($photo, 'large') ?>" title="<?php echo $photo['title'] ?>">

I'm using phpFlickr to assign the ID's plus some various other things, which works fine.
So the code to open a Fancybox I use is:
$("a.photoBig").attr('rel', 'gallery').fancybox({
            'titleShow'     : true,
            'overlayOpacity' : 0.9,
            'overlayColor' : '#000',
            'autoScale' : false,
            'scrolling' : true,
            'titlePosition' : 'inside',
            'showNavArrows' : true,
            'cyclic' : true,
            'showCloseButton' : false,
            'titleFormat' : formatTitle
        });

then the function fomatTitle, which is:
function formatTitle(title, id, currentArray, currentIndex, currentOpts) {
    return '
' + (title && title.length ? '' + title + '' : '' ) + $(this).id + 'view full size
';
}

Everything works in this function except for this.id. Obviously I'm doing this wrong, so any help would be tops! Thank you.
Comment: I'm assuming there is more than one a tag on the page with the matching class?
Comment: Duplicate: http://stackoverflow.com/questions/2961496/fancybox-get-id-of-clicked-anchor-element.

See if that helps.
Comment: Yup there are a series of images with the same class. I tried the solution you linked to, but when the Fancybox pops up it just has "Id of element clicked 4093839" so that string of numbers is the ID I'm after but I want to put that ID into my formatTitle function, specifically into my a href.
Answer: Change
$(this).id
to
this.id
or
$(this).attr('id')
and see if that works.
EDIT: Okay, I've tested this and it works:
Use currentArray[currentIndex].id to get the id.
Alternatively, if all you wanted was the id so you could use it to point to your image, you could  just use $(this).attr('href') in it.
Comment: No go, it just returns "undefined".
Comment: I see that in your function, you are using both $(this).id and this.id. Did you try changing both of them to $(this).attr('id')? What do you mean returns undefined, is that what is said in the box or when you click the link?

jQuery Fancybox get id value of a


itemdatabound event of a nested listview

Question: I have a nested listview which I databind on the parent 'ItemDataBound' event, but how do i access/register the nested listview's itemdatabound event?
Thanks!
Edits
My parent listview itemdatabound now looks like so,
Protected Sub lvwManagePolicy_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvwManagePolicy.ItemDataBound

    If e.Item.ItemType = ListViewItemType.DataItem Then
        Dim rv As DataRowView = CType(e.Item.DataItem, DataRowView)

        Me.dsAccoutnTransactionHistory = Wrap.getWrapAccountTransactionHistory(rv!PLATFORM_ID, False)
        Dim lvwTransactionHistory As ListView = DirectCast(e.Item.FindControl("lvwTransactionHistory"), ListView)
        lvwTransactionHistory.ItemDataBound += New EventHandler(Of ListViewItemEventArgs)(lvwTransactionHistory_ItemDataBound)
        lvwTransactionHistory.DataSource = dsAccoutnTransactionHistory
        lvwTransactionHistory.DataBind()
    End If

End Sub

but i get an error

BC32022: 'Public Event ItemDataBound(sender As Object, e As
  System.Web.UI.WebControls.ListViewItemEventArgs)' is an event, and
  cannot be called directly. Use a 'RaiseEvent' statement to raise an
  event.
Answer: Before assigning the data to nested control in your parent control you can register the event like below under your parent ItemBoundData
ListView f = new ListView();
f.ItemDataBound += new EventHandler<ListViewItemEventArgs>(f_ItemDataBound);

protected void f_ItemDataBound(object sender, ListViewItemEventArgs e)
{

}

Answer: You can this :
  <asp:ListView onitemcommand="inner_ItemCommand" ...

protected / public item command method need :
  public void inner_ItemCommand(object sender,  ListViewCommandEventArgs e)
    {
        if (e.CommandArgument == "delete")
        {
            //do delete here
        }
    }


MIPS Linux assembler code understanding about load byte

Question: I have the following question here
I need to understand the following MIPS disassembling code:
.text:00489060             la      $v0, 0x4D0000

.text:00489064             la      $v0, 0x4D0000

.text:00489068             addiu   $v1, $v0, (aBig5 - 0x4D0000)  # "BIG-5"

.text:0048906C             lw      $v0, (aBig5 - 0x4D0000)($v0)  # "BIG-5"

.text:00489070             lbu     $a0, (aBig5+5 - 0x4D6A68)($v1)

.text:00489074             lbu     $v1, (aBig5+4 - 0x4D6A68)($v1)

.text:00489078             swl     $v0, 0($s1)

.text:0048907C             swr     $v0, 3($s1)

.text:00489080             sb      $a0, 5($s1)

.text:00489084             b       loc_48A190

.text:00489088             sb      $v1, 4($s1)

.text:0048908C  # ---------------------------------------------------------------------------

.text:0048908C

.text:0048908C loc_48908C:              # CODE XREF: cgiGetVar+B8j

.text:0048908C             lw      $v1, (dword_4D6A5C - 0x4D0000)($v0) #"ISO-"

.text:00489090             addiu   $v0, (dword_4D6A5C - 0x4D0000)

.text:00489094             lw      $a0, (dword_4D6A60 - 0x4D6A5C)($v0) #"8859"

.text:00489098             swl     $v1, 0($s1)

.text:0048909C             lbu     $a1, (byte_4D6A66 - 0x4D6A5C)($v0)  # zero byte

.text:004890A0             lbu     $a2, (byte_4D6A64 - 0x4D6A5C)($v0)  # "-"

.text:004890A4             lbu     $v0, (byte_4D6A65 - 0x4D6A5C)($v0)  # "1"

.text:004890A8             swr     $v1, 3($s1)

.text:004890AC             swl     $a0, 4($s1)

.text:004890B0             swr     $a0, 7($s1)

.text:004890B4             sb      $a1, 0xA($s1)

.text:004890B8             sb      $a2, 8($s1)

.text:004890BC             b       loc_48A190

.text:004890C0             sb      $v0, 9($s1)

.text:004890C4  #

The task I need to solve is, to change Web Language ID from BIG-5 to ISO-8859-5 in my router firmware manager (without sources :) ) So  ISO-8859-5 is 5 letters longer then BIG-5. I've moved the right hand (of BIG-5) text block in .rodata section )here is hex fragment:
  4d6a50:   68746d6c 63686172 73657400 49534f2d     htmlcharset.ISO-
  4d6a60:   38383539 2d310000 4249472d 35000000     8859-1..BIG-5...
  4d6a70:   53757043 484c616e 67000000 636f6e6e     SupCHLang...conn

& changed the pointer in .text section. However when I run the program it loads just 6 bytes (I see "ISO-88" instead of (ISO-8859-5) in HTML-code page of router. So I guess I have to find where is the number of developing bytes is fixed and change it. Could somebody comments this code. Thanks a lot :)
Comment: @plaes Thanks a lot, but these router doesn't like OpenWRT :) It likes vxWorks and ASUS blobs (WMVN25E2plus)
Answer: The number of bytes is not specified. It just loads a word and two bytes and that's it:
; load one word (4 bytes) into v0
lw      $v0, (aBig5 - 0x4D0000)($v0)
; load one byte into a0
lbu     $a0, (aBig5+5 - 0x4D6A68)($v1)
; load one byte into v1
lbu     $v1, (aBig5+4 - 0x4D6A68)($v1)
; store left part of the word from v0
swl     $v0, 0($s1)
; store right part of the word from v0
swr     $v0, 3($s1)
; store byte from a0
sb      $a0, 5($s1)
; store byte from v1
sb      $v1, 4($s1)

So it's basically fixed for a 5-char string and a longer one won't work without patching the code. You might be able to patch it for a 7-char one (8 bytes) by loading words and replacing the two sb by swl and swr. Another option, if you are certain that s1 is aligned, is to load three words (12 bytes) and store the latter two using just sw instead of swl/swr pair.
Comment: Thanks, I've tried to change sb->swl/swr, but without success :(Could you comment 2-nd part of these code (from 0048908C to down) It contains example of 10 bytes word using. And why is neсessary use swl/swr and sb, when program loads bytes (lbu $v1 (aBig5+5 -0x4D6a68)($v1) ) after loading word (lw)?