text:
Q: Iterate four lists in different loop python I have these four prob. lists:
x1 = [1,0,0] ; prob. of No goal scored per timeslot.
x2 = [0,1,0] ; prob. of Home Team scoring per timeslot.
x3 = [0,0,1] ; prob. of Away Team scoring per timeslot.
y = [0.97, 0.02, 0.01]; constant prob. per timeslot.

I want the sum of squared difference (sse) of x1 and y until a goal is scored. Then the sse is calculated by x2 or x3 and y depending on who scored first. Then it loops back to x1 and y until a goal is scored again by either Team and so on...
Here is what I have attempted so far.

Total timeslot = 15.
Order of timeslot
Home_Goal_timeslot = 8th, 14th. i.e. at two different timeslots.
Away_Goal_timeslot = 11th
No_Goal = 12. i.e. number of timeslots 12

x1 = np.array([1,0,0])
x2 = np.array([0,1,0])
x3 = np.array([0,0,1])
y = np.array([0.97, 0.02, 0.01])

def sum_squared_diff(x1, x2, x3, y, k):
    for k in range(15):
        if k == 'No_Goal':
           return sum((x1 - y)**2)
        elif k == 'Home_Goal':
            return  sum((x2 - y)**2)
        else:
            return  sum((x3 - y)**2)

sum_squared_diff(x1, x2, x3, y, k=15)

Out[1912]: 1.9213999999999998

print(sum((x1 - y)**2)**12, sum((x2 - y)**2)**2, sum((x3 - y)**2)**1)

    5.669391237529683e-35 3.6153219599999997 1.9213999999999998
add up to 5.5367219599999995

Why is the above solutions are different?
I prefer to add the sse after each timeslot and make a note when a goal is scored. So I can go back and add/subtract some infinitesimal epsilon to y values and measure the test...
This is the out come i want

 0.0014000000000000017,
 0.0014000000000000017,
 0.0014000000000000017,
 0.0014000000000000017,
 0.0014000000000000017,
 0.0014000000000000017,
 0.0014000000000000017,
 0.0014000000000000017,
 1.9014,
 0.0014000000000000017,
 0.0014000000000000017,
 1.9213999999999998,
 0.0014000000000000017,
 0.0014000000000000017,
 1.9014

A: Solutions are different because last else-statement is True forever, because as @slybloty said, you compare int k with str. So your
def sum_squared_diff(x1, x2, x3, y, k):
        for k in range(15):
            if k == 'No_Goal':
               return sum((x1 - y)**2)
            elif k == 'Home_Goal':
                return  sum((x2 - y)**2)
            else:
                return  sum((x3 - y)**2)

and
def sum_squared_diff(x1, x2, x3, y, timeslot):
    return sum((x3 - y)**2)

do same work

A: What it seems to me you're trying to do is iterate through your total timeslot and if it matches any of your Home_Goal or Away_Goal then calculate as that.
What you're doing is this:

*

*Compare int to str (k == 'No_Goal') which you'll be getting False pretty much all the time.

*End your loop at the first iteration by using return after your calculation.

Based on my understanding this is what you're looking for:
total_timeslot = 15
Home_Goal = [8, 14]
Away_Goal = [11]

def sum_squared_diff(x1, x2, x3, y):
    r1, r2, r3 = 0, 0, 0
    for k in range(total_timeslot):
        if k in Home_Goal:
            r2 += sum((x2 - y)**2)
        elif k in Away_Goal:
            r3 += sum((x3 - y)**2)
        else:
            r1 += sum((x1 - y)**2)
    return r1, r2, r3

UPDATE:
After your updated question, seems that you want to print all results after each iteration, not only the end results. In that case you can add a print statement at the end of each loop and remove the incrementation.
UPDATE 2:
Here's the code reflecting the changes:
def sum_squared_diff(x1, x2, x3, y):
    r1, r2, r3 = 0, 0, 0
    for k in range(total_timeslot):
        if k in Home_Goal:
            r2 = sum((x2 - y)**2)
        elif k in Away_Goal:
            r3 = sum((x3 - y)**2)
        else:
            r1 = sum((x1 - y)**2)
    print(r1, r2, r3)


text:
Q: Bootstraped t-test with permuted p-values I would like to do a bootstraped t-test with permuted p-values. I have two unequal samples (first sample with 80 individuals and second with 35). Can anybody help with code? I'm a begginer in statistics, and don't understand how I can do this.
library(readxl)
rain <- read_excel('rain.xlsx')
mix <- read_excel('mix.xlsx')
rain       mix
0.738      1.50
0.725      2.13
2.64       2.46
0.877      1.52
1.61       1.47
1.48       ...
1.45
1.51
1.89
0.48
...

redpajama_set_name: RedPajamaStackExchange


text:
Q: User currently viewing launcher app I have an app that runs on background thread. I need to find out if the user is currently viewing the launcher and not on other app.
on pre Lollipop you could use
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> running = am.getRunningTasks(1);

and the first one on the list should have been the currently active app which you could have tested against the list of all installed launchers.
This doesn't work anymore. Is there any other way to find out if the user currently viewing the launcher app or not?
Thanks in advance


text:
Q: create stack using 2 queues Hey guys I am having trouble with my first assignment in my data structures class, and was hopping someone could provide some insight on what I am doing wrong.
I must create a stack that utilizes 2 queues for data storage.
import Queue_PlistLR as queueList

import Queue_PlistLR as queueList

class Stack_2Queues():

        def __init__(self, name, salary):
                self.items = []
                self.name = name
                self.salary = salary

        def isEmpty(self):
                return len(self.items) == 0

        def push(self, e):
                self._data.append(e)

        def pop(self):
                if self.is_empty:
                        raiseEmpty("Stack is empty")
                return self._data.pop()
        def size(self):
                return len(self.items)

        def to_String(self):
                str_i = ""
                for e in self.items:
                        str_i+=str(e)+" "
                return str_i.strip()

        def length(self):

                return len()

        def enqueue(self, item):
                self.items.append(item)

        def dequeue(self):
                if self.isEmpty():
                        raise Empty('Queue is empty')
                return self.items.pop(0)

        def employeeName(self):
                print("The employee is: ", self.name)

        def employeeSalary(self):

                print("Employees salary is", self.salary)

s1 = Stack_2Queues = [["Ash", "Jen", "Mike", "Zach"], [45000, 32000, 74000, 960000]]

s1.employeeName()
s1.employeeSalary()

***I know this is wrong, for the most part. but my question is this. For the stack I want to create 2 queues, one for employeeName and the other for employeeSalary, using 1 stack.
Also when I try printing the name and salary from the stack (to see if it works) and I get "list has no attribute" error.***
So, here are my questions:
1) Excuse my illiteracy as this may sound stupid, but is my s1 variable the form of a stack?
2) Why am I getting the list has no attribute since I defined all methods, and called them?

A: The AttributeError is caused by this line:
s1 = Stack_2Queues = [["Ash", "Jen", "Mike", "Zach"], [45000, 32000, 74000, 960000]]

This is not how you initialize Stack_2Queues. What's actually going here is that you're assigning the list which contains two other lists to the variables s1 and Stack_2Queues(thus changing the reference which points to the class definition to the list)
In [1]: s1 = Stack_2Queues = [["Ash", "Jen", "Mike", "Zach"], [45000, 32000, 74000, 960000]]

In [2]: print(s1)
[['Ash', 'Jen', 'Mike', 'Zach'], [45000, 32000, 74000, 960000]]

In [3]: print(Stack_2Queues)
[['Ash', 'Jen', 'Mike', 'Zach'], [45000, 32000, 74000, 960000]]

Simple example to understand this:
In [4]: a = 5

In [5]: b = 5

This is equivalent to:
In [6]: a = b = 5

Change the line to this:
s1 = Stack_2Queues(["Ash", "Jen", "Mike", "Zach"], [45000, 32000, 74000, 960000])

It works for me after that:
('The employee is: ', ['Ash', 'Jen', 'Mike', 'Zach'])
('Employees salary is', [45000, 32000, 74000, 960000])

Also you imported the same module twice right at the top of the script which you haven't used.
If you try to call either push or pop on an instance of Stack_2Queues python will throw another AttributeError because Stack_2Queues does not have any _data attribute.
def push(self, e):
    self._data.append(e)

def pop(self):
    if self.is_empty:
        raiseEmpty("Stack is empty")
    return self._data.pop()

You should maybe change this part of the code or add self._data in the __init__ method.
This will also not work:
def length(self):
    return len()

Calling the built-in len function without any argument will throw an error. https://docs.python.org/3.6/library/functions.html#len
It's probably redundant since you defined a size method and probably does the same thing.


text:
Q: How can I retrieve information from deleted CloudFormation stacks using boto3? I have a boto3 script that basically collects certain information from CloudFormation stacks with the state - CREATE_COMPLETE. However, I would also like to retrieve information from stacks with the DELETE-COMPLETE status. According to the docs, I can only do this by providing the stack ID. Unfortunately I don't know the Stack IDs. Is there any way I could retrieve information without the stack IDS or probably is there a way to obtain the deleted stack IDs?
P.S. I can see the deleted stacks and their IDs on the AWS console by selecting the "Deleted" filter option but I would like to get this information using boto3.

A: You can call list-stacks with a stack status filter to get the details of all the deleted stacks.


text:
Q: InputStream doens't read the whole answer of an URL connection I'm struggling against the uncompleted download of a file.
For example, I upload some data on github :https://gist.githubusercontent.com/rdanniau/3b7f26bb1101b28400bf24f2f9664828/raw/980d6ff511404bf14d3efc56be3dfb081541991f/LEDirium.hex
and on pasteBin : http://pastebin.com/raw/FcVfLf5b
I want to retrieve them and save them into a file "filename".
I've watch a lot of example on internet and it must be working.
Here is the code :
    private void download(final URL myUrl){
    new Thread(new Runnable() {
        //InputStream is = null;
        //FileOutputStream fos = null;
        public void run() {
            try {
                URLConnection connection = myURLL.openConnection();
                //HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
                //connection.setRequestMethod("GET");
                connection.setReadTimeout(5000);
                connection.setConnectTimeout(10000);
                connection.connect();

                //is = myUrl.openStream();
                is = connection.getInputStream();
                File file = new File(context.getFilesDir(),fileName);
                file.delete();
                file = new File(context.getFilesDir(),fileName);
                fos = new FileOutputStream(file);
                byte data[] = new byte[1024];
                String str ="";
                int count = 0;
                while ((count = is.read(data)) != -1) {
                    fos.write(data, 0, count);
                }
                is.close();
                fos.close();

            }
            catch (Exception e) {
                downloadedFileCallback.onError(e);
                Log.e("DownloadedFile", "Unable to download : " + e.getMessage() + " cause :" + e.getCause());
                return;
            }
            downloadedFileCallback.onDownloadedFinished();
            readFile(context);
        }
    }).start();
}
public void readFile(Context context){
    // read
    try {
        BufferedReader br = new BufferedReader(new FileReader(new File(context.getFilesDir(),fileName)));
        String line;

        while ((line = br.readLine()) != null) {

            Log.v("DL", line);
        }
        br.close();
    }
    catch (Exception e) {
        Log.e("DownloadedFile", "Unable to read : " + e.getMessage() + " cause :" + e.getCause());
    }
    //Log.v("DownloadedFile", text.toString());
}

where myURL are called like
  URL myURL = new URL("http://pastebin.com/raw/FcVfLf5b");

In the Log.v, I can see that I downloaded only a part of the file which is never the same (it could be the entire file, the half, the quarter, we don' know...)
It's probably the inputStream connection which is closed too fast. But why ?
Last question, instead of using Log.v to check if the file is correctly downloaded. Where can I found it on my phone ? I searched in many folders but I never seen my File.
Thanks a lot for any advice
EDIT : It seems to be the same here InputStream returns -1 before end of file but no one answered.


text:
Q: What is this function template in this class template doing? I'm working my way through a C++ class template in a book I'm reading, and while most of it is clear, this particular function is really bugging me:
template <typename T>
struct Vector3 {

T x; T y; T z;

//... several methods, constructors, etc

//Then this one, which is really confusing me:

template <typename P>
P* Write(P* pData)
   {
    Vector3<T>* pVector = (Vector3<T>*) pData;
    *pVector++ = *this;
    return (P*) pVector;
   }

First things first, this function appears to be treating an array of P or a pointer to P as if it can easily be casted from a pointer to a Vector3, the name of the class. How's that? If I have a Vector3<float> someVector, what makes a pointer to this someVector castable into a pointer to float ? (or even int ?) It also does the opposite: feed the function an array of floats, and then it can just cast it into an array of Vector3.
So that's the first area of my confusion.
Next is the *pVector++ = *this; -- I take it this is pointer arithmetic here, such that if pVector pointed to the second element in an array, with this expression we are incrementing the pointer to the next element of the array, but only after we first assign *this to the current element pointed at by pVector. Assuming I am correct in this, wouldn't pVector always point to the first element in the array, since it is just created on the previous line?! What's the purpose of the ++ operator in such a context?

A: Let's decompose how it works:

*

*This is the function declaration. The important point is that P is unrelated to T. So, we need to pay more attention, as some bad things might occur...
template <typename P>
P* Write(P* pData)
{

Let's represent the memory pointed by pData. For the sake of the explanation, I will assume that pData points to a sufficiently large area in the memory (or else Write will probably result in a segfault), and that Vector3<T> is only the size of 3 Ts. In the following, I will take T = float, with sizeof(float) = 4, but my explanations will still be valid with other types. So, here sizeof(Vector3<float>) = 12.
So, here is the memory, |-| is one byte:
|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|
^
|
pData : P*

*We interpret pData as a pointer to a Vector3<T>. This is bad style in general, as P can be anything.
    Vector3<T>* pVector = (Vector3<T>*) pData;

*The following line:
    *pVector++ = *this;

can be divided in:
    *pVector = *this;
    pVector++;

*

**pVector = *this; assign the contents of the vector (*this) to the data. The memory is now:
pVector : Vector3<float>*
|
v
|X|X|X|X|Y|Y|Y|Y|Z|Z|Z|Z|-|-|-|-|-|
^^^^^^^^^^^^^^^^^^^^^^^^^
copied content of the vector

*pVector++; increments the vector by 1 * sizeof(Vector3<float>), so it now points to the non-yet-written memory:
                        pVector : Vector3<float>*
                        |
                        v
|X|X|X|X|Y|Y|Y|Y|Z|Z|Z|Z|-|-|-|-|-|

*pVector is casted back to P* and returned.
    return (P*) pVector;
}

This enables to chain writes, as a write to the returned pointer will not overwrite the first write:
char data[2 * sizeof(Vector3<float>)];
v2.Write(v1.Write(data));
// now data is:
//                                                 contents of v2
//                                     vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// |X1|X1|X1|X1|Y1|Y1|Y1|Y1|Z1|Z1|Z1|Z1|X2|X2|X2|X2|Y2|Y2|Y2|Y2|Z2|Z2|Z2|Z2
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//          contents of v1

Now, some flaws:
This function can be useful for io, and is equivalent to a memcpy on the vector. However, it has a lot of flaws, the major one being the template parameter. Writing directly to memory for such operations should use char, and not something else. Writing in memory to overwrite the content of a class (ie, not io) is a very bad practice, (assignment operators are made for such a task, and they are safer). Also, the following example is not self-describing:
vec.Write<MyTimerClass>(pointer); // Does not make sense if you are reading this line for the first time

Secondly, there are problems in copying memory. Here, in the explanations, I assumed Vector3 was a simple type. It is not always the case. If it had virtual functions and members of different sizes, the layout in memory would have been implementation-defined, for example:
                 X, Y, Z            padding
        ------------------------    ----
|P|P|P|P|X|X|X|X|Y|Y|Y|Y|Z|Z|Z|Z|a|a|.|.
--------                        ----
 vtable                         some
 pointer                        other
                                member

And this is not reliable for io. See this SO question (the accepted answer is: "Here is how it works for msvc"...). And for multiple virtual inheritance it becomes a true nightmare.
By the way, the secure implementation of such a method would have been something like:
template<typename IOBuffer>
bool Write(IOBuffer& buffer)
{
    return buffer << X << Y << Z;
}

or better:
virtual bool Write(IOBufferInterface& buffer)
{
    return buffer << X << Y << Z;
}

It is way more simple to understand, maintain, debug, etc...


text:
Q: dynamodb decribe-table encryption status In the AWS Console, the DynamoDB table is having Encryption as "DEFAULT"...looking at the documentation the table may be encrypted using AWS owned CMK(Customer managed key)...
But is there a way to know for sure...that the table is encrypted? and if yes, what type of encryption is in place?
the "describe-table" command doesn't output any information about encryption.
C:\Users\test>aws dynamodb describe-table --profile snpp --table-name mydynamodbtable
{
    "Table": {
        "TableArn": "arn:aws:dynamodb:us-east-1:902919223373:table/mydynamodbtable",
        "AttributeDefinitions": [
            {
                "AttributeName": "hashKey",
                "AttributeType": "S"
            },
            {
                "AttributeName": "rangeKey",
                "AttributeType": "S"
            }
        ],
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "WriteCapacityUnits": 100,
            "ReadCapacityUnits": 400
        },
        "TableSizeBytes": 45160931,
        "TableName": "mydynamodbtable",
        "TableStatus": "ACTIVE",
        "TableId": "0e75b671-75bf-41ac-9cd1-f75ee3f787ca",
        "KeySchema": [
            {
                "KeyType": "HASH",
                "AttributeName": "hashKey"
            },
            {
                "KeyType": "RANGE",
                "AttributeName": "rangeKey"
            }
        ],
        "ItemCount": 206363,
        "CreationDateTime": 1529442343.583
    }
}

A: https://aws.amazon.com/about-aws/whats-new/2018/11/amazon-dynamodb-encrypts-all-customer-data-at-rest/
Per this November 15, 2018 announcement, all DynamoDB table Data at rest are encrypted except for AWS GovCloud US-West, US-East, China Bejing, and China Ningxia  regions.


text:
Q: How do i get visual studio like tabs? I've been thinking for a while in my head and I've not been able to find the solution to it ! Please help me.
I've always loved the visual studio tabs and how they look. They're small and perfect. The normal .NET TabControl, well is plain and boring! I've seen these tabs being used in many applications. My question is:

Is there a DLL that is available that has this kind of tabcontrol?

Here's a picture for reference:

A: You need "DockPanel Suite by mtwombley, spudcud, weifenluo".
It's an awsome open-source project, and you can get it at http://sourceforge.net/projects/dockpanelsuite/

A: I was looking for the same thing.  A tab control with VS-like tabs.
DocPanel Suite is great, but it's like filling a hole with a bulldozer.  Here is an extension of the existing tab control that does what I was looking for:
http://www.codeproject.com/Articles/91387/Painting-Your-Own-Tabs-Second-Edition

A: found this googling
http://www.freevbcode.com/ShowCode.asp?ID=3266

A: Telerik has a great TabStrip product whether you are looking for WinForms, WebForms, WPF, Silverlight, or MVC. All of these tabs can be customized and they come with some great default styles, you can find many more (including some VS templates) online, or you can create your own, which isn't that hard. They even provide a tool to help you create your own. Some of their products cost money and some are free, so it depends on what you're looking for.


text:
Q: Are there good tutorials for VST plugin creation in JUCE C++? I want to make VST plugins in C++. I read that the JUCE library is better than using the Steinberg SDK. My problem is that when I Google tutorials it only covers generic topics pertaining to application development only, not specialized audio plugin interfaces that the library was initially designed for.
I am looking for a tutorial that covers making a VST plugin (maybe a simple effect, like a lowpass filter) with the JUCE framework. Or, if anybody could tell me about better or easier ways to develop VST Plugins in Visual Studio (2008) and link to resources that will help me get started.

A: There is no easy way to develop VST plugins, they require knowledge of advanced signal processing and programming.
Here are some links that can help you out with your plugin development
KVR Audio: DSP / Plugin / Host Development
KVR Audio: How To Create VST Plugins
For JUCE C++ Framework there aren't many full featured tutorials as such so you will have to learn by reading code and understanding it.
For Filter Design I would suggest checking out DSPFilters by  vinniefalco. This is a collection of C++ classes for signal processing. It uses JUCE C++ Framework. So I suggest you check that out.
https://github.com/vinniefalco/DSPFilters
You can also check out TAL Plugins. Some of these plugins were made with JUCE C++ and their source code is available for free on their website.
For the Filter there is Tal-Filter, download is underneath source code section.
http://kunz.corrupt.ch/Products/TAL-Filter
For a Subtractive Synth Tal-NoiseMaker, download for source code is underneath source code section.
http://kunz.corrupt.ch/Products/TAL-NoiseMaker
Both of these plugins source code are open source and are using JUCE C++ Framework.

A: Nowadays I recommend using WDL instead of JUCE. WDL is free for commercial use, and you can build Win/Mac, 32/64 Bit, VST2/VST3/AU/RTAS/AAX and standalone from one codebase.
There's a tutorial series showing how to get started.


text:
Q: django-filter button in template I'm using the django-filter package. My page displays all books. I have 5 genres. I want someone to be able to click a "scary" button, and have that filter my book list (user shouldn't have to also click "submit", just the genre button).
But right now when I click a genre button, it doesn't filter. Unless I use a checkbox widget in my filters.py (commented out), check the box, and then click the genre button, but this looks ugly.
Thanks in advance for the help!
Filters.py
class BookFilter(django_filters.FilterSet):
    genre = django_filters.ModelMultipleChoiceFilter(queryset=Genre.objects.all(),
#widget=CheckboxSelectMultiple)
    class Meta:
        model = Book
        fields = ['genre']

book_list.html
<form method="get">

    {% for genre in filter.form.genre %}

      <button type="submit" class="button">
        {{ genre }}
      </button>

    {% endfor %}

</form>

Update
Thanks to GwynBleidD for the help! I also had to change {% for genre in filter.form.genre %} to {% for genre in genre_list %} where in my views, genre_list=Genre.objects.all(). Otherwise, the button value was value=option value=10 instead of value=10.

A: You can add name and value to your button. That way button, when clicked, will also set property of specified name to specified value before submitting your form
<form method="get">

    {% for genre in filter.form.genre %}

      <button type="submit" class="button" name="genre" value="{{ genre }}">
        {{ genre }}
      </button>

    {% endfor %}

</form>

A: I tried @GwynBleidD's method but ran into the same issue as @tei1. It seems as though the content of the filter.form is the generated html, so genre is the actual option html like the following:
<option value="">---------</option>

...which doesn't quite work with what the OP wanted, or what I was looking for as well.
I was able to get it to work by providing the data for my filtering values in the context along with the filter. I'm using class based views and looks something like this:
    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        context['genres'] = Genre.objects.all()
        context['filter'] = BookFilter(self.request.GET, queryset=Books.objects.all())
        return context

And the following template, assuming the value you want to display for the filter is available in a name attribute of the Genre model:
<form method="get">

    {% for genre in genres %}

      <button type="submit" class="button" name="genre" value="{{ genre.id }}">
        {{ genre.name }}
      </button>

    {% endfor %}

</form>

And if you want to have a "select all" button with no filter applied:
<form method="get">

      <button type="submit" class="button" name="genre" value="" selected>
        All Genres
      </button>

    {% for genre in genres %}

      <button type="submit" class="button" name="genre" value="{{ genre.id }}">
        {{ genre.name }}
      </button>

    {% endfor %}

</form>


text:
Q: HR SCHEMA ORACLE HR SCHEMA ORACLE
Create Function "GET_EMPLOYEE_SUMMARY" that receives an Employee ID and that returns, through an output parameter, a data structure with the following information:
 - Employee ID
 - First Name
 - Last Name
 - Manager Name
 - Department Name
So, the manager_name is baseade on employee_id..
Query:
select

      e.first_name as first_name,
      e.last_name,
      e.employee_id,
      e.manager_id as Name,
      d.department_name

      from employees e
      Cross join departments d

but i have some mistakes... idk

A: You just need to do a self join with the EMPLOYEE table again and join with the DEPARTMENT table should be inner join.
Something like following is needed:
SELECT
    E.FIRST_NAME   AS FIRST_NAME,
    E.LAST_NAME,
    E.EMPLOYEE_ID,
    M.FIRST_NAME || M.LAST_NAME   AS MANAGER_NAME, -- Change it according to your requirement
    D.DEPARTMENT_NAME
FROM
    EMPLOYEES E
    JOIN EMPLOYEES M ON E.MANAGER_ID = M.EMPLOYEE_ID
    JOIN DEPARTMENTS D ON D.DEPARTMENT_ID = E.DEPARTMENT_ID
WHERE
    E.EMPLOYEE_ID = 100;

Cheers!!

A: Since this looks very much like homework, here is a rough guide and you'll need to fill in the blanks:
The first part of your question is to:

create Function GET_EMPLOYEE_SUMMARY

so you should not be starting by writing a SQL query but should be writing a PL/SQL statement:
CREATE FUNCTION GET_EMPLOYEE_SUMMARY ...

You can look up the complete syntax in the Oracle documentation.

that receives an Employee ID

So one of the arguments to the function should be something like:
i_employee_id IN EMPLOYEE.EMPLOYEE_ID%TYPE

and that returns, through an output parameter, a data structure with the following information ...

So your return type should be a custom type created with a statement like:
CREATE TYPE <your_type_name> AS OBJECT(
  <list_of_properties _and_data_types>
)

and then you can use that return type in your function declaration.
When it comes to write the PL/SQL block for your function then you can include your query which should look something like:
CREATE FUNCTION <your_function_signature>
IS
  <declare your local variables>
BEGIN
  SELECT E.FIRST_NAME,
         E.LAST_NAME,
         M.FIRST_NAME || ' ' || M.LAST_NAME
         D.DEPARTMENT_NAME
  INTO   <your_first_name_variable>,
         <your_last_name_variable>,
         <your_manager_name_variable>,
         <your_department_name_variable>
  FROM   EMPLOYEES E
         LEFT OUTER JOIN EMPLOYEES M
         ON ( E.MANAGER_ID = M.EMPLOYEE_ID )
         INNER JOIN DEPARTMENTS D
         ON ( D.DEPARTMENT_ID = E.DEPARTMENT_ID )
  WHERE  E.EMPLOYEE_ID = i_employee_id;

  <do stuff>

  RETURN <your_custom_type>
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    <handle the exception>
END;
/


text:
Q: How to combine multiple output in tensorflow to create a metric? I am working on a multi-task neural net which has two outputs, a segmentation "mask" and a classification "label":
inputs = tf.keras.Input(shape=(352, 512, 3), name='image')
outputs = base_model(inputs)

mask = tf.keras.layers.Conv2D(4, (3,3), strides=1, padding='same', activation='sigmoid', name='mask')(outputs)

label = tf.keras.layers.GlobalAveragePooling2D()(outputs)
label = tf.keras.layers.Dense(4, activation='sigmoid', name='label')(label)
model = tf.keras.models.Model(inputs, [mask, label])

From this model I obtain one prediction "mask" and one prediction "label". The question is: I want to create a metric such that it only evaluates the dice coefficient of "mask" when the corresponding "label" > 0.5.
I have been searching this for quite a while and from tensorflow official site I can only find how to calculate metrics for each output, but no documentation on how to access all the predictions and combine them.
metrics = {'mask': [dice_coef(threshold=0.5)],
        'label': [tf.keras.metrics.binary_accuracy]}

here each metric only accept two arguments (y_true, y_pred).
Update:
I have figured out a work around myself, instead of combining results in the metrics, I added one lambda layer in the network and added one more output
inputs = tf.keras.Input(shape=(352, 512, 3), name='image')
outputs = base_model(inputs)

mask = tf.keras.layers.Conv2D(4, (3,3), strides=1, padding='same', activation='sigmoid', name='mask')(outputs)

label = tf.keras.layers.GlobalAveragePooling2D()(outputs)
label = tf.keras.layers.Dense(4, activation='sigmoid', name='label')(label)

label_exp = tf.keras.layers.Lambda(lambda label: tf.cast(tf.math.greater(label, 0.5), tf.float32))(label)
label_exp = tf.keras.layers.Reshape([1,1,4])(label_exp)
filtered = tf.keras.layers.Multiply(name='filtered')([mask, label_exp])

model = tf.keras.models.Model(inputs, [mask, filtered, label])

And the metrics now is set to be:
metrics = {'mask': [dice_coef(threshold=0.5)],
            'filtered': [dice_coef(threshold=0.5)],
            'label': [tf.keras.metrics.binary_accuracy]}

This works but seems like will cost additional memory. Still looking for a neat solution...


text:
Q: Maven Tests Does Not Run Cucumber Scenarios with Spring Boot 2.2 and JUnit 5 I am trying JUnit 5 and Cucumber at Spring Boot 2.2.6 and will need both BDD scenarios and unit tests at my application. I have created a dummy ping controller corresponding feature file which are OK.
Cucumber tests are not called when I run mvn clean test. Only JUnit test is called. However, I can run Cucumber scenarios from Intellij GUI when click on the Run Test button for CucumberTest.java.
Here are my classes:
DummyApplicationTests.java:
package com.a.dummy;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@ActiveProfiles("test")
public class DummyApplicationTests {

    @Test
    public void contextLoads() {
    }

}

CucumberTest.java:
package com.a.dummy.bdd;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/features")
public class CucumberTest {
}

CucumberSpringContextConfiguration.java:
package com.a.dummy.bdd;

import com.a.dummy.DummyApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@ContextConfiguration(classes = DummyApplication.class)
public abstract class CucumberSpringContextConfiguration {

}

PingTest.java:
package com.a.dummy.bdd.steps;

import com.a.dummy.bdd.CucumberSpringContextConfiguration;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;

public class PingTest extends CucumberSpringContextConfiguration {

    @When("^the client calls /ping")
    public void the_client_issues_GET_ping() {
        ...
    }

    @Then("^the client receives status code of (\\d+)$")
    public void the_client_receives_status_code_of(int statusCode) {
        ...
    }

    @And("^the client receives ping response")
    public void the_client_receives_ping_response_body() {
       ...
    }
}

What I am missing?

A: If you just upgraded to Spring 2.4.0 and maven doesn't run you integration tests, it's because:

Cucumber is based on JUnit 4. If you're using JUnit 5, remember to
include junit-vintage-engine dependency, as well. For more
information, please refer to JUnit 5 documentation.
Cucumber documentation

From Spring Boot 2.4.0 reference you can fix it as follows:

If you have tests that use JUnit 4, JUnit 5's vintage engine can be
used to run them. To use the vintage engine, add a dependency on
junit-vintage-engine, as shown in the following example:

<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

A: JUnit 5 support has not yet integrated and I had to include junit-vintage due to RunWith is a Junit 4 annotation.

A: A 2021 answer could be to add
<dependency>
  <groupId>io.cucumber</groupId>
    <artifactId>cucumber-junit-platform-engine</artifactId>
  <version>${cucumber.version}</version>
</dependency>

to your pom.xml file as this allows Cucumber to work with Junit 5. See also https://github.com/cucumber/cucumber-jvm/blob/main/junit-platform-engine/README.md for more ideas.

A: I have had the same issue with Spring boot 2.4.0 because it only supports JUnit 5, and seems like Cucumber only integrates with JUnit 4 (RunWith). Go back to Spring boot 2.3.6 (which has backwards compatibility with JUnit 4) solved the issue.
https://docs.spring.io/spring-boot/docs/2.3.6.RELEASE/reference/html/spring-boot-features.html#boot-features-testing

26.1. Test Scope Dependencies The spring-boot-starter-test "Starter" (in the test scope) contains the following provided libraries:
JUnit 5 (including the vintage engine for backward compatibility with
JUnit 4): The de-facto standard for unit testing Java applications.


text:
Q: Session works on localhost but not on server (Ipage, etc..) Here's a code:
 <?php
    require_once('./includes/connection.inc.php');
    session_start();

    // create database connection
    $connread = dbConnect('read', 'pdo');

    $connwrite = dbConnect('write', 'pdo');
    $komentari = 'SELECT * FROM komentariodobreni ORDER by komentarodobren_id DESC';

    $kontakt = 'SELECT poruka_id, ime, prezime, email, predmet, ordinacija, poruka,      DATE_FORMAT(datum, "%H:%i:%s %d. %b. %Y")
     AS datum  FROM kontakt ORDER by poruka_id DESC';

    if (isset($_POST['slanje'])) {
    $potvrdiquery = "SELECT * FROM kontrola WHERE adminname='" . $_POST["adminname"] . "' and adminpassword = '". $_POST["adminpassword"]."'";
     $stmt = $connwrite->prepare($potvrdiquery )

    ;
      // bind the parameters and execute the statement
      // execute and get number of affected rows
      $stmt->execute();
      $OK = $stmt->rowCount();

    foreach ($connread->query($potvrdiquery) as $row) {
    $_SESSION['adminid'] = $row['adminid'];
    $_SESSION["adminname"] = $row["adminname"];
    $_SESSION["adminpassword"] = $row["adminpassword"];
    }
     header('Location: index.php');
    }
?>

It works perfectly on my local, but when I upload it to Ipage or some other server it doesn't register session variables.

A: Try rearranging session_start() like this:
<?php
  session_start();
  require_once('./includes/connection.inc.php');
  ...

and give it a try. Something may be happing (error or output) in connectoin.inc.php that is preventing session_start() from working correctly.
To help debug the problem add error output like this:
<?php
  session_start();
  error_reporting(E_ALL);
  ini_set('display_errors', '1');
  require_once('./includes/connection.inc.php');
  ...

A: the page does not give you the default save path, you need to create one :
or use root path to save any files or session_save_path
like this one :
in the top of your code
session_save_path("/home/users/xxx/xxx/ipg.website/");
NOT :
session_save_path("/home/users/xxx/xxx/ipg.website/cgi-bin/tmp");

this path doesn't exist
you need to create it.

A: Go to your server and open your php.ini file and find session.save_path word on your php.ini
you have got 3 results for this search like
session.save_path = "4;/hermes/phpsessions"

First two result comment (simply add ; first of line) and last one change path
session_save_path("/home/users/xxx/xxx/ipg.website/cgi-bin/tmp");

you have set your own server root path
My server is iPage so I have put my server session example, it's various to your server to server but the last path set as it is but set your own root path.


text:
Q: python - pass 3d array to C code How to pass 3D python array to C code then get return back?
I have researched,

*

*Pass a 2d numpy array to c using ctypes
I have tried for 2D
Source :
 - http://cboard.cprogramming.com/c-programming/61578-4-dimensional-array-contiguous-allocation.html#post438210
test1.py
import numpy as np
import numpy.ctypeslib as npct
from numpy.ctypeslib import ndpointer
import ctypes
import sys
import time

_doublepp = ndpointer(dtype=np.uintp, ndim=2, flags='C')

_dll = ctypes.CDLL("foo_test.dll")

_foobar = _dll.foobar
_foobar.argtypes = [ctypes.c_int, ctypes.c_int, _doublepp, _doublepp]
_foobar.restype = None

def foobar(x):
    y = np.zeros_like(x)
    print x.__array_interface__
    print x.shape[0]
    print x.strides
    xpp = (x.__array_interface__['data'][0]
      + np.arange(x.shape[0])*x.strides[0]).astype(np.uintp)
    ypp = (y.__array_interface__['data'][0]
      + np.arange(y.shape[0])*y.strides[0]).astype(np.uintp)
    print xpp
    print ypp
    m = ctypes.c_int(x.shape[0])
    n = ctypes.c_int(x.shape[1])
    o = ctypes.c_int(x.shape[2])
    _foobar(m, n, o, xpp, ypp)
    return y

if __name__ == '__main__':
    n = sys.argv[1]
    n = float(n)
    dim = np.sqrt(n)
    s1=time.clock()
    x = np.arange(n).reshape((3,3,3))
    # x = np.arange(9).reshape((3,3))
    y = foobar(x)
    f1 = time.clock()
    print 'Execution Time is ', f1-s1, ' Second'
    print y[:]

foo_test.c
#include <stdio.h>
#include <stdlib.h>

#ifdef FOO_DLL
#ifdef FOO_EXPORTS
#define FOO_API __declspec(dllexport)
#else
#define FOO_API __declspec(dllimport)
#endif //For FOO_Export
#else
#define FOO_API extern
#endif //for FOO_DLL

#ifdef __cplusplus
extern "C" {
#endif

// http://cboard.cprogramming.com/c-programming/61578-4-dimensional-array-contiguous-allocation.html#post438210
void* my_malloc(char *expr, size_t size)
{
    void* result = malloc(size);
    printf("Malloc (%s) is size %lu, resulting %p\n", expr, (unsigned long)size, result );
    return result;
}

void my_free(void* ptr)
{
    printf("Freeing : %p\n", ptr);
    free(ptr);
}

#define MY_MALLOC(x)    my_malloc(#x, x)
#define MY_FREE(x)      my_free(x)

//Create float 2D
float **array2D(int dimx, int dimy)
{
    float **allx = MY_MALLOC(dimx * sizeof *allx);
    float *ally = MY_MALLOC(dimx * dimy * sizeof *ally);
    float **result = allx;
    int x;

    for(x = 0; x < dimx ; x++, ally += dimy)
    {
        result[x] = ally;
    }

    return result;
}

//create float 3D
float ***array3D(int dimx, int dimy, int dimz)
{
    float ***allx = MY_MALLOC(dimx * sizeof *allx);
    float **ally = MY_MALLOC(dimx * dimy * sizeof *ally);
    float *allz = MY_MALLOC(dimx * dimy * dimz * sizeof *allz);
    float ***result = allx;
    int x, y;

    for(x = 0; x < dimx ; x++, ally += dimy)
    {
        result[x] = ally;
        for (y = 0; y <dimy ; y++, allz += dimz)
        {
            result[x][y] = allz;
        }
    }

    return result;
}

void foobar(const int m, const int n, const int o, const double*** x, double*** y)
{
    float ***array3d;
    // int x, y;

    array3d = array3D(m,n,o);
    size_t i,j,k;
    for(i = 0; i< m; i++)
    {
        for(j = 0; j < n; j++)
        {
            for(k = 0; k < o; k++)
            {
                array3d[i][j][k] = 5.0;
                y[i][j][k] = array3d[i][j][k];
            }
        }
    }
}

#ifdef __cplusplus
    }
#endif

The Error said,

Traceback (most recent call last):   File "test1.py", line 40, in

      y = foobar(x)   File "test1.py", line 30, in foobar
      _foobar(m, n, o, xpp, ypp) ctypes.ArgumentError: argument 3: : argument must be an ndarray

A: Finally, I solved my problem, (Thanks to Evert for suggestion)
c_multiply.c
#include "c_multiply.h"
#include <stdio.h>

void ccmultiply4d(double* array, double multiplier, int m, int n, int o, int p) {

    int i, j,k, l ;
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            for (k = 0; k < o; k++)
                for (l = 0; l < p; l++)
                {
                    array[i*m*n*o + j*n*o + k*o + l] = array[i*m*n*o + j*n*o + k*o + l] ;
                    printf("Array[%d*%d*%d*%d + %d*%d*%d + %d*%d + %d] * Multiplier  = Array[%d] * %d = %.lf\n", i,m,n,o,j,n,o,k,o,l, i*m*n*o + j*n*o + k*o + l, multiplier, array[i*m*n*o + j*n*o + k*o + l]);
                }

}

test.pyx
import cython

# import both numpy and the Cython declarations for numpy
import numpy as np
cimport numpy as np

# declare the interface to the C code
cdef extern from "c_multiply.h":
    void ccmultiply4d(double* array, double value, int m, int n, int o, int p)

@cython.boundscheck(False)
@cython.wraparound(False)
def multiply(np.ndarray[double, ndim=4, mode="c"] input not None, double value):
    """
    multiply (arr, value)

    Takes a numpy arry as input, and multiplies each elemetn by value, in place

    param: array -- a 2-d numpy array of np.float64
    param: value -- a number that will be multiplied by each element in the array

    """
    cdef int m, n, o, p

    m, n, o, p = input.shape[0], input.shape[1], input.shape[2], input.shape[3]

    ccmultiply4d(&input[0,0,0,0], value, m, n, o, p)


text:
Q: Why are some ZLE sequences being remapped to "self-insert"? I've been tinkering with my dotfiles lately, and at some point I lost use of the default ^A and ^K keymappings, which I use frequently.
bindkey -L | grep '\^[AK]
# bindkey -R "^A"-"^C" self-insert
# bindkey "^K" self-insert

But the man page for zshzle clearly states that ^K and ^A are mapped by default to kill-line and asf, as I've come to expect.
I can't find anywhere in any of my initialization files where this would have been remapped! I certainly didn't do it:
print /usr/local/ ~/.z^(compdump|sh_history) ~/dotfiles | xargs ag 'bindkey'
# /Users/vercingetorix/.zshrc
# 56:bindkey "^[[3~" delete-char
#
# /Users/vercingetorix/dotfiles/zsh/zshrc
# 56:bindkey "^[[3~" delete-char

That's all I have!
In fact I know I didn't do it:
zsh -x &> diagnose.log
exit
wc -l diagnose.log
#     3802 diagnose.log
[[ -z $(ag '\^[AK]' diagnose.log) ]] && print 'nothing!'
# nothing!
[[ -z $(ag 'bindkey -[evaM]' diagnose.log) ]] && print 'nothing!'
# nothing!

So what gives? What's happening to the default mappings?

A: I figured it out!
From the zshzle man page:

In addition to these names, either 'emacs' or 'viins' is also linked to the name 'main'.  If one of the VISUAL or EDITOR environment  variables contain  the  string  'vi'  when  the  shell  starts up then it will be 'viins', otherwise it will be 'emacs'.  bindkey's  -e  and  -v  options provide a convenient way to override this default choice.

Lo and behold, I had recently set EDITOR and VISUAL to "vim". Removing this setting gives me back my key bindings (I guess these are Emacs defaults, but they're also familiar Mac bindings).


text:
Q: Creating a new table in a new worksheet with maximum column values from other worksheets Good evening, I am trying to load number of csv files and then calculate the max of each column from Column E to the last column (last column can be different for each run) and paste the values in a new work sheet.
I have tried to break my coading down in stages as I am learning VBA:
Step 1.  Code to open folder select dialogue box and load each text files to excel in different worksheets with file name
Step 2.  Code to open new worksheet and name as "Result"
with some sample data step 1 and 2 look like this [figure 1]:

and finally
Step 3. Code to find the maximum value for column E to last column and paste in the result sheet with the year number and the heigh number from the worksheet name, for example as follows:

So far with the help of this forum I have managed to create procedures with a simple userform with a run button that look like this:

I have manged to complete Step 1 and Step 2 (please see my codes below) but now really stuck with Step 3.
So far for step 3 I have managed to write something that can calculate max for column 'E' but just could not figure out how to calculate for all columns from column 'E' onwards for each work sheet and paste to the result sheet. I can calculate the col E max using the following code but the 5th line on the code do not copy to other columns:
Sub SumData()

    Dim lastrow As Long
       lastrow = Range("A1").End(xlDown).Row

    Cells(lastrow + 2, "E").Formula = "=MAX(E2:E" & lastrow & ")"

    Cells(lastrow + 2, "E").AutoFill , Type:=xlFillDefault

    End Sub

I would really appreciate any advise with my step 3 and to make you understand easier I have copied my sample csv files in the following drop box link:
https://www.dropbox.com/sh/hqhzd901vwlgbl9/AAApxVc_CAsESxR9iZ4cHoOua?dl=0
The codes that I have created for step 1 and 2 are below and working for me:
    Private Sub FilePath_Button_Click()
get_folder
End Sub

Private Sub Run_Button_Click()
load_file
End Sub

Public Sub get_folder()

Dim FolderName As String
With Application.FileDialog(msoFileDialogFolderPicker)
  .AllowMultiSelect = False
  .Show
  On Error Resume Next
  FolderName = .SelectedItems(1)
  Err.Clear
  On Error GoTo 0
End With
TextBox1.Text = FolderName
End Sub

Sub load_file()
Dim strFile As String
Dim WS As Worksheet
Dim test As String

Dim wb As Workbook

test = TextBox1.Text

strFile = Dir(Me.TextBox1.Text & "\*.plt")

       Set wb = Workbooks.Add
        'added workbook becomes the activeworkbook
       With wb
       Do While Len(strFile) > 0

        Set WS = ActiveWorkbook.Sheets.Add
        WS.Name = strFile

With WS.QueryTables.Add(Connection:= _
     "TEXT;" & test & "\" & strFile, Destination:=Range("$A$1"))
    .Name = strFile
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False

    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
strFile = Dir
Loop
End With

Dim WS2 As Worksheet
Set WS2 = Sheets.Add
Sheets.Add.Name = "Result"

MsgBox "Job Complete"
End Sub

Private Sub UserForm_Click()

End Sub

There may lot simpler way of writing the codes but this is the best I could come up with for step 1 and 2. Many thanks in advance!

A: If all the worksheet names has the same format i.e XXX_XXX_XX_XXXX then it is pretty simple to extract those values. You can use Split function. here is an example
Sub Sample()
    Dim sName(1 To 4) As String
    Dim i As Long

    sName(1) = "HP5_1gt_60_2010"
    sName(2) = "HP5_1gt_70_2010"
    sName(3) = "HP5_1gt_100_2008"
    sName(4) = "HP5_1gt_110_2008"

    For i = 1 To 4
        Debug.Print "Height --> " & Split(sName(i), "_")(2)
        Debug.Print "Year --> " & Split(sName(i), "_")(3)
        Debug.Print "-----"
    Next i
End Sub

Output

And to find the maximum value in a column, you can use the Max worksheet function in VBA. here is an example
Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range

    Set ws = ThisWorkbook.Sheets("Sheet1")
    Set rng = ws.Columns(5)

    Debug.Print Application.WorksheetFunction.Max(rng)
End Sub

Output


text:
Q: calculated date & time column, sharepoint 2007 With the following formula in my calculated column which formats the date & time column:
=TEXT(DatePublished,"d/m/yyyy")

How may i make sure the other dates are disabled when users create a custom list item, ie. users have actually no option to select any other dates?
Or maybe disable the calendar when they click on the calendar icon?
A workaround or am i missing out a lot?

A: oh my, sorry. I missed out something big, could have used the already available 'Created' field. Then create another calculated column 'DatePublished' with formula:
=TEXT(Created,"dd/m/yyyy")


text:
Q: Android search view auto suggest clicked bring related data I know there is a lot of solutions suggested and most of them i got understand them clear  use AutoCompleteTextView and i want usesearch view as small developer i try to find the solution to fit my goal , i have php script that bring these json data
[
{"fish_id":"1","fish_name":"Indian Mackerel","fish_weight":"2kg","price":"$10"},
{"fish_id":"2","fish_name":"Manthal Repti","fish_weight":"0.5kg","price":"$3"},
 {"fish_id":"3","fish_name":"Baby Sole Fish","fish_weight":"5kg","price":"$12"},
{"fish_id":"4","fish_name":"Clam Meat","fish_weight":"1kg","price":"$7"},
 {"fish_id":"5","fish_name":"Indian Prawn","fish_weight":"0.2kg","price":"$5"}
]

After long search i found this which bring data "fish_name" on auto suggestion and it works fine.The main goal is when i click item from  auto suggestion list it has to display all related contents as brough by json, So i got  this concept which bring data from sqlite database, the problem with it is it has to send request to the server based on selected item and bring results, so it kind annoying and time wasting.
So how can i bring all this data to the app and display "fish_name"on auto suggest and when item clicked it has to display all disired contents i mean "fish_name","price" and "fish_weight", so that i can increase app efficiency.
///Here is main activity with search  fuctionarity inside
 /// main activity with search  fuctionarity

    public class MainActivity extends AppCompatActivity {

   SearchView searchView = null;
    private String[] strArrData = {"No Suggestions"};

    @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textViewResult = (TextView) findViewById(R.id.textViewResult);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final String[] from = new String[] {"fishName"};
    final int[] to = new int[] {android.R.id.text1};
    // setup SimpleCursorAdapter
    myAdapter = new SimpleCursorAdapter(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, null, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
    // Fetch data from mysql table using AsyncTask
    new AsyncFetch().execute();
       }
    @Override
     public boolean onCreateOptionsMenu(Menu menu) {
    // adds item to action bar
    getMenuInflater().inflate(R.menu.menu_main, menu);
    // Get Search item from action bar and Get Search service
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
       }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
        searchView.setIconified(false);
        searchView.setSuggestionsAdapter(myAdapter);
        // Getting selected (clicked) item suggestion
        searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
            @Override
            public boolean onSuggestionClick(int position) {
                // Add clicked text to search box
                CursorAdapter ca = searchView.getSuggestionsAdapter();
                Cursor cursor = ca.getCursor();
                cursor.moveToPosition(position);
                String mimi= cursor.getString(cursor.getColumnIndex("fishName"));

                searchView.setQuery(cursor.getString(cursor.getColumnIndex("fishName")),false);
                int id = (int) searchView.getSuggestionsAdapter().getItemId(position);

                getData2(mimi);
                return true;
                   }
             @Override
             public boolean onSuggestionSelect(int position) {
                 return true;
            }
            });
           searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {

                // Filter data
                final MatrixCursor mc = new MatrixCursor(new String[]{ BaseColumns._ID, "fishName" });
                for (int i=0; i<strArrData.length; i++) {
                    if (strArrData[i].toLowerCase().startsWith(s.toLowerCase()))
                        mc.addRow(new Object[] {i, strArrData[i]});
                }
                myAdapter.changeCursor(mc);
                return false;
                }
                });
                }

               return true;
               }
            @Override
              protected void onNewIntent(Intent intent) {
            if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            if (searchView != null) {
            searchView.clearFocus();
                 }
        // User entered text and pressed search button. Perform task ex: fetching data from database and display
          }
           }

//AsyncTask  onPostExecute
         @Override
         protected void onPostExecute(String result) {
        //this method will be running on UI thread
        ArrayList<String> dataList = new ArrayList<String>();
        pdLoading.dismiss();
        if(result.equals("no rows")) {
            // Do some action if no data from database
             }
        else{
            try {
                JSONArray jArray = new JSONArray(result);
                // Extract data from json and store into ArrayList
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    dataList.add(json_data.getString("fish_name"));
                 }
                strArrData = dataList.toArray(new String[dataList.size()]);
                   }
                 catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show(); }
             }
             }

// Method to fetch data base on the fish_name selected using volley
     private void getData2(String fish_name ) {
          if (fish_name.equals("")) {
        Toast.makeText(this, "Please select item", Toast.LENGTH_LONG).show();
        return;
             }
           loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
           String url = Config.DATA_URL+fish_name ;
          StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            loading.dismiss();
            showJSON(response);
           }
         },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
                }
            });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
         requestQueue.add(stringRequest);
          }

       private void showJSON(String response){
       String name="";
       String weight="";
       String price = "";
          try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
        JSONObject allegeData = result.getJSONObject(0);
         name = allegeData.getString("fish_name");
        weight = allegeData.getString("fish_weight");
        price = allegeData.getString("price");
         } catch (JSONException e) {
        e.printStackTrace();
          }
        textViewResult.setText("Fish Name :\t"+name+"\n Weight :\t" +weight + "\n Price:\t"+ price);
        }


text:
Q: Javascript global variable I have a script tag with 'A' variable and has been initialised as 16 but when I use alert on IE under onclick event, I received undefine rather than 16.
Is this the problem in IE 6?
e.g.

undefine

A: I'd bet on it being caused by some slight confusion...
Being that putting var in front of a variable puts that variable into the local scope only in Javascript, and a variable delcaration without it (a = 16) is global.
function test() {
    a = 16;
    var b = 16;

}
test();

alert(a); # alerts 16
alert(b); # throws error, b is undefined

A: This is just a simple concept of global and local variable.. when You run the method the variable which is global has got its value and the variable which is local has also got the value but its lifecycle expires on going out of function thus it throws error to be undefined

A: You need to post an example of what you are talking about, but the problem may be in where your script tag is and where you are calling the variable from.


text:
Q: Upload using mime/multipart corrupts the file I wrote a server that has a route to upload a picture. This is a form that receive a few parameters: title, description, visibility and the picture. The page also uses the Authentication header.
func UploadPictureRoute(prv *services.Provider) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        user, err := auth.ValidateRequest(prv, w, r)
        if auth.RespondError(w, err) {
            return
        }

        r.ParseMultipartForm(10 << 20) // 10 meg max

        title := r.FormValue("title")
        desc := r.FormValue("description")
        visib := r.FormValue("visibility")
        visibInt, err := strconv.Atoi(visib)
        visibility := int8(visibInt) // Visibility can be either 0, 1, 2

        if err != nil {
            w.WriteHeader(http.StatusBadRequest)
        }

        file, _, err := r.FormFile("picture")
        if err != nil {
            w.WriteHeader(http.StatusBadRequest)
            return
        }
        defer file.Close()

        mimeType, _, err := mimetype.DetectReader(file) // Package gabriel-vasile/mimetype
        if err != nil {
            w.WriteHeader(http.StatusBadRequest)
            return
        }

        if !utils.IsValidMimetype(mimeType) { // Basically just comparing to image/png, image/jpg. Crashes here
            w.WriteHeader(http.StatusBadRequest)
            return
        }

        parentFolder := prv.PicturePath + "/" + strconv.FormatInt(*user.ID, 10) + "/"

        _, err = os.Stat(parentFolder)
        if os.IsNotExist(err) {
            err = os.MkdirAll(parentFolder, os.ModePerm)
            if err != nil {
                w.WriteHeader(http.StatusInternalServerError)
                return
            }
        }

        pict := model.Picture{
            Title:       title,
            Description: desc,
            Creator:     &user,
            Visibility:  visibility,
            Ext:         utils.GetExtForMimetype(mimeType),
        }

        pict, err = dal.CreatePicture(prv, pict)
        if err != nil {
            w.WriteHeader(http.StatusInternalServerError)
            return
        }

        outputFile, err := os.Create(parentFolder + strconv.FormatInt(*pict.ID, 10) + "." + pict.Ext)
        if err != nil {
            w.WriteHeader(http.StatusInternalServerError)
            dal.DeletePicture(prv, pict)
        }
        defer outputFile.Close()

        _, err = io.Copy(outputFile, file)
        if err != nil {
            w.WriteHeader(http.StatusInternalServerError)
            return
        }
// Responding
    }
}

This works well using Postman, it uploads the file correctly and everything works as expected.
However, i failed to write a go http client to upload a file:
type uploadResponse struct {
    URLID string
}

func main() {
    filename := "filename.png"

    file, err := os.Open(filename)
    if err != nil {
        fmt.Println(err)
    }
    defer file.Close()

    // Just to be sure we're really at the start of the file
    _, err = file.Seek(0, io.SeekStart)
    if err != nil {
        fmt.Println("Can't read the file")
        return
    }

    mime, _, err := mimetype.DetectReader(file)
    if err != nil {
        fmt.Println("Can't read the file")
        return
    }

    if !api.IsMimetypeAllowed(mime) { // Just check if it's a jpg/png/gif. This works on the client
        fmt.Println("This filetype can't be uploaded to a Scinna server.")
        fmt.Println("Please convert this file to jpeg, png or gif.")

        return
    }

    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)

    title, _ := writer.CreateFormField("title")
    title.Write([]byte("My picture title"))

    desc, _ := writer.CreateFormField("description")
    desc.Write([]byte("My picture description"))

    visib, _ := writer.CreateFormField("visibility")
    visib.Write([]byte("0"))

    pict, _ := writer.CreateFormFile("picture", file.Name())
    _, err = io.Copy(pict, file)

    writer.Close()

    r, err := http.NewRequest("POST", "https://myapi.local/pictures", body)
    if err != nil {
        panic(err)
    }
    r.Header.Add("Content-Type", writer.FormDataContentType())
    r.Header.Add("Authorization", "Bearer "+config.Token)

    client := &http.Client{}
    client.Do(r)
}

This code makes the server crash. The mimetype of the picture becomes application/octet-stream and the image headers are broken (It still opens in some editors, but EyesOfGnome basically says that the picture is not a JPG/PNG file because it can't find the magic numbers at the beginning)
How do i fix the HTTP go client to successfully upload pictures ?

A: The call to mimetype.DetectReader(file) reads part of the file.  The call to  _, err = io.Copy(pict, file) reads the remainder of the file. To read the entire file, seek back to offset 0 before the call to io.Copy.
Files are opened at offset 0. There's no need to seek to offset 0  immediately after the call to Open.
Fix the problem by swapping order of the calls:
...

mime, _, err := mimetype.DetectReader(file)
if err != nil {
    fmt.Println("Can't read the file")
    return
}

// Rewind to the start of the file
_, err = file.Seek(0, io.SeekStart)
if err != nil {
    fmt.Println("Can't read the file")
    return
}

...

The sever has a similar problem.  Rewind after detecting the type:
mimeType, _, err := mimetype.DetectReader(file) // Package gabriel-vasile/mimetype
if err != nil {
    w.WriteHeader(http.StatusBadRequest)
    return
}

// Rewind to the start of the file
_, err = file.Seek(0, io.SeekStart)
if err != nil {
    w.WriteHeader(http.StatusInternalServerError)
    return
}

A: I found a solution:
UploadFile
Clone this, if you find any problem, comment here.


text:
Q: How to set up Google Chrome as default browser in Xubuntu I use Xubuntu 12.04. I uninstalled Firefox and now use Google Chrome version 19.xxx.
To solve this problem, I tried:

*

*galternatives

*the "default apps" under settings and

*sudo update-alternatives --config x-www-browser
Neither of these worked. Does anybody have an alternative solution for this?
--> Solution: I used the "sudo gedit /usr/share/applications/defaults.list" tip from 天使の and searched for firefox in the whole document! Everytime I found "firefox" I replaced it with "google-chrome.desktop". I also used the "default apps" menu to change it to google-chrome. And now it works.. I hope it helps some other ;-)

A: SOLVED:
Listen, the easy way to do this is open xfce4-settings-manager as root either with
sudo bash
xfce4-settings-manager

or
gksu xfce4-settings-manager

then select preferred apps, and under browsers select other then paste:
/usr/bin/X11/chromium-browser

close it and you are good for all users, forever. :D

A: In "settings manager", chose "preferred applications". The path to the chromium executable is /usr/bin/X11/chromium-browser. Had the same problem as you, and this solved it.

A: First I tried replacing firefox with chromium-browser everywhere in this document:
gksudo gedit /usr/share/applications/defaults.list

It didn't work. Still Firefox would open my documents rather than Chromium.
Then I did this alternative:
sudo update-alternatives --config x-www-browser

Got three alternatives:
0 - auto
1 - manual Chromium-browser
2 - manual Firefox

I selected 0. Now it works!

A: Maybe use this way
gksudo gedit /usr/share/applications/defaults.list

try to find x-www-browser and set its value to your google-chrome.desktop location
EDIT
if you won't find x-www-browser, then try to search for

text/html=firefox.desktop;google-chrome.desktop
text/xml=firefox.desktop;google-chrome.desktop
application/xhtml_xml=google-chrome.desktop
x-scheme-handler/http=firefox.desktop;google-chrome.desktop
x-scheme-handler/https=firefox.desktop;google-chrome.desktop
x-scheme-handler/ftp=google-chrome.desktop

A: If you meant the 'Web Browser' shortcut at the bottom screen dock, when you click it, it will ask you to choose the browser you want to use and in the list, there is no chrome right?
Just choose "Other..." (it's on the bottom of the drop-down menu) and enter 'google-chrome' and press ok.
It will now open chrome when you click it later on.
Happy Xubuntuing! ;)

A: Instructions for setting up SRWare (Iron Browser) as your default in Linux Mint 14:
sudo apt-get install chromium ( or use synaptic ) then..
sudo apt-get install galternatives then.....
sudo update-alternatives --config x-www-browser

You will now see choices and you should now see chromium (was option 0 for me.. choose and hit enter)
Example:
  0            /usr/bin/chromium-browser   40        auto mode
  1            /usr/bin/chromium-browser   40        manual mode
  2            /usr/bin/firefox            40        manual mode

Now go into "preferred applications" and you'll see chromium, change that to Chromium.
Now selecting links in IRC, ect., it will open up Iron Browser and not the default Firefox, and wont open in Chromium as long as you have Iron already opened up!
Oh happy days are here again!!  \o/
(if you do not install chromium before doing any of this, you will see no other options in x-www-browser, config editor or preferred applications)
Hope this helps all the complaints I see all over the place on Iron not setting as default in Mint! :)

A: Xubuntu 14.04 LTS
Making Chrome as the default browser for XFCE.
gedit ~/.local/share/applications/mimeapps.list

[Added Associations]
text/plain=gedit.desktop;openoffice.org-writer.desktop;
application/x-shellscript=gedit.desktop;
x-scheme-handler/http=google-chrome.desktop;
x-scheme-handler/https=google-chrome.desktop;
x-scheme-handler/ftp=google-chrome.desktop;
x-scheme-handler/chrome=google-chrome.desktop;
text/html=google-chrome.desktop;
application/x-extension-htm=google-chrome.desktop;
application/x-extension-html=google-chrome.desktop;
application/x-extension-shtml=google-chrome.desktop;
application/xhtml+xml=google-chrome.desktop;
application/x-extension-xhtml=google-chrome.desktop;
application/x-extension-xht=google-chrome.desktop;
inode/directory=Thunar-folder-handler.desktop;
application/xml=gedit.desktop;
application/pdf=qpdfview.desktop;

[Default Applications]
x-scheme-handler/http=google-chrome.desktop
x-scheme-handler/https=google-chrome.desktop
x-scheme-handler/ftp=google-chrome.desktop
x-scheme-handler/chrome=google-chrome.desktop
text/html=google-chrome.desktop
application/x-extension-htm=google-chrome.desktop
application/x-extension-html=google-chrome.desktop
application/x-extension-shtml=google-chrome.desktop
application/xhtml+xml=google-chrome.desktop
application/x-extension-xhtml=google-chrome.desktop
application/x-extension-xht=google-chrome.desktop
application/pdf=qpdfview.desktop

A: I'm running 11.04 with Chrome 18 and I was able to change the default browser inside Chrome's Settings via the wrench menu.
At the very bottom of the main Settings page is a button for default browser. I had an external application open. The first time Firefox started. After the change, a new Chrome tab opened upon clicking a link in the external application, without restarting any of the applications.
You didn't say whether you have tried this, so we don't know whether this is an issue with 12.04.
Edit: It may be that Chrome's settings don't have the desired effect in Xubuntu, as they do in stock Ubuntu.  More info might help us find an answer.

A: This is still broken in 13.04. I installed Chrome, and now every time I click on a link in another application, it asks what browser I want to make the default (I click chromium-browser); and every time I start Chrome manually, it asks if I want to make it the default browser (yes).
Why is this setting not sticking? Has someone in Ubuntu dev got it in for Chrome?
This has been an issue since 12.04 and is still not fixed. Fixing it via the command line or config edit is fine for experts and sysadmins, but so far I have had to explain it away to all my users by saying that someone fouled up the code and you have to do this by hand and one day perhaps they'll get it fixed.
It really looks bad when this kind of thing never gets fixed.

A: gvfs-mime --set x-scheme-handler/http google-chrome.desktop
gvfs-mime --set x-scheme-handler/https google-chrome.desktop
gvfs-mime --set text/html google-chrome.desktop


text:
Q: Signing a letter to a company you're suing I am replying a letter to a letter a company send me I am currently going though the courts with. I used to work for this company and the director is not on my Christmas card list.
What is a funny/blunt/sends a message/harsh way to sign the letter at the end?
Something a little better than "Yours sincerely".

A: My co-worker once made a mistake while writing an email (luckily caught before sending), which I think would fit the bill here.
Best regrets,
sign


text:
Q: 'Error: [$rootScope:inprog] $apply already in progress' when selecting a value from dropdown, after migrating from v1.2 to v1.6 After migrating our AngularJS application from v1.2.9 to v1.6.9, whenever I click on any dropdown option, I get error in developer console stating

'Error: [$rootScope:inprog] $apply already in progress'

I have tried using $timeout solution and it solves the issue for some cases(where $apply was used). However, this specific issue occurs when I am clicking on a dropdown option. I have not called $apply anywhere in my code. I tried using the ng-options in select tag too, however the issue still occurs.
Select tag that gives issue:
<select name="task" id="task" ng-model="search.task">
    <option data-ng-repeat="each in taskList" value="{{each.id}}"
            ng-selected="each.id==search.task">
      {{each.taskName}}
    </option>
</select>

Code changes after using ng-options:
<select ng-model="search.task" ng-options="each for each in taskList">
    <option value="">Task Type</option>
</select>

Please follow link for complete error stack

Error: [$rootScope:inprog] $apply already in progress
  http://errors.angularjs.org/1.6.9/$rootScope/inprog?p0=%24apply

How do I fix this error? Any help/pointer is much appreciated.

A: Don't use ngSelected with ngModel1
<select name="task" id="task" ng-model="search.task">
    <option data-ng-repeat="each in taskList" value="{{each.id}}"
            ̶n̶g̶-̶s̶e̶l̶e̶c̶t̶e̶d̶=̶"̶e̶a̶c̶h̶.̶i̶d̶=̶=̶s̶e̶a̶r̶c̶h̶.̶t̶a̶s̶k̶"̶ >
      {{each.taskName}}
    </option>
</select>

From the Docs:

Note: ngSelected does not interact with the select and ngModel directives, it only sets the selected attribute on the element. If you are using ngModel on the select, you should not use ngSelected on the options, as ngModel will set the select value and selected options.
— AngularJS ng-selected Directive API Reference

See additional Docs:

*

*Using ng-repeat to generate select options

*Using select with ng-options and setting a default value
See Stackoverflow:

*

*Using ng-repeat to generate select options (with Demo)

Diagnosing Error: $rootScope:inprog Action Already In Progress2
When you get this error it can be rather daunting to diagnose the cause of the issue. The best course of action is to investigate the stack trace from the error. You need to look for places where $apply or $digest have been called and find the context in which this occurred.
There should be two calls:

*

*The first call is the good $apply/$digest and would normally be triggered by some event near the top of the call stack.

*The second call is the bad $apply/$digest and this is the one to investigate.
Once you have identified this call you work your way up the stack to see what the problem is.
If the second call was made in your application code then you should look at why this code has been called from within an $apply/$digest. It may be a simple oversight or maybe it fits with the sync/async scenario described earlier.
If the second call was made inside an AngularJS directive then it is likely that it matches the second programmatic event trigger scenario described earlier. In this case you may need to look further up the tree to what triggered the event in the first place.
For more information, see AngularJS Error Reference - $rootScope/inprog -
Diagnosing This Error
See also,

*

*AngularJS Developer Guide (V1.1) Runtime Concepts

*AngularJS $rootScope/Scope API Reference


text:
Q: ring of $p$-adic algebraic integers Let $K/\mathbb{Q}_p$ be a finite extension, and $\overline{K}$ be some fixed algebraic closure of $K$. Let $\mathcal{O}_{\overline{K}}$ be the ring of all algebraic integers in $\overline{K}$. I know it is a valuation ring so it is an integrally closed local domain.
I would like to know what is the Krull dimension of this ring? Is the maximal ideal the only nontrivial prime ideal? In particular, I am interested in whether $\mathrm{Spec}(\overline{K})\to\mathrm{Spec}(\mathcal{O}_{\overline{K}})$ is an open immersion?

A: I'm not quite sure why you're being downvoted. These are reasonable questions in my opinion.
So, you've singled out that you have a valuation ring $\mathcal{O}$ (for future reference let's call $L:=\mathrm{Frac}(\mathcal{O})$) and you want to know

*

*is it true that $\mathcal{O}$ has only one non-zero prime,

*what is the Krull dimension of $\mathcal{O}$,

*whether the map $\mathrm{Spec}(L)\to\mathrm{Spec}(\mathcal{O})$ is an open embedding.

To answer your first question, let us recall the following fact.

Fact: Let $\mathcal{O}$ be a valuation ring. Then, the set of ideals of $\mathcal{O}$ is a linearly ordered set.

In particular, we see that the spectrum $\mathrm{Spec}(\mathcal{O})$ looks like a 'path', like this (assuming it's finite dimensional)
$$(0)—\bullet-\cdots\bullet-\mathfrak{m}$$
(incidentally, spectra of valuation rings are exactly used as 'paths' in birational geometry of schemes/formal schemes). Moreover, it's clear that the length of this path is the same thing as the Krull dimension of $\mathcal{O}$. Thus, $\mathcal{O}$ has a unique non-zero prime ideal (which is the maximal ideal) if and only if it is of dimension $1$.
Is $\mathcal{O}_{\overline{K}}$ of dimension $1$? The answer is yes since $\mathrm{Spec}(\mathcal{O}_{\overline{K}})\to\mathrm{Spec}(\mathcal{O}_K)$ is surjective and integral (see Tag 0CEG). Thus, your first (and second) questions are answered.
To answer your third it is useful to put things in a bigger context. Namely, we would like to know when the map $\mathrm{Spec}(L)\to\mathrm{Spec}(\mathcal{O})$ is an open embedding or, equivalently, when $\mathrm{Spec}(L)$ is an open subset of $\mathrm{Spec}(\mathcal{O})$.
To this end, recall that any time you have a valuation ring $\mathcal{O}$ you get a valuation
$$v:L^\times\to \Gamma$$
where $\Gamma$ is some totally ordered abelian group (in fact, one can take $\Gamma=L^\times/\mathcal{O}^\times$ in the usual way). Recall that we say that $\Gamma$ is of height  1 if there exists an embedding of totally ordered abelian groups $\Gamma\hookrightarrow (\mathbb{R},^+)$.
One is then able to put a valuation topology on $L$ by declaring that a basis of open sets is given by (let's assume that $v$ is non-trivial!) $\{a\in L:v(a)\leqslant \gamma\}$ for some $\gamma$ in $\Gamma$.
We then have the following definition.

Definition A valuation ring $\mathcal{O}$ is called microbial if its valuation topology agrees with the valuation topology of some
height $1$ valuation $v'$ on $\mathcal{O}$.

In particular, note that being microbial doesn't mean your valuation is height $1$, it only means that your 'valuation topology is rank $1$'.
NB: Such valuation rings are very important in Huber's theory of adic spaces, and Fujiwara—Kato's theory of the birational geometry of formal schemes. You can look there for many natural examples of microbial valuation rings which aren't height 1. You can also see [Morel, Example I.1.5.5] for a concrete example.
We then have the following nice proposition.

Proposition: Let $\mathcal{O}$ be a valuation ring. Then, the following are equivalent:

*

*$\mathcal{O}$ is microbial,

*there exists some non-zero element $\varpi\in \mathcal{O}$ such that $\mathcal{O}$ is $\varpi$-adically separated,

*there exists some non-zero element $\varpi\in\mathcal{O}$ such that $L=\mathcal{O}[\frac{1}{\varpi}]$,

*the map $\mathrm{Spec}(L)\to\mathrm{Spec}(\mathcal{O})$ is an open embedding.

Proof: See this and [Morel, Theorem I.1.5.4]. $\blacksquare$
In particular, I can look at your example of $\mathcal{O}_{\overline{K}}$ and immediately see that $\mathrm{Spec}(\overline{K})\to \mathrm{Spec}(\mathcal{O}_{\overline{K}})$ is an open embedding since either:

*

*the valuation ring $\mathcal{O}_{\overline{K}}$ is height 1, and so of course microbial,

*it is $p$-adically separated (exercise!).

NB: Note that $\mathcal{O}_{\overline{K}}$ is not $p$-adically complete, so it's good that in the definition of microbial we only required separatedness!
References:
[Morel] Morel, S., 2019. Adic Spaces. Lecture Notes. https://web.math.princeton.edu/~smorel/adic_notes.pdf.


text:
Q: Adding a image button to a gridview header in c# with on click event I have a gridview (below) that populates with details about a project, I want to be able to sort the results by clicking on the header for which you want to sort by.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CssClass="mGrid"
PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt" DataKeyNames="ProjectID"
OnRowDataBound="OnRowDataBound" EnableModelValidation="True" Style="width: 95%;
float: left;" AllowSorting="True">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
<Columns>
    <asp:BoundField DataField="Title" HeaderText="Project Title" ItemStyle-Width="10%"
        ItemStyle-Font-Bold="true">
        <ItemStyle Width="10%" />
    </asp:BoundField>
    <asp:BoundField DataField="Division" HeaderText="Division" ItemStyle-Width="10%">
        <ItemStyle Width="10%" />
    </asp:BoundField>
    <asp:BoundField DataField="Due Date" HeaderText="Due Date" ItemStyle-Width="10%">
        <ItemStyle Width="10%" />
    </asp:BoundField>
    <asp:BoundField DataField="Status" HeaderText="Status" ItemStyle-Width="10%">
        <ItemStyle Width="10%" />
    </asp:BoundField>
</Columns>
<PagerStyle CssClass="pgr"></PagerStyle>

To do this I add in my c# code, 2 image buttons to the header with an on click event added, I call this method in the page_load after the gridview is populated:
public void addHeaderFilters()
    {
        //Add to project title
        ImageButton titleAscImg = new ImageButton();
        titleAscImg.ID = "IMGB_ProjTitleAsc";
        titleAscImg.Click += new ImageClickEventHandler(sortBy_Click);
        titleAscImg.ImageUrl = "images/image";
        titleAscImg.CssClass = "sortButton";

        ImageButton titleDescImg = new ImageButton();
        titleDescImg.ID = "IMGB_ProjTitleDesc";
        titleDescImg.Click += new ImageClickEventHandler(sortBy_Click);
        titleDescImg.ImageUrl = "images/image2";
        titleDescImg.CssClass = "sortButton";

        Label lbl = new Label();
        lbl.Text = "Project Title ";

        GV_Projects.HeaderRow.Cells[2].Controls.Add(lbl);
        GV_Projects.HeaderRow.Cells[2].Controls.Add(titleAscImg);
        GV_Projects.HeaderRow.Cells[2].Controls.Add(titleDescImg);
    }

    public void sortBy_Click(object sender, EventArgs e)
    {
        ImageButton imgb = new ImageButton();
        imgb = (ImageButton)sender;
    }

This displays the header as expected, however when I click on either image button, the event isn't fired and the header returns back to its default from the aspx code removing the arrows, and I'm not quite sure why?
Any help is appreciated.

A: It looks like you need to encase the addHeaderFilters() in a !IsPostBack statement
Like this
if(!IsPostBack)
{
    addHeaderFilters();
}

A: protected void GridViewTransaction_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.Header)
    {
        ImageButton btnExcelReport = new ImageButton();
        btnExcelReport.ID = "BtnExcelReport";
        btnExcelReport.ImageUrl = "images/excel.gif";
        btnExcelReport.ToolTip = "generate Excel report from result";
        btnExcelReport.Click += new ImageClickEventHandler(btnExcelReport_Click);

        e.Row.Cells[0].Controls.Add(btnExcelReport);
    }
}


text:
Q: separate event function trigger twice on a child element where parent has the same event function below is my snippet, the issue is, if you click unto the "li" element that has a text of "test 1" the alert prompt did trigger once (normal) but if you click unto the "li" element that has a text of "test 2", the alert prompt triggered twice like the click event function called twice. Any ideas, clues?

$(document).ready(function(){

  $(document).on("click", ".nav a", function(){

   alert("test");
  })
  $(document).on("click", ".dp a", function(){

   alert("test");
  })

});

test 1

test 1

test 1

test 2

test 2

A: Use event.stopPropagation(), It will prevent any parent event action

$(document).ready(function() {
  $(document).on("click", ".nav a", function() {
    alert("test");
  }).on("click", ".dp a", function(e) {
    e.stopPropogation();
    alert("test");
  })
});

test 1

test 1

test 1

test 2

test 2

UPDATE :
As haim770's suggested, bind event handler to the appropriate selector to prevent bubbling

$(document).ready(function() {
  $(document).on("click", ".nav > li > a", function() {
    alert("test");
  }).on("click", ".dp a", function() {
    alert("test");
  })
});

test 1

test 1

test 1

test 2

test 2

A: Specify which hyperlink for the first click event.
FIDDLE: https://jsfiddle.net/cshanno/Loc4427u/1/
JS
$(document).ready(function(){

  $(document).on("click", "ul:nth-child(1) > li > a", function(){

   alert("test");
  })
  $(document).on("click", ".dp a", function(){

   alert("test 2");
  })

});


text:
Q: Random text from string array list for button Example I have 3 buttons:
<Button
android:id="@+id/q1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/q2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/q3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

and and I have text to random from arraylist as bellow code:
final String[] answers = private static final String[] answers = {"a", "b", "c", "Vowel", "d", "e", "f", "Vowel"};

Bellow is the code get "Vowel" text from arrayList:
final ArrayList<Integer> numbers = new ArrayList<Integer>();
    Random rnd = new Random();
    while (numbers.size()<=4)
    {
      int randomInteger = rnd.nextInt(answers.length);
      if (!numbers.contains(randomInteger))
      {
        numbers.add(randomInteger);
      }
    }
    if (!numbers.contains(3))
    {// here 3 is index of vowel
        int index = rnd.nextInt(numbers.size());//this random to set the index of vowel at random position
        numbers.set(index,3);
    }

    final Button q1 = (Button) findViewById(R.id.q1);
    q1.setText(answers[numbers.get(0)]);

    final Button q2 = (Button) findViewById(R.id.q2);
    q2.setText(answers[numbers.get(0)]);

    final Button q3 = (Button) findViewById(R.id.q3);
    q3.setText(answers[numbers.get(0)]);

Code above is showing Vowel all the times when activity start... but sometimes Vowel show double because in ArrayList has 2 "Vowel":
(Not correct)Example 5 times to start acivity:

1st activity start random look like: a, c, Vowel
2st activity start random look like: b, Vowel, Vowel
3st activity start random look like: Vowel, e, b
4st activity start random look like: Vowel, e, Vowel
5st activity start random look like: Vowel, b, f

So, how to show only 1 "Vowel" event in array list has 2 "Vowel":
(Correct) Example 5 times to start acivity:

1st activity start random look like: a, c, Vowel
2st activity start random look like: b, Vowel, a
3st activity start random look like: Vowel, e, b
4st activity start random look like: a, e, Vowel
5st activity start random look like: Vowel, b, f

The code above no error at all...just sometimes it show 2 "Vowel"..but I want to show only 1 Vowel.
How to modified it?
Thanks

A: You are checking index 3, because it's index of Vowel but what about index 7? It's Vowel too.
if (!numbers.contains(3) && !numbers.contains(7))
    {// here 3 is index of vowel
        int index = rnd.nextInt(numbers.size());//this random to set the index of vowel at random position
        numbers.set(index,3);
    }


text:
Q: How does an exponent work when it's less than one? I'm rather familiar with exponents, I know that $y^x = y_1 \cdot y_2 \cdot y_3 .... y_x$, but what if the exponent is less than one, how would that work?
I put in my computer $25^{1/2}$ anyway, expecting it to give me an error, and I got an answer!! And even more surprising, when I did this with more numbers and a little research, I found that $$x^{1/y} = \sqrt[y] x$$ Is it just me, or can exponents take on the role of square roots?

A: You're right that there is something interesting going on. It's certainly true that $25^{1/2} = 5$ is a bit different than $3^2 = 3 \cdot 3 = 9$.
One of the reasons why we've chosen $25^{1/2}$ to mean $\sqrt{25}$ goes like this.
For normal, positive integer exponents, we have the really nice exponent laws
$a^b \cdot a^c = a^{b+c}$. For instance, $3^3 \cdot 3^5 = 3^8$. What if we wanted this law to work even when we used numbers less than $1$, or maybe fractions between integers?
Then we would want $25^{1/2} \cdot 25^{1/2} = 25^{\frac{1}{2} + \frac{1}{2}} = 25^1 = 25$, and so we would want $25^{1/2} = \sqrt {25}$. This works with others, too. For instance, $27^{1/3}$ should satisfy $27^{1/3} \cdot 27^{1/3} \cdot 27^{1/3} = 27^1 = 27$, so that $27^{1/3} = \sqrt[3]{27} = 3$.
For this also works for fractions bigger than $1$. Thus $36^{3/2}$ should satisfy $36^{3/2} \cdot 36^{3/2} = 36^3$, so $36^{3/2} = \sqrt{36^3}$. Note that you could also rationalize this as thinking that $36^{3/2}$ should equal $(36^3)^{1/2}$, and indeed that works here!
More generally, choosing $25^{1/2}$ to mean $\sqrt {25}$ (and the related identities) agrees with all of our previous rules regarding exponents, so it seems like a very natural choice to make. And indeed, it is the choice we make.
As an aside: one can further extend exponents to decimal expansions instead of fractions, or go further still.

A: For integer exponents we have the property that $(y^a)^b = y^{ab}$ (among others). In order to define $y^q$ for rational $q$, we want it to preserve this property. Writing $q = a/b$ with $a,b$ integers and $b$ positive, we would like
$$ (y^q)^b = (y^{a/b})^b = y^{(a/b)b} = y^a. $$
So we would like $y^q$ to be a $b$th root of $y^a$. This always exists if $y$ is positive. So we define
$$y^{a/b} = \sqrt[b]{y^a} \quad(y \ge 0).$$
Then it can be verified that the other properties of exponentiation are satisfied for rational exponents, so this is a good definition.

A: $$y^x = y\cdots y$$
only if $x$ is a positive integer.
In general:
$$y^x = \exp(x\log y)$$
provided that $y >0$ (the functions $\exp$ and $\log$ can be defined via power series).
Also one can prove:
$$\sqrt[x]{y} = y^{1/x}$$
as you noted (this can also be taken as the definition of roots).

A: One thing we notice right away about $b^n; n \in N$ is that $b^nb^m = b^{n+m}$ (This is obvious because $b^n = \underbrace{b\cdot b\cdots b}_{n\text{ times}}$ and $b^m = \underbrace{b\cdot b\cdots b}_{m\text{ times}}$, so $b^nb^m = \underbrace{b\cdot b\cdots b}_{n\text{ times}} \cdot \underbrace{b\cdot b\cdots b}_{m\text{ times}} = \underbrace{b\cdot b\cdots b}_{n+m\text{ times}} = b^{n+m}$).
And that $(b^n)^m = \underbrace{b^n\cdot b^n\cdots b^n}_{m \text{ times}} = b^{n+n+...+n} = b^{n\cdot m}$.
So if we want to extend the definition of $b^n$ so that $n$ is not just a natural number but maybe $n = 0$ or $n < 0$ or $n \in \mathbb Z$ we realize that we want to define it so that $b^0b^n = b^{0+n} = b^n$.  That means we must define $b^0 = b^n/b^n = 1$.  (We really have not choice).
We also want it so that if $0 < n < m$ then $b^{m-n}=b^mb^{-n}$ so $b^{-n} = \frac{b^{m-n}}{b^m}= \frac{b^{m-n}}{b^{(m-n)+n}} = \frac {b^{m-n}}{b^{m-n}b^n} = \frac 1 {b^n}$.
So we must define $b^{-n} = 1/b^n$.  (We really have no choice.)
Now we also have $(b^n)^m = b^{nm}$ this means $ \sqrt[m]{b^{nm}} = b^n$.  This really isn't that surprising. After all $\sqrt[m]{b^{nm}} =\sqrt[m]{(b^{n})^m} = b^n$, after all.
But what if we aren't talking about whole integers? What if $\sqrt[m]{b^n} = \sqrt[m]{(b^{nm/m})}=\sqrt[m]{(b^{n/m})^m} = b^{n/m}$.  Does that make any sense at all?
Well, it makes perfect sense if $m$ divides $n$ and $n/m$ is an integer.
But if $n/m$ then .... we haven't defined what $b^{n/m}$ means if $n/m$ isn't an integer.
But why shouldn't we define $b^{n/m}$ if $n/m$ isn't an integer?  If we define $b^{n/m} = \sqrt[m]{b^n}$ that is a fine definition[@].  And because of our rules $(b^r)^n = b^{rn}$ we really have no choice.  We must define it that way.
So $a^{1/2} = \sqrt{a}$.  This is because if $a^{1/2} = x$ then $x^2 = (a^{1/2})^2 = a^{\frac 12 * 2} = a^1 = a$.  So $x = \sqrt{a}$.
[@] Actually, we have to show that if $r = m/n = p/q$ then $\sqrt[n]{b^m} = \sqrt[q]{b^p}$ as it turns out that is true.  $m/n = p/q$ mean $mq= np$ and $\sqrt[n]{b^m} = \sqrt[q]{\sqrt[n]{b^m}^q}=\sqrt[nq]{b^{mq}} = \sqrt[nq]{b^{np}} = \sqrt[q]{\sqrt[n]{(b^p)^n}} = \sqrt[q]{b^p}$

A: This isn't really a proof but just another way to look at it.
If you raise $a^b$ to the $n$th power, i.e. $(a^b)^n$, you can calculate this by multiplying the exponents:
$$(a^b)^n = a^{bn}.$$
Now consider the case of $n = 1/b$:
$$(a^b)^{1/b} = a^{b\cdot \frac1b} = a^1 = a.$$
So if I square a number ($b=2$), and then get the number back after I raised it to the $1/2$ power, it sure looks like I took the square root.
In more general terms, raising to the $1/b$th power is the inverse operation of raising to the $b$th power (as long as we stay away from $b=0$).

A: I'd like to weigh in with how we define numbers, to give a big picture of it all.
Start with the natural numbers, define a starting point and the notion of a successor.
0
0+1
0+1+1
...

Now define addition as repeated succession, and multiplication as repeated addition. Easy enough.
Now we can answer questions such as
2+6=?
2*6=?

But we can also ask
2+?=6
2*?=6

We now define 6-2 as "the number which when added to 2 gives 6 and similarly define 6/2 as "the number which when multiplied by 2 gives 6.
We have a problem when we try to do things such as 6+?=2 because we only have the natural numbers defined so far. But here we say "I define the negative numbers to exist such that they obey the rules of addition and subtraction as above."
6+?=2
?=2-6=0-4=-4

And the number -4 is defined into existence Similarly
6*?=2
?=2/3

We have now defined the fractions. They are imaginary numbers which are only "real" insofar as they are consistent with the rules.
Likewise we define surds: $\sqrt{2}$ is the number such that $\sqrt{2}\times\sqrt{2}=2$.
We can define exponentiation as repeated multiplication and solve the problem of "what is the nth root of something" by defining it as "it's whatever thing that, when you multiply it by itself n times, gives you that something." That's what your question is essentially about.
$x^{-3}=\frac{1}{x^3}$ because $x^{-3}=x^{-1\times 3}=(x^{-1})^3=(\frac{1}{x})^3=\frac{1}{x^3}$ because we defined $x^{-1}=\frac{1}{x}$ and then followed the established rules.
The natural conclusion to this is to define imaginary numbers such as $i=\sqrt{-1}$ and this gives us an algebraic closure which means we don't have to invent any other kinds of number in order to answer any algebraic question. (You can invent other kinds of number but they have their own algebras.)

A: Also consider this: $25 = 5 \cdot 5$.
So if we take "half" of $25$, written as a multiplication, then it certainly makes sense that we get $5$ as the result. Other answers show the general extrapolation of this idea.