text:
Q: Comparator compare() method sorting confusion I am doing self-test question from Kathy and Seirra book. One of the question went wrong, so i was trying in IDE. My confusion can be found from this image. Main question is when i debugged it, i had put a debugging point in compare method. If the tooltip can be noticed o1 holds value pen. I thought o1 should be map and o2 should be pen. Can someone explain me this confusion?

A: You can check the source of Arrays.sort method on grepcode and understand it better now:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Arrays.java#Arrays.sort%28java.lang.Object%5B%5D%2Cjava.util.Comparator%29

A: The order doesn't matter when you implement a Comparator, you just need to conform to that Class contract and implement it as required.
You can only deduce the order of the calls knowing the input and the implementation.
Just for the sake of completeness, from OpenJDK 7, this is the implementation of Arrays.sort that uses merge sort (analysis below):
public static <T> void sort(T[] a, Comparator<? super T> c) {
    T[] aux = (T[])a.clone();
    if (c==null)
       mergeSort(aux, a, 0, a.length, 0);
    else
       mergeSort(aux, a, 0, a.length, 0, c);
}

And Arrays::mergeSort:
private static final int INSERTIONSORT_THRESHOLD = 7;

private static void mergeSort(Object[] src,
                              Object[] dest,
                              int low, int high, int off,
                              Comparator c) {
    int length = high - low;

    // Insertion sort on smallest arrays
    if (length < INSERTIONSORT_THRESHOLD) {
        for (int i=low; i<high; i++)
            for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)
                swap(dest, j, j-1);
        return;
    }

    // Recursively sort halves of dest into src
    int destLow  = low;
    int destHigh = high;
    low  += off;
    high += off;
    int mid = (low + high) >>> 1;
    mergeSort(dest, src, low, mid, -off, c);
    mergeSort(dest, src, mid, high, -off, c);

    // If list is already sorted, just copy from src to dest.  This is an
    // optimization that results in faster sorts for nearly ordered lists.
    if (c.compare(src[mid-1], src[mid]) <= 0) {
       System.arraycopy(src, low, dest, destLow, length);
       return;
    }

    // Merge sorted halves (now in src) into dest
    for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
        if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0)
            dest[i] = src[p++];
        else
            dest[i] = src[q++];
    }
}

In your example, this is true: length < INSERTIONSORT_THRESHOLD so an insertion sort will be actually performed for this small 4 elements array.
Edit: Wrong mergeSort, fixed.

A: I don't know why you expect o1 should be map and o2 should be pen. There is no guarantee for that, and in fact, you shouldn't care about it when you implement the compare() method.

A: How did the question go wrong? What was the original question?
Arrays.sort(Object[]) uses Mergesort, but that shouldn't really matter if all you are worried about is getting a sorted array. As long as you match the requirements of the Comparator interface (http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html) your array will come out sorted correctly.


text:
Q: AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: i have an enum as below:
public enum UserRole {
    ADMIN,ORGANIZER,USER
}

and then in another class, i am trying to make a collection of this enum:
@Data
@Entity
public class User {

    @Id
    @GeneratedValue
    Long id;

    @OneToMany
    Collection<UserRole> userRole;

}

But it complains with below error:
Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.eventer.demo.model.User.userRole[com.eventer.demo.model.UserRole]

A: You cannot use @OneToMany on non entity classes. You should use @ElementCollection instead which can be used on String, Integer, Enum and other basic types that don't have a primary key.

A: You must use @ElementCollection because , This User Role  is enum  and it is not included in database.  JPA 2.0 makes the latter case simple with @ElementCollection:

JPA 2.0 defines an ElementCollection mapping. It is meant to handle
  several non-standard relationship mappings. An ElementCollection can
  be used to define a one-to-many relationship to an Embeddable object,
  or a Basic value (such as a collection of Strings). An
  ElementCollection can also be used in combination with a Map to define
  relationships where the key can be any type of object, and the value
  is an Embeddable object or a Basic value.

    @ElementCollection(targetClass=UserRole.class)
    @Enumerated(EnumType.STRING)
    @CollectionTable(name = "USER_ROLE",
    joinColumns = @JoinColumn(name = "USER_ID"))
    @Column(name="ROLE")
    Collection<UserRole> roles;

redpajama_set_name: RedPajamaStackExchange


text:
Q: .findOne function, trying to have multiple params My .findOne function seems to work how it should, I think I'm missing something though. It displays the accounts that have the Username I put in, but it completely ignores the Password field.
exports.accountLogin = (req, res) => {
   Accounts.findOne({Username: 'Test', Password: 'Password'}, (err, account) => {
        if (err) return next(err);
        res.send(account)
    });

Here is my Accounts Schema
const AccountsSchema = new Schema({
    Username: {
        type: String,
        required: true,
        max: 8,
    },
    Password: {
        type: String,
        required: true,
        max: 10,
    },
    AccountType: {
        type: String,
        required: true,
        max: 100,
    },
    Email: {
        type: String,
        required: true,
        max: 35,
    },
    Age: {
        type: Number,
        required: true,
        max: 100,
    },
    Question1A: {
        type: String,
        required: true,
        max: 100,
    },
    Question2A: {
        type: String,
        required: true,
        max: 100,
    },
    Question3A: {
        type: String,
        required: true,
        max: 100,
    },
});
};


text:
Q: CABasicAnimation not work in swift 3    let path = CGMutablePath()

    path.move(to: CGPoint(x:0.0, y:10.5))
    path.addLine(to: CGPoint(x: (self.frame.width/2), y:20.5))

    let pathInit = CGMutablePath()

    pathInit.move(to: CGPoint(x: 0, y:0))
    pathInit.addLine(to: CGPoint(x: self.frame.width/2, y: 0))

    // update the path property on the mask layer, using a CATransaction to prevent an implicit animation
    let mask = CAShapeLayer()

    mask.path = pathInit

    let maskLayer: CAShapeLayer = CAShapeLayer()
    maskLayer.path = pathInit
    self.layer.mask = maskLayer
    let anim = CABasicAnimation(keyPath: "path")
    anim.fromValue = maskLayer.path
    anim.toValue = path
    anim.duration = 0.25
    anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    maskLayer.add(anim, forKey: nil)
    CATransaction.begin()
    CATransaction.setDisableActions(true)
    maskLayer.path = path
    CATransaction.commit()

After I migrate to swift 3 this function not work, I think it because CABasicAnimation  or  CGMutablePath
please help,


text:
Q: What is .gr file format? I am confused between a .gr file and an adjacency list representation of graph.
How does the data in .gr file looks like? Is it in adjacency list form or there is some other format in which the data is displayed in .gr file?
Please help.

A: Tab-delimited graph format. A simple text format containing two columns of numbers separated by a single space or tab.  The first number is the base position; the second number is the score.


text:
Q: Term for strengthening the bond between an employee and his organisation Edit: added one-sidedness of 'Employee retention' as an issue
I'm looking for an alternative to 'Employee retention'. Intuitively, I interpret 'retention' as a defensive term, while I mean to emphasise (strengthening of) the bond between an employee and their company in a positive way.
Additionally, 'Employee retention' is a one-sided term, in that it is primarily applicable when considering the bond from company's perspective.
In Dutch, we have the (to me) more neutral term medewerkersbinding. In German, there's the equivalent term Mitarbeiterbindung (Wikipedia, using Google Translate).
Does such a term exist in English?

A: Maybe what you are looking for is employee engagement?
It is sometimes defined as an employee's involvement with, commitment to, and satisfaction with work. It bridges job satisfaction and organizational commitment and is part of employee retention.
Reference:
https://en.wikipedia.org/wiki/Employee_engagement

A:
Team building is a collective term for various types of activities used to enhance social relations and define roles within teams, often involving collaborative tasks. It is distinct from team training, which is designed to improve the efficiency, rather than interpersonal relations. –Wiki


text:
Q: How to get object from ViewComponent on post? On my razor page project, I am using a View Component as a template for listings, like so in my html:
@foreach (var listingItem in Model.ListingItems)
{
    @await Component.InvokeAsync("Listing", new { listingItem = listingItem })
}

where a ListingItem object is passed down to be displayed with the model:
public class ListingViewComponent : ViewComponent
{
    public ListingItem ListingItem { get; private set; }

    public IViewComponentResult Invoke(ListingItem listingItem)
    {
       return View(this);
    }
}

In this Listing view component, I have among other things a form with a post:
<form method="post">
// some stuff
</form>

So far, I am able to successfully display data and get a post. I've search for ways to pass down object from ViewComponents to Page Models on click but haven't been successful. Can this be achieved with ViewComponents or do I need to use something like partial views?
Thanks!

A:
I've search for ways to pass down object from ViewComponents to Page Models on click.

You can try to use asp-page and asp-handler to set page and handler,so that when click button,the form data will be passed to the handler of the page.
 <form method="post" asp-page="xxpage" asp-handler="xxhandler">
// some stuff
    <input type="submit" value="submit"/>
</form>


text:
Q: Inverting Laplacian on tensor product of Sobolev spaces. Let $H^s$ denote the Sobolev Hilbert space. Let $\mathbb{T}$ be the circle. Let $H^{s,r}$ be the Hilbert space formed by completing $H^s(\mathbb{T})\otimes H^r(0,1)$. This space can be identified as the space of "dominating mixed smoothness": the subset of functions $u(x,y) \in L^2(\mathbb{T} \times [0,1])$ with norm
$$\|u\|_{H^{s,r}}^2 = \sum_{\sigma \leq s} \sum_{\rho \leq r} \|\partial_x^{\sigma} \partial_y^{\rho} u\|_{L^2}^2$$
Let $s,r \geq 2$. I am interested in finding a space, say $A$ such that the laplacian operator is an isomorphism from $H^{s,r}$ to $A$, given some boundary conditions, ie the map $\Delta : H^{s,r}\rightarrow A$ is invertible.
I am not sure how I can define this space, ideally it would be in terms of derivatives. Suppose for a moment we are on $\mathbb{T}^2$ instead of the circular strip. Then we can work in the Fourier spectrum, we have
$$\|u\|_{H^{s,r}}^2 \sum_{m,n} (1+m^2)^s(1+n^2)^r|\hat{u}_{m,n}|^2$$
and we can define a norm on $A$:
$$\|u\|_{A}^2 = \sum_{m,n} \frac{(1+m^2)^s(1+n^2)^r}{(1+m^2+n^2)^2}|\hat{u}_{m,n}|^2$$
then $I-\Delta: H^{s,r}\rightarrow A$ is clearly an isomorphism. I have tried to mess around with this norm, trying to find some equivalent norm in terms of derivatives hoping to get some insight into the case without Fourier series. But I have no success, has anyone some suggestions?
EDIT:
So looking some more at the $\mathbb{T}^2$ case I am reminded that we have $(1-\Delta)^{-1}: H^{-2}(\mathbb{T}^2) \rightarrow L^2(\mathbb{T}^2)$ is an isomorphism. Therefore we could write
$$\|u\|_{H^{s,r}}^2 = \sum_{\sigma \leq s} \sum_{\rho \leq r} \|(I-\Delta)^{-1}\partial_x^{\sigma} \partial_y^{\rho} u\|_{L^2}^2 = \sum_{\sigma \leq s} \sum_{\rho \leq r} \|\partial_x^{\sigma} \partial_y^{\rho} u\|_{H^{-2}}^2$$
or actually dividing out $\frac{(1+m^2)^s(1+n^2)^r}{(1+m^2+n^2)^2}$ we get something like:
$$\|u\|_{A}^2 = \|u\|_{L^2(\mathbb{T}^2)}^2 + \cdot \cdot \cdot + \|\partial_x^s \partial_y^r u\|_{H^{-2}(\mathbb{T}^2)}$$
So it seems this space $A$ is a subset of $L^2$ where the dominating mixed derivatives are not quite in $L^2$ but rather in $H^{-2}$. So perhaps on other domains where I can't use the Fourier approach, I can go ahead and define $A$ in such a manner. Specifically, define $A^{s,r,t}(\Omega)$ to be subset of $L^2$ whose partial derivatives up to $\partial_x^s \partial_y^r$ are in $H^{-t}(\Omega)$. But $H^{-s}(\Omega)$ is usually the dual of $H_0^s(\Omega)$ and not $H^s(\Omega)$. Not sure why that is.
Perhaps it would be a good exercise to check $\partial_x$ and $\partial_y$ are bounded maps on $H^{1,1} \rightarrow A^{1,1,1}$.


text:
Q: Posicionamento de ImageButton no XML Tenho um imagebutton em um relative layout. Quando coloco o comando:
"android:layout_marginLeft="
Ele faz o pretendido (se afastar da borda da esquerda em x medida), mas quando coloco:
"android:layout_marginRight=" nada acontece.
Alguém saberia me explicar o porque? ou qual comando eu devo usar para que o espaçamento se de a partir do "começo da tela" na parte da direita?

A: Esta é a configuração necessária para que o seu ImageButton alinhe-se de acordo com o inicio e fim da tela. Verifique se não há nenhum alinhamento com o Parent, que no caso é o RelativeLayout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="78dp"
        android:layout_height="78dp"
        android:layout_marginLeft="10dp"
        //::layout_marginStart="10dp"
        android:layout_marginRight="10dp
        //::layout_marginEnd="10dp"
        android:src="@drawable/image_button" />

</RelativeLayout>

*

*Os atributos marginStart e marginEnd são opcionais.


text:
Q: "a symbol name was expected" error trying to create a table in phpMyAdmin I am trying to create a table in a database in phpMyAdmin and I keep getting the "a symbol name was expected" error and I cannot figure out what is going on.  Is my syntax wrong?  I am new to this and I'm at a loss.

A: You used ' ' sign in your column properties. But mySQL allow you to use `` sign.
CREATE TABLE IF NOT EXISTS `sales` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `name` varchar(50) NOT NULL,
        `item` varchar(50) NOT NULL,
        `date` varchar(50) NOT NULL,
        `amount` int(11) NOT NULL,
        PRIMARY KEY (`id`)
    );

A: Column names, table names should be surrounded by backticks(``)
CREATE TABLE IF NOT EXISTS `sales` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(50) NOT NULL,
    `item` varchar(50) NOT NULL,
    `date` varchar(50) NOT NULL,
    `amount` int(11) NOT NULL,
    PRIMARY KEY (`id`)
)

Or you can go without backticks as well:
CREATE TABLE IF NOT EXISTS sales (
    id int(11) NOT NULL AUTO_INCREMENT,
    name varchar(50) NOT NULL,
    item varchar(50) NOT NULL,
   date varchar(50) NOT NULL,
   amount int(11) NOT NULL,
   PRIMARY KEY (id)
)

A: Your code is wrong , So here is the correct Code :
CREATE TABLE IF NOT EXISTS `sales` (
    `id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(50) CHARACTER SET utf8 NOT NULL,
    `item` VARCHAR(50) CHARACTER SET utf8 NOT NULL,
    `date` VARCHAR(50) NOT NULL,
    `amount` int(11) NOT NULL
)


text:
Q: For window user authentication, have a window API that authenticates the user using a kerberos ticket?
*

*For window user authentication, have a window API that authenticates the user using a kerberos ticket? If any the API, I would like to know how to sign in to windows without a password.

*Have a easy way to issue a Keberos a ticket! (Ex: window API)
Can anyone give me advice,
Thanks & best regards


text:
Q: How can I create a dictionary for a large amount to text and list the most frequent word? I am new to coding and I am trying to create a dictionary from a large body of text and would also like the most frequent word to be shown?
For example, if I had a block of text such as:

text = '''George Gordon Noel Byron was born, with a clubbed right foot, in London on January 22, 1788. He was the son of Catherine Gordon of Gight, an impoverished Scots heiress, and Captain John ("Mad Jack") Byron, a fortune-hunting widower with a daughter, Augusta. The profligate captain squandered his wife's inheritance, was absent for the birth of his only son, and eventually decamped for France as an exile from English creditors, where he died in 1791 at 36.'''

I know the steps I would like the code to take. I want words that are the same but capitalised to be counted together so Hi and hi would count as Hi = 2.
I am trying to get the code to loop through the text and create a dictionary showing how many times each word appears. My final goal is to them have the code state which word appears most frequently.
I don't know how to approach such a large amount of text, the examples I have seen are for a much smaller amount of words.
I have tried to remove white space and also create a loop but I am stuck and unsure if I am going the right way about coding this problem.
a.replace(" ", "")
#this gave built-in method replace of str object at 0x000001A49AD8DAE0>, I have now idea what this means!

print(a.replace) # this is what I tried to write to remove white spaces

I am unsure of how to create the dictionary.
To count the word frequency would I do something like:
frequency = {}
for value in my_dict.values() :
    if value in frequency :
        frequency[value] = frequency[value] + 1
    else :
        frequency[value] = 1

What I was expecting to get was a dictionary that lists each word shown with a numerical value showing how often it appears in the text.
Then I wanted to have the code show the word that occurs the most.

A: This may be too simple for your requirements, but you could do this to create a dictionary of each word and its number of repetitions in the text.
text = "..." # text here.
frequency = {}
for word in text.split(" "):
    if word not in frequency.keys():
        frequency[word] = 1

    else:
        frequency[word] += 1

print(frequency)

This only splits the text up at each ' ' and counts the number of each occurrence.
If you want to get only the words, you may have to remove the ',' and other characters which you do not wish to have in your dictionary.
To remove characters such as ','  do.
text = text.replace(",", "")

Hope this helps and happy coding.

A: First, to remove all non-alphabet characters, aside from ', we can use regex
After that, we go through a list of the words and use a dictionary
import re
d = {}
text = text.split(" ")#turns it into a list
text = [re.findall("[a-zA-Z']", text[i]) for i in range(len(text))]
#each word is split, but non-alphabet/apostrophe are removed
text = ["".join(text[i]) for i in range(len(text))]
#puts each word back together
#there may be a better way for the short-above. If so, please tell.
for word in text:
    if word in d.keys():
        d[word] += 1
    else:
        d[word] = 1
d.pop("")
#not sure why, but when testing I got one key ""

A: You can use regex and Counter from collections :
import re
from collections import Counter

text = "This cat is not a cat, even if it looks like a cat"

# Extract words with regex, ignoring symbols and space
words = re.compile(r"\b\w+\b").findall(text.lower())

count = Counter(words)
# {'cat': 3, 'a': 2, 'this': 1, 'is': 1, 'not': 1, 'even': 1, 'if': 1, 'it': 1, 'looks': 1, 'like': 1}

# To get the most frequent
most_frequent = max(count, key=lambda k: count[k])
# 'cat'


text:
Q: Active link not working in wordpress Hi I need some help with an active link not working in my wordpress theme. In the blog archive page I made some buttons to divide the archives blogs in sub categories however the active pseudo not working.
The php i'm using to get the subcategories list is

  <?php $subcategories = get_categories('&child_of=5&hide_empty');
    echo '
';
    foreach ($subcategories as $subcategory) {
    echo sprintf('

    %s
', get_category_link
    ($subcategory->term_id), apply_filters('get_term', $subcategory->name));
    }
    echo '
';
  ?>

I've tried a few options but with no luck.
Any help would be appreciated.


text:
Q: Force the origin of start at 1 in GGstream plot I would like my Y axis to start at 1 on the x-axis, my first data point, and end at 3, my last data point, at the moment there is a cell on each side of my plot making the plot look like it starts in the middle of the graph. My x axis is categorical
I've tried fiddling with all the functions in the GGstream PDF (there aren't that many). I am wondering if the fix lays within the "mapping" function but I can't seem to get it to work, the PDF gives no indication how to use it, with the only option as "NULL". I have tried using GGPlot2 language such as

*

*scale_x_discrete(limits=c("1", "2" "3")

and

*

*coord_cartesian(xlim = c(1,3))

But I still have this extra "padding" around my data
Reprex:
library(ggstream)

Date <- c("1", "1", "2", "2", "3", "3")
Taxon <- c("Turtle", "Invert", "Turtle", "Invert", "Turtle", "Invert")
Freq <- c("100", "50", "50", "2", "35", "0")

stream <- data.frame(Date, Taxon, Freq)

stream$Date <- as.factor(stream$Date)

ggplot(stream, aes(x = Date, y = Freq, fill = Taxon)) +
geom_stream (extra_span = 0.8, bw = 1, sorting = c( "onset"), type = "ridge")

A: Add + coord_cartesian(expand = FALSE) to turn off default expansion of limits.

A: You can either use scale_x_discrete(expand = c(0, 0)) or coord_cartesian(expand = FALSE) to remove padding around your plot. Here is the documentation.


text:
Q: How do we prove that if $M$ is complete, any sequence $x_n \in M$ satisfying $d(x_n,x_{n+1}) < 2^{-n}$ converges in $M$? I'd like to show that if $M$ is a metric space $(M,d)$, and is complete, any sequence $x_n \in M$ satisfying $d(x_n,x_{n+1}) < 2^{-n}$ converges in $M.
My proof is the following:
I think that this question is the same as showing that if all Cauchy sequences, say  $x_n \in M$ are convergent in $M$ (by definition of complete), then that sequence $x_n$ must also satisfy the condition $d(x_n,x_{n+1}) < 2^{-n}$. Is the proof as simple as choosing $\epsilon \leq 2^{-n}$ and then letting $m=n+1$? Since if we have that we can say:
Suppose $x_n \in M$ is a Cauchy sequence. Hence, it must be convergent. Then, by definition this means that given $\epsilon >0$, there exists an $N$ such that if $m,n \geq N$, $d(x_m,x_n)< \epsilon$.
Hence, just choose $\epsilon$ small enough so that $\epsilon \leq 2^{-n}$ and then let $m=n+1$. Then, pugging into the above, we will have the following statement:
given $0<\epsilon  \leq 2^{-n}$, there exists an $N$ such that if $m=n+1,n \geq N$, $d(x_m,x_n) = d(x_{n+1}, x_n) < \epsilon \leq 2^{-n}$. Hence, $x_n \in M$ satisfies
$d(x_{n+1}, x_n) < 2^{-n}$. And, since $x_n$ is a Cauchy sequence in a complete space, its also convergent.
I am wondering if the above makes sense. I am a bit wary of the part where I "choose" and "fix" the $\epsilon$. Thank you!

A: The proof as stated is wrong. A simple counterexample is $(1,0,\frac{1}{3},0,\frac{1}{5},0,\ldots)$. Moreover, it tries to prove the wrong implication. What you need to prove is the following: if $(x_n)$ is a sequence in $M$ such that $d(x_n,x_{n+1})<2^{-n}$ for all $n\in \mathbb{N}$, then $(x_n)$ is a Cauchy sequence. This suffices, since $M$ is complete.
A proof for this statement would look like this: for all $m,n\in \mathbb{N}$ with $n\ge m$ it is true that $d(x_m,x_n)\le \sum_{k=m}^n d(x_k,x_{k+1})$. You can use induction to prove this. Choose $N$ such that $\sum_{k=m}^n 2^{-k}<\epsilon$ for all $n,m\ge N$. You can do this, since the geometric series converges (absolutely). It follows that $d(x_m,x_n)\le \sum_{k=m}^n d(x_k,x_{k+1})\le \sum_{k=m}^n 2^{-k}<\epsilon$ for all $m,n\ge N$, hence $(x_n)$ is a Cauchy sequence.

A: Your proof is correct. For some large enough $N$, the distance between subsequent terms $x_n,x_{n+1}$ in any Cauchy sequence is less then $2^{-n}$, for any $n>N$.
However, this is not what you have to prove. You need the other implication.
Let $\{x_n\}^\infty$ be a sequence satisfying the property from your question. Let $\varepsilon>0$. Now choose a natural $N$ such that $\varepsilon>2^{-N}$. Such a number exists since the naturals are not bounded from above. Finally, consider any two natural numbers $n,m>N$. Do you see, by the triangle inequality, that $d(x_n,x_m)<2^{-N}<\varepsilon$? This makes the sequence a Cauchy sequence, and therefore it converges by completeness.
Q.E.D.


text:
Q: c# LINQ query filling a Tuple List I need to fill a Tuple-List with values from a MSSQL-Database with help of Linq to Entities. The code snippet below will help to get a Tuple-List where 1 Database row reflects 1 Tuple Entry. In case there are 3 rows for calculateData we would get 3 Tuple Entries in that list created with Field1 to Field4.
The code below makes it possible:
var queryResult = (from a in calculate
                   join b in calculateData on a.Id equals b.CalcId into c
                   where a.SpecialID == 2023 && a.VersionId == 1
                   orderby a.InternalOrderNr ascending
                   select new
                   {
                        a.Field1,
                        a.Field2,
                        a.Field3,
                        myField4 = c.Select(d => new {
                                    d.Field1, d.Field2, d.Field3, d.Field4})
                    }).ToList();

var result = queryResult.Select(r => new Storage
{
    myField1 = r.Field1,
    myField2 = r.Field2,
    myField3 = r.Field3,
    myField4 = r.myField4.Select(t => new Tuple<int,int,decimal,string>
        (
            t.Field1,
            t.Field2,
            t.Field3,
            t.Field4)
        ).ToList()
});

return result;

But what I need is a bit different. I need for those 3 database rows in total 9 Tuple Entries in the list. Example:
Database contains 4 Columns (Column1, Column2, Column3, Column4) per row.
And we have 3 Rows.

Tuple 1: DB-Row1 and Column1, Column2, 0, 0
  Tuple 2: DB-Row1 and Columm2, Column3 ,0 ,1
  Tuple 3: DB-Row1 and Columm3, Column4 ,0 ,2
  Tuple 4: DB-Row2 and Column1, Column2, 1, 0
  Tuple 5: DB-Row2 and Columm2, Column3 ,1 ,1
  Tuple 6: DB-Row2 and Columm3, Column4 ,1 ,2
  Tuple 7: DB-Row3 and Column1, Column2, 2, 0
  Tuple 8: DB-Row3 and Columm2, Column3 ,2 ,1
  Tuple 9: DB-Row3 and Columm3, Column4 ,2 ,2

So the difference here is that there is not a 1:1 Mapping between database row and Tuple. I need to make several Tuple out of 1 Database row. In the example above we have 3 Tuple entries, but it can differ and can be more or less.

A: I guess something like this should work for you:
var queryResult = (from a in calculate
                   join b in calculateData on a.Id equals b.CalcId into c
                   where a.SpecialID == 2023 && a.VersionId == 1
                   orderby a.InternalOrderNr ascending
                   select new
                   {
                        a.Field1,
                        a.Field2,
                        a.Field3,
                        myField4 = c.Select(d => new {
                                    d.Field1, d.Field2,
                                    d.Field3, d.Field4
                                    d.Field5, d.Field6})
                    }).ToList();

var result = queryResult.Select(r => new Storage
{
    myField1 = r.Field1,
    myField2 = r.Field2,
    myField3 = r.Field3,
    myField4 = r.myField4.SelectMany(t => new []
    {
        Tuple<int,int>(t.Field1, t.Field2),
        Tuple<int,int>(t.Field3, t.Field4),
        Tuple<int,int>(t.Field5, t.Field6)
    }).ToList()
}).ToList();

return result;

Alternative version with double 'foreach' loop should work in the same way but it will not create redundant arrays of tuples:
var queryResult = (from a in calculate
                   join b in calculateData on a.Id equals b.CalcId into c
                   where a.SpecialID == 2023 && a.VersionId == 1
                   orderby a.InternalOrderNr ascending
                   select new
                   {
                        a.Field1,
                        a.Field2,
                        a.Field3,
                        myField4 = c.Select(d => new {
                                    d.Field1, d.Field2,
                                    d.Field3, d.Field4
                                    d.Field5, d.Field6})
                    }).ToList();

var result = new List<Storage>();
foreach(var row in queryResult){
  var storage = new Strorage
  {
    myField1 = r.Field1,
    myField2 = r.Field2,
    myField3 = r.Field3,
    myField4 = new List<Tuple<int,int>>()
  };
  foreach(var subRow in row.myField4)
  {
    storage.myField4.Add(Tuple<int,int>(t.Field1, t.Field2));
    storage.myField4.Add(Tuple<int,int>(t.Field3, t.Field4));
    storage.myField4.Add(Tuple<int,int>(t.Field5, t.Field6));
  }
}

return result;


text:
Q: c# Func Delegate - how to pass the value in generics I would like to use the Func in an interface - Generics . based on the input i would like to process the operation. But somehow I am not able to get the input in the function .
1) What should be the use case where I shall pass Func<> as a parameter?
2) Whats the advantage of returning Fuc<> as a return object ?
I created an interface .
 public interface IAutoFacDemo
 {
    Task<string> GetAsync(Func<string, Task<string>> concat, string input);
 }

Which has a concrete implementation of
public class BusConcat : IAutoFacDemo
{
    #region Implementation of IAutoFacDemo

    public BusConcat()
    {

    }

// ?? I am not able to extract the input string "dinesh" where from the program
// I passed it as an lambda expression
    public async Task<string> GetAsync(Func<string, Task<string>> concat, string input)
    {
        var v = Function(concat, input).Result;
        return (v);
    }

    private static async Task<string> Function(Func<string, Task<string>> bus, string input)
    {
        var v = await bus(Process("").Result).ConfigureAwait(false);
        return  v;
    }

    private static async Task<string> Process(string input)
    {
        return Task.FromResult( ":").Result;
    }
    #endregion
}

Then to consume the interface i created another interface for Autofac module load
public interface IFactory
{
    Task<string> GetValue(Func<string,Task<string>> fn,string input);
}

And from the main
 static void Main(string[] args)
    {
        var scope = AutoFacContainerConfig.RegisterLifetimeScope();
        {
            using (var resolveEntity = scope.BeginLifetimeScope())
            {
                var names =new List<string>{"dinesh","tripathi","avenue"};

                var factory = resolveEntity.Resolve<IFactory>();
                Console.WriteLine(factory.GetType().ToString());
                var x = string.Empty;
                var v=(x.Insert(0, names.First(xc => xc.Contains("dinesh"))));

// I am trying to call the Func<string,Task<string>> where i want to pass
//the list if it contains "dinesh" to the function and based on the string
//it will process the function

                var xx = factory.GetValue(async i=>i+await Task.FromResult(names.First(x1=>x1.Contains("dinesh"))),"Test").Result;
                Console.WriteLine(xx);
            }
        }
    }

I am getting dinesh:Test as an output , but i want to handle "dinesh" when passed the string as a lambda value to the Func

A: Great.  Got it . To get the lambda value "dinesh" in the Function GetAsync
I declared string variable and called Invoke on Concat to get the reult.
string ret=string.empty
var retVal=concat.Invoke(ret).Result

Got me "dinesh" as passed from the lambda expression.
Thanks all. :)


text:
Q: VBA ADO adDecimal Error - Precision not set I'm attempting to pass data into a Stored Procedure in a SQL Server database, however I get an error which states 'The Precision is Invalid'
Here's the code for for setting the variables
Set oDatabase = oDBInstance.GetSharedDatabase()

oDatabase.AddToParamList "@UniquePID", adInteger, 8, UniquePIDpm, adParamInput
oDatabase.AddToParamList "@ProjectStage", adVarChar, 50, cboProjectStage, adParamInput
oDatabase.AddToParamList "@Area", adVarChar, 100, cboArea, adParamInput
oDatabase.AddToParamList "@RevisedCycleTime", adInteger, 8, (cboRevisedCTHours * 60) + cboRevisedCTMins, adParamInput
oDatabase.AddToParamList "@RevisedSelectionRate", adInteger, 8, txtRevisedSelectionRate, adParamInput
oDatabase.AddToParamList "@RevisedCycleRate", adDecimal, 8, CDbl(lblRevisedCycleRate), adParamInput

oDatabase.ExecuteStoredProc ("[dbo].[InsertUpdateMetrics]")

If I remove the @RevisedCycleRate parameter from the stored procedure and run the code without passing the decimal through the code runs fine and the SQL stored procedure runs (with the exception of adding the Revised Cycle Rate to the table).
I'm not sure what I'm doing wrong.
I'm at the point where I'm considering making the value a whole number by multiplying by 100 (it's a value with 2 decimal places) and passing it in as an Integer, then dividing by 100 within the stored procedure.
Any help is much appreciated.


text:
Q: Now able to use the XN and XO command in azcopy I am doing azure blob uploading winform application using azcopy.
In that i am able to upload and download the files.but i am need to download the blobs only based on the time of the modification so i used the /XO command as below but it does not work for me.
AzCopy.exe /Source:https://portalvhdsq3jyv0y3gccrn.blob.core.windows.net/sampes /Dest:C:/localblobs /SourceKey:VVPgjNO9V3397kOvoJRRZKtZVZaVNQP2xFPTNoWEp8zPJh4n487HVmwup498T8iufFnDS1Icu0EmUKyHg+DdkA== /MT /XO

even i tried the following command its also not working fine
AzCopy.exe /Source:https://portalvhdsq3jyv0y3gccrn.blob.core.windows.net/sampes /Dest:C:/localblobs /SourceKey:VVPgjNO9V3397kOvoJRRZKtZVZaVNQP2xFPTNoWEp8zPJh4n487HVmwup498T8iufFnDS1Icu0EmUKyHg+DdkA== /MT /XN

can any one give me suggestion


text:
Q: notifyDataSetChanged() does not affect my adapterView I am new to android and I have to create an android app for my final project.
I am making a swipe card app and I am using 'com.lorentzos.swipecards:library:1.0.9' library for the swiping engine.
It uses a custom adapter that extends a base adapter to inflate a layout file and populate certain ImageViews and TextViews with iformation coming from an ArrayList.
This is the code of the adapter
package com.botevplovdiv.foodmatch2;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Stelio on 13.5.2017 г..
 */

public class MyAppAdapter extends BaseAdapter {

    private static class ViewHolder {
        public FrameLayout background;
        public TextView DataText;
        public ImageView cardImage;
        public TextView shortDescriptionTextView;
        public TextView title;
    }
    ;
    public List<FoodDish> dishesList = new ArrayList<>();
    public Context mContext;

    public MyAppAdapter(Context context, List<FoodDish> foodDishes) {
        this.dishesList = foodDishes;
        this.mContext = context;
    }

    @Override
    public int getCount() {
        return dishesList.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public List<FoodDish> getDishesList(){
        return this.dishesList;
    }

    public void updateReceiptsList(List<FoodDish> newlist) {
        dishesList.clear();
        dishesList.addAll(newlist);
        this.notifyDataSetChanged();
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        FoodDish current = dishesList.get(position);

        ViewHolder viewHolder;

        if (convertView == null) {

            LayoutInflater inflater = LayoutInflater.from(mContext);
            convertView = inflater.inflate(R.layout.cards_layout, parent,false);
            // configure view holder
            viewHolder = new ViewHolder();
            viewHolder.DataText = (TextView) convertView.findViewById(R.id.priceText);
            viewHolder.background = (FrameLayout) convertView.findViewById(R.id.background);
            viewHolder.cardImage = (ImageView) convertView.findViewById(R.id.cardImage);
            viewHolder.shortDescriptionTextView = (TextView) convertView.findViewById(R.id.shortDescription);
            viewHolder.title = (TextView) convertView.findViewById(R.id.titleText);

            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.DataText.setText(current.getPrice());
        viewHolder.title.setText(current.getTitle());
        viewHolder.shortDescriptionTextView.setText(current.getDescription());
        Glide.with(mContext).load(current.getImagePath()).into(viewHolder.cardImage);

        return convertView;
    }
}

Everything is going fine till one point.
I have a Settings activity, which inflates a preferences.xml which has a bunch of switches. I could do it using MultiSelectListPreferences, but I want to be with switches for aesthetic reasons.
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory
    android:selectable="true"
    android:title="@string/food_categories_name">

    <SwitchPreference
        android:defaultValue="true"
        android:key="fishSwitch"
        android:title="Fish" />
    <SwitchPreference
        android:defaultValue="true"
        android:key="meatSwitch"
        android:title="Meat" />
    <SwitchPreference
        android:defaultValue="true"
        android:key="vegSwitch"
        android:title="Vegeterian" />
    <SwitchPreference
        android:defaultValue="true"
        android:key="pizzaSwitch"
        android:title="Pizza" />
    <SwitchPreference
        android:defaultValue="true"
        android:key="pastaSwitch"
        android:title="Pasta" />
</PreferenceCategory>

<ListPreference
    android:defaultValue="@array/area_list"
    android:entries="@array/area_list"
    android:entryValues="@array/area_list"
    android:key="list_preference_1"
    android:title="@string/areas" />
<PreferenceCategory android:title="@string/venues_categories">

    <SwitchPreference
        android:defaultValue="true"
        android:key="restaurantSwitch"
        android:title="Restaurants" />
    <SwitchPreference
        android:defaultValue="true"
        android:key="takeAwaySwitch"
        android:title="Take Away" />
</PreferenceCategory>

In my MainActivity I have prefereceChangedListner which register changes and refine the searcCriteria and refineList Lists throught the respectful methods.
package com.botevplovdiv.foodmatch2;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.SwitchPreference;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    // keys for reading data from SharedPreferences
    public static final String FISH = "fishSwitch";
    public static final String MEAT = "meatSwitch";
    public static final String VEGETARIAN = "vegSwitch";
    public static final String PIZZA = "pizzaSwitch";
    public static final String PASTA = "pastaSwitch";
    public static final String RESTAURANTS = "restaurantSwitch";
    public static final String TAKEAWAY = "takeAwaySwitch";

    private MyAppAdapter myAppAdapter;
    private List<FoodDish> dishList;
    private List<FoodDish> refineList;
    private List<FoodDish> dumpList;
    private List<Venue> venues;
    private boolean[] booleans;
    private String[] booleansTags;
    private List<String> searchCriteria;
    private SwipeFlingAdapterView flingContainer;
    public static Map<String, Bitmap> bitmaps = new HashMap<>();
    boolean fishSwitch;
    boolean meatSwitch;
    boolean vegetarianSwitch;
    boolean pizzaSwitch;
    boolean pastaSwitch;
    boolean restaurantSwitch;
    boolean takeAwaySwitch;
    boolean preferenceChanged = true;
    String TAG = "FoodMatch";

    @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);

        // set default values in the app's SharedPreferences
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

        // register listener for SharedPreferences changes
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        sharedPreferences.registerOnSharedPreferenceChangeListener(
                preferencesChangeListener);

        fishSwitch = sharedPreferences.getBoolean(FISH,false);
        meatSwitch =  sharedPreferences.getBoolean(MEAT,false);
        vegetarianSwitch =  sharedPreferences.getBoolean(VEGETARIAN,false);
        pizzaSwitch =  sharedPreferences.getBoolean(PIZZA,false);
        pastaSwitch =  sharedPreferences.getBoolean(PASTA,false);
        restaurantSwitch =  sharedPreferences.getBoolean(RESTAURANTS,false);
        takeAwaySwitch =  sharedPreferences.getBoolean(TAKEAWAY,false);

        booleansTags = new String[] {"FISH","MEAT","VEGETARIAN","PIZZA","PASTA","RESTAURANT","TAKE AWAY"};

        dishList = new ArrayList<>();
        searchCriteria = new ArrayList<>();
        refineList = new ArrayList<>();
        dumpList = new ArrayList<>();

        // load initial data
        loadDishes();

        createSearchCriteria(searchCriteria);
        refineDishesList();

        //lock the device to portrait mode
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        myAppAdapter = new MyAppAdapter(this, refineList);
        flingContainer.setAdapter(myAppAdapter);
        flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
            @Override
            public void removeFirstObjectInAdapter()
            {

            }

            @Override
            public void onLeftCardExit(Object dataObject)
            {
                FoodDish current = refineList.get(0);
                refineList.remove(0);
                myAppAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onRightCardExit(Object dataObject)
            {
                FoodDish current = refineList.get(0);
                Intent intent = new Intent(MainActivity.this,LikedProduct.class).putExtra("current",current);
                startActivity(intent);
                refineList.remove(0);
                myAppAdapter.notifyDataSetChanged();

            }

            @Override
            public void onAdapterAboutToEmpty(int itemsInAdapter)
            {

            }

            @Override
            public void onScroll(float scrollProgressPercent) {
                View view = flingContainer.getSelectedView();
                view.findViewById(R.id.background).setAlpha(0);
                view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
                view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);
            }
        });

        // Listener for touching events
        flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClicked(int itemPosition, Object dataObject) {

                View view = flingContainer.getSelectedView();
                view.findViewById(R.id.background).setAlpha(0);
                myAppAdapter.notifyDataSetChanged();
            }
        });

        //floating buttons for remote flipping the cards

        FloatingActionButton yesFAB =
                (FloatingActionButton) findViewById(R.id.acceptButton);
        yesFAB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!refineList.isEmpty())
                    flingContainer.getTopCardListener().selectRight();

            }
        });

        FloatingActionButton noFAB =
                (FloatingActionButton) findViewById(R.id.rejectButton);
        noFAB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!refineList.isEmpty())
                    flingContainer.getTopCardListener().selectLeft();

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG,"Entered onStart() method in MainActivity");

        if (preferenceChanged){
            myAppAdapter.notifyDataSetChanged();
            preferenceChanged = false;
        }
    }

    private void refineDishesList() {
        if (this.refineList.size() > 0)
        {
            this.refineList.clear();
        }
        for (FoodDish dish : this.dishList){
            if (this.searchCriteria.contains(dish.getCategory().toUpperCase()) && this.searchCriteria.contains(dish.getVenueType().toUpperCase())){
                this.refineList.add(dish);
            }
        }
    }

    private void createSearchCriteria(List<String> searchCriteria){
        booleans = new boolean[]{fishSwitch,meatSwitch,vegetarianSwitch,pizzaSwitch,pastaSwitch,restaurantSwitch,takeAwaySwitch};
        if (searchCriteria.size() >0){
            searchCriteria.clear();
        }
        for (int i = 0;i < booleansTags.length;i++){
            boolean temp = booleans[i];
            if (temp){
                searchCriteria.add(booleansTags[i]);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent preferencesIntent = new Intent(this, Settings.class);
        startActivity(preferencesIntent);
        return super.onOptionsItemSelected(item);
    }

    public void loadDishes(){
        dishList.add(new FoodDish("Shrimp dish","https://cdn.pixabay.com/photo/2015/04/10/00/41/food-715539_960_720.jpg",getString(R.string.test),"Price : 2,14", "FISH","Restaurant"));
        dishList.add(new FoodDish("Pizza ultra mega qkata rabota","http://www.seattleorganicrestaurants.com/vegan-whole-foods/images/Food-Guidelines.jpg","Test description.This a very tasty dish and you should definitely order it.I don`t know what are you waiting for", "Price: 3,87", "PIZZA","Take Away"));
        dishList.add(new FoodDish("Pasta","http://assets.simplyrecipes.com/wp-content/uploads/2008/03/pasta-tuna-arugula-horiz-a-1600.jpg",getString(R.string.test), "Price: 4,87","PASTA","Restaurant"));
        dishList.add(new FoodDish("Chicken wings","http://cf.yellowblissroad.com/wp-content/uploads/2015/02/Baked-Chicken-Wings.jpg",getString(R.string.test),"Price: 1,23","MEAT","Take Away"));
        dishList.add(new FoodDish("Fish","http://cdn.skim.gs/image/upload/v1456339187/msi/grilled-catfish_izglgf.jpg",getString(R.string.test), "Price: 5,87", "FISH","Take Away"));
        dishList.add(new FoodDish("Spaghetti","http://food.fnr.sndimg.com/content/dam/images/food/fullset/2009/6/12/2/FO1D41_23785_s4x3.jpg.rend.hgtvcom.616.462.jpeg",getString(R.string.test), "Price: 9,23", "PASTA","Restaurant"));
        dishList.add(new FoodDish("Ceasar salad","http://entomofarms.com/wp-content/uploads/2016/04/EF-caesar-salad-cricket-powder.jpg",getString(R.string.test), "Price: 3,45", "VEGETARIAN","Restaurant"));
        dishList.add(new FoodDish("Steak sandwich","http://s3.amazonaws.com/finecooking.s3.tauntonclud.com/app/uploads/2017/04/18125307/051120015-01-steak-sandwich-recipe-main.jpg",getString(R.string.test), "Price: 3,45","MEAT","Take Away"));
        dishList.add(new FoodDish("Lasagna","http://www.weightlossresources.co.uk/img/recipes/vegetarian-dishes.jpg",getString(R.string.test), "Price: 11,45","VEGETERIAN","Restaurant"));
        dishList.add(new FoodDish("Sea Food Risotto","http://www.dvo.com/recipe_pages/healthy/Lemony_Seafood_Risotto.jpg",getString(R.string.test), "Price: 8,45","VEGETERIAN","Take Away"));
    }

    private SharedPreferences.OnSharedPreferenceChangeListener preferencesChangeListener =
            new SharedPreferences.OnSharedPreferenceChangeListener() {
                @Override
                public void onSharedPreferenceChanged(
                        SharedPreferences sharedPreferences, String key) {
                    switch (key){
                        case FISH:
                            fishSwitch = sharedPreferences.getBoolean(FISH,false);
                            createSearchCriteria(searchCriteria);
                            refineDishesList();
                            myAppAdapter.notifyDataSetChanged();
                            preferenceChanged = true;
                            break;
                        case MEAT:
                            meatSwitch = sharedPreferences.getBoolean(MEAT,false);
                            createSearchCriteria(searchCriteria);
                            refineDishesList();
                            myAppAdapter.notifyDataSetChanged();
                            preferenceChanged = true;
                            break;
                        case VEGETARIAN:
                            vegetarianSwitch = sharedPreferences.getBoolean(VEGETARIAN,false);
                            createSearchCriteria(searchCriteria);
                            refineDishesList();
                            myAppAdapter.notifyDataSetChanged();
                            preferenceChanged = true;
                            break;
                        case PIZZA:
                            pizzaSwitch = sharedPreferences.getBoolean(PIZZA,false);
                            createSearchCriteria(searchCriteria);
                            refineDishesList();
                            myAppAdapter.notifyDataSetChanged();
                            preferenceChanged = true;
                            break;
                        case PASTA:
                            pastaSwitch = sharedPreferences.getBoolean(PASTA,false);
                            createSearchCriteria(searchCriteria);
                            refineDishesList();
                            myAppAdapter.notifyDataSetChanged();
                            preferenceChanged = true;
                            break;
                        case RESTAURANTS:
                            restaurantSwitch = sharedPreferences.getBoolean(RESTAURANTS,false);
                            createSearchCriteria(searchCriteria);
                            refineDishesList();
                            myAppAdapter.notifyDataSetChanged();
                            preferenceChanged = true;
                            break;
                        case TAKEAWAY:
                            takeAwaySwitch = sharedPreferences.getBoolean(TAKEAWAY,false);
                            createSearchCriteria(searchCriteria);
                            refineDishesList();
                            myAppAdapter.notifyDataSetChanged();
                            preferenceChanged = true;
                            break;

                    } //end of switch statement
        }
    };

}

The problem is after I change some of the switches, the adapter doesn`t update properly and still shows the last loaded "card".
If the refineList is empty however(e.g. there are mo object to show ), then everything works fine.
I read a lot of posts about my issue, but everywhere they say that the notifyDataSetChanged() should update the view.
I wrote a method in the adapter that updates the list that is assosiated with the adapter , but even if I use it , nothing happens.
Any suggestion what I am doing wrong?
If you need , I can post the code of SwipeFlingAdapterView class of the library I am using.
UPDATE
I forgot to mention that I tried returning to MainActivity from SetingsActivity both ways -> with the Up button of the SettingsActivity ( which parent is MainActivity) and with the hardware back button of the Android device.
1.If I use the UP button, everything works perfect and how I want it, but the Logcat is showing me that on return it destroys the current MainActivity and creates a new one and therefore my Adapter is restarted and I don`t think that this is very efficient.
2.If I use the back button on the device, when I am back to MainActivity it calls the onRestart() method and the top view is not updated. After I swipe it makes some update but it is definitely not what I want and I am completely stuck.
It turns out that there is a bug in the library and when you call notifyDataSetChanged() the control doesn`t go to getView() when you are using SwipeFlingAdapterView.If you use a normal ListView it works fine. So I just call flingContainer.removeAllViewsInLayout(); before calling notifyDataSetChanged() and works good.

A: just quick review on the code, is this part of code correct?
@Override
public Object getItem(int position) {
    return position;
}

why don't change it to
@Override
public Object getItem(int position) {
    return dishesList.get(position);
}

will check it out sometime later


text:
Q: How to send email of SQLite database using Intent.EXTRA_TEXT? I am trying to simply send an email with the data from my database as text in the email.
I have searched a ton of posts, and do not want to send as an attachment, I do not want to save to external storage etc. and cannot find what I am looking for.
I would like all the rows from the database to populate, but can only manage to get a single row.  Any help would be greatly appreciated.
    @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                String[] projection = {
                        LogEntry._ID,
                        LogEntry.COLUMN_LOG_DATE,
                        LogEntry.COLUMN_LOG_DESTINATION,
                        LogEntry.COLUMN_LOG_PURPOSE,
                        LogEntry.COLUMN_LOG_MILEAGE};

                Cursor cursor = getContentResolver().query(
                        LogEntry.CONTENT_URI,
                        projection,
                        null,
                        null,
                        null);

                //TODO ???????????? I want the cursor to continue and get all the data from the database???
                //This is the current result in the email.
                // 1
                // 05 Mar 2018
                // 12:10:52 PM
                // 0
                // 0
                // 88031

                // Extract the properties from cursor
                // Find columns of log attributes that I am interested in
                int idColumnIndex = cursor.getColumnIndex(LogEntry._ID);
                int dateColumnIndex = cursor.getColumnIndex(LogEntry.COLUMN_LOG_DATE);
                int destinationColumnIndex = cursor.getColumnIndex(LogEntry.COLUMN_LOG_DESTINATION);
                int purposeColumnIndex = cursor.getColumnIndex(LogEntry.COLUMN_LOG_PURPOSE);
                int mileageColumnIndex = cursor.getColumnIndex(LogEntry.COLUMN_LOG_MILEAGE);

                String id = cursor.getString(idColumnIndex);
                String date = cursor.getString(dateColumnIndex);
                int destination = cursor.getInt(destinationColumnIndex);
                int purpose = cursor.getInt(purposeColumnIndex);
                String mileage = cursor.getString(mileageColumnIndex);

                Intent emailIntent = new Intent(Intent.ACTION_SEND);
                emailIntent.setType("message/rfc822");
                emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"recipent@gmail.com"});
                emailIntent.putExtra(Intent.EXTRA_SUBJECT, "All Logs for " + LogEntry.COLUMN_LOG_DATE);
                emailIntent.putExtra(Intent.EXTRA_TEXT, id + "\n" + date + "\n" + destination + "\n" + purpose + "\n" + mileage);
                startActivity(Intent.createChooser(emailIntent, "Select App"));

A: Thank You CommonsWare for answering this question. I indeed used the Stringbuilder and it worked flawlessly. Exactly what I wanted.
Here is the code now.
     @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                StringBuilder stringBuilder = new StringBuilder();

                String[] projection = {
                        LogEntry._ID,
                        LogEntry.COLUMN_LOG_DATE,
                        LogEntry.COLUMN_LOG_DESTINATION,
                        LogEntry.COLUMN_LOG_PURPOSE,
                        LogEntry.COLUMN_LOG_MILEAGE};

                Cursor cursor = getContentResolver().query(
                        LogEntry.CONTENT_URI,
                        projection,
                        null,
                        null,
                        null);

                //if the cursor isn't null we will essentially iterate over rows and then columns
                //to form a table of data as per database.
                if (cursor != null) {

                    //more to the first row
                    cursor.moveToFirst();

                    //iterate over rows
                    for (int index = 0; index < cursor.getCount(); index++) {

                        //iterate over the columns
                        for(int j = 0; j < cursor.getColumnNames().length; j++){

                            //append the column value to the string builder and delimit by a pipe symbol
                            stringBuilder.append(cursor.getString(j) + " | ");
                        }
                        //add a new line carriage return
                        stringBuilder.append("\n");

                        //move to the next row
                        cursor.moveToNext();
                    }
                    //close the cursor
                    cursor.close();
                }

                Intent emailIntent = new Intent(Intent.ACTION_SEND);
                emailIntent.setType("message/rfc822");
                emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"recipent@gmail.com"});
                emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Logs for " + ;
                emailIntent.putExtra(Intent.EXTRA_TEXT, stringBuilder.toString()); //id + "\n" + date + "\n" + destination + "\n" + purpose + "\n" + mileage);
                startActivity(Intent.createChooser(emailIntent, "Select App"));


text:
Q: ORA-00979 Not a GROUP BY Expression with complex EXTRACTVALUE I'm trying to execute a rather simple Oracle query against a table with a XMLTYPE column:
Select POB_CODPOL, CODSIS From (
    Select T1.POB_CODPOL, EXTRACTVALUE(T1.POB_XMLPOL, '/Polbas/polfun[nomfun="filterBySystem"]/extpar[codele="codsis"]/valele/text()') CODSIS
    From TDTX_POLITICA_CLOB T1
    Where T1.POB_CODEMP = '001840'
)
Group By POB_CODPOL, CODSIS

This throws a ORA-00979 Not a GROUP BY Expression, which I don't really understand.
Even worse: when I execute the exact same query, but with a simplified XPATH query does work:
Select POB_CODPOL, CODSIS From (
    Select T1.POB_CODPOL, EXTRACTVALUE(T1.POB_XMLPOL, 'Polbas/codpol/text()') CODSIS
    From TDTX_POLITICA_CLOB T1
    Where T1.POB_CODEMP = '001840'
)
Group By POB_CODPOL, CODSIS

It looks like Oracle doesn't like conditions like [nomfun="filterBySystem"] when using a GROUP BY (without the grouping clause, everything works fine).
Any idea on why this can be happening?
Edit: the result of the inner query is rather simple:

A: EXTRACTVALUE is deprecated.
Oracle recommends to use XMLQUERY, XMLTABLE for it.
This one should work:
WITH t as
    (SELECT T1.POB_CODPOL, x.CODSIS
     FROM TDTX_POLITICA_CLOB T1
          NATURAL JOIN XMLTABLE('/Polbas/polfun[nomfun="filterBySystem"]/extpar[codele="codsis"]/valele'
             PASSING POB_XMLPOL COLUMNS
             CODSIS VARCHAR2(50) PATH '/') x
     Where T1.POB_CODEMP = '001840')
SELECT POB_CODPOL, CODSIS
FROM t
GROUP BY POB_CODPOL, CODSIS;

A: There's a Bug 28588011 : "ORA-00979: NOT A GROUP BY EXPRESSION" WHEN TABLE FORMAT IS BINARY XML.
Severity    2 - Severe Loss of Service
Created 02-Sep-2018
Status  11 - Code/Hardware Bug (Response/Resolution)
WORKAROUND No

I guess they won't fix it. But the hint NO_XML_QUERY_REWRITE (that I use for other XML related bugs, too) worked for me.


text:
Q: python-qt4 module installation Ubuntu 14.04 LTS I am trying to use the code here:
https://impythonist.wordpress.com/2015/01/06/ultimate-guide-for-scraping-javascript-rendered-web-pages/
When I run the code I get this error:
$ python javascrape.py

Traceback (most recent call last):
  File "javascrape.py", line 2, in <module>
    from PyQt4.QtGui import *
ImportError: No module named PyQt4.QtGui

After looking over many old solutions to this problem, the answer was supposed to be:
sudo apt-get install python-qt4

But, I have done this and the issue persists.
I am using Ubuntu 14.04 LTS and Python 2.7.5
Any help would be much appreciated.
I can even run:
python /usr/share/doc/python-qt4-doc/examples/tutorials/addressbook/part1.py

and get:
Traceback (most recent call last):
  File "/usr/share/doc/python-qt4-doc/examples/tutorials/addressbook/part1.py", line 45, in <module>
    from PyQt4 import QtCore, QtGui
ImportError: No module named PyQt4


text:
Q: Implicit Callback redirects to the Angular component and then to homepage automatically So I connected my Angular App to Okta login functionality.
Here is the scenario - Below is the routes setup. When the user lands on the site localhost home is displayed - works fine. User clicks on Login button on Navbar, the redirect to Okta login page works as well. Then the Users enters the credentials and authenticates successfully the redirect to localhost implicit/callback is triggered and it should now display the localhost secureuserhome and stop, instead it automatically redirects to localhost home again. At this point if I press the browser back button i can see the secureuserhome page that the callback should have stopped at. I need some help why the callback redirects to the homepage and not just the callback component.
const routes: Routes = [
  {path: '', redirectTo: '/home', pathMatch: 'full'},
  { path: 'home', component: ToolsComponent },
  { path: 'tool1lm', component: Tool1learnmoreComponent },
  { path: 'tool1try', component: Tool1trialComponent},
  { path: 'implicit/callback', redirectTo: '/secureuserhome', pathMatch: 'full'},
  { path: 'secureuserhome', component: SecureuserhomeComponent}
];

Here is the app.component.html setup.
<app-navbar></app-navbar>

{{headermessage}}

<router-outlet></router-outlet>

The secureuserhome template is below. My understanding is when secureuserhome gets called this html should be displayed in place of the router outlet along with the other stuff in app component html above.

Hello!

I am Authenticated...

Okta Login Successful

Let me know I should provide any other code fragments or setup.

A: The problem seems to be with routing and redirect URL. I have implemented Okta exampleand this is what my routing looks like
export function onAuthRequired({ oktaAuth, router }) {
  // Redirect the user to your custom login page
     router.navigate(['/login']);
}

const appRoutes: Routes = [
  {
    path: 'implicit/callback',
    component: OktaCallbackComponent
  },
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'protected',
    component: ProtectedComponent,
    canActivate: [ OktaAuthGuard ],
    data: {
      onAuthRequired
    }
  }

Hope this helps :)


text:
Q: How to create txt or csv file by tsql I have a temp table in sql server 2008 and I need to create a csv of txt file by tsql from that temp table.
What is the correct way for it?
Thanks.

A: select col1 + "," + col2
from table

send results to file

A: If you provide tempdb.. it can access temp tables
exec master..xp_cmdshell 'bcp " select * from tempdb..#tables" queryout c:\test.txt -c -T'


text:
Q: Java repaint() method doesn't work when I try to delete shapes from panel I would like to draw some circles every second and delete them all (or at least one) from the panel.
Here is the exisiting code:
    public class DrawShape {
        ShapePanel panel;
        public DrawShape(ShapePanel panel) {
            this.panel = panel;

            Timer t = new Timer();
            t.schedule(new TimerTask() {
                long startTime = System.currentTimeMillis();
                int secondsToRun = 3;
                @Override
                public void run() {
                    if (System.currentTimeMillis() - startTime > secondsToRun * 1000) {
                        panel.deleteCircle();
                        System.out.println("\t" + panel.circles.size());
                        cancel();
                    } else {
                        panel.addCircle(new Circle((int) (Math.random() * 200), (int) (Math.random() * 200)));
                        System.out.println(panel.circles.size());
                    }
                }
            }, 0, 1000);
        }
    }

If the time is greater than 3 seconds, delete all circles, else continue to draw circles on screen.
Here is the ShapePanel class:
    public class ShapePanel extends JPanel {

        public List<Circle> circles = new LinkedList<Circle>();

        public ShapePanel() {

            // Setting up the frame
            JFrame frame = new JFrame();
            frame.setSize(500, 500);
            frame.setVisible(true);
            frame.setBackground(Color.black);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(this); // adding the panel to the frame
        }

        public void addCircle(Circle circle) {
            circles.add(circle);
            this.repaint();
        }

        public void deleteCircle() {
    //        circles.remove(circles.get(0));
            circles.clear(); //remove them all
            this.repaint();

        }

        @Override
        public void paint(Graphics g) {
            for (Circle c : circles) {
                g.setColor(Color.GREEN);
                g.drawOval(c.x, c.y, Circle.radius * 2, Circle.radius * 2);
            }
        }
    }

When I call deleteCircle(), the circles should be removed from the list and repaint. I should end up with a blank screen with no circles in it. I think repaint doesn't work in this case.
P.S.: first time asking a question, so sorry if it's long one :D

A: So, two things jump out at me immediately.

*

*Using java.util.Timer
Swing is NOT thread safe and since java.util.Timer runs in it's own thread, updating the UI (or in this case, something the UI relies on) could cause you random issues.
I'd consider using a javax.swing.Timer instead, as it is triggered inside the Event Dispatching Queue (and is generally simpler to use)

*Not calling super.paint
You've failed to take into consideration what paint does and failed to take over it's responsibilities, which, in this case, would be to "prepare" the Graphics context for painting.
Graphics is a shared resource, which is passed to all the components been updated in the paint pass.  This means it will contain what ever was previously painted to it.
Two recommendations:

*

*As a general recommendation, prefer overriding paintComponent instead of paint (paint does a lot of important jobs, so unless you're willing to do them, it's generally to high up in the paint chain)

*Call super.paintComponent first, before doing any custom painting.

I would, highly, recommend reading:

*

*Performing Custom Painting

*Painting in AWT and Swing
and

*

*Concurrency in Swing

*How to Use Swing Timers


text:
Q: Why is UITest.Maps filename null during UITestClass.Saving? I'm writing a coded ui package extension, and have it hooked up like this:
public override object GetService(Type serviceType)
      {
         if (!_initialized)
         {
            _initialized = true;
            UITestClass.Saving += OnUiTestSave;
         }

         return null;
      }

Then inside that method:
private void OnUiTestSave(object sender, UITestEventArgs e)
      {
         if (e.UITest != null && e.UITest.Maps != null && e.UITest.Maps.Count == 1)
         {
            foreach (TopLevelElement topLevelElement in e.UITest.Maps[0].TopLevelWindows)
            {
               LoopThroughAll(topLevelElement, topLevelElement.Id);
            }
         }
      }

Notice in the above code e.UITest.Maps[0] actually exists and is totally valid, but I need to get the filename. The property exists but it's always null.
Is this a Microsoft bug?


text:
Q: Bypass javascript errors for graceful degradation I have a javascript function which is called onclick of a button. It is working fine in chrome and firefox. It basically places some validation checks, so that in case of incomplete information form is not submitted to the server.
My question is that if in some browser the javascript function has some syntax errors, how can I ignore the errors, so that validation function is bypassed, after all validation function is just to reduce invalid form submits and checks are also placed on the server.

A: Its very unlikely (if not impossible), that you write some ECMAscript code which works fine on some engines and throws syntax errors on others. Unless you're dealing with something like IE4 or real old Netscape browsers.
However, you can of course always wrap your code into try..catch blocks, like
try {
   // beautiful javascript code
} catch( ex ) {
   alert(ex.message);
}


text:
Q: Changing background of spinner items based on sqlite data I am changing the background color of the items in my spinner based on the data provided by my SQLite query. I've used getDropDownView method to check the data and change the background color.
Now let's suppose I have 2 records on my SQLite table with ids 1 and 2. The issue that I'm facing is that only the last record (in this case record with id: 2) gets the background color. This is what I'm doing:
    ArrayAdapter<Category> categoryAdapter = new ArrayAdapter<Category>(getActivity(),
                    android.R.layout.simple_dropdown_item_1line, categoryList){
                @Override
                public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                    View row = null;
                    Category category = (Category) getItem(position);
                    Cursor crsCheckCatAva = database.rawQuery("SELECT distinct category_id FROM "+ ItemsTable.TABLE_OUTLET_DATA +" WHERE "+ ItemsTable.COLUMN_OUTLET_DATA_OUTLET_ID +"='"+ Info.getInstance().getOutletID() +"'", null);
                    if(crsCheckCatAva.getCount() > 0){
                        while (crsCheckCatAva.moveToNext()){
                            if(crsCheckCatAva.getInt(crsCheckCatAva.getColumnIndex("category_id")) == category.getCategory_id()){
                                row = super.getDropDownView(position, convertView, parent);
                                row.setBackgroundColor(Color.GRAY);
                            }else {
                                row = super.getDropDownView(position, null, parent);
                                row.setBackgroundColor(Color.WHITE);
                            }
                        }
                    }else {
                        row = super.getDropDownView(position, null, parent);
                    }
                    crsCheckCatAva.close();

                    return row;
                }
            };
 categorySelectionSpinner.setAdapter(categoryAdapter);

This is the output:
01-15 19:19:16.361 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 0
01-15 19:19:16.362 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 0
01-15 19:19:16.363 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 4
01-15 19:19:16.363 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 4
01-15 19:19:16.364 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 6
01-15 19:19:16.365 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 6
01-15 19:19:16.366 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 7
01-15 19:19:16.366 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 7
01-15 19:19:16.368 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 8
01-15 19:19:16.368 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 8
01-15 19:19:16.370 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 26
01-15 19:19:16.371 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 26
01-15 19:19:16.372 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 27
01-15 19:19:16.372 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 27
01-15 19:19:16.373 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 28
01-15 19:19:16.374 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 28
01-15 19:19:16.375 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 29
01-15 19:19:16.375 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 29
01-15 19:19:16.379 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 30
01-15 19:19:16.381 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 30
01-15 19:19:16.382 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 31
01-15 19:19:16.382 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 31
01-15 19:19:16.386 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 0
01-15 19:19:16.387 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 0
01-15 19:19:16.388 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 4
01-15 19:19:16.388 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 4
01-15 19:19:16.389 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 6
01-15 19:19:16.390 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 6
01-15 19:19:16.391 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 7
01-15 19:19:16.391 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 7
01-15 19:19:16.394 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 8
01-15 19:19:16.394 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 8
01-15 19:19:16.396 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 26
01-15 19:19:16.397 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 26
01-15 19:19:16.398 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 27
01-15 19:19:16.399 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 27
01-15 19:19:16.401 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 28
01-15 19:19:16.401 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 28
01-15 19:19:16.403 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 29
01-15 19:19:16.404 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 29
01-15 19:19:16.405 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 30
01-15 19:19:16.405 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 30
01-15 19:19:16.407 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 31
01-15 19:19:16.407 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 31
01-15 19:19:16.656 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 6
01-15 19:19:16.658 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 6
01-15 19:19:16.658 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 7
01-15 19:19:16.659 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 7
01-15 19:19:16.660 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 8
01-15 19:19:16.660 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 8
01-15 19:19:16.662 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 26
01-15 19:19:16.662 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 26
01-15 19:19:16.663 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 27
01-15 19:19:16.664 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 27
01-15 19:19:16.665 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 28
01-15 19:19:16.665 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 28
01-15 19:19:16.674 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 29
01-15 19:19:16.675 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 29
01-15 19:19:16.676 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 30
01-15 19:19:16.676 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 30
01-15 19:19:16.678 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 31
01-15 19:19:16.678 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 31
01-15 19:19:16.679 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 4
01-15 19:19:16.679 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 4
01-15 19:19:16.680 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 4, VIEW ID: 0
01-15 19:19:16.681 7596-7596/? I/OUTPUT: getDropDownView: DB ID: 6, VIEW ID: 0

A: The problem here, is that your query returns more than one result(it seems that returns 2 results per query, DB ID: 4  and DB ID: 6), and you are iterating over the cursor inside getDropDownView method.
So, this produces that your dropdown view's background color is going to be always the value which meets your if-else statement condition the second time.


text:
Q: Understanding compatibility of PDE
THEOREM $1$: The equations $$f(x, y, z, p, q)=0\qquad (1)$$ and $$g(x, y, z, p, q)=0\qquad(2)$$ are compatible on a domain $D$ if
(i) $J=\frac{\partial(f, g)}{\partial(p, q)}=\left|\begin{array}{ll}f_{p} & f_{q} \\ g_{p} & g_{q}\end{array}\right| \neq 0$ on $D .$
(ii) $p$ and $q$ can be explicitly solved from $(1)$ and $(2)$ as $p=\phi(x, y, z)$ and $q=\psi(x, y, z)$.
Further, the equation
$$
d z=\phi(x, y, z) d x+\psi(x, y, z) d y
$$
is integrable.
THEOREM $2$: A necessary and sufficient condition for the integrability of the equation $d z=\phi(x, y, z) d x+\psi(x, y, z) d y$ is
$$
[f, g] \equiv \frac{\partial(f, g)}{\partial(x, p)}+\frac{\partial(f, g)}{\partial(y, q)}+p \frac{\partial(f, g)}{\partial(z, p)}+q \frac{\partial(f, g)}{\partial(z, q)}=0\qquad(3)
$$
In other words, the equations (1) and (2) are compatible iff (3) holds.

In my lecture note, these two theorems are mentioned without any proof. But I am wondering how the Jacobian tell me the system are compatible? And how the expression $[f, g]$ guarantee the integrability of the equation $d z=\phi(x, y, z) d x+\psi(x, y, z) d y$? The definition of compatibility they followed are,

A system of two first-order PDEs are said to be compatible if they have a common solution

I am more interested to get the answer about their intuition (or connection) rather a complete proof (which may be beyond my scope of the syllabus).
Thanks in advance.


text:
Q: Extract content between first "]" and last "[" using regex? Is it possible to have a PHP regex expression that extracts the content from the first ] to the last [?
For example if I had the following string:
$string = [shortcode]You write a shortcode by using ([])[/shortcode]

I would want to extract:
You write a shortcode by using brackets ([])

and store it in a variable.  The content to be extracted could be anything. Thanks in advance.

A: You should be using capturing groups to make sure you match the closing tag.
\[(\w+)\].*?\[/\1\]

This will match a word inside [] and keep going until if finds the same word inside [/...].

A: Regexes are greedy by default, so this will do the job just fine:
/\](.*)\[/

To get this working in PHP properly, you would do something like this:
preg_match('/\](.*)\[/', $text, $matches);

$result = $matches[1];

A: this could make, what you need
[^\]]\](.*)\[[^\[]

A: This works:
preg_match( '@\](.*)\[@', $string, $matches);
print_r($matches);


text:
Q: How to loop through this nested object? I have a dynamically generated JavaScript object which consist of nested objects and arrays. I couldn't find a proper way to list all nested objects, since that particular object is created dynamically.
Here is the object:
var tagdata = {
  "Sentence": [{
      "NP": [{
          "NMP": "cat"
        }, {
          "NMP": "dog"
        }]
    }, {
      "VP": [{
          "KPD": "tree"
        }, {
          "NP": [{
              "NMP": "ball"
            }, {
              "NMP": "bat"
            }]
        },{
          "NP": [{
              "NMP": "ground"
            }, {
              "NMP": "time"
            }]
        }]
    }]
};

The output I require looks like this:
[{ key: 1, text: 'Sentence' },
 { key: 2, text: 'NP', parent: 1 },
 { key: 3, text: 'VP', parent: 1 },
 { key: 4, text: 'NMP', parent: 2 },
 { key: 5, text: 'NMP', parent: 2 },
 { key: 6, text: 'KPD', parent: 3 },
 { key: 7, text: 'NP', parent: 3 },
 { key: 8, text: 'NP', parent: 3 },
 { key: 9, text: 'cat', parent: 4 },
 { key: 10, text: 'dog', parent: 5 },
 { key: 11, text: 'tree', parent: 6 },
 { key: 12, text: 'NMP', parent: 7 },
 { key: 13, text: 'NMP', parent: 7 },
 { key: 14, text: 'NMP', parent: 8 },
 { key: 15, text: 'NMP', parent: 8 },
 { key: 16, text: 'ball', parent: 12},
 { key: 17, text: 'bat', parent: 13},
 { key: 18, text: 'ground', parent: 14},
 { key: 19, text: 'time', parent: 15},]

This data is to be used in a tree, so the order might be different, but the key:parent relationship should be maintained. Here is the code I've tried with:
let newtags=[{key:1,text:'Sentence'}];
tagdata["Sentence"].map( (elem,x) => {
  newtags.push({key:x,text:Object.keys(elem)[0],parent:x});
  if(Object.keys(elem)[0].length !== 0){
    var y=x+1;
    newtags.push({key:y,text:Object.values(elem)[0][x],parent:y});
  }
});

console.log(newtags);

A: Your code works for the first level, but in your attempt to go one level deeper you will assign duplicate key values (y=x+1 when x will have that value in the next iteration of the .map() method as well).
What you need here is a recursive function, one that calls itself to deal with nested levels in the same way as any other level.
You could use this ES6, functional programming solution for that:

function listItems(obj) {
    var key = 0;
    return (function recurse(obj, parent = undefined) {
        return Object(obj) !== obj ? { key: ++key, text: obj, parent }
            :   Array.isArray(obj) ? Object.keys(obj).reduce( (acc, text) =>
                    acc.concat(recurse(obj[text], parent)), [])
            :   Object.keys(obj).reduce( (acc, text) =>
                    acc.concat({ key: ++key, text, parent },
                                recurse(obj[text], key)), []);
    })(obj);
}

// Sample data
var tagdata = {
  "Sentence": [{
      "NP": [{ "NMP": "cat" }, { "NMP": "dog" }]
    }, {
      "VP": [{
          "KPD": "tree"
        }, {
          "NP": [{ "NMP": "ball" }, { "NMP": "bat" }]
        },{
          "NP": [{ "NMP": "ground" }, { "NMP": "time" }]
        }]
    }]
};

// Extract the objects and output:
console.log(listItems(tagdata));
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: I think this does what you want. It uses a recursive algorithm that handles the case where you have an array separately from the case where you have an object. The base case of just a string is handled in processChild.

let state = [];

function processChild(child, parent) {
  if (Array.isArray(child)) {
    return processArray(child, parent);
  }

  if (typeof(child) == 'object') {
    return processObject(child, parent);
  }

  let tag = {
    key: state.length + 1,
    text: child,
  };
  if (parent) {
    tag.parent = parent;
  }
  state.push(tag);
}

function processObject(object, parent) {
  parent = parent || 0;

  let keys = Object.keys(object);
  for (let i = 0; i < keys.length; i++) {
    //console.log(keys[i]);
    let tagIndex = state.length + 1;
    let text = keys[i];
    let tag = {
      key: tagIndex,
      text: text,
    };
    if (parent) {
      tag.parent = parent;
    }

    state.push(tag);

    let child = object[keys[i]];
    processChild(child, tagIndex);
  }
}

function processArray(array, parent) {
  parent = parent || 0;
  for (let i = 0; i < array.length; i++) {
    //console.log(array[i]);
    let child = array[i];
    //console.log('Child', child);
    processChild(child, parent);
  }
}

function process(){
  let initialState = JSON.parse(input.innerHTML);
  processChild(initialState);
  code.innerHTML = JSON.stringify(state).replace(/},/g,'},\n');
}
#input{
  width: 100%;
  height: 200px;
}
<textarea id="input">
  {
  "Sentence": [{
    "NP": [{
      "NMP": "cat"
    }, {
      "NMP": "dog"
    }]
  }, {
    "VP": [{
      "KPD": "tree"
    }, {
      "NP": [{
        "NMP": "ball"
      }, {
        "NMP": "bat"
      }]
    }, {
      "NP": [{
        "NMP": "ground"
      }, {
        "NMP": "time"
      }]
    }]
  }]
}
</textarea>
<button onClick="process()">Process</button>

A: Just for fun, a non-recursive approach.

*

*One array keeps track of the eventual results (results)

*One array keeps track of data-to-process

*When nested data is found, it is wrapped in a "to-do item" and added to the todo array

*Repeat until no items left

var tagData = [{Sentence:[{NP:[{NMP:"cat"},{NMP:"dog"}]},{VP:[{KPD:"tree"},{NP:[{NMP:"ball"},{NMP:"bat"}]},{NP:[{NMP:"ground"},{NMP:"time"}]}]}]}];

var isNode = n => Array.isArray(n);
var isLeaf = n => !isNode(n);
var todoItem = parent => node => ({ parent, node });

var flatten = function(arr) {
  var result = [],
      todo = arr.map(todoItem(0)),
      current, node, parent, key, innerNode;

  while (todo.length) {
    ({node, parent} = todo.pop());
    key = result.length + 1;

    Object.keys(node).forEach(k => {
      innerNode = node[k];
      result.push({ key, parent, text: k });

      if (isLeaf(innerNode)) {
        result.push({
          key: key + 1,
          parent: key,
          text: innerNode
        });
      } else {
        todo = todo.concat(
          innerNode.map(todoItem(key)));
      }
    });
  };

  return result;
};

// Print output
console.log(
  flatten(tagData)
  .map(o => [
    "key: " + (o.key < 10 ? " " : "") + o.key,
    "parent: " + (o.parent < 10 ? " " : "") + o.parent,
    o.text
  ].join(" | "))
);
.as-console-wrapper {
  min-height: 100%;
}


text:
Q: Search a vector of objects by object attribute I'm trying to figure out a nice way to find the index of a certain object in a vector - by comparing a string to a member field in the object.
Like this:
find(vector.begin(), vector.end(), [object where obj.getName() == myString])

I have searched without success - maybe I don't fully understand what to look for.

A: You can use std::find_if with a suitable functor. In this example, a C++11 lambda is used:
std::vector<Type> v = ....;
std::string myString = ....;
auto it = find_if(v.begin(), v.end(), [&myString](const Type& obj) {return obj.getName() == myString;})

if (it != v.end())
{
  // found element. it is an iterator to the first matching element.
  // if you really need the index, you can also get it:
  auto index = std::distance(v.begin(), it);
}

If you have no C++11 lambda support, a functor would work:
struct MatchString
{
 MatchString(const std::string& s) : s_(s) {}
 bool operator()(const Type& obj) const
 {
   return obj.getName() == s_;
 }
 private:
   const std::string& s_;
};

Here, MatchString is a type whose instances are callable with a single Type object, and return a boolean. For example,
Type t("Foo"); // assume this means t.getName() is "Foo"
MatchString m("Foo");
bool b = m(t); // b is true

then you can pass an instance to std::find
std::vector<Type>::iterator it = find_if(v.begin(), v.end(), MatchString(myString));

A: In addition to the Lambda and the handwritten functor used by juancho, you have the possibility to use boost::bind (C++03) or std::bind (C++11) and a simple function:
bool isNameOfObj(const std::string& s, const Type& obj)
{ return obj.getName() == s; }

//...
std::vector<Type>::iterator it = find_if(v.begin(), v.end(),
  boost::bind(&isNameOfObj, myString, boost::placeholders::_1));

Or, if Type has a method isName:
std::vector<Type>::iterator it = find_if(v.begin(), v.end(),
  boost::bind(&Type::isName, boost::placeholders::_1, myString));

This is just for completeness. In C++11 I'd prefer Lambdas, in C++03 I'd use bind only if the comparison function itself exists already. If not, prefer the functor.
PS: Since C++11 has no polymorphic/templated lambdas, bind still has it's place in C++11, e.g. if the parameter types are unknown, hard to spell, or otherwise not easy to deduce.

A: A simple iterator may help.
typedef std::vector<MyDataType> MyDataTypeList;
// MyDataType findIt should have been defined and assigned
MyDataTypeList m_MyObjects;
//By this time, the push_back() calls should have happened
MyDataTypeList::iterator itr = m_MyObjects.begin();
while (itr != m_MyObjects.end())
{
  if(m_MyObjects[*itr] == findIt) // any other comparator you may want to use
    // do what ever you like
}


text:
Q: My website running in Oracle Cloud is down, how can I repair it? I have a website that is running in Oracle Cloud, the website now is down and I tried to access using SSH in Putty but it cannot be accessed I only see the terminal screen.
What should I do?

A: Could you please check if the instance is running or not. If the instance is running please check for the ingress/egress firewall rules at security list/NSG/OS firewall for connectivity to the instance. Make sure you are not connected to any VPN or any corporate network. Once you are able to connect to the instance check for the status of the service. It should be Active.
Could you please confirm, were you able to connect to the instance before? Since when you are facing this issue?
For your reference: connecting to your instance.


text:
Q: Options for passive speakers I would like to buy a small external speaker (mono) to use for my laptop and mobile phone, both of which have very poor-quality and low-volume built-in speakers.
However, all that I can find in shops are powered (battery or AC) speakers, and no passive speakers at all. I would be using the speaker at home most of the time, and thus it would not make sense to keep charging the battery every few hours. I don't need the new speaker to have massive volume, thus I'd have thought that a passive solution should be doable.
Also, for convenience, I would prefer the speaker to not require mains plugging, but only a wired connection to the device's audio jack.
Is such a solution at all possible, or will I have to settle for powered speakers?

A: This won't work out: the speakers in your devices are as loud as they can be with the built-in amplifiers.
Sure, you could argue that maybe these built-in speakers are very inefficient, i.e. bad at converting amplifier output power to loudness, and you can buy better, higher-efficiency speakers that can make more and better sound out of the same power, but that's extremely unlikely, since mobile devices typically pick astonishingly high-efficiency speakers.
So, with the power you'll get out of these, you're very unlikely to get better sound out of external speakers, unless you're willing to accept less loud speakers, and you won't get much louder speakers, unless you're willing to accept more horrible sounding.
So, you'll need an external amplifier. I don't understand your requirements – you're mostly using them at home (where you have power), but don't want to plug them in – you're making your life unnecessarily hard.