text:
Q: Group homology in degrees zero and one using the standard resolution I'm trying to show using the standard resolution that for any group $G$,
$$
H_0(G) = \mathbb{Z} \text{ and } \quad H_1(G) = \frac{G}{[G,G]}.
$$
(I already know this holds, as by definition it is $H_\bullet(G) = H_{\bullet}(X)$ with $X$ a $K(G,1)$ space: these are always path connected, and by Hurewicz's theorem we get $H_1(X) = \pi_1(X)^{ab} = G^{ab}$. However, this exercise explicitly asks for the computations to be done with the standard resolution and so I want to get to understand it.)
So, we start with the chain complex
$$
\cdots \xrightarrow{d_n} C_n \to C_{n-1} \xrightarrow{d_{n-1}} \cdots \to C_1 \xrightarrow{d_1} C_0 \xrightarrow{\varepsilon} \mathbb{Z} \to 0
$$
where $C_n$ is the free $\mathbb{Z}$-module generated by $G^{n+1}$ with its $\mathbb{Z}[G]$-module structure given by the action $g(g_0,\dots,g_n) := (gg_0,\dots,gg_n)$, and the differentials are defined by
$$
d_n : (g_0, \dots,g_n) \in C_n \mapsto \sum_{i=0}^n(-1)^i(g_0,\dots,\widehat{g_i},\dots,g_n) \in C_{n-1}.
$$
Hence I want to compute the homology in degrees zero and one of
$$
\cdots \to \mathbb{Z} \otimes_{\mathbb{Z}[G]} C_2 \xrightarrow{1 \otimes d_2} \mathbb{Z} \otimes_{\mathbb{Z}[G]} C_1 \xrightarrow{1 \otimes d_1}\mathbb{Z} \otimes_{\mathbb{Z}[G]} C_0 \to 0.
$$
So far, I have proved that:

*

*$\mathbb{Z} \otimes_{\mathbb{Z}[G]} C_0 \simeq \mathbb{Z}$ simply because $C_0 \simeq \mathbb{Z}[G]$ as a $\mathbb{Z}[G]$-module, with basis $(1)$.

*We have $1 \otimes d_1 = 0$. In effect: as any element of $C_1$ is a $\mathbb{Z}[G]$-linear combination of elements of the form $(1,g)$, it suffices to note that
$$
\begin{align}
1 \otimes d_1 (n \otimes (1,g)) &= n \otimes [(g)-(1)] = n \otimes (1) - n \otimes (g) = n \otimes (1) - n \otimes g(1) \\
&= n \otimes (e) - gn \otimes (1) = 0.
\end{align}
$$
because the action of $G$ on $\mathbb{Z}$ is trivial.
From here one can see that $$H_0(G) = \frac{\mathbb{Z} \otimes_{\mathbb{Z}[G]} C_0}{\operatorname{im}1 \otimes d_1} = \frac{\mathbb{Z} \otimes_{\mathbb{Z}[G]} C_0}{0} = \mathbb{Z} \otimes_{\mathbb{Z}[G]} C_0 \simeq \mathbb{Z}.$$
I also know by a direct calculation that
$$
\begin{align}
1 \otimes d_2(n \otimes (1,g,h)) &= n \otimes [(g,h) - (1,h) + (1,g)]\\
&= n \otimes [(1,g^{-1}h) - (1,h) + (1,g)].
\end{align}
$$
and so
$$
H_1(G) = \frac{\ker 1 \otimes d_1}{\operatorname{im} 1 \otimes d_2} = \frac{\mathbb{Z} \otimes_{\mathbb{Z}[G]} C_1}{\operatorname{im} 1 \otimes d_2} = \frac{\mathbb{Z} \otimes_{\mathbb{Z}[G]} C_1}{<n \otimes [(1,g^{-1}h) - (1,h) + (1,g)]>_{n \in \mathbb{Z}, \ g,h \in G}}
$$
So far, I've failed to come up with a good description for $\mathbb{Z} \otimes_{\mathbb{Z}[G]} C_1$ and $\operatorname{im} 1 \otimes d_2$.
Any hints on how to continue would be greatly appreciated! Thanks in advance.

A: As you have pointed out, in $\Bbb Z\otimes_{\Bbb Z[G]}C_1$ you have the relation
$1\otimes(g,h)=1\otimes(1,g^{-1}h)$. Then $\Bbb Z\otimes_{\Bbb Z[G]}C_1$
is the free Abelian group on the symbols $1\otimes(1,g)$, which I'll denote
by convenience $[g]$. Then $H_1(G)$ is the quotient of
$\Bbb Z\otimes_{\Bbb Z[G]}C_1$ by the symbols $[g^{-1}h]-[h]+[g]$, as you point out. That is $[g]+[k]-[gk]$ where $k=g^{-1}h$. So $H_1(G)$ is the quotient
of the free Abelian group on $G$ by the relations $[gk]=[g]+[k]$. That's
just the Abelianisation of $G$: $G/[G,G]$. In more detail, $G\mapsto H_1(G)$
via $g\mapsto [g]$ is a homomorphism, and as the target is Abelian, it factors
through $G/[G,G]$, so in effect is a map $G/[G,G]\to H_1(G)$. Considering the
map going the other way taking $[g]$ in the free Abelian group over $G$ to
$g[G,G]\in G/[G,G]$ yields the inverse map.


text:
Q: How to reset for loop to make it read a list from the beginning So I have a for loop, which deletes elements of the list if it meets some conditions. When it deletes the 2nd element, it continues for loop from 2nd element my problem is that I want it to start this loop from the beginning, so it checks a list from 1st item. Is it possible?
some_list = ["one", "two", "two", "one", "two", "three", "two"]

for element in some_list:
    if element == "one":
        if some_list.index(element) + 1 == two:
            some_list.remove(some_list.index(element) + 1)

here's some sample code. I want it to check there's "one", remove "two" and when it removes, start again at "one" in the beginning, remove "two", go to "one again, go to 2nd "one", remove "two" and list looks like this:
some_list = ["one", "one", "three", "two"]

A: I would suggest using a while loop since the for loop in python once initiated follows along the initial execution unlike C++, Java, etc
some_list = ["one", "two", "two", "one", "two"]
i = 0
while( i != (len(some_list) - 1)):
    if some_list[i] == "one":
        if some_list[i + 1] == 'two':
            del some_list[i + 1]
            i = 0
            continue
    i = i + 1
print(some_list)

A: Algorithm to delete all 'two''s that occur after 'one':
>>> def del_two(some_list):
...     i = 0
...     while i < len(some_list):
...             if some_list[i] != 'one':
...                     i += 1
...                     continue
...             i += 1
...             while i < len(some_list) and some_list[i] == 'two':
...                     del some_list[i]

>>> some_list = ["one", "two", "two", "one", "two"]
>>> del_two(some_list)
>>> print(some_list)
['one', 'one']

A: You can try while loop instead of for loop and what you need will be this:
some_list = ["one", "two", "two", "one", "two"]

i = 0
while i < len(some_list):
    element = some_list[i]
    if element == "one":
        idx = i + 1
        if idx < len(some_list) and some_list[idx] == "two":
            some_list.pop(idx)
            i -= 1
    i += 1

print(some_list)

A: Your method is somewhat inefficient, as all the elements "two" are removed by the end of the loop, so it would be better to straight out remove all "two" elements.
for i, elem in enumerate(some_list):
    if elem == "two":
        del some_list[i]

For the sake of answering the question, though, here is my solution:
i=0
while i != len(some_list):
    if some_list[i] == "one" and some_list[i+1] == "two":
        del some_list[i+1]
    else:
         i += 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Current Location is not display above Api 23 I am displaying Map using Map view and before API 23 my App is Working fine and showing current location but when I run on 23 and above it's not showing current location.My code is as follow:
 mMap = googleMap;
        mMap.getUiSettings().setMapToolbarEnabled(false);

        LatLng loc = new LatLng(currentLatitude, currentLongitude);
        //mMap.addMarker(new MarkerOptions().position(loc).title(currentLocation + ", none"));
        //mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 14.0f));
        if (ActivityCompat.checkSelfPermission(MapClass.this.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapClass.this.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mMap.setMyLocationEnabled(true);

help me?

A: I might be a little late, but this answer will help people, who are having the same issue and want to run their app on both the versions. The catch is that for API's more than 21, you need to ask for Run time permission.
Firstly, I created a function named gettingLocationBasedOnApiVersion(mMap) in which I put all the code for which I used user's location. But beforehand, in the onMapReady()I checked for the API version and if the API version is more than 21, I asked for permissions.
@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        if(Build.VERSION.SDK_INT <= 21){
            gettingLocationBasedOnApiVersion(mMap);
            Toast.makeText(getApplicationContext(), "APK less than 21", Toast.LENGTH_LONG).show();
        }else{
            Log.i("SDK Version", "SDK more than 21 will require permissions on run time");
            Toast.makeText(getApplicationContext(), "APK greater than 21", Toast.LENGTH_LONG).show();
            enableMyLocation();
        }
    }

Then In the enable function I asked for the run time permissions.
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private boolean mPermissionDenied = false;
private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission to access the location is missing.
            PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                    Manifest.permission.ACCESS_FINE_LOCATION, true);
        } else if (mMap != null) {
            // Access to the location has been granted to the app.
            mMap.setMyLocationEnabled(true);
            gettingLocationBasedOnApiVersion(mMap);

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            return;
        }

        if (PermissionUtils.isPermissionGranted(permissions, grantResults,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Enable the my location layer if the permission has been granted.
            enableMyLocation();
        } else {
            // Display the missing permission error dialog when the fragments resume.
            mPermissionDenied = true;
        }
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (mPermissionDenied) {
            // Permission was not granted, display error dialog.
            showMissingPermissionError();
            mPermissionDenied = false;
        }
    }

    /**
     * Displays a dialog with error message explaining that the location permission is missing.
     */
    private void showMissingPermissionError() {
        PermissionUtils.PermissionDeniedDialog
                .newInstance(true).show(getSupportFragmentManager(), "dialog");
    }

For better understanding, use you can refer the Places Class on my github page.
PS. Don't forget to add the PermissionUtils Class in your app folder.

A: Checking the document about Requesting Permissions at Run Time it is stated that:

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app. It also gives the user more control over the app's functionality; for example, a user could choose to give a camera app access to the camera but not to the device location. The user can revoke the permissions at any time, by going to the app's Settings screen.
If the device is running Android 6.0 or higher, and your app's target SDK is 23 or higher: The app has to list the permissions in the manifest, and it must request each dangerous permission it needs while the app is running. The user can grant or deny each permission, and the app can continue to run with limited capabilities even if the user denies a permission request

 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
            @NonNull int[] grantResults) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            return;
        }

        if (PermissionUtils.isPermissionGranted(permissions, grantResults,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Enable the my location layer if the permission has been granted.
            enableMyLocation();
        } else {
            // Display the missing permission error dialog when the fragments resume.
            mPermissionDenied = true;
        }
    }

The ApiDemos repository on GitHub includes samples that demonstrate the use of location on a map:

*

*MyLocationDemoActivity: Using the My Location layer, including runtime permissions

*LocationSourceDemoActivity: Using a custom LocationSource
Hope this helps.


text:
Q: React-Pdf Is not printed correctly even after using all elements provided by the Library So I'm trying to build a mid-complex invoice for an app, but I'm having many problems getting the right layout printed, and I don't know the reason, I have tried some of the things.
So this is the design before I'm printing it (the React-pdf template):

So I want you to pay attention, to the items below that are iterated and printed. (Don't worry the logo will be shown on the print page, I don't know why is not showing by default on the design page).
And here is the template after the print, that the layout of items is broken, and it doesn't show the one I designed. But rather something else. Here it is:

Here is the live link to the React Pdf Editor, so you can check the code (because is to long for here):
React PDF Editor Online


text:
Q: MBR status confusion
EB 58 90 6D 6B 64 6F 73 66 73 00 00 02 08 20 00 02 00 00 00 00 F8 00
  00 3E 00 83 00 00 00 00 00 94 88 7E 00 98 1F 00 00 00 00 00 00 02 00
  00 00 01 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 29 A9 38
  B1 34 57 61 76 65 20 20 20 20 20 20 20 46 41 54 33 32 20 20 20 0E 1F
  BE 77 7C AC 22 C0 74 0B 56 B4 0E BB 07 00 CD 10 5E EB F0 32 E4 CD 16
  CD 19 EB FE 54 68 69 73 20 69 73 20 6E 6F 74 20 61 20 62 6F 6F 74 61
  62 6C 65 20 64 69 73 6B 2E 20 20 50 6C 65 61 73 65 20 69 6E 73 65 72
  74 20 61 20 62 6F 6F 74 61 62 6C 65 20 66 6C 6F 70 70 79 20 61 6E 64
  0D 0A 70 72 65 73 73 20 61 6E 79 20 6B 65 79 20 74 6F 20 74 72 79 20
  61 67 61 69 6E 20 2E 2E 2E 20 0D 0A 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 55 AA

Learning disk records, this is my USB MBR record viewed by bless on ubuntu formatted with disk utility as MBR table and FAT partition, referring to this Wiki of first record

status (0x80 = bootable (active), 0x00 = non-bootable, other = invalid
  )

but my MBR shows first offset as EB. ( The first byte )
What's this record stands for ? also, can you provide me with good tables/images tutorials for MBR and other disks' records :)

A: You're confusing the master boot record with the partition table.
The Wikipedia page about master boot records you linked to explains the layout in detail:

*

*The first 440 bytes form the code area, which contains the boot loader.
The boot loader is a tiny program that can get called by the BIOS.

*The next 6 bytes are entirely optional.
They may contain a disk signature (usually 4 bytes) and (usually 2) trailing 00 bytes.

*Only the next 64 bytes –  four 16-byte entries for each of the four possible primary partitions – form the partition table.

*The last two bytes are always 55 AA, the MBR signature.
In your example, the partition table consists entirely of 00 bytes, which means that your device contains no partitions.


text:
Q: RabbitMQ: Priority queue with changing priority I want to implement a priority work queue, in which the priority of a group of messages can change once they are in the queue. Since it is a work queue with variable processing time, the messages are not assigned using round-robin algorithm, but are pulled from the queue when a resource is free (using per-consumer limit).
I came up with 2 ideas for implementation:

*

*Use priority queue from RabbitMQ, and when a request for priority change comes, read messages with this priority from the queue and re-send them with different priority. (I am not sure this is a good approach, given the O(n) complexity.)

*Use several queues with distinct names for each group of messages, and use a separate queue to communicate the current priority list (ordered list of queue names) to workers. (Using this approach, I am not sure how to make the list of priorities "persistent", so that newly joined worker knows what is the current priority list.)

How would you implement it? Is RabbitMQ viable option for this use case?

A: your idea "priority of a message can change once they are in the queue" IMO is not possible with rabbitmq because rabbitmq only allows you to get messages from the head of a queue.
for example:

*

*you have N queues each used for a different priority

*each queue has 100+ messages

*your idea requires you to reach into the middle of a queue to get a specific message but this is not possible with rabbitmq so the thought experiment stops here because you can only get messages at the head of a queue

your idea IMO would require using something else besides rabbitmq.
a quick and dirty idea that would work with rabbitmq now and is similar to your idea:

*

*create one rabbitmq queue with N priorities

*submit a message with priority x

*if you need to change the priority to higher priority like priority y then you could send the same message again but with a new higher priority y

*this would ensure the new message is processed faster

*the side effect is that you may process the same request twice

*

*you could fix the side effect in your design by having a some sort of database for synchronization to keep track of what jobs are completed and then this could avoid processing the job twice

*there are many other details that would need to be addressed like keeping the original message around somehow outside of rabbitmq, concurrency, etc, etc,


text:
Q: how to add dynamic values using .each in jquery? enter image description hereDynamic  value as input:
2 //line 1
8 //line 2
code:
    var a = 0;
$('.finealert').each(function (){

   var fine = $(this).html();

   a+ = parseInt(fine);

});

Got the output as
2
10

Expected output
10

here two input values i got it dynamically,suppose if you are creating a page for library,we need to generate fine concept those who submit books after their due date and fine amount will generate dynamically,here in each loop first it displays value 2 and during 2nd iteration it displays 10(2+8) but here i want is instead of displaying 2,i want 10(total amount) should replace 2(first value) at the end of all iterations and i want to print the total amount(10) to the user not "2 and 10"

A: try change "html" method for "val" or "text" in otherwises, html method return HTML contents of the element matched

var a = 0;

$('.finealert').each(function (i, obj){
  var fine = $(obj).val();
  a += parseInt(fine);
});

alert(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<input type="text" value="8" class="finealert" />
<input type="text" value="2" class="finealert" />


text:
Q: How to make the keyboard disappear from a UITextView? I have a screen in my application that only consists of a UITextView. When first entering this screen, the keyboard is not present until you tap to edit.
But if you close the screen, and then come back to it, the keyboard is still visible, presumably remembering its status from before. I want it to be gone when re-entering the view.
Any tips? I've tried the following:
-(void)textViewDidEndEditing:(UITextView *)textView {
  NSLog ( @"end editing" );
  [textView resignFirstResponder];
}

Looking at the console, it does indeed get called when closing that screen, but it doesn't seem to help - the text view still has the keyboard when i re-enter the screen.
Thanks a lot

A: Always set your outlets to nil on:
-(void)viewDidUnload
{
   self.textViewObject = nil;
}

A: In the end, i had to make it so that the view that opened this view re-created this view every time it opened it to get the keyboard to not reappear.

A: try putting the same in
-(void)viewWillDisappear:(BOOL)animated

function
the code goes like this
-(void)viewWillDisappear:(BOOL)animated
{
   [self.textViewObject resignFirstResponder];
}

You can also specify the same in
-(void)viewWillAppear:(BOOL)animated

function as well.


text:
Q: How do I extract data from a dynamicly created table ASP.NET I got table, generated by this code (I know it looks bad but it just as a test):
 protected void Gen_Load(object sender, EventArgs e)
        {
            List<string> ParamList = new List<string>();
            ParamList.Add("Perforation");
            ParamList.Add("Top of perforation");
            ParamList.Add("Bottom of perforation");
            ParamList.Add("Well radius");
            for (int i = 0; i < 4; i++)
            {
                TableRow row1=new TableRow();
                TableCell cell1=new TableCell();
                cell1.BorderColor=System.Drawing.Color.DarkGray;
                cell1.BorderWidth=2;
                cell1.Font.Size = 11;
                cell1.Text=ParamList.ElementAt(i);
                TableCell cell2 = new TableCell();
                cell2.BorderColor=System.Drawing.Color.DarkGray;
                cell2.BorderWidth=2;
                cell2.Width = 200;
                TextBox text1 = new TextBox();
                text1.ID = "txtb_1" + i;
                text1.Width = cell2.Width;
                text1.Height = cell2.Height;
                cell2.Controls.Add(text1);
                TableCell cell3 = new TableCell();
                cell3.BorderColor=System.Drawing.Color.DarkGray;
                cell3.BorderWidth=2;
                cell3.Width = 200;
                DropDownList dlist = new DropDownList();
                dlist.ID = "dlist_1" + i;
                ListItem li1 = new ListItem("m");
                ListItem li2 = new ListItem("ft");
              //  if (i != 0)
               // {
                    dlist.Items.Add(li1);
                    dlist.Items.Add(li2);
             //   }
                dlist.Width = cell3.Width;
                dlist.Height = cell3.Height;
                cell3.Controls.Add(dlist);
                row1.Cells.Add(cell1);
                row1.Cells.Add(cell2);
                row1.Cells.Add(cell3);
                row1.ID = "id" + i;
                ParamTable.Rows.Add(row1);
            }
        }

So how do I can get data from dropdownlist and textbox elements on it? I assume that I could use elements ID somehow to call  them, but I can't find any example.
UPD: aspx
          <asp:Table CssClass="span9"  style="margin-top:2px; margin-bottom:5px;"   ID="ParamTable" runat="server">
                   <asp:TableHeaderRow >
                                <asp:TableHeaderCell  Font-Size="Medium" BorderColor="DarkGray" BorderWidth="2px"  >Parameters</asp:TableHeaderCell>
                                <asp:TableHeaderCell  Font-Size="Medium" BorderColor="DarkGray" BorderWidth="2px" >Value</asp:TableHeaderCell>
                                <asp:TableHeaderCell  Font-Size="Medium" BorderColor="DarkGray" BorderWidth="2px" >Units</asp:TableHeaderCell>
                    </asp:TableHeaderRow>
                   <asp:TableRow >
              </asp:TableRow>
           </asp:Table>

A: See below code to get the value of each row :
for (int i = 0; i < ParamTable.Rows.Count; i++)
{
    var textBoxValue = ((TextBox)ParamTable.Rows[i].Cells[1].FindControl("txtb_1" + i)).Text;
    var dropDownValue = ((DropDownList)ParamTable.Rows[i].Cells[2].FindControl("dlist_1" + i)).SelectedItem.Text;
}

Note: I don't store values in any list. You can use POCO/Property class as per your requirement.
Update:
Remove <asp:TableRow ></asp:TableRow> from aspx and update forloop as mentioned below:
for (int i = 0; i < ParamTable.Rows.Count - 1; i++)
{
    var textBoxValue = ((TextBox)ParamTable.Rows[i].Cells[1].FindControl("txtb_1" + i)).Text;
    var dropDownValue = ((DropDownList)ParamTable.Rows[i].Cells[2].FindControl("dlist_1" + i)).SelectedItem.Text;
}


text:
Q: Jquery to switch between iframe and image I wish to have a onclick button to switch between an iframe and an image.
How is this possible? Please show me with jsfiddle if possible.

A:

$('iframe').toggle();
$('button').click(function(){
  $('img').toggle();
  $('iframe').toggle();
});

<button>toggle</button>
<img src="data:image/png;base64,[encoded data, 10012 characters]
" />


text:
Q: Composing addition and division verbs over lists If data =: 3 1 4 and frac =: % +/, why does % +/ data result in 0.125 but frac data result in 0.375 0.125 0.5?

A: %+/ 3 1 4 is "sum, then find reciprocal of that sum", that is:
   +/ 3 1 4
8
   % 8       NB. same as 1%8
0.125

But if you define frac =: %+/, then %+/ becomes a group of two verbs isolated from their arguments (aka tacit definition), that is, a hook:
   (%+/) 3 1 4
0.375 0.125 0.5

Which reads "sum, then divide original vector by that sum":
   +/ 3 1 4
8
   3 1 4 % 8
0.375 0.125 0.5

If you want frac to behave as in the first example, then you need to either use an explicit definition:
   frac =: 3 : '%+/y'
   frac 3 1 4
0.125

Or to compose % and +/, e.g. with atop conjunction or clever use of dyadic fork with capped left branch:
   %@(+/) 3 1 4
0.125
   ([:%+/) 3 1 4
0.125


text:
Q: eMFCC_ARGB32 to eMFCC_NV12 conversion make picture lighter In our EXISTING code we have two shaders applaying one by another for convert from eMFCC_ARGB32 pixel format to eMFCC_NV12.
First shader:
Texture2D tx_top : register( t0 );
Texture2D tx_bottom : register( t1 );
SamplerState sampler_in : register( s0 );
cbuffer PS_CONVERT : register (b0)
{
    float4 size;
    float4 vecY;
    float4 vecU;
    float4 vecV;
};
struct PS_INPUT
{
    float4 Pos : SV_POSITION;
    float2 Tex : TEXCOORD;
};
float4 PS(PS_INPUT input) : SV_Target
{
    float4 p1 = tx_top.Sample( sampler_in, float2(input.Tex.x - 0.5/size.x, input.Tex.y) );
    float4 p2 = tx_top.Sample( sampler_in, float2(input.Tex.x + 0.5/size.x, input.Tex.y) );
    float4 pm = (p1 + p2) * 0.5;
    float4 yuv;
    yuv.b = dot(pm.rgb, vecU.rgb) + vecY.a;
    yuv.g = dot(p1.rgb, vecY.rgb) + vecY.a;
    yuv.r = dot(pm.rgb, vecV.rgb) + vecU.a;
    yuv.a = dot(p2.rgb, vecY.rgb) + vecY.a;
   yuv = clamp(yuv, float4(0.0625, 0.0625, 0.0625, 0.0625), float4(0.9375, 0.9180, 0.9375, 0.9180));
    return yuv;
}

Second shader:
Texture2D tx : register( t0 );
SamplerState sampler_in : register( s0 );
cbuffer PS_CONVERT : register (b0)
{
    float4 size;
};
struct PS_INPUT
{
    float4 Pos : SV_POSITION;
    float2 Tex : TEXCOORD;
};
float4 PS(PS_INPUT input) : SV_Target
{
    float luma_flag = step(input.Tex.y, 0.666666);
    float pos_y = luma_flag * input.Tex.y / 0.666666 + (1 - luma_flag) * (input.Tex.y - 0.666666) / 0.333333;
    float4 pix1 = tx.Sample(sampler_in, float2(input.Tex.x - 0.5 / size.x, pos_y - 0.5 * (1.0 - luma_flag) / size.y) );
    float4 pix2 = tx.Sample(sampler_in, float2(input.Tex.x + 0.5 / size.x, pos_y - 0.5 * (1.0 - luma_flag) / size.y) );
    float4 pix3 = tx.Sample(sampler_in, float2(input.Tex.x - 0.5 / size.x, pos_y + 0.5 * (1.0 - luma_flag) / size.y) );
    float4 pix4 = tx.Sample(sampler_in, float2(input.Tex.x + 0.5 / size.x, pos_y + 0.5 * (1.0 - luma_flag) / size.y) );
    pix1 = (pix1 + pix3) * 0.5;
    pix2 = (pix2 + pix4) * 0.5;
    return float4(pix2.g, pix1.a, pix1.g, pix2.a) * luma_flag + float4(pix2.b, pix1.r, pix1.b, pix2.r) * (1.0 - luma_flag);
}

But the image got ligher than original.
Original:

After processing:


text:
Q: Rabbit MQ Strategy to not lose messages I have some load balanced web servers that get hit with lots of requests (events).  To keep the web servers very quick I want to push these events into rabbitMq and process them later.
I have a couple questions about the best setup for this.
The initial way I thought about it was have these web servers, publish to a rabbitMq cluster somewhere.  The only problem is that these events are very business critical and we can't afford to lose any (network outages and such).
Is it possible to set up rabbitmq locally on all the web servers, and have the web handlers (IIS) publish these events to the local rabbitmq broker and whenever the 'main' cluster is available the local broker would push them to the main cluster.  Later on the consumers would read the queues from the main cluster and do whatever processing needs to be done.

*

*Is this feasibly/easy with RabbitMq?

*Is this a good way to solve this problem or are there better alternatives?

*Can I guarantee that no messages will be lost with this strategy?

A: Take a look at the Federation Plugin: https://www.rabbitmq.com/federation.html
You can have your local RabbitMQ servers, and then federate the messages upstream to another(s) RabbitMQ cluster


text:
Q: Trigonometric Identities: Given that $\frac{2\cos(a)+3\sin(a)}{3\cos(a)-2\sin(a)}=-2$ find $\sin(2a)$ Given: $\dfrac{2\cos(a)+3\sin(a)}{3\cos(a)-2\sin(a)}=-2$
$\sin(2a)$ = ?
So what I did first was expand $\sin(2a)$ to $2\sin(a)\cos(a)$
Then I went back to the given and simplified that, and got that
$\sin(a)=8\cos(a)$
Then I plugged that into the first expanded expression I got, and got
$16\cos^2(a)$
Somehow this is wrong? What am I doing wrong.

A: If I'm not wrong, then you should just do this after finding out, that $\sin(a) = 8\cos(a)$
$\tan(a) = 8$
$1 + \tan^2(a) = 1/\cos^2(a)$, so
$\sin(2a) = 2\sin(a)\cos(a)=2\tan(a)\cos^2(a) = \dfrac{2\tan(a)}{1 + \tan^2(a)}$

A: you have $$\sin(a)=8\cos(a)$$ and we know that $$\sin ^ 2 ( \alpha) + \cos ^2 (\alpha ) =1$$
That gives you $$ \cos^2 (\alpha )=1/{65} $$ and $$ \sin^2 (\alpha )=64/{65} $$
Thus$$\sin(\alpha) \cos (\alpha) = \frac {8}{65}$$
That makes $$\sin ( 2 \alpha) =  \frac {16}{65}$$

A: HINT
We have that
$$\frac{2\cos(a)+3\sin(a)}{3\cos(a)-2\sin(a)}=-2 \iff \frac{2+3\tan a}{3-2\tan a}=-2 \implies \tan a=?$$
then use that by Tangent half-angle substitution
$$\sin 2a = \frac{2\tan a}{1+\tan^2 a}$$


text:
Q: How to set a 2 profit targets in pine script , one with 1:1 risk reward and 1:2.? How do I in pine script set a stop loss below a recent swing low and set 2 targets one of a 1:1 risk to reward ratio (rr) and a second target for the rest of the investment to 1:2 (rr). I cant seem to figure it out. Is there an example somewhere?
I get that if I get the swinglow, I can substract the buy price, but somehow it seems that I cant store the difference.
any help is much appreciated :) thanks

//@version=5
strategy("My Strategy", overlay=true, margin_long=100, margin_short=100)

shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
if (shortCondition)
    strategy.entry("My Short Entry Id", strategy.short)

var float swingLow = 0
var float recentSwinglow = 0
var float SL= 0

var float TP1 = 0
var float TP2 = 0
var float difference = 0

swingLow := ta.lowest(low, 20)

longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)

    strategy.entry("My Long Entry Id", strategy.long)
    recentSwinglow := swingLow
    // set 1 TP 1:1
    // use difference from swinglow and buy price and add that to the buy price that is the 1: 1 price
    SL := recentSwinglow

    difference := strategy.position_avg_price - recentSwinglow

    firstTakeProfit = strategy.position_avg_price + difference
    TP1 := firstTakeProfit
    TP2 := firstTakeProfit + difference

//shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))

//if shortCondition
//    strategy.entry('My Short Entry Id', strategy.short)

plot(recentSwinglow, color = color.red, linewidth = 2)
plotchar(recentSwinglow, title = "recentSwinglow")

plot(strategy.position_avg_price, color = color.white)
plotchar(strategy.position_avg_price, title = "price")

plotchar(difference, title = "difference")

plot(SL != 0? SL : na, color = color.red, linewidth = 2 )
plot(TP1 != 0? TP1 : na, color = color.green, linewidth = 2 )
plot(TP2 != 0? TP2 : na, color = color.purple, linewidth = 2 )
plotchar(TP1, title = "TP1")
plotchar(TP2, title = "TP2")

// idea from https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/
strategy.exit('25%TP1', qty_percent=25, profit=TP1, loss=SL)
//strategy.exit("x2", qty_percent = 25, profit = percentAsPoints(2), loss = SL)
//strategy.exit("x3", qty_percent = 25, profit = percentAsPoints(3), loss = SL)
strategy.exit('TP2', profit=TP2, loss=TP1)

if (close < SL and  strategy.position_size > 0 )
    strategy.close('My Long Entry Id')


text:
Q: Backbone: keep in sync both collections I have a collection of tiles. When app starts collection is fetched from server and its clone is assigned to a collection property of MdApp.TilesCollection object:
MdApp.TilesCollection.fetch({
        success: function(){
            console.log('Tiles collection fetched from server');
            console.log(MdApp.TilesCollection);
            if(!MdApp.TilesCollection.collection){
                MdApp.TilesCollection.collection = new Backbone.Collection(MdApp.TilesCollection.models);
                console.log('Made copy of collection in fetched collection instance');
            }
        },
        error: function(){
            console.log('Error!Unable to fetch tiles collection from server');
        }
    });

This is done for filtering purposes :
    TilesCollection = Backbone.Collection.extend({

    model: MdApp.TileModel,

    url : 'api/',

    rewriteModel: function(model){
        this.set(model);
    },

    byPrivate : function(){
        var filtered = this.collection.filter(function(tile){
            return tile.get('private') == '1';
        });
        console.log('filtered private: ' + filtered);
        return filtered;
    },

    byPublic : function(){
        var filtered = this.collection.filter(function(tile){
            return tile.get('private') == '0';
        });
        console.log('filtered public: ' + filtered);
        return filtered;
    },

    byFavourite: function(){
        var filtered = this.collection.filter(function(tile){
            return tile.get('favourite') == '1';
        });
        console.log('filtered favourite: ' + filtered);
        return filtered;
    },

    byAsc : function(){
        var filtered = this.collection.sortBy(function(tile){
            return tile.get('id');
        });
        console.log('filtered ascending: ' + filtered);
        return filtered;
    },

    byDesc : function(){
        var filtered = this.collection.sortBy(function(tile){
            return -tile.get('id');
        });
        console.log('filtered descending: ' + filtered);
        return filtered;
    },

    refilter: function(){
        console.log(this.collection);
        return this.collection.models;
    }
});

What I want to do is to keep MdApp.TilesCollection and MdApp.TilesCollection.collection in sync. When MdApp.TilesCollection's models are added or modified I want to make those particular changes to its clone. Of course I can just create new collection every time something is changed and assign it to that property, but it can be highly inefficient when collection is quite big. Does anyone can drop off any hint or solution?

A: You don't need to keep a clone of the collection in order to do filtering, you can do those filter operations on the original collection.
byPrivate : function(){
    var filtered = this.where({ private: 1 });
    console.log('filtered private: ' + filtered);
    return filtered;
}

If for whatever reason you still want to keep a clone and sync it, instead of creating a new collection in the fetch success callback you can simply reset it like this:
MdApp.TilesCollection.collection.reset(MdApp.TilesCollection.models);


text:
Q: how to fix this border issue I am using a border shadow, it is working fine till iPhone 6s but in greater variant the border is not coming.
I hierarchy is as:
tableView --> cell--> view(parentView)--> objects
   created extension for uiView:

 func addViewShadow(offset: CGSize, radius: CGFloat, color: UIColor, opacity: Float, cornerRadius: CGFloat? = nil) {
    self.layer.shadowOffset = offset
    self.layer.shadowRadius = radius
    self.layer.shadowOpacity = opacity
    self.layer.masksToBounds = false
    self.layer.shadowColor = color.cgColor
    if let r = cornerRadius {

        self.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: r).cgPath
        self.layer.cornerRadius = r
        //            self.clipsToBounds = true
    }
}

used as in class:
cell.parentView.addViewShadow(offset: CGSize.zero, radius: 2, color: UIColor.darkGray, opacity: 1, cornerRadius: 5)
image:

A: Move your code for adding shadow to layoutSubviews.

A: override func layoutSubviews() {
        super.layoutSubviews()
//your code here
    }

A: Best Solution of this issue is to give a white colour to your view which you putted in your cell
Change the colour from default to white its the best solution try it :)


text:
Q: multi column headers on ultrawebgrid of Infragistics I am currently using UltraWebGrid control of Infragistics to display data from an Oracle database. I was able to do this just right. Now I need to place a multi column header at the top of all the others column headers. I tried using the code below but when I checked it, it seems that the InitializeLayOut event is not triggered. Is there other way to do this? by the way I am using Visual Studio 2008, Oracle 11g and Infragistics v3.
protected void UltraWebGrid1_InitializeLayout(object sender, Infragistics.WebUI.UltraWebGrid.LayoutEventArgs e)
        {

            ColumnHeader colHead;
            for (int i = 0; i < e.Layout.Bands[0].HeaderLayout.Count; i++)
            {
                colHead = e.Layout.Bands[0].HeaderLayout[i] as ColumnHeader;
                colHead.RowLayoutColumnInfo.OriginY = 1;
            }

            ColumnHeader ch = new ColumnHeader(true);

            ch.Caption = "From Dispo";

            ch.RowLayoutColumnInfo.OriginX = 0;

            ch.RowLayoutColumnInfo.OriginY = 0;

            e.Layout.Bands[0].HeaderLayout.Add(ch);

            ch.RowLayoutColumnInfo.SpanX = 2;
        }

Thanks guys.

A: The InitializeLayout event should be triggered as part of data binding.  If it isn't firing, you should verify that it is being wired up properly.
If you did want to test the logic outside of the event, e.Layout is equal to ultraWebGrid1.DisplayLayout so you could modify the code and put it in your page load event.


text:
Q: Wrong props on client even though getServerSideProps returns properly I have a route /dashboard and /dashboard/[id].ts.
The getServerSideProps of /dashboard/[id].ts does a database call and returns data:

const books = await orm.find({ library: context.params.id });

return {
  props: { books }
}

So now this is the problme:

*

*I load /dashboard/1 - this shows the right books on the page

*I click button on the page to go to /dashboard

*I then click button page to go to /dashboard/2 - the problem is here. Instead of showing books that belong to id 2 its using the data that was loaded on the route I hit on first step.

Did anyone have this issue? Any ideas on how to fix?


text:
Q: Multiple summary data in crosstab row (duplicate) My time table report takes in this data:
Time    Day        Section
 10AM   Sunday       10
 10AM   Sunday       20
 9PM    Monday       5
 11PM   Tuesday      4

I want the following output in my crosstab.

But I only get one value in each section per a given Time and Same Day. I need to show multiple values across each row. How can I accomplish this?


text:
Q: Containing single data in multiple containers I've lots of data to acquire and process (near a million) and i don't wanna copy or move it along the whole program.
Let me describe the situation with an example. I have a Vector with 100.000 elements. And i want to keep the track of the time when these elements were inserted into the vector. So, it's a good idea to keep both time and data in a Map. However, i still want to use the Vector.
Is there any way to achieve that second elements of Map shows the Vector but not waste any resource unnecessarily?
The first thing that comes to my mind is containing the adress of datas in Vector. However, pointers use 4 bytes(not sure) and for example, if we wanna contain the address of char, it is 4 times bigger than the data itself.
Any ideas ?

A: I'd say it's not solely a question of memory consumption, but of consistency also. Depends on how you're going to use various views on your original input data. In general I'd advise using std::unique_ptr for the original data and std::weak_ptr for reference in views.
But you're right that might have a certain memory usage overhead because of pointer sizes exceed size of the pointee objects.
For the latter case having a kind of FlyWeight pattern implementation might be more appropriate.

A:
Containing single data in multiple containers

Yes, you can use the Boost Multi-index Containers Library to index the same data in more than one way with no duplication of content.  Unlike homebrew XXX_ptr solutions, the multi-index containers also takes care of keeping everything coherent (removing a data unit from the container automatically elides it from all indexes.)
Lighter weight, more specialized solutions (and possibly more efficient than either muklti-index containers and/or homebrew XXX_ptr solutions) may also be possible depending on your application's requirements, particularities and data insertion/lifecycle patterns:

*

*Do you need the memory layout of your original vector to remain unchanged, or can you accommodate a vector of some derived type?

*Will your vector contents change? can it grow?

*Will the elements therein be (inserted & kept) in chronological order anyway?

*Do you need to look up a vector element by insertion time in addition to vector position?


text:
Q: Typescript type hinting inside dot notation I have the following interface:
export interface IRenderStruct {
  type: string;
  props: {
    className?: string;
    children?: (string | IRenderStruct) | (string | IRenderStruct)[];
    [propName: string]: any;
  };
}

So resulting objects may be nested inside via elm.props.children. I am now creating some unit tests and in one case, I know that I will have a RenderStruct object as children of another. No string as children, and also no array of RenderStruct objects as children.
But when I want to do this:
expect(result.props.children.type === 'something');
The TS compiler complains that I cannot access type because children may be a string and that doesnt have the property type.
Okay, TS - you are correct! But I definitely know that in this case we will have the nested structure. How do I tell TS that its the case?

A: Create an user-defined type guard to check it:
var render: IRenderStruct;

// function to check if something is an IRenderStruct:
function isIRenderStruct(p: any): p is IRenderStruct {
    return ('props' in p) && ('type' in p);
}

let b: boolean;
if (isIRenderStruct(render.props.children)) {
    b = render.props.children.type === 'something'; // No errors
}

EDIT:
For the specific case of your test, you can do:
let test = false;
if (isIRenderStruct(render.props.children)) {
    test = render.props.children.type === 'something'; // No errors
}

expect(test).toBeTruthy();

this way, you avoid elses. If the guard fails, test will be false and your test will fail. This way you can even get a broader range of errors.


text:
Q: Number formatting using regex with special characters I am learning regex and I want to implement this in react app so when I write something on input field I want to allow user to write only numbers and maximum one space. This string also must starts with + character. My regex tool shows me good result but in app I cannot write anything.
const handlePhone = ({currentTarget}) => {
    let val = currentTarget.value;
    // Regular expression
    const reg = /^\+\d+/g;
    const isNumber = val.match(reg);
    if (isNumber || val === '') {
      setFieldValue('phone', val);
    }
  };

With this expression I wanted to implement this: starts with + and later you can write some digits.

But in app I cannot write anything. Why this tool is so different from this live matching?
With this:
const reg = /^\+\d+( \d+)*$/;

A: This should work:
^\+?\d+( \d+)?$

*

*^ - start anchor

*\+? - optionally start with a plus sign

*\d+ - require at least one digit to follow

*( \d+)? - Optionally allow a space which must be followed by one or more digits

*$ - end anchor

https://regex101.com/r/pxbefb/1

A: I think you need something really simple like /^\+\d* ?\d*$/ which means:

*

*^\+  starts with '+'

*\d*  then zero or more digits

*?  (space?) then zero or one space

*\d*  then zero or more digits

*$  end of string

E.g.

function checkValue(el) {
  let re = /^\+\d* ?\d*$/;
  document.getElementById('err').textContent = re.test(el.value)? 'good':'bad';
}
<input oninput="checkValue(this)">

A: Try out this regex , And also check the regex in this LINK
const reg = /^\+\d+ \d+$/gm;

^+ :- will check that string is starting with +.
  \d+ :- this will allow 1 or more digits
  \s :- This will allow only one space .
  $ :- this will ensure that string ends with digit and this will restrict the second use of space character .

A: My Regex is pretty bloated but it should work.
const regex = \^\+[\d]+(\s)*(\d)+$\g;

*

*^+ just negates the power of +

*[\d]+ is letting you pick 0-9 digits 1 or more times

*(\s)* is a group and it allows for 0 or 1 space

*(\d)+$ can pick digits between 0-9 one or more time. And $ is just the end anchor


text:
Q: How do I cycle through each line of a text file or string, and set it to a variable in Node Js? I have a text file with names, each name is on a different line. I want to set the first line to a variable, then after 3 seconds, take the second line and set it to the same variable and so forth. Something like a for loop will probably try to be used. I am using Node Js, and can use packages and others code etc, just need a way to get this done. Additionally I can set the text files contents to a string, so if there is no way to sort through the text file I can use a string no problem. I just need a way to go through the lines and set each to a variable (const, var, etc).
Test.txt example:
Kevin
Bob
Sally
Darla
John
Kim
Then what I want to do is set line 1: Kevin to a string.
const name = Kevin;
Then 3 seconds later set it to Bob etc etc.
Thanks in advance!
Line Reader NPM Package Link: https://www.npmjs.com/package/line-reader
Current Code to Set Text File Contents to a String:
var lineReader = require('line-reader');

lineReader.eachLine('Test.txt', function(text, last) {
  console.log(text);
//"text" is equal to the contents of the text file Test.txt
});

A: You can try readline internal module (file reading example).
CJS variant:
const fs = require('fs');
const readline = require('readline');

function sleep(time) {
  return new Promise((resolve) => {
    setTimeout(resolve, time);
  });
}

async function processLineByLine() {
  const fileStream = fs.createReadStream('test.txt');

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });

  for await (const line of rl) {
    console.log(line);
    await sleep(3000);
  }
}

processLineByLine();

ESM variant with top-level await:
import fs from 'fs';
import readline from 'readline';

function sleep(time) {
  return new Promise((resolve) => {
    setTimeout(resolve, time);
  });
}

const fileStream = fs.createReadStream('test.txt');

const rl = readline.createInterface({
  input: fileStream,
  crlfDelay: Infinity
});

for await (const line of rl) {
  console.log(line);
  await sleep(3000);
}


text:
Q: Android: Youtube videos of a channel are not playing in Webview I have an tabbed application realized with ABS and Fragments. One of this fragments should contain a webview that shows a certain youtube channel, where the user can look through the channel's videos and watch them, if he likes. Therefore I want to show the videos in the webview.
Everything works fine until I click play to watch a video. Than it only shows the loading circle.
I've tried some approaches I found here, like turning on hardware acceleration or implemeting my own WebChromeClient. Either it changes nothing or the application offers me to select the native browser or Chrome to open the link.
Any idea what I have to do get the videos to play inside the webview? Attached is my current implementation:
private WebView wv;
private FrameLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);

@SuppressWarnings("deprecation")
@SuppressLint("SetJavaScriptEnabled")
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    setHasOptionsMenu(true);
    View v = inflater.inflate(R.layout.didacta_channel_layout, container, false);
    wv = (WebView) v.findViewById(R.id.test_web);
    mContentView = (FrameLayout) v.findViewById(R.id.main_content);
    mCustomViewContainer = (FrameLayout) v.findViewById(R.id.fullscreen_custom_content);
    wv.getSettings().setJavaScriptEnabled(true);
    if (Build.VERSION.SDK_INT < 8) {
        wv.getSettings().setPluginsEnabled(true);
    } else {
        wv.getSettings().setPluginState(PluginState.ON);
    }
    wv.setWebChromeClient(new DDChromeClient());
    wv.loadUrl("http://www.youtube.com/user/bikltv");

    return v;
}

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu, inflater);

    menu.add(0, 1, 0, "Restart")
    .setIcon(R.drawable.ic_menu_refresh)
    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    if(item.getItemId() == android.R.id.home)
    {
        ((DidactaNavigationActivity)getActivity()).finish();
    }
    if(item.getItemId() == 1)
    {
        wv.loadUrl("http://www.youtube.com/user/bikltv");
    }
    return super.onOptionsItemSelected(item);
}
class DDChromeClient extends WebChromeClient
{
    public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
    {
        // if a view already exists then immediately terminate the new one
        if (mCustomView != null)
        {
            callback.onCustomViewHidden();
            return;
        }

        // Add the custom view to its container.
        mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
        mCustomView = view;
        mCustomViewCallback = callback;

        // hide main browser view
        mContentView.setVisibility(View.GONE);

        // Finally show the custom view container.
        mCustomViewContainer.setVisibility(View.VISIBLE);
        mCustomViewContainer.bringToFront();
    }

    public void onHideCustomView()
    {
        if (mCustomView == null)
            return;

        // Hide the custom view.
        mCustomView.setVisibility(View.GONE);
        // Remove the custom view from its container.
        mCustomViewContainer.removeView(mCustomView);
        mCustomView = null;
        mCustomViewContainer.setVisibility(View.GONE);
        mCustomViewCallback.onCustomViewHidden();

        // Show the content view.
        mContentView.setVisibility(View.VISIBLE);
    }
}

A: Dont  use a WebView to play YouTube Videos? It won't be needed if you use the Android YouTube API. More information in Click Here .
With the Android YouTube API,you can Pass VID to the YouTube Android Player that's it. The video will get Played in your Application

A: Finally foun my solution here...
https://stackoverflow.com/a/8490751/687475
Setting the webview client two times after setting the webchrome client did it somehow.
For me the easier solution for showing a complete channel.


text:
Q: Python dictionary access data I'm having a headache by trying to access data in a dictionary. I'm not sure what I call dictionary is really a correct one but at least the following structure doesn't give me error.
From a file configuration.py
...
appList =   {
    "app1": {
        "appCode": "xyz",
        "appName": "name1",
        "appType": "ChromeWebApp",
        "appAddress": '/opt/google/chrome/google-chrome \"--profile-directory=Profile {0}\"'.format(v.profil),
        "appID": " --app-id=abcdefgh123456",
        "appRemoteDebug": ' --remote-debugging-port=9222',
        "functions": {
            "action1",
            "action2",
            "action3"}
},
"app14": {
        "appCode": "xyz",
        "appName": "name1",
        "appType": "python",
        "appAddress": '/bin/python3 /home/folder/app.py',
        "appID": " --app-id=qwertyui48965",
        "appRemoteDebug": ' --remote-debugging-port=9222',
        "functions": {
            "action17",
            "action29",
            "action39"}
}
    }

def checkUser(dico, user):
    if user in dico:
        return True
    return False

def checkArgs(dico, webapp, functions, function):
    if webapp in dico:
        if functions in dico[webapp]:
            if function in dico[webapp][functions]:
                return True
    return False

a script main.py is requiring 3 arguments
parser = argparse.ArgumentParser(...)
group = parser.add_mutually_exclusive_group()
parser.add_argument("-u", type=str, dest='u', help="the user")
parser.add_argument("-a", type=str, dest='a', help="the app")
parser.add_argument("-f", type=str, dest='f', help="the function")
args = parser.parse_args()

arguments are then checked as per the dictionaries located in the first file (config.py)
and data which are matching the arguments are accessed and will feed a third file variables.py
def varDefining():
    v.user = args.u
    v.appCode = args.a
    v.appFunc = args.f
    v.profil = [c.userList][v.user]["profil"]
    v.appID = [c.appList][v.appCode]["appID"]
    v.appPath = [c.appList][v.appCode]["appAddress"]
    v.appRemoteDebug = [c.appList][v.appCode]["appRemoteDebug"]

if args.quiet:
    if c.checkUser(c.userList, args.u) == True:
        if c.checkArgs(c.appList, args.a, "functions", args.f) == True:
            varDefining()

During a couple of thousand of trying and error i used to get the following error message:

TypeError: list indices must be integers or slices, not NoneType

I can get it for example with this: print([c.appList][args.a])
Which most likely means the way i'm accesing the data is not correct or maybe the dictionaries themselves are not properly formated...
I'm actually trying to properly code my Python scripts that's why there are three files: main, config and variables which is maybe a wrong way, I haven't see this in a tutorial that's come from my own imagination. So my first need is obviously getting rid of the list indices error but any comments on my style of coding and recommendations or even a link to doc where it's talking about the subject are welcome.
Thanks

A: You create a list and index into it by v.user and ["profile"] - you can only index into lists with integers or slices:

def varDefining():
    v.user = args.u
    v.appCode = args.a
    v.appFunc = args.f
    v.profil = [c.userList][v.user]["profil"]   # creates & indexes in list
    # etc

This puts c.userList into a list and immediately tries to index into it by the value of v.user ( == args.u) - which (in your case) is None. Even if not, it would most likely be a string due to

parser.add_argument("-u", type=str, dest='u', help="the user")

The error has nothing to do with your dictionary.
You essentially do something like:
a = [1,2,3,4]["2"]    # can not work, index not an integer or slice

which produces your exact error message:

SyntaxWarning: list indices must be integers or slices, not str; perhaps you missed a comma?
a = [1,2,3,4]["2"]


text:
Q: A recursive function to discuss in Ocaml I have defined a type and a function:
type element = ...

let merge (x0: element) (x1: element): element * bool = ...

The second part of the return of merge represents if x0 and x1 are merge-able. If so, the first part of the return is the result of merging, otherwise the first part could be ignored.
Then I would like to realize a function restructure: element list -> element list which keeps merging as long as any 2 elements of the list are merge-able (we replace the 2 elements by the result of their merging of couse) the order of merging is not important.
I guess it must be a recursive function, and a little bit complicated for me at this stage, could anyone help?
Thank you very much

A: Ok, I could post a solution but that's neither fun nor very instructive for you :). Instead let me try to give a few hints and if you're still stucked I'll try to help more.

*

*Indeed, as Nathan suggested, it sounds like your merge function should return option(element), which is a classical way to return optional results of functions.

*To write restructure I suggest you start with a function merge_into(res : element, elts : element list) which will try to merge elts into res. That should, hopefully, be easier than restructure.

*How do you implement restructure using merge_into?

Don't hesitate to let me know if you still have problems... happy coding! :)


text:
Q: How to find all Shared Step references for a given ITestCase object in TFS Given that I have a ITestCase object obtained like so
ITestCase tc = project.TestCases.Find(2034);

Where project is an object of type ITestManagementTeamProject obtained by
TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(tfsLocation));
ITestManagementService testService = tfs.GetService<ITestManagementService>();
return testService.GetTeamProject(projectName);

How do I get all the shared step references(don't even know if there was one in the first place) for that particular test case, considering that I don't have any prior state knowledge about that test case.
Please help.

A: There is a ISharedStepReference Interface to call a shared step from a test case. You just need to use FindSharedStep method return the shared step definition from the server. A sample code for your reference:
public ISharedStep tstSharedStep { get; private set; }

public ISharedStepReference tstSharedStepRef { get; private set; }

    foreach (ITestAction tstAction in tstCase.Actions)
            {
                tstSharedStep = null;
                tstSharedStepRef = tstAction as ISharedStepReference;
                    if (tstSharedStepRef != null)
                    {
                        tstSharedStep = tstSharedStepRef.FindSharedStep();
                        foreach (ITestAction tstSharedAction in tstSharedStep.Actions)
                        {
                            ITestStep tstSharedTestStep = tstSharedAction as ITestStep;
                            resultData.Step = Regex.Replace(tstSharedTestStep.Title, @"<[^>]+>| ", "").Trim();
                            resultData.ExpectedResult = Regex.Replace(tstSharedTestStep.ExpectedResult, @"<[^>]+>| ", "").Trim();

                        }
                    }
                    else {
                     // regular step action
                    }

}


text:
Q: Cannot set variable by listener I'm beginning with GUI and listeners. I want to choose and set file from pc into the "File zvolenysubor" in class Hlavna by another class implementing ActionListener.
I can choose file in the listener's actionPerformed method and set it into "File subor" but I fail in saving it into the "File zvolenysubor" in my main (and all of my ideas how to do it failed too).
What should I change/add there please?
Here are my classes:
public class Hlavna {
    public static void main(String[] args) {
        File zvolenysubor = null;
        JFrame frame = new JFrame("ABCDE");
        JButton vybersuboru = new JButton("vyber");
        vybersuboru.setBounds(220, 15, 200, 20);

        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(640, 480);
        frame.add(vybersuboru);
        frame.setLayout(null);

        VyberListener list1 = new VyberListener(zvolenysubor);
        vybersuboru.addActionListener(list1);
        vybersuboru.setText("vyber subor");
    }
}

public class VyberListener implements ActionListener {
    private File subor;

    public VyberListener(File subor){
        this.subor = subor;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();
        System.out.println("lol");
        FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");
        chooser.setFileFilter(filter);
        chooser.showOpenDialog(null);
        subor = chooser.getSelectedFile();
        System.out.println(subor.getAbsolutePath());
    }
}

A: Not really sure what you're asking here.  Java passes method arguments by value as opposed to reference, so the File parameter you're supplying to the constructor of VyberListener is only updated in the VyberListener class by the actionPerformed method, not the reference in your main method.  What is it you're trying to accomplish here?
If you're trying to update "File zvolenysubor" in your main method, it may be worthwhile making your "File subor" in your VyberListener class public, so that it can be accessed by the main method.
Update
To minimise the amount of chatter in the comments below, I'll try and summarise.  Although Java supports pass by reference, it's actually only passing pointers by reference.  Thus in your example, you pass a null object reference (subor) to your ActionListener, which is then overwritten in the actionPerformed method:
subor = chooser.getSelectedFile();

Thus your File variable "zvolenysubor" is never updated.  In order to update fields in your Hlavna class, I recommend using the following "Container" pattern:
public class Hlavna {
    public static void main(String[] args) {
        // New "FileReference" container instance
        FileReference zvolenysubor = new FileReference();
        JFrame frame = new JFrame("ABCDE");
        JButton vybersuboru = new JButton("vyber");
        vybersuboru.setBounds(220, 15, 200, 20);

        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(640, 480);
        frame.add(vybersuboru);
        frame.setLayout(null);

        VyberListener list1 = new VyberListener(zvolenysubor);
        vybersuboru.addActionListener(list1);

        // Retrieves the updated File instance
        File updatedFile = zvolenysubor.getFile();
    }
}

public class VyberListener implements ActionListener {
    private FileReference subor;

    public VyberListener(FileReference subor){
        this.subor = subor;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");
        chooser.setFileFilter(filter);
        chooser.showOpenDialog(null);
        subor.setFile(chooser.getSelectedFile());
    }
}

// FileReference container class allows the file reference to be updated by the ActionListener
// without re-initialising the object reference
public class FileReference {
    private File _file;

    public void setFile(File file) {
        _file = file;
    }

    public File getFile() {
        return _file;
    }
}


text:
Q: Remove Toast calls from Android using ProGuard I want to remove the calls of Toast in my AndroidProject. Th ecalls to Log.d I've removed using the following ProGuard rule in my proguard-rules.pro file in AndroidStudio.
-assumenosideeffects class android.util.Log {
    public static *** d(...);
    public static *** w(...);
    public static *** v(...);
    public static *** i(...);
}

Now I want to add a rule to the same file to remove th calls to Toast in release mode. How does this rule looks like? Can anyone help me?

A: -assumenosideeffects class android.widget.Toast {
    public static *** makeText(...);
    public *** show();
}


text:
Q: Node serve command returns empty response I'm building and hosting a react app and the script to run it is as follows:
npm run build;
npm install -g serve
serve -s build

But when I run, it says it's running on localhost:5000, but when I go to it it returns an empty response.
I'm running this from inside a docker container that inherits from node image.
docker-compose.yml:
version: '3'

services:
    frontend:
        build: ./frontend
        command: ["./docker_up.sh"]
        restart: always
        volumes:
           - ./frontend:/app/frontend
           - node-modules:/app/frontend/node_modules
        ports:
          - "3000:3000"
          - "5000:5000"
          - "80:80"
          - "443:443"
        environment:
          - MODE=PROD
volumes:
  node-modules:

Dockerfile:
FROM node

WORKDIR /app/frontend
COPY package.json /app/frontend
COPY build/* /usr/share/nginx/html/

RUN npm install

EXPOSE 3000
EXPOSE 5000
EXPOSE 80
EXPOSE 443
CMD ["docker_up.sh"]

docker_up.sh:
#!/bin/bash

if [ $MODE == "PROD" ]; then
    echo "Using production settings.";
    apt-get update;
    apt-get install xsel;
    npm run build;

    npm install -g serve
    serve -s build
else
    echo "Using development settings."
    npm start;
fi;


text:
Q: why is a comma used before "contents" I saw the following snippet in a jquery code, but I don't understand why it uses a comma right before 'contents' instead of a period.
var that = $(this),
contents = that.serialize();

Does anyone have an idea why a comma is being used?
I am missing the words to search properly I think.

A: same as :
var that = $(this);
var contents = that.serialize();

A: You can use it to declare multiple variables, it's just shorthand for:
var that = $(this);
var contents = that.serialize();

Many other languages support the same.


text:
Q: Why do we assume that $A \subset (0,1)$ when proving that $N \subset A \subset \mathbb{R}$ is not measurable? If $A \subseteq \mathbb{R}$ is a Lebesgue measurable set and $m(A) > 0$, then there exists $N \subset A$ that is non-measurable.
In some proof, they start by assuming that $A \subset (0,1)$ and it seems that they imply that this is sufficient. How to reason out mathematically and intuitively that this is indeed true?

A: Measurability is translation- and scaling-invariant. That is, given $a \in \mathbb{R}$ and $b \in \mathbb{R}^n$ and $E \subseteq \mathbb{R}^n$, if we define
$$\begin{align*}
aE &:= \{ x \in \mathbb{R}^n \mid x = az \text{ for a } z \in E \} \\
E+b &:= \{ x \in \mathbb{R}^n \mid x = b+z \text{ for a } z \in E \}
\end{align*}$$
then if $E$ is measurable, so are $aE,E+b$ with $\mu(E) = \mu(E+b)$ and $\mu(aE) = a \cdot \mu(E)$. This is, in principle, easy to show: take your coverings by boxes from the definition of (outer) measure, and apply an analogous transformation to them.
So, suppose $V$ is non-measurable. Then $aV$ and $V+b$ necessarily are also non-measurable, for any $a,b$ with $a \ne 0$. (Otherwise, the sets $\frac 1 a (aV)$ and $(V+b)-b$ will be non-measurable scalings/translations of measurable sets.)
So, it is enough to start a non-measurable $V$ in $(0,1)$, and shift/scale $V$ or copies thereof to wherever in $\mathbb{R}^1$ that they're needed and so that they're within $A$.
One can then extend this in the obvious manner for $\mathbb{R}^n$ in general, to achieve even more generality.


text:
Q: Checking entry in the log file using RegEx in unit testing I have log4net log file that logs entries for certain errors. I have to check after i.e. 30 seconds the first error it logged in the log file. I believe Reg Ex is what can do it.
So far I have:
string dataToLog = "certain logged error message";
var matches = Regex.Matches(File.ReadAllText(logfile), dataToLog);
Assert.AreEqual(3, matches.Count);

Above code works fine for number of errors in whole file. But I need to
add to it code which can check and return Boolean  i.e after 20 seconds first error it logged or not. Any idea how to accomplish that?

A: You can add the following code before reading the log file :
DateTime dt30 = DateTime.Now.AddSeconds(30);
            while(DateTime.Now!=dt30)
            {
                continue;
            }

A: You can just freeze current thread for period given:
Start();
Thread.Sleep("30000"); // 30 sec
Read();

or support a callback or event.


text:
Q: jQuery - Coda-like content sliding I need to achieve an effect where when a user triggers a hover on an a tag, current content on the screen slides out, and the new content slides in (depending on what was hovered on). Here is my HTML:

Secure Mobile Computing

IT
Consulting

Software
Engineering

Microsoft
Services

Cyber
Security

Infrastructure & System
Adminstration

So, when a user triggers a#box-2 hover, the divs below ease in/out with new content. Example container markup:

text

text

text

text

text

text

A: I remember seeing this tutorial - it's aimed at designers, so you should fly through it :)
http://jqueryfordesigners.com/coda-slider-effect/
It should be easy enough to change the click events to mouseover.


text:
Q: Adding File and Directory to Array I have this method that searches all files and folders in "C:\Sharing".
string[] fileArray = Directory.GetFiles(@"C:\Sharing", "*.*", SearchOption.AllDirectories);

And foreach shows me full path of each file. Great. However, since these are in a directory called "Sharing", I want to check and add files that are like
C:\Sharing\Jerry2022\wedding.jpg (array: 'wedding.jpg', 'Jerry2022')
C:\Sharing\snapshot.jpg (array: 'snapshot.jpg')
C:\Sharing\Newsletter\cover-june.webp (array: 'cover-june.webp', 'Newsletter')
So as you can see, I want to add file and subdirectory name to a string array or List, doesnt matter. Excluding "Sharing".
How can I split the results? I know I can use Substring and LastIndexOf("\") + 1 and separate the ending '' but I'm not sure how to match up the filename with the subdir name too.
Any help is appreciated

A: You could split the results using Split
But of course you can also work with FileInfo instead

A: You can use DirectoryInfo to get the information you want:
C#:
var directoryInfo = new DirectoryInfo(@"C:\Sharing");
if (directoryInfo.Exists)
{
    foreach (var fileInfo in directoryInfo.GetFiles("*.*", SearchOption.AllDirectories))
    {
        var fileName = fileInfo.Name;
        Console.WriteLine(fileName);
        var directoryName = fileInfo.DirectoryName;
        // you can use split to get the directory name array
        Console.WriteLine(directoryName);
    }
}

I found an other way, use Uri for this scenario:
C#:
string[] fileArray = Directory.GetFiles(@"C:\Sharing", "*.*", SearchOption.AllDirectories);
foreach (var s in fileArray)
{
    var uri = new Uri(s);
    var uriSegments = uri.Segments.ToArray();
}

You will see each part of the full path, but you may need to use .Trim('/') for each part. Then you can use string.Equals to get directories which you want.


text:
Q: c++ Error when passing class object into class function from main? I am using a switch statement based off user's input to decide which function to call.
I then want to pass a class object to a class function in which the code will be that fills in the details of that class object.
Here are segments of my code:
//main.cpp
void myswitch(int input)
{
    switch (input)
    {
        case 1:
        {
            ElectricityBill eBill;
            ElectricityBill::eBillData(eBill);
            break;
        }
//----------------------------------------------
//bill.h
class ElectricityBill: public Bill
{
    public:
        void eBillData(ElectricityBill eBill);
};
//----------------------------------------------
//bill.cpp
void ElectricityBill::eBillData(ElectricityBill eBill)
{
    //get data
}

The error I am getting is:
error: cannot call member function 'void ElectricityBill::eBillData(ElectricityBill)' without object
Help is appreciated, thanks in advance.

A: You are invoking a member function, so the object on which the function is going to be invoked will be passed implicitly to the eBillData() function if you just do:
ElectricityBill eBill;
eBill.eBillData();

Which is perhaps what you actually meant to do. In that case, eBillData should take no explicit argument (a pointer to eBill will be passed implicitly), and it will access all the necessary information about the object it is invoked on through the implicit this pointer:
#include <string>

class ElectricityBill: public Bill
{
    public:
        void eBillData();
    private:
        std::string something;
};

Now the definition of eBillData() should of course reflect the declaration above. Notice, that in a member function you can access data members of the object the function is being invoked on through the implicit this pointer, or (more commonly) but just using their name without the this-> indirection. For instance:
#include <iostream>

void ElectricityBill::eBillData()
{
     // The following two statements are equivalent...
     std::cout << something;
     std::cout << this->something;
}


text:
Q: How do I get access to Google Cloud Storage services with a Firebase user? Is there any way to get a Google Cloud token with a Firebase user token?
Specifically, I want to address REST API endpoints at https://storage.googleapis.com/storage/v1/b/<bucket>/o, but Firebase Auth tokens are not accepted here.
In detail, I send the Firebase Token in the header of the request:
  CustomHeaders['Authorization'] := 'Bearer ' + FirebaseAuthToken

And get a status code 401 with the message Invalid Credentials.
On the other hand, I address successfully the Firebase API at https://firebasestorage.googleapis.com/v0/b/<bucket>/o in the same way with the bearer and the Firebase auth token.
I am looking for a way to list all objects within a directory under Firebase storage for a signed-in Firebase user.


text:
Q: Can I work out the numbers in the groups, based on the results of hazard ratio? I need to extract data from a paper that report a hazard ratio=0.72,
95% CI=0.57, 0.92, p=0.010. Knowing that the one group that did better had 255 individuals and the other 252. How can I find out the concrete numbers based on the hazard ratio?

A: If you only have the hazard ratio with 95% CI (and possibly a p-value) from a Cox-regression, you cannot work out the number of patients. All you can work out - if you know that there was a 1:1 randomization - from the confidence interval width is the number of patients with at least one event, because you know that asyptomtically the estimate of the log-hazard rate has a variance of 4 divided the number of events and that on the log-scale the confidence interval is approximately $\log(\hat{\beta}) \pm 1.96\ldots \times \sqrt{\text{Var}(\hat{\beta})}$. This applies as long as this number is large enough for the asymptotics to apply. If other randomization ratios this is less straightforward. If you know that follow-up in the two treatment groups was very comparable and the proportion that experienced an event was very low, then the hazard ratio will be approximately the ratio of of the number with an event in each group so that those can also be approximately back-calculated.


text:
Q: Bigquery column name with multiple where clause below is my requirement.
prod is the prodname
count_group is the count of groupname that has count greater than 100
count_success is the sum of all records that have category=AAA and package ='BBB'.
 count_user is the exact_count_distinct of userid column that have category=AAA and package ='BBB'

sample query below
    SELECT prod,
count_group,
Count_success,
count_user
FROM
(SELECT
  prod,
  EXACT_COUNT_DISTINCT(group) AS count_group,
SUM(IF(categoty = 'AAA' AND package ='BBB', 1, 0)) AS Count_success,
  EXACT_COUNT_DISTINCT(userID) as count_user
 FROM
  [mytable]
WHERE
   Package ='FFF'

  AND (StartTime > ('2016-01-24 00:00:00 UTC')
    AND StartTime < ('2016-03-16 00:00:00 UTC')
    OR (StartTime > ('2016-03-26 00:00:00 UTC')
      AND StartTime < CURRENT_TIMESTAMP()))
      GROUP BY
  1
ORDER BY
  2 DESC IGNORE CASE)
WHERE Count_group >100


text:
Q: Oracle access varray elements in SQL I'm playing around with array support in Oracle and hit a roadblock regarding array access within a SQL query. I'm using the following schema:
create type smallintarray as varray(10) of number(3,0);
create table tbl (
   id number(19,0) not null,
   the_array smallintarray,
   primary key (id)
);

What I would like to do is get the id and the first element i.e. at index 1 of the array. In PostgreSQL I could write select id, the_array[1] from tbl t but I don't see how I could do that with Oracle. I read that array access by index is only possible in PL/SQL, which would be fine if I could return a "decorated cursor" to achieve the same result through JDBC, but I don't know if that's possible.
DECLARE
 c1   SYS_REFCURSOR;
 varr smallintarray2;
BEGIN
  OPEN c1 FOR SELECT t.id, t.THE_ARRAY from tbl t;
  -- SELECT t.THE_ARRAY INTO varr FROM table_with_enum_arrays2 t;
  -- return a "decorated cursor" with varr(1) at select item position 1
  dbms_sql.return_result(c1);
END;

A: You can do this in plain SQL; it's not pretty, but it does work. You would prefer that Oracle had syntax to hide this from the programmer (and perhaps it does, at least in the most recent versions; I am still stuck at 12.2).
select t.id, q.array_element
from   tbl t cross apply
       ( select column_value as array_element,
                rownum       as ord
         from   table(the_array)
       ) q
where  ord = 1
;

EDIT If order of generating the elements through the table operator is a concern, you could do something like this (in Oracle 12.1 and higher; otherwise the function can't be part of the query itself, but it can be defined on its own):
with
  function select_element(arr smallintarray, i integer)
    return number
    as
    begin
      return arr(i);
    end;
select id, select_element(the_array, 1) as the_array_1
from   tbl
/

A: First of all, please don't do that on production. Use tables instead of storing arrays within a table.
Answer to your question is to use column as a table source
SELECT t.id, ta.*
  from tbl t,
       table(t.THE_ARRAY) ta
 order by column_value
--  offset 1 row -- in case if sometime you'll need to skip a row
fetch first 1 row only;

UPD: as for ordering the array I can only say playing with 2asc/desc" parameters provided me with results I've expected - it has been ordered ascending or descending.
UPD2: found a cool link to description of performance issues might happen


text:
Q: Added Markers on Map from an Array but only one marker is displayed I'm trying to add multiple markers to the map, the coordinates of the marker are in an array List named locationList but as I run the project, it only displays the last index. I tried to solve this with the some related questions but it does not work. Here is the code.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
EditText et;
private ArrayList<Location> locationList ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent=getIntent();
    locationList= (ArrayList<Location>) intent.getSerializableExtra("location");

    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);

    mapFragment.getMapAsync(this);
    et = (EditText) findViewById(R.id.et);
    if (googleServiceAvailable()) {
        Toast.makeText(this, "Perfect", Toast.LENGTH_LONG).show();
    }
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

  /*  MarkerOptions opts = new MarkerOptions();
    opts.position(new LatLng(14.559691260979879,121.02173693084717));
    mMap.addMarker(opts);

    MarkerOptions asd = new MarkerOptions();
    asd.position(new LatLng(14.556659026561825,121.01744539642334));
    mMap.addMarker(asd);*/

    //loop for adding markers. I tried printing the indexes and got the total size

    for(int i=1; i<locationList.size();i++)
    {
      LatLng latlng = new LatLng(locationList.get(i).getLatitude(),locationList.get(i).getLongitude());
      mMap.addMarker(new MarkerOptions().position(latlng));
    }

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setMyLocationButtonEnabled(true);

}

private void goToLocationZoom(double lat,double lng,float zoom){
    LatLng ll= new LatLng(lat,lng);
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
    mMap.moveCamera(update);

}

//Using geoLocate

public void geoLocate(View view) throws IOException {

    InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    mgr.hideSoftInputFromWindow(et.getWindowToken(),0);

    String location = et.getText().toString();

    Geocoder gc = new Geocoder(this);
    List<Address> list = gc.getFromLocationName(location,1);
    Address address = list.get(0);
    String locality = address.getLocality();

    Toast.makeText(this,locality,Toast.LENGTH_LONG).show();
    double lat = address.getLatitude();
    double lng = address.getLongitude();
    goToLocationZoom(lat,lng,17);

}

A: If your list is 2 items long, your for loop is only running once and it's picking up the second item on it's first run through.
I think you've mixed up the indexes between 0 and 1. Java Lists are 0-based.
Initialize i to 0 and you should be good.
for(int i=0; i<locationList.size();i++)
{
  Location l = locationList.get(i);
  LatLng latlng = new LatLng(l.getLatitude(),l.getLongitude());
  mMap.addMarker(new MarkerOptions().position(latlng));
}


text:
Q: Select from two tables, convert rows from one table into colums I'm trying to export data as a CSV and need to convert multiple columns from a second table into rows.  To boot, I do not have a fixed number of rows in the second table but need to use a fixed number of fields in my export.  Here's a sample of my data (I hope it clears up my question).  Data joins on StudentID.  Using MS SQL Server 2014.
User Table
StudentID | Last Name | First Name | Middle Name/Initial | Is Active | Grade | School Name
___________________________________________________________________________________________
1         | Pinciati  | Donna      | J                   | Y         | 10    | High
2         | Hyde      | Steven     | K                   | Y         | 11    | Middle
3         | Foreman   | Eric       | L                   | Y         | 10    | High
4         | Kelso     | Michael    | G                   | Y         | 11    | High

Alert Table
ID | StudentID | Alert Type       | Alert Comments
___________________________________________________
1  | 2         | Asthma           | NULL
2  | 2         | Allergy          | Bee Sting
3  | 3         | Allergy          | Peanut
4  | 4         | Medial Equipment | Crutches
5  | 4         | Allergy          | Bee Sting

My Result Set Needs to look like this:
StudentID | Last Name | First Name | Middle Name/Initial | Is Active | Grade | School Name | Alert Type 1     | Alert Comments 1 | Alert Type 2 | Alert Comments 2 | Alert Type 3 | Alert Comments 3
1         | Pinciati  | Donna      | J                   | Y         | 10    | High        | NULL             | NULL             | NULL         | NULL             | NULL         | NULL
2         | Hyde      | Steven     | K                   | Y         | 11    | Middle      | Asthma           | NULL             | Allergy      | Bee Sting        | NULL         | NULL
3         | Foreman   | Eric       | L                   | Y         | 10    | High        | Allergy          | Peanut           | NULL         | NULL             | NULL         | NULL
4         | Kelso     | Michael    | G                   | Y         | 11    | High        | Medial Equipment | Crutches         | Allergy      | Bee Sting        | NULL         | NULL

I know I have more alerts than there are in my data, though there are a fixed number of fields in the template that I cannot change so I have to fill all alert fields even if they are NULL.
Help me Obi-Wan Kenobi; You're my only hope!

A: Using a subquery or common table expression with row_number(), you can left join on the StudentId and aggregate based on the row number (rn).
select
    s.StudentID
  , s.LastName
  , s.FirstName
  , s.MiddleName
  , s.IsActive
  , s.Grade
  , s.SchoolName
  , AlertType_1     = max(case when rn = 1 then al.AlertType else null end)
  , AlertComments_1 = max(case when rn = 1 then al.AlertComments else null end)
  , AlertType_2     = max(case when rn = 2 then al.AlertType else null end)
  , AlertComments_2 = max(case when rn = 2 then al.AlertComments else null end)
  , AlertType_3     = max(case when rn = 3 then al.AlertType else null end)
  , AlertComments_3 = max(case when rn = 3 then al.AlertComments else null end)
  from dbo.student as s
    left join (
      select StudentId, AlertType, AlertComments
        , rn = row_number() over (
            partition by StudentId
            order by AlertType, AlertComments
          )
       from dbo.Alert
    ) as al on s.StudentId = al.StudentId
  group by
    s.StudentID
  , s.LastName
  , s.FirstName
  , s.MiddleName
  , s.IsActive
  , s.Grade
  , s.SchoolName

rextester: http://rextester.com/YMDQI47779
test setup:
create table Student  (
    StudentID    int
  , LastName   nvarchar(32)
  , FirstName  nvarchar(32)
  , MiddleName nvarchar(32)
  , IsActive   char(1)
  , Grade      int
  , SchoolName nvarchar(32)
  );
insert into dbo.Student values
 (1,'Pinciati','Donna','J','Y',10,'High')
,(2,'Hyde','Steven','K','Y',11,'Middle')
,(3,'Foreman','Eric','L','Y',10,'High')
,(4,'Kelso','Michael','G','Y',11,'High');

create table dbo.Alert (
    ID            int
  , StudentID     int
  , AlertType     nvarchar(64)
  , AlertComments nvarchar(64)
);
insert into dbo.Alert values
 (1,2,'Asthma','NULL')
,(2,2,'Allergy','Bee Sting')
,(3,3,'Allergy','Peanut')
,(4,4,'Medial Equipment','Crutches')
,(5,4,'Allergy','Bee Sting');

query:
;with al as (
  select StudentId, AlertType, AlertComments
    , rn = row_number() over (
      partition by StudentId
      order by AlertType, AlertComments
      )
from dbo.Alert
)
select
    s.StudentID
  , s.LastName
  , s.FirstName
  , s.MiddleName
  , s.IsActive
  , s.Grade
  , s.SchoolName
  , AlertType_1     = max(case when rn = 1 then al.AlertType else null end)
  , AlertComments_1 = max(case when rn = 1 then al.AlertComments else null end)
  , AlertType_2     = max(case when rn = 2 then al.AlertType else null end)
  , AlertComments_2 = max(case when rn = 2 then al.AlertComments else null end)
  , AlertType_3     = max(case when rn = 3 then al.AlertType else null end)
  , AlertComments_3 = max(case when rn = 3 then al.AlertComments else null end)
  from dbo.student as s
    left join al on s.StudentId = al.StudentId
  group by
    s.StudentID
  , s.LastName
  , s.FirstName
  , s.MiddleName
  , s.IsActive
  , s.Grade
  , s.SchoolName

results:
+-----------+----------+-----------+------------+----------+-------+------------+-------------+-----------------+------------------+-----------------+-------------+-----------------+
| StudentID | LastName | FirstName | MiddleName | IsActive | Grade | SchoolName | AlertType_1 | AlertComments_1 |   AlertType_2    | AlertComments_2 | AlertType_3 | AlertComments_3 |
+-----------+----------+-----------+------------+----------+-------+------------+-------------+-----------------+------------------+-----------------+-------------+-----------------+
|         1 | Pinciati | Donna     | J          | Y        |    10 | High       | NULL        | NULL            | NULL             | NULL            | NULL        | NULL            |
|         2 | Hyde     | Steven    | K          | Y        |    11 | Middle     | Allergy     | Bee Sting       | Asthma           | NULL            | NULL        | NULL            |
|         3 | Foreman  | Eric      | L          | Y        |    10 | High       | Allergy     | Peanut          | NULL             | NULL            | NULL        | NULL            |
|         4 | Kelso    | Michael   | G          | Y        |    11 | High       | Allergy     | Bee Sting       | Medial Equipment | Crutches        | NULL        | NULL            |
+-----------+----------+-----------+------------+----------+-------+------------+-------------+-----------------+------------------+-----------------+-------------+-----------------+

A: try this :
with alert as (
select f0.*,
row_number() over(partition by f0.studientID order by f0.ID) rang from Alert_TAble f0
)
select f0.*,
       f1.AlertType as AlertType1, f1.AlertComment as AlertComment1,
       f2.AlertType as AlertType2, f2.AlertComment as AlertComment2,
       f3.AlertType as AlertType3, f3.AlertComment as AlertComment3
from User_Table f0
left outer join alert f1 on f0.studientID=f1.studientID and f1.rang=1
left outer join alert f2 on f0.studientID=f2.studientID and f2.rang=2
left outer join alert f3 on f0.studientID=f3.studientID and f3.rang=3


text:
Q: OpenGL: Should i always clip the glColor*f values myself? This may sound stupid... but I've been wondering, does it matter if i send a value greater than 1.0f to the glColor*f functions?
Does older gfx cards/drivers handle these differently? Does OpenGL directly use the color value i give to it, or does it clip it on its own? Should i stop doing if(r > 1.0f) r = 1.0f; ? Is there any danger the greater than 1.0f would result in unexpeceted behaviour?
I cant seem to get greater than 1.0f to do anything different.

A: From the manpage:
"Neither floating-point nor signed integer values are clamped to the range [0,1] before the current color is updated. However, color components are clamped to this range before they are interpolated or written into a color buffer."

A: OpenGL will clamp the values to the [0, 1] range automatically.


text:
Q: Equicontinuity of set of functions. The problem: Let $x(t) \in C[0,1]$. Then, define $x_n(t)=cos^nx(t)$ for all $n\in \mathbb{N}$. When is the set $(x_n)_{n=1}^{\infty}$ is equicontinuous in $C[0,1]$? Find a criterion in terms of the function $x(t)$.
My approach: I know that if the derivatives are uniformly bounded, then the set is equicontinuous. However, $x$ is arbitrary so that I cannot say anything about the derivatives. Unfortunately, I do not know any other idea about approaching this question. Can you help me? Thanks for any help.
Moreover, does something change when we consider $sin$ instead of $cos$?

A: The sequence $x_n\left(t\right)$ is uniformly bounded by $1$. According to the Arzelà–Ascoli theorem, it will be equicontinuous if and only if it is pre-compact (its closure is compact), that is, any subsequence has a convergent sub-subsequence.
Fortunately, we know the pointwise limit of the sequence. Granted, if $x\left(t_0\right) = \pi+2\pi k$ for some $k\in\mathbb Z$ then there is no limit, but this can easily be overcome by splitting the sequence into even and odd indices. I'll ignore this issue for the sake of simplicity.
Anyway, if $x\left(t\right)\equiv \pi k$ for some $k\in\mathbb Z$ then clearly the sequence is equicontinuous. Otherwise, there will necessarily be values of $t$ for which $\left| \cos\left(x\left(t\right)\right)\right| < 1$ and therefore $\lim_{n\to\infty} x_n\left(t\right) = 0$. This precludes the possibility of $x\left(t\right)$ ever being equal to any $\pi k$, for this would imply the discontinuity of the pointwise limit and therefore of uniform convergence.
In short summary, it would appear that $x\left(t\right)$ should either be always $\pi k$ or never $\pi k$. There are more details to add to the argument of course. Can you fill them in?


text:
Q: Create a Kafka Topic from SQL Server Stored Proc? My .NET application is stored procedure intensive and I need to create a Kafka topic from a stored procedure.    I have a key process that is running on stored procedure and at the end of that process, I need to create a Kafka topic to trigger the next process from another .NET service. Do we have any documentation for using Kafka in a stored procedure. We use confluent's Kafka.

A: Functions in .NET applications are not "stored procedures". Sure, you can use AdminClient class from Confluent library to create topics.

If you literally meant a database stored procedure, and your stored procedure can run arbitrary C# code (which isn't safe), you can do the same, but you could also shell out to kafka-topics.sh script..
Alternatively, create your topic elsewhere, and use tools like Debezium to read from the database into Kafka topics, keeping database logic internal to the database. (Have your stored proc write to a new table, if needed)


text:
Q: Displaying images in a Recyclerview I have a recyclerview that I want to display images that I have saved in drawables in jpeg. For loading I was using an Async Task, but this doesn't preload or Cache them. I was told to use one of the tools like fresco or glide to do that, but which one can do the Job better?
The most important thing for me is that the app doesn't crash, but it would also be nice to be able to preload certain images already before the View is displayed and afterwards preload as many as memory allows.

A: You can use Fresco for this. An example for a recycler view that loads images from the network can be found here:
https://github.com/facebook/fresco/blob/master/samples/showcase/src/main/java/com/facebook/fresco/samples/showcase/drawee/DraweeRecyclerViewFragment.java


text:
Q: Random folders appear on all my drives So I have various desktops and all have more or less the same issue. In the root of each drive there are randomly named folders generated.
Names like:
2b174a7b6cd269132e8dd780
52aebd6aec88ceb00badbc
32601669e81d70e5b9c7c8
ae888118d1365c5a165784ed221b20

So the only common thing seems to be that they are all hexadecimal, but even the lenght of the names are different.
There is a minor difference in Win10:

*

*For Win 7/8/8.1 the folders are empty.

*On Win 10 the folders contain a folder called SandBox which is empty.

The majority of the folders can be deleted without any issues, but some of them can't even with administrator rights.
I spent the last two days on google but couldn't solve this. I read that many of the people thinks that this is due to Windows Update. If that was true why my non-system partitions, external hard drives, usb pendrives are also affected?
I have to mention that all of my machines are affected regardless of their OS, location, user, etc. They run different anti-virus/anti-malware tools. None of them shows any sign of any infection.
What the heck is that?

A: Sounds like Visual Studio windows updates. Have you got that installed on your machine?
http://answers.microsoft.com/en-us/windows/forum/windows_vista-performance/random-files-being-created-in-c-unable-to-delete/84d2b5c4-54ea-4c6f-94e3-2649c61becdf?auth=1
I see that on a lot of users PC who has Visual studio installed.