text:
Q: Dynamically call a function by overriding the typecast #include <iostream>

using namespace std;

class Base
{
public:
  void who()
  {
    cout << "I am " << _name << endl;
  }

protected:
  std::string _name;
};

class A : public Base
{
public:
  A()
  {
    _name = "A class";
  }
};

class B : public Base
{
public:
  B()
  {
    _name = "B class";
  }
};

class Wrapper
{
public:
  Wrapper(Base *i):_data(i)
  {
  }

  operator A()
  {
      A a;
  //  dynamic_cast<A*>(_data);
      return a;
  }

  operator B()
  {
      B a;
   // dynamic_cast<B*>(_data);
      return a;
  }
private:
  Base* _data;
};

void madeForClass(A iObject)
{
  cout << "call madeForClass A";
}

void madeForClass(B iObject)
{
  cout << "call madeForClass B";
}

int main()
{
  A a;
  Base* b = &a;

  madeForClass(Wrapper(b));

  return 0;
}

when I execute this, I get error from compile saying:
error: call of overloaded 'madeForClass(Wrapper)' is ambiguous
I understand that it cannot deduce right function even though i have overloaded the typecast. But, How can I achieve such dynamism?
For more info, I somehow want to use the dynamic_cast in the overloading function or somewhere in such a way that based on the outcome of cast it should choose the corresponding madeForClass function.
For the given example, the cast will fail for 'B' hence should call madeForClass(A i);

A: As alternative, you may do
class Wrapper
{
public:
    Wrapper(Base *i) : _data(i) {}

    template <typename F>
    auto Apply(F f)
    {
        if (auto a = dynamic_cast<A*>(_data)) {
            f(*a);
        } else if (auto b = dynamic_cast<B*>(_data)){
            f(*b);
        }
    }

private:
  Base* _data;
};

And then
Wrapper(base).Apply([](const auto& e){ madeForClass(e); });

Demo
or use Visitor instead of manual dynamic_cast


text:
Q: Using same authentication for EWS API and Graph API We've been using Azure Active Directory and EWS SOAP web services successfully.
Trying to see if we can use our current authentication method to be able to also invoke Microsoft Graph (i.e. https://graph.microsoft.com/v1.0/me/)
I went into Azure and added Microsoft Graph under App Registrations -> Settings -> Required Permissions.
This was our authorize endpoint url:
https://login.microsoftonline.com/common/oauth2/authorize?resource=https%3A%2F%2Foutlook.office365.com%2F
I changed it to :
https://login.microsoftonline.com/common/oauth2/authorize?resource=https%3A%2F%2Fgraph.microsoft.com
Is this all I had to do?  When I try to go through the oAuth 2.0 flow, the authorize request seems successful, then I'm asked to enter my credentials, and then I get an error:

"Misconfigured application. This could be due to one of the
  following: The client has not listed any permissions for 'Microsoft
  Graph' in the requested permissions in the client's application
  registration. Or, The admin has not consented in the tenant. Or, Check
  the application identifier in the request to ensure it matches the
  configured client application identifier. Please contact your admin to
  fix the configuration or consent on behalf of the tenant. Client app
  ID: b1313958-.... "

A:
I went into Azure and added Microsoft Graph under App Registrations ->
  Settings -> Required Permissions.

You mentioned this as part of your question. Please check if after performing these steps for your App Registration in Azure AD, did you click on the "Grant Permissions" button to provide consent or not.
Looking at the error it seems Consent for Microsoft Graph related permissions isn't done yet.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using affinity to keep two kubernetes pods apart with unknown label values Imagine I have some pods I need on separate k8s nodes, I could use something like this if I know both pods have a label my/label=somevalue
affinity:
  podAntiAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 2
        podAffinityTerm:
          labelSelector:
            matchLabels:
              my/label: somevalue

I have some pods I need separated, according to multiple values of the same label, which doesn't known up-front (it's a shared key which is calculated by an operator).
Is there a way of specifying a podAffinityTerm which applies to any pods sharing the same value of my.label, regardless of the actual value?
E.g.
Pod a has my/label=x
Pod b has my/label=x
Pod c has my/label=y
Pod d has my/label=y

I'd need pods a & b separated from each other, and pods c & d separated form each other, but e.g. a and d can coexist on the same node

A: As far as I know, there is no built-in way to specify affinity without knowing label values. At the stage of creating a pod you need to provide both key and value. In order for affinity to work properly, you need to know this value at the time of creation and put it in the appropriate yaml file.
Theoretically, you could create a custom script, e.g. in bash, which will take your value for you

its a sharding key which is calculated by an operator

and then replace it in yaml files. This way it will be set correctly when creating pod.
Additionally, you can also have a look at Well-Known Labels, Annotations and Taints.
Depending on your exact situation, you can try to solve the problem with them. See also this page. There you will find everything about assigning pod to nodes.


text:
Q: Can Mono 2.4 Ahead-Of-Time (AOT) compile on FreeBSD x86 (or x64)? I use a shared web server (NearlyFreeSpeech.net, highly recommended!) running FreeBSD 7.2 and would love to write CGI scripts for it using C# but they have not installed Mono on there yet. If I use my own FreeBSD 7.2 box and compile my C# programs there, can I AOT compile my code and deploy the binaries on the Mono-less server?
I know multiple iPhone games are selling on the App Store and all of those are AOT compiled (to ARM). And the above referenced page says x86 and x64 are supported, but on my x86 Mac OS X Leopard Mono install I tried
sudo mono --aot /Library/Frameworks/Mono.framework/Versions/2.4.2.1/lib/mono/2.0/mscorlib.dll

and
sudo mono --full-aot /Library/Frameworks/Mono.framework/Versions/2.4.2.1/lib/mono/2.0/mscorlib.dll

and got the errors:
AOT compilation is not supported on this platform.

and
Failed to load AOT module '/Library/Frameworks/Mono.framework/Versions/2.4.2.1/lib/mono/2.0/mscorlib.dll.dylib' in aot-only mode.

respectively. I just don't want to put a lot of work into getting FreeBSD 7.2 + Mono 2.4.2.1 working and find out the same thing: AOT compilation is not supported, which is the only reason for caring about FreeBSD + Mono for me...

A: AOT only removes the need for (most) JIT-compiling. You still need the VM for all the other services it provides - garbage collection, metadata, IO, security, dynamic compilation, etc.
The advantage of AOT in a desktop environment is to reduce startup time, allow more expensive compiler optimizations to be used, and to allow code sharing between apps.
The iPhone is a special case, since it disallows both dynamic libraries and JITing. So the CLI code is AOT-compiled into static libraries which are then linked together with a slimmed down Mono runtime, producing a single binary. However, disabling the JIT adds some limitations. For example, certain uses of generics are impossible (the AOT compiler cannot always statically determine which reified generic types it needs to compile), and dynamic code generation (needed by languages like IronPython) is impossible.
Your best bet would be to build a Parallel Mono Environment - either build it directly on the remote machine, or build it locally, install into some temp prefix, tar that and copy it over.


text:
Q: Показывать по три элемента на странице Необходимо ограничить показ элементов на странице. Есть отзывы, необходимо показывать по три отзыва. Если их больше, то разделить по три отзыва на каждую страницу и добавить переключатель по ним.
Я то понимаю как в ручную засунуть в слайдер много элементов, но как автоматизировать это дело ? Чтоб на странице было не больше трех статей отзывов? Прикреплен код только мобильного маркапа.
Заранее благодарен за помощь!

.feedback .items article {
 width: 100%;
 padding: 10px 0 0 0;
}

.feedback .items article .text, .author, .date {
 color: #000000;

}

.feedback .items article .text {
 margin: 0 0 20px;
}

.feedback .items article .author {
 margin: 0 0 10px;
 text-align: center;
}
.feedback .items article .date {
 margin: 0 0 40px;
 text-align: center;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Мария

01.01.2016

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Валентина

18.01.2016

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Екатерина

21.02.2016

A: Используйте адаптивный слайдер, который будет менять количество слайдов в зависимости от ширины экрана/слайдера. Например, Slick.js


text:
Q: Python custom method set to new variable changes old variable I have created a class with two methods, NRG_load and NRG_flat. The first loads a CSV, converts it into a DataFrame and applies some filtering; the second takes this DataFrame and, after creating two columns, it melts the DataFrame to pivot it.
I am trying out these methods with the following code:
nrg105 = eNRG.NRG_load('nrg_105a.tsv')
nrg105_flat = eNRG.NRG_flat(nrg105, '105')

where eNRG is the class, and '105' as second argument is needed to run an if-loop within the method to create the aforementioned columns.
The behaviour I cannot explain is that the second line - the one with the NRG_flat method - changes the nrg105 values.
Note that if I only run the NRG_load method, I get the expected DataFrame.
What is the behaviour I am missing? Because it's not the first time I apply a syntax like that, but I never had problems, so I don't know where I should look at.
Thank you in advance for all of your suggestions.
EDIT: as requested, here is the class' code:
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 16 15:22:21 2019

@author: CAPIZZI Filippo Antonio
"""

import pandas as pd
from FixFilename import FixFilename as ff
from SplitColumn import SplitColumn as sc
from datetime import datetime as ddt

class EurostatNRG:
    # This class includes the modules needed to load and filter
    # the Eurostat NRG files

    # Default countries' lists to be used by the functions
    COUNTRIES = [
        'EU28', 'AL', 'AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'EL',
        'ES', 'FI', 'FR', 'GE', 'HR', 'HU', 'IE', 'IS', 'IT', 'LT', 'LU', 'LV',
        'MD', 'ME', 'MK', 'MT', 'NL', 'NO', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK',
        'TR', 'UA', 'UK', 'XK'
    ]

    # Default years of analysis
    YEARS = list(range(2005, int(ddt.now().year) - 1))

    # NOTE: the 'datetime' library will call the current year, but since
    # the code is using the 'range' function, the end years will be always
    # current-1 (e.g. if we are in 2019, 'current year' will be 2018).
    # Thus, I have added "-1" because the end year is t-2.

    INDIC_PROD = pd.read_excel(
        './Datasets/VITO/map_nrg.xlsx',
        sheet_name=[
            'nrg105a_indic', 'nrg105a_prod', 'nrg110a_indic', 'nrg110a_prod',
            'nrg110'
        ],
        convert_float=True)

    def NRG_load(dataset, countries=COUNTRIES, years=YEARS, unit='ktoe'):
        # This module will load and refine the NRG dataset,
        # preparing it to be filtered

        # Fix eventual flags
        dataset = ff.fix_flags(dataset)

        # Load the dataset into a DataFrame
        df = pd.read_csv(
            dataset,
            delimiter='\t',
            encoding='utf-8',
            na_values=[':', ': ', ' :'],
            decimal='.')

        # Clean up spaces from the column names
        df.columns = df.columns.str.strip()

        # Removes the mentioned column because it's not needed
        if 'Flag and Footnotes' in df.columns:
            df.drop(columns=['Flag and Footnotes'], inplace=True)

        # Split the first column into separate columns
        df = sc.nrg_split_column(df)

        # Rename the columns
        df.rename(
            columns={
                'country': 'COUNTRY',
                'fuel_code': 'KEY_PRODUCT',
                'nrg_code': 'KEY_INDICATOR',
                'unit': 'UNIT'
            },
            inplace=True)

        # Filter the dataset
        df = EurostatNRG.NRG_filter(
            df, countries=countries, years=years, unit=unit)

        return df

    def NRG_filter(df, countries, years, unit):
        # This module will filter the input DataFrame 'df'
        # showing only the 'countries', 'years' and 'unit' selected

        # First, all of the units not of interest are removed
        df.drop(df[df.UNIT != unit.upper()].index, inplace=True)

        # Then, all of the countries not of interest are filtered out
        df.drop(df[~df['COUNTRY'].isin(countries)].index, inplace=True)

        # Finally, all of the years not of interest are removed,
        # and the columns are rearranged according to the desired output
        main_cols = ['KEY_INDICATOR', 'KEY_PRODUCT', 'UNIT', 'COUNTRY']
        cols = main_cols + [str(y) for y in years if y not in main_cols]
        df = df.reindex(columns=cols)

        return df

    def NRG_flat(df, name):
        # This module prepares the DataFrame to be flattened,
        # then it gives it as output

        # Assign the indicators and products' names
        if '105' in name:  # 'name' is the name of the dataset
            # Creating the 'INDICATOR' column
            indic_dic = dict(
                zip(EurostatNRG.INDIC_PROD['nrg105a_indic'].KEY_INDICATOR,
                    EurostatNRG.INDIC_PROD['nrg105a_indic'].INDICATOR))
            df['INDICATOR'] = df['KEY_INDICATOR'].map(indic_dic)
            # Creating the 'PRODUCT' column
            prod_dic = dict(
                zip(
                    EurostatNRG.INDIC_PROD['nrg105a_prod'].KEY_PRODUCT.astype(
                        str), EurostatNRG.INDIC_PROD['nrg105a_prod'].PRODUCT))
            df['PRODUCT'] = df['KEY_PRODUCT'].map(prod_dic)
        elif '110' in name:
            # Creating the 'INDICATOR' column
            indic_dic = dict(
                zip(EurostatNRG.INDIC_PROD['nrg110a_indic'].KEY_INDICATOR,
                    EurostatNRG.INDIC_PROD['nrg110a_indic'].INDICATOR))
            df['INDICATOR'] = df['KEY_INDICATOR'].map(indic_dic)
            # Creating the 'PRODUCT' column
            prod_dic = dict(
                zip(
                    EurostatNRG.INDIC_PROD['nrg110a_prod'].KEY_PRODUCT.astype(
                        str), EurostatNRG.INDIC_PROD['nrg110a_prod'].PRODUCT))
            df['PRODUCT'] = df['KEY_PRODUCT'].map(prod_dic)

        # Delete che columns 'KEY_INDICATOR' and 'KEY_PRODUCT', and
        # rearrange the columns in the desired order
        df.drop(columns=['KEY_INDICATOR', 'KEY_PRODUCT'], inplace=True)
        main_cols = ['INDICATOR', 'PRODUCT', 'UNIT', 'COUNTRY']
        year_cols = [y for y in df.columns if y not in main_cols]
        cols = main_cols + year_cols
        df = df.reindex(columns=cols)

        # Pivot the DataFrame to have it in flat format
        df = df.melt(
            id_vars=df.columns[:4], var_name='YEAR', value_name='VALUE')

        # Convert the 'VALUE' column into float numbers
        df['VALUE'] = pd.to_numeric(df['VALUE'], downcast='float')

        # Drop rows that have no indicators (it means they are not in
        # the Excel file with the products of interest)
        df.dropna(subset=['INDICATOR', 'PRODUCT'], inplace=True)

        return df

EDIT 2: if this could help, this is the error I receive when using the EurostatNRG class in IPython:

[autoreload of EurostatNRG failed: Traceback (most recent call last):
  File
  "C:\Users\CAPIZZIF\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\extensions\autoreload.py",
  line 244, in check
      superreload(m, reload, self.old_objects)   File "C:\Users\CAPIZZIF\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\extensions\autoreload.py",
  line 394, in superreload
      update_generic(old_obj, new_obj)   File "C:\Users\CAPIZZIF\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\extensions\autoreload.py",
  line 331, in update_generic
      update(a, b)   File "C:\Users\CAPIZZIF\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\extensions\autoreload.py",
  line 279, in update_class
      if (old_obj == new_obj) is True:   File "C:\Users\CAPIZZIF\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py",
  line 1478, in nonzero
      .format(self.class.name)) ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or
  a.all(). ]

A: I managed to find the culprit.
In the NRG_flat method, the lines:
df['INDICATOR'] = df['KEY_INDICATOR'].map(indic_dic)
...
df['PRODUCT'] = df['KEY_PRODUCT'].map(indic_dic)

mess up the copies of the df DataFrame, thus I had to change them with the Pandas assign method:
df = df.assign(INDICATOR=df.KEY_INDICATOR.map(prod_dic))
...
df = df.assign(PRODUCT=df.KEY_PRODUCT.map(prod_dic))

I do not get any more error.
Thank you for replying!


text:
Q: How do I apply the browser height to a CSS class? You can read your browser dimensions with jQuerys $document.height or with simple JS via height: window.innerHeight || document.body.clientHeight.
But how do I apply the value to a CSS class?

A: jQuery:
$('.targetClass').css('height',otherObject.height()+'px');

A: You cannot rewrite/add new values to CSS properties/classes on the fly; you can write/rewrite/add values to elements.
You should post your situation, maybe there is a different way to do what you're trying to do.

A: $('#target').css('height',$(document.body).height()+'px')

(jQuery)

A: Find the rule object in a browser-specific way ( http://www.javascriptkit.com/domref/cssrule.shtml )
Then you can edit the style object of the rule object and actually change the CSS class definition

A: No need to overcomplicate this - you don't need to find a way to apply the height to a CSS class. Just give each of your
s a class in the HTML:

This is some content.

then use jQuery code similar to this:
var document_height = $(document).height();
$('.viewport_height').css('height', document_height + 'px');

to apply the measured height to all elements of that class.
For a more robust solution, attach a function to the window's onresize event to recalculate and apply the height whenever the viewport height changes.


text:
Q: How do I set this table row to a specific height using CSS? I have researched this issue and tried a few suggestions but I must be missing something. This is a sample XML file with dummy data:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="SRRSchedule.xsl"?>
<SRRSchedule>
  <ReportTitle>Assignments - October 2018</ReportTitle>
  <Columns>
    <Heading>Date</Heading>
    <Heading>Hall Attendant</Heading>
    <Heading>Car Park</Heading>
    <Heading>Sound</Heading>
    <Heading>Platform</Heading>
    <Heading>Mic Left</Heading>
    <Heading>Mic Right</Heading>
    <Heading>Chairman</Heading>
    <Heading>Watchtower Reader</Heading>
  </Columns>
  <MonthAssignments IncludeHeadings="true" IncludeGap="true">
    <Assignment RowType="Odd">
      <Date Day="6" DayShort="Thu" DayFull="Thursday" Month="12" MonthShort="Dec" MonthFull="December" Year="2018">Thu, October 04</Date>
      <Name Conflict="false" Highlight="true">Name 1</Name>
      <Name Conflict="false" Highlight="false">Name 2</Name>
      <Name Conflict="false" Highlight="false">Name 3</Name>
      <Name Conflict="false" Highlight="false">Name 4</Name>
      <Name Conflict="false" Highlight="false">Name 5</Name>
      <Name Conflict="false" Highlight="false">Name 6</Name>
      <Name Conflict="false" Highlight="false">Name 7</Name>
      <Name Conflict="false" Highlight="false">Name 8</Name>
    </Assignment>
    <Assignment RowType="Even">
      <Date Day="6" DayShort="Thu" DayFull="Thursday" Month="12" MonthShort="Dec" MonthFull="December" Year="2018">Thu, October 04</Date>
      <Name Conflict="false" Highlight="true">Name 1</Name>
      <Name Conflict="false" Highlight="false">Name 2</Name>
      <Name Conflict="false" Highlight="false">Name 3</Name>
      <Name Conflict="false" Highlight="false">Name 4</Name>
      <Name Conflict="false" Highlight="false">Name 5</Name>
      <Name Conflict="false" Highlight="false">Name 6</Name>
      <Name Conflict="false" Highlight="false">Name 7</Name>
      <Name Conflict="false" Highlight="false">Name 8</Name>
    </Assignment>
    <Assignment RowType="Odd">
      <Date Day="6" DayShort="Thu" DayFull="Thursday" Month="12" MonthShort="Dec" MonthFull="December" Year="2018">Thu, October 04</Date>
      <Name Conflict="false" Highlight="true">Name 1</Name>
      <Name Conflict="false" Highlight="false">Name 2</Name>
      <Name Conflict="false" Highlight="false">Name 3</Name>
      <Name Conflict="false" Highlight="false">Name 4</Name>
      <Name Conflict="false" Highlight="false">Name 5</Name>
      <Name Conflict="false" Highlight="false">Name 6</Name>
      <Name Conflict="false" Highlight="false">Name 7</Name>
      <Name Conflict="false" Highlight="false">Name 8</Name>
    </Assignment>
  </MonthAssignments>
  <MonthAssignments IncludeHeadings="true" IncludeGap="true">
    <Assignment RowType="Even">
      <Date Day="6" DayShort="Thu" DayFull="Thursday" Month="12" MonthShort="Dec" MonthFull="December" Year="2018">Thu, October 04</Date>
      <Name Conflict="false" Highlight="true">Name 1</Name>
      <Name Conflict="false" Highlight="false">Name 2</Name>
      <Name Conflict="false" Highlight="false">Name 3</Name>
      <Name Conflict="false" Highlight="false">Name 4</Name>
      <Name Conflict="false" Highlight="false">Name 5</Name>
      <Name Conflict="false" Highlight="false">Name 6</Name>
      <Name Conflict="false" Highlight="false">Name 7</Name>
      <Name Conflict="true" Highlight="false">Name 8</Name>
    </Assignment>
  </MonthAssignments>
  <MonthAssignments IncludeHeadings="true" IncludeGap="true">
    <Assignment RowType="Odd">
      <Date Day="6" DayShort="Thu" DayFull="Thursday" Month="12" MonthShort="Dec" MonthFull="December" Year="2018">Thu, October 04</Date>
      <SpecialEvent>Circuit Assembly—Be Bold!</SpecialEvent>
    </Assignment>
  </MonthAssignments>
  <Note>
    All assigned brothers should try to arrive at least 15 minutes before the meeting to confirm duties, set up and test the sound and prepare the platform.
  </Note>
</SRRSchedule>

This is the CSS file:
body
{
    font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
    font-size: 12pt;
}

.textReportTitle {
    text-align: center;
    font-size: 18pt;
    font-weight: 700;
}

table {
    border-collapse: collapse;
    width: 100%;
}

table td {
    height: 14pt;
    border: 1px solid black;
    padding: 1mm;
}

.cellHeading {
    font-weight: 700;
    background-color: red;
}

.cellDate {
    background-color: magenta;
}

.cellName {

}

.cellHighlight {
    background-color: cyan;
}

.cellConflict {
    background-color: gray;
}

.cellSpecialEvent {
    text-align: center;
    font-style: italic;
}

.cellNote {
    text-align: center;
    background-color: darkgrey;
}

.cellGap {
    max-height: 5mm;
    background-color: orange;
}

.rowOdd {
    background-color: yellow;
}

.rowEven {
    background-color: pink;
}

This is the XSL script:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">
  <xsl:output method="html" indent="yes" version="4.01"
    doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
    doctype-public="//W3C//DTD XHTML 1.0 Transitional//EN"/>
  <xsl:template match="/">

        <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
        <link rel="stylesheet" type="text/css" href="SRRSchedule.css"/>
        <title>Report</title>

        <xsl:apply-templates select="SRRSchedule/ReportTitle"/>

          <xsl:apply-templates select="SRRSchedule/MonthAssignments"/>
          <xsl:apply-templates select="SRRSchedule/Note"/>

  </xsl:template>

  <xsl:template match="ReportTitle">

      <xsl:value-of select="."/>

  </xsl:template>

  <xsl:template match="MonthAssignments">
    <xsl:if test="@IncludeHeadings">

        <xsl:apply-templates select="/SRRSchedule/Columns/Heading"/>

    </xsl:if>
    <xsl:apply-templates select="Assignment"/>
    <xsl:if test="@IncludeGap='true'">
      <xsl:call-template name="GapRow"/>
    </xsl:if>
  </xsl:template>

  <xsl:template match="Heading">

      <xsl:value-of select="."/>

  </xsl:template>

  <xsl:template match="Assignment">

      <xsl:attribute name="class">
        <xsl:choose>
          <xsl:when test="@RowType='Even'">rowEven</xsl:when>
          <xsl:when test="@RowType='Odd'">rowOdd</xsl:when>
        </xsl:choose>
      </xsl:attribute>
      <xsl:apply-templates select="Date"/>
      <xsl:apply-templates select="Name"/>
      <xsl:apply-templates select="SpecialEvent"/>

  </xsl:template>

  <xsl:template match="Date">

      <xsl:value-of select="."/>

  </xsl:template>

  <xsl:template match="Name">

      <xsl:choose>
        <xsl:when test="@Highlight='true'">
          <xsl:attribute name="class">cellHighlight</xsl:attribute>
        </xsl:when>
        <xsl:when test="@Conflict='true'">
          <xsl:attribute name="class">cellConflict</xsl:attribute>
        </xsl:when>
      </xsl:choose>
      <xsl:value-of select="."/>

      <xsl:if test=".=''">
        <xsl:text> </xsl:text>
      </xsl:if>

  </xsl:template>

  <xsl:template match="Note">

        <xsl:attribute name="colspan">
          <xsl:value-of select="count(/SRRSchedule/Columns/Heading)"/>
        </xsl:attribute>

        <xsl:copy-of select="."/>

  </xsl:template>

  <xsl:template match="SpecialEvent">

      <xsl:attribute name="colspan">
        <xsl:value-of select="count(/SRRSchedule/Columns/Heading)-1"/>
      </xsl:attribute>
      <xsl:value-of select="."/>

  </xsl:template>

  <xsl:template name="GapRow">

        <xsl:attribute name="colspan">
          <xsl:value-of select="count(/SRRSchedule/Columns/Heading)"/>
        </xsl:attribute>
        <xsl:text> </xsl:text>

  </xsl:template>

</xsl:stylesheet>

This is what the transformation looks like:

In the XSL file I have:
  <xsl:template name="GapRow">

        <xsl:attribute name="colspan">
          <xsl:value-of select="count(/SRRSchedule/Columns/Heading)"/>
        </xsl:attribute>
        <xsl:text> </xsl:text>

  </xsl:template>

The CSS for this row gap is:
.cellGap {
    max-height: 5mm;
    background-color: orange;
}

How do I change this so that the row gap can be whatever height I stipulate in the CSS file? I tried reducing the font height to 6pt and it made no difference.

A: .cellGap {
    max-height: none;
    height: Number of Andrew's choosing in em, px, whatevs.
}

https://developer.mozilla.org/en-US/docs/Web/CSS/max-height


text:
Q: Inserting label to a Plot I have the following figure

Given by the Following code
pic3 := Plot[0.7 + 0*x, {x, -0.5, 1}]
pic4 := ListLinePlot[
  Thread[List[0.8 & /@ Range[0, 1], Range[-0.2, 1]]]]

pic5 := Graphics[Line[{{0, 0}, {0, 1}, {1, 0}, {0, 0}}]]
Show[pic5, pic4, pic3, PlotRange -> {{-1, 1}, {-1, 1}}]

I would like to add 2 brackets one that said $\alpha$ between $(0,0)$ and the cut in $y$-axis and another that said $\beta$ between $(0,0)$ and the cut at the $x-$Axis. Is this possible ? Thanks in advance .

A: For a different approach, beginning with version 12 you can use the EXPERIMENTAL function GeometricScene
Clear["Global`*"]

Show[
 GeometricScene[
   {"O" -> {0, 0},
    a -> {0, 1}, b -> {1, 0},
    α -> {0, 0.7}, β -> {0.8, 0},
    α2 -> {1.5, 0.7}, (*
    chosen outside the plot range *)
    β2 -> {0.8, 1.5}},(*
   chosen outside the plot range *)
   {Triangle[{a, b, "O"}],
    InfiniteLine[{α, α2}],
    InfiniteLine[{β, β2}]}]
  ["Graphics"],
 PlotRange -> {{-0.5, 1.1}, {-0.2, 1.1}}]

Or for a dynamic scene
Manipulate[
 Show[
  GeometricScene[
    {"O" -> {0, 0},
     a -> {0, 1}, b -> {1, 0},
     "α" -> {0, α}, "β" -> {β, 0},
     α2 -> {1.5, α}, (*
     chosen outside the plot range *)
     β2 -> {β, 1.5}},(*
    chosen outside the plot range *)
    {Triangle[{a, b, "O"}],
     InfiniteLine[{"α", α2}],
     InfiniteLine[{"β", β2}]}]
   ["Graphics"],
  PlotRange -> {{-0.5, 1.1}, {-0.2, 1.1}}],
 {{α, 0.7}, 0, 1, 0.025, Appearance -> "Labeled"},
 {{β, 0.8}, 0, 1, 0.025, Appearance -> "Labeled"}]

A: {a, b} = MapThread[Graphics[{#, Disk[], White,
      Inset[Style[#2, FontSize -> Scaled[.5]]]}, ImageSize -> 40] &,
   {{Blue, Red}, {"α", "β"}}];

Deploy @ DynamicModule[{pt1 = {0., .8}, pt2 = {.8, 0}},
  Graphics[{EdgeForm[Black], FaceForm[], Triangle[],
    FaceForm[Opacity[1]],
    Locator[Dynamic[pt1, (pt1 = {#[[1]], .8}) &], a],
    Locator[Dynamic[pt2, (pt2 = {.8, #[[2]]}) &], b]},
   PlotRangePadding -> .2,
   GridLines -> {{.8}, {.8}},
   GridLinesStyle -> Directive[Thick, ColorData[97]@1]]]


text:
Q: why this error "TypeError: execute expected at most 2 arguments, got 3"? c.execute("INSERT INTO users (username, password) VALUES (?, ?)", username, password)

as a beginner, I am trying to make a sign up form for my first web app using Flask and python.

A: Instead of using different arguments for each variable, you need to put all variables in an array or a tuple:
c.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, password) )


text:
Q: How do i assert, compile time, that the nth element of a tuple is an optional of some type? I need to check if the nth element of a tuple is an optional of some type.
It has to be an std::optional and not a std::variant (which could have made the code simpler).
My first instinct is the following. But this throws a compiler error.
template<int N, typename TupleToCheck>
void StaticCheck() {
    using NthType = typename tuple_element<N, TupleToCheck>::type;
    static_assert(std::is_same<NthType, std::optional<NthType::value_type>>);
}

I suspect that this is because the compiler does not know if NthType could have a type value_type defined within it.
Is there a way to achieve this?

A: You did not post the error, but this scheme should work for all templates regardless whether ::value_type exists:
#include <tuple>
#include <optional>

template<typename T>
struct is_optional{
    constexpr static bool value = false;
};

template<typename T>
struct is_optional<std::optional<T>>{
    constexpr static bool value = true;
};

template<typename T>
constexpr bool is_optional_v = is_optional<T>::value;

template<int N, typename TupleToCheck>
void StaticCheck() {
    static_assert(is_optional_v<std::tuple_element_t<N,TupleToCheck>>);
}

int main(){

    using t1 = std::tuple<int,std::optional<double>,double>;

    StaticCheck<1,t1>();
}

A: Answering my own question for the sake of closure.
The issue with my code was syntax, as @DanielLangr pointed out in the comments.

It works for me (no compilation errors) if I correct syntax errors: godbolt.org/z/dxndEx. Added std::, typename , and ::value.

The fixed code is as below
template<int N, typename TupleToCheck>
void StaticCheck() {
    using NthType = typename std::tuple_element<N, TupleToCheck>::type;
    static_assert(std::is_same<NthType, std::optional<typename NthType::value_type>>::value);
}


text:
Q: Android change textsize of textview which is inside a view pager I have a text view inside a view pager with pager adapter. In my activity on click on a button I want to change text size of that textview. What I have tried so far
View view1 = (View) customPagerAdapter.instantiateItem(viewPager, viewPager.getCurrentItem());
            TextView textView = (TextView) view1.findViewById(R.id.tvPoem);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textView.getTextSize() + 1);
            customPagerAdapter.notifyDataSetChanged();

And also tried
    ((TextView) viewPager.getChildAt(currentPagePosition).findViewById(R.id.tvPoem)).setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                ((TextView) viewPager.getChildAt(currentPagePosition).findViewById(R.id.tvPoem)).getTextSize() + 1);
        customPagerAdapter.notifyDataSetChanged();
        viewPager.invalidate();

Where currentPagePosition is the position I got from on page change listener. It is working fine on the first page. But Once I change my page, It's not working at all. I have debug my code and check currentPagePosition. It is returning the accurate position. I have also tried it on UIThread and on runnable with posted delay. Any help on this would be much appreciated . thanks


text:
Q: need help regarding the docker implementation I am actually new to docker. I have taken basic tutorials on docker and know the commands to docker regarding images, containers.
Now, All my applications servers like running on tomcat9 or nginx and also services like redis , scylla db , activemq are running on the ubuntu servers and installation,everything I am doing it manually.
I am confused like to how to start implementing the docker in my company.
Like for the commercial use, what are the prerequisites, is docker hub account neccessary or else can we use directly like docker pull image_name?
I have searched in many blogs, but could not find the way of implementation.

A: *

*Install docker on your computer/server first.

*Use you cmd/bash/terminal to interact with docker. Just to make sure Docker is installed on you computer by typing on cmd docker ps
If you are using Docker Desktop, you can use Docker desktop to check as well.

*Search on hub.docker the image you need. Follow it's instruction, make a cmd docker pull <image> to pull their image first

*Use docker run to run you image, if you image need to use a port, make sure that port isn't used by another process.


text:
Q: Animation stop actionscript 3.0 tick So, I have this game and I want the player to move, so I use a tick method when the key is down it creates 2 event listeners, a keyup listener and a tick.The keyup listener removes its self and removes the tick.The tick contains the movement and where I presumed the animation.
Here is my code:
// For every frame //
import flash.events.Event;
import flash.events.TouchEvent;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
var gravity = 0.6;
var floor = 410;
jordan1.y = floor;
jordan1.speedY = floor;
jordan1.impulsion = 10;
var onFloor:Boolean = false;
var keyRight:Boolean = false;
stage.addChild(jordan1);
stage.addChild(leftwall1);
stage.addChild(finish1);
stage.addChildAt(abovedoor, 0);
stage.addChild(left);
stage.addChild(right);
stage.addChild(jump);
addEventListener(Event.ENTER_FRAME, enters);
function enters(e:Event) {
    jordan1.speedY += gravity;
    jordan1.y += jordan1.speedY
    if(jordan1.y > floor) {
        jordan1.speedY = 0;
        jordan1.y = floor;
        onFloor = true;
        if(keyRight == true) {
            jordan1.gotoAndPlay(7);
        }
        if(keyRight == false) {
        jordan1.gotoAndStop(1);
        }
    }
}

function stageup(e:MouseEvent) {
    removeEventListener(Event.ENTER_FRAME,tickleft);
    removeEventListener(Event.ENTER_FRAME,tickright);
    removeEventListener(MouseEvent.MOUSE_UP, stageup);
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, stagedown);
function stagedown(e:MouseEvent) {
    stage.addEventListener(MouseEvent.MOUSE_UP, stageup);
}

stage.addEventListener(KeyboardEvent.KEY_DOWN, jumpkey);
function jumpkey(e:KeyboardEvent) {
    if(e.keyCode == Keyboard.SPACE) {
       if(onFloor == true)
       {
        jordan1.speedY=-jordan1.impulsion;
        onFloor = false;
        jordan1.gotoAndStop(2);
       }
       }
    }

stage.addEventListener(KeyboardEvent.KEY_DOWN, leftkey);
function leftkey(e:KeyboardEvent) {
if(e.keyCode == Keyboard.LEFT) {
    addEventListener(Event.ENTER_FRAME, leftkeytick);
    stage.addEventListener(KeyboardEvent.KEY_UP, leftkeydown);

}
}
function leftkeydown(e:KeyboardEvent) {
    removeEventListener(Event.ENTER_FRAME, leftkeytick);
    stage.removeEventListener(KeyboardEvent.KEY_UP, leftkeydown);

}
function leftkeytick(e:Event) {
    jordan1.x-=10;
        if(onFloor == true) {
    jordan1.gotoAndStop(3);
    }
    if(onFloor == false) {
        jordan1.gotoAndStop(6);
    }

}

stage.addEventListener(KeyboardEvent.KEY_DOWN, rightkey);
function rightkey(e:KeyboardEvent) {
if(e.keyCode == Keyboard.RIGHT) {
    keyRight == true;
    addEventListener(Event.ENTER_FRAME, rightkeytick);
    stage.addEventListener(KeyboardEvent.KEY_UP, rightkeydown);
}
}
function rightkeydown(e:KeyboardEvent) {
    removeEventListener(Event.ENTER_FRAME, rightkeytick);
    keyRight == false;
    stage.removeEventListener(KeyboardEvent.KEY_UP, rightkeydown);
}
function rightkeytick(e:Event) {
    jordan1.x+=10;
    if(onFloor == true) {
    jordan1.gotoAndPlay(7);
    }
    if(onFloor == false) {
        jordan1.gotoAndStop(5);
    }
}

// Just for this frame //
leftwall1.addEventListener(Event.ENTER_FRAME, leftwall1hit);
function leftwall1hit(e:Event) {
    if(leftwall1.hitTestObject(jordan1)) {
        jordan1.x +=10;
    }
}

abovedoor.addEventListener(Event.ENTER_FRAME, abovedoorhit);
function abovedoorhit(e:Event) {
    if(abovedoor.hitTestObject(jordan1)) {
        jordan1.x-=10;
    }
}

jordan1.addEventListener(Event.ENTER_FRAME, finish1hit);
function finish1hit(e:Event) {
    if(jordan1.x > 960) {
        gotoAndStop(67);

    }
}

So, when I test it and put the keydown it goestoandstops at 7, instead of playing.Please help! Thank you!

A: Your goto shouldn't be in your tick, or they will be executed each frame. Which explain why it's staying on frame 7.
Instead put them in your KEY_DOWNlistener :
animated = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, rightkey);
function rightkey(e:KeyboardEvent) {
  if(e.keyCode == Keyboard.RIGHT) {
    if(onFloor == true && !animated) {
       jordan1.gotoAndPlay(7);
    }
    if(onFloor == false && !animated) {
        jordan1.gotoAndStop(5);
    }
    animated = true;
    addEventListener(Event.ENTER_FRAME, rightkeytick);
    stage.addEventListener(KeyboardEvent.KEY_UP, rightkeydown);
  }
}
function rightkeydown(e:KeyboardEvent) {
    animated = false;
    removeEventListener(Event.ENTER_FRAME, rightkeytick);
    stage.removeEventListener(KeyboardEvent.KEY_UP, rightkeydown);
}
function rightkeytick(e:Event) {
    jordan1.x+=10;
}

But you shouldn't use a tick function with a keydown event.
KEY_DOWNis called each frame while you're pressing the/a key.
If you can't change your logic (which is not good for what you want to achieve) you could flag your handlers.
By having a boolean for each key you're listening to.
And then in your tick, do what you need to do depending on what keys are down.
keyRight = false;
keyLeft = false;
//... same for all your keys.
// or you could store them in one object for a more dynamic solution.

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
stage.addEventListener(Event.ENTER_FRAME,tick);

function keyDown(e:KeyboardEvent){
    if(e.keyCode === Keyboard.RIGHT && !keyRight){
        keyRight = true;
    }
    else if(e.keyCode === Keyboard.LEFT && !keyLeft){
        keyLeft = true;
    }
    //... same for all your keys.
}

function keyUp(e:KeyboardEvent){
    if(e.keyCode === Keyboard.RIGHT){
        keyRight = false;
    }
    else if(e.keyCode === Keyboard.LEFT){
        keyLeft = false;
    }
    //... same for all your keys.
}

function tick(e:Event){
     if(keyRight) jordan1.x += 10;
     if(keyLeft) jordan1.x -= 10;
     //... etc for all your keys.
}

This other question cover the subject of multiple KEY_DOWN pretty well.


text:
Q: Change credentials on GCloud API Storage manually due to account used is deleted i would like to ask.
There is a Golang instance running, which has features to upload/download to Google Cloud Storage API. Due to last developer is out and the credentials used is his, now his account is deleted.
Can i change the credentials manually to my account?
Sorry for bad explanation but i will try to give more details if u guys asked.
This is the response which i get if i access Google Cloud Storage API.
message: "Post https://www.googleapis.com/upload/storage/v1/b/psb/o?alt=json&projection=full&uploadType=multipart: oauth2: cannot fetch token: 400 Bad Request↵Response: {↵  "error": "invalid_grant",↵  "error_description": "Account has been deleted"↵}"

status: "500 Internal Server Error"


text:
Q: .net WinForms WebBrowser resets headers on redirect An internal webserver requires me to supply a custom http header in order to access the webpages. This works fine the most part but if the html or javascript starts a redirect or uses an AJAX request it doesn't use my headers anymore.
Is there some way to change this behaviour so it always sends my custom header?
    private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.Navigate("http://localhost/test.php", null, null, "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36\r\nSomething-Custom: TestValue");
    }

Javascript code in the php file:
<script>
window.location="?redirect";
</script>

The first requests received my header 'Something-Custom', while the second request with ?redirect doesn't. I also added the user-agent to verify that it indeed resets all headers.

A: There are several possible ways to do this. Really wide field for research.
Overwrite headers for each navigation
Hook Navigating event, cancel it and call Navigate with required headers (and do not cancel this event:)
You can even load data outside of WebBrowser control.
Change headers before navigation
If you don't like the idea of cancelling requests and then reissuing them, then you can try to hook Navigating event and update headers.
Here is the problem: IWebBrower2 control itself provides headers as an argument for BeforeNavigate event. But when .NET code handles this event, headers are not exposed in WebBrowserNavigatingEventArgs for a client code.
Possible solution is that you create own version of WebBrowserEvent, subclass WebBrowser control, override CreateSink method to connect your version of WebBrowserEvent. This version should handle headers correctly.
So you'd be able to change headers before navigation.
Adjust Javascript side - somewhat fuzzier.
You can connect browser application with client-side via WebBrowser.ObjectForScripting property - it is available for Javascript objects as window.external.
You can hook links click events, or build own approach about how to notify external object about navigation need.
Then you'll be able to perform all navigations from .NET side, specifying headers as needed.
System Proxy
Set up local proxy (you can experiment with Fiddler). You'll be able to make any headers manipulation you wish. The only issue that WebBrowser control would use proxy from IE configuration.


text:
Q: How to map structures inheriting a protocol? First of all I am really sorry about the terrible wording of the question but I am not sure how to put it.
Imagine we have a structure such as Fruit.
    struct Fruit {
        enum FruitType {
            case apple
            case pear
            case unknown
        }

        let id: String
        let type: FruitType
        let apple: Apple?
        let pear: Pear?
    }

    struct Apple {
        let something: String
    }

    struct Pear {
        let somethingElse: String
    }

I'd like to have the structures AppleFruit and PearFruit which would follow the protocol FruitProtocol and have the id of the fruit and the data of either Apple or Pear depending on the type. I have tried something like this but it does not work.
    init?(from fruit: Fruit) {
        switch fruit.type {
        case .apple:
            guard let apple = fruit.apple else { return nil }

            Apple(...)
        case .pear:
            guard let pear = coreAsset.pear else { return nil }

            Pear(...)
        default:
            self = nil
        }
    }

What am I missing here? I have tried with return or self = but none of them work.

A: In your description, Fruit isn't a protocol, it's an enum with associated data:
enum Fruit {
    case apple(Apple)
    case pear(Pear)
}

This will handle everything you're describing.
If there really is just one property in both (or a very small number of properties), then you can embed that directly into the enum:
enum Fruit {
    case apple(something: String)
    case pear(somethingElse: String)
}

This can get unwieldy very quickly, so it can often be better to have a separate struct to hold all the properties.


text:
Q: Chart.js not being displayed inside Jquery Dialog I am trying to display a chart with Chart.js inside a Jquery dialog. If I display the chart on a regular page it show without any problem.
This is the Smarty template I am using to try to display the chart (it's being included inside the dialog):

    {translate id=1431}
    <canvas id="myChart" width="400" height="400"></canvas>

Here I am opening the dialog:

Now, when I inspect the element with Firebug, the canvas has a width and height of 0, which explains why the chart can't be drawn. But I don't understand why the width and height are set to 0.
I am also using Bootstrap tabs inside the dialog, but even without the tabs, the chart is not being displayed.
Anybody know what I am missing here?

A: I have found the solution myself. Strangely enough, what made it work was moving the code that instantiates the chart object to the same Smarty template where I am calling the dialog. In that case, the canvas does have a size, and the chart is drawn correctly.
It is also displayed correctly inside the Bootstrap tab, and I can switch between tabs and the chart still works.
(In my case, the chart is being displayed in the first tab, which is set to active. If the chart is in another tab that's not active yet, I need to use "$('#tab1').on('shown.bs.tab', function (e)" instead of "$(document).ready(function()")
So the code now looks like this:


text:
Q: space complexity for queue with fixed size Currently, I am studying space and time complexity analysis. I have a question.
If we create a queue, we know we only need this queue to maintain 5000 elements at most.
The space complexity for this queue should be O(1)?

A: Within the constraints of your problem, no matter how many operations you perform, your queue never exceeds 5000 elements, so its size is bounded by a constant (5000). That's the definition of O(1) size complexity.

A: I haven't really studied space complexity as extensively as I did for time complexity. My research comes from https://www.quora.com/How-do-we-calculate-space-complexity
As we add to the queue of Size < 5000 the space complexity of the queue would be O(N), I would think. You are growing the queue which will take up N*(Size of element) bytes.

If my queue size is > 5000, then I will poll the top element from the queue and add a new element into the queue. Will that operation affect the space complexity for my queue?

If your queue was at max capacity (5000), and you were to remove the first element of the queue as you added more elements, then the overall size stays the same. Adding additional elements once queue reaches max capacity is now O(1).

A: It depends, if you somehow take all the space needed for the queue to hold all the 5000 elements, or just start with one that has 5000 element already, then is O(1) space complex. And it would be something like an array at this point.
However if you start with zero nodes and you keep adding nodes to the structure, then it would be O(n) complex since a queue is dynamic in that sense, regardless the fact you will have 5000 max elements.
Here is a nice complexity cheatsheet by the way.


text:
Q: WHICH TARGET FRAMEWORK IS REQUIRED XAMARIN FORMS 10 Severity    Code    Description Project File    Line    Suppression State
Error       The $(TargetFrameworkVersion) for App1.Android (v9.0) is less than the minimum required $(TargetFrameworkVersion) for Xamarin.Forms (10.0). You need to increase the $(TargetFrameworkVersion) for Application.
Previously I was getting same error with android 8.1 then I changed Target Framework to android 9.
Now it is giving same error for android 9 How to fix it I don't have Target Framework for android 10.
When I am forcefully changing android version to 10 via .csproj file I am getting this error
Could not determine API level for $(TargetFrameworkVersion) of 'v10.0'. App1.Android
I want to work on C# XAMARIN using Visual Studio 2017.

A: You need to update to VS2019, to target API Level 29 which is Android 10. Visual Studio 2017 only supports up to Android 9, API Level 28.


text:
Q: Can you run an inner join command on multiple tables with different primary keys? If I want to select rows from 3 different tables in SQL, do I need to have at least 1 table that relates to both?
Here is my example:
I have 3 tables - Table A, Table B and Table C
Table B has a primary key that relates to both Table A and C and I can relate to it easily using something like this.
In the coding examples, Table A = employee, Table B = works_with, Table C = client
SELECT employee.fname, employee.lname, client.client_name, works_with.total_sales
FROM works_with INNER JOIN client ON works_with.client_id = client.client_id
INNER JOIN employee ON works_with.emp_id = employee.emp_id;

So my  above query works for obvious reasons. But because I am learning MySQL I am trying to break stuff and test things to see what the limits are.
So this is my question - Is there a way to write a query like below. The example fails but am curious if its possible.
SELECT employee.fname, employee.lname, client.client_name, works_with.total_sales
    FROM employee INNER JOIN employee ON employee.emp_id = works_with.client_id FROM
    works_with INNER JOIN client ON works_with.emp_id = = client.client_id;

A: Your second query:
SELECT employee.fname, employee.lname, client.client_name, works_with.total_sales
FROM employee INNER JOIN
     employee
     ON employee.emp_id = works_with.client_id
FROM works_with INNER JOIN
     client
     ON works_with.emp_id = client.client_id;

This just makes no sense.  It has two FROM clauses.  That is not syntactically valid.  It has a self-join on employee, which is unnecessary for the logic you want.  It refers to works_with before it is defined in the FROM clause.  No sense at all.
I would suggest that you write your first query with table aliases:
SELECT e.fname, e.lname, c.client_name, ww.total_sales
FROM works_with ww INNER JOIN
     client c
     ON ww.client_id = c.client_id INNER JOIN
     employee e
     ON ww.emp_id = e.emp_id;


text:
Q: Difference between racearound condition and deadlock What is the difference between a dead lock and a race around condition in programming terms?

A: I assume you mean "race conditions" and not "race around conditions" (I've heard that term...)
Basically, a dead lock is a condition where thread A is waiting for resource X while holding a lock on resource Y, and thread B is waiting for resource Y while holding a lock on resource X. The threads block waiting for each other to release their locks.
The solution to this problem is (usually) to ensure that you take locks on all resources in the same order in all threads. For example, if you always lock resource X before resource Y then my example can never result in a deadlock.
A race condition is something where you're relying on a particular sequence of events happening in a certain order, but that can be messed up if another thread is running at the same time. For example, to insert a new node into a linked list, you need to modify the list head, usually something like so:
newNode->next = listHead;
listHead = newNode;

But if two threads do that at the same time, then you might have a situation where they run like so:
Thread A                       Thread B
newNode1->next = listHead
                               newNode2->next = listHead
                               listHead = newNode2
listHead = newNode1

If this were to happen, then Thread B's modification of the list will be lost because Thread A would have overwritten it. It can be even worse, depending on the exact situation, but that's the basics of it.
The solution to this problem is usually to ensure that you include the proper locking mechanisms (for example, take out a lock any time you want to modify the linked list so that only one thread is modifying it at a time).

A: A deadlock is when two (or more) threads are blocking each other. Usually this has something to do with threads trying to acquire shared resources. For example if threads T1 and T2 need to acquire both resources A and B in order to do their work. If T1 acquires resource A, then T2 acquires resource B, T1 could then be waiting for resource B while T2 was waiting for resource A. In this case, both threads will wait indefinitely for the resource held by the other thread. These threads are said to be deadlocked.
Race conditions occur when two threads interact in a negatve (buggy) way depending on the exact order that their different instructions are executed. If one thread sets a global variable, for example, then a second thread reads and modifies that global variable, and the first thread reads the variable, the first thread may experience a bug because the variable has changed unexpectedly.

A:
Deadlock :

*

*This happens when 2 or more threads are waiting on each other to release the resource for infinite amount of time.

*In this the threads are in blocked state and not executing.

Race/Race Condition:

*

*This happens when 2 or more threads run in parallel but end up giving a result which is wrong and not equivalent if all the operations are done in sequential order.

*Here all the threads run and execute there operations.

In Coding we need to avoid both race and deadlock condition.

A: Think of a race condition using the traditional example. Say you and a friend have an ATM cards for the same bank account. Now suppose the account has $100 in it. Consider what happens when you attempt to withdraw $10 and your friend attempts to withdraw $50 at exactly the same time.
Think about what has to happen. The ATM machine must take your input, read what is currently in your account, and then modify the amount. Note, that in programming terms, an assignment statement is a multi-step process.
So, label both of your transactions T1 (you withdraw $10), and T2 (your friend withdraws $50). Now, the numbers below, to the left, represent time steps.
       T1                        T2
       ----------------          ------------------------
 1.    Read Acct ($100)
 2.                              Read Acct ($100)
 3.    Write New Amt ($90)
 4.                              Write New Amt ($50)
 5.                              End
 6.    End

After both transactions complete, using this timeline, which is possible if you don't use any sort of locking mechanism, the account has $50 in it. This is $10 more than it should (your transaction is lost forever, but you still have the money).
This is a called race condition. What you want is for the transaction to be serializable, that is in no matter how you interleave the individual instruction executions, the end result will be the exact same as some serial schedule (meaning you run them one after the other with no interleaving) of the same transactions. The solution, again, is to introduce locking; however incorrect locking can lead to dead lock.
Deadlock occurs when there is a conflict of a shared resource. It's sort of like a Catch-22.
   T1            T2
   -------       --------
1.  Lock(x)
2.               Lock(y)
3.  Write x=1
4.               Write y=19
5.  Lock(y)
6.  Write y=x+1
7.               Lock(x)
8.               Write x=y+2
9.  Unlock(x)
10.              Unlock(x)
11. Unlock(y)
12.              Unlock(y)

You can see that a deadlock occurs at time 7 because T2 tries to acquire a lock on x but T1 already holds the lock on x but it is waiting on a lock for y, which T2 holds.
This bad. You can turn this diagram into a dependency graph and you will see that there is a cycle. The problem here is that x and y are resources that may be modified together.
One way to prevent this sort of deadlock problem with multiple lock objects (resources) is to introduce an ordering. You see, in the previous example, T1 locked x and then y but T2 locked y and then x. If both transactions adhered here to some ordering rule that says "x shall always be locked before y" then this problem will not occur. (You can change the previous example with this rule in mind and see no deadlock occurs).
These are trivial examples and really I've just used the examples you may have already seen if you have taken any kind of undergrad course on this. In reality, solving deadlock problems can be much harder than this because you tend to have more than a couple resources and a couple transactions interacting.
As always, use Wikipedia as a starting point for CS concepts:
http://en.wikipedia.org/wiki/Deadlock
http://en.wikipedia.org/wiki/Race_condition

A: Withe rest to Programming language if you are not locking shared resources and are accessed by multiple threads then its called as "Race condition", 2nd case if you locked the resources and sequences of access to shared resources are not defined properly then threads may go long waiting for the resources to use then its a case of "deadlock"


text:
Q: Jenkins: Increase Parameter after successful build I am using to Jenkins to deploy versions as needed.
So I have build parameter eg
VERSION 0.0.1

If job is successful and 0.0.1 has been deployed the next time job will be run I manually change version ie
VERSION 0.0.2

Build again and repeat etc.
Is there a way to automatically increase this number after a successful build?

A: You can create a post build script using the Post Build Script plugin which will update the version number and stores that in a file. Then you can access the version number in that file using the EnvInject plugin from your job.


text:
Q: Что делает данный однострочник на Perl?
Дополнение от модератора: данный вопрос содержит код, который может
привести к удалению всех файлов в вашей Линукс системе, не стоит
бездумно пытаться запустить данный код.
Подробнее см. Rm -rf

Что делает данный однострочник:
cat "test... test... test..." | perl -e '$??s:;s:s;;$?::s;;=]=>%-{<-|}<&|`{;;y; -/:-@[-`{-};`-{/" -;;s;;$_;see'

A: Эта программа удаляет все директории, в том числе и корневую /.
А если подробнее то:
echo "test... test... test..." выполнение этой команды не влияет на работу и добавлено, скорее всего, для усыпления бдительности. То, что происходит в остальном коде — совсем не очевидно из-за преднамеренно запутанного написания. В данной строчке записано всего три последовательно выполняемых команды. Запишем команду следующим образом:
$? ? s:;s:s;;$?: : s;;=]=>%-{<-|}<&|`{; ;
y; -/:-@[-`{-};`-{/" -; ;
s;;$_;see

Первая конструкция анализирует переменную $? — код возврата предыдущей команды. Так как перед выполнением этой конструкции дочерних процессов не создавалось, $? будет содержать 0, и выполнена будет вторая «ветка» — s;;=]=>%-{<-|}<&|`{;. Эта команда, в свою очередь, заменяет строку в переменной-аккумуляторе $_ на =]=>%-{<-|}<&|{ (первый символ после s устанавливает ограничитель параметров этого оператора, и хотя традиционно используются слэш / или |, для неясности в этой конструкции используется ограничитель ;).
Вторая команда транслирует содержимое «аккумулятора» по достаточно сложным правилам. В левой части указано четыре диапазона символов, в правой — один. Если раскрыть эти диапазоны, получим следующее соответствие:
 !"#$%&'()*+,-./:;<=>?@[\]^_`{|}
`abcdefghijklmnopqrstuvwxyz{/" -

В результате содержимое $_ принимает вид:
system"rm -rf /"

Третья же команда дважды (как инструктирует флаг ee) «вычисляет» содержимое аккумулятора — вышеуказанную деструктивную команду — и пытается заменить пустую строку в аккумуляторе на результат вычисления.


text:
Q: Comparing array from user to array from database PHP I am working on adding product module.
The user can upload a csv file to add products. How can I create a system that  if there is existing product in db, it will skip the product and then check again for another product. If there is no such product in the db, then the product will be added into the db.
So let's say
//Products in db
//Code       //Description
1            Item 1
2            Item 2
3            Item 3

//Products in user input
//Code       //Description
1            Item 1
3            Item 3
4            Item 4
5            Item 5

From above example, how can I create a system that will add only Item 4 and Item 5 into the db?
Here is my $db_products array that contains products from db
foreach($db_products as $prod){
  $products[] = array(
    "code" => $prod['code'],
    "description" => $prod['description']
  );
}

Here is my $products_array which contains user input
foreach($products as $v){
    $products_array[] = array(
        "code"        => $v['code'],
        "description" => $v['description'],
    );
}

I used this code to compare
foreach($products_array as $prod){
  foreach($db_products as $db_prod){
    $result = array_diff($db_prod, $prod);
        var_dump($result);
  }
}

But why it returns me the same data between the arrays?
What am I missing here?? thank you

A: You can use a recursive function to check if $prod from $products_array exists in the multidimensional array $db_products, like this:
$products_to_add = array();
foreach ($products_array as $prod) {
    if (!inMultiArray($prod, $db_products)) {
        $products_to_add[] = $prod; // Add the product that's -not- in the DB to $products_to_add
    }
}

function inMultiArray($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (is_object($item)) {
            $item = get_object_vars($item);
        }

        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && inMultiArray($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}


text:
Q: golang gin-gonic and splitting files in package I am quite new to go and try to learn, I am setting up an application with a gin-gonic server.
I managed to have it to work with everything in on main package, I would like to organize it better with all the apirest related in a package (which I manage) AND to split each group CRUD by file.
so in the "main" file of the package within the init function, I defined :
Router := gin.New()
Router.Use(gin.Logger())
Router.Use(gin.Recovery())

and I though that I would be able in each other files of the package to use it like that :
v1 := Router.Group("/api/v1/todos")
v1.Use(AuthRequired())
{
    v1.POST("/", CreateTodo)
    v1.GET("/", FetchAllTodo)
    v1.GET("/:id", FetchSingleTodo)
    v1.PUT("/:id", UpdateTodo)
    v1.DELETE("/:id", DeleteTodo)
}

or
packagename.Router.Group

but none are working and I get :

undefined: Router in Router.Group

Stéphane
PS : I did setup a sub folder for the package and I am able to go build it if it's in one file.

I though that the solution was to declare the Router variable as *gin.Engine but while it's compiling fine, I get a panic error on the Router.Group call
let me post some more part of code :
maincode.go :
package main

import (
    "fmt"
    "./apirest"
    "github.com/braintree/manners"
)

func main(){
    fmt.Printf("hello world.\n")
    //router.Run()
    manners.ListenAndServe(":8080", apirest.Router)
}

Then I split the apirest package in 2 files :
apirest.go (I did manually cleanup, maybee I missed an import) :
package apirest

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "github.com/braintree/manners"
    "os"
    "os/signal"
)

//Router pour gérer l'api
var Router *gin.Engine

/*
    MAIN FUNCTION
*/
func init() {

    Router := gin.New()
    Router.Use(gin.Logger())
    Router.Use(gin.Recovery())

    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt)
    go func(){
        for sig := range c {
            // sig is a ^C, handle it
            fmt.Printf("ctl+c catched "+sig.String())
            manners.Close()
        }
    }()

    LoadMonitor()

}

and then the todoCRUD.go file that handle all the declaration, the todoCRUD.go and apirest.go are in the same subfolder apirest (and compile ok) :
package apirest

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "gopkg.in/validator.v2"
    "github.com/jinzhu/gorm"
    "strconv"
    "net/http"
    "time"
)

//Todo definition d'un element todo
type Todo struct {
    gorm.Model
    CreatedAt   time.Time
    UpdatedAt   time.Time
    OwnerID     int    `json:"ownerid"  validate:"nonzero"`
    URL         string `json:"url"`
}

//TransformedTodo version pour le retour d'api sans certaines infos
type TransformedTodo struct {
    ID          uint   `json:"id"`
    CreatedAt   time.Time
    UpdatedAt   time.Time
    OwnerID     uint   `json:"ownerid"`
    URL         string `json:"url"`
}

//LoadTodo permet de lancer le mappage todos
func LoadTodo(){
    v1 := Router.Group("/api/v1/todos")
    {
        v1.POST("/", CreateTodo)
        v1.GET("/", FetchAllTodo)
        v1.GET("/:id", FetchSingleTodo)
        v1.PUT("/:id", UpdateTodo)
        v1.DELETE("/:id", DeleteTodo)
    }
}

//CreateTodo génération d'un todo
func CreateTodo(c *gin.Context) {

    owner, _ := strconv.Atoi(c.PostForm("ownerid"))
    todo := Todo{
        OwnerID: owner,
        URL: c.PostForm("url"),
    };
    v := validator.NewValidator()
    if errs := v.Validate(todo); errs!=nil {
        errors := errs.(validator.ErrorMap)
        var errOuts []string
        for f, e := range errors {
            errOuts = append(errOuts, fmt.Sprintf("\t - %s (%v)\n", f, e))
        }
        //c.JSON(500, gin.H{"Error": errs.Error()})
        c.JSON(500, gin.H{"Erreur sur le(s) champ(s) : ": errOuts})
    } else {

        db, _ := Database()
        defer db.Close()
        db.Save(&todo)

        c.JSON(http.StatusCreated, gin.H{"status" : http.StatusCreated, "message" : "Todo item created successfully!", "resourceId": todo.ID})
    }
}

//FetchAllTodo récupération de tous les todos
func FetchAllTodo(c *gin.Context) {
    var todos []Todo
    var _todos []TransformedTodo

    db, _ := Database()
    defer db.Close()
    db.Find(&todos)

    if (len(todos) <= 0) {
        c.JSON(http.StatusNotFound, gin.H{"status" : http.StatusNotFound, "message" : "No todo found!"})
        return
    }

    //transforms the todos for building a good response,
    //je peux choisir des champs a ne pas display
    for _, item := range todos {
        status := false
        if (item.Status == 1) {
            status = true
        } else {
            status = false
        }
        _todos = append(_todos, TransformedTodo{ID: item.ID, URL:item.URL})
    }
    c.JSON(http.StatusOK, gin.H{"status" : http.StatusOK, "data" : _todos})
}

//FetchSingleTodo Récupération d'un seul todo en fonction de son id
func FetchSingleTodo(c *gin.Context) {
    var todo Todo
    todoID := c.Param("id")

    db, _ := Database()
    defer db.Close()
    db.First(&todo, todoID)

    if (todo.ID == 0) {
        c.JSON(http.StatusNotFound, gin.H{"status" : http.StatusNotFound, "message" : "No todo found!"})
        return
    }

    _todo := TransformedTodo{ID: todo.ID, URL:todo.URL}
    c.JSON(http.StatusOK, gin.H{"status" : http.StatusOK, "data" : _todo})
}

//UpdateTodo Mise à jour d'un todo
func UpdateTodo(c *gin.Context) {
    var todo Todo
    todoID := c.Param("id")
    db, _ := Database()
    defer db.Close()
    db.First(&todo, todoID)

    if (todo.ID == 0) {
        c.JSON(http.StatusNotFound, gin.H{"status" : http.StatusNotFound, "message" : "No todo found!"})
        return
    }

    db.Model(&todo).Update("title", c.PostForm("title"))
    db.Model(&todo).Update("completed", c.PostForm("completed"))
    c.JSON(http.StatusOK, gin.H{"status" : http.StatusOK, "message" : "Todo updated successfully!"})
}

//DeleteTodo Suppression d'un todo
func DeleteTodo(c *gin.Context) {
    var todo Todo
    todoID := c.Param("id")
    db, _ := Database()
    defer db.Close()
    db.First(&todo, todoID)

    if (todo.ID == 0) {
        c.JSON(http.StatusNotFound, gin.H{"status" : http.StatusNotFound, "message" : "No todo found!"})
        return
    }

    db.Delete(&todo)
    c.JSON(http.StatusOK, gin.H{"status" : http.StatusOK, "message" : "Todo deleted successfully!"})
}

The Idea is to have a xxxxCRUD.go file for each entity to handle but the whole folder in the same package.
the exact errror is :

PS D:\www\developpement> go run .\maincode.go [GIN-debug] [WARNING]
  Running in "debug" mode. Switch to "release" mode in production.
   - using env:   export GIN_MODE=release
   - using code:  gin.SetMode(gin.ReleaseMode)
panic: runtime error: invalid memory address or nil pointer
  dereference [signal 0xc0000005 code=0x0 addr=0x0 pc=0x46cc0f]
goroutine 1 [running]: panic(0x831880, 0xc04200a080)
          C:/Go/src/runtime/panic.go:500 +0x1af
  /D/www/developpement/apirest.LoadTodo()
          D:/www/developpement/apirest/todoCRUD.go:33 +0x2f   [Router.Group]
  /D/www/developpement/apirest.init.1()
          D:/www/developpement/apirest/apirest.go:73 +0x220     [LoadTodo()]
  /D/www/developpement/apirest.init()
          D:/www/developpement/apirest/todoCRUD.go:190 +0x80  [last line] main.init()
          D:/www/developpement/maincode.go:13 +0x3a         [manners.ListenAndServe(":8080", apirest.Router)] exit status 2

I hope that this will help to understand !
Thanks for your time and help !
Stéphane

A: I did manage to make it work by "sending" the router in the LoadTodo function :
in apirest.go :
LoadTodo(Router)

and in todoCRUD.go :
func LoadTodo(r *gin.Engine){

and it's working fine ... I hope I didn't bring a bug failure in the code ...
Stéphane


text:
Q: NetShareEnum returns 1702 Im writing some software and i need to get the list of Network Shared Folders. I did all according to this article
http://www.codeproject.com/Articles/2939/Network-Shares-and-UNC-paths
and the method NetShareEnum returns 1702, and returns no folders.
The compiled sample from article works fine, I tried to dissasemble it througth Resharper but it is also returns 1702 result here:
protected static void EnumerateSharesNT(string server, ShareCollection shares)
{
    int dwLevel = 2;
    int hResume = 0;
    IntPtr zero = IntPtr.Zero;
    try
    {
        int num2;
        int num3;
        **int num4 = NetShareEnum(server, dwLevel, out zero, -1, out num2, out num3, ref hResume);**
        if (5 == num4)
        {
            dwLevel = 1;
            num4 = NetShareEnum(server, dwLevel, out zero, -1, out num2, out num3, ref hResume);
        }
        if ((num4 == 0) && (num2 > 0))
        {
            Type t = (2 == dwLevel) ? typeof(SHARE_INFO_2) : typeof(SHARE_INFO_1);
            int num6 = Marshal.SizeOf(t);
            int num7 = 0;
            for (int i = zero.ToInt32(); num7 < num2; i += num6)
            {
                IntPtr ptr = new IntPtr(i);
                if (1 == dwLevel)
                {
                    SHARE_INFO_1 share_info_ = (SHARE_INFO_1)Marshal.PtrToStructure(ptr, t);
                    shares.Add(share_info_.NetName, string.Empty, share_info_.ShareType, share_info_.Remark);
                }
                else
                {
                    SHARE_INFO_2 share_info_2 = (SHARE_INFO_2)Marshal.PtrToStructure(ptr, t);
                    shares.Add(share_info_2.NetName, share_info_2.Path, share_info_2.ShareType, share_info_2.Remark);
                }
                num7++;
            }
        }
    }
    finally
    {
        if (IntPtr.Zero != zero)
        {
            NetApiBufferFree(zero);
        }
    }
}

server is input string for example "\192.168.1.69"


text:
Q: Anyone experienced data lost when using AWS kinesis streams, lambda and firehose? I'm currently sending a series of xml messages to aws kinesis stream, I've been using this on different projects, so I'm pretty confident that this bit works. Then I've written a lambda to process events from kinesis stream to kinesis firehose:
import os
import boto3
import base64

firehose = boto3.client('firehose')

def lambda_handler(event, context):
    deliveryStreamName = os.environ['FIREHOSE_STREAM_NAME']

    # Send record directly to firehose
    for record in event['Records']:
        data = record['kinesis']['data']

        response = firehose.put_record(
            DeliveryStreamName=deliveryStreamName,
            Record={'Data': data}
        )
        print(response)

I've set the kinesis stream as the lamdba trigger, and set the batch size as 1, and starting position LATEST.
For the kinesis firehose I have the following config:
Data transformation*: Disabled
Source record backup*: Disabled
S3 buffer size (MB)*: 10
S3 buffer interval (sec)*: 60
S3 Compression: UNCOMPRESSED
S3 Encryption: No Encryption
Status: ACTIVE
Error logging: Enabled

I sent 162 events, and I read them from s3, and the most I've managed to get it 160, and usually it's less. I've even tried to wait a few hours incase something strange was happening with retries.
Anyone had any experience using kinesis-> lamdba -> firehose, and seen issues of lost data?

A: From what I see here, most likely items are lost when you are publishing data to the Kinesis Stream (not FireHose).
Since you are using put_record when writing to FireHose, it will throw an exception and the lambda will be retried in that case. (Make sense to check if there are failures on that level).
So considering that I may suppose that records are lost before they reach Kinesis stream.
If you are sending items to Kinesis stream using put_records method, that doesn't guarantee that all the records will be sent to the stream(due to exceeded write throughput or internal errors), some of the records may fail to be sent. In that case failed subset of records should be resend by your code (Here is Java example, sorry I wasn't able to find the Python one).


text:
Q: Do I need to do any extra work when publishing an app in Google Play Store which uses firebase/firestore service? I have published several normal apps in Google Play Store which do not use firebase/firestore service. Now, I am going to publish an app which uses firebase/firestore service.
In some places I have seen some people using SHA-1 when publishing an app having firebase/firestore service, but I am confused about it.
Do I need to do any extra work when publishing an app which uses firebase/firestore service?
(my app uses Firebase Authentication)

A: If you are signing your published apps with Google Play then add the newly generated SHA-1 in Release>App Signing>App signing key certificate to the project setting on firebase.
Otherwise, No extra work needed as long as you have setup your firebase project correctly.


text:
Q: AggregateException on Cluster.OpenBucket method in Couchbase I am trying out Couchbase database, I've followed the tutorial here:
http://developer.couchbase.com/documentation/server/4.0/sdks/dotnet-2.2/hello-couchbase.html
I've installed the nugget from Package manager, and started to code. But as I am trying to call Cluster.OpenBucket function I am getting :

An unhandled exception of type 'System.AggregateException' occurred in Couchbase.NetClient.dll
"A connection attempt failed because the connected party did not
  properly respond after a period of time, or established connection
  failed because connected host has failed to respond"

That's my code:
class DbMgr
{
    private static readonly Cluster Cluster = new Cluster();
    const string BUCKET_NAME = "This-Is-A-Bucket-Name";

    public void Init()
    {
        //This is where I get exception....
        using (var bucket = Cluster.OpenBucket(BUCKET_NAME, ""))
        {
            var document = new Document<dynamic>
            {
                Id = "Hello",
                Content = new
                {
                    name = "Couchbase"
                }
            };
        }
    }
}

Any Ideas?


text:
Q: Container name is not resolved in compose, but IP is I run two containers in compose mode. Containers can communicate with each other by IP, but not by container name - it is not resolved.
Docker network inspect where containers are ran

docker inspect mycompose
[
    {
        "Name": "mycompose",
        "Id": "5d6f614b1a67efa38143adf745700cac103be07f74bcb219fd547aa8ce8abd1e",
        "Created": "2019-11-07T17:08:49.940162+01:00",
        "Scope": "local",
        "Driver": "nat",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "windows",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.22.144.0/20",
                    "Gateway": "172.22.144.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": true,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "876efda0f26487b4c56dd52485e6f76ecc5c97214ae99cb0760a5cad4c65ea74": {
                "Name": "mycompose_brim_1",
                "EndpointID": "15a3049b1f79d5da3129030574fd16dc46ced5246f15fe00b08b778a2b8ab8ef",
                "MacAddress": "00:15:5d:57:23:87",
                "IPv4Address": "172.22.144.113/16",
                "IPv6Address": ""
            },
            "b8c596491ae84a1da8d597ea6ab6edf5872405856520e46d8f35581f48314b5f": {
                "Name": "mycompose_brimdb_1",
                "EndpointID": "8bbf233cfeb57729570f581dd34f6677a6a6655dd64c2090dacc26b91604eb7c",
                "MacAddress": "00:15:5d:57:25:be",
                "IPv4Address": "172.25.113.185/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.windowsshim.hnsid": "48240B53-F49A-43B9-9A20-113C047D65A1"
        },
        "Labels": {
            "com.docker.compose.network": "v2",
            "com.docker.compose.project": "mycompose",
            "com.docker.compose.version": "1.24.1"
        }
    }
]

Trying to ping one container within another by container name:
PS C:\inetpub\wwwroot> ping mycompose_brimdb_1
Ping request could not find host mycompose_brimdb_1. Please check the name and try again

Trying to ping by service name:
PS C:\inetpub\wwwroot> ping brimdb
Ping request could not find host brimdb. Please check the name and try again.

Trying to ping same container by IP:
PS C:\inetpub\wwwroot> ping 172.25.113.185

Pinging 172.25.113.185 with 32 bytes of data:
Reply from 172.25.113.185: bytes=32 time=1ms TTL=128
Reply from 172.25.113.185: bytes=32 time<1ms TTL=128
Reply from 172.25.113.185: bytes=32 time=5ms TTL=128
Reply from 172.25.113.185: bytes=32 time<1ms TTL=128

Ping statistics for 172.25.113.185:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 5ms, Average = 1ms

compose file:
version: "3.7"

services:

  brim:
    image: brim:latest
    ports:
      - target: 50893
        published: 50893
        protocol: tcp

  brimdb:
    image: brimdb:latest
    ports:
      - target: 1555
        published: 1555
        protocol: tcp


text:
Q: MSOLAPSvc.3 service missing from kerberos delegation I'm trying to configure PerformancePoint using this article and Analysis Services is running and configured on that box, but the constrained delegation won't let me choose the MSOLAPSvc.3 service because it's not there. My SPN's are as follows.
PerformancePoint Web application pool service account:

HTTP/webapplication HTTP/webapplicationFQDN
  HTTP/webapplicationFQDN:port (port 80 is seperate and uses NTLM)

SQL Analysis Service account:

MSSQLSVC/SQLServer MSSQLSVC/SQLServerFQDN
  MSSQLSVC/SQLServerFQDN:instance MSOLAPSvc.3/SQLServer
  MSOLAPSvc.3/SQLServerFQDN MSOLAPSvc.3/SQLServer:instance

PerformancePoint Service Application Pool account:

SP/svcPPS (to open delegation)

Claims to Windows Token Service Application Pool account:

SP/C2WTS (to open delegation)

IIS settings:
Kernel mode and EP off.
Providers are: Negotiate first, NTLM second.
I am getting security logs that Kerberos is used successfully on the web application level, but using Kerberos for PerformancePoint i've read needs to have constrained delegation, and I can't select the MSOLAPSvc.3 service on the sqlserver, and therefore my dashboard designer will not connect to a test data source.

A: After 4 hours, I found you need to add the SPN of the service you want to use to the SERVER itself. Anything that is missing is not added to that server's SPN (not user account)
setspn -A MSOLAPSvc.3/serverFQDN server


text:
Q: Redis/Mongo Sorted list complexity I know it's not a fair comparison, but my question is theoretically about the complexity of operations.
Redis (sorted set)-

*

*ZADD - Time complexity: O(log(N)) where N is the number of elements
in the sorted set.

*ZRANGE - Time complexity: O(log(N)+M) with N
being the number of elements in the sorted set and M the number of
elements returned.

What would be the Mongo equivalent on a sorted array:
{
   sorted_list : [{name : <string>,score : <Number>}]
}

collection.update(
   { _id: 1 },
   {
     $push: {
       sorted_list: {
         $each: [ { name: 3, score: 8 }, { name: 4, score: 7 }, { name: 5, score: 6 } ],
         $sort: { score: 1 }
       }
     }
   }
)

collection.find( { _id: 1}, { sorted_list: { $slice: [ 20, 10 ] } } )

What is the complexity of the update and find operations?
Moreover, my aim is to find a solution where the "read" operation (pull from an index in the sorted list), will be optimal - O(1). And still have an O(log(N)) insertion. That should be viable by utilizing memory (have an array copy of the sorted set).
Is there a platform which implement it?

A: I have implemented zadd and zrange for a project in mongodb although I didn't store the sorted set elements in an embedded array.
The problem I had with embedded arrays is that there was no easy way to make sure elements were unique. In your case someone can zadd another element with the same name but with a different score. In this case redis just updates the score of the element and doesn't add a new element.
So instead of using an embedded array I made each sorted set element a new document in the following form.
{
 _key: "sortedSetKey",
 value: "value1",
 score: 12
},
{
 _key: "sortedSetKey",
 value: "value2"
 score: 3
}

There are 2 compound indices on the collection for {_key: 1, score: -1} and {_key: 1, value: -1}.
With all of this in place adding a new element to a sorted set becomes :
db.objects.update({
  _key: key, value: value
}, {
   $set: {
     score: parseInt(score, 10)
   }
}, { upsert: true });

This will be O(log(n)) since there is an index on (key, value).
Getting a range is a bit more complex :
db.objects.find({_key: key}, {fields: {_id: 0, value: 1})
    .limit(stop - start + 1)
    .skip(start)
    .sort({score: sort})

Again this uses the key index to find all the elements that belong to a sorted set and then sorts on the score field so the compound index is used. The limit and skip is used to grab a portion of the sorted set. Obviously this won't be O(1). If you pass in higher values of skip in a large sorted set it will scan many documents.
Hope that gives some ideas.
You can check the full source here


text:
Q: Url of active index with p:steps I'm using p:steps as a workflow, it works well except active index doesn't have an URL attach
xhtml:
<p:fieldset legend="Etape" toggleable="true" toggleSpeed="500" style="height:110px;">
    <p:steps model="#{etapeModel.model}" activeIndex="#{besoin.etape.code}"
    styleClass="custom" readonly="false" />
</p:fieldset>

java code:
public EtapeModel(){
    model = new DefaultMenuModel();
    Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
    selected = BesoinService.get(Integer.parseInt(params.get("id")));

    for(Etape e : Etape.values()){
        DefaultMenuItem item = new DefaultMenuItem(e.getLibelle());
        item.setUrl("besoinForm.xhtml?faces-redirect=true&i=1&id="+selected.getId()+"&etape="+e.getCode());
        item.setId("etape"+e.getCode());
        model.addElement(item);
    }
}

I understand this behaviour, but what possibilities I have to attach an url on active index ?
Mojarra 2.2.0 and Primefaces 5.3

A: I don't use this component anymore, but best solution I found is to write a custom component based on Steps, a good example here
http://www.mastertheboss.com/jboss-web/primefaces/extending-primefaces-components
By extending Steps and StepsRenderer using this source and modify the way attribute "href" is write (and "class" too for thing like cursor:hover)


text:
Q: Rails: Two instance variables or just one and create another one in the view I have a doubt of good manners in Rails and I believe MVC in general.  I have a controller which retrieves some objects from a model given a particular condition.  I need those objects in the view, and I also need a particular data structure with attributes of those objects.  That data structure is like this:
[[object1.attr1, object1.attr2],[object2.attr2,object2.attr2],...]

My question is:
Should I create two instance variables in the controller: one with all the objects retrieved from the model, and another one with the data structure created from the attributes of those objects or should I just create one instance variable with all the objects and create that data structure in the view?

A: It depends, but you shouldn't create data structures in the view.
Either do it in a controller function, or if it's tightly coupled to the model, in the model. From the limited description it sounds like this belongs in the model, but it's hard to say.

A: You could move some of your code out of your views to:

*

*a view helper

*the controller

*the model
A Rails Helper (opt. 1) seem more appropriate for your case. If you need for example to populate a select tag an helper with a method that returns options_for_select(...your complex structure formatted) would be the right choice.
You can use options_for_select (from the rails guides) this way
<%= options_for_select([[object1.attr1, object1.attr2],[object2.attr2,object2.attr2],...], 2) %> will become:
<option value="object1-attr2-value">object1-attr1-value</option>
<option value="object2-attr2-value" selected="selected">object2.attr1-value</option>
...

You can add that method inside the ApplicationHelper (if it needs to be application wide) or in a model specific helper:
# app/helpers/...the helper you choose
def options_for_your_complex_select(default_state)
  options_for_select( [[object1.attr1, object1.attr2],[object2.attr2,object2.attr2],...],
                  default_state )
end

and the use this helper in your views this way (please choose a better method name than mine :) ): <%= select_tag :state, options_for_your_complex_select(params[:default_state]) %>
This will help you make your code more manageable and your view more readable.
Rails best practices website has more on this. See how move your code in a ViewHelper, Model and Controller.
If you have to deal with a lot of attributes, this screencast about the draper gem by @ryanb explain how to simplify your views.


text:
Q: Array not displaying properly when passed to a function as pointer Given below is my main() function:
int main()
{
    int N = 4;
    int A[N][N] = {
        {1 , 0 , 0 , 0},
        {1 , 1 , 0 , 1},
        {0 , 1 , 0 , 0},
        {1 , 1 , 1 , 1}
    };
    for (int i = 0; i < N; ++i)
    {
        for (int j = 0; j < N; ++j)
            cout << A[i][j] << " ";
        cout << "\n";
    }
    cout << "\n";
    printSolution(N , *A);
    cout << "\n";
    return 0;
}

Here I had declared a 4x4 array with values. Given below is printSolution where I am passing a pointer to the array inside it.
void printSolution(int N , int *sol)
{
    for (int i = 0; i < N; ++i)
    {
        for (int j = 0; j < N; ++j)
            cout << *((sol + i) + j) << " ";
        cout << "\n";
    }
}

Given below is the output:
1 0 0 0
1 1 0 1
0 1 0 0
1 1 1 1

1 0 0 0
0 0 0 1
0 0 1 1
0 1 1 0

As it is visible in the output, the for loop inside the main function printed the array correctly, whereas the printSolution() function could not print it properly. Why is that so?

A: *((sol + i) + j)

Say, for i = 2 and j = 2 this is merely *(sol + 4), the element in row 1 column 0 (exactly what is printed.)
You probably want *((sol + i * N) + j).


text:
Q: LaTeX Markup Options? I was wondering what prevented the implementation of a MarkDown system in (La)TeX? I know that pandoc does a conversion of MarkDown with extra features to LaTeX. I also know that many are happy with the way LaTeX is right now, so please do not feel offended.
In particular I was wondering why stuff like -> or => cannot be translated to \rightarrow or \Rightarrow and similar transformations along with the usual MarkDown features. After all to me it seems that (La)Tex after all is a way to mark-up plain text in a way that it can be rendered neatly for printing devices. I also know that there's LyX and TeXmacs but those have left the plain-text approach of tex.
In particular I'm genuine curious if and why one could not implement MarkDown features right in LaTeX, after all TeX is Turing complete, no? Does it in some way break the existing system in a way I do not see?
There's a lot that could make writing text a little more pleasant on the eyes. For example, writing a theorem like so:
THEOREM: ...

PROOF: ...

Next paragraph continues after two new lines...

and similarly for definitions lemmata, you name it. Again please don't get me wrong. There are enormous amounts of useful commands in (La)TeX. As it is now, (La)TeX does do some of these transformations already. E.g. turning --- into an em-dash or treating a blank line as the separation of two paragraphs. And modern (La)TeX can deal with unicode thus not necessarily requiring the ASCII-fication of Greek Letters. There will always be more obscure things one wants to do with (La)TeX, but what is preventing the system from incorporating features like these? Or am I missing something completely and this is possible already?

A: You might find this interesting (though it's for ConTeXt, not LaTeX):
https://github.com/adityam/filter

A: Here is a proof of concept solution that works in ConTeXt MkIV.
\defineenumeration[THEOREM][text={Theorem },style=italic]

\usemodule[translate]
\translateinput[THEOREM:][\THEOREM]
\translateinput[->][\rightarrow]
\enableinputtranslation

\starttext

THEOREM: Let $f : X -> Y$ be a continuous function ...

Paragram after the theorem.

\stoptext

which gives the expected output. With LuaTeX it is possible to parse the input before it is fed to TeX, and if you want, you could write a markdown parser in lua. IIRC John MacFarlane has already written a LPEG based parser for Markdown, so it should be relatively easy to incorporate it with LuaTeX.

A: A wiki-like markup/down syntax is already supported by the nicetext package.
And yes, TeX is Turing (not turning) complete and can be used to implement parsers for a lot of different syntaxes. See the tikz, tikz-timing or e.g. the \Macro macro of ydoc for a few more complex examples. However, there are limits -- I wouldn't try to program an OS with it (TeXnix or so) :-)

A: Not really an answer to your question, but a related idea I had a long time ago: Some of the substitutions you want could be done by the editor. I once wrote an editor for LaTeX where you have a substitution table, so that you can get the following effects. If you type ->, then this is automatically converted to →, but saved as \to. When \to is read from a file (or typed), you again see → in the editor. Same for ∑ for \sum, ± for \pm, ∞ for \infty and so on.
The main advantage: In the editor it looks nice, and the file is plain ascii text. However, I've got no idea what editors support this feature.
Similar things would be possible for your THEOREM: ... PROOF:, but that would be less elementary to implement.

A: LaTeX is this LaTeX for historical reason. It is not perfect. And it could support some MarkDown features. For example, there is a LaTeX package wiki, which support document like this:
\documentclass{article}
\usepackage{wiki}
\begin{document}
\wikimarkup

==section title==

A numbered list:
# foo
# bar
# baz

===subsection title===

''important'' thing

\end{document}

Another good example is listings package. It read the input verbatim, recognize the keywords, and make proper output. listings is designed for typeset programming languages with syntax highlighting. However, the same approach can be used for your request. So, this shows another example you request:
\documentclass{article}
\usepackage{listings}
\lstset{literate={->}{$\rightarrow$}1 {=>}{$\Rightarrow$}1}

\begin{document}

\begin{lstlisting}
a -> b, A => B
\end{lstlisting}

\end{document}

But remember, TeX, the core language is not designed for this kind of markup texts. We have to use some weird trick to implement the features in TeX.
Unlike most modern programming language, TeX uses category codes for special purpose. If TeX use a common lexical analysis, it will be easier to define a markdown system. In TeX, it is easy to define a command \THEOREM or \PROOF to typeset a theorem. But it will take much more effort (although possible) to support a syntax like
THEOREM: foo
PROOF: baz

And we can ask why Knuth choose this macro syntax. I think it is natural to use a markup language syntax, like troff, SGML and RTF. And it is clear that a pure markdown system (like stackexchange without HTML) is not powerful enough for complex style. So early TeX, which is a personal tool of Knuth, needn't support a Markdown syntax, thus the design based on category codes and macros is OK. Many people complain about this, I have no good idea for this.
Things are changing, LaTeX becomes easier to use today. For math symbol, we can use unicode-math package to write a math equation like this:
$ ∑A_n → ±∞ $

A: The problem with things like
THEOREM: ...

PROOF: ...

is, that at the point we can decide that we want special formatting here (the :), the signs before it are already typeset, and it is extremely hard for TeX (or macros written in TeX) to get these characters typed before again (to make them bold or similar).
One workaround would be to make the line-breaking character (or \par) active, and then implement a lookahead in macros (or in Lua with LuaTeX) to decide what to do next.


text:
Q: how to set radiogroup radiofield based on the json data extjs 4 hi forum member I am having one problem with setting the radiofield in the extjs 4
my form radiogroup xtype code is given below
{
  xtype: 'radiogroup',
  dataIndex: 'gender',
  margin: 5,
  fieldLabel: 'Gender',
  items: [{
    xtype: 'radiofield',
    name: 'gender',
    boxLabel: 'Male',
    inputValue:'0'
  }, {
    xtype: 'radiofield',
    name: 'gender',
    boxLabel: 'Female',
    inputValue:'1'
  }]
}

my json data I am receiving is
{
  "total": 1,
  "success": true,
  "employeedata": [{
     "username": "yaryan997",
     "surname": "Singh",
     "firstname": "Yogendra",
     "gender": false
  }]
}

my employee list view has action column editEmployee which executes the below function
editEmployee:function(grid,no,rowindex,colindex,temp) {
        alert('Edit EMPLOYEE button pressed');
        var rec = grid.store.getAt(rowindex);
        var employeeid = rec.get('id');

        store = grid.getStore();
        store.load({
            params: {'employeeid':employeeid},
            scope: this,
            callback: function(records, operation, success) {
                //the operation object contains all of the details of the load operation
                console.log(records);
                this.getEmployeeEdit().editform=1;
                this.getEmployeeEditForm().loadRecord(rec);
                this.getEmployeeEdit().show();
            }
        });
        this.getEmployeeStore().load();
    },

based on the id the editEmployee view is shown. My edit Employee shows all the values correctly but only the problem is with the radiofield. They didn't show the selected value.
my json data I had provide you which comes as employeedata
I am not able to set the radiogroup gender based on the data i am receiving from the json.
please suggest me some solution for it.

A: First you should set inputValue to 'false' and 'true'. The second is the new design of a radiogroup. You will find the solution in my thread at the sencha forum See: http://www.sencha.com/forum/showthread.php?187185-Set-a-int-value-on-a-radiogroup-fails&goto=newpost
The problem is that setValue is expecting a object which would only be the case if you had to datatypes for gender; one for male and one for female... And that's the point why I posted this as bug. Down the override code from my post.
setValue: function (value) {
    if (!Ext.isObject(value)) {
        var obj = new Object();
        obj[this.name] = value;
        value = obj;
    }
    Ext.form.RadioGroup.prototype.setValue.call(this, value);
}

A: Actually, the problem is that you are trying to pass a boolean value to your radioBox:
"gender": false

which you are not supposed to.
The radioBox will be set to checked/unchecked if a true/false value is passed to its setValue method, ignoring what is the inputValue field set to.
Here is the source code, we can see that any other value passed in will finally end with a recursive call with boolean parameter:
setValue: function(v) {
    var me = this,
        active;

    if (Ext.isBoolean(v)) {
        me.callParent(arguments);
    } else {
        active = me.getManager().getWithValue(me.name, v, me.getFormId()).getAt(0);
        if (active) {
            active.setValue(true);
        }
    }
    return me;
}