text:
Q: how to save canvas for gradient background php/html5? I am trying to saving gradient linear background. I am using a plugin of https://github.com/niklasvh/html2canvas/releases.
The code is working for solid background color and images but not when I use css background-linear-gradient.
and how can i save this canvas image?
//EDITED:
I have another bug
I would like to save data which is loading from database, so i am looping between the database and showing content. How can i save the pictures one by one showing the content?

A: In the browser-compatibility section of the html2canvas' readme you can read :

As each CSS property needs to be manually built to be supported, there
  are a number of properties that are not yet supported.

background-image 's gradients are of those.
You will just have to write it yourself or wait until someone does for the html2canvas library.
If you've got a fixed gradient to render, it's quite easy to render it on a canvas element first, and set the dataURI version of this canvas to the background-image of your css.

var renderGradients = function(elem){
  // get the size of your element
  var rect = elem.getBoundingClientRect();
  // create a canvas and set it to the same size as the element
  var canvas = document.createElement('canvas');
  canvas.width = rect.width;
  canvas.height = rect.height;

  var ctx = canvas.getContext('2d');
  // create a new gradient, the size of our element
  var gradient = ctx.createLinearGradient(0,0,rect.width,rect.height);
  // add the colors we have in our style
  gradient.addColorStop(0, 'blue');
  gradient.addColorStop(1, 'red');

  ctx.fillStyle = gradient;
  // draw a rect with our gradient
  ctx.fillRect(0, 0, rect.width, rect.height);
  // set our element's background-image to the canvas computed gradient
  elem.style.backgroundImage = 'url('+canvas.toDataURL()+')';

  // now call html2canvas
  html2canvas(elem, {onrendered : function(can){
      document.body.appendChild(can);
    }});
  }

renderGradients(cont);
#cont {background-image: linear-gradient( 90deg, blue, red );}

  Some content

html2canvas result :

But given the complexity of the css gradients syntax, it's much harder to make something that will convert an already existing CSS background-image gradient into a canvas version. If someone wants to make this, I'd be glad to read it. So you will have to stick with hard-coded gradient values.


text:
Q: Django: Правильно ли использовать dict в views.py Здравствуйте!
В нескольких туториалах встречал использование dict в views.py, например:
def home(request):
images_all = ImagesArticles.objects.all()
article_get = Articles.objects.filter(is_active=True)
image_get = images_all.filter(is_main=True)
articles = {}
count = 0
for i in article_get:
    articles[count] = {}
    articles[count]['title'] = i.article_title
    articles[count]['slug'] = i.article_slug
    articles[count]['text'] = i.article_text
    articles[count]['date'] = i.article_pup_date
    articles[count]['video'] = i.article_video
    for image in image_get:
        if image.image_articles_id == i.id:
            articles[count]['image'] = image.image_thumbnail
    count += 1

context = {
    'articles': articles,
}
return render(request, 'articles/home.html', context)

Потом в шаблоне
{% for key, value in articles %}
    ...
{% endfor %}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hardware Random Number Generator error Arm M4 I´m new in Arm microcontroller programming. I read the datasheet and found this :

*

*Reset/initialize.

*Write 1 to CR[INTM], CR[HA], and CR[GO]

*Poll SR[OREG_LVL] until it is not 0.

*When SR[OREG_LVL] is not 0, read the available random data from
OR[RANDOUT]

*Repeat steps 3 and 4 as needed.

These are the steps for generating random numbers. Could someone give me a code example ? I'm working with the k64 sub-family, specifically MK64FX512VLL12.
Here's what I've tried:
void Rng_Test()
{
  RNG->CR |= RNG_CR_SLP_MASK;
  RNG->CR |= RNG_CR_GO_MASK;
  RNG->CR |= RNG_CR_HA_MASK;
  RNG->CR |= RNG_CR_INTM_MASK;
  while (RNG_SR_OREG_LVL_MASK == 0) { }
}

A: Using the code you already have
void Rng_Init() {
    RNG->CR |= RNG_CR_SLP_MASK;
    RNG->CR |= RNG_CR_GO_MASK;
    RNG->CR |= RNG_CR_HA_MASK;
    RNG->CR |= RNG_CR_INTM_MASK;
}

int Rng_GetRand() {
    while ((RNG->SR & RNG_SR_OREG_LVL_MASK) == 0);
    return RNG->OR;
}

Something like the above should work, Rng_Init() is required once, Rng_GetRand should return a new random number (not necessarily different) each time it's called.


text:
Q: Grant RDP access to non-admin user Using Windows Server 2012 R2, I want a non-admin user to be able to connect to the server via RDP. I found this and added a test non-admin user to the list, however, it still says it mustn't connect due to insufficient privileges. Any solution?

A: There is a missing step in the tutorial you linked.
You need to allow the RDP connection via the Advanced System settings :

You can find more info about that here :
http://sysads.co.uk/2013/01/enable-remote-desktop-windows-server-2012/


text:
Q: how can i access content of gridIndex My Grid has many row and column.
It looks like this.
<Grid x:Name="grid" Grid.ColumnSpan="3" RenderTransformOrigin="0.5,0.5">
        <Grid.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform/>
                <TranslateTransform/>
            </TransformGroup>
        </Grid.RenderTransform>
        <Grid.RowDefinitions>
            <RowDefinition Height="1*" />
            <RowDefinition Height="1*" />
            <RowDefinition Height="1*" />
            <RowDefinition Height="1*" />
            <RowDefinition Height="1*" />
            <RowDefinition Height="1*" />
            <RowDefinition Height="1*" />
            <RowDefinition Height="1*" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <rectImg:RectImg Grid.Row="0" Grid.Column="0"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="1"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="2"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="3"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="4"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="5"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="6"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="7"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="8"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="9"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="9"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="9"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="9"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="10"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="11"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="12"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="13"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="14"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="0" Grid.Column="15"></rectImg:RectImg>

        <rectImg:RectImg Grid.Row="1" Grid.Column="0"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="2" Grid.Column="0"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="3" Grid.Column="0"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="4" Grid.Column="0"></rectImg:RectImg>
        <rectImg:RectImg Grid.Row="5" Grid.Column="0"></rectImg:RectImg>

    </Grid>

I want to initialize on code behind and use foreach or for on this code:
    <rectImg:RectImg Grid.Row="0" Grid.Column="0"></rectImg:RectImg>

I have tried many ways. but i did't do it.. many people say"use Grid.SetColumn and Grid.SetRow" but it can't be applied....
How can I solve this?

A: For the sake of your requirements this can be done as following...
From code behind you can add the RectImg controls in the grid children and before that make sure you assign the Row and Column indices.
     private void AddRectImgControls()
     {
            var rectImg = new RectImg();
            for(var i = 0; i++; i < this.grid.RowDefinitions.Count)
            {
                 for(var j = 0; j++; j < this.grid.ColumnDefinitions.Count)
                 {
                     var rectImg = new RectImg();
                     Grid.SetRow(rectImg, i);
                     Grid.SetColumn(rectImg, j);
                     this.grid.Children.Add(rectImg);
                 }
            }
     }

But such design is not efficient. It should actually be an ItemsControl hosting multiple RectImg controls in it.
like this....
    <ItemsControl ItemsSource="{x:Static local:MainWindow.UniformGridCollection}">
        <ItemsControl.ItemsPanel>
             <ItemsPanelTemplate>
                  <UniformGrid Rows="8" Columns="23" />
             </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                 <rectImg:RectImg/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

Here "local" is the XAML namespace of you local project namespace where MainWindow resides.
Your MainWindow should be as below...
    public partial class MainWindow : Window
    {
       //// .... rest of the MainWindow code.

       public static List<object> UniformGridCollection
       {
           get
           {
               var coll = new List<object>();
               for(i = 0; i < 8 * 23; i++) //// 8 and 23 are UniformGrid's row and column size.
               {
                   coll.Add(new object());
               }
               return coll;
           }
       }
    }

Let me know if this helps.


text:
Q: Skip Django Allauth " You are about to sign in using a third party account from Google" page How can I skip the page and automatically logged in users, when they clicked on Login in With Google.

A: Instead of adding anchor tag add form and it will sign in User directly
<form action="{% provider_login_url 'google' %}" method="post">
  {% csrf_token %}
  <button type="submit">SIGN IN WITH GOOGLE</button>
</form>

A: You need to set up SOCIALACCOUNT_LOGIN_ON_GET=True in your configuration (by default it's False). according to https://django-allauth.readthedocs.io/en/latest/configuration.html:

SOCIALACCOUNT_LOGIN_ON_GET (=False)
Controls whether or not the endpoints for initiating a social login
(for example, "/accounts/google/login/") require a POST request to
initiate the handshake. For security considerations, it is strongly
recommended to require POST requests.

A: Just Add this:
SOCIALACCOUNT_LOGIN_ON_GET=True


text:
Q: RadioGroup onCheckedChanged getting an index higher than ChildCount I'm creating dinamically a LinearLayout (a custom Class that extends LinearLayout) with a RadioGroup inside it. I'm adding RadioButtons dinamically also. This LinearLayout class is used in several Activities and Fragments.
The strange behaviour is that the second time I add LinearLayout, when OnCheckedChanged is called, a get an index that doesn't exists in my current RadioGroup. I't seems that every time I create a new Instance of my LinearLayout, RadioGroup thinks that RadioButtons added previously are still there.
For example, if I create a custom LinearLayout and I add four items and after that I create another LinearLayout (in other Activity) with other 4 items, when I click in the first item (on the second Activity), I get a 5 as clicked item position.
This is my custom LinearLayout class:
public class AgrupacionConmutadorLayout extends LinearLayout{

    private static final String TAG = "AgrupacionConmutadorLayout";
    private int[] mColorFromLevel = {R.color.inspeccion_aparato_agrupacion_color_level_1, R.color.inspeccion_aparato_agrupacion_color_level_2,
            R.color.inspeccion_aparato_agrupacion_color_level_3, R.color.inspeccion_aparato_agrupacion_color_level_4, R.color.inspeccion_aparato_agrupacion_color_level_5};
    private Context mContext;

    private LinearLayout dataContainer;
    private TextView mTitle;
    private RelativeLayout mSubAgrupacionesContainer;
    private LinearLayout mDataAndSubAgrupacionesContainer;
    private RadioGroup mConmutadorContainer;

    private ArrayList<View> mLayoutsDataContained = new ArrayList<View>();

    private int mLevel;
    private LinearLayout mTitleContainer;
    private InspeccionesFormWidgetReceiver mModificationReceiver;

    private boolean isEdicion;

    public AgrupacionConmutadorLayout(Context context) {
        super(context);
        this.mContext = context;
        init(null, 0);
    }

    public AgrupacionConmutadorLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init(attrs, 0);
    }

    public AgrupacionConmutadorLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.mContext = context;
        init(attrs, defStyle);
    }

    private void init(AttributeSet attrs, int defStyle) {
        dataContainer = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.ins_agrupacion_conmutador_container, this);
        mTitle = (TextView) dataContainer.findViewById(R.id.ins_agrupacion_container_title);
        mSubAgrupacionesContainer = (RelativeLayout) findViewById(R.id.rl_ins_subagrupacion_container);
        mConmutadorContainer = (RadioGroup) findViewById(R.id.ins_agrupacion_conmutador_radio_group);
        mDataAndSubAgrupacionesContainer = (LinearLayout) findViewById(R.id.ll_ins_data_and_subagrupacion_container);
        mTitleContainer = (LinearLayout) findViewById(R.id.ll_ins_agrupacion_container_title);
        mConmutadorContainer.removeAllViews();
        mConmutadorContainer.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int pos) {
                Log.d(TAG, "onCheckedChanged Clicked pos: " + pos);
                Log.d(TAG, "onCheckedChanged RadioGroup size: " + radioGroup.getChildCount());
                Log.d(TAG, "onCheckedChanged " + mLayoutsDataContained.size());
                    //OnCheckedChanged comienza a devolver en 1, al ArrayList en 0
                    for (int i = 1; i < mLayoutsDataContained.size() + 1; i++) {
                        if (i == pos) {
                            mLayoutsDataContained.get(i - 1).setVisibility(View.VISIBLE);
                        } else {
                            mLayoutsDataContained.get(i - 1).setVisibility(View.GONE);
                        }
                    }
            }
        });

    }

    public void initialice(AgrupacionSios agrupacionSios, InspeccionesFormWidgetReceiver modificationReceiver, boolean isEdicion) {
        this.mModificationReceiver = modificationReceiver;
        this.isEdicion = isEdicion;

        mTitle.setText(agrupacionSios.getTitle());
        mTitle.setTextColor(mContext.getResources().getColor(mColorFromLevel[agrupacionSios.getLevel()]));
        if (agrupacionSios.isOcultarContenedor()) mTitleContainer.setVisibility(View.GONE);

        if (agrupacionSios.getNumOfSons() > 0) {
            drawSubAgrupaciones(agrupacionSios);
        }
        this.refreshDrawableState();
    }

    private void drawSubAgrupaciones(AgrupacionSios agrupacionSios) {
        ViewGroup.LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

        ArrayList<AgrupacionSios> agrupaciones = agrupacionSios.getAgrupacionesHijos();
        Iterator itAgr = agrupaciones.iterator();

        while (itAgr.hasNext()) {
            AgrupacionSios agrupacionHija = (AgrupacionSios) itAgr.next();
            if (agrupacionHija.getNumOfLevels() > 0 || agrupacionHija.getNumOfSons() > 0) {
                switch (agrupacionHija.getTipoSubAgrupaciones()) {
                    case CONMUTADOR:
                        AgrupacionConmutadorLayout v = new AgrupacionConmutadorLayout(mContext);
                        v.initialice(agrupacionHija, mModificationReceiver, isEdicion);
                        mSubAgrupacionesContainer.addView(v, layoutParams);
                        mLayoutsDataContained.add(v);
                        break;
                    case COLUMNAS:
                        AgrupacionColumnasLayout vCol = new AgrupacionColumnasLayout(mContext);
                        vCol.initialice(agrupacionHija, mModificationReceiver, isEdicion);
                        mSubAgrupacionesContainer.addView(vCol, layoutParams);
                        mLayoutsDataContained.add(vCol);
                        break;
                    default:
                        AgrupacionGenericaLayout vGen = new AgrupacionGenericaLayout(mContext);
                        vGen.isSonOfConmutador(true);
                        vGen.initialice(agrupacionHija, mModificationReceiver, isEdicion);
                        mSubAgrupacionesContainer.addView(vGen, layoutParams);
                        mLayoutsDataContained.add(vGen);
                        break;
                }
            }
            //Añadimos el botón de conmutación correspondiente a la subagrupación.
            addAgrupacionToConmutadorContainer(agrupacionHija);
        }
        mConmutadorContainer.check(1);
    }

    public void setBackgroundColor(int color) {
        setBackgroundResource(color);
    }

    private void addAgrupacionToConmutadorContainer(AgrupacionSios mAgrupacion) {
        ViewGroup.LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        RadioButton b = new RadioButton(mContext);
        b.setLayoutParams(layoutParams);
        b.setText(mAgrupacion.getTitle());
        b.setButtonDrawable(android.R.color.transparent);
        b.setBackground(mContext.getResources().getDrawable(R.drawable.ins_conmutador_radio_background));
        b.setPadding(20,5,20,5);
        RadioGroup.LayoutParams params
                = new RadioGroup.LayoutParams(mContext, null);
        params.setMargins(10, 0, 10, 0);
        b.setLayoutParams(params);

        mConmutadorContainer.addView(b);
    }
}

And this is the way I create AgrupacionConmutadorLayout on Activities & Fragments:
   AgrupacionConmutadorLayout vConm = new AgrupacionConmutadorLayout(this);
   vConm.initialice(agrupacion, this, isEdicion);
   vConm.setVisibility(View.VISIBLE);
   mAgrupacionesContainer.addView(vConm, layoutParams);

-----------------SOLUTION---------------------------
Marius answer was the key, I was getting clicked RadioButton id, not his position inside RadioGroup.
Finally I have done it by using tags. I set its order to every RadioButton as a tag:
private void addAgrupacionToConmutadorContainer(AgrupacionSios mAgrupacion) {
    ViewGroup.LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
    RadioButton b = new RadioButton(mContext);
    b.setLayoutParams(layoutParams);
    b.setText(mAgrupacion.getTitle());
    b.setButtonDrawable(android.R.color.transparent);
    b.setBackground(mContext.getResources().getDrawable(R.drawable.ins_conmutador_radio_background));
    b.setPadding(20, 5, 20, 5);
    RadioGroup.LayoutParams params
            = new RadioGroup.LayoutParams(mContext, null);
    params.setMargins(10, 0, 10, 0);
    b.setLayoutParams(params);
    b.setTag(mConmutadorContainer.getChildCount());
    mConmutadorContainer.addView(b);
}

And I get that tag in OnCheckedChangeListener:
   mConmutadorContainer.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int clickedId) {
            View radioButtonClicked = radioGroup.findViewById(clickedId);
            if (radioButtonClicked != null) {
                Integer pos = (Integer) radioButtonClicked.getTag();
                Log.d(TAG, "onCheckedChanged RadioGroup clicked position: " + pos);
                for (int i = 0; i < mLayoutsDataContained.size(); i++) {
                    View view = mLayoutsDataContained.get(i);
                    if (pos.intValue() == i) {
                        view.setVisibility(View.VISIBLE);
                    } else view.setVisibility(View.GONE);
                }
            }
        }
    });

A: You must have misread the API. Second parameter is NOT position. It's the id, of the button. There are several solutions to your problem.
Adding id, based on position:
//not recommended way, as activity.findViewById uses this id, I GUESS something wrong may happen
private int currId;
...
b.setId(currId);
currId++;
container.addView(b);

Adding a tag:
//recommended
b.setTag(mAgrupacion);
container.addView(b);
//then...
AgrupacionSios tag = (AgrupacionSios) b.getTag();
//do action based on tag information

A: Use this.
for (int i = 0; i < mLayoutsDataContained.size(); i++) {
                        if (i == pos) {
                            mLayoutsDataContained.get(i - 1).setVisibility(View.VISIBLE);
                        } else {
                            mLayoutsDataContained.get(i - 1).setVisibility(View.GONE);
                        }
                    }


text:
Q: Spark cluster - read/write on hadoop I would like to read data from hadoop, process on spark, and wirte result on hadoop and elastic search. I have few worker nodes to do this.
Spark standalone cluster is sufficient? or Do I need to make hadoop cluster to use yarn or mesos?
If standalone cluster mode is sufficient, should jar file be set on all node unlike yarn, mesos mode?

A: First of all, you can not write data in Hadoop or read data from Hadoop. It is HDFS (Component of Hadoop ecosystem) which is responsible for read/write of data.
Now coming to your question

*

*Yes, it possible to read data from HDFS and process it in spark engine and then write the output on HDFS.

*YARN, mesos and spark standalone all are cluster managers and you can use any one of them to do management of resources in your cluster and it had nothing to do with hadoop. But since you want to read and write data from/to HDFS then you need to install HDFS on cluster and thus it is better to install hadoop on your all nodes that will also install HDFS on all nodes. Now whether you want to use YARN, mesos or spark standalone that is your choice all will work with HDFS I myself use spark standalone for cluster management.

*It is not clear about which jar files you are talking to but I assume it will be of spark then yes you need to set the path for spark jar on each node so that there will be no contradiction in paths when spark run's.


text:
Q: Run-time error 1004 - Range of object failed - VBA 2013 I'm getting a run time error 1004, Method 'Range' of object '_Worksheet' failed.
This code worked before on a draft of this project, but when imported into new project file, i get this.... none of the named ranges or worksheet names have changed from previous version. Please help!
Private Sub UserForm_Initialize()
'Set Variables to populate combobox
Dim rngProjects As Range
Dim ws1 As Worksheet

Set ws1 = Worksheets("Validation")

For Each rngProjects In ws1.Range("Projects")

Me.cboProject.AddItem rngProjects.Value
Me.cboAccount.AddItem rngProjects.Value

Next rngProjects

'Add static data for combobox
Me.cboTransactionType.AddItem "Income"
Me.cboTransactionType.AddItem "Expense"

A: It seems to me that either the sheet name changed (sometimes a leading or trailing space is not recognizable) or the name for the named range changed. Furthermore, it could also be that the named range moved to another sheet (other than the validation sheet).
If you check all of the above and furthermore use explicit references as suggested in the comments then you should be able to find the problem. Here is your code with some additional checks. Give it a try and let us know if this works or made you aware of the problem.
Option Explicit

Private Sub UserForm_Initialize()
'Set Variables to populate combobox
Dim rngProjects As Range
Dim ws1 As Worksheet
Dim bolFound As Boolean
Dim nm As Name

For Each ws1 In ThisWorkbook.Worksheets
    If ws1.Name = "Validation" Then bolFound = True
Next ws1
If bolFound = False Then
    MsgBox "Required sheet not found."
    Exit Sub
End If

Set ws1 = Worksheets("Validation")

For Each rngProjects In ws1.Range(ws1.Cells(8, 1), ws1.Cells(ws1.Rows.Count, 1).End(xlUp))
    frmAddTransaction.cboProject.AddItem rngProjects.Value
    frmAddTransaction.cboAccount.AddItem rngProjects.Value
Next rngProjects

'Add static data for combobox
frmAddTransaction.cboTransactionType.AddItem "Income"
frmAddTransaction.cboTransactionType.AddItem "Expense"

End Sub

As commented below, the indirect named range has been removed. Instead, the sheet is now directly referenced in the code. Like this any change of the named range will have no impact on the code. Instead, the offset of 8 rows is written in the VBA where it is slightly more secure.


text:
Q: Xamarin Android, Bluetooth conection not working I am trying to do a simple bluetooth connection Using Xamarin studio. My code builds sucessfully but raises a Java.IO.IOExeption When I try to connect the bluetooth.
This is a snippet from my code.
    BluetoothAdapter  BluetoothAdapter1 = BluetoothAdapter.DefaultAdapter;
    BluetoothSocket socket;
    BluetoothDevice device
    btnConnect.Click += async delegate {
            if (BluetoothAdapter1 == null)
            {
                AlertDialog1.SetMessage("Device Does not support bluetooth");

                AlertDialog1.Show();
            }

            if(!BluetoothAdapter1.IsEnabled)
            {
                AlertDialog1.SetMessage("Bluetooth is not enabled");
                AlertDialog1.Show();
            }

            else{

                device = (from bd in BluetoothAdapter1.BondedDevices where bd.Name == "GT-N8000" select bd).FirstOrDefault();

                if(device == null)
                {
                    AlertDialog1.SetMessage("Device Not Found \n Make sure you are paired to the bluetooth device");
                    AlertDialog1.Show();

                }

                else
                {
                    ParcelUuid[] list = device.GetUuids();
                    String MyUUID = list[0].ToString();

                    try
                    {
                    socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString(MyUUID));

                        socket.Connect();
                    btnConnect.Text = socket.RemoteDevice.Name;

                    socket.Close();
                }

                    catch (Exception e)
                    {
                        AlertDialog1.SetMessage(e.Message);
                        AlertDialog1.Show();
                    }

                }
            }

This is some of my Output from the log.
[Mono] Assembly Ref addref MatrixDisplay[0xb8da14b8] -> System.Core[0xb8e6b7e0]: 3
[BluetoothAdapter] 584852085: getState(). Returning 12
[BluetoothAdapter] getBluetoothService() called with no BluetoothManagerCallback
[Choreographer] Skipped 295 frames!  The application may be doing too much work on its main thread.
[ViewRootImpl] Dropping event due to root view being removed: MotionEvent { action=ACTION_MOVE, id[0]=0, x[0]=599.4283, y[0]=596.4481, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=328245301, downTime=328245292, deviceId=1, source=0x1002 }
[InputEventReceiver] Attempted to finish an input event but the input event receiver has already been disposed.
[InputEventReceiver] Attempted to finish an input event but the input event receiver has already been disposed.

A: I solved this by not closing the socket immediately  after  connecting.


text:
Q: Can't execute yolo/darknet from php exec - predictions.png never appears? YOLO: https://github.com/pjreddie/darknet
I'm trying to run this from within a php script, but predictions.png never appears.  I assume this is a general problem with my understanding of how exec works, rather than how YOLO works.
I've changed the permissions and users on all relevant folders and directories to nginx/777.  I know that's not ideal but it's a troubleshooting step!
What happens when calling darknet from the terminal:
Logging output appears on the screen, and at the end of the process a file called predictions.php should be created in the /darknet directory.  When running this from PHP in the browser I don't care about the logging output, I just want the png file to be created.
Works:
/darknet/darknet detect /darknet/cfg/yolo.cfg /darknet/yolo.weights /path/to/photo.jpg

Works:
sudo -u nginx php71 -r 'exec("/darknet/darknet detect /darknet/cfg/yolo.cfg /darknet/yolo.weights /path/to/photo.jpg");'

Works from commandline (php71 myfile.php), but not in the browser:
<?php
exec("/darknet/darknet detect /darknet/cfg/yolo.cfg /darknet/yolo.weights /path/to/photo.jpg");

What am I doing wrong?


text:
Q: Raycaster-intersected events for glb model children I am loading a glb model as shown below:
<a-scene>
    <a-assets>
        <a-asset-item id="tree" src="/path/to/tree.gltf"></a-asset-item>
    </a-assets>
    <a-entity gltf-model="#tree"></a-entity>
</a-scene>

I am selecting the model by querySelector in JavaScript and attaching raycaster-intersected event to the modelEl. But this event doesn't get triggered when I hover from one child node to another child node inside the glb model. Anyone please help me with this.

A: This method works with primitive entities, but gltf-model entities work a little differently. That is because the gltf-model entity contains many child objects, so you need to write a custom component to get a reference to the models that you want to intersect with a raycaster and test them for intersection. In that component, you loop through all the child models using traverse, like this
 AFRAME.registerComponent('treeman', {
            init: function(){
                let el = this.el;
                let self = this;
                self.trees = [];
                el.addEventListener("model-loaded", e =>{
                    let tree3D = el.getObject3D('mesh');
                    if (!tree3D){return;}
                  //console.log('tree3D', tree3D);
                    tree3D.traverse(function(node){
                        if (node.isMesh){
                          console.log(node);
                          self.trees.push(node);
                          node.material = new THREE.MeshStandardMaterial({color: 0x33aa00});
                        }
                    });
              });

Then you can test for intersection with a 'raycaster-intersected' event listener, like this
  el.addEventListener('raycaster-intersected', e =>{
                self.raycaster = e.detail.el;
                let intersection = self.raycaster.components.raycaster.getIntersection(el);
                  console.log('click', intersection.object.name, self.mouseOverObject,
                            intersection.object.name != self.mouseOverObject );
                if (self.mouseOverObject != intersection.object.name){
                  intersection.object.material.emissive = new THREE.Color(0xFFFF00);
                  intersection.object.material.emissiveIntensity = 0.5;
                } else {
                   intersection.object.material.emissive = new THREE.Color(0x000000);
                  intersection.object.material.emissiveIntensity = 0.0;
                }
                  self.mouseOverObject = intersection.object.name;
              });

And do something on click event like this
 el.addEventListener('click', function(){
                console.log(self.mouseOverObject);
                if(self.mouseOverObject === "Trunk_A"){
                  //console.log('link');
                  let url = 'https://supermedium.com/supercraft/';
                  let win = window.open(url, '_blank');
                  win.focus();
                }
              });

here is a glitch


text:
Q: the backgroung image not showing up in browser I have used background-image its being detected in the chrome but not getting displayed in the browser.can anyone help
thanks in advance.
css
.home-inner
{
    background-image: url(../images/Slider/Slider.jpg);
}

html

A:

.home-inner{
  width: 100vw;
  height: 100vh;
  background-size: cover;
background-position: center;
  background-image: url("http://coursehd.com/wp-content/uploads/2016/05/5-tips-market-yourself-elearning-professional.jpg"); }

A: Give image path should be inside sinle / double quotation. And also check the directory path.
background-image: url("../images/Slider/Slider.jpg");


text:
Q: Screen scraping: how to get the image I'm working on a screen scraper to archive card data for a game I play.
Here's one of the pages: http://imperialassembly.com/oracle/#cardid=1,#hashid=1fc816f7545c2bd39f6cc7737803644c,#cardcount=2
This is my first screen scraper and it's been a lot easier than I initially expected, however I'm not quite sure how to go about getting the image file.  When I inspect the card picture, this is the html element that comes up:
<img width="428" height="600" src="showimage?prefix=printing&cardid=1&nestid=1&class=details&tagid=34&hash=4c/a4,428,600,image/jpeg">

How would I go about getting the actual file?
In my code I am just using an HtmlDocument object to get at the HtmlElement's.


text:
Q: Julia | Push or Append in 2 Dimensional Array I am trying to push or append elements from a 2 dimensional array to a 3 dimensional array. The array 2 (2nd dimension) is associated with an index that goes like this [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5...] and I would like the last element of the same index to be pushed / appended to array 1, that is the 1st, the 3rd, the 6th, the 10th elements etc.. Here is the MWE:
arr1 = Array{Float64,3}(length, per, ro)
arr2 = Array{Float64,2}(length, per * ro * (ro + 1) ÷ 2)

length = 100
per = 20
ro = 10

for l in 1:length
    for p in 1:per
        for r in 1:ro

         x = arr2[l, p * ro * (ro + 1) ÷ 2]
         push!(arr1, x)

        end
    end
end

Thank you for your time.
Λ


text:
Q: Shared experience in solidarity, describe mother's act, son can't eat before surgery, she decides to fast too, in solidarity and shared experience I want to describe a mother's act for her child, who is not allowed to eat before surgery and she chooses not to eat also, so I have thought of solidarity or support, but I want to also describe sharing this experience with her child.  They both feel the hunger together, the child must and the mother chooses.

Mom was fasting in solidarity with her child who was NPO before the procedure.

A: I would suggest co-suffering but you could also combin it with love:

Mom was fasting in co-suffering (love) with her child who was NPO before the procedure.

You will find co-sufferer in dictionaries with the meaning:

One who suffers with another. (FreeDict)

This is in fact also the etymological meaning of compassion (suffering with another), but this word is more used to describe a feeling, or state, not taking action, like co-suffering does.

A: The words "solidarity" and "support" have connotations that are somewhat  too formal, I would say, but they might be used. Instead, I'd use the plain verb "to join".

(OAlD)
[transitive] to take part in something that somebody else is doing or to go somewhere with them
join somebody
• Do you mind if I join you?
join somebody for something
• Will you join us for lunch?
join somebody + adv./prep
• They've invited us to join them on their yacht.
• He joined her downstairs a few minutes later.
join something
• Over 200 members of staff joined the strike.
•  Members of the public joined the search for the missing boy.
join somebody in doing something
• I'm sure you'll all join me in wishing Ted and Laura a very happy marriage.

*

*Mom joined her child in fasting so as to give strength to him  who was NPO before the procedure.

A: "Sympathetic" has a meaningful parallel in the sense that twins are said to have "sympathetic pain," (one quite literally experiences the suffering of the other) in that the Mother is undertaking the same trevail in an effort to comfort her child.  It may need some additional syntax to make it work but it makes for a powerful image.


text:
Q: How should I power these components at different voltages? I'll be using a 12V power source, as this is an automotive application.
I have the following components:

*

*ATmega2560, 1.8V-5.5V, 200mA (actually an Arduino Mega 2560, as I couldn't find a through-hole AVR with four UARTs)

*GPS module, 3.3V-5V with 5V-safe inputs, 20mA

*GSM module, 3.4V-4.5V (4.0V is recommended), 3.3V logic, 2A peak

*MCP2515 CAN controller, 2.7V-5.5V, 5mA

*MCP2551 CAN tranceiver, 4.5V-5.5V, 75mA

Everything would be a nice, easy 5V if it weren't for the GSM module, which wants around 4V. So should I use two regulators (a 5V one and an adjustable one set to 4V)? Or if I already have a 5V regulator, is it possible to just use a voltage divider after that for the 4V?
I plan to use a 4050 for level conversion from the MCU to the GSM module (the MCU at 5V reads 3.3V as high).
Would I also require a heatsink? The Arduino's regulator doesn't have one, but it gets hot given a 12V supply.

A: I have similar project.
I did it with two voltages. First I put the switching regulator to drop to 3.9V for GSM. Then LDO to drop from 3.9V to 3.3V for MCU, GPS, CAN.
I see the GPS module you pointed out possibly has it's own LDO on board and that's why its voltage ranges from 3.3V. Take a look on those modules alone http://www.gtop-tech.com/en/category/GPS-Antenna-Module/A01_MT3339.html they all go from 3.0V so both voltages could be used (3.9V or 3.3V).
For CAN tranceiver I used SN65HVD230D from Texas Instruments, which is a little more expensive but works with 3.3V (that eliminated necessity of third 5V supply).
Don't use voltage dividers for supplying power. The load connected to this divider acts like another resistor in parallel with one from divider. If the load you connect is mcu or some module, the impedance is unknown and variable in time - you wont be able to achieve desired voltage.
Voltage dividers are good if you connect some high impedance line to it. Then almost no current flow through that line and the voltage at the divider stays at the level it was set. This should be fine in case you need to lower some logic levels (you mentioned 4050 which is a good solution).
You might also need some protection circuit at the power input, before the voltage regulator. Automotive power can have load dumps (100V on power line for about 400ms), positive and negative voltage transients. Cold crank condition can lower the voltage to 3V for 15ms. Jump start can raise it to 24V.

A: I would use a 5V switching DC/DC converter with a TVS diode and a capacitor in front of it to guard against load dumps on the 12V rail. You then have the option of an adjustable LDO (with > 2A capacity!) from the 5V rail (which would put more load on the 5V DC/DC converter, too) or a separate 4V switching DC/DC converter with similar TVS and capacitor protection.
All the 5V things can easily be driven by a single Murata OKI-78SR, which is a TO-220 form factor switching DC DC converter that generates 5V/1.5A out, and costs < $5 in quantity 1. (Sweet!)
The 4V is harder. 2A is a fair bit of current. You can burn it all off from 12V with a LM350 adjustable regulator (3A rated) with a heat sink. Or you can design a switching regulator on your own that targets 4V out. Or, if this is a large-quantity design, talk to suppliers like GE or Murata or Recom to see if they can make a custom part for you, so you don't have to.
Another option is to get a 3A+ converter to get 5V out (they range about $40 up from DigiKey in quantity 1) and linear regulator down to 4V. Check out the CUI VYB10W-Q24-S5-T. Note that you'd need a LDO regulator with drop-out at 1.2V or lower to get to 3.8V. Finding one of those that can do 2A is a little harder. Try something like a MIC29302AWU perhaps, realizing that it only goes up to 16V for input, which a car 12V rail can temporarily go way above (see above about load dumps.)

A: All the ASIC's whether it be Atmega, GSM Module, GPS Module, CAN Transceiver and Controller will come with the ratings of MIN, MAX and TYPICAL supply. But, for the proper and best functioning of any of the modules or ASIC always feed the TYPICAL supply input mentioned in the datasheet.
If its some industrial design, don't use dividers to feed power supply to ASIC's or modules, as it may not deliver the expected power.
Go with the power consumption analysis of the system and design your power supply using LDO or DC-DC Converters.


text:
Q: Multi-OS imaging strategy I've been backup up my Windows system to an external 2TB WD drive for a while, but not my CentOS server. Most of the code I write lives on GitHub so I haven't been concerned about it. I'm currently working on setting up some machine learning services on my CentOS server and the setup and configuration is long and painful, so I've decided I need to start backing up my server too.
Currently I wake the Windows machine at 3AM and take the image, as I have 4 drives on it, and backup that image. Is there any benefits to moving my external backup drive (which is USB connected) to the server and use CentOS as the backup controller, or should I keep the drive connected to windows and backup the server to it?
If I leave the device where it is, my thought is that I'd like to adopt the same strategy, in that I'll take a disk image of the server and back that up over the network to the Windows machine.
Are there any issues with this approach? Is it better to use Windows to image the drive and send it across the network to CentOS?
Any other issues I should take into consideration?
Can I mount a network drive on the Windows machine that points to a folder on the CentOS machine that I can drop a backup image in?
I'm a developer not a sysadmin, so I know my way around my server, but I'm still getting used to administering it.
Thanks for any and all help.
Paul


text:
Q: Как описать модель данных в UML? Есть заказчик, который занимается on-line продажей виски класса премиум.
В целях повышения продаж заказчик собирается заняться продажей подарочных коробок для виски.
Менеджер по продажам на стороне заказчика выбрал 5 типов подарочных коробок, которые будут представлены в интернет-магазине.
Клиент выставил функциональные требования к ПО:
На сайте интернет магазина необходимо показывать товар (виски) вместе с подходящей подарочной коробкой.
Коробки подобраны следующим образом:
Не все подарочные коробки подходят ко всем бутылкам, но каждая бутылка виски будет иметь по крайней мере одну подходящую подарочную коробку (может быть несколько).
С помощью каких диаграмм можно описать модель данных, которая позволит решить задачи проекта?
Быть может, стоит выбрать альтернативу UML? Подскажите.

A: Возможно подойдёт диаграмма классов, где ваши бутылки и коробки будут классами с атрибутами,соединенные связями один ко многим, один к одному и т.д. Нужно грамотно оформить только


text:
Q: Nested NavigationFrame in Silverlight App (Multi animation) I would like to build a navigation enabled Silverlight app with a slight difference. I don't want to load the entire screen area just a part of it and only in some scenarios.
For example #/Customer/Cases loads /Customer/Cases.xaml in the entire screen area. But #/Customer/Cases/Orders loads /Customer/Cases/Orders.xaml in an area where a data grid was displayed (slides to the right maybe).
How do I tell the parent navigation frame not to load the entire #URL but just a part of it? And vis versa for the child navigation frame?
Has anyone done anything like this before?
Please let me know if doesn't make any sense, it's quite hard to explain :)

A: One possibility would be to have two frames.
In the inner-frame you set:
InnerFrame.JournalOwnership = JournalOwnership.OwnsJournal;

The link #/Customer/Cases/Orders loads the page /Customer/Cases.xaml?Orders in the outer-frame. The outer-frame than knows it should navigate the inner frame to /Customer/Cases/Orders.xaml

A: Check out Ultimate Framework - Silverlight Navigation Framework that supports unlimited parallel and nested frames with Prism


text:
Q: Find sum of subset with multiplication Let's say we have got a set
{a_1, a_2, a_3, ..., a_n}

The goal is to find a sum that we create in the following way: We find all subsets whose length is 3, then multiply each subset's elements (for the subset {b_1, b_2, b_3} the result will be b_1*b_2*b_3). At the end we sum up all these products.
I am looking for a shortest time-execution algorithm.
Example
SET: {3, 2, 1, 2}

Let S be our sum.

S = 3*2*1 + 3*2*2 + 2*1*2 + 3*1*2 = 28

A: Here is an O(n^2) approach:
sum = SUM(list)
answer = 0
for each i from 0 to n:
   sum -= list[i]
   remains = sum
   for each j from i+1 to n:
      remains -= list[j]
      answer += list[i] * list[j] * (remains)

It works because for each two elements x,y you need to sum x*y*z (for all elements z), but the sum of all possible z values is SUM(list) - x - y.
So, instead of doing: x*y*z1 + x*y*z2 + ... + x*y*z(n-2) , you basically do x*y*(z1 + ... + z(n-2))
EDIT: Editted multi-counting due to not multiplying only in the 'tail', as mentioned by @AbhishekBansal . You need to multiply each element only with the 'tail' of the list, where the tail is all the elements after the last element among x,y.

A: Full Working Code in C++ (Following up on Amit's idea)
#include <iostream>

using namespace std;

int main()
{
    int s[] = {3, 2, 1, 2};

    double sumOfFullList = 0;
    for ( int i = 0; i < 4; i++ )
        sumOfFullList += s[i];

    double sum = 0;

    for ( int i = 0; i < 4; i++ ) {
      double sumOfList = sumOfFullList - s[i];
      sumOfFullList -= s[i];
      for ( int j = i+1; j < 4; j++ ) {
          sumOfList -= s[j];
          sum += s[i]*s[j]*(sumOfList);
          //cout << s[i] << " " << s[j] << " " << sumOfList;
      }
    }

    cout << sum << endl;
    return 0;
}

Output:
28

A: It is easier to calculate sum of multiplied triplets when repetitions are allowed (like a_1*a_1*a_1). This sum is just (sum^3).
Since repetitions are not allowed, we could just subtract them: (sum^3 - 3*sumsquares*sum).
But the above formula subtracts elements on main diagonal 3 times while it should be subtracted only once. Need to compensate this: (sum^3 - 3*sumsquares*sum + 2*sumcubes).
The above formula does not take into account 3! permutations of each triplet. So it should be divided by 3!.
Finally we have a linear-time algorithm:

*

*Compute sum of given multiset elements, sum of squares, sum of cubes.

*result = (sum^3 - 3*sumsquares*sum + 2*sumcubes)/6


text:
Q: How does the real time clock in Motherboard of a computer function in relation to the operating system Out of curiosity, I did a few readings online about how a computer keeps track of time, without being powered (and not being connected to the internet).
Of what I learnt, there is a special micro-processor having a crystal oscillator, keeping track of seconds, milliseconds etc. that reflects when a computer is switched on, hence displaying the precisely right time.
A few questions I have,
How is this clock related to the operating system? Is it's initialization included in the bootstrap program?
What are the different ways how the Operating System can vary this time, reflecting faulty time?
Also, many a times we switch on a computer the time displayed is wrong. Is this only because of failure of motherboard battery or failure of the oscillator itself?
Lastly,
Varying this time is a privileged function or not?

A:
How is this clock related to the operating system?

One of the first devices accessed by the BIOS is the Real Time Clock, it is accessed through one of the ports, a common I/O address assignment is 0x70.


text:
Q: How to place legend next to each line in matplitlib Here is my plot, you can see that there is over 15 lines in a plot, although I put a legend in the top right corner, I still can not easily differentiate each line.
Is there a better way of doing this? for example, put legend next each line? I can not find a API. any help is appreciated.

You can

A: The comment is indeed what you need. This post is just to make a solution a bit more explicit.
Using annotate a label can be placed at a specific position. I.e. it can be placed based on the coordinates of the last point of the curve, e.g. (xlast, ylast). To make the plot more pretty, the horizontal position can increased by e.g. 2% to place the label at a small distance from the last point (i.e. the label is placed at (1.02*xlast, ylast)).
In a small example:
import numpy             as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x     = np.linspace(0,1,2)
y     = 1*x
label = '1x'
color = 'b'

ax.plot(x, y, color=color)

ax.annotate(label,
  xy     = (     x[-1], y[-1]),
  xytext = (1.02*x[-1], y[-1]),
  color  = color,
)

x     = np.linspace(0,1,2)
y     = 2*x
label = '2x'
color = 'r'

ax.plot(x, y, color=color)

ax.annotate(label,
  xy     = (     x[-1], y[-1]),
  xytext = (1.02*x[-1], y[-1]),
  color  = color,
)

ax.set_xlim([0,1.2])

ax.set_xlabel('x')
ax.set_ylabel('y')

plt.savefig('so.png')
plt.show()

Which results in:


text:
Q: Find out the Duplicate Records in Sql-server In our application, we have some tables storing staff data. I need to find out whether the same office is allocated to a staff member multiple times. How can I figure this out in SQL Server?
I have tried below query but it didn't give me the correct solution.
SELECT DISTINCT STAFFID, officeid
FROM [stafftable]
WHERE rowstatus = 'A'
GROUP BY STAFFID, officeid
HAVING COUNT(staffid) > 1
    AND COUNT(officeid) > 1
ORDER BY STAFFID, officeid

It returns the staff members allocated to different offices also.  Any help would be greatly appreciated.

A: You can use COUNT(*) to count all rows in each group:
SELECT STAFFID, officeid
FROM [stafftable]
WHERE rowstatus = 'A'
GROUP BY STAFFID, officeid
HAVING COUNT(*) > 1
ORDER BY STAFFID, officeid

A: SELECT *
FROM (
    SELECT *, RowNum = ROW_NUMBER() OVER (PARTITION BY STAFFID, officeid ORDER BY STAFFID)
    FROM dbo.stafftable
    WHERE rowstatus = 'A'
) t
WHERE t.RowNum > 1

A: ;With cte
as (
select * row_number() over(partition by STAFFID, officeid )as count from stafftable
where rowstatus = 'A'
)
select * from cte where count > 1


text:
Q: VB.NET DataGrid not showing first row data from database I am trying to populate my database table in a datagrid.
Now I am able to populate it but the problem here is it only showing the second row data onwards only. The first row data is not showing in the table.
I double checked my database table its showing I have 3 rows of data but in the datagrid its only showing 2 rows of data only. I did my research on the web before asking the question here but I could not find any solution from the web search.
Here is my xaml code:
<Grid Background="#FF006E8C">
    <Separator HorizontalAlignment="Left" Height="100" Margin="0,60,0,0" VerticalAlignment="Top" Width="695" FontSize="16" Background="White"/>
    <Label x:Name="labelLoginName" Content="Label" HorizontalAlignment="Left" Margin="552,125,0,0" VerticalAlignment="Top"/>
    <DataGrid x:Name="userDataGrid" HorizontalAlignment="Left" Margin="35,146,0,0" VerticalAlignment="Top" Height="265" Width="640"/>

</Grid>

Here is my vb code:
Private Sub Windows_Loaded(sender As Object, e As RoutedEventArgs)
    labelLogin = loginName
    labelLoginName.Content = labelLogin
    Dim query As String
    query = "select * from users"
    reader = db.QueryCommand(query)

    If Not IsNothing(reader) Then
        If reader.HasRows() Then
            While reader.Read()
                userDataGrid.ItemsSource = reader
            End While
        Else
            MessageBox.Show("No data")
        End If
    Else
        MessageBox.Show("Error at reader")
    End If

Can someone help me on this please. I did this by following the tutorial from this tutorial video in youtube: here
Tq.

A: I was able to solved it by removing the while loop from my function.
If Not IsNothing(reader) Then
    If reader.HasRows() Then
        userDataGrid.ItemsSource = reader
    Else
        MessageBox.Show("No data")
    End If
Else
    MessageBox.Show("Error at reader")
End If


text:
Q: QML Button assign arrow shortcut Is it possible to assign an arrow shortcut to a QML Button? With the Action item I can assign a shortcut by string or by KeySequence (https://doc.qt.io/qt-6/qml-qtquick-controls2-action.html#shortcut-prop), but how can I assign a shortcut of an arrow?

A: you can use Shortcut ,like this :
import QtQuick
import QtQuick.Controls 2.15

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Shortcut")

    Button {
        id: button
        x: 199
        y: 144
        width: 190
        height: 105
        text: qsTr("Button")
        Shortcut
        {
            sequence:"Up" // "Down" , "Right" ,"Left"
            onActivated:button.clicked()
        }

        onClicked:
        {
            console.log("Up Arrow")
        }
    }

}

"Up" ↑, "Down" ↓, "Right"→ ,"Left"← used for Arrows in keyboard.


text:
Q: How to implement Facebook Login for multiple apps with a custom backend? I work for a company that has a suite of 5 iOS and 5 Android apps. They all talk to common API we built. We support traditional email/password account creation and login, but we also support Facebook login in parallel. Given the impending Graph API v2.0 changes, I figured this would be a good time to audit our implementation of Facebook Login to bring it up to the latest standards.
What I haven't been able to find in the Facebook Developers portal is a good high-level overview of what we should be doing given our particular circumstances:

*

*we have multiple mobile apps authenticated with shared accounts

*we use facebook login alongside email/password accounts

*we have custom backend API that all the apps talk to

Here's a simplified walkthrough of our current implementation of FB Login:

*

*App prompts user to login with FB (or enter email to login/create account)

*If user clicks FB button, FB's login magic happens, and the app gets a token which it passes to our API

*API server calls /me using the facebook-php-sdk in order to get the user's graph id, name, and email

*

*If we don't get an email back, FB login fails

*Using the email from FB, we look to see if we already have an account with that email

*

*If no account exists with that email, we create a new account using that email and name

*Once we have a user account (either through creation or lookup), we store the token with that account (unique to the app)

*At this point we tell the app that the user successfully authenticated

What should we be doing? Should we even bother storing the FB token?

A: Instead of checking email for a user on the server, I would have gone for the userid (why let those 2-3% of users leave your app just because we can't fetch their email ids).
But anyhow with v2 in picture, we can't get original id of user; the ids returned are app-scoped now!
Now coming to your question.

*

*You should save the these app scoped ids in your database (may be one-many mapping). And since you are only registering the users with email id that wont be a problem at all.
Benefits? You can access to their profile data easily at any point without any problem with /<id>?access_token=<app-access-token>

*Saving user access token don't make any sense to me since it expires in approx 2 hours. Although you can extend the validity of the user access token but you can anytime get a fresh token on client side itself. So store this only if you are doing some stuff/manipulation on server that's important to you.

*If you are looking for posting Open Graph stories or normal feed on the user's profile when the user's session is not active, you can use the app access token to publish.


text:
Q: PHPPowerpoint must display Slide Number I have a question of using GetSlideNumber and SetSlideNumber in PHPPowerpoint is that the function code to display page number in the every slide? Need help to use that code or proper way in order to display the slide number. Thank you

A: you will be able to get and set page number use following example.
http://phpoffice.github.io/PHPPowerPoint/docs/master/classes/PhpOffice.PhpPowerpoint.Slide.html


text:
Q: Parsing in block a YAML File I have a yaml file that is currently written as:
host: hostname
resource:
      File:
        title: "file"
        containment_path:
        - Test
        - Test::Value
        tags:
        - file
        failed: false
        skipped: false
        corrective_change: false
      Exec:
        title: Exec
        containment_path:
        - Test
        - Value::Test
        tags:
        - exec
        failed: true
        skipped: false
        corrective_change: false

Then the values in resource like File and Exec can be different each time
I use this structure to parse my YAML data
    type YamlResource struct {
        Host                 string        `yaml:"host"`
        Resource             []Resource    `yaml:"resource"`
    }

    type Resource struct {
        ContainmentPath      string        `yaml:"containment_path"`
        Skipped              bool          `yaml:"skipped"`
        Failed               bool          `yaml:"failed"`
    }

func ScanningYAMLModulesStatus(filename string) (YamlModulesStatus, error) {

    f, err := os.Open(filename)
    if err != nil {
        fmt.Println("Error reading YAML ", filename, ": ", err)
    }
    defer f.Close()

    scanner := bufio.NewScanner(f)
    isRecord := false
    data := ""
    for scanner.Scan() {
        line := scanner.Text()
        if strings.Contains(scanner.Text(), "host:") {
            data += line + "\n"
        }
        if strings.Contains(scanner.Text(), "resource:") {
            isRecord = true
        }
        if strings.Contains(scanner.Text(), "corrective_change:") {
            break
        }
        if isRecord {
            data += line + "\n"
        }
    }

    if err := scanner.Err(); err != nil {
        fmt.Println("Error scanning YAML ", filename, ": ", err)
    }

    var ConfigResource YamlResource
    if err = yaml.Unmarshal([]byte(data), &ConfigResource); err != nil {
        fmt.Println("Error parsing YAML ", filename, ": ", err)
    }
    return ConfigResource, err
}

I get this error and I would like to parse the resources by block because I have a lot of data such as a File block, an Exec block and I can't modify my YAML file
I use package "gopkg.in/yaml.v2"
line 3: cannot unmarshal !!map into []main.YamlResource

How can I do this in Go, to parse File, Exec and others ?
Thanks

A: Looks like the to be unmarshalled struct definition is mismatching as suggested in comments.
I have refactored the code to correct struct definitions. The working code can be found here on playground. Link
type YamlResource struct {
    Host     string   `yaml:"host"`
    Resource Resource `yaml:"resource"`
}

type Resource struct {
    File File `yaml:"File"`
    Exec Exec `yaml:"Exec"`
}

type Exec struct {
    ContainmentPath []string `yaml:"containment_path"`
    Skipped         bool     `yaml:"skipped"`
    Failed          bool     `yaml:"failed"`
}

type File struct {
    ContainmentPath []string `yaml:"containment_path"`
    Skipped         bool     `yaml:"skipped"`
    Failed          bool     `yaml:"failed"`
}


text:
Q: Add element to a dictionary by input Python I need to create a dictionary like this using user's input:
a = {
'1': {'2': 2, '3': 5, '4': 1},
'2': {'1': 2, '3': 2, '4':4},
'3': {'1': 5, '2':2},
'4': {'1': 1, '2': 4, '5':3},
'5': {'4':3}}

For example, in input I have to write "2 2 3 5 4 1" and these values goes to index N. 1 "{'1': {'2': 2, '3': 5, '4': 1}"
I've been trying to do this for a while but I couldn't succeed.
I've tried to use a for and split the list in many arguments but still I have concluded nothing.
Thanks for any answer.

A: You can add an element to dict using this code:
dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
dict[index] = [7, 8, 9]

A: One way is to use str.split and utilise itertools.islice:
from itertools import islice

input_str = '2 2 3 5 4 1'

def zipper(mystr):
    split = mystr.split()
    return zip(islice(split, 0, None, 2), islice(split, 1, None, 2))

d = {}
d['1'] = dict({k: int(v) for k, v in zipper(input_str)})

# {'1': {'2': 2, '3': 5, '4': 1}}

A: Use input to get the data, and split to break it at spaces:
response = input('Enter digits separated by spaces').split()

Now a loop that continues until the user doesn't provide any more input:
while response:
    payload = response[:-1]   # all but the last number
    index = response[-1]      # this is your dictionary key
    # Now count the repetitions in the user's input and assign to a[index]
    a[index] = {k: payload.count(k) for k in payload}
    # And ask for more input
    response = input('Enter more digits (press Enter to finish)').split()

Then display your results:
print(a)


text:
Q: Can double generating functions be used to solve this? I was really interested in this question here
What is the expected number of red apples left when all the green apples are picked?

We have 4 green apples and 60 red apples. Each time we pick one out
  without replacement. Then what is the expected number of red apples
  left when all 4 green apples are picked?

I tried to use generating functions to get a closed form. I wrote a recurrence for the expected number of red apples like this (and I've verified that it is correct):
$$E(r,g) = \frac{r}{r+g}E(r-1,g) + \frac{g}{r+g}E(r,g-1)$$
and $E(0,g) = 0$ and $E(r,0) = r$.
So I did this
$$G(x) = \sum_{r=0}^{\infty} \sum_{g=0}^{\infty} E(r,g) x^r y^g$$
and tried expanding it out and shifting indices and taking derivatives but it was a huge mess and I had no confidence in what I was doing. Can generating functions be used here to get the closed form $E(r,g) = \frac{r}{g+1}$? I noticed this pattern by inspection and used induction to prove that the closed form was correct, but I wanted to know how to actually derive it using generating functions.

A: [2016-08-13]:  A different way to proceed from the  PDE in (5), independent of other answers is stated  here. Coefficient extraction added at the end of this answer.

OPs recurrence relation is fine (if we additionally specify the range of validity) and we can derive a generating function from it.

We start by recalling the recurrence relation
  \begin{align*}
(r+g)E(r,g)&=rE(r-1,g)+gE(r,g-1)\qquad\qquad &r,g\geq 1\tag{1}\\
E(r,0)&=r &r\geq 0\\
E(0,g)&=0 &g\geq 0\\
\end{align*}

In the following we consider each term of the recurrence relation separately.
It is also convenient to use the differential operator $D_x:= \frac{d}{dx}$ and $D_y:=\frac{d}{dy}$.

With the Ansatz
  \begin{align*}
G(x,y)=\sum_{r=0}^\infty\sum_{g=0}^\infty E(r,g)x^ry^g
\end{align*}
we obtain
  \begin{align*}
\sum_{r=1}^\infty&\sum_{g=1}^\infty(r+g)E(r,g)x^ry^g\tag{2}\\
&=(xD_x+yD_y)\sum_{r=1}^\infty\sum_{g=1}^\infty E(r,g)x^ry^g\tag{3}\\
&=(xD_x+yD_y)\left(G(x,y)-\sum_{g=0}^\infty E(0,g)y^g-\sum_{r=0}^\infty E(r,0)x^r+E(0,0)\right)\\
&=(xD_x+yD_y)\left(G(x,y)-\sum_{r=0}^\infty rx^r\right)\\
&=(xD_x+yD_y)\left(G(x,y)-(xD_x)\frac{1}{1-x}\right)\\
&=(xD_x+yD_y)G(x,y)-(xD_x)^2\frac{1}{1-x}\tag{4}\\
\end{align*}

Comment:

*

*In (2) we have to respect the validity of the recurrence relation and start with $r=g=1$ accordingly

*In (3) we use the operator $(xD_x)$ to transform a series $\sum_{r=1}^\infty a_r x^r$ to $\sum_{r=1}^\infty r a_r x^r$

*In (4) we use the linearity of the differential operator and since the geometric series is a function in $x$ the operator $yD_y$ transforms it to $0$.
Now we consider the the first summand of the RHS of (1).

\begin{align*}
\sum_{r=1}^\infty&\sum_{g=1}^\infty rE(r-1,g)x^ry^g\\
&=xD_x\sum_{r=1}^\infty\sum_{g=1}^\infty E(r-1,g)x^ry^g\\
&=xD_x\sum_{r=0}^\infty\sum_{g=1}^\infty E(r,g)x^{r+1}y^g\\
&=xD_xx\left(G(x,y)-\sum_{r=0}^\infty E(r,0)x^r\right)\\
&=xD_xx\left(G(x,y)-\sum_{r=0}^\infty r x^r\right)\\
&=xD_xxG(x,y)-xD_xx^2D_x\frac{1}{1-x}\\
\end{align*}

and  now the other summand of the RHS of (1).

\begin{align*}
\sum_{r=1}^\infty&\sum_{g=1}^\infty gE(r,g-1)x^ry^g\\
&=yD_y\sum_{r=1}^\infty\sum_{g=1}^\infty E(r,g-1)x^ry^g\\
&=yD_y\sum_{r=1}^\infty\sum_{g=0}^\infty E(r,g)x^ry^{g+1}\\
&=yD_yy\left(G(x,y)-\sum_{g=0}^\infty E(0,g)y^g\right)\\
&=yD_y yG(x,y)
\end{align*}

Putting all three expressions together we obtain

\begin{align*}
(xD_x+yD_y)&G(x,y)-(xD_x)^2\frac{1}{1-x}\\
&=xD_xxG(x,y)-xD_xx^2D_x\frac{1}{1-x}+yD_y yG(x,y)\\
(xD_x+yD_y&-xD_xx-yD_y y)G(x,y)\\
&=\left((xD_x)^2-xD_xx^2D_x\right)\frac{1}{1-x}\\
(xD_x(1-x)&+yD_y(1-y))G(x,y)=(xD_x)(1-x)(xD_x)\frac{1}{1-x}
\end{align*}
  and finally
  \begin{align*}
(xD_x(1-x)&+yD_y(1-y))G(x,y)=\frac{x}{(1-x)^2}\tag{5}
\end{align*}

We see $G(x,y)$ fulfills a linear differential equation in two variables. Please find   here a different way to proceed. But in fact we need not necessarily try to solve it, since we already know from  @MarkoRiedels answer:
\begin{align*}
E(r,g)=\frac{r}{g+1}
\end{align*}

So, we do the easy way and calculate $G(x,y)$ this way
\begin{align*}
G(x,y)&=\sum_{r=0}^\infty\sum_{g=0}^\infty E(r,g)x^ry^g\\
&=\sum_{r=0}^\infty\sum_{g=0}^\infty \frac{r}{g+1}x^ry^g\\
&=\left(\sum_{r=0}^\infty rx^r\right)\left(\sum_{g=0}^\infty \frac{1}{g+1}y^g\right)\\
&=xD_x\frac{1}{1-x}\cdot\frac{1}{y}\int\frac{1}{1-y}\,dy\\
&=-\frac{x}{(1-x)^2}\cdot\frac{1}{y}\left(\ln(1-y)+C\right)\tag{6}\\
\end{align*}

In order to determine the integration constant $C$ we evaluate $G(x,y)$ at $\left(\frac{1}{2},\frac{1}{2}\right)$.

We obtain
  \begin{align*}
G\left(\frac{1}{2},\frac{1}{2}\right)
&=\sum_{r=0}^\infty r\left(\frac{1}{2}\right)^r\sum_{g=0}^\infty \frac{1}{g+1}\left(\frac{1}{2}\right)^g
=2\ln 4=4\ln 2
\end{align*}
  It follows together with (6)
  \begin{align*}
-4\left(\ln\frac{1}{2}+C\right)=4 \ln 2\qquad\longrightarrow\qquad C=0
\end{align*}
We finally conclude
  \begin{align*}
G(x,y)=-\frac{x}{(1-x)^2}\cdot\frac{\ln(1-y)}{y}
\end{align*}
  is a generating function for the sequence $\left(E(r,g)\right)_{r,g\geq 0}$ which fulfills the PDE (5).

[Update 2016-08-13]: According to OPs comments we extract the coefficient $E(r,g)$ from $G(x,y)$.
In order to do so, it's convenient to use the coefficient of operator $[x^r]$ to denote the coefficient of $x^r$ in a series $A(x)$.

We obtain for $r,g\geq 0$
  \begin{align*}
E(r,g)&=[x^ry^g]G(x,y)\\
&=[x^ry^g]\left(-\frac{x}{(1-x)^2}\cdot\frac{\ln(1-y)}{y}\right)\\
&=-[x^{r-1}y^{g+1}]\frac{\ln(1-y)}{(1-x)^2}\tag{1}\\
&=[x^{r-1}y^{g+1}]\sum_{k=0}^\infty\binom{-2}{k}(-x)^k\sum_{j=1}^\infty{\frac{1}{j}y^j}\tag{2}\\
&=\frac{1}{g+1}[x^{r-1}]\sum_{k=0}^\infty\binom{k+1}{1}x^k\tag{3}\\
&=\frac{r}{g+1}\tag{4}
\end{align*}

Comment:

*

*In (1) we use the rule $[x^p]x^qA(x)=[x^{p-q}]A(x)$.

*In (2) we apply the binomial series expansion and the use the series representation of $\ln(1-y)$.

*In (3) we select the coefficient of $y^{g+1}$ and use the binomial identity $\binom{-p}{q}=\binom{p+q-1}{p-1}(-1)^q$.

*In (4) we select the coefficient of $x^{r-1}$.

A: Suppose we have $G$ green apples  and $R$ red apples and ask about the
number of red apples left when all green apples have been picked.
In computing  a recurrence  for the expectation  $E(R, G)$  we note
that if the  sequence of samples ends in a $G$  the expected number of
red apples  left is  zero. If it  ends in  a $R$ it  is one  more than
$E(R-1, G).$ We obtain the recurrence
$$E(R, G) = {R+G\choose R}^{-1} {R-1+G\choose R-1}
(1 + E(R-1, G))$$
where $E(0, G) = 0.$ Now
$${R+G\choose R}^{-1} {R-1+G\choose R-1} =
\frac{(R-1+G)! R! G!}{(R+G)! (R-1)! G!}
= \frac{R}{R+G}$$
so this is
$$E(R, G) = \frac{R}{R+G}
(1 + E(R-1, G)).$$
We may drop the $G$ as an index variable as it never changes. We get
$$R E(R) + G E(R) = R + R E(R-1).$$
Introducing the generating function
$$F(z) = \sum_{R\ge 0} E(R) z^R$$
and multiplying by $z^R$ and summing over $R\ge 1$ we get
$$\sum_{R\ge 1} R z^R [z^R] F(z)
+ \sum_{R\ge 1} G z^R [z^R] F(z)
= \sum_{R\ge 1} R z^R
+ \sum_{R\ge 1} R z^R [z^{R-1}] F(z).$$
This is
$$z F'(z) + G F(z) = \frac{z}{(1-z)^2} +
\sum_{R\ge 1} R z^R [z^{R-1}] F(z).$$
Solving the remaining term we get
$$\sum_{R\ge 2} R z^R [z^{R-1}] F(z)
= z^2 \sum_{R\ge 2} R z^{R-2} [z^{R-1}] F(z)
\\ = z^2 \sum_{R\ge 2} (R-1) z^{R-2} [z^{R-1}] F(z)
+ z^2 \sum_{R\ge 2} z^{R-2} [z^{R-1}] F(z)
\\ = z^2 F'(z) + z F(z).$$
This ODE is linear and we get
$$F'(z) + \frac{G-z}{z(1-z)} F(z) = \frac{1}{(1-z)^3}.$$
The integrating factor is
$$\exp((1-G)\log(z-1) + G\log(z))
= z^G (z-1)^{1-G}$$
and we obtain
$$F(z) = z^{-G} (z-1)^{G-1}
\left(\kappa - \int \frac{1}{(z-1)^3} z^G (z-1)^{1-G} dz\right)
\\ = z^{-G} (z-1)^{G-1}
\left(\kappa + \frac{1}{G+1} \frac{z^{G+1}}{(z-1)^{G+1}}\right)
\\ = \kappa \frac{1}{z} \left(1-\frac{1}{z}\right)^{G-1}
+ \frac{1}{G+1} \frac{z}{(z-1)^2}.$$
It follows even without  determining $\kappa$ (the polynomial in front
contains only negative powers of $z$) that for $R\ge 0$
$$\bbox[5px,border:2px solid #00A000]{
[z^R] F(z) = \frac{1}{G+1} [z^R] \frac{z}{(1-z)^2}
= \frac{R}{G+1}.}$$


text:
Q: swift: how to calculate the date interval (today~specified day) Days from the date that the current intervals specified,
for example: Specified dates = 15/01/2016, Today = 03/01/2016
Expected results: should display After 12 days

A: try this extension:
extension NSDate{

    func relativeDaysFromToday()->String
    {
        let now = NSDate()

            let calendar = NSCalendar.currentCalendar()
            let unitFlags:NSCalendarUnit = NSCalendarUnit.Day
            let components = calendar.components(unitFlags, fromDate: now, toDate: self, options: [])
            return "After \(components.day) days"
    }
}

let jan2 = NSDate(timeIntervalSinceNow: 24*60*60*5)

jan2.relativeDaysFromToday()

A: Try this
let startDateString = "03/01/2016" // start date
let endDateString = "15/01/2016" // end date

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"

let startDate:NSDate = dateFormatter.dateFromString(startDateString)!
let endDate:NSDate = dateFormatter.dateFromString(endDateString)!

let gregorian = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian)
let components = gregorian?.components(NSCalendarUnit.Day, fromDate: startDate, toDate: endDate, options: .MatchFirst)

let day = components?.day
if day == 0 {
  print( "Today")
} else {
  print( "After\(Int64(day!)) day(s)")
}

A: You can simply use NSDateFormatter()... and NSCalendar()... try something like this:
let start = "03/01/2016"
let end = "15/01/2016"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/mm/yyyy"

let startDate:NSDate = dateFormatter.dateFromString(start)!
let endDate:NSDate = dateFormatter.dateFromString(end)!

let cal = NSCalendar.currentCalendar()
let unit:NSCalendarUnit = NSCalendarUnit.Day
let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: [])

If I understood you wrong, please feel free to correct me. Best Regards, Alex

A: You can use the following code for Swift 5:
func DateFormat() -> DateFormatter {
    let x = DateFormatter()
    x.dateFormat = "dd/MM/yyyy"
    x.timeZone = TimeZone(abbreviation: "GMT")
    return x
}

func secondsToDays (seconds : Int) -> (Int) {
    return (seconds / 86400)
}

var dates: Date?
var today: Date?

dates = DateFormat().date(from: "15/01/2016")
today = DateFormat().date(from: "17/01/2016")

let timeInterval = Int(exactly: (today?.timeIntervalSince(dates!))!) ?? 0
print("After", secondsToDays(seconds: timeInterval), "days" ) //After 2 days

A: I would suggest to use next method for calculation.
func relativeDaysFromToday(startDate: Date, endDate: Date)->String
{
let diffComponents = Calendar.current.dateComponents([.day], from: startDate, to: endDate)
let days = diffComponents.day
return "After \(days ?? 0) days"
}


text:
Q: MAX Date for each worker Consider two tables. Worker table has fields like W_ID, W_Name. Course table has fields like C_ID, C_Name, C_Date.
A Worker can take many courses and a course can be taken by many Workers. Therefore, there is a many to many relationship between the two tables. Break the many to many, and create a new table called Takes which consists of the foreign keys W_ID and C_ID.
Here is the question: I want to find out a list of all workers and their last course taken. For example if W_ID=1 took C_Date 20/01/2010 and C_Date 25/10/2010 and C_Date 20/12/2010.
Then the Result required is:
W_ID     C_Date
1        20/12/2010
2
3
4

Edit
I want to find the maximum date of the course each worker has done as workers would have done many courses. I am a business student, so I can't use INNER JOIN command. IN can be used instead?
I am using my SQL in Microsoft Access

A: SELECT  w.w_id, MAX(c.c_date)
FROM    worker w
LEFT JOIN
        worker_course wc
ON      wc.w_id = w.w_id
LEFT JOIN
        course с
ON      c.c_id = wc.c_id
GROUP BY
        w.w_id

or this:
SELECT  w.w_id, MAX(c.c_date)
FROM    course с
JOIN    worker_course wc
ON      wc.c_id = c.c_id
RIGHT JOIN
        worker w
ON      w.w_id = wc.w_id
GROUP BY
        w.w_id

A: select W_ID,C_ID,max(C_Date)
from(select W_ID,C_ID,C_Date
    from worker
    join takes using (W_ID)
    join course using (C_ID)
)wc
group by W_ID,C_ID;


text:
Q: How big should database adapters/gateways be? Outline
When you build an Adapter that connects your application and the database,

*

*How big should you make this adapter?  Should it contain all possible queries that could be made to the DB?

*Do you split it up into several adapters?

*By what means should split it up?

Concrete example
I'm imagining the following rough architecture:
Application
 |
 |   calls (e.g. db.queryData() )
 ↓
DBAdapter
 |
 |   calls (e.g. http request)
 ↓
Database

Let's think of an to be a task list management application for multiple users. For this application You would need queries like

*

*queryTaskList

*queryTask

*queryUserInfo

*updateUserInfo

*createUser

How would you organize these queries?
Would you build one adapter for all queries?
class DBAdapterSQL:
  queryTaskList(): ...
  queryTask(): ...
  queryUserInfo(): ...
  updateUserInfo(): ...
  createUser(): ...

In a big application this might lead to a class with hundreds of methods, which seems a little impractical and hard to maintain.
Would you divide the responsibility by domain?
class DBAdapterTasksSQL:
  queryTaskList(): ...
  queryTask(): ...

class DBAdapterUserSQL:
  queryUserInfo(): ...
  updateUserInfo(): ...
  createUser(): ...

This approach has less methods per class. However, there are probably still many methods that remain unused for defined use cases:
E.g. A component responsible for (ultimately) getting a task list on the screen might never use queryTask, because it does not need that level of detail per task.
Where would you locate queries that lie in the middle between tasks and users?
Would you divide the responsibility by use case?
class DBAdapterTaskReadingSQL:
  queryTaskList(): ...
  queryTask(): ...

class DBAdapterTaskWritingSQL:
  upsertTask(): ...

class DBAdapterUserReadingSQL:
  queryUserInfo(): ...

class DBAdapterUserWritingSQL:
  updateUserInfo(): ...
  createUser(): ...


text:
Q: Query table with different list of variables using like I call a webservice and i get a list of codes: A, B, C, D, E, F etc.
In my problem i get A, B, C.
There's a table where you can create sets with the above codes and for each set you can add a specific message so the end user can understand the codes.
For example A means "ok", B means "you can log in"
So for the set A, B a message could be "you can log in".
The code sets are saved in one column (codes).
In my problem i query the table by using the following query:
Select setid, codes, messagedescr from table1 where setid = (select max(setid) from  table1
                        And codes Like '%A%'
                        And codes Like '%B%'
                        And codes Like '%C%');

This query finds a row but it's wrong, the column "codes" contains the following codes: A, B, C, D.
For example:
setid   codes       messagedescr
1       A, B, C, D  You can login
2       B, C, D     You can login for one day
3       A, C, E     You can login but update your profile
4       B, C, E, F  You cannot login

I don't know the order of the codes from the webservice and i don't how the codes are saved in the table, so i had to make something without order, this why i used the Likes.
There are 25 codes: A, B, C, etc
How can i fix the query so i can find the correct message?
Thanks!
Update:
Thank you all for your answers and specially the more detailed answers that had extra work such as creating the tables.
The table might have from 10-20 rows.
One case is to create another table for the codes and join it with the set ids. Or the other case is to count the lengths of the codes from the service and see if they match with the length in the table.

A: If I understand well your need, this could be a way.
Say you have a table like this:
create table yourTable(setid, codes, messagedescr) as (
  select 1,       'A, B, C, D',  'You can login' from dual union all
  select 2,       'B, C, D'   ,  'You can login for one day' from dual union all
  select 3,       'A, C, E'   ,  'You can login but update your profile' from dual union all
  select 4,       'B, C, E, F',  'You cannot login' from dual
).

This could be a way:
with inputData(codes) as (
    select listagg(trim (regexp_substr(input_codes, '[^,]+', 1, level))) within group ( order by trim (regexp_substr(input_codes, '[^,]+', 1, level)))
    from ( select 'A, D, C, B' as input_codes from dual )  /* the input string */
    CONNECT BY instr(input_codes, ',', 1, level - 1) > 0
)
select *
from inputData
    inner join (
                select listagg(trim (regexp_substr(codes, '[^,]+', 1, level)))
                         within group ( order by trim (regexp_substr(codes, '[^,]+', 1, level))) as codes,
                        messagedescr
                from yourTable
                CONNECT BY instr(codes, ',', 1, level - 1) > 0
                  and prior setId = setId
                  and prior sys_guid() is not null
                group by setId, messagedescr
               )
      using (codes)

The idea here is to split your input string in many rows, and then aggregate the resulting rows in alphabetic order, then apply the same order on the values in table and then check that the ordered strings are equal.
This part is used to split, order and aggregate the input values, so that the result is an ordered string:
select listagg(trim (regexp_substr(input_codes, '[^,]+', 1, level))) within group ( order by trim (regexp_substr(input_codes, '[^,]+', 1, level)))
    from ( select 'A, D, C, B' as input_codes from dual )  /* the input string */
    CONNECT BY instr(input_codes, ',', 1, level - 1) > 0

gives:
ABCD

This part is used to do the same on your table:
select listagg(trim (regexp_substr(codes, '[^,]+', 1, level)))
         within group ( order by trim (regexp_substr(codes, '[^,]+', 1, level))) as codes,
        messagedescr
from yourTable
CONNECT BY instr(codes, ',', 1, level - 1) > 0
  and prior setId = setId
  and prior sys_guid() is not null
group by setId, messagedescr

gives:
CODES      MESSAGEDESCR
---------- -------------------------------------
ABCD       You can login
BCD        You can login for one day
ACE        You can login but update your profile
BCEF       You cannot login

The join between these partial results is quite straightforward and simply checks if a value (ordered) exists in your table that corresponds to the (ordered) input string.

A: Oracle Setup:
Start with a simple function to split a delimited string into a collection:
CREATE OR REPLACE TYPE stringlist AS TABLE OF VARCHAR2(20)
/

CREATE OR REPLACE FUNCTION split_String(
  i_str    IN  VARCHAR2,
  i_delim  IN  VARCHAR2 DEFAULT ','
) RETURN stringlist DETERMINISTIC
AS
  p_result       stringlist := stringlist();
  p_start        NUMBER(5) := 1;
  p_end          NUMBER(5);
  c_len CONSTANT NUMBER(5) := LENGTH( i_str );
  c_ld  CONSTANT NUMBER(5) := LENGTH( i_delim );
BEGIN
  IF c_len > 0 THEN
    p_end := INSTR( i_str, i_delim, p_start );
    WHILE p_end > 0 LOOP
      p_result.EXTEND;
      p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, p_end - p_start );
      p_start := p_end + c_ld;
      p_end := INSTR( i_str, i_delim, p_start );
    END LOOP;
    IF p_start <= c_len + 1 THEN
      p_result.EXTEND;
      p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, c_len - p_start + 1 );
    END IF;
  END IF;
  RETURN p_result;
END;
/

and some sample data:
CREATE TABLE your_table( setid, codes, messagedescr )
  SELECT 1, 'A,B,C,D', 'You can login' FROM DUAL UNION ALL
  SELECT 2, 'B,C,D',   'You can login for one day' FROM DUAL UNION ALL
  SELECT 3, 'A,C,E',   'You can login but update your profile' FROM DUAL UNION ALL
  SELECT 4, 'B,C,E,F', 'You cannot login' FROM DUAL;

Then you can do (passing your input C,A,B - in any order - as the bind parameter :your_code):
SELECT *
FROM   (
  SELECT *
  FROM   your_table
  WHERE  split_string( codes ) SUBMULTISET OF split_String( :your_code )
  ORDER BY setid DESC
)
WHERE ROWNUM = 1;

and it will output the row with the highest matching set of codes.
Note: The above example assumes that you need to match all the codes in the table to codes in your input string. If you only need to match at least one then you can use:
WHERE split_string( codes ) MULTISET INTERSECT split_String( :your_code ) IS NOT EMPTY


text:
Q: Not able to upload image to server using flutter API integration I am trying to send Form data to the backend using Flutter.
As a result, all the text type data is sent easily but my image file is not shared.
Help me Guys
uploadImage(
   filepath,url) async {
EasyLoading.show(status: 'Uploading Data...');
try {
  final result = await InternetAddress.lookup('example.com');
  if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
    var request = http.MultipartRequest('POST', Uri.parse(url));
    print(filepath); *// this filepath is not empty*
    request.files.add(await http.MultipartFile.fromPath('image', filepath));
    request.headers.addAll(headers);
    request.fields['name'] = _pName.text;
    request.fields['store_id'] = store_id;
    request.fields['seller_name'] = seller_name;
    request.fields['seller_id'] = seller_id;
    request.fields['product_id'] = 35.toString();
    request.fields['stock_status_id'] = 6.toString();
    request.fields['price'] = _pPrice.text;
    request.fields['model'] = _pModel.text;
    request.fields['sku'] = _pSKU.text;
    request.fields['status'] = 1.toString();
    request.fields['product_name'] = "Shoes Sport";
    request.fields['is_approved'] = 1.toString();
    request.fields['special'] = false.toString();
    request.fields['quantity'] = _pQuantity.text;
    var res = await request.send();
    if(res.statusCode==200)
    {
      EasyLoading.showSuccess('Data is Uploaded!\n Waiting For Approval');
      EasyLoading.dismiss();
      print(res.reasonPhrase);
      Navigator.pop(context);
    }
    print(request.fields);
    // print(filepath);

  }
  }
  on SocketException catch (_) {
  EasyLoading.showError("Internet Connection is not available");
  }
}

all the data is uploaded except image, i have also crosschecked the parameter its correct.

A: chek the spelling of "image" it should be same mention in your api doc and the one you are using, your code seems correct i was stuck at the same issue i was using the image key but the key was "profile " please do a recheck , let me know if this works


text:
Q: Redirect standard error of one command to standard input of another command I wish to redirect standard error of one command to standard input of another command like
g++ filename.cpp 'redirection' less

A: You can use pipe to do that
command1 2>&1 >/dev/null | command2

It will redirect the standard error stream of the first command to the standard input stream of the second command while discarding the standard output stream of command1.
The redirections are done in order:

*

*command1 2>&1 will redirect file descriptor 2 (standard error) to wherever file descriptor 1 (standard output) is connected.

*>/dev/null (the same as 1>/dev/null) will redirect standard output to /dev/null.
In your case:
g++ filename.cpp 2>&1 >/dev/null | less


text:
Q: Почему выскакиевает Unknown column '*' in 'field list' if(isset($_POST['newname']))
    {
        $nick=$_POST['nazv'];
        $new_name_theme=mysql_query("INSERT INTO  `названия` (наименование)
        VALUES(`$nick`)")or die(mysql_error());
        echo "account is added";
        if($_POST['nazv']==false)
        {
        echo 'your account is not set';
        }
    }

A: Можешь прислать точный запрос, отправляемый в бд?

в идеале синтаксис должен быть таким
INSERT INTO `test`.`tabname` (`param1`,`param2`,`param3`) VALUES ('val1','val2','val3')

Попробуйте задать имена таблиц и полей латинскими буквами
A: "наименование" тоже в кавычках должно быть. К тому же, у вас SQL injection.


text:
Q: Generating all permutation of a character array After reading so many post of "generating permutation of string", I tried to write it in Java.
1) Take the first character start swapping with rest of the character in the combination.
But when I tried to implement it using recursion it gave me only two string for a string of length 3 :(.
public static void main(String[] args) {
    char a[]= "123".toCharArray();
    printPermutation(a,0);

}
private static void printPermutation(char[] a, int i) {
    if(i==a.length-1)
        System.out.println(new String(a));
    else{
        for(int x=i+1;x<a.length;x++)
        {
            swap(a,i,x);
            printPermutation(a,x );
            swap(a,i,x);
        }
    }
}
private static void swap(char[] a, int i, int x) {
        char t=a[i];
        a[i]=a[x];
        a[x]=t;
    }

I am expecting 6 string to be printed.
expected:
123,
132,
213,
231,
312,
321

A: The method printPermutation is the core of your recursion. It doesn't capture the start and end indices properly. This is important because you are trying to swap in chunks
Following change should make it work.
public static void main(String[] args) {
    char a[]= "123".toCharArray();
    printPermutation(a, 0, a.length);
}

private static void printPermutation(char[] a, int startIndex, int endIndex) {
    if (startIndex == endIndex)//reached end of recursion, print the state of a
        System.out.println(new String(a));
    else {
        //try to move the swap window from start index to end index
        //i.e 0 to a.length-1
        for (int x = startIndex; x < endIndex; x++) {
            swap(a, startIndex, x);
            printPermutation(a, startIndex + 1, endIndex);
            swap(a, startIndex, x);
        }
    }
}

private static void swap(char[] a, int i, int x) {
    char t = a[i];
    a[i] = a[x];
    a[x] = t;
}

A: The general idea of your permutation algorithm is correct, but you forgot to handle some of possible cases there.
First. You should add printPermutation(a, i + 1) before going into loop.
Second. Call printPermutation(a, i + 1) instead of printPermutation(a, x) in the loop.
public static void main(String[] args) {
    char a[]= "1234".toCharArray();
    printPermutation(a, 0);
}

private static void printPermutation(char[] a, int i) {
    if (i == a.length - 1) System.out.println(new String(a));
    else {
        printPermutation(a, i + 1);
        for (int x = i + 1; x < a.length; x++) {
            swap(a, i, x);
            printPermutation(a, i + 1);
            reswap(a, i, x);
        }
    }
}

private static void swap(char[] a, int i, int x) {
    char tmp = a[i];
    a[i] = a[x];
    a[x] = tmp;
}

private static void reswap(char[] a, int i, int x) {
    swap(a, i, x);
}


text:
Q: Nav Affix background image change I am using Nav affix to change the background of my nav on scroll. There are two separate nav classes, nav-affix, and nav-affix-top. It seems to be working:
http://[redacted]
(please point out bugs) but for some reason, if the page is reloaded, and then there is a mouse click on any of the links or the sliders on the page, the nav will change classes and backgrounds again. Any insight as to why this is hapening is appreciated!
JS:
$(function() {

    $('#nav-wrapper').height($("#nav").height());
    $('#nav').affix({
        offset: { top: $('#nav').offset().top }
    });
});

CSS:
#nav.affix {
    position: fixed;
    overflow:visible;
    width:100%;
    background-image:url(../navbackground2.png);
}

#nav.affix-top {
    background-image:url(../navback1.png);
    margin-top:0;
}

A: This could be a bug from Bootstrap, please put following code in your javascript file:
$('#nav').on('affix.bs.affix', function() {
    if (!$(window).scrollTop()) return false;
});

This piece of code will check if it is possible to scroll to the top of your page. If this returns false, which means you are on top already, it won't change the affix-top class of your navbar.


text:
Q: Give my IP as the default value in an AWS CFN parameter When creating a Security Group manually via the console, the Source for a rule can be selected as "My IP" which automatically fetches the client browser's IP address as a /32 CIDR.
Is there a way to have a CloudFormation parameter grab the clients IP address as the default when running the CF template from the console?
Use case: I have a bastion host / access host that I build when needed from a CFN template. Each time I build the host I have to visit a 'WhatsMyIP' type site to get my current IP address and copy and paste it into my CFN parameter. As the AWS Console has a way of grabbing the IP automatically and formatting it as a /32 CIDR it would be good if this was available as a function in a CFN template as well.

A: There is no way to do that, this feature on the AWS console is a pure AWS console UI implementation and is not part of the AWS API nor of the default CloudFormation parameters. However, you could have a look at the AWS CDK which lets you define your resources in a language of your choosing and can also immediately initiate the deployment if you so want.
This would allow you to use the language you're defining your resources in, to make the call to whatsmyip and automate the process.