text:
Q: Java Double value = 0.01 changes to 0.009999999999999787
Possible Duplicate:
Why not use Double or Float to represent currency?

I'm writing a basic command-line program in Java for my high school course. We're only working with variables right now. It's used to calculate the amount of bills and coins of whatever type in your change after a purchase. This is my program:
class Assign2c {
    public static void main(String[] args) {
        double cost = 10.990;
        int paid = 20;
        double change = paid - cost;
        int five, toonie, loonies, quarter, dime, nickel, penny;

        five = (int)(change / 5.0);
        change -= five * 5.0;

        toonie = (int)(change / 2.0);
        change -= toonie * 2.0;

        loonies = (int)change;
        change -= loonies;

        quarter = (int)(change / 0.25);
        change -= quarter * 0.25;

        dime = (int)(change / 0.1);
        change -= dime * 0.1;

        nickel = (int)(change / 0.05);
        change -= nickel * 0.05;

        penny = (int)(change * 100);
        change -= penny * 0.01;

        System.out.println("$5   :" + five);
        System.out.println("$2   :" + toonie);
        System.out.println("$1   :" + loonies);
        System.out.println("$0.25:" + quarter);
        System.out.println("$0.10:" + dime);
        System.out.println("$0.05:" + nickel);
        System.out.println("$0.01:" + penny);
    }
}

It should all work but at the last step when there's $0.01 leftover, number of pennies should be 1 but instead, it's 0. After a few minutes of stepping into the code and outputting the change value to the console, I've found out that at the last step when change = 0.01, it changes to 0.009999999999999787. Why is this happening?

A: 0.01 does not have an exact representation in floating-point (and neither do 0.1 nor 0.2, for that matter).
You should probably do all your maths with integer types, representing the number of pennies.

A: doubles aren't kept in decimal internally, but in binary.  Their storage format is equivalent to something like "100101 multiplied by 10000" (I'm simplifying, but that's the basic idea).  Unfortunately, there's no combination of these binary values that works out to exactly decimal 0.01, which is what the other answers mean when they say that floating point numbers aren't 100% accurate, or that 0.01 doesn't have an exact representation in floating point.
There are various ways of dealing with this problem, some more complicated than others.  The best solution in your case is probably to use ints everywhere and keep the values in cents.

A: Using double for currency is a bad idea, Why not use Double or Float to represent currency?. I recommend using BigDecimal or doing every calculation in cents.

A: Floating point numbers are never 100% accurate (not quite true, see comments below). You should never compare them directly. Also integer rounding. The best way to do this would probably be to do it in cents and convert to dollars later (1 dollar == 100 cents). By converting to an integer you are losing precision.

A: As the others already said, do not use doubles for financial calculations.
This paper http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html (What Every Computer Scientist Should Know About Floating-Point Arithmetic) is a must-read to understand floating point math in computers.

A: its a float(double)
You should not use it to compute money....
I recommend using int values and operate on pennys

A: This is a problem that's arisen many times over. The bottom line is that on a computer that uses binary floating point (which Java requires), only fractions in which the denominator is a power of 2 can be represented precisely.
The same problem arises in decimal. 1/3, for example, turns into 0.3333333..., because 3 isn't a factor of 10 (the base we're using in decimal). Likewise 1/17, 1/19, etc.
In binary floating point, the same basic problem arises. The main difference is that in decimal, since 5 is a factor of 10, 1/5 can be represented precisely (and so can multiples of 1/5). Since 5 is not a factor of 2, 1/5 cannot be represented precisely in binary floating point.
Contrary to popular belief, however, some fractions can be represented precisely -- specifically those fractions whose denominators with only 2 as a prime factor (e.g., 1/8 or 1/256 can be represented precisely).

A: I'm sure you know that some fractions' decimal representations terminate (e.g. .01) while some don't (e.g. 2/3=.66666...). The thing is that which fractions terminate changes depending on what base you're in; in particular, .01 doesn't terminate in binary, so even though double provides a lot of precision it can't represent .01 exactly. As others said, using BigDecimal or fixed-point integer computations (converting everything to cents) is probably best for currency; to learn more about floating point, you could start at The Floating-Point Guide- What Every Programmer Should Know About Floating-Point Arithmetic.


text:
Q: How to fetch id from bottom-up approach in django ORM How to fetch id of Process and Client model in Emp_Process using Client_Process
Models.py
class Process(models.Model):
    Name = models.CharField(max_length=50)
    def __str__(self):
        return self.Name
    class Meta:
        db_table : 'process'

class Client(models.Model):
    Name = models.CharField(max_length=50, unique=True)
    def __str__(self):
        return self.Name
    class Meta:
        db_table : 'client'

class Client_Process(models.Model):
    process = models.ForeignKey(Process, on_delete=models.CASCADE)
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    class Meta:
        db_table : 'client_process'

class Emp_Process(models.Model):
    username = models.ForeignKey(Emp_Profile, on_delete=models.CASCADE)
    process = models.ForeignKey(Client_Process, on_delete=models.CASCADE)
    class Meta:
        db_table : 'emp_process'

A: Assuming you have you object, then why not just use?
process_id = object.process.id
client_id = object.process.client.id

redpajama_set_name: RedPajamaStackExchange


text:
Q: Semi-finite trace on a von Neumann algebra: Equivalent definitions Let $(N,\tau)$ be a semi-finite von Neumann algebra. This means that $\tau$ is a normal, faithful and semi-finite trace.
Normality means that $\tau(x) = \sup_i \tau(x_i)$ if $x \in N_+$ is the limit of an increasing net $x_i$ in $N_+$.
With $\tau$ one associates the following sets:
$$
N_\tau^+ := \{x \in N_+ : \tau(x) < \infty \}
$$
and
$$
 \mathscr L_\tau^1(N) := \{ x \in N : \tau(\lvert x \rvert) < \infty \}.
$$
The latter set is in fact a $*$-ideal and equals the complex linear span of $N_\tau^+$.
I read a few definitions of semi-finiteness and I wonder if these are all equivalent. Lets recall a few definitions:

*

*Every $0 \neq x \in N_+$ majorizes some $0 \neq y \in N_\tau^+$. (Takesaki: Theory of Operator Algebras I, p. 309)

*$\tau(x) = \sup \{ \tau(y) : y \leq x, \ y \in N_\tau^+ \}$ for $x \in N_+$. (Dixmier: von Neumann algebras p. 93)

*The $\sigma$-weak (=ultra weak) closure of $N_\tau^+$ equals $N_+$. (A. M. Bimkchentaev: On a Property of $L^p$ Spaces on Semifinite von Neumann Algebras)

*For all $x \in N_+$ there exists an increasing net $x_\alpha$ in $N_\tau^+$ with strong (SOT) limit $x$. (Edward Nelson: Notes on Non-commutative Integration)

I hope that all these definitions are equivalent for a normal tracial weight $\tau$ on a von Neumann algebra. By tracial I mean that $\tau(x^*x) = \tau(xx^*)$ for all $x \in N$. I am also wondering if the normality may be dropped to see the equivalence.
Maybe the following result is helpful (Haagerup): A weight on a von Neumann algebra is normal iff it is ultra weakly lower semi-continuous.

A: $1\iff4$ : Assume $1$. Given $x\in N_+$, there exists nonzero $y\in N_\tau^+$ with $y\leq x$. Now use Zorn to find a maximal ordered family $\{y_j\}\subset N_\tau^+$ with $y_j\leq x$ for all $j$. As the net is bounded, it has a sup, say $y=\lim_{sot}y_j$. Then $y=x$, because otherwise a nonzero element of $N_\tau^+$ below $y-x$ contradicts the maximality. The converse is trivial, just take some $x_\alpha$.
$3\iff 4$ : note that $4$ implies $3$ directly. For the converse, note that $N_\tau^+$ is convex, and so its wot closure agrees with its sot closure. And a $\sigma$-weak limit is in particular a wot limit, so $3$ implies $4$.
$4\implies 2$ : this follows directly by definition of normality.
$2\implies 1$ : if $x\in N_+$ does not majorize nonzero elements of $N_\tau^+$, then by $2$ we have $\tau(x)=0$. Then faithfulness implies $x=0$.


text:
Q: How to check if .xls and .csv files are empty Question 1: How can I check if an entire .xls or .csv file is empty.This is the code I am using:
try:
    if os.stat(fullpath).st_size > 0:
       readfile(fullpath)
    else:
       print "empty file"
except OSError:
    print "No file"

An empty .xls file has size greater than 5.6kb so it is not obvious whether it has any contents. How can I check if an xls or csv file is empty?
Question 2: I need to check the header of the file. How can I tell python that files which are just a single row of headers are empty?
import xlrd
def readfile(fullpath)
    xls=xlrd.open_workbook(fullpath)
    for sheet in xls.sheets():
        number_of_rows = sheet.nrows
        number_of_columns = sheet.ncols
        sheetname = sheet.name
        header = sheet.row_values(0) #Then if it contains only headers, treat it as empty.

This is my attempt. How do I continue with this code?
Please provide a solution for both questions. Thanks in advance.

A:
Question 1: How I check the entire .xls file are empty.

def readfile(fullpath):

    xls = xlrd.open_workbook(fullpath)

    is_empty = None

    for sheet in xls.sheets():
        number_of_rows = sheet.nrows

        if number_of_rows == 1:
            header = sheet.row_values(0)
            # then If it contains only headers I want to treat as empty
            if header:
                is_empty = False
                break

        if number_of_rows > 1:
            is_empty = False
            break

        number_of_columns = sheet.ncols
        sheetname = sheet.name

    if is_empty:
        print('xlsx ist empty')

Question 2: How I check header of the file .If the file has only a header(I mean only a single row) I need to treat the file is empty .How can I do that.

import csv
with open('test/empty.csv', 'r') as csvfile:
    csv_dict = [row for row in csv.DictReader(csvfile)]
    if len(csv_dict) == 0:
        print('csv file is empty')

Tested with Python:3.4.2

A: This is simple in pandas with the .empty method. Do this
import pandas as pd

df = pd.read_csv(filename) # or pd.read_excel(filename) for xls file
df.empty # will return True if the dataframe is empty or False if not.

This will also return True for a file with only headers as in
>> df = pd.DataFrame(columns = ['A','B'])
>> df.empty
   True

A: I don't think Stackoverflow allows 2 question at the time but let me give you my answer for the Excel part
import xlrd
from pprint import pprint

wb = xlrd.open_workbook("temp.xlsx")

empty_sheets = [sheet for sheet in wb.sheets() if sheet.ncols == 0]
non_empty_sheets = [sheet for sheet in wb.sheets() if sheet.ncols > 0]

# printing names of empty sheets
pprint([sheet.name for sheet in empty_sheets])

# writing non empty sheets to database
pass # write code yourself or ask another question

About the header: let me give you a little hint, test for sheet.nrows == 1.

A: For your excel code, I like the pandas solution someone came up with but if you are at work and can't install it, then I think you were almost there with the code approach you were taking.  You have a loop traversing each sheet.  So you can test the rows in each sheet and then take appropriate action if empty like so:
import xlrd

xlFile = "MostlyEmptyBook.xlsx"

def readfile(xlFile):
    xls=xlrd.open_workbook(xlFile)
    for sheet in xls.sheets():
        number_of_rows = sheet.nrows
        number_of_columns = sheet.ncols
        sheetname = sheet.name
        header = sheet.row_values(0) #then If it contains only headers I want to treat as empty
        if number_of_rows <= 1:
            # sheet is empty or has just a header
            # do what you want here
            print(xlFile + "is empty.")

Note:  I added a variable for the filename to make it easier to change in one place throughout the code when used.  I also added : to your function declaration which was missing it.  If you want the test to be has header only (mine includes completely blank page), then change <= to ==.
Regarding the related csv issue.  csv is just a text file.  We can be reasonably certain a file is empty except for the header using a coding approach like the one that follows.  I would try this code on a sample of files, and you may want to adjust my math logic.  For example, it may be sufficient to use + 1 on the if comparison instead of *1.5 as I have it.  My thinking is with white space or if a few characters were mistakenly included this would be a good file size cushion + the chars on second line test given in the coding logic.
This was written on the assumption you want to know if the file is empty before you load some giant file into your computer.  If that assumption is wrong, you can use my test logic and then keep the file open, or even read in more code to make sure there isn't a blank line followed by additional content after the header (in a badly formatted input file):
import os

def convert_bytes(num):
    """
    this function will convert bytes to MB.... GB... etc
    """
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return "%3.1f %s" % (num, x)
        num /= 1024.0

def file_size(file_path):
    """
    this function will return the file size
    """
    if os.path.isfile(file_path):
        file_info = os.stat(file_path)
        return convert_bytes(file_info.st_size)

# testing if a csv file is empty in Python (header has bytes so not zero)

fileToTest = "almostEmptyCSV.csv"

def hasContentBeyondHeader(fileToTest):
    answer = [ True, 0, 0, 0]
    with open(fileToTest) as f:
        lis = [ f.readline(), f.readline() ]
        answer[1] = len(lis[0])                # length header row
        answer[2] = len(lis[1])                # length of next row
        answer[3] = file_size(fileToTest)      # size of file

        # these conditions should be high confidence file is empty or nearly so
        sizeMult = 1.5   # test w/ your files and adjust as appropriate (but should work)
        charLimit = 5

        if answer[1] * sizeMult > answer[2] and answer[2] == 0:
            answer[0] = False
        elif answer[1] * sizeMult > answer[2] and answer[2] < charLimit:
            # separate condition in case you want to remove it
            # returns False if only a small number of chars (charLimit) on 2nd row
            answer[0] = False
        else:
            answer[0] = True   # added for readability (or delete else and keep default)

        f.close()
    return answer

hasContentBeyondHeader(fileToTest)  # False if believed to be empty except for header

During testing, the readline commands extracted this content from the file:
['year,sex,births\n', '']

sample output:
[True, 16, 0, '17.0 bytes']

This approach means you can access the results of the test which are True/False in [0] element of the list it returns.  The additional elements allow you to get info on the inputs to the program's decision-making in case you want to tweak it later.
This code starts with a custom file size function.  You can probably replace that with this depending on your preferences if you are looking for shorter code. This would replace the first two tiny functions:
import os
os.path.getsize(fullpathhere)

A: what about something like this :
file = open(path, "r")
file_content = file.read()
file.close()
if file_content == "":
    print("File '{}' is empty".format(path))
else:
    rows = file_content.split("\n", 1)
    if rows[1] == "":
        print("File '{}' contains headers only.".format(path))

where path is the path of your xls or csv file.

A: For your question:

Question 2: I need to check the header of the file. How can I tell python that files which are just a single row of headers are empty?

You can just check the line in files.
with open('empty_csv_with_header.csv') as f:
    f.readline()  # skip header
    line = f.readline()
    if line == b'':
        print('Empty csv')

A: Try this solves the problem.
Not all empty CSV files are 0 bytes. This works in that condition also.
import os
from os.path import isfile
import pandas

if isfile(PASSWORD_MANAGER_FILE):
    try:
        pandas.read_csv(PASSWORD_MANAGER_FILE)
    except pandas.errors.EmptyDataError:
        os.remove(PASSWORD_MANAGER_FILE)


text:
Q: How to cout with input in c++? Hello guys actually i want to show output with input

e.g:
int main()

   int a, b, c;

    cin >>a >>b;
c = a-b;

cout <<"Here would be input e.g: 4+5=" << c <<endl;
cout <<"Here would be input e.g: 4-5=" << e <<endl;

If input is in this format a+b and user enter input's then output show after input like this 4+5= and after equal answer would there. Thanx in advance

A:     cout << "Here would be input e.g: " << a << "+" << b<<"=" << c << endl;
    cout << "Here would be input e.g: " << a << "-" << b<<"=" << e << endl;

A: Add the input variables in the cout command as follows:

cout << a << " + " << b<<" = " << c << endl;


text:
Q: SharePoint list How to restrict input value format I have a column with name Secure in my SharePoint list. And I want to set validation in that column as below mentioned conditions. and if any user not entered in that format than , he will not able to save the form.
Condition :-

*

*it should contain total 12 characters

*first four character should be Alphabet (i.e. A to Z)

*next 4 characters should be any number between 0 to 9

*next 4 character should follow DDMM format (i.e. DD should allow maximum value 31/30/29/28 as per month and MM should between 01 to 12)

A: Because there is no clear year information, it is impossible to tell whether February is 28 or 29 days.
However, you could create three columns to achieve your plan:
Please the following steps:

*

*Column1: Test[Single line of text]

In the Test field, you must to enter 8 characters:

*

*The first 4 characters are uppercase letters

*The last 4 characters are numbers from 0 to 9

Formula:
=AND(LEN(Test)=8,CODE(MID(Test,1,1))>64,CODE(MID(Test,1,1))<91,CODE(MID(Test,2,1))>64,CODE(MID(Test,2,1))<91,CODE(MID(Test,3,1))>64,CODE(MID(Test,3,1))<91,CODE(MID(Test,4,1))>64,CODE(MID(Test,4,1))<91,CODE(MID(Test,5,1))>47,CODE(MID(Test,5,1))<58,CODE(MID(Test,6,1))>47,CODE(MID(Test,6,1))<58,CODE(MID(Test,7,1))>47,CODE(MID(Test,7,1))<58,CODE(MID(Test,8,1))>47,CODE(MID(Test,8,1))<58)

*Column2: Date[Date and Time]

*Column3:IDs[Calculated]

The IDs field automatically generates a unique identifier based on the value of the Test field and the Date field, without your manual operation.
Formula:
=Test&TEXT(Date,"ddmm")

Have a nice day!


text:
Q: Refresh State in Action Bar Sherlock i want to rotate refresh in actionbarsherlock.previously i was using actionbar and was doing setRefreshActionItemState.

A: For refresh state you may try this link to get the answer Refresh menu item animation in ActionBarSherlock..
case R.id.refreshMenuItem:
    isRefreshing = true;
    item.setActionView(R.layout.action_bar_indeterminate_progress);
    ImageView iv = (ImageView) item.getActionView().findViewById(R.id.loadingImageView);
    ((AnimationDrawable) iv.getDrawable()).start();


text:
Q: java-Thymeleaf: how get next date? I want list like:

2017-01-31

2017-02-01

2017-02-02

Now I have only first li:

th:text="${#dates.format(#dates.createToday(), 'yyyy-MM-dd')

How to get next date ( like: #dates.createToday() + "1 day")?

A: This is something that thymeleaf just doesn't do well... that being said, if you include common-lang3 in your pom, you can get it working like this:
POM:
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.5</version>
</dependency>

Thymeleaf:

I would recommend that you add the dates in your controller (creating them in the java, which is easy), and then just loop and format in thymeleaf.


text:
Q: SQLAlchemy ORM: Filter by multiple include/exclude matches on many-to-many relationship I'm trying to use an SQLite database via SQLAlchemy 1.4 ORM to filter data based on relationships.
Data
My example data consists of groups and members in a simple many-to-many schema:
[...]
member_f = Member(name="F")

group_1 = Group(name="1", members=[member_a, member_b, member_c])  <-- find this group via member names
group_2 = Group(name="2", members=[member_a, member_b, member_f])
group_3 = Group(name="3", members=[member_a, member_c, member_d])
group_4 = Group(name="4", members=[member_d, member_e, member_f])
[...]

Full running example code (schema, objects, queries):

from sqlalchemy import Table, Column, Integer, String, ForeignKey
from sqlalchemy import create_engine, select, func, text, and_
from sqlalchemy.orm import relationship, declarative_base, sessionmaker

engine = create_engine("sqlite+pysqlite:///:memory:", future=True, echo=False)
Session = sessionmaker(bind=engine, future=True)

# Schema

Base = declarative_base()

groups_members = Table("groups_members", Base.metadata,
    Column("group_id", ForeignKey("groups.id")),
    Column("member_name", ForeignKey("members.name")),
)

class Group(Base):
    __tablename__ = "groups"
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String, nullable=False)
    members = relationship("Member", secondary=groups_members, backref="groups", lazy="subquery")

    def __repr__(self):
        return f"<Group: {self.name}>"

class Member(Base):
    __tablename__ = "members"
    name = Column(String, primary_key=True)

    def __repr__(self):
        return f"<Member: {self.name}>"

Base.metadata.create_all(engine)

# Objects

member_a = Member(name="A")
member_b = Member(name="B")
member_c = Member(name="C")
member_d = Member(name="D")
member_e = Member(name="E")
member_f = Member(name="F")

group_1 = Group(name="1", members=[member_a, member_b, member_c])
group_2 = Group(name="2", members=[member_a, member_b, member_f])
group_3 = Group(name="3", members=[member_a, member_c, member_d])
group_4 = Group(name="4", members=[member_d, member_e, member_f])

print(f"{member_a}: {member_a.groups}")  # OK

with Session() as session:
    session.add(group_1)
    session.add(group_2)
    session.add(group_3)
    session.add(group_4)

    session.commit()

    print(session.query(Group).all())  # OK

# Query users example

def get_members_in_more_than_2_groups():
    with Session() as session:
        return session.execute(
            select(Member, func.count(groups_members.columns.group_id).label('group_members_count'))
            .join(groups_members)
            .group_by(Member.name)
            .having(text('group_members_count > 2'))
        ).all()

for m in get_members_in_more_than_2_groups():
    print(m)  # OK

# Query groups problem: associated with A and B but not with E or F

def get_groups_by_member_names(member_names_included, member_names_excluded):
    with Session() as session:
        included = session.execute(select(Member).where(Member.name.in_(member_names_included))).all()
        excluded = session.execute(select(Member).where(Member.name.in_(member_names_excluded))).all()

        return session.execute(
            select(Group)
            .join(Group.members)
            .where(
                and_(
                    Group.members.contains(included),
                    ~Group.members.contains(excluded),
                )
            )
            .group_by(Group.id)
        ).scalars().all()

for g in get_groups_by_member_names(member_names_included=["A", "B"], member_names_excluded=["E", "F"]):
    print(g)  # Expected output: <Group: 1>

Goal
Now I'm trying to find all groups that

*

*have both members with the names A and B (that's groups 1 and 2)

*and don't have any member named E or F (removing group 2)

resulting in just group 1.
Problem
The relevant (and failing) function in the example code is get_groups_by_member_names and with my lack of database knowledge, I'm quite stuck.
Most existing questions that I could find on SO only need to filter by one relationship value. But I need them to consider the lists of included and excluded member names.
I have tried to get the members as SQLAlchemy objects first and inserting those into the query but without any luck. I may have done that completely wrong, though.
I also tried joining the tables, filtering with the names list and counting the grouped results... It's hard for me to tell whether I'm on the right track or not at all.
Running over all groups in Python and applying the filtering there would be my fallback workaround. But with many items, the database can probably handle it more efficiently.
Any help greatly appreciated, I am happy with anything that works. I could probably also work my way up from a functioning SQL statement.
Thanks for your time!

Edit 1:
I found this answer https://stackoverflow.com/a/21104689/5123171 and while it works on small data sets, it's terribly slow on larger ones (about 60 seconds for 500 members and 10k groups):
def get_group_by_members(member_names_included, member_names_excluded):
    with Session() as session:
        return session.query(Group).join(groups_members).filter(
            groups_members.columns.member_name.in_(member_names_included)).group_by(Group.id).having(func.count(groups_members.columns.member_name) == len(member_names_included),
        ).filter(
            ~Group.members.any(Member.name.in_(member_names_excluded)),
        ).all()

A: Ok, here's what I ended up with via trial & error in an SQL editor. This is faster than the previous attempt (50 milliseconds on the same data).
The comments in the code correspond to the following steps:

*

*Find groups containing excluded members

*Filter those out of the assignment table

*Filter remaining assignment table by included members

*Group by group IDs

*Return all remaining groups matching the number of included members

SQL
SELECT * FROM groups
WHERE id IN (
    SELECT group_id FROM groups_members
    WHERE member_name IN ("A", "B")                                     // 3.
    AND group_id NOT IN (                                               // 2
        SELECT group_id FROM groups_members
        WHERE member_name IN ("E", "F")                                 // 1.
    )
    GROUP BY group_id                                                   // 4.
    HAVING count(member_name) == 2                                      // 5.
)

SQLAlchemy
session.query(Group)
.where(Group.id.in_(
    session.query(groups_members.c.group_id)
    .where(
        groups_members.c.member_name.in_(member_names_included),         # 3.
        groups_members.c.group_id.not_in(                                # 2.
            session.query(groups_members.c.group_id).where(
                groups_members.c.member_name.in_(member_names_excluded)  # 1.
            )
        ),
    )
    .group_by(groups_members.c.group_id)                                 # 4.
    .having(
        func.count(groups_members.c.member_name)
        == len(member_names_included)                                    # 5.
    ))
)
.all()

And the full running example in one piece:

from sqlalchemy import Table, Column, Integer, String, ForeignKey
from sqlalchemy import create_engine, select, func, text, and_, not_
from sqlalchemy.orm import relationship, declarative_base, sessionmaker

engine = create_engine("sqlite+pysqlite:///:memory:", future=True, echo=False)
Session = sessionmaker(bind=engine, future=True)

# Schema

Base = declarative_base()

groups_members = Table(
    "groups_members",
    Base.metadata,
    Column("group_id", ForeignKey("groups.id")),
    Column("member_name", ForeignKey("members.name")),
)

class Group(Base):
    __tablename__ = "groups"
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String, nullable=False)
    members = relationship(
        "Member", secondary=groups_members, backref="groups", lazy="subquery"
    )

    def __repr__(self):
        return f"<Group {self.id}: {self.name}>"

class Member(Base):
    __tablename__ = "members"
    name = Column(String, primary_key=True)

    def __repr__(self):
        return f"<Member: {self.name}>"

Base.metadata.create_all(engine)

# Objects

member_a = Member(name="A")
member_b = Member(name="B")
member_c = Member(name="C")
member_d = Member(name="D")
member_e = Member(name="E")
member_f = Member(name="F")

group_1 = Group(name="1", members=[member_a, member_b, member_c])
group_2 = Group(name="2", members=[member_a, member_b, member_f])
group_3 = Group(name="3", members=[member_a, member_c, member_d])
group_4 = Group(name="4", members=[member_d, member_e, member_f])

with Session() as session:
    session.add(group_1)
    session.add(group_2)
    session.add(group_3)
    session.add(group_4)

    session.commit()

# Query

member_names_included = ["A", "B"]
member_names_excluded = ["E", "F"]

# Raw SQL variant

with Session() as session:
    result = session.execute(
        f"""
            SELECT * FROM groups
            WHERE id IN (
                SELECT group_id FROM groups_members
                WHERE member_name IN ("A", "B")
                AND group_id NOT IN (
                    SELECT group_id FROM groups_members
                    WHERE member_name IN ("E", "F")
                )
                GROUP BY group_id
                HAVING count(member_name) == 2
            )
    """
    ).all()

    groups = [Group(**r) for r in result]

    for r in groups:
        print(f'SQL {r}')

# ORM Variant

with Session() as session:
    result = (
        session.query(Group)
        .where(
            Group.id.in_(
                session.query(groups_members.c.group_id)
                .where(
                    # Matching any included members
                    groups_members.c.member_name.in_(member_names_included),
                    # Removing any groups containing excluded members
                    groups_members.c.group_id.not_in(
                        session.query(groups_members.c.group_id).where(
                            groups_members.c.member_name.in_(member_names_excluded)
                        )
                    ),
                )
                # This is to make sure that all included members exist in a group, not just a few
                .group_by(groups_members.c.group_id)
                .having(
                    func.count(groups_members.c.member_name)
                    == len(member_names_included)
                )
            )
        )
        .all()
    )

    for r in result:
        print(f'ORM {r}')

I hope this is helpful to anyone and if you have suggestions for improvement, please let me know.


text:
Q: What is the best way prevent duplicate records in a SQL Server database what is the best way to prevent duplicate records in a SQL Server database? Using triggers? Using a unique constraint?

A: Use unique constraints on one or more columns in the table.
Example:
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL UNIQUE,
FirstName varchar(255) NOT NULL UNIQUE,
Address varchar(255),
City varchar(255)
)

Alter existing table as below
ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)

If you are using a front-end application to populate the table in the database. Do your validation select query from the application on the database to check for duplicates before inserting into the database. Using constraints will prevent duplicates by throwing an exception.
Note: The above example is SQL SERVER, Oracle, ms access
For much more indepth solution see How to prevent duplicate records being inserted with SqlBulkCopy when there is no primary key

A: If you don't want error throw from unique constraint and you also want database to receive duplicated data but insert nothing. You may look at merge statement
https://technet.microsoft.com/en-us/library/bb522522%28v=sql.105%29.aspx?f=255&MSPPError=-2147217396


text:
Q: 4Gb sd recognized as 1.6Gb I used as dd command to make my 4GB sd card bootable for arch linux arm as explained here since it didn't work I tried formatting the card in my ubuntu again but now it recognizes it as a 1.6GB card and a 32MB card.
Is there any way I can restore my card?

A: The dd command has the effect of creating whatever partition or partitions are in the image file you start with (i.e., the file given after if=). Those partitions' sizes are not determined by the size of the disk being written to (i.e., the disk specified after of=). When the disk is larger than necessary, it will have unpartitioned space after being written to with dd. Reformatting the partitions that already exist does not change their size and consequently will not make the extra space accessible.
Repartitioning the SD card is the solution. Install the gparted  package.  Assuming there is nothing of any value on the SD card, you can use GParted to delete the existing partitions (or to create a new partition table, which will get rid of them too). After the gparted package is installed you can run GParted by typing it into the dash (press the Super/Windows key or click the home button on the upper-left corner of the screen, then start typing in gparted until the GParted icon appears; then click on it).
Make sure you are editing the partitions on the SD card, and not on some other drive; if you accidentally perform actions on the wrong drive with GParted, you could experience great data loss. (And if you ever do need to modify the partitions on the physical disk that contains the running Ubuntu system, it's not safe to run GParted from the system on that disk to do that. Instead, for that purpose, you must run GParted from a live CD/DVD/USB instead.)
To make sure you're on the SD card and not some other device, select in from the drop-down menu at the upper-right corner of the GParted window. Make sure its partitions are the same size and type as you expected. An SD card will typically be called /dev/mmcblkN, where N is a number (usually 0, if you only have one SD card). The device names for the partitions on an SD card called /dev/mmcblk0 are called /dev/mmcblk0p1, /dev/mmcblk0p2, and so forth. You can verify that the drive name takes the form /dev/mmcblkN in the drop-down menu where you select it, and also that its partitions are listed as the device name with pN appended.
Once you've verified that you're working on the right disk, create whatever partition(s) you want. If you want one big partition, create one, of whatever partition type you prefer. (Most SD cards are formatted FAT32.)

A: Open disk utility in ubuntu to view, modify and configure disks and media. Just unmount it first before formatting. Hope it help!


text:
Q: Is it possible to call the function by using the datagrid column? Is it possible to call the function by using the datagrid column item?
I want to call the function while the user click the particular column item in the datagrid?
Thank's in advance...

A: You have to assign an eventhandler on the datagrid, and use a switch, which calls a function based on what you clicked on.
myDataGrid.addEventListener(DataGridEvent.ITEM_FOCUS_IN,clickFunction);

    private function clickFunction(e:DataGrigEvent):void
    {
        switch(e.label)
        {
             case 'function1': function1(); break;
             case 'function2': function2(); break;
             ...
        }

    }


text:
Q: Proving that a function's image contains (1/n,...,1/n) This question is a follow-up to a previous question answered by Neil Strickland:
Map from simplex to itself that preserves sub-simplices
Let $B$ denote the closed unit ball in $\mathbb{R}^2$ and let $\Delta_{n-1}$ denote the $(n-1)$-simplex.  I have a continuous function $f(x_1,\dots,x_n):B^n \rightarrow \Delta_{n-1}$ defined for all subsets $\lbrace x_1,\dots,x_n\rbrace \subset B$ of size $n$ that satisfy $x_i \neq x_j$ for all pairs $i,j$ (in other words, the function is only defined if all of the $n$ arguments are distinct).  This function has the property that, if $\sigma$ denotes a permutation, then $f(\sigma(x_1,\dots,x_n)) = \sigma(f(x_1,\dots,x_n))$. In other words, permuting the arguments of the function merely permutes the output.  My question is:  are there non-trivial sufficient conditions on $f$ under which the point $(1/n , \dots, 1/n)$ lies in the image of this map?  (or, even better, is this always the case?)
Here's one property of the map $f$ that I can add regarding the requirement that arguments be distinct:  if $\lbrace \mathbf{x}_k \rbrace$ is a sequence of $n$-tuples (with distinct entries) in $B$ that converges to an $n$-tuple $\bar{\mathbf{x}}$ with (possibly) non-distinct entries, then the limit of $f(\mathbf{x}_k)$ exists if and only if, for each pair of entries $x_i^k$ and $x_j^k$ in the $n$-tuple, the unit direction vector from $x_i^k$ to $x_j^k$ (i.e. $\frac{x_i^k - x_j^k}{||x_i^k - x_j^k||}$) has a limit.

A: This isn't an answer to your question but rather a comment that is too long for a comment. I once tried to solve what was then an open problem called the Knaster hypothesis. It's a beautiful and highly plausible statement: that if $f$ is a continuous function defined on the sphere $S^n$ and $x_1,\dots,x_{n+1}$ are points in $S^n$, then there is an orthogonal map $T\in SO(n+1)$ such that $f(Tx_1)=\dots=f(Tx_{n+1})$. One reason for being interested in the conjecture was that, as observed by Milman, it easily implies Dvoretzky's theorem with an essentially optimal bound in all parameters.
When $n=1$ we have two points in the circle and the result can be proved by an easy application of the intermediate value theorem. When $n=2$ the result is true but nothing like so easy. In that case we can think about the map from $SO(3)$ to $\mathbb{R}^3$ that takes $T$ to the triple $(f(Tx_1),f(Tx_2),f(Tx_3))$. This map is continuous, and if $f$ is a counterexample to the Knaster hypothesis then the image of this map does not intersect the line $x=y=z$. So one can hope to try to prove the result by contradiction, showing that the image somehow "surrounds" the line $x=y=z$ enough to be forced to contain it (just as a map from the closed disc to itself that preserves the boundary must map something to the centre of the disc). It is this that I am reminded of by your question, though I don't claim that there is a close connection.
If I remember correctly a proof along those lines can be given when $n=2$, but the conjecture in general turned out to be false. This interesting (but slightly disappointing since the hypothesis would have been such a nice theorem) result was proved by Kashin and Szarek. Their function $f$ was just the $\ell_\infty$ norm. The set of points was slightly more complicated but not too bad.

A: This turns out to be a remarkably interesting question.  I don't have a complete answer but here is a start.
First, for any space $X$ I'll write $F_n(X)\subset X^n$ for the space distinct $n$-tuples.  The question asks whether there exist $\Sigma_n$-equivariant maps  $f:F_n(B^2)\to\Delta_{n-1}$ with the fixed point $b=(1/n,\dotsc,1/n)$ not in the image.  If there is such a map then we can push it away from $b$ to the boundary of $\Delta_{n-1}$, which is homeomorphic to $S^{n-2}$.  On the other side, there is an obvious embedding $i:B\to\mathbb{R}^2$ and one can choose an embedding $j:\mathbb{R}^2\to B$ such that $ij$ and $ji$ are isotopic to the respective identity maps; using this we see that $F_n(B^2)$ is equivariantly homotopy equivalent to the space $X=F_n(\mathbb{R}^2)$.  This space is well-known: the following paper is one entry point to the literature:
\bib{MR1344842}{article}{
   author={Cohen, F. R.},
   title={On configuration spaces, their homology, and Lie algebras},
   journal={J. Pure Appl. Algebra},
   volume={100},
   date={1995},
   number={1-3},
   pages={19--42},
   issn={0022-4049},
   review={\MR{1344842 (96d:55005)}},
   doi={10.1016/0022-4049(95)00054-Z},
}

In particular:

*

*$\pi_1(X)$ is the pure braid group $Br_n$ on $n$ strings.  Moreover, the higher homotopy groups are trivial, so $X$ is the classifying space $BBr_n$.

*$X$ has an equivariant deformation retract $X_0$ that is a finite simplicial complex of dimension $n-1$.  This means that $H^k(X)=0$ for $k>n-1$.

*The cohomology of $X$ is completely known, together with the action of $\Sigma_n$.  In particular, the top group $H^{n-1}(X)$ is the module known as $\text{Lie}(n)$ (or maybe the dual of that?).  As a $\mathbb{Z}[\Sigma_{n-1}]$-module this is free of rank one, but the $\Sigma_n$-action is harder to describe.  The standard description also implies that all Steenrod operations in $H^*(X_0;\mathbb{Z}/p)$ are trivial.
If we can show that there is no $\Sigma_n$-equivariant map from $X_0$ to $S^{n-2}$ then we will be done.
In the case $n=2$ we just have $X_0=S^1$ and $S^{n-2}=S^0$ with $\Sigma_2$ acting antipodally on both sides: it is clear that there is no equivariant map, as required.
In the case $n=3$ we have $S^{n-2}=S^1=K(\mathbb{Z},1)$, so the nonequivariant mapping set is $[X_0,S^1]=H^1(X_0)$, and one can check that this is just $\mathbb{Z}^3$ with the action given by permuting the coordinates and multiplying by the signature.  The only fixed point for this action is zero, so any map $X_0\to S^1$ that is equivariant-up-to-homotopy is nonequivariantly homotopic to a constant map.  Here the action of $\Sigma_3$ on $S^1$ is generated by a reflection and a rotation through $2\pi/3$, so there are no fixed points.  This means that constant maps $X_0\to S^1$, although equivariant-up-to-homotopy, cannot be equivariant on the nose.  I suspect that there are no equivariant maps, and it should be possible to prove this by equivariant obstruction theory (ie working up the skeleta of $X_0$) but I do not see the details at the moment.
For $n>3$ we still have an evident map $[X_0,S^{n-2}]\to H^{n-2}(X_0)$, but it need not be bijective.   We can compare $S^{n-2}$ with the fibre of the map $Sq^2:K(\mathbb{Z},n-2)\to K(\mathbb{Z}/2,n)$, recalling that $Sq^2$ acts trivially on $H^*(X_0)$, which should give an explicit description of $[X_0,S^{n-2}]$.  With a bit of representation theory we should be able to calculate the group of equivariant-up-to-homotopy maps $X_0\to S^{n-2}$.  We would then need some equivariant obstruction theory to improve this to understand whether there are any equivariant maps.  Because $\Sigma_n$ acts freely on $X_0$ and $S^{n-2}$ is nonequivariantly $(n-3)$-connected and $X_0$ is $(n-1)$-dimensional, this obstruction theory will only involve the last two or three skeleta of $X_0$, so it should hopefully be tractable.

A: Let me rephrase the question and give a complete answer:
What are conditions for the existence of a $\Sigma_n$-equivariant map
$$f: F_n(B)\to \Delta_{n-1}\backslash(\tfrac{1}{n},\dots,\tfrac{1}{n})\; ?$$
Here $B\subset \mathbb{R}^2$ denotes the closed unit ball, $F_n(B)$ is the ordered configuration space of $n$ points on $B$ with $\Sigma_n$ acting by permutation and $\Sigma_n$ acts on $\Delta_{n-1}:=\{(x_1,\dots,x_n)\in\mathbb{R}^n: \sum_ix_i=1, 0\leq x_i\leq 1\}$ by permuting the coordinates.
As Neil Strickland pointed out, using an equivariant homeomorphism, we can replace
$\Delta_{n-1}\backslash(\tfrac{1}{n},\dots,\tfrac{1}{n})$ by $\partial\Delta_{n-1}\cong_{\Sigma_n} S^{n-2}.$ This sphere $S^{n-2}$ can be viewed as $S(W_n)$, where $W_n:=\{(x_1,\dots,x_n)\in\mathbb{R}^n: \sum_ix_i=0\}$ and $\Sigma_n$ is again acting by permuting the coordinates. Using equivariant homotopy equivalences, we can replace $F_n(B)$ by $F(\mathbb{R}^2)$ and further use an equivariant model of dimension $n-1$, which Neil Strickland calls $X_0$ and I will call $\mathcal{F}_n(\mathbb{R}^2)$. So an equivalent question is:
What are conditions for the existence of a $\Sigma_n$-equivariant map
$$f: \mathcal{F}_n(\mathbb{R}^2)\to S(W_n)\; ?$$
Fortunately, there is a complete answer to that questions; it is given by Blagojević and Ziegler: arxiv, springer:
Such a map exists if and only if $n\geq 2$ is a not a prime power
The authors use equivariant obstruction theory and an explicit model $\mathcal{F_n(\mathbb{R}^2)}$, which is called $\mathcal{F}(d,n)$ in their notation. Just plug in $d=2$ and the result is the main theorem of section 4 in the paper on the arxiv.
From the nonexistence of the map we conclude that the barycenter $(\frac{1}{n},\dots,\frac{1}{n})$ is hit: If $n$ is a prime power, then your continous equivariant function $B^n\to\Delta_{n-1}$ will always hit the barycenter  and if $n$ is not a prime power, there exist equivariant functions that miss the barycenter.


text:
Q: Qt Creator error: LNK1123: failure during conversion to COFF: file invalid or corrupt When i tried to debug project on QT 5.0 Creator (MSVC2010(x86)compiler 10.0) i have this error:
LNK1123: failure during conversion to COFF: file invalid or corrupt
I googled and i saw some solutions but only for Visual Studio 2012, i need solution of this problem for QT Creator.
Thank you.
Before this problem i had problem with MSVC(x86)compiler 11.0, and i was installed MSVC2010(x86)compiler 10.0 and now i have this error.

A: In addition to QMAKE_LFLAGS += /INCREMENTAL:NO, I "cleaned" and also removed the output directory to force a fresh recompile. Then the tutorial application built.

A: Set
QMAKE_LFLAGS += /INCREMENTAL:NO in the file .pro

A: I had the same problem, but it was solved by marking in Build -> "Open build and run kit selector" the MSVC2012 64bit version, instead of the 32 bit. Hope it helps!


text:
Q: Docplex return first feasible solution found I'm trying to solve a NP-Hard problem using docplex and cplex and I need that docplex return the first factible solution founded and stop the search. In general, stop when find the nth best solution. Something like that:
set limits solutions n

A: You can use parameters.mip.limits.solutions with docplex python api
A small change to this code gives
from docplex.mp.model import Model

mdl = Model(name='buses')

mdl.parameters.mip.limits.solutions=1

nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*500 + nbbus30*400)

mdl.solve()

print("int sol limit = ",mdl.parameters.mip.limits.solutions.get())

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value)

which gives
int sol limit =  1
nbBus40  =  8.0
nbBus30  =  0

With all other apis you can do the same.
With pyomo for instance:
import pyomo.environ as pyo
from pyomo.opt import SolverFactory

opt = pyo.SolverFactory("cplex")

opt.options['mip limits solutions'] = 1

model = pyo.ConcreteModel()

model.nbBus = pyo.Var([40,30], domain=pyo.PositiveIntegers)

model.OBJ = pyo.Objective(expr = 500*model.nbBus[40] + 400*model.nbBus[30])

model.Constraint1 = pyo.Constraint(expr = 40*model.nbBus[40] + 30*model.nbBus[30] >= 300)

opt.solve(model)

print("nbBus40=",model.nbBus[40].value)
print("nbBus30=",model.nbBus[30].value)


text:
Q: PHP Sessions not working in background process I have this code that when the payment gateway is successful, it will redirect to the notification url in the parameters.
include 'payment_information_rebill.php';

if(isset($_GET)){

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'url here',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>'{
                "merchantId": "' .$_mid. '",
                "orgResponseId": "' .$_responseid. '",
                "requestId": "' .$_requestid. '",
                "amount": "' .$_verifamount. '",
                "clientId": "' .$_clientid. '",
                "clientIp": "' .$_clientip. '",
                "ipAddress": "' .$_ipaddress. '",
                "signature": "' .$_signverify. '"
        }',
        CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Idempotency-Key: ' .$_requestid. '',
                'Authorization: Basic auth here'
              ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    $result = json_decode($response, true); // true turns it into an array
}

payment information rebill contains all the variables needed for the curl, which works on the shopping cart page. however, when I put the curl function in the redirecturl of the payment gateway, the variables seems to be empty. the variables gets their data from sessions. does session only work when you access the page? does it not work on background?


text:
Q: Python Socket Connection Hangs On Different Instance but Works on Same Instance I'm currently using two different AWS instances to try and communicate using two python files, one a client and one a server. One instance, Server, has a copy of the server file and the client file. The other instance, Client, has only a copy of the client file.
The problem is that when I run the client file on the Server instance, it works as intended. However, when I run the client file on the Client instance, it hangs on the socket.connect call.
server.py
import socket
# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# get local machine name. I have also used ''
host = socket.gethostname()
# I use this print to set the host name in the client file.
print(host)

port = 12000

# bind to the port
serversocket.bind((host, port))

# queue up to 5 requests
serversocket.listen(5)

while True:
    # establish a connection
    clientsocket,addr = serversocket.accept()
    print("Got a connection from %s" % str(addr))

    msg='Thank you for connecting'+ "\r\n"
    clientsocket.send(msg.encode('ascii'))
    clientsocket.close()

client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# host is hard-coded to the output of the server file's gethostname() result
# hard-coded value from server.py
host = '###.##.##.##'
port = 12000

# connect. This is where the code hangs when run in the terminal
s.connect((host, port))

# Receive no more than 1024 bytes
msg = s.recv(1024)
s.close()
print (msg.decode('ascii'))

I've checked my security group on my AWS instances as well. Both of them have the same security group, which includes:
Custom ICMP Rule - IPv4 Echo Reply N/A 0.0.0.0/0 ICMP
Custom ICMP Rule - IPv4 Echo Reply N/A ::/0 ICMP

which I believe should allow things to run properly.
I'm unsure as to where I could be going wrong. I am certain that both client files are the same and that both servers have the same security group. I read that socket.gethostname() should return a value that is accessible from the public, so I don't think my host address is wrong. The port number is also correct. Any help would be greatly appreciated.

A: My issue what that I was missing a TCP rule with source allowing "Anywhere". I was under the impression that ICMP was the only rule I needed given my assignment, but that seems to not be the case. Thanks for the help.


text:
Q: how to install ZIP (ZZIPlib) for PHP on CentOS I have Cent OS 5 and want to install ZIP or ZIPlib extension i tried to look it up using YUM utility and its not there how can i install it?

A: There is php-pecl-zip (1.8.10) package on EPEL additional repository.

A: You can also install the php-devel package via yum and then use the pecl command to install pecl extensions. It should be something like "pecl install zip".


text:
Q: How do I get a object/objects from CheckboxTreeViewer? I'm trying to obtain an object or objects from my CheckboxTreeViewer.
I set the content provider to supply the data, and I can get the data easily from a selected item. I would think it would be something like:
treeViewer.getElements();
But this works to get selected objects:
IStructuredSelection ss = (IStructuredSelection) treeViewer.getSelection();
if (ss.size() == 1) {
  Object selectedObject = ss.getFirstElement();

   if (selectedObject instanceof IndividualNode) {
     individual = ((IndividualNode) selectedObject).getIndividual();
   }
}

that gives me my object I want from the selection.
Know how to get an object from the treeViewer if it's not selected?
There are methods like
treeViewer.getCheckedElements();

which returns Object[].
But can't find anything like
treeViewer.getElements();

Much thanks,
Brandon

A: Figured it out.
Access the Tree Items by using:
TreeItems[] treeItems = treeViewer.getTree().getItems();

then get the object by using getData()
for(int i = 0; i < treeItems.length; i++){
    Object itemObject = treeItems[i].getData();

    //Then cast to the object type
    Foo foo = (Foo) itemObject;
}

This works for TreeViewer and CheckboxTreeViewer.

A: I don't think there is anything like this. The closest thing is the elementMap field in the StructureViewer, but this is private, so you really can't even make your own subclass and get this information.


text:
Q: TypeScript metadata in module issue I have a framework that uses metadata with decorator in TypeScript so I know it is working.
However, today I just found a bizarre basic case that I can't figure out why.
It is reproducible in TS@2.1.5, @2.1.6, and @2.2.0-dev.20170214
The issue can be demo in https://github.com/unional/some-issues/tree/ts-meta-import
Summary of the situation
// Foo.ts
import 'reflect-metadata'

@Reflect.metadata('somekey', 123)
export class Foo { }

Reflect.getMetadata('somekey', Foo) // returns 123

The above code works fine, however if I try to access Foo in a different file and do the same thing, it doesn't work:
import 'reflect-metadata'
import { Foo } from './Foo'

Reflect.getMetadata('somekey', Foo) // returns undefined

It really shouldn't be the case....
UPDATE: in my framework, I'm using aurelia-metadata and it seems to work in this case. But the question remains, why this "simple" scenario doesn't work with reflect-metadata?

A: The answer is that it does work. For some reason, when I try it today, it started working.
The unicorn just pass by.
Thanks @blakeembrey for taking a look into this.


text:
Q: Problema variavel global angular app.controller('controllerPrincipal', function($scope, $http){

        var resultado;
        $http({method: 'GET', params: {id: 2}, url: 'url'}).success(function(data)
        {
            // limpando o retorno
            var p = data.search("{")-1;
            var res = data.substring(76);
            var f = res.search('<');
            dados = data.substring(p, p+f);
            resultado = JSON.parse(dados);
        });

        console.log(resultado);

});

Quando dou um console.log(resultado), fora do http ele me retorna undefined, quando do um console.log() dentro do http ainda ele me retorna o resultado correto..
nao esta com a url pois e de um cliente meu.. mas a url o retorno esta ok, so quando eu pego fora nao esta rolando a variavel resultado.
Alguem tem uma LUZ?

A: Isso acontece porque o $http executa uma requisição assíncrona, então o resultado no momento em que você loga ele não foi preenchido ainda. Ele só vai ser preenchido depois que a requisição terminar e no seu caso se for com sucesso. Aliás você deveria criar um serviço para fazer isso e não dentro do controle, mas isso é uma outra história.
Para você utilizar esses dados, onde quer que você esteja usando, você tem que dar continuidade dentro do success. Por exemplo: Se você usa isso em uma lib de terceiro, tem que chama-la lá dentro, ou em qualquer função, passando esse resultado.
Ficou claro?
Atualização
No seu caso, para incluir um serviço você pode usar o factory ou service, ambos providers. Esse exemplo usa o primeiro:
app.factory('controllerPrincipalService', function($http, $q) {
    return {
            getResultado: function(id)
            {
                var deferred = $q.defer();

                $http(
                {
                    method: 'GET',
                    url: 'url',
                    data: {id:id}
                }).success(function(data, status, headers, config)
                {
                    deferred.resolve(data);
                }).error(function(data, status, headers, config)
                {
                    deferred.reject(status);
                });

                return deferred.promise;
            }
        };
});

Assim você separa as camadas e deixa as requisições fora do controller, o que deixa seu código bem mais organizado. Seu controller ficaria assim:
app.controller('controllerPrincipal', ["$scope", "controllerPrincipalService", function($scope, $http) {
    controllerPrincipalService.getResultado(id).then(function(dados)
    {
        // limpando o retorno
        var p = data.search("{")-1;
        var res = data.substring(76);
        var f = res.search('<');
        dados = data.substring(p, p+f);
        resultado = JSON.parse(dados);
    });
}]);

Note a injeção de dependência que o controller possui ["$scope", "controllerPrincipalService". Isso te dá no scopo o serviço completo, que por sua vez, retorna um deferred. Note também que o controller agora não trabalha mais com o callback success mas sim com o then, o que é chamado de promisses. O success e o error ficam no serviço para serem tratados lá. Mas a idéia é a mesma, você tem que continuar seu fluxo a partir do callback then.
Atualização 2
Uma forma melhor de dar um parse nesse xml pode ser assim:
xmlparser = new DOMParser();
xmlDoc = xmlparser.parseFromString(dados, "text/xml");
var string = xmlDoc.getElementsByTagName("string")[0].innerHTML;
var json = JSON.parse(string);

Neste artigo tem uma versão cross-browser(o código acima provavelmente não irá funcionar no IE). E neste post tem como fazer em jQuery, que é bem mais simples.

A: Outra duvida Marcio..
 controllerPrincipalService.getResultado(id).then(function(dados)
    {
        // limpando o retorno
        var p = data.search("{")-1;
        var res = data.substring(76);
        var f = res.search('<');
        dados = data.substring(p, p+f);
        resultado = JSON.parse(dados);
    });

por exemplo eu estou utilizando esse service ai... beleza...
caso eu precise usar o resultado em outro lugar, por exemplo uma funcao abaixo desse service dentro da controle seria possivel ?
Exemplo;
 controllerPrincipalService.getResultado(id).then(function(dados)
    {
        // limpando o retorno
        var p = data.search("{")-1;
        var res = data.substring(76);
        var f = res.search('<');
        dados = data.substring(p, p+f);
        resultado = JSON.parse(dados);
    });

    function pegaResultado(resultado){
        ///trabalhar com o resultado do service a cima.
        console.log(resultado);

    }

O porque disso...
Pq eu preciso fazer um setInterval, no qual ele sempre vai ficar executando o service getResultado, caso tenha alteracao no meu webservice.. entendeu ?
vlw


text:
Q: Fetch Unique List of Items from Related property Entity Framework I am having 2 entities Customer and Orders and they are related
customer
---------
CustomerId
name

Order
---------

OrderId
OrderDate
CustomerId

I want to fetch a specific no of unique customers based on some specific scenarios or conditions and sort based on the Order Date.
Ended up with this entity framework query
IQueryable<Order> query = context.Orders;

//build various conditions
query = query.where()....

List<Order> OrdersList = new List<Order>();

OrdersList =  query.
                OrderByDescending(s=>s.OrderDate).
                Take(20).
                ToList();

//prepare unique list of contact IDS & Subscription IDs associated with current selection
List<int> Customers = OrdersList.GroupBy(s => s.CustomerId)
                            .Select(grp => grp.First().CustomerId)
                            .ToList();

This is returning the  last 20 orders to me  and from this there might not be 20 unique customers always. If a given customer got multiple orders then this list is
less than 20.
But how can i fetch the 20 unique customers based on the Order Date
[The customers who did some recent purhchases ?]

A: You say you need customers, so why not start with customers?
Assume you're using EntityFramework.
Pseudocode:
  var topCustomers = customers.Include(c=>c.Orders)
      .OrderbyDescending(c=>c.Orders.Max(o=>o.OrderDate))
      .Take(20)


text:
Q: What is actually 1.73 GHz, 555MHz, FSB I am owning a Acer Aspire laptop and its configuration are as follows:

*

*Intel Celeron M processor 430 (1.73 GHz, 533MHz FSB, 1MB L2 Cache

*Mobile Intel 940 GML Express chipset

*"14.1" WXGA wide TFT, LCD
and some more details. I would like to know what exactly is 1.73GHz, 533MHz, FSB? I know that it's something related to Processor speed, but i would like to have an formal idea of what actually this is, and how the laptop may work if the configuration were >2000GHz.
Another question would be:

*

*I use a Fedora 13 OS and it shows me the speed 16.2 MB/sec (approx.) when i transfer a movie or a file into an USB. Does, this transfer speed have any connection with the above configuration?

A: The first value, 1.73GHz, is the speed of the processor core, by other words, it is the speed that the instructions are processed.
The second value is the FSB, that means Front Side Bus, it is the speed of the bus that the processor uses to communicate with rest of the computer.
The speed of data transfer is limited by the write speed of the USB device. It is almost independent of CPU speed.


text:
Q: Como fazer upload de arquivo ao mesmo tempo que enviar um formulario asp.net mvc 5 Eu já tenho um formulário que faz um cadastro, quero adicionar um campo a mais nele onde o usuário vai fazer o upload de uma foto, quero fazer tudo no mesmo submit.
Minha VM VMDominioCreate:

    public class VMDominioCreate
    {

        [Required]
        [StringLength(200)]
        [Display(Name = "URL")]
        public string url { get; set; }

        [Display(Name = "ID C")]
        [StringLength(100)]
        public string idC { get; set; }

        [Display(Name = "ID S")]
        [StringLength(100)]
        public string idS { get; set; }

    }

Meu metodo que recebe o create:

        public async Task<ActionResult> Create(VMDominioCreate d)
        {
            if (ModelState.IsValid)
            {
              ....
            }

          }

Meu formulário:

@using (Html.BeginForm())
            {
                    @Html.AntiForgeryToken()

                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                            @Html.LabelFor(model => model.url)
                            @Html.EditorFor(model => model.url, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.url, "", new { @class = "text-danger" })

                            @Html.LabelFor(model => model.idC)
                            @Html.EditorFor(model => model.idC, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.idC, "", new { @class = "text-danger" })

                            @Html.LabelFor(model => model.idS)
                            @Html.EditorFor(model => model.idS, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.idS, "", new { @class = "text-danger" })

                            <input type="submit" value=@Resources.Create class="btn btn-default" />

                }

Tudo isso funciona perfeitamente.
Eu quero incluir o seguinte:
Um campo a mais na VM:

[Required]
public HttpPostedFileBase File { get; set; }

E a entrada a mais no formulário:

                            @Html.LabelFor(model => model.File)
                            @Html.EditorFor(model => model.File, new { htmlAttributes = new { @class = "form-control" }})
                            @Html.ValidationMessageFor(model => model.File, "", new { @class = "text-danger" })

Aí vem o problema, em vez dele gerar um botão de localizar arquivo ele gera 3 texts boxs (ContentLength, ContentType e FileName). O que não me atende.
O que eu estou fazendo de errado?
Eu quero que ele crie um botão de localizar arquivo e quando eu fizer o submit do form ele jogue a imagem junto.
ATUALIZAÇÃO
Tentei o que foi sugerido no comentário (incluir @type="file") e obtive o seguinte resultado:
Agora em vez de três text boxs ele mostrou o botão de selecionar arquivo, mas ainda continua mostrando 3 botões, como antes mostrava 3 text boxs. Os botões vem com os mesmos labels (ContentLength, ContentType e FileName).
ATUALIZAÇÃO
Nova tentativa com:
@Html.TextBoxFor(model => model.File, new { htmlAttributes = new { @class = "form-control", @type="file" }})

Ele exibe um único text box, não é mais um botão de selecionar o arquivo, mas pelo menos não aparecem os 3 campos.
Coloquei um diretório de um arquivo no text box e mandei submeter, o campo continua nulo.

A: Utilize TextBoxFor para criar o input
@Html.TextBoxFor(model=>model.File, null, new { type="file", @class="form-control" })

Para o envio de qualquer tipo de arquivo, seu formulário deve conter também o atributo enctype
@using (Html.BeginForm("ACTION", "CONTROLLER", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    //inputs aqui
}


text:
Q: How to integrate Wicket and Dagger? We are trying to integrate our web framework Wicket (1.4.x) with the dependency injection of Dagger. To do this we created a Wicket component injector:
class DaggerComponentInjector
        extends ConfigurableInjector
        implements IComponentInstantiationListener {

    ...

    @Override
    public Object inject(Object object, IFieldValueFactory factory) {
        if (!AppModule.canInject(object.getClass())) {
            return object;
        }

        final DaggerGraphHolder holder = Application.get().getMetaData(DaggerGraphHolder.GRAPH_KEY);
        holder.getGraph().inject(object);
        return object;
    }

    @Override
    public void onInstantiation(Component component) {
        inject(component);
    }

    ...

It checks if the object's class contains an @Inject anywhere and then calls Dagger to inject the dependencies.
Unfortunately, this doesn't work:
public class LogoutPage extends WebPage {

   @Inject
   private AuthenticationService authenticationService;

   ...
}

In our logout page a service is injected. But when we navigate to the page this happens:
Caused by: java.lang.IllegalArgumentException: No inject registered for members/com.myapp.LogoutPage. You must explicitly add it to the 'injects' option in one of your modules.
    at dagger.ObjectGraph$DaggerObjectGraph.getInjectableTypeBinding(ObjectGraph.java:309)
    at dagger.ObjectGraph$DaggerObjectGraph.inject(ObjectGraph.java:290)

We have hundreds of classes like this.
How do we solve this issue WITHOUT manually adding all classes to the @Module inject array (or creating a provider method)?


text:
Q: CakePHP 3 Soap Server Error I try to create a Soap Server in CakePHP 3 but if I want to connent with my client i become error's every time.
I set up the server in a function:
public function view($id) {

    $connection = ConnectionManager::get('default');
    $user = $connection->execute('SELECT * FROM users WHERE id='.'"'.$id.'"')->fetchAll('assoc');

    $obj = new Post;

    $this->viewBuilder()->layout = false;
    $this->autoRender = false;
    ini_set("soap.wsdl_cache_enabled",0); //disable wsdl cache

    $server = new SoapServer(null, array(
        'uri' => 'http://localhost/test-uri',
        'encoding'=>'UTF-8'
    )
    );

    $server->setObject($obj);
    $server->handle();

}

in a model I create this function:
namespace App\Model\Entity;

use Cake\ORM\Entity;
use Cake\Utility\Xml;

class Post {

    function testfunktion($param){

        return $param;

    }

}

my client script show this:
$soap = new SoapClient(
null,
array(
   "location" => "http://localhost/shop_system/users/view/2",
   "uri" => "http://test-uri",
   "trace" => 1
  )
);

try {
    $product = $soap->testfunktion("Michael");
} catch (SoapFault $e) {
    echo $e;
    print($soap->__getLastResponse());
}

and this is my output:

SoapFault exception: [Client] looks like we got no XML document in C:\xampp\htdocs\shop_system\webroot\client.php:15 Stack trace: #0 C:\xampp\htdocs\shop_system\webroot\client.php(15): SoapClient->__call('testfunktion', Array) #1 C:\xampp\htdocs\shop_system\webroot\client.php(15): SoapClient->testfunktion('Michael') #2 {main}
  Notice (8): Undefined index: HTTP_ACCEPT_LANGUAGE [APP/Controller\UsersController.php, line 22]Michael

i dont know what i must do by this error


text:
Q: href link not working for the first time in email I have href link which was built on java, I am using it for forget password.
when ever user clicks forget password it asks for email id, user enters email and it sends email with a link where user can enter new password. but this functionality is braking some ware. when I click the link for first time it says session expired it works fine for the second time. Any idea about this problem or anybody faced this kind of problems please reply. Thanks


text:
Q: Missing property 'type' while De/Serialization of Map the contains mixed subtype - polymorphism I have an object called Animal with two subclasses, Monkey and Lion, I used JsonTypeInfo to support subtype detection, and I suppose on serializing JsonTypeInfo should automatically put property called 'type' depending on the class.
Animal Class
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = Lion.class, name = "Lion"),
        @JsonSubTypes.Type(value = Monkey.class, name = "Monkey")
})
public class Animal implements Serializable {

    String name;

    public Animal(String name) {
        super();
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Animal other = (Animal) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

}

Lion Class

public class Lion extends Animal{

    public Lion(String name) {
        super(name);
    }

}

Monkey Class

public class Monkey extends Animal{

    public Monkey(String name) {
        super(name);
    }

}

Main Function
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        Map<String,Animal> animals = new HashMap<String, Animal>();
        animals.put("Bob", new Lion("Bob"));
        animals.put("Alice", new Monkey("Alice"));
        StringWriter sw = new StringWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        mapper.writeValue(sw, animals);
        String animlasStr = sw.toString();
        Map<String,Animal> dAnimalMap = mapper.readValue(animlasStr, new TypeReference<Map<String, Animal>>() {});
        assert dAnimalMap.get("Alice") instanceof Monkey;
    }

But when I am deserializing a map of animals it is not working!!, It throws the following exception, the type property is missing.
 com.fasterxml.jackson.databind.JsonMappingException: Unexpected token (END_OBJECT), expected FIELD_NAME: missing property 'type' that is to contain type id  (for class ....Animal)
 at [Source: {"Bob":{"name":"Bob"},"Alice":{"name":"Alice"}}

I tried to both type referencing and visible property, I got the same results.
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type" , visible =true)

A: Instead of:
mapper.writeValue(sw, animals);
use
mapper.writerFor(new TypeReference<Map<String, ? extends Animal>>() {}).writeValue(sw, animals);
And instead of:
mapper.readValue(animlasStr, new TypeReference<Map<String, Animal>>() {});
use:
mapper.readValue(animlasStr, new TypeReference<Map<String, ? extends Animal>>() {});
with empty constructors in all the classes


text:
Q: SMTP errors with iOS devices I'm trying to diagnose why when an iOS device like an iPhone or iPad is set up to use email with our server for the first time, these errors occur.  We choose "Other" from the initial set of choices for provider in setting up the account. You can see the connection transaction below after putting in the IMAP and SMTP server names. 69.197.220.11 is the address of the phone.  We run CommuniGate Pro 6.0.10.

*

*What are the errors in the log from 10:06:40.691 to 10:06:40.723?

*What is the address listed at time 10:06:51.067 (10.33.64.161)?
The errors do not occur when setting up IMAP/SMTP on a Macbook (Mail) or PC (Outlook, Thunderbird), or Linux, or with the one Android device I've been able to test with.  The protocol errors end up causing the iOS device's IP address to be blacklisted by the email server.
System log follows:
10:06:40.688 5 SMTP [0.0.0.0]:587 <- [69.197.220.11]:49426 connection request. socket=191
10:06:40.688 5 SMTP new VStream created, 1 total
10:06:40.688 5 SMTP stream thread started
10:06:40.688 4 SMTPI-011473([69.197.220.11]) [192.168.200.100]:587 <- [69.197.220.11]:49426 incoming connection(our domain.net)
10:06:40.688 5 SMTPI-011473([69.197.220.11]) out: 220 ourdomain.net ESMTP CommuniGate Pro 6.0.10\r\n
10:06:40.691 5 SMTPI-011473([69.197.220.11]) inp: \022\003\001
10:06:42.693 5 SMTPI-011473([69.197.220.11]) out: 501 Unknown command\r\n
10:06:42.693 5 SMTPI-011473([69.197.220.11]) inp: \163\001
10:06:44.696 5 SMTPI-011473([69.197.220.11]) out: 501 Unknown command\r\n
10:06:44.696 5 SMTPI-011473([69.197.220.11]) inp:
10:06:46.698 5 SMTPI-011473([69.197.220.11]) out: 501 Unknown command\r\n
10:06:46.698 5 SMTPI-011473([69.197.220.11]) inp: \159\003\001T\135 l
10:06:48.700 5 SMTPI-011473([69.197.220.11]) out: 501 Unknown command\r\n
10:06:48.700 5 SMTPI-011473([69.197.220.11]) inp: \004\225\176d2\217\180\005"]\167\176\182\131N&\183\175\218\167\200\167\245\003\246\005\221
10:06:50.702 5 SMTPI-011473([69.197.220.11]) out: 501 Unknown command\r\n
10:06:50.702 1 SMTPI-011473([69.197.220.11]) Too many protocol errors, aborting
10:06:50.723 4 SMTPI-011473([69.197.220.11]) closing connection
10:06:50.723 4 SMTPI-011473([69.197.220.11]) releasing stream
10:06:50.966 5 SMTP [0.0.0.0]:587 <- [69.197.220.11]:49427 connection request. socket=214
10:06:50.966 4 SMTPI-011474([69.197.220.11]) [192.168.200.100]:587 <- [69.197.220.11]:49427 incoming connection(ourdomain.net)
10:06:50.966 5 SMTPI-011474([69.197.220.11]) out: 220 ourdomain.net ESMTP CommuniGate Pro 6.0.10\r\n
10:06:51.067 5 SMTPI-011474([69.197.220.11]) inp: EHLO [10.233.64.161]
10:06:51.067 5 SMTPI-011474([69.197.220.11]) out: 250-ourdomain.net your name is not [10.233.64.161]\r\n250-DSN\r\n250-SIZE\r\n250-STARTTLS\r\n250-AUTH LOGIN PLAIN CRAM-MD5 GSSAPI\r\n250-ETRN\r\n250-TURN\r\n250-ATRN\r\n250-NO-SOLICITING\r\n250-8BITMIME\r\n250-HELP\r\n250-PIPELINING\r\n250 EHLO\r\n
10:06:51.165 5 SMTPI-011474([69.197.220.11]) inp: STARTTLS
10:06:51.165 5 SMTPI-011474([69.197.220.11]) out: 220 please start a TLS connection\r\n
10:06:51.549 4 SMTPI-011474([69.197.220.11]) TLSv1.0 security initiated
10:06:51.635 4 SMTPI-011474([69.197.220.11]) TLS-102107(AES256_SHA) connection accepted for 'ourdomain.net'
10:06:51.865 5 SMTPI-011474([69.197.220.11]) s-inp: EHLO [10.233.64.161]
10:06:51.865 5 SMTPI-011474([69.197.220.11]) s-out: 250-ourdomain.net your name is not [10.233.64.161]\r\n250-DSN\r\n250-SIZE\r\n250-AUTH LOGIN PLAIN CRAM-MD5 GSSAPI\r\n250-ETRN\r\n250-TURN\r\n250-ATRN\r\n250-NO-SOLICITING\r\n250-8BITMIME\r\n250-HELP\r\n250-PIPELINING\r\n250 EHLO\r\n
10:06:51.976 5 SMTPI-011474([69.197.220.11]) s-inp: AUTH PLAIN AGZ1ZGRsZXMAMWJpZ2RvZw==
10:06:51.976 5 SMTPI-011474([69.197.220.11]) SASL(PLAIN) ini: \000fuddles\0001bigdog\000
10:06:51.977 2 SMTPI-011474([69.197.220.11]) 'fuddles@ourdomain.net' connected(CLRTXT) [69.197.220.11]:49427->[192.168.200.100]:587(tls)
10:06:51.977 2 SMTPI-011474([69.197.220.11]) 'fuddles@ourdomain.net' disconnected ([69.197.220.11]:49427)
10:06:51.977 2 SMTPI-011474([69.197.220.11]) authenticated as fuddles@ourdomain.net
10:06:51.977 5 SMTPI-011474([69.197.220.11]) s-out: 235 fuddles@ourdomain.net relaying authenticated\r\n
10:06:52.086 5 SMTPI-011474([69.197.220.11]) s-inp: QUIT
10:06:52.086 5 SMTPI-011474([69.197.220.11]) s-out: 221 ourdomain.net CommuniGate Pro SMTP closing connection\r\n
10:06:52.086 4 SMTPI-011474([69.197.220.11]) TLS connection is closing
10:06:52.086 4 SMTPI-011474([69.197.220.11]) closing connection
10:06:52.086 4 SMTPI-011474([69.197.220.11]) releasing stream

A: What are the errors in the log from 10:06:40.691 to 10:06:40.723?
Line
10:06:40.691 5 SMTPI-011473([69.197.220.11]) inp: \022\003\001

was part of SSL handshake.

*

*Byte 0 = 022 means SSL record type = 22 (SSL3_RT_HANDSHAKE)

*Byte 1-2 = 0301 was means SSL version = TLS1_VERSION

See this page for reference.
But unfortunately the server on port 587 doesn't talk with SSL (SMTPS), but with STARTTLS. Server with STARTTLS expect that initial connection will sits in unencrypted channel then move to encrypted channel.
So, at initial the IOS attempted to connect with SMTPS (SMTP on top SSL protocol). But the server doesn't understand it, so it give warning Unknown command until some limits then disconnect the client.
Because the initial connection rejected, IOS do fallback action and connect again to the server with STARTTLS.
10:06:51.165 5 SMTPI-011474([69.197.220.11]) inp: STARTTLS

In this case, iOS successfully connect to server.
What is the address listed at time 10:06:51.067 (10.33.64.161)?
IP Address 10.33.64.161 seems to be IP Address from Internet Provider. Usually client will announce HELO <something>  with <something> is IP address/hostname of the computer/handphone
iOS Behaviour
As I've never used IOS, so I can't tell you what iOS setting that caused this behaviour (or maybe this is default iOS behaviour). In your case, intended behaviour is directly connect via STARTSSL, bypassing SMTPS attempt so it won't be rejected and blacklisted again.
In comment, BillThor confirmed that above behavior was iOS's default behaviour.

IOS defaults to SSL (secure connection) and then offers to connect insecurely if that fails. After the SSL connection fails the user is given the option to connect insecurely. If STARTTLS is available, it is used. The activities involved in the connection discovery are being logged by the server.

Solution
The obvious solution is configure the mail server - CommuniGate Pro -, so it won't blacklist the client who behave like this. The behaviour should not be considered a failure, and should not get the device blacklisted either.
Workaround from OP
The settings for the protocol error threshold and getting blacklisted are in Settings-> Mail -> SMTP -> Receiving -> Limits. The default is Disconnect after 20 errors and Deny access for 15 minutes. I've changed mine to Disconnect after 100 errors and Deny access for 0 seconds.  Not sure about the 0 seconds but it has resolved the problems with initial setup of IMAP accounts on iOS devices with our CommuniGate Pro server.


text:
Q: C++ Fast Bitset Short-Circuit Bitwise Operations A demo problem: Given two std::bitset<N>s, a and b check if any bit is set in both a and b.
There are two rather obvious solutions to this problem.  This is bad because it creates a new temporary bitset, and copies values all sorts of places just to throw them away.
template <size_t N>
bool any_both_new_temp(const std::bitset<N>& a, const std::bitset<N>& b)
{
    return (a & b).any();
}

This solution is bad because it goes one bit at a time, which is less than ideal:
template <size_t N>
bool any_both_bit_by_bit(const std::bitset<N>& a, const std::bitset<N>& b)
{
    for (size_t i = 0; i < N; ++i)
        if (a[i] && b[i])
            return true;
    return false;
}

Ideally, I would be able to do something like this, where block_type is uint32_t or whatever type the bitset is storing:
template <size_t N>
bool any_both_by_block(const std::bitset<N>& a, const std::bitset<N>& b)
{
    typedef std::bitset<N>::block_type block_type;
    for (size_t i = 0; i < a.block_count(); ++i)
        if (a.get_block(i) & b.get_block(i))
            return true;
    return false;
}

Is there an easy way to go about doing this?

A: I compiled your first example with optimization in g++ and it produced code identical to your third solution.  In fact, with a smallish bitset (320 bits) it fully unrolled it.  Without calling a function to ensure that the contents of a and b were unknown in main it actually optimized the entire thing away (knowing both were all 0).
Lesson:  Write the obvious, readable code and let the compiler deal with it.

A: You say that your first approach "copies values all sorts of places just to throw them away." But there's really only one extra value-copy (when the result of operator& is returned to any_both_new_temp), and it can be eliminated by using a reference instead of a value:
template <size_t N>
bool any_both_new_temp(const std::bitset<N>& a, const std::bitset<N>& b)
{
    std::bitset<N> tmp = a;
    tmp &= b;
    return tmp.any();
}

(But obviously it will still create a temporary bitset and copy a into it.)


text:
Q: Type of the parameter must be a class annotated with @Entity I'm working with Room persistance databases in android but i get this error
error: Type of the parameter must be a class annotated with @Entity or a collection/array of it.
    test.android.orca.com.ws2db.Models.User... user);
Please help me
This is my DAO :
@Dao
abstract interface UserDao
{
@get:Query("SELECT * FROM user")
val getall: List<User>

@Query("SELECT * FROM user where name LIKE  :name AND login LIKE :login")
fun findByName(name: String, login: String): User

@Query("SELECT COUNT(*) from user")
fun countUsers(): Int

@Insert
fun insertAll(users: List<User>)

@Delete
fun delete(vararg user: User)
}

This is my Entity
@Entity(tableName = "user")
class UserTable {

@PrimaryKey(autoGenerate = true)
var uid: Int = 0

@ColumnInfo(name = "name")
var name: String? = null

@ColumnInfo(name = "login")
var login: String? = null

@ColumnInfo(name = "id")
var id: Int = 0

@ColumnInfo(name="url")
var url: String? = null

@ColumnInfo(name="company")
var company:String?=null

}

Database
@Database(entities = [UserTable::class], version = 1)
abstract class AppDatabase : RoomDatabase() {

abstract fun userDao(): UserDao

companion object {

    private var INSTANCE: AppDatabase? = null

    fun getAppDatabase(context: Context): AppDatabase? {
        if (INSTANCE == null) {
            INSTANCE = Room.databaseBuilder(context.applicationContext,
             AppDatabase::class.java, "user-database")
                .allowMainThreadQueries()
                .build()
        }
        return INSTANCE
    }

    fun destroyInstance() {
        INSTANCE = null
    }
}}

This is the error : https://i.stack.imgur.com/FnECR.jpg

A: You are mixing user and UserTable. User is valid for referencing your table, but your entity is UserTable
@Dao
abstract interface UserDao
{
@get:Query("SELECT * FROM user")
val getall: List<UserTable>

@Query("SELECT * FROM user where name LIKE  :name AND login LIKE :login")
fun findByName(name: String, login: String): UserTable

@Query("SELECT COUNT(*) from user")
fun countUsers(): Int

@Insert
fun insertAll(users: List<UserTable>)

@Delete
fun delete(vararg user: UserTable)
}


text:
Q: INSERT query doesn't return an object I'm simply trying to retrieve the inserted row's unique ID. Why doesn't this code work?
include('lib_connection.php');
$con = dbconnect();
$res = $con->query("insert into schools(school,city) values('CyFair High School','houston') ");
echo $res->insert_id;
$con->close();

I only get:
Notice: Trying to get property of non-object in C:\Program Files (x86)\wampserver\www\hwsource\do_test.php on line 5

dbconnect() works fine. The query also executes fine and inserts the values in the DB, but I don't get an object returned. I simply get a boolean true. If Insert doesn't return an object, then how can I retrieve the inserted ID?

A: Try
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");  //use your data
$mysqli->query("insert into schools(school,city) values('CyFair High School','houston') ");
echo $mysqli->insert_id
$mysqli->close();

UPDATED:
instead of $con->close() try mysql_close($con);

A: If i am right to asume that your dbconnection uses the plain and simple mysql functions then just replace
echo $res->insert_id;

with:
echo mysql_insert_id();

A: If you are using PDO you need to set the fetch mode to PDO::FETCH_OBJECT...Also if your code is returning an array you can simply cast it to object like this (object) $res.

A: Amend
echo $res->insert_id;
to
echo $con->insert_id;
It's an old question at this stage, but the best answers remain ambiguous, so I thought I'd clarify, using the actual variable names in the question, and the usual currently implemented PHP versions.
My answer works if $con is a mysqli object, which it probably is (and not the older mysql -- the 'i' stands for 'improved'). Thus, when performing its query method it

returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.[Source]

This explains the error message, as the query is an INSERT.
I came here as a result of a textbook instructing me to get the insert_id from the result and not the mysqli object itself, but I can't find any justification for this in the documentation for past or present versions of MySQL.


text:
Q: Laravel public content not a accessible on Shared Host I'm using a shared hosting with php 7.4 and Laravel.
I created the project inside root www/ folder then I need to add a htaccess file to load index.php
source file: www/.htaccess

<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteRule ^ /public/index.php [L]
</IfModule>

It allowed me to load the website but I couldn't load public content since then.
Runing local server I can load the public resources such as stylesheet
<link rel="stylesheet" href="{{ URL::asset('css/main.css')}}">

But on production environment it returns 404 on generated source
<link rel="stylesheet" href="http://neovita.web277.uni5.net/css/main.css">

A: Obviously, the correct URL to the CSS file is http://neovita.web277.uni5.net/public/css/main.css.
If the shared hosting in question allows you to put files & folders at the same level with the www folder, you can make the www folder to be the "public" folder of your Laravel project (by renaming public to www). Details here: How to change public folder to public_html in laravel 5

A: in .htaccess add this
RewriteEngine On
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]


text:
Q: XML Signature in a Web application We are developing an e-Banking web application for a small bank (up to 20000 clients/users). We have to implement digital signatures with X509 certificates (issued by CA on USB tokens) for signing payment information. We tried using CAPICOM but it seems that it is not working well with Windows Vista (have not tried it with Win 7). The other problem is that core banking system can process only Xml digital signatures, so we have to sign XML documents (not just a bulk-formatted text data like with CAPICOM and Win32 Crypto API).
So my questions here are:

*

*Does anyone of you have similar
problem and how did they solved it?

*Is there a plug-in, library,
component or external tool (for
Internet Explorer and/or Fire Fox)
that supports XML Digital Signatures
in a web application?

*Can you please recommend some of
these products and write something
about your experience with them?

A: I used to work in an IT consulting company and in that time we used Ubi Sign ActiveX for XML Signatures in web applications from Ubisecure (www.ubisecure.com). Now I could not find any information about this product on their web site so try to email them. Also you can try this ActiveX component that I found on the internet. The name is XSign ActiveX XML Signature Component from Lizard Labs (www.lizardl.com). Didn't tried it jet but the author says it works fine.

A: See the types in the System.Security.Cryptography.Xml namespace, especially the SignedXml class.

A: XML Signature Applet is a software component, which enables creation of XML digital signature in web applications. XML Signature Apple is a simple Java applet for doing a digital signature on a XML documents using X.509 digital certificates stored in system certificate store. This applet receives the data in a XML format and generates a enveloped signature representation in XMLDsig format.
Found it here:
http://www.digisecsolutions.com/


text:
Q: Print lines from text file splitted into parts by a pattern in bash I have a text file like this:
line 1
line 2
*
line 3
*
line 4
line 5
line 6
*
line 7
line 8

I would like to write out parts which are between the two patterns (* in this case). So if I want the first section, I want to get
line 1
line 2

If I want to get the third one it should be
line 4
line 5
line 6

The returned lines should be without the asterisk, and it is important that there is no asterisk at the beginning or at the end.
I was thinking about "splitting" the whole text into columns using '*' as delimiter with sed or awk, but I did not succeed. Anyone could help? Thanks a lot.
This was what I tried:
sed "/^%/{x;s/^/X/;/^X\\{$choice\\}$/ba;x};d;:a;x;:b;$!{n;/^%/!bb}" "$file"

but this needs to have an * at the beginning and it also prints the asterisks before and after.

A: $ awk -v num=3 '$0=="*"{ if (++count >= num) exit; next } num-1==count' data
line 4
line 5
line 6
$ awk -v num=1 '$0=="*"{ if (++count >= num) exit; next } num-1==count' data
line 1
line 2

A: awk to the rescue
$ awk -v RS='\n\\*\n' -v n=3 'NR==n' file
line 4
line 5
line 6

this requires multi-char record separator support (gawk).
Another alternative, with counting stars
$ awk -v n=3 '/^*/{c++;next} c==n-1' file
line 4
line 5
line 6


text:
Q: Bash: Strange characters even after setting locale to UTF-8: "•" prints as "ΓÇó" We have some Groovy scripts that we run from Git Bash (MINGW64) in Windows.
Some scripts prints the bullet character • (or similar).
To make it work we set this variable:
export LC_ALL=en_US.UTF-8
But, for some people, this is not enough. Its console prints ΓÇó instead of •.
Any idea about how to make it prints properly and why is printing that even after setting the LC_ALL variable?
Update
The key part is that the output from Groovy scripts is printing incorrectly, but there are no problems with the plain bash scripts.

A: An example with querying the current characters mapping locale charmap used by the system locale, and filtering the output with recode to render it with compatible characters mapping:
#!/usr/bin/env sh

cat <<EOF | recode -qf "UTF-8...$(locale charmap)"
• These are
• UTF-8 bullets in source
• But it can gracefully degrade with recode
EOF

With a charmap=ISO-8859-1 it renders as:
o These are
o UTF-8 bullets in source
o But it can gracefully degrade with recode

Alternate method using iconv instead of recode and results may even be better.
#!/usr/bin/env sh

cat <<EOF | iconv -f 'UTF-8' -t "$(locale charmap)//TRANSLIT"
• These are
• UTF-8 bullets followed by a non-breaking space in source
• But it can gracefully degrade with iconv
• Europe's currency sign is € for Euro.
EOF

iconv output with an fr_FR.iso-8859-15@Euro locale:
o These are
o UTF-8 bullets followed by a non-breaking space in source
o But it can gracefully degrade with iconv
o Europe's currency sign is € for Euro.


text:
Q: sort based on templatefield gridview asp.net web forms 4.5 I'm trying to sort a gridview based on templatefields.
My gridview basically has a few databoundfields, and in the backend
I call rowdatabound function to get data from other tables.
Some thing like this..
<asp:Gridview runat="server" ID="testGrid" selectMethod="testGrid_GetData"
 AutoGenerateColumns="false" AutoGenerateDeleteButton="true" OnRowDataBound="testGrid_RowDataBound" ItemType="testItem"
 DeleteMethod="testGrid_DeleteItem" AutoGenerateEditButton="true" UpdateMethod="testGrid_UpdateItem" DataKeyNames="idx">
    <Columns>
        <asp:BoundField DataField="Field1" HeaderText="Field1" />
        <asp:BoundField DataField="Field2" HeaderText="Field2" />
        <asp:TemplateField HeaderText="Field3"></asp:TemplateField>
    </Columns>
<asp:GridView>

And I'm calling from GetData from Backend and also rowDataBound to get data from other table,
something like this..
public Iqueryable testGrid_GetData() {
    var testIt = db.testItems.orderbyDescending(r => r.Field1);
    return testIt;
}

protected void testGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    string f1 = e.Row.Cells[1].Text.ToString();
    var item = db.otherItems.Where(it => it.FieldFrom1.Equals(f1)).field3;
    e.Row.Cells[4].Text = field3;

}

This may be an oversimplification of what I'm doing right now but I think I can solve my problem if someone could sort from here.
So my goal is to sort by Field3, and I did not used any datatables or datasources and all the tutorials are asking me to do so.
I've even tried using OnSorting function but I have no clue where to start.
Also worried that even though I fired Onsorting function, the RowdataBound event will override that function.
If someone could help me with this, it would be truly grateful.
And again, the code is much, much more complicated than this and all other functionalities beside this is working fine, so it would be nice if I could do this without changing the structure of the code too much.
Thanks in advance!!


text:
Q: A failed login lockout system for ssh on Ubuntu that actually works? Currently, my ssh server lets a user fail to login an infinite number of times (theoretically until the password is correctly guessed). I do not want this to be the case, I want the user to be banned for an arbitrary length of time after an arbitrary number of failed login attempts. I know that there are solutions availble and have tried at least three of them, but none has worked. I am wondering if anyone here has had a more successful experience than I, and how I might get something like this working with minimal hassle. Thanks!
I have a Kubuntu 9.10 system running the latest debian-stable openssh-server package.

A: Take a look at DenyHosts
I've just recently installed it after someone tried to bruteforce me, so I don't have any experience with it, but it'll do what you want.  In the configuration you can even set it up to send you an email when it blocks someone.
It may or may not be in the Ubuntu repositories; I don't use Ubuntu so I don't know.

A: You don't mention which ones you've tried already.  I've used fail2ban on servers before, but not recently so I'm not sure how much has changed.
Here's a good writeup about using it with ssh.


text:
Q: redirect to folder without changing URL I am having trouble with redirecting the main domain to a subdirectory without changing the URL.
RewriteCond %{HTTP_HOST} ^kargomastercompanies\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.kargomastercompanies\.com$
RewriteRule ^/?$ "http\:\/\/kargomastercompanies\.com\/kargomastercompanies\.com" [R=301,L]

that's the code written in .htaccess file. What should I do to keep the domain name same as it's in my root directory?
Thanks in advance for helping me.

A: To simply rewrite, without redirecting, you should not use [R=301]
Use:
RewriteCond %{HTTP_HOST} ^(www\.)?kargomastercompanies\.com$ [NC]
RewriteRule !^kargomastercompanies\.com /kargomastercompanies.com%{REQUEST_URI} [NC,NE,L]


text:
Q: Hosting a website I have created a website using xampp(localhost) as one of the project in my college.Now our professor said we have to host it. So i searched for the free hosting websites. I got 000webhost.com as one of the website.I created an account; downloaded FileZilla using which I uploaded all my project folders.
Now I created database on 000webhost.com changing my code accordingly from localhost to server name , root to username; and password.
My Problem is that now how should i create a table for storing data.Because in my actual website ( on my pc using localhost) i created directly using phpmyadmin.
I want to create a single table once and use it again and again for example if a user inputs some details then I need to store their details.
So can anyone please tell me how should i create table directly on 000webhost.com??

A: Although this question is really off-topic, I am going to answer it anyways.
Your webhost, should -if it supports SQL- provide you with the details for your mysql. So for example, if I had the host host.com, I would connect using their provided data, which could be db.host.com with port 3306. Just put those details instead of localhost to connect.
Then they should have a utility like PHPMyAdmin to manage the database, or you have to get one yourself (there is plenty of SQL managers out there!)
Update: 000webhost apparently has CPanel, on CPanel there should be a MySQL link which takes you to the utility.


text:
Q: CSS corrupted and gone blanked - How can i recover it. - (PC BOSD & Restarted) CSS corrupted and gone blanked - how can i recover it.
problem PC BOSD and Restarted when i BOSD i was editing and CSS file. soon after i restart the pc the CSS gone blanked. all browser cash also show blank as well.
Please give a solution.

A: If you lost your CSS file's contents in your editor, it's likely gone.
Unless you have backups, he only place where you might be able to fetch it from is a browser cache (maybe on some other machine that accessed the page) -  depending on cache settings, it may be gone there as well, but it's worth a try.