text:
Q: Replacing specific values with others in a .csv, 'tuple' object has no attribute I can find hwo to debugge my code
    with open("f_in.csv",'rb') as f, open("f_out.csv", "w") as outputfile:
        for line in f:

    replacements = (
        ("(B)", "0"), ("(D)", "2"), ("Entrée air absente", "2"),
        ("+", "0,5"), ("++", "1"), ("+++", "2"),
        ("(S) +", "0,5"), ("(S) expi. ++", "1"), ("(S) +++", "2"),
        ("100", "0"), ("99", "0"), ("98", "0"), ("97", "0"), ("96", "0"),
        ("95", "0"), ("94", "1"),("93", "1"),
        ("92", "1"),("91", "1"),("90", "1"),("89", "1"))

    for i, j in replacements.iteritems():
         line = line.replace(i, j)
         outputfile.write(line)`

    for pair in replacements:
        line = line.replace(*pair)

I want to replace some value by a specific number for each of them on each line of my csv file
So (B) will be 0, (D) will be 2, + will be 0.5 , ++ will be 1, +++ will be 2 and so  one for the other
Sample of the csv file :
1277|2013-12-17 16:00:00|100|+|
1360|2014-01-15 16:00:00|(B)|99|++|E
1402|2014-02-05 20:00:00|(D)|99|++|D
1360|2014-01-29 08:00:00|(D)|99||C
1378|2014-01-21 20:00:00|(B)|100||D

But with my program i get this error :
     for i, j in replacements.iteritems():
     AttributeError: 'tuple' object has no attribute 'iteritems'

A: Usually a dictionary is preferred in replacements or even translations, you can change the replacements into a dictionary by using the function dict(replacements):
replacements = (
        ("(B)", "0"), ("(D)", "2"), ("Entrée air absente", "2"),
        ("+", "0,5"), ("++", "1"), ("+++", "2"),
        ("(S) +", "0,5"), ("(S) expi. ++", "1"), ("(S) +++", "2"),
        ("100", "0"), ("99", "0"), ("98", "0"), ("97", "0"), ("96", "0"),
        ("95", "0"), ("94", "1"),("93", "1"),
        ("92", "1"),("91", "1"),("90", "1"),("89", "1"))

import re

replvalues = dict(replacements)
regex = "|".join(map(re.escape,replvalues.keys()))
repl = lambda x : replvalues.get(x.string[x.start():x.end()])
with open("f_in.csv") as f:
        for i in f:
            line =  re.sub(regex,repl, i)
            print(line)

Now the rest remains the same. ie, you can add the outputfile.write(line) etc


text:
Q: Build and run an executable locally with Conan Say I have a simple hello world project in CMake that creates a binary under bin.
I build it with Conan using the latest CMake module.
In the conanfile.py, is this package method enough to announce the executable?
    def package(self):
        cmake = CMake(self)
        cmake.install()

Then, if I want to build the project and run the executable locally, but in Conan's context, which commands should I type?

A: The package method you've defined will use the installation structure defined by cmake.install() to define the package structure. For example, if your cmake.install() method installs binaries to the bin directory, the bin directory will be present in the package folder in your conan cache, i.e. ~/.conan/data/<package>/<version>/<user>/<channel>/package/<package_id>/bin.
This alone is enough to run the executable locally - you can execute it from the above path, put it onto your PATH - whatever you need. It's not convenient though. To add some convenience, you can use the VirtualRunEnv generator to consume executables. To illustrate with cmake:
$ conan install cmake/3.22.4@ --build=missing -g VirtualRunEnv

This will install cmake 3.22.4 into your local cache, and generate the following files in your cwd:
.
├── conanrunenv-release-x86_64.sh
├── conanrun.sh
├── deactivate_conanrunenv-release-x86_64.sh
└── deactivate_conanrun.sh

You can use this in the same way you would a python virtual environment:
$ source conanrun.sh
$ which cmake
/home/user/.conan/data/cmake/3.22.4/_/_/package/5c09c752508b674ca5cb1f2d327b5a2d582866c8/bin/cmake

And to restore the environment:
$ source deactivate_conanrun.sh
Restoring environment
$ which cmake
/usr/bin/cmake

The second method is to use the deploy generator:
$ conan install cmake/3.22.4@ --build=missing -g deploy

This will grab cmake and all of it's dependencies from the conan cache and dump them to your cwd. After running this command, the directory looks like the following:
.
├── cmake
│   ├── bin
│   │   ├── ccmake
│   │   ├── cmake
│   │   ├── cpack
│   │   └── ctest
│   ├── licenses
│   │   └── Copyright.txt
│   └── share
│       ├── aclocal
│       ├── bash-completion
│       ├── cmake-3.22
│       ├── emacs
│       └── vim
├── deploy_manifest.txt
└── openssl
    ├── bin
    │   ├── c_rehash
    │   └── openssl
    ├── include
    │   └── openssl
    ├── lib
    │   ├── cmake
    │   ├── libcrypto.a
    │   └── libssl.a
    └── licenses
        └── LICENSE

You can then move this wherever you need to and put it on your system PATH if you so desire. The same principle would apply to your package - create the recipe in the local cache, and use generators to consume it.
To illustrate:

*

*Place your package in the conan cache

$ conan create .

*Consume it using VirtualRunEnv
$ conan install mypkg/0.1.0@user/channel --build=missing -g VirtualRunEnv

*Consume it using deploy
$ conan install mypkg/0.1.0@user/channel --build=missing -g deploy

Instead of issuing conan install commands above, you can also list your package as a requirement in a conanfile.txt or conanfile.py for a consumer package, i.e. for a conanfile.py:
def requirements(self):
    self.requires(mypkg/0.1.0)
    self.requires(someotherpkg/1.2.0)

And then you can use the virtual environment generators to collect environment information for all dependencies. In the directory containing the conanfile.py:
$ conan install . -g VirtualRunEnv

Hope this helps.
References:

*

*VirtualRunEnv generator

*deploy generator

*Mastering Conan Virtual Environments

*virtualrunenv generator (deprecated, I believe)

*Conan generators

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does retrying to process a kafka message forever cause a consumer rebalance I have a kafka consumer method annotated @kafkalistener. I have set the retry template on the container and the retry config is such that it would always retry for a couple of exceptions, if occurred while processing the msg. I have set max-poll-records to 1. If this situation occurs in real time and the consumer keeps retrying the msg forever, will the broker think that this consumer is dead and trigger a rebalance? Or, while retrying does the consumer poll for the same msg that was failed to process? If this is true, since poll is happening, there wouldn't be any rebalancing is my assumption. Also I am manually committing offsets, so my enable.auto.commit property is set to false and ack-mode is manual. Can anyone please clarify? Thanks in advance.

A: Yes, when using none-stateful retry (the default) at the listener adapter level, it will cause a rebalance when max.poll.interval.ms is exceeded.
You should use Stateful Retry instead.
In that case, the exception is thrown to the container and a SeekToCurrentErrorHandler re-seeks the unprocessed partitions (including the failed record). You still need to ensure the largest backoff time is less than the poll interval. There is no need to set max.poll.records to 1 because seeks are done on all unprocessed partitions.
Starting with version 2.3, you can eliminate retry at the listener level and just use a SeekToCurrentErrorHandler.


text:
Q: Объявление структуры через typedef #ifndef SOCKETTEST_H
#define SOCKETTEST_H

#include <QObject>
#include <QUdpSocket>
#include <QDebug>

typedef unsigned long int ISZ;
typedef unsigned int DWORD;
typedef unsigned char BYTE;
typedef unsigned short WORD;

#pragma pack(1)

// Заголовок всех сообщений
typedef struct
{
    WORD msg_type;          // Тип сообщения                        1-2
    WORD msg_len;           // Длина сообщения                      3-4
    WORD send_id;           // Отправитель                          5-6
    WORD recv_id;           // Получатель                           7-8
    WORD reserv_1;          // Резерв                               9-10
    WORD reserv_2;          // Резерв                               11-12
    WORD reserv_3;          // Резерв                               13-14
    WORD reserv_4;          // Резерв                               15-16
    DWORD u_id;             // Уникальный индификатор               17-20
} _AAHDR;  //? зачем????

Сам вопрос, в общем, зачем класс обзывать (_AAHDR) в самом конце? Перерыл много книг, но так и не понял, зачем так делать.


text: Q: Calculating time taken for acceleration about tickertape timer,when we measure the time for a particular object's acceleration, we would take 7 ticks multiply 0.020s(for example), instead of taking 8 ticks. Why do we exclude the other tick, is it because it will be more accurate?


text:
Q: Let $p$ be a prime number and let $G$ be a finite $p\text{-group}$. Let $M$ be a maximal subgroup of $G$. QUESTION: Let $p$ be a prime number and let $G$ be a finite $p\text{-group}$. Let $M$ be a maximal subgroup of $G$.   Show that $M$ is a normal subgroup of $G$ and that $| G: M | = p$.
THE HINT GIVEN IS: By strong induction on $n$, where $| G | = p ^{n}$. Let $ y \in Z(G) - \{1 \}$, a convenient $x$ power belonging to $Z(G) - \{1\}$ has order $p$. Consider $G / \langle x \rangle$.
ANSWER GIVEN:
By induction on $n$, where $| G | = p^ n$. According to the tip, consider $x \in Z (G)$ of order $ p $ and let $N = \langle x \rangle$. The group $ G / N $ has order $ p^{n-1} $, so we can apply induction. If $ N $ is a subgroup of $ M $ then $ M / N $ is normal for the $ p $ index in $ G $. Now suppose $ N $ is not a subgroup of $ M $. Being $ M $ maximal we get $ NM = G $. On the other hand being $ | N | = p $ prime we have $ N \cap M = \{1 \} $ logo $ p^{n-1} = | G / N | = | MN / N | = | M / M \cap N | = | M | $ e we deduct $| G: M | = p $. In addition $ M $ is a subgroup of $ N_G (M) $ and $ N $ is a subgroup of $ N_G (M) $ because $ N \leq Z (G) $. It follows that $ G = NM \leq N_G (M) $ so $ M $ is a normal subset of $ G $.
MY QUESTIONS: I didn't understand the following steps showed in this proof.

*

*The induction used in its solution.

*If $N$ is subgroup of $M$
then one is stated that $M/N$ is normal (why?)

*If $N$ is NOT a
subgroup of $M$ then one is stated that $NM=G$ (again, why?)

*Why
$N \cap M=\{1\}?$

*Why $N \leq N_G(M)$ ?

*Why $NM\leq N_G(M)$?

A: *

*The induction is on the exponent of the group. Every $p$ group has order $p^n$ for some $n$, so the induction is assuming that the theorem is true for every $p^m$ for $m<n$.

*$N$ is part of the center so it commutes with everything, which is stronger than being normal.

*If $N$ is not a subgroup of $M$ then some element of $NM$ must not be in $M$, which means $M$ is a subgroup of $NM$. $M$ is maximal, so that means $NM=G$.

*$N$ is prime and cyclic so if any element of $N$ other than the identity is in $M$, then all of $N$ must be in $M$, which would make it a subgroup of $M$, which is assumed not to be true in this case.

*Again, $N$ is part of the center, so it commutes with everything.

*Of course $M$ normalizes itself, and $N$ commutes with everything in $M$ so it normalizes $M$. Therefore the product of these two groups normalizes $M$.


text:
Q: Selecting data of a 'person'' using LIMIT from table I was wondering how to fetch data of a person from a table. I found the query to LIMIT data fetch from table. Here is what I got so far:
$result = mysql_query("SELECT * FROM users WHERE username = '" . $username[$x] . "' LIMIT " . $last_limt . " , " . $nxt_limt . "");

It returns data when LIMIT is available but if the LIMIT exceed the entire data returns null. So how can I know if ROW is available or not in table?

A: use mysql Count
SELECT count(username) FROM users WHERE username ='xyz'

And your $last_limt is not grater than total count-1

A: You have to check number of rows of the result from that query before proceeding
$result = mysql_query("SELECT * FROM users WHERE username = '" . $username[$x] . "' LIMIT " . $last_limt . " , " . $nxt_limt . "");
$rowcount=mysql_num_rows($result);
if($rowcount > 0)
{
    //next operations

}
else
{
    //No more data
}


text:
Q: Where to put controllers in an Express.js project I'm still pretty new to software development and one thing I am having difficulty understanding is the directory architecture of different types of projects. I am about to start building an Express project, and I like to separate out controller classes rather than putting logic inside route callbacks. But I don't really know where I should put my controllers. Here is my project structure right now:
.
├── bin
├── config
├── controllers
├── migrations
├── models
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
├── routes
├── seeders
└── views

This was generated by the Sequelize CLI, but I added controllers to the root directory. Should I put controllers in a src directory? If anyone could help me understand how to set this up in the most efficient way I'd be grateful. There seems to be so many opinions out there and conflicting information. Thanks.

A: The thing with Express projects is that there is no "the one and only" standard for setting up a project structure. You can organize it in any way, as long as it makes sense and is understandable. In your case, it's totally fine to have controllers in the controllers/ directory for a couple of reasons:

*

*It makes sense to separate the logic into separate files

*It's clear what the directory is for just by reading its name

*The files from controllers/ dir can be easily imported into routes/ files

So I would say it's OK, you can go with that. But at the same time, feel free to reorganize that if you'll feel that you are getting lost in your project - you won't break any rules because there aren't any.


text:
Q: How to implement OpenXml GradientFill in vb.net I am not suceeding in translating into vb.net some code which works in c#.
The code is from StackOverflow article:
How to use a gradient fill (GradientFill) with ClosedXML
I can get most of it correctly except this:
 GradientFill gradientFill = new GradientFill() { Degree = 354 };
    gradientFill.Append(new GradientStop() { Position = 0D, Color = new Color() { Rgb = "FF00FF00" } });
    gradientFill.Append(new GradientStop() { Position = 0.49D, Color = new Color() { Rgb = "FF00FF00" } });
    gradientFill.Append(new GradientStop() { Position = 0.51D, Color = new Color() { Rgb = "FFFFFFFF" } });
    gradientFill.Append(new GradientStop() { Position = 1D, Color = new Color() { Rgb = "FFFFFFFF" } });

Any help would be super apreciated!

A: You need a With and a . to do that in VB.NET, e.g.
Dim myGradientFill As New GradientFill() With {.Degree = 354}
myGradientFill.Append(New GradientStop() With {.Position = 0D, .Color = New Color() With {.Rgb = "FF00FF00"}})


text:
Q: Não consigo acessar uma página de formulário Estou fazendo um curso do Alura de Spring framework, porém não consigo acessar uma página de formulário através do link http://localhost:8080/casadocodigo/produtos/form. Dá o seguinte erro:

HTTP Status 404 – Not Found
  Type Status Report
Message /casadocodigo/produtos/WEB-INF/views/produtos/form.jsp
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Apache Tomcat/9.0.5

Creio eu que seja o caminho que está errado. Acho que não deveria ter esse /produtos entre o nome do projeto e /WEB-INF. É esse o problema? Por que ele está adicionando esse /produtos?
Segue o fonte do controller e da classe de configuração abaixo:
Classe ProdutosController:
package br.com.casadocodigo.loja.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import br.com.casadocodigo.loja.daos.ProdutoDAO;
import br.com.casadocodigo.loja.models.Produto;

@Controller
public class ProdutosController {

    @Autowired
    private ProdutoDAO produtoDao;

    @RequestMapping("/produtos")
    public String gravar(Produto produto) {
        System.out.println(produto);
        this.produtoDao.gravar(produto);
        return "produtos/ok";
    }

    @RequestMapping("/produtos/form")
    public String form() {
        System.out.println("Entrando em método FORM");
        return "produtos/form";
    }

}

Classe AppWebConfiguration:
package br.com.casadocodigo.loja.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import br.com.casadocodigo.loja.controllers.HomeController;
import br.com.casadocodigo.loja.daos.ProdutoDAO;

@EnableWebMvc
@ComponentScan(basePackageClasses={HomeController.class, ProdutoDAO.class})
public class AppWebConfiguration {

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

A: O Spring está preparado para lidar com urls com várias "/". Modifique esta linha:
resolver.setPrefix("WEB-INF/views/");
para
resolver.setPrefix("/WEB-INF/views/");


text:
Q: How to sum values in pandas based on bool condition I have the following dataframe:
                   High          Low  ...    Adj Close    bcc
Date                                  ...
2018-01-02  2695.889893  2682.360107  ...  2695.810059  False
2018-01-03  2714.370117  2697.770020  ...  2713.060059  False
2018-01-04  2729.290039  2719.070068  ...  2723.989990  False
2018-01-05  2743.449951  2727.919922  ...  2743.149902  False
2018-01-08  2748.510010  2737.600098  ...  2747.709961   True
                ...          ...  ...          ...    ...
2020-04-09  2818.570068  2762.360107  ...  2789.820068  False
2020-04-13  2782.459961  2721.169922  ...  2761.629883  False
2020-04-14  2851.850098  2805.100098  ...  2846.060059  False
2020-04-15  2801.879883  2761.540039  ...  2783.360107  False
2020-04-16  2806.510010  2764.320068  ...  2778.219971  False

How can i add the next 3 values of column Low whenever bcc column is True and save this data into a different dataframe?

A: I am not sure of the efficiency of this code but you can try this :
match_idx = df.index[df.bcc == True].tolist()

next_three_rows_list = [list(range(idx+1,idx+4)) for idx in match_idx]
sums = []
for i in range(0,len(next_three_rows)):
    sums.append(df.loc[next_three_rows[i]].Low.sum())

new_df = pd.DataFrame(sums,columns=['sum'])


text:
Q: A lot of assertions missing after upgrading to PHPUnit 8 I'm working on upgrading our codebase.
In this process I upgraded PHPUnit from 7 to 9. This decreased our assertions quite drastically.
I downgraded to PHPUnit 8 to see what happened, they were still gone.
Downgrading back to PHPUnit 7 made them 'popup' again.
I've ran the checks with '--debug' and compared the output. This does not show tests being skipped. I also don't see much difference in other metrics... Code coverage is the similar as well.
PHPUnit 7:
Time: 14.08 minutes, Memory: 1.71 GB
OK, but incomplete, skipped, or risky tests!
Tests: 2053, Assertions: 143695, Skipped: 56.

PHPUnit 8:
Time: 16.14 minutes, Memory: 1.31 GB
OK, but incomplete, skipped, or risky tests!
Tests: 2053, Assertions: 22304, Skipped: 56, Risky: 56.

We have some tests which run 'optionally'. So if a setting isn't true, they're skipped. This is marked as 'risky' in PHPUnit 8 and I plan to address that later. However that should not impact the number of assertions as in both cases the tests isn't running.
I've looked at the changelog (https://github.com/sebastianbergmann/phpunit/blob/8.0.0/ChangeLog-8.0.md#800---2019-02-01) but that doesn't really help me.
It would be great if somebody could help me to figure out if this is a problem, or a change in PHPUnit which I could safely ignore.

Update:
I've added a tearDown function which echos '$this->getCount() and $this->getNumAssertions()'. This shows the following numbers. The getNumAssertions is mostly 0, so I guess this is not the right place to call it or the right way to use it.
PHPUnit 7:
ERRORS!
Tests: 2053, Assertions: 142339, Errors: 3, Skipped: 67.
Sum of 'getCount' results: 22341

PHPUnit 8:
ERRORS!
Tests: 2053, Assertions: 22641, Errors: 2, Skipped: 67.
Sum of 'getCount' results: 22342

PS: Numbers are a bit different compared to the first results, but I've worked on some tests in the meanwhile.
Interesting thing here is that the getCount results for PHPUnit7, PHPUnit8 and the total for PHPUnit 8 are comparable. Still no explanation for the missing assertions though.


text:
Q: How to extend 'text' field in Graph.ExtendData with Plotly-Dash? I have an animated graph that I update in a clientside callback. However, I want to update the text as well as the x and y values of the traces in Graph.extendData(), but it seems that that doesn't work. Is there something I'm missing? Alternatively, is there a different method I should be using instead?
Adopting the code from this post (Plotly/Dash display real time data in smooth animation), I'd like something like this, but where updating the text with extendData actually worked:
import dash
import dash_html_components as html
import dash_core_components as dcc
import numpy as np

from dash.dependencies import Input, Output, State

# Example data (a circle).
resolution = 1000
t = np.linspace(0, np.pi * 2, resolution)
x, y = np.cos(t), np.sin(t)
text = str(t)

# Example app.
figure = dict(data=[{'x': [], 'y': []}], text = [], layout=dict(xaxis=dict(range=[-1, 1]), yaxis=dict(range=[-1, 1])))
app = dash.Dash(__name__, update_title=None)  # remove "Updating..." from title
app.layout = html.Div([
    dcc.Graph(id='graph', figure=dict(figure)), dcc.Interval(id="interval", interval=25),
    dcc.Store(id='offset', data=0), dcc.Store(id='store', data=dict(x=x, y=y, text=text, resolution=resolution)),
])

# This makes the graph fail to draw instead of just extending the text as wel!
app.clientside_callback(
    """
    function (n_intervals, data, offset) {
        offset = offset % data.x.length;
        const end = Math.min((offset + 10), data.x.length);
        return [[{x: [data.x.slice(offset, end)], y: [data.y.slice(offset, end)], text: [data.text.slice(offset, end)]}, [0], 500], end]
    }
    """,
    [Output('graph', 'extendData'), Output('offset', 'data')],
    [Input('interval', 'n_intervals')], [State('store', 'data'), State('offset', 'data')]
)

if __name__ == '__main__':
    app.run_server()

Alternatively, is there a different method I should be using instead?


text:
Q: Facebook API feed dialog - prevent unnecessary click hi,
Using Facebook's API it's possible to prompt a user to post to his/her wall using the feed dialog. However, using the javascript SDK, this requires two clicks: one on the button which brings up the dialog, the other on the "Share" button within the dialog.
Is it possible to get rid of one of these clicks? I thought of two approaches:

*

* Embedding the dialog within an iframe, as Facebook provides a URL for a full page dialog. That will require the user to click only on the "Share" button. Apparently Facebook blocks that option.

*Using an access token and display=iframe, but I want to avoid the user having to authorize my application.

Any ideas?

A: i would suggest you to use fb.api instead.
function PostToMyWall(){

        FB.login(function(response)
        {
            if (response.authResponse)
            {

                  //Post to my wall
                  FB.api('/me/feed', 'post', {
                  message: lnk,link: lnk

                  },
                  function(response) {
                    if (!response || response.error) {
                     // //alert('Error occured');

                   } else {
                     // //alert("Successfully Posted to My Wall!");

                    }
                  });}else
            {
                alert('Not logged in');
            }}, { scope : 'publish_stream' });
         }

My application got a similar function, check it out at www.wootube.woolei.com - "Post to WooTube Page and Group"
or popup when the page using jquery
$(document).ready(function() {   FB.ui({method: 'feed',
            name: mdtxt,
            link: lnk,
            picture: hackImageUrl(img,fld),
            caption: '<?php echo $clickme; ?>',
            description: '<?php echo $app_desc; ?>'
        },
         function(response) {
           if (!response || response.error) {
             alert('Error occured');

          } else {
             alert("Successfully Posted to Group");

           }
         });});


text:
Q: XML to CSV with XSLT multiple node I am trying to convert xml file to CSV format using XSLT.
My XML file has multiple root (Account) with attributes and also with children of differend types.
Here is my XML:
<SiebelMessage>
<ListOfSwiOrganizationIO>
    <Account>
        <Email>jozk8o@sk.ibm.com</Email>
        <Name>ESET</Name>
        <Address>
            <StreetAddress>Vodna 9</StreetAddress>
            <City>Nitra</City>
        </Address>
        <Contact>
            <LastName>Jozo</LastName>
            <FirstName>Sekera</FirstName>
        </Contact>
        <AccountCategory>
            <CategoryValue>90</CategoryValue>
        </AccountCategory>
        <AccountCategory>
            <CategoryValue>91</CategoryValue>
        </AccountCategory>
        <IntegrityCode>
            <IntegrityType>AllowSms</IntegrityType>
            <ConsentCode>YES</ConsentCode>
        </IntegrityCode>
        <IntegrityCode>
            <IntegrityType>AllowEmail</IntegrityType>
            <ConsentCode>YES</ConsentCode>
        </IntegrityCode>
    </Account>
    <Account>
        <Email>ferk8o@sk.ibm.com</Email>
        <Name>IBM</Name>
        <Address>
            <StreetAddress>Dlha 1</StreetAddress>
            <City>Bratislava</City>
        </Address>
        <Contact>
            <LastName>Fero</LastName>
            <FirstName>Kopacka</FirstName>
        </Contact>
        <AccountCategory>
            <CategoryValue>90</CategoryValue>
        </AccountCategory>
        <AccountCategory>
            <CategoryValue>91</CategoryValue>
        </AccountCategory>
        <IntegrityCode>
            <IntegrityType>AllowSms</IntegrityType>
            <ConsentCode>YES</ConsentCode>
        </IntegrityCode>
        <IntegrityCode>
            <IntegrityType>AllowEmail</IntegrityType>
            <ConsentCode>YES</ConsentCode>
        </IntegrityCode>
    </Account>
</ListOfSwiOrganizationIO>

I was able to create XSLT based on some articles here but only displaying the root attributes without children.
Required output is:
Email;Name;StreetAddress;City;LastName;FirstName;CategoryValue;AllowSms;AllowEmail
jozk8o@sk.ibm.com;ESET;Vodna 9;Nitra;Jozo;Sekera;90,91;YES;NOTSET
ferk8o@sk.ibm.com;IBM;Dlha 1;Bratislava;Fero;Kopacka;90,91;YES;NO

Here is my current XSLT:
<xsl:output method="text" encoding="utf-8"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="delimiter" select="';'"/>
<xsl:template match="/">
<!-- Output the CSV header -->
<xsl:text>Email;Name;StreetAddress;City;LastName;FirstName;CategoryValue;AllowSms;AllowEmail
</xsl:text>
<!-- Output the values -->
<xsl:for-each select="SiebelMessage/ListOfSwiOrganizationIO/Account">
    <!-- begin values -->
    <xsl:value-of select="concat(Email, $delimiter, Name, $delimiter, ListOfAddress/Address/StreetAddress, $delimiter, ListOfAddress/Address/City, $delimiter, Contact/LastName, $delimiter, Contact/FirstName, $delimiter)"/>
    <!-- Category Values -->
    <xsl:for-each select="AccountCategory">
        <xsl:value-of select="CategoryValue"/>
        <xsl:if test="position()!=last()">
            <xsl:text>,</xsl:text>
        </xsl:if>
    </xsl:for-each>
    <xsl:value-of select="$delimiter"/>
    <!-- Integrity Codes -->
    <xsl:value-of select="concat(IntegrityCode[IntegrityType='AllowSms']/ConsentCode, $delimiter, IntegrityCode[IntegrityType='AllowEmail']/ConsentCode)"/>
    <xsl:choose>
          <xsl:when test="ConsentCode=YES">
             (1)
          </xsl:when>
       </xsl:choose>
    <!-- end values -->
    <xsl:if test="position()!=last()">
        <xsl:text>
</xsl:text>
    </xsl:if>
</xsl:for-each>

Could you please advice how to implement also children?
My current output is only:
EMAIL;NAME
jozk8o@sk.ibm.com;ESET;
ferk8o@sk.ibm.com;IBM;

Thank you very much

A: If the structure is constant and known beforehand, I'd suggest you construct your output by naming the input elements explicitly:
XSLT 1.0
(edited to match the updated question)
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:variable name="delimiter" select="';'"/>

<xsl:template match="/">
    <!-- Output the CSV header -->
    <xsl:text>Email;Name;StreetAddress;City;LastName;FirstName;CategoryValue;AllowSms;AllowEmail
</xsl:text>
    <!-- Output the values -->
    <xsl:for-each select="SiebelMessage/ListOfSwiOrganizationIO/Account">
        <!-- begin values -->
        <xsl:value-of select="concat(Email, $delimiter, Name, $delimiter, Address/StreetAddress, $delimiter, Address/City, $delimiter, Contact/LastName, $delimiter, Contact/FirstName, $delimiter)"/>
        <!-- Category Values -->
        <xsl:for-each select="AccountCategory">
            <xsl:value-of select="CategoryValue"/>
            <xsl:if test="position()!=last()">
                <xsl:text>,</xsl:text>
            </xsl:if>
        </xsl:for-each>
        <xsl:value-of select="$delimiter"/>
        <!-- Integrity Codes -->
        <xsl:value-of select="concat(IntegrityCode[IntegrityType='AllowSms']/ConsentCode, $delimiter, IntegrityCode[IntegrityType='AllowEmail']/ConsentCode)"/>
        <!-- end values -->
        <xsl:if test="position()!=last()">
            <xsl:text>
</xsl:text>
        </xsl:if>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

This has the advantage of both speed and no unnecessary "moving parts".


text:
Q: d3-force - Nodes are dragged away from links, ticks not run I need to make a "sticky force layout" with drag-able features, and tried to replicate the example of Mike Bostock at this link. Because the author wrote that program in D3 v3, I must "upgrade" his code to D3 v4. This means both d3-force and d3-drag statement must be changed accordingly. Though the logic flow in original example is quite easy to understand, I still cannot manage to make my own version (see the code below). Issue: After a certain amount of time (2 - 3 seconds), the nodes are dragged away but the links are not updated.
My initial thoughts were focused on drag-function (.call(drag)), but later I found that the "tick" function does not run anymore after the the amount of time mentioned above (I got it via putting a count variable inside tick function, then console.log it). Up to this point, my mind is empty, cannot explore further.

Where is the problem?
var width = 960,
    height = 500;

var simulation = d3.forceSimulation()
    .force("charge", d3.forceManyBody().strength(-100))

d3.forceX(width)
d3.forceY(height)

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var drag = d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended);
var link = svg.selectAll(".link")
var node = svg.selectAll(".node")

d3.json("graph.json", function (error, graph) {
    if (error) throw error;

    simulation.nodes(graph.nodes)
            .force("link", d3.forceLink(graph.links))
            .on("tick", tick);

    link = link.data(graph.links)
        .enter().append("line")
        .attr("class", "link");

    node = node.data(graph.nodes)
        .enter().append("circle")
        .attr("class", "node")
        .attr("r", 12)
        .on("dblclick", dblclick)
        .call(drag)

});

var count = 0;

function tick() {
    count++;
    console.log(count);
    link.attr("x1", function (d) { return d.source.x; })
        .attr("y1", function (d) { return d.source.y; })
        .attr("x2", function (d) { return d.target.x; })
        .attr("y2", function (d) { return d.target.y; });

    node.attr("cx", function (d) { return d.x; })
        .attr("cy", function (d) { return d.y; })
}

function dblclick(d) {
    d3.select(this).classed("fixed", d.fixed = false);
    // console.log("Is clicking");
}

function dragstarted(d) {
    d3.select(this).classed("fixed", d.fixed = true);
    console.log("Is dragging");
}

function dragged(d) {
    d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}

function dragended(d) {
    d3.select(this).classed("active", false);
}

A: There are two things that are causing problems in this force directed graph:

*

*d3v4 does not use d.fixed to fix nodes

*d3v4 doesn't have the same default alpha decay as d3v3

1: fixing nodes
While you don't expressly note this, in the 2-3 seconds the graph updates link data, the nodes still move after dragging.
This is because, as opposed to d3v3, you need to fix both the x and y values of a coordinate manually using d.fx and d.fy; d.fixed no longer fixes your nodes. For your code this would look something like:
function dragended(d) {
  d.fx = d3.event.x;
  d.fy = d3.event.y;
}

and
function dblclick(d) {
      d.fx = null;
      d.fy = null;
}

2: setting alpha decay
This is causing your graph to freeze up. After the graph has stabilized due to alpha decay, the tick function is no longer called. At this point, your drags happen without any update to the links, resulting in severed connections between node and link.
In d3v3 alpha decay is undefined by default, and d3 likely falls back on a either not computing alpha decay or using zero as the alpha decay factor (either results in the same outcome). In d3v4, alpha decay is set at a non-zero value:

If decay is specified, sets the alpha decay rate to the specified
  number in the range [0,1] and returns this simulation. If decay is not
  specified, returns the current alpha decay rate, which defaults to
  0.0228… = 1 - pow(0.001, 1 / 300) where 0.001 is the default minimum alpha.
The alpha decay rate determines how quickly the current alpha
  interpolates towards the desired target alpha; since the default
  target alpha is zero, by default this controls how quickly the
  simulation cools. Higher decay rates cause the simulation to stabilize
  more quickly, but risk getting stuck in a local minimum; lower values
  cause the simulation to take longer to run, but typically converge on
  a better layout. To have the simulation run forever at the current
  alpha, set the decay rate to zero; alternatively, set a target alpha
  greater than the minimum alpha.

So, you could just use:
var simulation = d3.forceSimulation()
    .force("charge", d3.forceManyBody().strength(-100))
    .alphaDecay(0);

(or alternatively, set the alphaTarget to an appropriate value as noted in the documentation quote above).
Altogether, this looks like this.


text:
Q: AWS load balancer security group not allowing traffic even when all allowed
The security group assigned to it has both Inbound and Outbound rule as ALL traffic and ALL port range, so why does it say it's not allowing traffic on that listener port?

A: If the LoadBalancer was created by ElasticBeanstalk environment, you would have to add the listener in the ElasticBeanstalk configurations


text:
Q: Skype 4.2 crashes when connecting to one specific person ok i have Skype 4.2 on Windows Vista 32 bit.  Skype was working fine with no problems at all but a situation came up and i had to reformat my laptop.
Since the reformat Skype doesn't connect to just one person on my contacts list.  Ive uninstalled reinstalled multiple times, even removed him from my contacts and re-added but to no avail.  He is on Skype mobile with his phone not sure if this is a prob as it wasn't before.

A: Advice: Contact Skype support. That's the only way I guess to work this around. (After you filled out the form and you wait, you can give a try to Skype portable.)


text:
Q: paypal ipn listener errors I'm implementing an IPN listener for Paypal Adaptive Payments, I downloaded the sample code from here:
https://cms.paypal.com/cms_content/IT/it_IT/files/developer/IPN_PHP_41.txt
Then I made a transaction (with sandbox) but I think the sample is wrong because the code returns some errors in my error_log file:
[16-Jun-2013 16:11:34 UTC] PHP Warning:  stripslashes() expects parameter 1 to be string, array given in /var/www/actions/IPNListener.php on line 7
[16-Jun-2013 16:11:34 UTC] PHP Notice:  Undefined variable: header in /var/www/actions/IPNListener.php on line 12
[16-Jun-2013 16:11:34 UTC] PHP Notice:  Undefined index: item_name in /var/www/actions/IPNListener.php on line 18

The Undefined index is not only "item_name" but ALL INDEXES!!!!!
The transaction works correctly and the IPN is called by paypal automatically after the transaction...but the paypal sample code does not work at all! Do you know how to fix it?

A: Try this one
<?php
//Build the data to post back to Paypal
$postback = 'cmd=_notify-validate';

// go through each of the posted vars and add them to the postback variable
foreach ($_POST as $key => $value) {
   $value = urlencode(stripslashes($value));
   $postback .= "&$key=$value";
}

// build the header string to post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($postback) . "\r\n\r\n";

// Send to paypal or the sandbox depending on whether you're live or developing
// comment out one of the following lines
//$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);//open the connection
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
// or use port 443 for an SSL connection
//$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

    if (!$fp)
    {
        // HTTP ERROR Failed to connect
        //error handling
    }
    else // if we've connected OK
    {
        fputs ($fp, $header . $postback);//post the data back
        while (!feof($fp))
        {
            $response = fgets ($fp, 1024);

            if (strcmp ($response, "VERIFIED") == 0) //It's verified
            {
                //do something
            }
            else if (strcmp ($response, "INVALID") == 0)
            {
                //the Paypal response is INVALID, not VERIFIED
                // This implies something is wrong
            }
        } //end of while
        fclose ($fp);
    }
?>


text:
Q: fast way to create a big bitmap from an array of bitmap? I have this code,
copy/paste in a new winform app and this will write a file on your desktop if you run it: test123abcd.png
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim SquareSize = 5
    Dim GridX = 2500
    Dim GridY = 2500
    Dim SquareCount = GridX * GridY - 1
    Dim sw As New Stopwatch

    Dim Rect(4) As Rectangle
    Rect(0) = New Rectangle(0, 3, 3, 1)
    Rect(1) = New Rectangle(3, 0, 1, 3)
    Rect(2) = New Rectangle(3, 3, 3, 1)
    Rect(3) = New Rectangle(0, 0, 1, 3)

    Dim fullsw = Stopwatch.StartNew
    Using board = New Bitmap(SquareSize * (GridX + 1), SquareSize * (GridY + 1), Imaging.PixelFormat.Format32bppPArgb)
        Using graph = Graphics.FromImage(board)
            Using _board = New Bitmap(SquareSize, SquareSize, Imaging.PixelFormat.Format32bppPArgb)
                Using g As Graphics = Graphics.FromImage(_board)
                    For i = 0 To SquareCount
                        g.Clear(If((i And 1) = 1, Color.Red, Color.Blue))
                        g.FillRectangles(Brushes.White, Rect)
                        sw.Start()
                        graph.DrawImageUnscaled(_board, ((i Mod GridX) * SquareSize), ((i \ GridY) * SquareSize))
                        sw.Stop()
                    Next
                End Using
            End Using
        End Using
        fullsw.Stop()
        board.Save(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) & "\test123abcd.png", Imaging.ImageFormat.Png)
    End Using

    MessageBox.Show("Full SW: " & fullsw.ElapsedMilliseconds & Environment.NewLine &
                    "DrawImageUnscaled SW: " & sw.ElapsedMilliseconds)
End Sub

about 40% to 45% of the time spent is on DrawImageUnscaled, about 23 seconds on my current computer while the whole thing take about 50 seconds
is there a way to speed up DrawImageUnscaled? (and maybe the whole thing?)
EDIT - question in vb.net, answer in c#

A: By assuming that the generation part (g.FillRectangles(Brushes.White, Rect), pretty time-consuming too) cannot be avoided, the best thing you can do is avoiding a second graph-generation process (also for board) and just copying the information from _board. Copying is much quicker than a new generation (as shown below), but you have the problem that the source information (_board) do not match the destination format (board by relying on .SetPixel) and thus you will have to create a function determining the current pixel (X/Y point) from the provided information (current rectangle).
Below you can see a simple code showing the time requirement differences between both approaches:
Dim SquareSize As Integer = 5
Dim _board As Bitmap = Bitmap.FromFile("in.png")
Dim board As Bitmap = New Bitmap(_board.Width * SquareSize, _board.Height * SquareSize)

For x As Integer = 0 To _board.Width - 1
    For y As Integer = 0 To _board.Height - 1
        board.SetPixel(x * SquareSize, y * SquareSize, _board.GetPixel(x, y))
    Next
Next

board.Save("out1.png", Imaging.ImageFormat.Png)

board = New Bitmap(_board.Width, _board.Height)

Using board
    Using graph = Graphics.FromImage(board)
        Using _board
            Using g As Graphics = Graphics.FromImage(_board)
                For x As Integer = 0 To _board.Width - 1
                    For y As Integer = 0 To _board.Height - 1
                        graph.DrawImageUnscaled(_board, x, y)
                    Next
                Next
            End Using
        End Using
    End Using
    board.Save("out2.png", Imaging.ImageFormat.Png)
End Using

Bear in mind that it is not a "properly-working code". Its whole point is showing how to copy pixels between bitmaps (by multiplying by a factor, just to get different outputs than inputs); and putting the DrawImageUnscaled method under equivalent conditions (although the output picture is, logically, different) to get a good feeling of the differences in time requirements between both methodologies.
As said via comment, this is all what I can do under the current conditions. I hope that will be enough to help you find the best solution.

A: wow I like unsafe code when it is worthed, solved my problem with c# in the end
here is the code, which is about 70x faster to the code in my question
using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace BmpFile
{
    public class BmpTest
    {
        private const int PixelSize = 4;

        public static long Test(int GridX, int GridY, int SquareSize, Rectangle[][] Rect)
        {
            Bitmap bmp = new Bitmap(GridX * SquareSize, GridY * SquareSize, PixelFormat.Format32bppArgb);
            BitmapData bmd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
                                          System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                          bmp.PixelFormat);

            int Stride = bmd.Stride;
            int Height = bmd.Height;
            int Width = bmd.Width;

            int RectFirst = Rect.GetUpperBound(0);
            int RectSecond;
            int Offset1, Offset2, Offset3;
            int i, j, k, l, w, h;
            int FullRow = SquareSize * Stride;
            int FullSquare = SquareSize * PixelSize;

            var sw = System.Diagnostics.Stopwatch.StartNew();
            unsafe
            {
                byte* row = (byte*)bmd.Scan0;

                //draw all rectangles
                for (i = 0; i <= RectFirst; ++i)
                {

                    Offset1 = ((i / GridX) * FullRow) + ((i % GridX) * FullSquare) + 3;
                    RectSecond = Rect[i].GetUpperBound(0);

                    for (j = 0; j <= RectSecond; ++j)
                    {
                        Offset2 = Rect[i][j].X * PixelSize + Rect[i][j].Y * Stride;
                        w=Rect[i][j].Width;
                        h=Rect[i][j].Height;
                        for (k = 0; k <= w; ++k)
                        {
                            Offset3 = k * PixelSize;
                            for (l = 0; l <= h; ++l)
                            {
                                row[Offset1 + Offset2 + Offset3 + (l * Stride)] = 255;
                            }
                        }
                    }
                }

                //invert color
                for (int y = 0; y < Height; y++)
                {
                    Offset1 = (y * Stride) + 3;

                    for (int x = 0; x < Width; x++)
                    {
                        if (row[Offset1 + x * PixelSize] == 255)
                        {
                            row[Offset1 + x * PixelSize] = 0;
                        }
                        else
                        {
                            row[Offset1 + x * PixelSize] = 255;
                        }
                    }
                }
            }
            sw.Stop();

            bmp.UnlockBits(bmd);

            bmp.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\test.png", ImageFormat.Png);
            bmp.Dispose();

            return sw.ElapsedMilliseconds;
        }
    }
}


text:
Q: How to filter a Dashboard using a formula field? I have a dashboard that I wish to display on clicking a link. This link has to be prepared in a way the dashboard filters and displays the components only for the products that are associated with the record but it is displaying for all the products. Attaching screenshots related to it.
Field Formula with the link

The Dashboard screenshot :

You can see there are multiple products but I'm trying to filter out with this 1 Product.
After editing and adding the filters

Edit 2 :
I changed the formula to the below

And I changed the filter in the dashboard also equally the Product Code in my Cart

So Now when I add the Item and I click on the Item it is opening correctly only for the item with that Product Code but I want it to open correctly for any code. I also want to bring another Customer filter. How can I make the filter work.

A: The issue is that the filter value you are passing HAS to be a pre-defined selectable value in the dashboard filter(s).
You can not pass in anything you please.
I have created a reasonable solution (there are scaling limits) to this issue if you want to check it out on my blog here https://salesforceconfig.com/show-any-accounts-data-on-a-universal-dashboard/


text:
Q: Categorize git repositories I would like to organize my git repositories into categories. My main reason to do this is to get a better overview of my code repositories in the web interface I use (GitList - http://www.gitlist.org).
Now I get a long list of all the repositories, it would be nice to see only a few categories (as "repositories" or something else with description). And when you select one category you see all the repositories within that category.
I have my own git server with Gitolite (https://github.com/sitaramc/gitolite/) and Gitolite has some settings to categorize repositories for GitWeb, but I can't see that information in either GitWeb nor GitList, the later is not that surprising, when the setting is for GitWeb.
It would be really great to be able to categorize the repositories from Gitolite and that it showed up in GitList. But since this may not be possible (I can't see that it even works for GitWeb, where it is supposed to work) is there an other way I can manage this?
I have read some about nested git repositories, but that is not really what I am after, it does not have to affect the repositories at all, just the way that they are presented in the web interface.
Someone with helpful tips on the subject?

A: GitWeb will categorize the repositories it lists, if—and only if—you enable the categorized output in the configuration section. You will need to change the value of $projects_list_group_categories to make this happen:
our $projects_list_group_categories = 1;

Afterwards, GitWeb will pick up the category from the gitweb.category configuration in each repository. You can set this in Gitolite by setting the category for a repo to some value.
repo something
    RW+ = @members
    category = My category name


text:
Q: Rendering multiple pandas html tables side-by-side I have produced individual html tables showing work orders from multiple departments , and a running count rendered in the header of how many are orders are 'Completed' out of the 'Total' number of orders in that department. This all works fine, but I cannot find a way, clever or otherwise, to render these tables side by side on an html page. I can't have the tables on top of one another because the page will be appear static on a large monitor through a raspberry pi, so scrolling isn't an option.
pd.set_option('colheader_justify', 'center')   # FOR TABLE

table1 = CNC.to_html(classes='mystyle', na_rep='', index = False)
status1 = f"{C10} of {Total10} Completed"

html_string = f'''

  <title>HTML Pandas Dataframe with CSS</title>
  <link rel="stylesheet" type="text/css" href="df_style.css"/>

 C N C

 {status1}

    {table1}

.
'''

with open("CNC.html", mode = 'w') as f:
     f.write(html_string.format(table=CNC.to_html(classes='mystyle', na_rep='', index = False)))

CSS
.mystyle {
    font-size: 15pt;
    font-family: Arial;
    border-collapse: collapse;
    border: 1px solid silver;
}

.mystyle td, th {
    padding: 10px;
}

.mystyle tr:nth-child(even) {
    background: #E0E0E0;
}

.mystyle tr:hover {
    background: silver;
    cursor: pointer;
}

.mystyle {
    margin: auto;
    padding: 0;
}

.mystyle {
    text-align: center;
    width: 100%;
}

Rendered CNC html table
This obviously creates and renders only a single table on an html page
It would be great if there was some CSS magic I could use so that I could just apply that stylesheet to each department's html.


text:
Q: Simple positioning problem for child element Let's say I have this for loop to create HTML.

let content;
for (let i = 0; i < 4; i++) {
  if (i % 2 == 0) {
    content = "Stack Overflow is a question and answer website for professional and enthusiast programmers. It is the flagship site of the Stack Exchange Network,[4][5][6] created in 2008 by Jeff Atwood and Joel Spolsky.[7][8]"
  } else {
    content = "Stack Overflow is a question and answer website for professional and enthusiast programmers."
  }
  document.body.innerHTML += `

${content}

<button class='buttons'>Click</button>
<button class='buttons'>ADD</button>

`
}
body {
  display: grid;
  grid-column-gap: 50px;
  grid-row-gap: 50px;
  grid-template-columns: repeat(2, auto);
}
.whole {
  width: 200px;
}
.buttons {
  position: relative;
  top: 10px;
  left: 200px
}

This all works fine, but I want to let the button position always keep the same position (vertcially) with the other buttons.
Now in my code, the button's height will be affected by the length and other child elements (p). I try use position:absolute or position:sticky, but both of them doesn't solve my problem.
Is there a way to make the position of child element to be absolute to only child element?
The effect I want to achieve are all the buttons could always have same vertically position with others.

A: If what you want to achieve is the buttons to be vertically aligned on the same line, you can simply use CSS flexbox in .whole. By forcing the flex direction to column and then forcing spaces to be inserted between its children via justify-content: space-between, you can pretty much achieve what you want:

let content;
for (let i = 0; i < 4; i++) {
  if (i % 2 == 0) {
    content = "Stack Overflow is a question and answer website for professional and enthusiast programmers. It is the flagship site of the Stack Exchange Network,[4][5][6] created in 2008 by Jeff Atwood and Joel Spolsky.[7][8]"
  } else {
    content = "Stack Overflow is a question and answer website for professional and enthusiast programmers."
  }
  document.body.innerHTML += `

${content}

<button class='buttons'>Click</button>

`
}
body {
  display: grid;
  grid-column-gap: 50px;
  grid-row-gap: 50px;
  grid-template-columns: repeat(2, auto);
}

.whole {
  width: 200px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.buttons {
  position: relative;
  width: min-content;
  left: 100%;
}

A: This is a solution using a grid. Make whole a grid item and then use place-self and grid-row-start to place the buttons at the end; You can learn the complete working of grid here at CSS tricks.

let content;
for (let i = 0; i < 4; i++) {
  if (i % 2 == 0) {
    content = "Stack Overflow is a question and answer website for professional and enthusiast programmers. It is the flagship site of the Stack Exchange Network,[4][5][6] created in 2008 by Jeff Atwood and Joel Spolsky.[7][8] Stack Overflow is a question and answer website for professional and enthusiast programmers."
  } else {
    content = "Stack Overflow is a question and answer website for professional and enthusiast programmers."
  }
  document.body.innerHTML += `

${content}

<button class='buttons'>Click</button>
<button class='buttons'>ADD</button>

`
}
body {
  display: grid;
  grid-column-gap: 50px;
  grid-row-gap: 50px;
  grid-template-columns: repeat(2, auto);
}
.whole {
  display: grid;
  width: 200px;
  column-gap: 5px;
}
.buttons {
  position: relative;
  grid-row-start: 2;
  height: 20px;
  place-self: end;
}


text:
Q: Try & Catch in double Array not working as I expected I'm trying to perform a try catch on a user input and place the user input into an array if it passes the check but if I enter an invalid input, it would replace that index with 0 and move onto the next index. I'm trying to figure out how to get a reprompt to work inside the for loop so that the invalid value in that particular index gets replaced with a valid user input. The order of the values in the array doesn't matter. I'm trying to do this without importing other Java libraries!
I would very much appreciate any help ! I'm new to programming and Java. Thank you for your time !
public static double[] getAmount()
   {
      int MAX_NUM = 10;
      double[] numArray = new double[MAX_NUM];
      for (int i = 0; i < numArray.length;i++)
      {
         double numInput;
         do
         {
            try
            {
               numInput = Double.parseDouble(JOptionPane.showInputDialog("Enter amounts in $: "));
            }
            catch (NumberFormatException e)
            {
               numInput = MAX_NUM - 11;
            }
            if (numInput < 0 || numInput > 999999)
            {
               JOptionPane.showMessageDialog(null, "Error. Please enter valid amount in dollars");
               numInput = Double.parseDouble(JOptionPane.showInputDialog("Enter amount in $: "));
            }
            else
            {
               numArray[i] = numInput;
            }
          }
          while (numInput < 0 && numInput > 999999);
       }
       return numArray;
    }

A: public static double[] getAmount()
{
  int MAX_NUM = 10;
  double[] numArray = new double[MAX_NUM];
  int i = 0;
  while (i < numArray.length)
  {
     double numInput;

        try
        {
           numInput = Double.parseDouble(JOptionPane.showInputDialog("Enter amounts in $: "));
        }
        catch (NumberFormatException e)
        {
           numInput = MAX_NUM - 11;
        }
        if (numInput < 0 || numInput > 999999)
        {
           JOptionPane.showMessageDialog(null, "Error. Please enter valid amount in dollars");
           numInput = Double.parseDouble(JOptionPane.showInputDialog("Enter amount in $: "));
        }
        else
        {
           numArray[i] = numInput;
           i++;
        }
   }

   return numArray;
}

A: This should work:

public static double[] getAmount()
   {
      int MAX_NUM = 10;
      double[] numArray = new double[MAX_NUM];
      for (int i = 0; i < numArray.length;i++)
      {
         double numInput;
         do
         {
            try
            {
               numInput = Double.parseDouble(JOptionPane.showInputDialog("Enter amounts in $: "));
            }
            catch (NumberFormatException e)
            {
               numInput = MAX_NUM - 11;
            }
            if (numInput < 0 || numInput > 999999)
            {

               JOptionPane.showMessageDialog(null, "Error. Please enter valid amount in dollars");
            }
          }
          while (numInput < 0 || numInput > 999999);
          numArray[i] = numInput;
       }
       return numArray;
    }


text:
Q: Accuracy falling down tensorflow v1.5 I'm using tensorflow 1.5 and keras 2.1.6. The code is taken from this tutorial and reworked to work on version 1.5. There is it:
import tensorflow as tf
import keras

import numpy as np
import matplotlib.pyplot as plt

fashion_mnist = keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

train_images = train_images / 255.0
test_images = test_images / 255.0

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10)
])

model.compile(optimizer='adam',
              loss="sparse_categorical_crossentropy",
              metrics=['accuracy']);

model.fit(train_images, train_labels, epochs=10);

But accuracy drops with every epoch and does not rise above 0.3. What i'm doing wrong?

A: As you classifying images from the Fashion MNIST dataset, we need to set the activation function of the last Dense layer to softmax. The softmax function outputs probabilities for each of the 10 classes. Learn more about the softmax function here.
Replace,
tf.keras.layers.Dense(10)

With,
tf.keras.layers.Dense(10 , activation='softmax' )


text:
Q: How do I get all the mail accounts set up in Mail.app programmatically? My app need to know all the accounts set up in Mail.app, then ask the user to select one for a specific use.
How can I achieve this?

A: AppleScript is probably the way to go (check NSAppleScript):
http://www.mactech.com/articles/mactech/Vol.21/21.09/ScriptingMail/index.html
Sample:
NSAppleScript* script= [[NSAppleScript alloc] initWithSource:@"tell application \"Mail\" \nname of every account \nend tell"];
NSDictionary* scriptError = nil;
NSAppleEventDescriptor* descriptor=[script executeAndReturnError:&scriptError];
if(scriptError)
{
    NSLog(@"Error: %@",scriptError);
    return;
}
NSLog(@"Result: %@",descriptor);


text:
Q: How can I access the same phpMyAdmin account from different computers? (not on same network) Members of the team have to use the same database for working on a project. Uptill now, only one person was working on backend, using localhost for running MySQL along with node.js. But now different members have to upload data on the same database from different computers.
There is information on using same phpMyAdmin account from different computers on the same network (LAN). However, our computers are not on the same network. ( This is the video link: https://www.youtube.com/watch?v=vf_BBBTfxm0 )
So how can we use the same database?


text:
Q: CNAME not resolving I've got a domain (example.com) registered with godaddy and pointed to nameservers hosted by linode. I've got a multisite WordPress install on linode (blogs.com) and I want to point the domain to a subdomain of the wordpress install (example.com -> example.blogs.com).
The subdomain of the wordpress install works fine - DNS can find it and I can browse to it.  in the linode's DNS manager I've set up a CNAME to make the pointer I referenced above.
Whois shows that the linode nameservers are set for the domain, but DNS can't find any nameserver for example.com.
Am I missing a step, or do I have something misconfigured?
EDIT 1
The answer section of the dig request using one of linode's nameservers is
;; ->>HEADER<<- opcode: QUERY, status: REFUSED, id: 44359
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

The answer section from the dig using my host's nameserver is
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 16379
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

Same response in the status field if I specify CNAME or just accept the standard A query.
I do not have an A record for that example.com on the linode nameservers; do I need to set that up?
This is a fairly recent change - a few hours ago, so maybe I'm just being impatient? The nameserver changes made at the same time came through pretty quickly. I figured that the CNAME entry would be simultaneous with that; am I wrong in that expectation?

A: Technically what you're asking for is invalid.  CNAME conflicts with all other records (with a special exception for DNSSEC records), thus having CNAME xxxxx conflicts with the SOA, MX, NS etc records for the domain.  My guess is that the reason the domain resolves when you use an A there and fails when you use CNAME is because the DNS server enforces those restrictions and is unable to process your zone file.
Furthermore, based on your response to @xwincftwx's question, it's not clear that getting CNAME to work would do what you want in the first place.  A CNAME pointing to an A record is exactly the same as an A record in the first place.  The CNAME is handled entirely internally by the DNS system and the web browser only sees the IP address.  In your test with an A record (let's say 1.2.3.4), the browser connected to 1.2.3.4 and asked it for the website example.com.  If that server isn't configured to serve a website for example.com it typically serves a default site (in this case blogs.com).
If you got your domain to work as a CNAME, the browser would ask for the IP address of example.com.  DNS would see that it is a CNAME, look up example.blogs.com and return 1.2.3.4.  The browser would connect to 1.2.3.4 and ask it for example.com just as it did when it was an A record.
If you want people going to example.com to be redirected to example.blogs.com then you'll need to set up a basic web server that receives connections to example.com and sends a 301 permanent redirect to the browser to tell it go to example.blogs.com

A: You cannot use a CNAME for the root record in a zone file (this is prohibited per RFC 1034, read section 3.6.2). You'll need to put in an A record instead that points to the same IP as the target of your CNAME rule.

A: What is the output of dig example.com? If your know your nameserver's IP you can force dig to use your nameserver (dig @nameserver-ip example.com). If this works, your nameserver is not used for example.com. When did you assign the linode nameservers? Those changes can take time. Especially if your ISP's DNS server caches results...

A: Just looks like that your nameserver isnt running.
Can you check if you name server is running.
ps -aux | grep named
If your nameserver is not running.. start it and check again.
If it isnt started after you started it.. please post the named information of /var/log/daemon and /var/log/messages
grep named /var/log/messages
grep named /var/log/daemon
Perhaps it is a misconfiguration in your zone file.
if your nameserver IS RUNNING, please check your named.conf if your zone accept all incomming traffic.
It is not required to include A records of example.com in your zone file but it is recommended to do for DNS checks and whois checks.


text:
Q: How do I convert my *.py files to *.class files? I need to convert .py files to .class files so that I can make use of my Python code in a Java environment. How do I do it?

A: The easiest way to integrate Python and Java is by using Jython.

A: Use Jython. It has a built-in compiler to convert .py files to .class, called jythonc.


text:
Q: Correctly Typing Return Value of Async Fetch Functions The flow of an asynchronous function in Javascript requires typing such a workflow in Typescript as multiple possible return values. My main question is whether or not this is necessary and best practice.
If all goes well, the function returns my desired value. If it doesn't go well, I may want to throw an error.
But if I throw an error, that doesn't communicate the return value of the function, and so I still need to inform typescript what value the function should return.
So we start that code that looks a bit like this example:
class PostsClient {

   public async fetchPosts(): Promise<Posts[]> {
     try {
        const posts: Posts[] = await this.httpClient.fetch(this.apiUrl);
        return posts;
     } catch (e) {
        this.logger.captureError(e);
        throw e;
     }
   }

}

// Error from Typescript: `Function lacks ending return statement and return type does not include 'undefined'.`

In response to the warning from Typescript we change the return value of the function to Promise<Posts[] | undefined>
My hope would be that using this function inside another caller, for example a layout controller, could communicate with the typescript engine that the only reason that this function would not return the desired type Posts[] would be if an error is thrown, and the control flow of the function would be interrupted anyways.
But instead one ends up having problems like this.
class PostLayoutController {

    public async fetchAndStorePosts(): void {
       const posts = await this.postsClient.fetchPosts();
        this.sendAnalyticsData(posts)  // ERROR -- posts could be undefined!
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    }
}

Is it correct to deal with this by simply using a return statement to prevent further logic from executing?
if (!posts) {
   return;
}

or is there some better solution to this?

A: As @jonrsharpe mentioned in a comment to my question, Typescript actually does recognize that the fetchPosts function throws an error.
My problem was that in the actual implementation, we were using a handleApiErrors function which didn't have a recognizable 'error throwing' signature for Typescript, so it assumed the execution flow would continue.
This was an example of how the actual code was implemented:
class PostLayoutController {

    public async fetchAndStorePosts(): void {
       try {
          const posts = await this.postsClient.fetchPosts();
          this.storePosts(posts);
       } catch (e) {
          this.handleApiErrors(e);
       }
    }

    private handleApiErrors(e: Error) {
       if (e.code === 400) {
          throw new InvalidSubmissionError(e.message, ...more props)
       }

       // Some other error class cases.

       throw e;
    }
}

So I see that I need to do the error logic in the catch block and not delegate it to another function in order for Typescript to understand what is going on.


text:
Q: How to add a default method for an action class of a grammar? Recently, I experimented with some grammars for modifying small parts of a
 file. In those test cases, I would keep much
of the file as it was, only modifying small pieces here and there, see
this review question for an example.
So I needed one (or a few) action methods (i.e. methods in the action class of the
 grammar) where I would attach the modified parts of the file to the
 match object using its
make method. The problem was that the grammar itself would have many more
token/rules/regex with complicated
nesting. Hence, there was a need to propagate (by successively calling
 make()) the small change (currently attached to
 a token's match object) up to the TOP() method in the action class
such that everything
 else (all other tokens/rules/regexes) in the file was kept untouched
 in the result returned from the grammar's .parse() call.
So all methods in the action class except for one, was on the exact same form:
method make-data ($match-data) {
    $match-data.make( [~] $match-data.chunks.map: {$_.value.?made // $_.value} );
}

Now, this explicit repetition of the same code for all action methods seems
to me very verbose, and also breaks with the DRY programming principle.
Is there a way to tell the grammar class that if an action method
(corresponding to a token in the grammar) is
not specified , it will default to the make-data method above (or a similar one)?
So in this case, I envision a DEFAULT() method in the action class:
method DEFAULT ($match-data) {
    $match-data.make( [~] $match-data.chunks.map: {$_.value.?made // $_.value} );
}

that is called if a token in the grammar class does not have a
corresponding method in the action class.

A: Perl 6's Type system will call a FALLBACK method, if it's present in a class and an unknown method call is made.
The following solution adds default construction methods to the Calculations actions class.
grammar Calculator {
    token TOP { [ <add> | <sub> ] }
    rule  add { <num> '+' <num> }
    rule  sub { <num> '-' <num> }
    token num { \d+ }
}

class Calculations {
    method ws($) {}
    method FALLBACK($token, $match-data) {
        $match-data.make( [~] $match-data.chunks.map: {
            $_.value.?made // $_.value;
        } );
    }
}

say Calculator.parse('2 + 3', actions => Calculations).made;


text:
Q: Pygame - Looking for matches across 2 .txt files and user input For my program I have 2 .txt files: one with correctly spelt words (wordsCorrect.txt) and the other with the same words, on the same line, but misspelled in some way. One of the misspelled words is picked randomly and displayed on screen. The user has to input the correct version of that word.
I tried to write some code for comparing the words in the .txt files, but can't work out how to check if user input matches the correct word which, in turn, matches the randomly picked word on screen. I'm sorry if this is badly explained, but any help would be great!
   while word_pick == True:
        for event in pg.event.get():
            file1 = open("words.txt","r")
            file2 = open("wordsCorrect.txt","r")
            with file1 and file2:
                same = set(file1).intersection(file2)

A: Don't open and read the files in the event loop, otherwise the files are read again and again every time an event is added to the queue, for example if you move the mouse or press a key.
I recommend storing the correct together with the misspelled words in one file (maybe a csv file), create a dictionary, open the file and add the misspelled words as the keys and the correct words as the values.
words = {}

with open('words.txt') as f:
    for line in f:
        misspelled, correct = line.strip().split(',')  # Comma as word separator.
        words[misspelled] = correct

Then you can check if the user input is correct in this way:
current_word = 'bred'
user_input = 'bread'
if words[current_word] == user_input:
    print('Correct answer.')

Alternatively, you could use the zip function to zip the words in the two files together. This is a bit more error prone, since the files could, for example, have different line numbers.
with open('misspelled.txt') as f1, open('correct_words.txt') as f2:
    for misspelled, correct in zip(f1, f2):
        misspelled = misspelled.strip()
        correct = correct.strip()
        words[misspelled] = correct


text:
Q: CosmosDB Table API - CORS rules are not supported for this API We have some Azure Table storage tables in our subscription and would like to migrate them to CosmosDB table API due to performance reasons. To do this, I started creating cosmos db account by selecting Table API but my deployment failed with the following error. When i tried with SQL API, it works.
{"code":"DeploymentFailed","message":"At least one resource deployment operation failed. Please list deployment operations for details. "details":[{"code":"BadRequest","message":"{\r\n \"code\": \"BadRequest\",\r\n \"message\": \"CORS rules are not supported for this API\rMicrosoft.Azure.Documents.Common/2.1.0.0\"\r\n}"}]}
Can someone please let me know what could be the reason for this?

A: @AngiSen, may be related to a recent (breaking) update of Azure Cosmos DB resource provider (Microsoft.DocumentDb/databaseAccounts) as I just noticed today (28th of Nov 2018) that a previously running deployment (as of 23th of Nov 2018) of Cosmos DB Table API is now failing with this same error:

9:16:23 AM - Resource Microsoft.DocumentDb/databaseAccounts 'xxx-xxx-xxx' failed with message '{
  "code": "BadRequest",
  "message": "CORS rules are not supported for this API\r\nActivityId: xxx, Microsoft.Azure.Documents.Common/2.1.0.0"
}'

In my case I'm using 2015-04-08 version with Table API but I don't configure explicitly the CORS part and anyway there's no such configuration option in the resource provider.
Digging into the existing Cosmos DB instance with https://resources.azure.com shows there's indeed a CORS member that is part of the definition:

{
  "id": "/subscriptions/xxx/resourceGroups/xxx/providers/Microsoft.DocumentDB/databaseAccounts/xxx",
  "name": "xxx",
  "location": "North Europe",
  "type": "Microsoft.DocumentDB/databaseAccounts",
  "kind": "GlobalDocumentDB",
  "tags": {},
  "properties": {
    "provisioningState": "Succeeded",
    "documentEndpoint": "https://xxx.documents.azure.com:443/",
    "tableEndpoint": "https://xxx.table.cosmosdb.azure.com:443/",
    "ipRangeFilter": "",
    "enableAutomaticFailover": false,
    "enableMultipleWriteLocations": false,
    "isVirtualNetworkFilterEnabled": false,
    "virtualNetworkRules": [],
    "EnabledApiTypes": "Table, Sql",
    "databaseAccountOfferType": "Standard",
    "consistencyPolicy": {
      "defaultConsistencyLevel": "BoundedStaleness",
      "maxIntervalInSeconds": 86400,
      "maxStalenessPrefix": 1000000
    },
    "configurationOverrides": {},
    "writeLocations": [
      {
        "id": "xxx-northeurope",
        "locationName": "North Europe",
        "documentEndpoint": "https://xxx-northeurope.documents.azure.com:443/",
        "provisioningState": "Succeeded",
        "failoverPriority": 0
      }
    ],
    "readLocations": [
      {
        "id": "xxx-northeurope",
        "locationName": "North Europe",
        "documentEndpoint": "https://xxx-northeurope.documents.azure.com:443/",
        "provisioningState": "Succeeded",
        "failoverPriority": 0
      }
    ],
    "locations": [
      {
        "id": "xxx-northeurope",
        "locationName": "North Europe",
        "documentEndpoint": "https://xxx-northeurope.documents.azure.com:443/",
        "provisioningState": "Succeeded",
        "failoverPriority": 0
      }
    ],
    "failoverPolicies": [
      {
        "id": "xxx-northeurope",
        "locationName": "North Europe",
        "failoverPriority": 0
      }
    ],
    "cors": [],
    "capabilities": [
      {
        "name": "EnableTable"
      }
    ]
  }
}

Hope it'll get fixed quickly if it's indeed a breaking change...

A: Wanted to make an official statement here. I have spoken with the Cosmos DB team and they have a fix ready and it should be deployed tonight. Please let me know if you should have any questions. Thank you for posting the issue.


text:
Q: Why does org.joda.time.DateTimeFormatter not parse custom date time with millis correctly? I have a custom formatter...
// default our time zone to the machine local one.
private static final DateTimeZone LOCAL_TZ = DateTimeZone.getDefault();

// format of date (i.e., timestamp) is yyyy-MM-dd HH:mm:ss.S
private static final DateTimeFormatter YEAR_MONTH_DAY_HOUR_MINUTE_SECOND_MILLIS_FORMATTER =
        new DateTimeFormatterBuilder()
.appendYear(4,4)
.appendLiteral('-')
.appendMonthOfYear(1)
.appendLiteral('-')
.appendDayOfMonth(1)
.appendLiteral(' ')
.appendHourOfDay(2)
.appendLiteral(':')
.appendMinuteOfDay(1)
.appendLiteral(':')
.appendSecondOfDay(1)
.appendLiteral('.')
.appendMillisOfDay(1)
.toFormatter().withZone(LOCAL_TZ);

I do something like...
String value = "2011-06-21 05:00:00.0";
YEAR_MONTH_DAY_HOUR_MINUTE_SECOND_MILLIS_FORMATTER.parseDateTime(value);

If I look at the org.joda.time.DateTime in a debugger, I will see that the hour:minute:second.millis got converted to 00:00:00.0.
What gives?  I've tried mucking around with minDigits on HourOfDay, MinuteOfDay, SecondOfDay and so on.  Is this a bug in JodaTime 2.0? Or (more likely) my own ignorance?

A: You've said that it's 0 millis of the day. In other words, it's the first millisecond of the day. That obviously conflicts with it being hour 5, and it looks like the last-specified value  is taking precedence.
I suspect you want appendMillisOfSecond - the milliseconds within the already-specified second.
(Let me know if the difference isn't clear to you. I've recently been writing the parsers and formatters for Noda Time, so I'm coming from a somewhat different perspective to most people...)


text:
Q: Error in setting Prometheus datasource in Grafana on Kubernetes I am setting up Grafana on Kubernetes with some custom dashboards and Prometheus as a default data source.
All services are running behind Traefik. Prometheus is running at https://myapp.dev/svc/prometheus/ and Grafana is running at https://myapp.dev/svc/grafana/
I can log in to both grafana(also able to see dashboards that were added to config) and prometheus, however when I test the Prometheus data source, I see the following error in grafana logs:

lvl=eror msg="Data proxy error" logger=data-proxy-log userId=1 orgId=1 uname=xxx path=/api/datasources/proxy/1/api/v1/query remote_addr=192.168.64.1 referer=https://myapp.dev/svc/grafana/datasources/edit/1/ error="http: proxy error: dial tcp: lookup prometheus on 10.96.0.10:53: no such host"

Grafana deployment
kind: Deployment
apiVersion: apps/v1
metadata:
  namespace: default
  name: grafana-deployment
  labels:
    app: grafana
spec:
  replicas: 1
  selector:
    matchLabels:
      app: grafana
  template:
    metadata:
      labels:
        app: grafana
    spec:
      containers:
      - name: grafana
        image: grafana/grafana:latest
        ports:
        - containerPort: 3000
        volumeMounts:
          - mountPath: /etc/grafana/provisioning/datasources/
            name: datasource-volume
          - mountPath: /etc/grafana/provisioning/dashboards/
            name: dashboard-volume
          - mountPath: /var/lib/grafana
            name: grafana-storage
      volumes:
        - name: grafana-storage
          emptyDir: {}
        - configMap:
            defaultMode: 420
            name: grafana-datasource-cm
          name: datasource-volume
        - configMap:
            defaultMode: 420
            name: grafana-dashboard-cm
          name: dashboard-volume

Configmap
kind: ConfigMap
apiVersion: v1
metadata:
  name: grafana-datasource-cm
data:
  datasource.yml: |-
    apiVersion: 1
    datasources:
    - name: Prometheus
      type: prometheus
      orgId: 1
      access: proxy
      url: http://prometheus:9090/svc/prometheus/
      basicAuth: false

I am not sure on how to fix this error and test Prometheus datasource.

A: Sounds like it cannot find the prometheus service in the cluster. Maybe:

*

*It's in a different namespace❓

*It's defined but with a different name❓

If it's a different namespace you can try changing your config with the full FQDN of the service. prometheus.<namespace>.svc.cluster.local
kind: ConfigMap
apiVersion: v1
metadata:
  name: grafana-datasource-cm
data:
  datasource.yml: |-
    apiVersion: 1
    datasources:
    - name: Prometheus
      type: prometheus
      orgId: 1
      access: proxy
      url: http://prometheus.<namespace>.svc.cluster.local:9090/svc/prometheus/
      basicAuth: false

See if you can get to the service from your grafana pod :
$ kubectl exec -it <grafana-pod> sh
# curl http://prometheus.<namespace>.svc.cluster.local:9090

✌☮

A: Did you test the connection to the Prometheus data source after adding it?
Notice that if you're choosing the direct access type and you're adding a / to  the end of the url - you're receiving Unknown error:

After removing the / at the end - the test should succeed:

(*) I'm on: Grafana v3.1.1 (commit: a4d2708).


text:
Q: Adding a custom view to a list doesn't add all columns (Using PnP in Sharepoint Framework) I'm creating a list with PnP with an allready existing content type and then I'm trying to add a custom view with the columns from that content type.
The problem is that the view gets created but it only have some of the columns and it is random witch columns gets added when i run the function.
Can anybody tell me what is wrong?
Here's the code that creates the list with existing content type and adds the view.

Thanks in advance.

A: This is something that is unique to SharePoint list views and not in a good way unfortunately. Even I learnt it when I tried your code.
To add columns to the list views, they need to be done one after the other and not in parallel. Perhaps that is why you got tripped up.
So, you can use either of the below mentioned code to add your fields to the created list view:
1) Using then syntax:
spList.list.views.add("My New View 4", false, {
      RowLimit: 20,
      DefaultView: true,
      ViewQuery: "<OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy>",
    }).then((v) => {

    v.view.fields.removeAll().then(() => {

        v.view.fields.add("AnniversariesEventTitle").then(() =>{
        v.view.fields.add("AnniversariesDate").then(() =>{
        v.view.fields.add("AnniversariesPerson").then(() =>{
                    console.log("Done");
                });
            });
        });
    });
});

2) Using batch endpoint, it wont work in 2013 AFAIK, but in SP Online, SP 2016 and upcoming SP 2019, it will work:
spList.list.views.add("My New View 4", false, {
      RowLimit: 20,
      DefaultView: true,
      ViewQuery: "<OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy>",
    }).then((v) => {

        var spBatch = sp.web.createBatch();

        var fieldArray = ['AnniversariesEventTitle','AnniversariesDate','AnniversariesPerson'];

        v.view.fields.inBatch(spBatch).removeAll();
        fieldArray.forEach(fieldInternalName => {
            v.view.fields.inBatch(spBatch).add(fieldInternalName);
        });

        spBatch.execute()
        .then(console.log)
        .catch(console.log)
});


text:
Q: Vim commands :Explore :Sexplore :Hexplore doesn't work in cygwin 3.3 in cywing 2.721, the installation was made using cywing, every thing works but when I try to use the following command.
:Explore

vim said E492: Not an editor command
also neither :Sexplore or :Hexplore works.
is there any way to activate this functionality?
This is in machine with windows xp.

A: Well I solved reading the
:help usr_01.txt
It said that is necessary to run this command !cp -i $VIMRUNTIME/vimrc_example.vim ~/.vimrc inside vim, it just copy a .vimrc to home user.
I close and opened vim and :Explore, Hexplore, Vexplore worked.

A: I had the same problem as well. Since it's a fresh install of Vim you don't have a .vimrc (or _vimrc on Windows). A vimrc is Vim's configuration file, and once you have one Vim will no longer try to be compatible with Vi (usually what you want).
So all you have to do is create a vimrc file and you should be ready to :Explore all you want. Below are locations you can put your vimrc file, and the filename to use for it. (depending on your system)
    Unix/Linux/OSX: $HOME/.vimrc or $HOME/.vim/vimrc

    MS-Windows: $HOME/_vimrc, $HOME/vimfiles/vimrc
            or $VIM/_vimrc

sources:
* :help 'compatible'
* :help 'vimrc'
I also recommend following atomsfat's answer as well to give you a simple vimrc to start out with.

A: Those commands are provided by the netrw plugin.  Check :scriptnames to see if that plugin is loaded.


text:
Q: Refactoring controller As I'm sure you can tell by the following code, I'm a newbie.  But I have managed to get this to work correctly...
However, I'd really like to know how to refactor this code, as I'm sure its not the best way to do it.  Can anyone point me in the right direction?
Thank you very much in advance...
current_controller = params[:controller]

if current_controller == "menus" && params[:id].present?
    @menu = Menu.find(params[:id])
elsif current_controller == "menus" && params[:id].nil?
    @menu = Menu.first
elsif current_controller == "items" || current_controller == "categories"
    @menu = Menu.find(params[:menu_id])
else
    @menu = Menu.last
end

A: A naive translation into (slightly) smaller code:
current_controller = params[:controller]
@menu = if current_controller == "menus"
          params[:id].present? Menu.find(params[:id]) : Menu.first
        elsif current_controller == "items" || current_controller == "categories"
          Menu.find(params[:menu_id])
        else
          Menu.last
        end

Where does this code live?
Would it make more sense to have this in a base app controller, or filter, etc. and override in the three controllers that are special-cased? Or is this wrapped up in a helper, or...?
Edit Using Procs.
# Default if hash entry not found.
menus = Hash.new(Proc.new { |p| Menu.last })

# Items and categories controllers
itemcats = Proc.new { |p| Menu.find(p[:menu_id]) }
menus["items"] = menus["categories"] = itemcats

# Menus controller
menus["menus"] = Proc.new { |p| p[:id] ? Menu.find(p[:id]) : Menu.first }

@menu = menus[params[:controller]].call(params)

(More or less.)

A: This would be my refactoring to your code:
@menu = case controller.controller_name
        when "menus"
            if params[:id]
                Menu.find(params[:id])
            else
                Menu.first
            end
        when "items" || "categories"
            Menu.find(params[:menu_id])
        else
            Menu.last
        end

A: This is untested, but you could try using the case statement as davenewton said
# Case on an expression:
@menus = case params[:controller]
when "menus" && params[:id].present? then Menu.find(params[:id])
when "menus" && params[:id].nil? then Menu.first
when "items", "categories" then Menu.find(params[:menu_id])
else Menu.last
end

You can replace the "then's" with semicolons if you prefer


text:
Q: Prevent process from turning unresponsive My program has to do some heavy calculation. The whole process turns unresponsive after a few seconds in cause of the calculation, while the CPU usage stays somewhere around 20% and the memory usage around 100 MB.
Is there a general way to keep a Windows forms app responsive while doing heavy calculations?

A: All you have to do is to just move that heavy calculation to different thread.
Here is a modified example from documentation:
using System;
using System.Threading;

public class ServerClass
{
    // The method that will be called when the thread is started.
    public void HeavyCalculation()
    {
        Console.WriteLine(
            "Heavy Calculation is running on another thread.");

        // Pause for a moment to provide a delay to make
        // threads more apparent.
        Thread.Sleep(3000);
        Console.WriteLine(
            "Heavy Calculation has ended.");
    }
}

public class App
{
    public static void Main()
    {
        ServerClass serverObject = new ServerClass();

        // Create the thread object, passing in the
        // serverObject.InstanceMethod method using a
        // ThreadStart delegate.
        Thread InstanceCaller = new Thread(
            new ThreadStart(serverObject.HeavyCalculation));

        // Start the thread.
        InstanceCaller.Start();

        Console.WriteLine("The Main() thread calls this after "
            + "starting the new InstanceCaller thread.");

    }
}

And some more documentation just in case you need:
https://learn.microsoft.com/en-us/dotnet/standard/threading/using-threads-and-threading
https://www.tutorialspoint.com/csharp/csharp_multithreading.htm
And a short way of starting a function in thread:
C# Call a method in a new thread


text:
Q: Azure Linux Container Web App does not resolve name within the vnet using private DNS vnet is connected to my Web App through which I can communicate with other services and applications. When I specify the internal IP of another application to my application, everything works fine. But now the task has come from the management to remake it to use the internal DNS server and internal DNS names. In Azure vnet, in the DNS servers settings, I specified the IP of my DNS servers. I added 168.63.129.16 - now work. If you connect Windows VM to the network everything works fine. Perhaps something needs to be added to the Dockerfile or Linux Container Web App settings so that integration with vnet and DNS works.

A: If your web application is integrated with the virtual network, your application would be able to communicate with the applications in the virtual network
After integrating your web application with the virtual network, you need to perform sync network action
Go to Azure portal --> Go to your App Service plan where the web app is hosted --> Under Networking, select Virtual Network Integration --> select Sync Network

Once the sync action is complete, you would be able  to communicate with your internal application using the DNS name from your web application
Reference: Name resolution for resources in Azure virtual networks | Microsoft Docs


text:
Q: True diameter of black holes? It's currently estimated that a black of ten solar masses would have a diameter (i.e. an event horizon) of about 30 kilometres or so. I've been recently considering black holes from a quantum gravity perspective and I'm wondering to what extent this apparent diameter could just be an illusion. My thought was that, if light escaping, or being reflected from black holes, is being condensed by a field of fermions surrounding it, then it may give the illusory effect that the event horizons' diameter is larger than it actually is since the wavelength(s) of the emitted/reflected photons would be increasing in proportion to the increased distance from the event horizon. This is all rather speculative, but I was thinking that the true diameter of an event horizon (if a singularity really is there, and if it really is infinitely dense) might be more like the diameter of a proton, or something. Perhaps even smaller.
Perhaps as an adjunct to this I ought to briefly elaborate on my idea concerning singularities: I was thinking that infinities of density may certainly be possible in the cores of black holes since they operate within a special case so far as the universe is concerned, i.e. they operate beyond the bounds of relativistic physics (underpinned by fermionic fields whereby the minima of measurable space is determined by Planck's constant) and hence finite masses compacted within infinitesimal of 'space' may be possible.
Any thoughts on this?

A: The true diameter of a black hole is that which determines a surface beyond which not even light escapes.


text:
Q: IE7: click triggers only on blur I try to hide a div, when click on a checkbox:
$("input[type='checkbox']").on('click', function() {
  $("div.new").hide();
});

The hidding of the div occurs only after the mouse is off the checkbox, why? should I use mousedown for explorer?

A: Try giving the checkboxes a class and call the function on that class
$(".checkbox").on('click', function() {
  $("div.new").hide();
});


text:
Q: how to create a php class which can be casted to boolean (be truthy or falsy) I am creating a collection class and would like it to be drop-in-replacement for arrays, which I use currently.
How to create a class which could be casted to boolean, so the class can be truthy or falsy?
A simple test shows that an object of empty class is truthy:
class boolClass {}
$obj = new boolClass();
var_dump( (bool)$obj);
//prints
//bool(true)

But I need to decide if my class is truthy or falsy. Is there eny way to tell the PHP engine how to cast my class to boolean? Like I could do with __toString()?
Background:
Lets say I write a class like this (it's an example only):
class MyCollection implements ArrayAccess, Iterator {
    //...
}

I heavily use this patterns currently:
$var = array();

if (empty($var)) {
   //array is empty, (or there is no array at all)
   // I do something here
}

I would like that to look like:
$var = new MyCollection(array());

and keep the rest unchanged. But the $var containing MyCollection is always truthy so I would need to all the conditions to:
if ($var->isEmpty()) {
    //...
}

But this is unacceptable, as my codebase have many megabytes.
Any solution here?

A: On this page, the magic methods that you can define for your classes are enumerated.
http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring
You demonstrate that you already know about __toString().
Unfortunately, there is no magic method listed there that does what you are asking. So, I think for now your only option is to define a method and call that method explicitly.

A: You can take a look at the PHP operator extension which you can use to overload many operators including == and ===. With this extension, you should be theoretically able to write a class comparable to boolean values like this:
if($object == true)

A: After much angst, disappointment, and hacking - I believe I have found a solution. The solution doesn't call for any extensions; it can be implemented with a very small amount of PHP boilerplate. However, before implementing this solution yourself, please take note that this is - in fact - a HUGE hack. That being said, here is what I discovered:
Frustrated, I spent some time looking over the PHP documentation for Booleans. While user-created classes are simply denied the ability to be cast as a boolean, one class - oddly enough - was afforded the capability. The astute reader would notice that this class is none other than the built-in SimpleXmlElement. By process of deduction, it seems fair to assume that any subclass of SimpleXmlElement would also inherit its unique boolean-casting capability. While, in theory this approach seems valid, the magic surrounding SimpleXmlElement also takes away from the utility of this approach. To understand why this is, consider this example:
class Truthy extends SimpleXmlElement { }

Truthy is a subclass of SimpleXmlElement, so we should be able to test if its special boolean-casting property was inherited:
$true = new Truthy('<true>1</true>'); // XML with content eval's to TRUE
if ($true) echo 'boolean casting is happening!';
$false = new Truthy('<false></false>'); // empty XML eval's to FALSE
if (!$false) echo 'this is totally useful!';

Indeed, the boolean-casting property afforded to SimpleXmlElement is inherited by Truthy. However, this syntax is clumsy, and it is highly unlikely that one would get much utility out of this class (at least when compared to using SimpleXmlElement natively). This scenario is where the problems start to come up:
$false = new Truthy('<false></false>'); // empty XML eval's to FALSE
$false->reason = 'because I said so'; // some extra info to explain why it's false
if (!$false) echo 'why is this not false anymore?!?';
else echo 'because SimpleXMLElements are magical!';

As you can see, trying to set a property on our subclass immediately breaks the utility we get from the inherited boolean-casting. Unfortunately for us, the SimpleXmlElement has another magical feature that breaks our convention. Apparently, when you set a property of a SimpleXmlElement, it modifies the XML! See for yourself:
$xml = new SimpleXmlElement('<element></element>');
$xml->test = 'content';
echo $xml->asXML(); // <element><test>content</test></element>

Well there goes any utility we would get from subclassing SimpleXmlElement! Thankfully, after much hacking, I found a way to save information into this subclass, without breaking the boolean casting magic: comments!
$false = new Truthy('<!-- hello world! --><false></false>');
if (!$false) echo 'Great Scott! It worked!';

Progress! We were able to get useful information into this class without breaking boolean-casting! Ok, now all we need to do is clean it up, here is my final implementation:
class Truthy extends SimpleXMLElement {

public function data() {

    preg_match("#<!\-\-(.+?)\-\->#", $this->asXML(), $matches);

    if (!$matches) return null;

    return unserialize(html_entity_decode($matches[1]));

}

public static function create($boolean, Serializable $data = null) {
    $xml  = '<!--' . htmlentities(serialize($data)) . "-->";
    $xml .= $boolean ? '<truthy>1</truthy>' : '<truthy/>';
    return new Truthy($xml);
}

}

To remove some of the clumsiness, I added a public static factory method. Now we can create a Truthy object without worrying about the implementation details. The factory lets the caller define any arbitrary set of data, as well as a boolean casting. The data method can then be called at a later time to retrieve a read-only copy of this data:
$false = Truthy::create(false, array('reason' => 'because I said so!'));
if (!$false) {
   $data = $false->data();
   echo 'The reason this was false was ' . $data['reason'];
}

There you have it! A totally hacky (but usable) way to do boolean-casting in user-defined classes. Please don't sue me if you use this in production code and it blows up.

A: You cannot.
In PHP an object when cast to bool always produces true. There is no way of changing that.

A: If you have a code size of "many megabytes" the issue is probably not that your naming scheme is too verbose. I would instead look for duplication and try to abstract code.
OTOH, why is the size of the code a big issue? Try to minimize the code you are including each time php runs. Stray code that isn't used makes no difference. If you have to include a lot of code, consider using caching software, such as MMCache.
And to answer your original question, AFAIK there is no way to add type coercion to PHP classes. an instance will always evaluate to true.

A: If you don't want to implement your own method you could hack your way into __toString, like this:
class foo
{
    public function __toString()
    {
        return strval(false);
    }
}

$foo = new foo();

if (strval($foo) == false) // non-strict comparison
{
   echo '$foo is falsy';
}

echo (bool) strval($foo); // false

A: Well, there is __invoke method which seems close to your intention:
class boolClass {
    public function __invoke() {
        return true;
    }
}
$obj = new boolClass();
var_dump( (bool)$obj());
//prints
//bool(true)