text:
Q: Trying to convert from lowercase to uppercase and viceversa. strange result using .toUpperCase() I'm a real noob and my question may be stupid.
I'm building an app to convert from uppercase to lowercase and vice versa.
I have two editText and 2 buttons.
One editText is the user input and the other is the converted text; one button is to convert to lowercase and the other is to convert to uppercase.
this is my .xml so far:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="myapplication.example.falcoleo.lettercaseconverter.MainActivity"
tools:showIn="@layout/activity_main"
android:orientation="vertical">

<android.support.v7.widget.CardView
    android:id="@+id/card_originalText"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginBottom="8dp"
    android:layout_weight="1"
    app:cardBackgroundColor="@color/grey800"
    card_view:cardCornerRadius="4dp">

    <EditText
        android:id="@+id/originalText"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="8dp"
        android:gravity="top"/>

</android.support.v7.widget.CardView>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="8dp"
    android:orientation="horizontal">

    <Button
        android:id="@+id/buttonSetToUppercase"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="convertToUpperCase" />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="convertToLowerCase" />
</LinearLayout>

<android.support.v7.widget.CardView
    android:id="@+id/card_convertedText"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    app:cardBackgroundColor="@color/grey800"
    card_view:cardCornerRadius="4dp">

        <EditText
            android:text="TEST"
            android:id="@+id/convertedText"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="8dp"
            android:gravity="top"
            android:editable="false"
            android:inputType="none"
            android:textIsSelectable="false"
            android:background="#00000000"
            />

</android.support.v7.widget.CardView>

it's far from perfect but the real problem lies in the .java
package myapplication.example.falcoleo.lettercaseconverter;

import android.content.ClipData;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.content.ClipboardManager;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    Button copyText;

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

        final TextView textView = (TextView) findViewById(R.id.convertedText); //the second editText is called textView
        final TextView original =(TextView) findViewById(R.id.originalText); //the first editTExt is called original

        final String upper = original.toString().toUpperCase(); //Convert to uppercase
        final String lower = original.toString().toLowerCase(); //Convert to lowercase

        Button convertToUpperCase=(Button)findViewById(R.id.buttonSetToUppercase);  // il primo pulsante si chiama convertToUpperCase
        convertToUpperCase.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                textView.setText(upper);//Set Text on button click via this function.
            }
        });

        Button convertToLowerCase = (Button)findViewById(R.id.buttonSetToUppercase);  // il secondo pulsante si chiama convertToLowerCase
        convertToLowerCase.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                textView.setText(lower); //Set Text on button click via this function.

            }
        });

    }
}

When I build the app it doesn't give any error.
If I run it on a device, when I tap the convertToLowerCase button it does nothing; and when i tap convertToUpperCase button it writes android.support.v7.widget.appcompatedittext{28f38fb7 vfed..cl......i. 0,0-0,0 #7f0c006b app:id/originaltext} on the convertedText EditText.
Nothing to see on the log.
What is it doing? i'm not even sure it is an error message.

A: You should do the following
final String upper = original.getText().toString().toUpperCase(); //Convert to uppercase
final String lower = original.getText().toString().toLowerCase(); //Convert to lowercase

A: The one thing that might be causing you problems is the element type;
You are referencing :
TextView original;

But the actual elements are:
EditText

Can you please fix those first then try?
Then make sure once you get the typed text, convert to String and perhaps check for empty strings?
I hope this helps!


text:
Q: How to get an array of object from firestore in appscript I have a set of documents in Firestore in this format. Questions array will 10 questions.

I want to get the data of questions field: one row for one question

I do I code in the appscript to perform this
This is my code so far (for one document only)
function test(){
  const firestore = getFirestore();

  var query =  firestore.getDocument("QuestionCollection/test").fields;
  var data =  {};

  data.subject = query.subject;
  data.questions= query.questions;

  const sheet = SpreadsheetApp.getActiveSheet();

  for(i = 0 ; i < 10 (no. of question); i++){
    const row = [data.questions[i].answer, data.questions[i].difficulty];
    sheet.appendRow(row);
  }
}

Error:
TypeError: Cannot read property 'answer' of undefined

A: Modification points:

*

*When I saw your sample data in the image, it seems that the array length of questions is 2. But at the for loop, the end index of loop is 9. I think that by them, such error occurs.

*When you want to put the value of "Serial", it is required to add the value for putting to Spreadsheet.

*In your script, appendRow is used in a loop. In this case, the process cost becomes high.

When above points are reflected to your script, it becomes as follows.
Modified script:
Your for loop is modified as follows.
From:
for(i = 0 ; i < 10 (no. of question); i++){
  const row = [data.questions[i].answer, data.questions[i].difficulty];
  sheet.appendRow(row);
}

To:
var values = [];
for (var i = 0; i < data.questions.length; i++) {
  const row = [i + 1, data.questions[i].answer, data.questions[i].difficulty];
  values.push(row);
}
sheet.getRange(sheet.getLastRow() + 1, 1, values.length, values[0].length).setValues(values);

*

*For the end index of loop, the array length is used.

Reference:

*

*setValues(values)

A: You shouldn't query the .fields property directly (because your data isn't converted properly). Assuming you're using v28+ of the library, your code should look something like this:
function test(){
  const firestore = getFirestore();

  const query = firestore.getDocument("QuestionCollection/test").obj;  // Don't use .fields here

  const sheet = SpreadsheetApp.getActiveSheet();
  const values = [["Serial", "Answer", "Difficulty"]];  // Init 2D array with Header row

  // Loop through each question in the array and extract necessary values to construct Data rows
  for (const question of query.questions){
    values.push([query.questions.indexOf(question) + 1, question.answer, question.difficulty]);
  }

  // Replace 1, 1 below with coords of "Serial" header cell
  const range = sheet.getRange(1, 1, values.length, values[0].length);
  range.setValues(values);

  // sheet.getRange(subjRow, subjCol).setValue(query.subject);  // Add location for Subject data
}

I saw that you wanted "Serial" to represent "Question number", so I added that column to the header and data rows.
As Tanaike mentioned, there's a huge performance hit for writing to the spreadsheet in a loop, so it's better if you set up a 2D array of values to write all at once using range.setValues(array2D). Ideally, you'll want to minimize the calls to the Spreadsheet API.
Disclaimer: I'm an active contributor to the FirestoreGoogleAppsScript library.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bash syntax error: line 7: unexpected end of file So I have a bash script
!#/bin/bash
while [ true ];do
ls -lah /sth/ | grep sth*
sleep 0.001
done
exit 0

I thoought thai it was ok but when I run it I get

line 7: syntax error: unexpected end of file

But the code has only 6 lines?
What may be a problem? I edited the file in linux, deleted unnecessary spaces but still my scropt doesn't work.

A: The shebang line is wrong.  You are not running it under Bash at all.
#!/bin/bash

Notice the order of the sharp (#) and the bang (!).


text:
Q: WagtailAdminPageForm and URL not saving in admin or passing to page I have a quick script that parses a JSON response from an API and adds it to a WagtailAdminPageForm, like so:
"""Flexible page."""
from django.db import models
import requests
from django import forms
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.core.models import Page
from wagtail.core.fields import RichTextField
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.admin.forms import WagtailAdminPageForm

def get_mp3_choices():
    response = requests.get('https://api.somexamplepage.com')
    response.raise_for_status()
    jsonResponse = response.json()
    jsonResponse['results'][0]['audio']
    mp3_list = []
    return [
        (key['audio'], key['title'])
        for key in jsonResponse['results']
    ]

class FlexPageForm(WagtailAdminPageForm):
    audioUrl = forms.ChoiceField(choices=get_mp3_choices)

    class Meta:
        label = 'Select Audio for Player'

class FlexPage(Page):
    """Flexibile page class."""

    template = "flex/flex_page.html"

    # @todo add streamfields
    # content = StreamField()
    base_form_class = FlexPageForm
    subtitle = models.CharField(max_length=100, null=True, blank=True)
    Flexbody = RichTextField(blank=True)
    bannerImage = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+"
    )
    content_panels = Page.content_panels + [
        FieldPanel("subtitle"),
        FieldPanel('Flexbody', classname="full"),
        ImageChooserPanel('bannerImage'),
    ]

    class Meta:  # noqa
        verbose_name = "Flex Page"
        verbose_name_plural = "Flex Pages"

The code works well and I'm able to see the returned list of MP3's within my admin panel. The problem, the selected MP3 is not being preserved when I save the page and, when I look in the sqlite table, I'm not seeing any record of the audioUrl. The following fields do show.
page_ptr_id subtitle    Flexbody    bannerImage_id

I've tried running migrations, but they aren't showing that I need to make any migrations. When I try to call the field within the Wagtail App:
<audio controls="" style="
  margin-bottom: 25px;
">
    <source
     src="{{ self.audioUrl }}"
     type="audio/mp3">
 </audio>

The page loads but the developer tools list the URL as unknown.


text:
Q: Line direction histogram plugin vector identification? I was wondering if there is a way of identfying which vector ids fall into a bin. Is this possible to find out? If there isnt is there another plugin that allows you to identify what the angle in a similar fashion as the line histogram. I have used this plugin as a visual aid but do require to know which vectors fall into i.e. 0-11.25 degrees for stats purposes
Below if the line direction histogram and the CSV file that accompanies it..... I want to identify which vectors go in which bin for example the first line on the csv file gives you the sum length and the number of trails in that bin. But I want to identify which vector falls in a bin to carry out statistical analysis

A: The line direction histogram plugin does not operate on complete lines, it operates on the line segments (a line can be made up of hundreds or even thousands of segments). So there is no way to associate lines to direction bins.
See the plugin help for more details on the plugin. About functionality:
The QGIS Line Direction Histogram Plugin creates a rose diagram that can be used to investigate the distribution of the directions of line segments of a line or polygon vector dataset


text:
Q: R RandomForest: Proximity for new object I trained a random forest:
model <- randomForest(x, y, proximity=TRUE)

When I want to predict y for new objects, I use
y_pred <- predict(model, xnew)

How can I calculate the proximity between the new objects (xnew) and the training set (x) based on the already existing forest (model)?
The proximity option in the predict function gives only the proxmities among the new objects (xnew). I could run randomForest unsupervised again on a combined data set (x and xnew) to get the proximities, but I think there must be some way to avoid building the forest again and instead using the already existing one.
Thanks!
Kilian

A: I believe what you want is to specify your test observations in the randomForest call itself, something like this:
set.seed(71)
ind <- sample(1:150,140,replace = FALSE)
train <- iris[ind,]
test <- iris[-ind,]

iris.rf1 <- randomForest(x = train[,1:4],
                         y = train[,5],
                         xtest = test[,1:4],
                         ytest = test[,5],
                         importance=TRUE,
                         proximity=TRUE)

dim(iris.rf1$test$prox)
[1]  10 150

So that gives you the proximity from the ten test cases to all 150.
The only other option would be to call predict on your new case rbinded to the original training cases, I think. But that way you don't need to have your test cases up front with the randomForest call.
In that case, you'll want to use keep.forest = TRUE in the randomForest call and of course set proximity = TRUE when you call predict.


text:
Q: Cutting a 1 metre stick, what is the expected length?
I am unable to understand 2 things in this problem:

*

*Why is $f_X (x)$ = 1, should it not be 1/x because every point has the same chance of being cut. Does that mean every point has P=1 of being cut? However, the cdf on [0,1] seems to be 1, which is fine.
edit: Nvm I figured it out, 1/x where x=1m is 1...

*How come the expected value is not 0.5m ? If every point has the same probability of being cut, then it is reasonable to choose the mean, which is 0.5m. However, the answer is 0.75. I am not sure if that is because the question asks for "the length of the longer piece".

A: 1) The density probability function being a constant is the telltale sign that the distribution is uniform over whatever interval is considered. Being constant means that each point has the same probability (density) to be chosen, which is intended. The value of the constant is then determined to make sure (as you wrote) that the intergral overt the whole considered interval is $1$.
2) The expected value for say the first piece is actually $0.5m$. The key is (as you write) that it asks for the longer piece. The longer piece must be at least $0.5m$ long, because if it was shorter, than the other piece would be shorter still, and together they can't be $1m$ long in their sum.

A: The longer piece has a length uniform in $[0.5,1]$ (and the shorter uniform in $[0,0.5]$).
The expectation of the longer length is the middle of the range,
$$\frac{0.5+1}{2}.$$


text:
Q: Returning all rows falling within a time period I have a doubt in writing sql.
I had a farmerfields table with
YEAR,SEASON,Number of Fields.

and season look like this
Kharif---- 15june-15Oct
Rabi---15 oct to 15 Feb
Summer----15Feb to 15 June

now i want to write sql which returns all the rows excluding the current season in the current year. ie we should get the current season based on system date.
I am cracking my brain to get this, but could not.
Please help me.

A: I would suggest that you define a seasons table with three rows as above, e.g.
create table season (
  season_id              int,
  description            varchar(32),
  start_day_of_month     int,
  start_month            int
  end_day_of_month       int,
  end_month              int
)

the year is not included here just the day of month and month indices.
Your farmerfields table should then have a seaon_id column referring to this and most likely have a year column too.
Depending on your SQL vendor different date functions will be available but should should be able to compose a start and end date using the year from farmerfields and the month and day-of-month from season. Given this you can then determine if the current date falls within a given farmerfield entry's start and end dates.

A: Your table structure is wrong and not fit for what you need.
Instead of single field called SEASON, have two fields: SEASON_START and SEASON_END both of type Date then the query is as simple as:
Select * From [farmerfields] Where GetDate() Between SEASON_START And SEASON_END

If the names are part of your current SEASON field, add third field SEASON_NAME as well and the new structure will be:

SEASON_NAME | SEASON_START | SEASON_END
---------------------------------------
Kharif      | 15june       | 15Oct
Rabi        | 15 oct       | 15 Feb
...

Edit: in my above sample code I assumed you have SQL Server database - in case of different database you'll have different function to get current system date.

A: For difference of dates you can use the sql function DATEDIFF
SELECT * FROM table WHERE `date` BETWEEN '2011-10-20' AND '2011-1-1' AND DATEDIFF(`date`, '2011-10-20') % 10 = 0

A: I would suggest that you define a seasons table with three rows as above, e.g.
create table season (
  season_id              int,
  description            varchar(32),
  start_day_of_month     int,
  start_month            int
  end_day_of_month       int,
  end_month              int
)

The year is not included here just the day of month and month indices.
Your farmerfields table should then have a season_id column referring to this and most likely have a year column too.
Depending on your SQL vendor different date functions will be available but should should be able to compose a start and end date using the year from farmerfields and the month and day-of-month from season. Given this you can then determine if the current date falls within a given farmerfield entry's start and end dates.


text:
Q: How can I find the value of the TextBlock in the Listview? Some functions change the value of a TextBlock in the ListView. I want to access TextBlock value at the end of these functions. How can I do it?
ListView code :
<ListView BorderThickness="0" x:Name="OrderList">
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel/>
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="BorderBrush" Value="Transparent"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListViewItem}">
                        <Grid Background="{TemplateBinding Background}">
                            <Border BorderBrush="{StaticResource MenuluxRedBrush}" BorderThickness="0,0,0,1" Height="30">
                                <local:OrderPopUpItem/>
                            </Border>
                            <GridViewRowPresenter Grid.RowSpan="2"
                                                  Margin="{TemplateBinding Padding}"
                                                  HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                                  VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                                  SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Foreground"
                                        Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

OrderPopUpItem.xaml code :
<Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <TextBlock Text="{Binding productName}"
                   VerticalAlignment="Center"
                   Margin="15,0,0,0"
                   FontSize="20"/>

        <Grid Grid.Column="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>

            <Image Source="/Images/PopUp/icon_minus_red.png"
                   MouseLeftButtonUp="azalt"
                   Name="minusIcon"
                   Height="30"/>

            <TextBlock Text="0"
                       Grid.Column="1"
                       Name="amountText"
                       VerticalAlignment="Center"
                       HorizontalAlignment="Center"
                       FontSize="20"/>

            <Image Source="/Images/PopUp/icon_plus_red.png"
                   MouseLeftButtonUp="arttir"
                   Name="plusIcon"
                   Grid.Column="2"
                   Height="30"/>
        </Grid>

A: If i understand your question correctly, You can achieve this behind code with C#. You should add the code below to your source code.
//Get ListViewItem
ListViewItem item = (ListViewItem)OrderList.Items.GetItemAt(SatirIndex);

//Get Content from item (use if you want read items value)
string deger = item.content;
//Set items content (use if you want set items value)
item.content = amountText.Text;


text:
Q: How to use and check the performance improvement by HipHop for PHP? I am impressed by the discussions around HipHop PHP from Facebook, also want to try it once. I found many articles saying how HipHop is improving performance and I found installation steps as well. But no where I found the steps/guide to use this HipHop and check the performance improvement.
I guess many people already used the HipHop, so please let me know the exact steps to use the HipHop and check the performance improvement. If you know there are already some blogs or something to specify the corresponding flow then at least please point me to those resources.
FYI: I have already installed the HipHop in my Ubuntu 12.04 LTS by following the instructions from the wiki page, but don't know to use that. I am using CodeIgniter framework in my project.

A: One approach (for a web application) would be to run ab, a pretty simple benchmarking tool.
It will not take other resources like images or scripts into account, but only response time of the page itself, so you should get a decent idea about what the load times were before and after. To test concurrenct request handling, it has options for parallel requests.
Basic usage is something like
ab -n2000 -c5 http://www.example.com

Where n is the amoutn of requests and c is the concurrency level


text:
Q: Why is the ListView empty? I am trying to make a listView that contains only images without texts but it gives a white screen and I am not getting any error or anything.
Here is my codes:
xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="3">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="2">

    <ListView
       android:id="@+id/setOneListView"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:gravity="center" />

</RelativeLayout>

   .........

</LinearLayout>
</LinearLayout>

Activity:
public class Set1_Activity extends Activity {

ListView list;
int[] images = {
        R.drawable.iv1, R.drawable.iv2, R.drawable.iv3, R.drawable.iv4,
        R.drawable.iv5, R.drawable.iv6, R.drawable.iv11, R.drawable.iv12,
        R.drawable.iv13, R.drawable.iv14, R.drawable.iv15, R.drawable.iv16,
        R.drawable.iv111, R.drawable.iv112, R.drawable.iv113, R.drawable.iv114,
        R.drawable.iv115, R.drawable.iv116, R.drawable.iv7, R.drawable.iv8,
        R.drawable.iv9, R.drawable.iv19, R.drawable.iv49, R.drawable.iv50,
        R.drawable.iv52, R.drawable.iv54
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main2);

    list = (ListView) findViewById(R.id.setOneListView);
    HeartlessAdapter adapter = new HeartlessAdapter(this, images);
    list.setAdapter(adapter);

    list.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {

            switch(position){
               case 0:
                   display.setImageResource(R.drawable.iv1);
                tophone = R.drawable.iv1;
                break;
           .........

class HeartlessAdapter extends ArrayAdapter<String>
{
Context context;
int[] images;

HeartlessAdapter(Context c, int imgs[])
{
    super(c, R.layout.imageview);
    this.context=c;
    this.images=imgs;
}

class MyViewHolder
{
    ImageView myImage;

    MyViewHolder(View v)
    {
        myImage = (ImageView) v.findViewById(R.id.imageView);

    }
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    View row = convertView;
    MyViewHolder holder = null;
    if(row==null)
    {
       LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       row = inflater.inflate(R.layout.imageview, parent, false);
       holder = new MyViewHolder(row);
       row.setTag(holder);
    }
    else
    {
        holder = (MyViewHolder) row.getTag();
    }

    holder.myImage.setImageResource(images[position]);

    return row;
}
}

All works fine, no error and the emulator just show empty white screen nothing inside. What could be missing?
Thanks!

A: Try moving the android:layout_weight="2" up a level to the horizontal LinearLayout.

A: try this...
 runOnUiThread(new Runnable() {
                public void run() {
                    adapter.notifyDataSetChanged()
                }
            });

A: 1) Let HeartlessAdapter extend ArrayAdapter<Integer> instead of ArrayAdapter<String>.
2) on your constructor, call super(c, R.layout.imageview, imgs); It should work like that.
3) If you wanna optimize it a lot, remove the references to Context and the array of images from the adapter. You can get any item you need calling getItem(position) and the Context by calling getContext().
EDIT:
In order for it to work, call this:
super(c, R.layout.imageview, HeartlessAdapter.toIntegerArray(imgs));

and add this method to HeartlessAdapter:
private static Integer[] toIntegerArray(int[] array){
    Integer[] finalArray = new Integer[array.length];
    for (int i=0; i<array.length; i++){
        finalArray[i] = array[i];
    }
    return finalArray;
}


text:
Q: Warning in Jetty 9 Http requests - Under Utilization of N/W in local loopback I am trying to run Jetty 9 on Ubuntu 12.10 (32 bit). The JVM i am using in JDK 1.7.0_40. I have setup a rest service on my server that uses RestLib. The rest service is a POST method that just receives the data and does no processing with it and responds a success.
I want to see what is the maximum load the Jetty9 server will take with the given resources. I have a Intel i5 processor box with 8 GB memory. I have setup a Jmeter to test this rest in the localhost setting. I know this is not advisable but i would like to know this number (just out of curiosity).
When I run the JMeter to test this POST method with 1 MB of payload data in the body, i am getting a through put of around 20 (for 100 users).
I measured the the bandwidth using iperf to begin with
iperf -c 127.0.0.1 -p 8080
------------------------------------------------------------
Client connecting to 127.0.0.1, TCP port 8080

TCP window size:  167 KByte (default)

[  3] local 127.0.0.1 port 44130 connected with 127.0.0.1 port 8080

[ ID] Interval       Transfer     Bandwidth

[  3]  0.0-10.0 sec   196 MBytes   165 Mbits/sec

the number 165 MB seems ridiculously small for me but that's one observation.
I ran the server with StatisticsHandler enabled and was observing the request mean time. Also was observing the system resources using nmon monitoring tool.
The CPU usage was around 20 % (overall), 4GB of free memory and the number of threads in the server (monitored using jconsole) around 200 (i had specified max thread count as 2000 in start.ini file).
Jmeter was configured to bombard repeatedly.
I observed the network usage in local loopback interface in nmon tool and it was around
30 MB. This was inline with the iperf data quoted earlier.
I tried the same experiment with weblogic(using JDK 1.6) and it was using nearly 250 MBps in lo interface. I had explicitly disabled tcp sync cookies in the sysctl config to avoid the limitation due to system thinking the test as DOS attack.
Please help me comprehend this numbers. Am I missing something here in the config. The n/w seems to be a limiting factor here but since it is a loopback interface there is no physical limitation as proved by the Weblogic case.
Please help me understand what am I doing wrong in the Jetty 9 case.
Also I am getting this warning in Jetty9 logs very frequently

WARN:oejh.HttpParser:qtp14540840-309: Parsing Exception: java.lang.IllegalStateException: too much data after closed for HttpChannelOverHttp@1dee6d3{r=1,a=IDLE,uri=-}

A: This question is effectively being answered on this mailing list thread:
http://dev.eclipse.org/mhonarc/lists/jetty-users/msg03906.html


text:
Q: two phase commit in nodeJS application I am currently working on a nodeJS application that will soon need to write simultaneously on two PostgreSQL databases. This is meant for redudancy purposes: the writing operations must be made in the same time on both databases, or rollbacked if there is anything wrong with one of the databases.
In order to achieve that, I need to rely on a transaction manager that would (or at least could) use two-phase commit in the persisting process.
Currently,  the application uses an out-of-the-box solution to perform actions on the current database (i.e. the pg-promise package, which for now stands as the application's transaction manager).
To put it all in a nutshell, I am going to need every persisting action in the Node application to be performed on two databases simultaneously.
For now, I merely use the pg-promise to persist data on one database like on this example:
db.one(mySQLRequest)

but I only found to create a db object for one specific database at a time.
I have found no example for such a vast problematic on a NodeJS RESTful application, but I suspect it might be a rather common issue. And I would be glad if it was not necessary that I recode the whole transaction manager on my own...
If you have any lead about how I could allow my NodeJS application to perform two-phase commits, it would be greatly appreciated. :)

A:
nodeJS application that will soon need to write simultaneously on several PostgreSQL databases

Within pg-promise each Database object contains a separate connection pool, with unique connection.
So when communicating with several databases you simply create one Database object for each, and in this scenario it is also a good idea to make use of the Database Context parameter, which can be anything.
Example
const pgp = require('pg-promise')(/* initialization options */);

const db1 = pgp(connection1, dbContext1);
const db2 = pgp(connection2, dbContext2);
const db3 = pgp(connection3, dbContext3);

I have to implement a two-phase commit in the persisting process

This would have to be a custom implementation that depends on the business logic of your application. The library cannot help you there, as there is no such thing as inter-database transaction, you will have to implement it on your own.

I even thought of rewriting some parts of the pg-promise module myself

I don't see what it can give you. The parts that can be automated for transactions are already all there, and the parts for the inter-database integrity are all on your side.

A: I've searched and haven't found any node.js modules for distributed transaction management.
If you're working on a roll-your-own, take a look at XA transactions, a distributed database transaction standard.  Java has robust and mature support via JTA (Java Transaction API) which helps a node developer only as inspiration and reference.
postgresql has two phase commit support so the building blocks are there for either XA support or a hand-rolled postgresql-specific implementation.
I'm working on an XA-ish transaction manager myself, but the going will be slow with work and kids; side projects are last in line for time. Look for ivolucien/coaction in a year or two...


text:
Q: Dropdown button not displaying links Was following a tutorial on how to create a hoverable drop-down button with HTML/CSS. The button displays on the page when I load but does not display the links when I hover over it. I thought it may have been the browser but it does the same thing in Firefox and google chrome. I changed the code around when I tried it initially, then typed the code verbatim as the tutorial but had the same issue. Tried to post screenshot of page but site would not allow me yet.

.container {
  text-align: center;
}

h1 {
  color: brown;
}

.crumbs-btn {
  background-color: #04AA6D;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
}

.crumbs {
  position: relative;
  display: inline-block;
}

.dropdown-crumbs {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-crumbs a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown-crumbs a: hover {
  background-color: #ddd;
}

.crumbs: hover .dropdown-crumbs {
  display: block;
}

.crumbs: hover .crumbs-btn {
  background-color: #3e8e41;
}
<!DOCTYPE html>

  <title>Memoir of the mind</title>

Fish for Waves

The website dedicated to providing daily gems of wisdom
     to help nourish your mind and spirit.

Daily Crumbs

February 28, 2022

"Wisdom stems from the tree of experience and the branch of patience"

-Buddy Nawlidge

    <button class="crumbs-btn">Previous Crumbs</button>

      Mar 9th, 2022
      Mar 10th, 2022
      Mar 11th, 2022

A: Divide your CSS from HTML. Create a CSS file, I named mine app.css
This is the snippet:

.container {
  text-align: center;
}

h1 {
  color: brown;
}

.crumbs-btn {
  background-color: #04aa6d;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
}

.crumbs {
  position: relative;
  display: inline-block;
}

.dropdown-crumbs {
  visibility: hidden;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-crumbs a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown-crumbsa:hover {
  background-color: #ddd;
}

.crumbs:hover .dropdown-crumbs {
  visibility: visible;
}

.crumbs:hover .crumbs-btn {
  background-color: #3e8e41;
}
<!DOCTYPE html>

  <title>Memoir of the mind</title>

  <link rel="stylesheet" href="/app.css">

Fish for Waves

The website dedicated to providing daily gems of wisdom
     to help nourish your mind and spirit.

Daily Crumbs

February 28, 2022

"Wisdom stems from the tree of experience and the branch of patience"

-Buddy Nawlidge

    <button class="crumbs-btn">Previous Crumbs</button>

      Mar 9th, 2022
      Mar 10th, 2022
      Mar 11th, 2022

I used visibility hidden and visible but it also works with your way too. There are many solutions to do the same thing. There is nothing wrong with your code but I think you should divide your HTML from the CSS (external) so that the hover works better.


text:
Q: Efficient loop multithreading I have a function which takes an integer and then runs for some time (5-500 seconds depending on function input).
void foo(int parameter) { /*do some staff*/ }
Results of this calculation are stored in text file created by this function.

resultsFor{parameter}.txt

Then i have a for loop which evaluates this function for given set of integers.
for (int i = 0; i < 100; i++)
   foo(i);

Now I want to optimize computing time for this loop with threads. Preferably using std library.
#include <thread>

At first I want to create certain number of threads which would be equal to number of cores of current machine.
numberOfThreads = std::thread::hardware_concurrency();

And then I want to assign those threads to calculate my function for first numberOfThreads integers of the loop and if one thread finishes its work then next step of the loop is assigned to it. How do I achieve that?
The thing is a cannot redistribute the work by dividing the for loop into numberOfThreads parts, because it is impossible to determine how long the calculation would take for given integer. And redistributing to threads by even parts of the loop could result in one thread finished and another would not even have one tenth of its work done.

A: The following is one example of how you can do this with an atomic, an affordance that works well if you have a static set of data that needs to be processed. For this sample, I'm building 100 vectors of 100,000 elements each, all of them randomly shuffled, and sending them to the threads for sorting.
Note: I did have to introduce a mutex into this to get the output to stdout to properly not interlace. In reality, it isn't needed if you're not doing interactive output like this. Pay special attention to the output thread ids, and you'll see each thread gets multiple work items, all fairly balanced (because the workload was).
I hope it helps you out.
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <thread>
#include <atomic>
#include <random>
#include <mutex>

// our work item
typedef std::vector<std::vector<int>> WorkQueue;

// holds the atomic counter for our vector
std::atomic<std::size_t> cnt = ATOMIC_VAR_INIT(0);
std::mutex mtx;

void thread_proc(WorkQueue& wq)
{
    int count = 0;
    std::size_t n = std::atomic_fetch_add(&cnt, std::size_t(1));
    while (n < wq.size())
    {
        //
        // TODO: do something with the n-th item in the vector
        //
        std::unique_lock<std::mutex> lck(mtx);
        std::cout << "Thread " << std::this_thread::get_id() << ": item " << n << std::endl;
        lck.unlock();

        std::sort(wq[n].begin(), wq[n].end());
        ++count;

        // increment by one and move to next item
        n = std::atomic_fetch_add(&cnt, std::size_t(1));
    }

    std::unique_lock<std::mutex> lck(mtx);
    std::cout << "Thread " << std::this_thread::get_id() << " processed " << count << " items." << std::endl;
    lck.unlock();
}

int main(int argc, char *argv[])
{
    std::random_device rd;
    std::default_random_engine rng(rd());

    // build a sizable work queue.
    WorkQueue wq;

    // make a 100000 element sequence of incrementing numbers
    std::vector<int> item;
    item.reserve(100000);
    std::generate_n(std::back_inserter(item), 100000,
                    [](){ static int i=0; return ++i;});

    // add 100 vectors of 1000000 elements each
    wq.reserve(100);
    for (unsigned i=0; i<100; ++i)
    {
        // make a unique shuffle for this insertion
        std::shuffle(item.begin(), item.end(), rng);

        // append a random length of values (1000..size);
        long len = 1000 + (rng() % (item.size() - 1000));
        std::cout << "Appending vector of " << len << " items. " << std::endl;
        wq.emplace_back(item.begin(), std::next(item.begin(), len));
    }

    // ok. get the number of threads we're going to be using.
    unsigned n_threads = std::thread::hardware_concurrency();
    std::vector<std::thread> threads;
    for (unsigned i=0; i<n_threads;++i)
        threads.push_back(std::thread(thread_proc, std::ref(wq)));

    // now join the threads
    for (auto& thrd : threads)
        thrd.join();

    return EXIT_SUCCESS;
}

Output (system dependent, obviously)
Appending vector of 67742 items.
Appending vector of 87839 items.
Appending vector of 13960 items.
Appending vector of 64161 items.
Appending vector of 56993 items.
Appending vector of 30626 items.
Appending vector of 24970 items.
Appending vector of 96336 items.
Appending vector of 2697 items.
Appending vector of 70087 items.
Appending vector of 35234 items.
Appending vector of 82828 items.
Appending vector of 15808 items.
Appending vector of 38646 items.
Appending vector of 55819 items.
Appending vector of 99380 items.
Appending vector of 33486 items.
Appending vector of 9742 items.
Appending vector of 50267 items.
Appending vector of 4421 items.
Appending vector of 33577 items.
Appending vector of 55888 items.
Appending vector of 61601 items.
Appending vector of 19894 items.
Appending vector of 90217 items.
Appending vector of 80498 items.
Appending vector of 40101 items.
Appending vector of 50601 items.
Appending vector of 71679 items.
Appending vector of 65707 items.
Appending vector of 8671 items.
Appending vector of 67409 items.
Appending vector of 47066 items.
Appending vector of 53989 items.
Appending vector of 88724 items.
Appending vector of 82923 items.
Appending vector of 38571 items.
Appending vector of 58705 items.
Appending vector of 13149 items.
Appending vector of 97816 items.
Appending vector of 59586 items.
Appending vector of 20798 items.
Appending vector of 45906 items.
Appending vector of 96078 items.
Appending vector of 24951 items.
Appending vector of 19954 items.
Appending vector of 52154 items.
Appending vector of 49653 items.
Appending vector of 14830 items.
Appending vector of 45169 items.
Appending vector of 96009 items.
Appending vector of 15941 items.
Appending vector of 37832 items.
Appending vector of 55441 items.
Appending vector of 65057 items.
Appending vector of 69484 items.
Appending vector of 27425 items.
Appending vector of 11579 items.
Appending vector of 43795 items.
Appending vector of 71688 items.
Appending vector of 17214 items.
Appending vector of 69687 items.
Appending vector of 18897 items.
Appending vector of 96105 items.
Appending vector of 62040 items.
Appending vector of 26292 items.
Appending vector of 34464 items.
Appending vector of 49473 items.
Appending vector of 83357 items.
Appending vector of 50406 items.
Appending vector of 48313 items.
Appending vector of 22030 items.
Appending vector of 2352 items.
Appending vector of 82989 items.
Appending vector of 42358 items.
Appending vector of 59134 items.
Appending vector of 46823 items.
Appending vector of 36615 items.
Appending vector of 40752 items.
Appending vector of 49963 items.
Appending vector of 73666 items.
Appending vector of 29816 items.
Appending vector of 4112 items.
Appending vector of 31045 items.
Appending vector of 8810 items.
Appending vector of 43021 items.
Appending vector of 83699 items.
Appending vector of 5551 items.
Appending vector of 85914 items.
Appending vector of 11835 items.
Appending vector of 82329 items.
Appending vector of 13567 items.
Appending vector of 74271 items.
Appending vector of 49083 items.
Appending vector of 42803 items.
Appending vector of 92871 items.
Appending vector of 17562 items.
Appending vector of 28686 items.
Appending vector of 61544 items.
Appending vector of 13375 items.
Thread 0x101bc3000: item 0
Thread 0x101c46000: item 1
Thread 0x101cc9000: item 2
Thread 0x101e81000: item 3
Thread 0x101cc9000: item 4
Thread 0x101bc3000: item 5
Thread 0x101e81000: item 6
Thread 0x101e81000: item 7
Thread 0x101bc3000: item 8
Thread 0x101c46000: item 9
Thread 0x101bc3000: item 10
Thread 0x101bc3000: item 11
Thread 0x101e81000: item 12
Thread 0x101e81000: item 13
Thread 0x101bc3000: item 14
Thread 0x101cc9000: item 15
Thread 0x101c46000: item 16
Thread 0x101bc3000: item 17
Thread 0x101bc3000: item 18
Thread 0x101c46000: item 19
Thread 0x101c46000: item 20
Thread 0x101bc3000: item 21
Thread 0x101cc9000: item 22
Thread 0x101bc3000: item 23
Thread 0x101bc3000: item 24
Thread 0x101c46000: item 25
Thread 0x101e81000: item 26
Thread 0x101e81000: item 27
Thread 0x101bc3000: item 28
Thread 0x101c46000: item 29
Thread 0x101e81000: item 30
Thread 0x101e81000: item 31
Thread 0x101cc9000: item 32
Thread 0x101bc3000: item 33
Thread 0x101cc9000: item 34
Thread 0x101e81000: item 35
Thread 0x101c46000: item 36
Thread 0x101bc3000: item 37
Thread 0x101cc9000: item 38
Thread 0x101cc9000: item 39
Thread 0x101c46000: item 40
Thread 0x101bc3000: item 41
Thread 0x101bc3000: item 42
Thread 0x101e81000: item 43
Thread 0x101cc9000: item 44
Thread 0x101bc3000: item 45
Thread 0x101bc3000: item 46
Thread 0x101cc9000: item 47
Thread 0x101e81000: item 48
Thread 0x101c46000: item 49
Thread 0x101e81000: item 50
Thread 0x101cc9000: item 51
Thread 0x101bc3000: item 52
Thread 0x101c46000: item 53
Thread 0x101cc9000: item 54
Thread 0x101bc3000: item 55
Thread 0x101c46000: item 56
Thread 0x101e81000: item 57
Thread 0x101c46000: item 58
Thread 0x101cc9000: item 59
Thread 0x101e81000: item 60
Thread 0x101bc3000: item 61
Thread 0x101c46000: item 62
Thread 0x101e81000: item 63
Thread 0x101c46000: item 64
Thread 0x101cc9000: item 65
Thread 0x101cc9000: item 66
Thread 0x101bc3000: item 67
Thread 0x101c46000: item 68
Thread 0x101cc9000: item 69
Thread 0x101e81000: item 70
Thread 0x101bc3000: item 71
Thread 0x101cc9000: item 72
Thread 0x101cc9000: item 73
Thread 0x101bc3000: item 74
Thread 0x101e81000: item 75
Thread 0x101c46000: item 76
Thread 0x101bc3000: item 77
Thread 0x101cc9000: item 78
Thread 0x101e81000: item 79
Thread 0x101c46000: item 80
Thread 0x101bc3000: item 81
Thread 0x101cc9000: item 82
Thread 0x101cc9000: item 83
Thread 0x101e81000: item 84
Thread 0x101e81000: item 85
Thread 0x101cc9000: item 86
Thread 0x101bc3000: item 87
Thread 0x101bc3000: item 88
Thread 0x101e81000: item 89
Thread 0x101e81000: item 90
Thread 0x101c46000: item 91
Thread 0x101c46000: item 92
Thread 0x101cc9000: item 93
Thread 0x101bc3000: item 94
Thread 0x101e81000: item 95
Thread 0x101c46000: item 96
Thread 0x101cc9000: item 97
Thread 0x101bc3000: item 98
Thread 0x101c46000: item 99
Thread 0x101cc9000 processed 24 items.
Thread 0x101c46000 processed 22 items.
Thread 0x101bc3000 processed 30 items.
Thread 0x101e81000 processed 24 items.


text:
Q: Sublime Text Blade Highlighter I'm using Medalink's Blade Highlighter for Sublime Text 3 (https://github.com/Medalink/laravel-blade)
I encountered, that the forelse directive isn't highlighted correctly, as you can see in this picture

Is this my computer's fault?


text:
Q: Get name of node in Kendo UI Multiple Select when you click I am using the Kendo UI multiple select, and I want the name of the node which is currently selected when you click on it. This is not just when I click on X to remove the node, although I also want the name when I remove it.
In this example, when I click on the tags, I want the names such as "Europe" and "Africa".
I have tried this code, but it works only sometimes, and not when I click on X.
    $('.k-multiselect-wrap li .k-delete').click(function() {
           console.log('Select to remove it');
    });

A: You need to use delegated events because the items are being added to the DOM after your initial binding, so regular .click event bindings won't work for any elements added in the future. For example:
$(document).on("click", "li.k-button span.k-icon.k-delete", function () {
    console.log("Clicked on X: " + $(this).siblings().first().text());
});

See  update jsFiddle


text:
Q: Concatenate string rows up to length in oracle sql What I'm trying to achieve is concatenating strings up to a length of 10 with carriage return. If the row goes over length 10 then it should be added to the next concatenation row.
Example, having the following data set

SELECT '0123' col FROM DUAL
UNION ALL
SELECT '45 67' FROM DUAL
UNION ALL
SELECT '89A' FROM DUAL
UNION ALL
SELECT 'BC' FROM DUAL
UNION ALL
SELECT 'DEFGHI' FROM DUAL

What I expect for the result

SELECT '0123
45 67' col FROM DUAL
UNION ALL
SELECT '89A
BC' FROM DUAL
UNION ALL
SELECT 'DEFGHI' FROM DUAL

I'm running oracle 12.1 and I don't want to do it in PLSQL due to performance reasons. I'm dealing with higher numbers.
I posted the simple example so it'll be easier. My end goal is to use listagg somehow where each row has a max of 4k chars

A: You can use MATCH_RECOGNIZE to group the rows and then LISTAGG to concatenate them:
SELECT LISTAGG( col, CHR(10) ) WITHIN GROUP ( ORDER BY rn ) AS col
FROM   ( SELECT ROWNUM AS rn, col FROM table_name )
MATCH_RECOGNIZE(
  ORDER     BY rn
  MEASURES
    MATCH_NUMBER() AS mno
  ALL ROWS PER MATCH
  PATTERN ( short_strings* last_string )
  DEFINE short_strings AS NEXT(LENGTH(col)) <= 10 - SUM(LENGTH(col) + 1)
)
GROUP BY mno;

Which, for the sample data:
CREATE TABLE table_name ( col ) AS
SELECT '0123'   FROM DUAL UNION ALL
SELECT '45 67'  FROM DUAL UNION ALL
SELECT '89A'    FROM DUAL UNION ALL
SELECT 'BC'     FROM DUAL UNION ALL
SELECT 'DEFGHI' FROM DUAL;

Outputs:

| COL    |
| :----- |
| 0123   |
| 45 67  |
| ------ |
| 89A    |
| BC     |
| ------ |
| DEFGHI |

db<>fiddle here

A: Here is a match_recognize solution, which requires Oracle 12.1 or higher. I make the following additional assumptions: the newline character is chr(10) as in Unix, the last row does NOT require a newline at the end, and all input row strings have length at most equal to the limit. (The limit, 10, can be changed to a bind variable.) I assume there is also an ordering column, which I called ORD.
with
  sample_data (ord, col) as (
    select 1, '0123'   from dual union all
    select 2, '45 67'  from dual union all
    select 3, '89A'    from dual union all
    select 4, 'BC'     from dual union all
    select 5, 'DEFGHI' from dual
  )
select rn, listagg(col, chr(10)) within group (order by ord) as fragment
from   sample_data
match_recognize (
  order by ord
  measures match_number() as rn
  all rows per match
  pattern (a+)
  define  a as sum(length(col)) + count(*) - 1 <= 10
)
group  by rn
order  by rn
;

   RN  FRAGMENT
-----  ------------
    1  0123
       45 67
    2  89A
       BC
    3  DEFGHI

A: If you want to group pairs of adjacent rows together, then you need a column that defines the ordering of the rows. Let me assume that you have such column and that is called id.
Then, you can use a recursive query. The idea is to traverse the dataset row by row, concatenating values until the length would exceed 10, at which point a new group must sart. The the outer query returns the latest row in each group:
with
    data (id, col, rn) as (
        select t.*, row_number() over(order by id) rn
        from mytable t
    ),
    cte (id, rn, newcol, grp) as (
        select id, rn, col, 1 from data d where rn = 1
        union all
        select d.id, d.rn,
            case when length(c.newcol) + length(d.col) < 10
                then c.newcol || chr(13) || d.col
                else d.col
            end,
            case when length(c.newcol) + length(d.col) < 10
                then c.grp
                else d.rn
            end
        from cte c
        inner join data d on d.rn = c.rn + 1
    )
select max(newcol) as newcol
from cte
group by grp order by min(id)

Demo on DB Fiddle


text:
Q: Dropdown menu is out of the screen I want to add a dropdown menu to my navbar but the menu is always out of the page.
Here is my code :

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

  PEL

    <button
      type="button"
      class="btn btn-secondary dropdown-toggle mr-3"
      data-toggle="dropdown"
      aria-haspopup="true"
      aria-expanded="false">${pseudo}</button>

      <button
        class="dropdown-item dropdown-menu-right"
        type="button">Action</button>
      <button
        class="dropdown-item dropdown-menu-right"
        type="button">Another action</button>
      <button
        class="dropdown-item dropdown-menu-right"
        type="button">Something else here</button>

Dropdown works good but it is always out of the right side of my screen...

A little space is created by my dropdown menu on the right side of the page.

A: According to the v4.0 doc :
https://getbootstrap.com/docs/4.0/components/dropdowns/#menu-alignment

Heads up! Dropdowns are positioned thanks to Popper.js (except when they are contained in a navbar).

Two options :

*

*Upgrade your bootstrap version. It's working fine with v4.6

*Use custom classes instead of bootstrap navbar

[EDIT 1] Here is a working example with bootstrap v4.6. Also i have removed the mr-3 class for better rendering.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

  PEL

    <button
      type="button"
      class="btn btn-secondary dropdown-toggle"
      data-toggle="dropdown"
      aria-haspopup="true"
      aria-expanded="false">${pseudo}</button>

      <button
        class="dropdown-item"
        type="button">Action</button>
      <button
        class="dropdown-item"
        type="button">Another action</button>
      <button
        class="dropdown-item"
        type="button">Something else here</button>


text:
Q: How to get total number of edits for a given wikipedia page from the API? I actually do not want to list each edit, but to get only the count of it.
this data is available for every article on the left panel in link:
https://en.wikipedia.org/w/index.php?title=Wikipedia&action=info

But this produces complete web page with tables, formatting etc and its exhaustive for wikipedia servers. So I ask if is there a way to only get those few numbers and ommit the whole website scraping.

A: Probably not the answer you want but there isn't a way to get this information yet.
As a workaround you can use the prop=revisions to get all the revisions contributed to the article. You will be able to count the rev tag from here:
http://en.wikipedia.org/w/api.php?format=xml&action=query&titles=Wikipedia&prop=revisions&rvprop=ids&rvlimit=max
Alternatively, you can ask YQL to count it for you with the following command:
SELECT * FROM xml
WHERE url="http://en.wikipedia.org/w/api.php?format=xml&action=query&titles=Wikipedia&prop=revisions&rvprop=ids&rvlimit=max"
AND itemPath="/api/query/pages/page/revisions/rev"

Example output (Link to full output):
{
    "query": {
        "count": 500, //This is the total amount of edits
        "created": "2014-03-04T02:29:42Z",
        "lang": "en-US",
        "results": {
            "rev": [{
                "parentid": "597995345",
                "revid": "598005528"
            }, {
                "parentid": "597994174",
                "revid": "597995345"
            }, {
                "parentid": "597891867",
                "revid": "597994174"
            }]
        }
    }
}

Unfortunately, the upper limit for users to retrieve revision data is 500 and for bots it's 5000.
To get the exact count, you will have to set up a parser on your server to capture the exact count from the info page whenever a user queries the data from your side.


text:
Q: how to address object dynamically in c# I have a need to build some search criteria using the inputs user entered.
string searchText1 = "";
string searchText2 = "";
string searchText3 = "";

searchText1 = scCB1.Text + op1.Text + cr1.Text;
searchText2 = scCB2.Text + op2.Text + cr2.Text;
searchText3 = scCB3.Text + op3.Text + cr3.Text;

where scCB1, op1, cr1, ... are the combobox and text fields on GUI.
Is there a way I could use a loop to replace the hard coded statements (they look awkward)?
For (i = 0; i < 3; i++)
{
   //    searchText(i) = scCB(i).Text + op(i).Text +cr(i).Text)
}

As a rookie in programming, I understand if I display and build only one set of fields on GUI, then I'll be able to loop in the code.  But I am curious how i could address the name of the objects dynamically. Thanks in advance for all your help!

A: Assuming that the controls are on a GroubBox named options:
string[] searchText = new string[3];
for(int i = 1; i<=3; i++)
   {
        searchText[i - 1] = options.Control["scCB" + i.Tostring()] +
                        options.Control["ops" + i.Tostring()] +
                        options.Control["cr" + i.Tostring()];
   }

A: I would suggest to make an array containing your text boxes and other elements, this way your can easily reference them inside a loop:
TextBox[] boxes = {scCB1, scCB2, scCB3}; // do same for op1..3 and cr1..3
for (int i = 0; i < 3; i++)
{
  string searchText = boxes[i].Text + ops[i].Text + cr[i].Text;
}


text:
Q: Delete row with specific text in a specific field at a specific time I have a feature class that resides in an Enterprise geodatabase, I need to delete a row that has specific text in a specific field at a specific.
Data is being submitted daily to this feature class via Survey123, a "dummy" point is created daily for other purposes.  I would like to delete that "dummy" point daily at a specific time using ArcPy.  I am novice with ArcPy.
import arcpy

myFC = ("target dataset")

commentfield = 'Comments'
sql = """{0} LIKE '%NameOfTextToSearchFor%'""".format(arcpy.AddFieldDelimiters(myFC,commentfield))

with arcpy.da.UpdateCursor(myFC, commentfield, sql) as cursor:
    for row in cursor:
        cursor.deleteRow(row)

I couldn't figure out how to indent the last two lines

A: In this example, I check for any occurrence of the text 'Test' in the field "some_field" using an if statement. For example, this will delete rows in any of the following cases: '1234test_abcd', 'Test', 'test', 'one_moreTest'. Using the `.lower() method allows you to include any type of case in the search term (e.g. 'Test', 'test', 'TeSt', etc).
You would use the .deleteRow() method to delete any instances of the search term.
For example:
import arcpy

fc = r'C:\path\to\your\geodatabase.gdb\featureclass'

with arcpy.da.UpdateCursor(fc, "some_field") as cursor:
    for row in cursor:
        if row[0] is not None and 'test' in row[0].lower():
            cursor.deleteRow()

To be more specific in your search term, replace the following:
if row[0] is not None and 'test' in row[0].lower():

with:
if row[0] == 'Test':

Finally, if you need to specify a time constraint, try the following (untested) code:
import arcpy

fc = r'C:\path\to\your\geodatabase.gdb\featureclass'

time_value = 'add-your-time-stamp-here'

with arcpy.da.UpdateCursor(fc, ["time_field", "some_field") as cursor:
    for row in cursor:
        if row[0] == time_value: # Only iterates through rows with your time stamp
            if row[1] == 'Test': # Checks for your search term
                cursor.deleteRow() # Delete row


text:
Q: Show menu items only if they have submenu's in Wordpress Example:
Menu layout in Appearance->menu
Menu name: Main menu
About us(menu)
- Contact (submenu)
- Team (submenu)
- Portfolio (submenu)
These four pages need to show all four menu items including the parent: About us, Contact, Team and Portfolio.
Currently I am only able to show the sub menu items only so: Contact, Team and Portfolio. So I am missing the parent.
How can I display the parent menu item(Example: About us) as well?
This is how I call the menu:
<?php // Usage:
                $args = array(
                    'menu'     => 'Main menu',
                    'sub_menu' => true,
                );
                wp_nav_menu( $args );
                ?>

This is the function I used for showing the submenus:
// add hook
add_filter( 'wp_nav_menu_objects', 'my_wp_nav_menu_objects_sub_menu', 10, 2 );
// filter_hook function to react on sub_menu flag
function my_wp_nav_menu_objects_sub_menu( $sorted_menu_items, $args ) {
    if ( isset( $args->sub_menu ) ) {
        $root_id = 0;

        // find the current menu item
        foreach ( $sorted_menu_items as $menu_item ) {
            if ( $menu_item->current ) {
                // set the root id based on whether the current menu item has a parent or not
                $root_id = ( $menu_item->menu_item_parent ) ? $menu_item->menu_item_parent : $menu_item->ID;
                break;
            }
        }

        // find the top level parent
        if ( ! isset( $args->direct_parent ) ) {
            $prev_root_id = $root_id;
            while ( $prev_root_id != 0 ) {
                foreach ( $sorted_menu_items as $menu_item ) {
                    if ( $menu_item->ID == $prev_root_id ) {
                        $prev_root_id = $menu_item->menu_item_parent;
                        // don't set the root_id to 0 if we've reached the top of the menu
                        if ( $prev_root_id != 0 ) $root_id = $menu_item->menu_item_parent;
                        break;
                    }
                }
            }
        }
        $menu_item_parents = array();
        foreach ( $sorted_menu_items as $key => $item ) {
            // init menu_item_parents
            if ( $item->ID == $root_id ) $menu_item_parents[] = $item->ID;
            if ( in_array( $item->menu_item_parent, $menu_item_parents ) ) {
                // part of sub-tree: keep!
                $menu_item_parents[] = $item->ID;
            } else if ( ! ( isset( $args->show_parent ) && in_array( $item->ID, $menu_item_parents ) ) ) {
                // not part of sub-tree: away with it!
                unset( $sorted_menu_items[$key] );
            }
        }

        return $sorted_menu_items;
    } else {
        return $sorted_menu_items;
    }
}

A: Just add 'show_parent' option to the $args array and set it True:
$args = array(
    'menu'     => 'Main menu',
    'sub_menu' => true,
    'show_parent' => true,
);


text:
Q: SQL SERVER 2008 Connection String using Java throws an Exception's Message SQL SERVER 2008 Connection String using Java throws the following exception
"java.lang.ClassNotFoundException:com.microsoft.jdbc.sqlserver.SQLServerDriver"
Please Update!

A: Download and extract the jar file to your project.

A: You should add the connector's jar to your application's classpath.


text:
Q: Linux CLI find dir paths without their children - only parent paths as a result I have this dir tree:
/tmp/find-test/
├── one
│   ├── abc
│   │   ├── one
│   │   └── two
│   └── def
│       ├── one
│       └── two
└── two
    ├── abc
    │   ├── one
    │   └── two
    └── def
        ├── one
        └── two

and the same for find-test2
/tmp/find-test2/
├── one
│   ├── abc
│   │   ├── one
│   │   └── two
│   └── def
│       ├── one
│       └── two
└── two
    ├── abc
    │   ├── one
    │   └── two
    └── def
        ├── one
        └── two

If I issue:
find /tmp -ipath "*find-test*" -type d

I get:
/tmp/find-test
/tmp/find-test/two
/tmp/find-test/two/def
/tmp/find-test/two/def/two
/tmp/find-test/two/def/one
...
/tmp/find-test2
/tmp/find-test2/two
/tmp/find-test2/two/def
/tmp/find-test2/two/def/two
/tmp/find-test2/two/def/one
...

but I would like to get as a result only parent dirs without their children. The desired result should be just these two parent paths:
/tmp/find-test
/tmp/find-test2

and similarly if I issue command:
find /tmp -ipath "*one*" -type d

I would like to get only:
/tmp/find-test/one
/tmp/find-test/two/abc/one
/tmp/find-test/two/def/one
/tmp/find-test2/one
/tmp/find-test2/two/abc/one
/tmp/find-test2/two/def/one

Please note it is without for example:
/tmp/find-test/one/abc/one

since it is already held by
/tmp/find-test/one

script to replicate dir trees:
mkdir -p /tmp/find-test1/{one,two}/{abc,def}/{one,two}
mkdir -p /tmp/find-test2/{one,two}/{abc,def}/{one,two}

and find commands:
find /tmp -ipath "*find-test*" -type d
find /tmp -ipath "*one*" -type d

I would like to ask how to use the find command to get the desired result containing only parent paths matching the pattern.
I need to use -ipath switch so I can match paths with more conditions but still only the parent paths are desired result.
I'm using sh and bash.

A: Use -prune. I  used your command to replicate the dir tree and issued your commands with -prune, which resulted in:
$ find 2>&- /tmp -ipath '*find-test*' -type d -prune
/tmp/find-test2
/tmp/find-test1
$ find 2>&- /tmp -ipath '*one*' -type d -prune
/tmp/find-test2/two/def/one
/tmp/find-test2/two/abc/one
/tmp/find-test2/one
/tmp/find-test1/two/def/one
/tmp/find-test1/two/abc/one
/tmp/find-test1/one


text:
Q: Call finish() inside onPause() but not when orientation changes I have an app that needs to call finish when someone exits its main activity (so i do not want it to be paused), even by pressing home activity has to be finished, to handle this currently i simply call finish() in my onPause() method, since everything is done with fragments it works pretty well and gives no stability issues.
My only problem is that i cannot handle orientation changes since onPause() is called before onConfigurationChanged() (allowing me to disable this behavior when rotation occurs).
I could create a service that handles this but its way to complex.
Any idea?

A: You can use onWindowFocusChanged event instead of onPause. This function is not called when orientation changed.
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    Log.d(TAG, "FOCUS = " + hasFocus);
    if (!hasFocus) finish();
}

But note: this event is called when activity is still visible (like onPause()), you should
use onStop if you want to finish the activity when it is really and fully invisible:
private boolean isInFocus = false;

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    Log.d(TAG, "FOCUS = " + hasFocus);
    isInFocus = hasFocus;
}

@Override
public void onStop() {
    super.onStop();
    if (!isInFocus) finish();
}

A: its simple just do:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        display = ((WindowManager) getSystemService(WINDOW_SERVICE))
                .getDefaultDisplay();
        orientation = display.getOrientation();

    }

@Override
    protected void onPause() {
        // TODO Auto-generated method stub

        int orientation_ = display.getOrientation();
        if (orientation_ != orientation) {
            finish();
        }
        Log.e("hello=---->", "onPause");
        super.onPause();
    }

A: From your question, it seems that you only have one activity, in this case you should set a flag in the manifest instead. In your MainActivity manifest add
android:clearTaskOnLaunch="true"

A: You could listen for orientation changes, and on the change event store a boolean value about it, like
boolean orientationChanging;

make this true when orientation is changing, and false afterwards, than in your onPause:
@Override
protected void onPause() {

    if(!orientationChanging){
                finish();
            }
}


text:
Q: Hyperplane Reflection Given the reflection $R_H(−2, 2, 2, −3) = (−4, 0, −2, 1)$,  what is the reflection of $R_H(−1, −1, −1, 3)$, and how I can find it ?
I tried to use $R_H = (2P_H b -I)b$, but I have no idea how to keep going on this exercise
thanks

A: Let
$$U=(−2, 2, 2, −3)^T  \ \ \text{and} \ \ V=(−4, 0, −2, 1)^T  \ \ \text{giving} \ \ W=U-V=(2, 2, 4, -4)^T$$
(recall: the $^T$ operators mean that $U,V,W$ are transposed of line vectors, therefore are column vectors).
Let us consider the hyperplane $P$ with unit normal vector
$$N=W/\|W\|=\frac{1}{\sqrt{40}}(2, 2, 4, -4)^T$$
Taking the formula of the Householder reflection matrix (similar to yours) with respect to hyperplane $P$:
$$H=I-2NN^T=\left[\begin{array}{rrrr}0.8&-0.2&-0.4& \ \ 0.4\\
-0.2&0.8&-0.4&0.4\\
-0.4&-0.4&0.2&0.8\\
0.4&0.4&0.8&0.2\\
\end{array}\right]$$
It remains to apply this matrix to vector
$$(-1, -1, -1, \ 3)^T$$


text:
Q: Godot Nix Expression Fails I've added the following nix expression to my project (verbatem from nixpkgs) and tried to build it, but I get the following error message:
these derivations will be built:
  /nix/store/l6l5j1gas74pnzc2pb8w9fv2namxpgki-godot-3.0.6.drv
building '/nix/store/l6l5j1gas74pnzc2pb8w9fv2namxpgki-godot-3.0.6.drv'...
unpacking sources
unpacking source archive /nix/store/mlbp5ibpyq2rd710fl43pwr6a03ysz57-source
source root is source
patching sources
applying patch /nix/store/yk47p909lklbcai94izb5dfqjqqnnxmc-pkg_config_additions.patch
patching file platform/x11/detect.py
applying patch /nix/store/sdr3xp65cibpd06vq4fg5czv2s3m6a3c-dont_clobber_environment.patch
patching file SConstruct
configuring
no configure script, doing nothing
building
no Makefile, doing nothing
installing
cp: missing destination file operand after '/nix/store/mxvinscpfbv3k5j7dvpa83pd4w1p1f4f-godot-3.0.6/bin/godot'
Try 'cp --help' for more information.
builder for '/nix/store/l6l5j1gas74pnzc2pb8w9fv2namxpgki-godot-3.0.6.drv' failed with exit code 1

What could be causing this? Note that when I simply add godot to my nix config (in NixOS using nixos-18.09 channel), it installs and runs just fine. Aren't these the same expressions? If so, why does it work globally and not locally?
NOTE: Here is the part of the nix expression that invokes the cp shell command (related to the error above):
  installPhase = ''
    mkdir -p "$out/bin"
    cp bin/godot.* $out/bin/godot

    mkdir "$dev"
    cp -r modules/gdnative/include $dev

    mkdir -p "$man/share/man/man6"
    cp misc/dist/linux/godot.6 "$man/share/man/man6/"

    mkdir -p "$out"/share/{applications,icons/hicolor/scalable/apps}
    cp misc/dist/linux/godot.desktop "$out/share/applications/"
    cp icon.svg "$out/share/icons/hicolor/scalable/apps/godot.svg"
    cp icon.png "$out/share/icons/godot.png"
    substituteInPlace "$out/share/applications/godot.desktop" \
      --replace "Exec=godot" "Exec=$out/bin/godot"
  '';


text:
Q: How to transform numbers in data-frame column to comma separated i am working with python , so in my dataframe i have a column named Company Profit and values of this column are 33536310, 842925200,.. etc.
I want to convert all values to be comma separated every three digits, like: 231,535,366  etc in whole column

A: Something like this will work:
In [601]: def thousand_separator(val):
     ...:     return f"{val:,}"
     ...:

In [602]: df['Company Profit'] = df['Company Profit'].apply(thousand_separator)
In [603]: df['Company Profit']
Out[602]:
0     33,536,310
1    842,925,200
Name: Profit, dtype: object

A: Alternatively you can do this with f-string in newer version of Python. Use comma as a separator:
df = pd.DataFrame({'Company Profit':[33536310,842925200,231535366]})
df['Company Profit'] = df['Company Profit'].apply(lambda x: f"{x:,}")
print(df)

  Company Profit
0     33,536,310
1    842,925,200
2    231,535,366


text:
Q: How to create a mysql php multi-level list navigation Basically I want to be able to create a multi-level navigation (many sub navs). Obviously I know this will be done through creating lists with in each other but I am pretty stuck on the logic of displaying it correctly.
I have seen stuff regarding parent/children relationships but can't find anything that is efficient and easy to udnerstand.
I don't need to know how the HTML is built. Just how the php/mysql can generate the lists.
Hope you can help.
A

A: Here is code I used. It builds unordered list with unlimited level of subitems.
/*
* Table has 3 fields: `ID`, `PARENTID` and `NAME`
* `ID` is unique, `PARENTID` showing his parent node id.
* This function will go through it and build unordered list and call itself when needed to build subitems.
* $level argument used to define wich node's subitems to build. Default is 0 which is top level.
*/

function showMenu($level = 0) {

$result = mysql_query("SELECT * FROM `tbl_structure` WHERE `PARENTID` = ".$level);
echo "
";
    while ($node = mysql_fetch_array($result)) {
        echo "
".$node['NAME'];
        $hasChild = mysql_fetch_array(mysql_query("SELECT * FROM `tbl_structure` WHERE `PARENTID` = ".$node['ID'])) != null;
        IF ($hasChild) {
            showMenu($node['ID']);
        }
        echo "
";
    }
echo "
";
}

Hope that helps.

A: I think the most efficient would be to get all records in one go from the database and then build the hierarchical structure again in php.
So you would have a structure similar to this in your database:
id    parent_id    menu_item

Then you can get all items and use a recursive function to build a hierarchical array which you can loop through to get your menu, sub-menu, sub-sub-menu, etc. items. See this question and the top-two answers on how to re-build the structure.

A: If you mean the HTML it's like this:

      Title

Title

Title

Title

Title

Title

Title

A: assuming you know how to create  filled with the content of a mysql table
assuming you have the following tables : Universes > Categories > Markets > Segments
1) list the content of 'Universes' in a select. when the user picks, call another .php script and send it the id of the chosen Universe (using GET or POST)
2) list the content of 'Categories', WHERE idUniverses = the id you sent to the second script.
3) same for the Markets...
It's easier with AJAX.
need the code ?


text:
Q: Entity Framework Code First Two navigationProperty to/from one abstract entity The following entities is my code first which PersonParameter is an abstract class and Shirt and Shoes are inherited from it with typ(1,2)
[Table("Person")]
public class Person
{
    [Key]
    public int id { get; set; }
    public string Name { get; set; }

    public int? shirtID { get; set; }
    public int? shoesID { get; set; }

    [ForeignKey("shirtID")]
    public Shirt Shirt { get; set; }
    [ForeignKey("shoesID")]
    public Shoes Shoes { get; set; }
}

[Table("PersonParameter")]
public abstract class PersonParameter
{
    public int id { get; set; }
    public string Title { get; set; }
    public string Value { get; set; }

    public List<Person> Persons { get; set; }
}

public class Shirt : PersonParameter
{

}
public class Shoes : PersonParameter
{

}

and for model dbcontext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<PersonParameter>()
        .Map<Shirt>(p => p.Requires("typ").HasValue(1))
        .Map<Shoes>(p => p.Requires("typ").HasValue(2));
}

but the above codes will create unwanted field PersonParameter_id in Person table:
public override void Up()
{
    CreateTable(
        "dbo.PersonParameter",
        c => new
            {
                id = c.Int(nullable: false, identity: true),
                Title = c.String(),
                Value = c.String(),
                typ = c.Int(nullable: false),
            })
        .PrimaryKey(t => t.id);

    CreateTable(
        "dbo.Person",
        c => new
            {
                id = c.Int(nullable: false, identity: true),
                Name = c.String(),
                shirtID = c.Int(),
                shoesID = c.Int(),
                PersonParameter_id = c.Int(),
            })
        .PrimaryKey(t => t.id)
        .ForeignKey("dbo.PersonParameter", t => t.shirtID)
        .ForeignKey("dbo.PersonParameter", t => t.shoesID)
        .ForeignKey("dbo.PersonParameter", t => t.PersonParameter_id)
        .Index(t => t.shirtID)
        .Index(t => t.shoesID)
        .Index(t => t.PersonParameter_id);

}

how can I solve it (PersonParameter_id)
I did some FluentApi with HasOptional.WithMany but didn't solve.
EDIT
After some test, found that for non abstract class it create extra id too and the one solution for fixing that issue is removing navigation property from parameter class and adding it to the inheritance classes (shirt and shoes)

A: The reason you end up with one additional FK on Persons table is because of the Persons property on PersonParameter class. Basically EF cannot relate that to any of the current two relationships defined (Shirt and Shoes) and figured that Persons property must have been a third relationship between Persons and PersonParamter tables and therefore creates a third FK (PersonParameter_id) to create this relationship. As a result, you end up with 3 uni-directional Many to One relationships from PersonParameter to Persons.
To fix this, you need to explicitly tell EF that Persons is in fact the Inverse Property of Shoes and Shirts since there is no way that EF can pick that up automatically. You can do that with fluent API or by Annotations like this:
[Table("PersonParameter")]
public abstract class PersonParameter
{
    public int id { get; set; }
    public string Title { get; set; }
    public string Value { get; set; }
}

public class Shirt : PersonParameter
{
    [InverseProperty("Shirt")]
    public List<Person> Persons { get; set; }
}

public class Shoes : PersonParameter
{
    [InverseProperty("Shoes")]
    public List<Person> Persons { get; set; }
}

You can also achieve this by using the Fluent API:
modelBuilder.Entity<Shirt>()
    .HasMany(s => s.Persons)
    .WithOptional(p => p.Shirt)
    .HasForeignKey(p => p.shirtID);

modelBuilder.Entity<Shoes>()
    .HasMany(s => s.Persons)
    .WithOptional(p => p.Shoes)
    .HasForeignKey(p => p.shoesID);


text:
Q: Why split button dropdown hides options behind the cell? i have added a column to have bootstrap split button dropdown in jqGrid grid. This is a react component and code as follows:
The React code:
    "use strict";

var EmployeeGrid = React.createClass({
    displayName: "EmployeeGrid",

    componentDidMount: function componentDidMount() {
        this.loadGrid();
    },
    loadGrid: function loadGrid() {
        var $grid = $("#list"),
            resizeGrid = function resizeGrid() {
            var newWidth = $grid.closest(".ui-jqgrid").parent().width();
            $grid.jqGrid("setGridWidth", newWidth, true);
        };
        $(window).on("resize", function () {
            resizeGrid();
        });

        var $body = $('body');

        $.ajax({
            url: 'sample.json',
            dataType: 'json',
            success: function success(data1) {
                var d1 = data1;
                console.log('hello');
                $("#list").jqGrid({
                    data: d1,
                    colNames: ["id", "FirstName", "LastName", "Country", "Status"],
                    colModel: [{ name: "id", align: "center", hidden: true },
                        { name: "FirstName", align: "center", sortable: false, hidden: false },
                        { name: "LastName", align: "center", sortable: false, hidden: false },
                        { name: "Country", align: "center", sortable: false, hidden: false },
                        { name: "Status",
                        align: "center",
                        width: 93,
                        sortable: false,
                        edittype: 'select',
                        hidden: false,
                        editoptions: { value: { '1': 'Hired', '2': 'Extended', '3': 'Terminated',
                                '4': 'Fired', '5': 'Retired' }, defaultValue: 'Hired' },
                        formatoptions: { disabled: false },
                        formatter: function formatter(cellvalue, options, rowObject) {

                            var str = '
 ' + '<button type="button" class="btn btn-sm btn-success" style="min-width: 65px;max-width: 65px">Action</button>' + '<button type="button" class="btn btn-sm btn-success dropdown-toggle" data-toggle="dropdown">' + '' + 'Toggle Dropdown' + '</button>' + '
' + '
Hired
' + '
Extended
' + '
Terminated
' + '
Retired
' + '
' + '
';

                            return str;
                        } }],
                    loadComplete: function() {//chaneg the height of each row to 200
                        var grid = $("#list");
                        var ids = jQuery("#list").jqGrid('getDataIDs');
                        for (var i = 0; i < ids.length; i++) {
                            grid.jqGrid('setRowData',ids[i], false, { height : 200 });
                        }
                    },
                    cmTemplate: { autoResizable: true },
                    autoResizing: { compact: true, resetWidthOrg: true },
                    autowidth: true,
                    height: 350,
                    iconSet: "fontAwesome",
                    guiStyle: "bootstrap",
                    pager: '#pager',
                    caption: 'Employees Listing',
                    pgbuttons: false,
                    viewrecords: false,
                    pgtext: "",
                    pginput: false

                });
            },
            error: function error(x,y,z) {
                //alert('DATA CANNOT READ'+ JSON.stringify(x));
                console.log(JSON.stringify(x));
            }
        });
    },
    render: function render() {
        return React.createElement(
            "div",
            null,
            React.createElement(
                "div",
                null,
                React.createElement(
                    "h1",
                    null,
                    "Top header"
                )
            ),
            React.createElement(
                "div",
                null,
                React.createElement(
                    "div",
                    { className: "container-fluid" },
                    React.createElement("table", { id: "list" }),
                    React.createElement("div", { id: "pager" })
                )
            ),
            React.createElement(
                "div",
                null,
                React.createElement(
                    "h1",
                    null,
                    "bottom header"
                )
            )
        );
    }
});

/////////////////////////////////////////////////////////
// this code will show the seleted text on the button
////////////////////////////////////////////////////////////
$('.btn-success').on('click',function(e){
    e.preventDefault();
})
$('.dropdown-menu a').on('click', function(e){
    e.preventDefault();
    var anchor = $(e.currentTarget);
    var href = anchor.attr('href');
    var text = anchor.text();
    var button = anchor.closest('.btn-group').find('button:first-child');
    button.attr('data-url', href);
    button.text(text);
    button.on('click', gotoUrl);
});
function gotoUrl(e){
    e.preventDefault();

}
/////////////////////////////////////////////////////

ReactDOM.render(React.createElement(EmployeeGrid, null), document.getElementById('divOuterContainer'));

The HTML:
**
<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/south-street/jquery-ui.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/free-jqgrid/4.14.0/css/ui.jqgrid.min.css">

**
in the above code stack overflow wont let me add facebook's react libraries. So please when you test the code add react files ie: react-15.0.0.js and react-dom-15.0.0.js
The JSON data it uses
[{"id":1, "FirstName":"John","LastName":"Akram", "Country":"USA", "Status":"Hired"},
  {"id":2, "FirstName":"John","LastName":"Akram", "Country":"USA", "Status":"Hired"},
  {"id":3, "FirstName":"John","LastName":"Akram", "Country":"USA", "Status":"Hired"}
]

it generates the following grid:

Question # 1:
As you can see in code i have added four options for teh split button

*

*Hired

*Extended

*Terminated

*Retired

but as you can see in the image it shows only three options, why it hides the last option "Retired" inside the cell and how do i fix this?
Question #2:

As you can see the user selects options but the selected option wont show on button. but i have written code for it, if you see the react code at bottom of the grid's code
$('.btn-success').on('click',function(e){
    e.preventDefault();
})
$('.dropdown-menu a').on('click', function(e){
    e.preventDefault();
    var anchor = $(e.currentTarget);
    var href = anchor.attr('href');
    var text = anchor.text();
    var button = anchor.closest('.btn-group').find('button:first-child');
    button.attr('data-url', href);
    button.text(text);
    button.on('click', gotoUrl);
});
function gotoUrl(e){
    e.preventDefault();

}

But why it wont set selected option text as the text of the button? How do i fix this?

A: This should fix it:
tr.jqgrow:hover {
  position:relative;
  z-index: 1;
}

If displaying it correctly on :hover is not enough, consider adding a class to the row on dropdown open and removing it on close:
$(this).closest('tr.jqgrow').addClass('opened');

... that needs to go into the open event of your dropdown. And needs to be removed on dropdown close event. And, of course, adjust the CSS above to tr.jqgrow.opened {...}
Another thing to check for is if any of the .dropdown parents has an overflow:hidden and override it with visible.


text:
Q: Is it possible for a statement to be executed after raise in python? I found following code in TwistedSNMP library:
try:
  raise ImportError
  import psyco
except ImportError, err:
  pass
else:
  from pysnmp.asn1 import base
  psyco.bind(base.SimpleAsn1Object)  psyco.bind(base.Asn1Object)

Source filename: pysnmpproto.py, Line 42
Are there any cases that either import psyco or else block will ever be executed?

A: import psyco will never be reached because of the exception raised on the previous line.  The exception will be caught by the except clause, which in this case does nothing.  The else clause will never be reached because you only reach it if your try clause executed without exceptions.
In short, this code will always raise an exception, catch it, and do nothing else.  It should be deleted.


text:
Q: How to count the number of groupings of elements in a data frame subject to multiple conditions using base R or dplyr? In the below example data frame myDF, I am trying to figure out the base R or dplyr code to derive the number of groupings of elements whereby Group code <> 0. For example in this data frame, with the generating code beneath and dput() version at the very bottom, I would like to get two different outputs:

*

*a single digit output of 4 (where Elements R with Group = 1, X with
Group = 1, R with Group 2, and X with Group -3, comprise the 4
groupings), and

*an output show only those grouped elements (listing
out those grouped elements listed in the above bullet).

Any recommendations for a simple and concise way to do this?
> myDF
   Element Group
1        R     1
2        R     1
3        X     0
4        X     1
5        X     1
6        X     0
7        B     0
8        R     0
9        R     2
10       R     2
11       X    -3
12       X    -3
13       X    -3

Generating code:

    myDF <- data.frame(
      Element = c("R","R","X","X","X","X","B","R","R","R","X","X","X"),
      Group = c(1,1,0,1,1,0,0,0,2,2,-3,-3,-3)
    )

Dput(myDF):
> dput(myDF)
structure(list(Element = c("R", "R", "X", "X", "X", "X", "B",
"R", "R", "R", "X", "X", "X"), Group = c(1, 1, 0, 1, 1, 0, 0,
0, 2, 2, -3, -3, -3)), class = "data.frame", row.names = c(NA,
-13L))

A: In dplyr:
filter(myDF, Group !=0) %>% distinct()

gives
  Element Group
1       R     1
2       X     1
3       R     2
4       X    -3


text:
Q: Lemma 5.3.6 in Bruns and Herzog, Cohen-Macaulay Rings In the picture we discuss the Stanley-Reisner ring over a simplicial complex $\Delta$.

I do not understand the steps "(i) implies" and "(ii) implies", maybe I do not catch how to translate the complexes language into the element language. For example, which element in the $F$? Please help.

A: $F=\operatorname{supp}(x)$ and $\operatorname{supp}(x)\cup\operatorname{supp}(v)=\operatorname{supp}(xv)$; $xv\ne0$ (in the Stanley-Reisner ring) is equivalent to $xv\notin I_{\Delta}$. If  $\operatorname{supp}(x)\cup\operatorname{supp}(v)=\operatorname{supp}(xv)\notin\Delta$ what can we say about $xv$?
$\deg v/x^l=a$ shows that $a_i=b_i-lc_i$ where $b_i$, resp. $c_i$ is the degree of variable $x_i$ in $v$, resp. in $x$. If $a_i<0$, then the variable $x_i$ appears necessarily in $x$ otherwise $c_i=0$, and thus $a_i\ge0$. Conclusion: $F\supset G_a$.
$a_i>0$ implies $b_i>lc_i$ and since $l\ge0$ and $c_i\ge 0$ we get $b_i>0$. Conclusion:
$H_a\subset\operatorname{supp}(v)$.


text:
Q: How to implement an browser idle system? What I want to do is to check if the user of my Ember application is in idle mode in the browser, and if so I want to implement some rules. Please check the following example.
if (User is idle)
   transition to template1
else
   transition to index

I need to do this for every template of my application.
Can anyone please suggest a solution or an example for this example?

A: This was exactly what I needed http://emberjs.jsbin.com/laxomesi/2/edit (Many thanks @panta82), but if you still have other solutions you may post them !


text:
Q: Project settings: Actual difference between Application and User scopes? I want to know what is the actual difference between Application and User scope in Settings configuration for vs projects.
Is the only difference the fact that if I select Application, I can't use Settings.MyProperty as a setter, but I have to use Settings["MyProperty"] instead?
How would using the User scope affect the program otherwise, if the config file is located at my application root?

A: User scope means each user gets their own copy, the settings are stored in the users profile folders and your App can Save those settings without Admin privileges.
If you change an Application setting (using Settings["MyProperty"]) and call Settings.Save() you will have to be running as Admin because the changes are saved to MyApplication.exe.config . And changes apply to all users.

A: Your best bet is to use the 'User' setting because with the newer operating systems Windows doesn't like you reading and writing to files that are local to your executable, this looks suspicious due to the awareness of viruses. So Windows likes you to read and write to designated safe areas which I believe happens in some application data area that the operating system keeps track of. If you set the scope to 'Application' it may try to write this data to the local config file(which is why you need to run with admin privileges) and with the operating systems becoming more locked down there may still be issues doing this. Your app may work in XP like this but anything newer might not work, especially when apps run in the 'c:\Program Files' folders...


text:
Q: How could one use Node.js to run JS from PHP and return a value back? This isn't for anything serious, more so to just play around and experiment. Just not sure where I would start. Also not bound to Node.js, just figured it's the most popular server-side JS tool around.
Though if there are some major technical reasons why one shouldn't do something like this on a real site, feel free to throw them out there.
What I'm asking about is something like…
$input = $js_string_built_via_php;

if ($run_on_server)
     $output = node.js($input);
else
     $output = '<script type="text/javascript">'.$input.'</script>';

echo $output;

A: There are several alternatives to using node here.
Have you seen the V8js PHP extension, which integrates the V8 engine with PHP? I don't have any experience with using it myself, though.
Alternatively, similar to using node, you could install Rhino (available in the Ubuntu repos, at least from 12.04). Or another command line javascript interpreter. Then you can execute javascript from the shell:
rhino -e '<javascript code>';

So you should be able to do something like the following. You would have to use print to output data and then parse the output back in php somehow:
<?php

function execute_js($script) {
    return shell_exec('rhino -e '.escapeshellarg($script));
}

$javascript = "
    function add(a,b) {
        return a+b;
    }
    print(add(5,6));
";

$result = execute_js($javascript);

print $result;

I doubt this would be a good idea in a production application and seems like it might be quite vulnerable with a much greater attack surface. With clients being able to inject javascript code that actually gets executed on the server. It's probably very slow at load also.

A: A better solution 3 years later?
dnode-php would a better solution for what you want today.
There is a cool introduction here. As mentioned by the author Henri Bergius:

DNode is a remote method invocation protocol originally written for
  Node.js, as the name probably tells. But as the protocol itself is
  quite simple, just sending newline-terminated JSON packets over TCP
  connections, implementations have started popping up in other
  languages. You can talk DNode in Ruby, Perl, Python, Java, and now
  PHP.


text:
Q: Evaluation of $ \int\frac{\sqrt{\sin x}}{\sqrt{\sin x}+\sqrt{\cos x}}dx$ Evaluation of $\displaystyle \int\frac{\sqrt{\sin x}}{\sqrt{\sin x}+\sqrt{\cos x}}dx$
$\bf{My\; Try::}$ Given $\displaystyle \int\frac{\sqrt{\sin x}}{\sqrt{\sin x}+\sqrt{\cos x}}dx = \int \frac{\sqrt{\tan x}}{1+\sqrt{\tan x}}dx$
Now Let $\displaystyle \tan x = t^2\;,$ Then $\sec^2 xdx = 2tdt$ or $\displaystyle dx = \frac{2t}{1+t^4}dt$
So Integral is $\displaystyle \int\frac{t}{1+t}\cdot \frac{2t}{1+t^4}dt = 2\int\frac{t^2}{(1+t)\cdot  (1+t^4)}dt$
Now How can I solve after that
Help me
Thanks

A: By collecting all the suggestions, you should be able to prove that:
$$\frac{2t}{(t+1)(t^4+1)}=\frac{t}{1+t^4}+\frac{t^3}{1+t^4}+\frac{1-t^2}{1+t^4}-\frac{1}{1+t},$$
and since $(1+t^4)=(1+\sqrt{2}t+t^2)(1-\sqrt{2}t+t^2)$, it follows that:
$$\int\frac{2t\,dt}{(t+1)(t^4+1)}=\frac{1}{2}\arctan t^2+\frac{1}{4}\log(1+t^4)+\frac{1}{2\sqrt{2}}\log\frac{1+\sqrt{2}t+t^2}{1-\sqrt{2}t+t^2}-\log(1+t).$$
$\\$
Addendum
Suggestion for evaluating $\displaystyle{\int \frac{1 - t^2}{t^4 + 1}\,\mathrm{d}t}$:
Write
$$
\begin{aligned}
\int- \frac{t^2 - 1}{t^4 + 1}\,\mathrm{d}t &= -\int \frac{1 - \dfrac{1}{t^2}}{t^2 + \dfrac{1}{t^2}}\,\mathrm{d}t \\
&=-\int \frac{1 - \dfrac{1}{t^2}}{\left(t + \dfrac{1}{t}\right)^2 - 2}\,\mathrm{d}t
\end{aligned}
$$
Now, set $\displaystyle{u = t + \frac{1}{t}}$ and $\mathrm{d}u = \left(1 - \dfrac{1}{t^2}\right)\,\mathrm{d}t$:
$$
\begin{aligned}
-\int \frac{\mathrm{d}u}{u^2 - 2} &= \dfrac{1}{2\sqrt{2}}\ln\left|\frac{u + \sqrt{2}}{u - \sqrt{2}} \right| + C \\
&=\frac{1}{2\sqrt{2}}\ln\left|\frac{t^2 + t\sqrt{2} +1}{t^2 - t\sqrt{2}+1} \right| + C
\end{aligned}
$$
Note that $t^2 + t\sqrt{2}+1 = \left(t + \dfrac{1}{\sqrt{2}}\right)^{\!2} + \dfrac{1}{2} >0$ and $t^2 - t\sqrt{2}+1 = \left(t - \dfrac{1}{\sqrt{2}}\right)^{\!2} + \dfrac{1}{2} >0$, then we can get rid of the absolute value bars:
$$\int \frac{1-t^2}{t^4 + 1}\,\mathrm{d}t = \frac{1}{2\sqrt{2}}\ln\!\left(\dfrac{t^2 + t\sqrt{2}+1}{t^2 - t\sqrt{2}+1}\right) + C $$
This is a very famous technique.