text:
Q: Is there a way to automate webpage login and download report? Is there a way to automate a task a webpage login and download report maybe with power-automate or some other method?

*

*open web page

*enter any parameters.

*click download button.

*save download to local drive.

Thanks

A: Yes it is possible to automate it using Power Automate Desktop, you can take control of the browser, If the webpage structure remains the same and the login doesn't ask additional captcha except usual login and password fields.
You can configure the automation by

*

*First opening the webpage using Browser Control in PAD(Power Automate Desktop)

*Entering the username password can be automatically done with PAD (both should
be defined in the
automation)

*Capture the web element using the action to click a button - either to
navigate the page or download something.

*Can save the file into local system using PAD by usual browser download or mentioning separate path in the automation.

A: If you know how to code such as Python. Then Selenium,playwright,Clicknium would be a good choice. Clicknium should be the most simple one, but it can only run in Windows. In include a Recorder to identity the UI element and include APIs for click and set_text.
If you don't want to code, you can use RPA tools, such as power automate and UI path.


text:
Q: C# System.InvalidCastException: Specified Cast is not valid I've been struggling with one problem these past few hours.
I keep getting an error and it tells me that the specified cast is not valid. I'm able to change the values on the database using the stored procedure. However, when I try doing it with the executable I get that error.
This is the error
System.InvalidCastException: Specified cast is not valid.
at Administrator_Panel.DB.ReadAccountInfo(String UserID, In32& Count)

This is the code.
 public static Account ReadAccountInfo(string UserID, out int Count)

 if (Reader.Read())
                ReturnValue = new Account((int)Reader["UserUID"],
                                            (string)Reader["Pw"],
                                            (bool)Reader["Admin"],
                                            (bool)Reader["Staff"],
                                            (short)Reader["Status"],
                                            (int)Reader["Point"],
                                            (int)Reader["DaemonPoints"]);

Any help would be appreciated. :) Thank you

A: See this answer:  How to (efficiently) convert (cast?) a SqlDataReader field to its corresponding c# type?
You can't just cast SqlDataReader fields to their corresponding value types because of the possibility of nulls.  You can use nullable types but it's likely your Account object isn't setup to take nullable types.
One way you can try to handle this is to add null checking:
 ReturnValue = new Account(Reader["UserUID"] == DBNull.Value ? 0 : (int)Reader["UserUID"] ,
                           Reader["Pw"] == DBNull.Value ? "" : Reader["Pw"].ToString(),
                           Reader["Admin"] == DBNull.Value ? false : (bool)Reader["Admin"],
                           Reader["Staff"] == DBNull.Value ? false : (bool)Reader["Staff"],
                           Reader["Status"] == DBNull.Value ? (short) 0 : (short)Reader["Status"],
                           Reader["Point"] == DBNull.Value ? 0 :  (int)Reader["Point"],
                           Reader["DaemonPoints"] == DBNull.Value ? 0 : (int)Reader["DaemonPoints"]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I create a button which Rectangle object filled with a color in WPF with C#? How can I create Button control which contains a Rectangle object filled with the color represented by the Colors.Aqua?
I have a rectangle
Rectangle rectangle = new Rectangle();
rectangle.Fill = new SolidColorBrush(Colors.Aqua);
rectangle.Width = 100;
rectangle.Height = 50;

and I have a button:
Button button = new Button();
button.Content = "Button";

I can't figure out how to combine these things.
Any ideas?

A: button.Content = rectangle;

or in XAML that would be like
<Button>
  <Button.Content>
     <Rectangle Width="100" Height="50">
        <Rectangle.Fill>
           <SolidColorBrush Color="Aqua" />
         </Rectangle.Fill>
      </Rectangle>
  </Button.Content>
</Button>

A: You can also define a Style in your XAML, set the TargetType to Button, and then set the Background property's Value to "Aqua".  Of course, you'll also have to specify the Style for all of the Buttons that you drop into your interface so that they get the desired look.


text:
Q: Why might the Lawson minimal surface $\xi_{1,2}$ have a Morse index 9? In page 15 of the article New Applications of Min-max Theory, Andre Neves said that: a wishful thinking would suggest the Lawson minimal surface $\xi_{1,2}$ in the 3-sphere to have a Morse index 9, but there is no real evidence.
My question is, what suggests the index to be 9? Say, can we find a 9-parameter deformation of $\xi_{1,2}$ which decreases its area?

A: Due to a recent preprint by Kapouleas and Wiygul (arXiv:1904.05812), the index of the Lawson $\xi_{1,g}$ surface is $2g+3$. I have not looked at the paper in detail so far, but let me cite from the authors introduction:
"The ideas of our proof originate with work of NK on the approximate kernel for Scherk surfaces. Our approach requires a detailed understanding of the elementary geometry of $S^3$ and of the surfaces involved, especially their symmetries. The proof makes also heavy use of Alexandrov reflection in the style of Schoen's. The Courant nodal theorem [ and an argument of Montiel- Ros play important roles as well. In ongoing work we hope to extend this result to determine the index and nullity of all Lawson surfaces desingularizing intersecting great two-spheres in the round three-sphere $S^3$."

A: This is an old thread, but I figured I would add a short comment that may explain some of the reasoning behind the 'wishful thinking' that Neves refers to.
Let us, for all integer $p \geq 1$, write $\omega_p$ for the $p$-width of $\mathbf{S}^3$, that is the min-max value associated to a $p$-parameter Almgren-Pitts construction. Then
\begin{equation}
\omega_1 \leq \cdots \leq \omega_p \leq \cdots
\end{equation}
is an increasing, though not strictly increasing sequence.
Moreover, for each $p$ there is an embedded minimal surface $\Sigma_p \subset \mathbf{S}^3$ with area and Morse index satisfying
\begin{equation}
\mathrm{area} \, \Sigma_p = \omega_p
\quad \text{and} \quad \mathrm{index} \, \Sigma_p \leq p.
\end{equation}
Note that the index bound is not sharp in general. For example $\omega_1 = \cdots = \omega_4 = 4 \pi$ are all realised by an equatorial sphere, and therefore
\begin{equation}
\mathrm{index} \, \Sigma_4 = 1.
\end{equation}
The specific values of the widths are only known for relatively small $p$, but a PhD student of Neves, Charles Nurser, proved some estimates for the ninth width, namely:
\begin{equation}
2 \pi^2 < \omega_9 < 8 \pi.
\end{equation}
The lower bound means that $\Sigma_9$ is not a Clifford torus, and the upper bound that it is not a multiplicity-two copy of a minimal sphere. It must therefore be a 'new' surface, and it is not unreasonable to conjecture that it might be the Lawson surface $\xi_{1,2}$.
This is just a guess, but as far as the Morse index is concerned, perhaps the thinking was that $\omega_p > \omega_{p-1}$ might mean that $\mathrm{index} \, \Sigma_p = p$. For example $\omega_5 = 2 \pi^2 >  4 \pi = \omega_4$, and is realised by a Clifford torus, with Morse index five. However I must emphasise this is purely speculative, and I'd be very curious to hear from someone more knowledgeable.


text:
Q: How to force BE users to paste as plain text in TYPO3 6.x? CMS users tend to paste anything into CMS text editors. To prevent website destruction - and as log as there's no non-wysiwyg editor (like markitup) for TYPO3, I would like to as least have some good old "force plain text paste" in place.
TYPO3's RTE has a button "pastetoggle, pastebehaviour, pasteastext". But I haven't managed to configure it so it's always active.
Also, there's an extension ad_rtepasteplain, but it produced no result in TYPO3 6.1.
Is there a usable way to implement paste-as-plain-text for TYPO3 6.x?
[EDIT]
I found (for user TSConfig)

*

*setup.default.rteCleanPasteBehaviour

*setup.override.rteCleanPasteBehaviour

as well as (for page TSConfig)

*

*buttons.pastetoggle.setActiveOnRteOpen

*buttons.pastetoggle.hidden

... none of which I got running yet. If that's the way to go: is there a working tutorial?

A: Got it. This is my current setup
RTE.default {
  enableWordClean = 1
  removeTrailingBR = 1
  removeComments = 1
  removeTags = center, font, o:p, sdfield, u
  removeTagsAndContents = link, meta, script, style, title

  hidePStyleItems = h5,h6,pre,address,div

  // buttons
  showButtons =  chMode, formatblock, insertcharacter, removeformat, unorderedlist, orderedlist, outdent, indent, link, copy, cut, paste,  showhelp, about,line, bold,pastetoggle, pastebehaviour, pasteastext

 buttons.pastetoggle.setActiveOnRteOpen = 1
 buttons.pastetoggle.hidden = 1

}

as well as setup.override.rteCleanPasteBehaviour=pasteStructure or plainText in user TSConfig


text:
Q: Azure Devops Error : "unknown field "imagePullPolicy" in io.k8s.api.core.v1.PodSpec" I am using Azure Devops, and getting unknown field imagePullPolicy"in io.k8s.api.core.v1.PodSpec while doing helm install :

2019-07-05T10:49:11.0064690Z ##[warning]Can't find command extension for ##vso[telemetry.command]. Please reference documentation (http://go.microsoft.com/fwlink/?LinkId=817296)
2019-07-05T09:56:41.1837910Z Error: validation failed: error validating "": error validating data: ValidationError(Deployment.spec.template.spec): unknown field "imagePullPolicy" in io.k8s.api.core.v1.PodSpec
2019-07-05T09:56:41.1980030Z ##[error]Error: validation failed: error validating "": error validating data: ValidationError(Deployment.spec.template.spec): unknown field "imagePullPolicy" in io.k8s.api.core.v1.PodSpec
deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "clusterfitusecaseapihelm.fullname" . }}
labels:
{{ include "clusterfitusecaseapihelm.labels" . | indent 4 }}
spec:
strategy:
    rollingUpdate:
    maxSurge: 1
    maxUnavailable: 0
    type: RollingUpdate
selector:
    matchLabels:
    app.kubernetes.io/name: {{ include "clusterfitusecaseapihelm.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
template:
    metadata:
    labels:
        app.kubernetes.io/name: {{ include "clusterfitusecaseapihelm.name" . }}
        app.kubernetes.io/instance: {{ .Release.Name }}
    spec:
    containers:
    - image:  {{ .Values.image.repository }}:{{ .Values.image.tag }}
        name:  {{ .Chart.Name }}
        env:
        - name: ASPNETCORE_ENVIRONMENT
        value: {{ .Values.environment }}
        resources:
        requests:
            cpu: {{ .Values.resources.requests.cpu }}
            memory: {{ .Values.resources.requests.memory }}
        limits:
            cpu: {{ .Values.resources.limits.cpu }}
            memory: {{ .Values.resources.limits.memory }}
        livenessProbe:
        httpGet:
            path: /api/version
            port: 80
        initialDelaySeconds: 90
        timeoutSeconds: 10
        periodSeconds: 15
        readinessProbe:
        httpGet:
            path: /api/version
            port: 80
        initialDelaySeconds: 30
        timeoutSeconds: 10
        periodSeconds: 15
        ports:
        - containerPort:  80
        name:  http
        volumeMounts:
        - mountPath: /app/config
        name: {{ include "clusterfitusecaseapihelm.name" . }}
        readOnly: true
    volumes:
        - name: {{ include "clusterfitusecaseapihelm.name" . }}
    imagePullPolicy: Always
    imagePullSecrets:
    - name: regsecret

Tried this also but failed:

A: imagePullPolicy is a property of a Container object, not a Pod object, so you need to move this setting inside the containers: list (next to image:).


text:
Q: NoSuchMethodError with spring-webmvc upgrade We upgraded to spring-webmvc 5.2.3.RELEASE.
This is causing a JUnit to fail.
I think the issue is with the .build() method - it can't be found.
The code:
@RunWith(MockitoJUnitRunner.class)
public class CommunicationDeliveryControllerTest {

    @InjectMocks
    CommunicationDeliveryController controller = new CommunicationDeliveryController();

    @Mock
    private RequestHandler requestHandler;

    @Mock
    private HttpServletRequest httpServletRequest;

    private MockMvc mockMvc;
    private Gson gson = new Gson();
    private CommunicationDeliveryController spiedController;

    @Before
    public void setup() {
        spiedController = spy(controller);
        mockMvc = standaloneSetup(spiedController).build();
    }

    @Test
    public void initiateBatchRunTest() throws Exception{
        MvcResult result = mockMvc.perform(post("/api/BatchRun").contentType(MediaType.APPLICATION_JSON_VALUE).content(gson.toJson(BulkCommunicationRequestData.getBulkEmailRequestForPositive()))).andReturn();
        assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
    }

    @Test
    public void deliverCommunicationTest() throws Exception{
        MvcResult result = mockMvc.perform(post("/api/deliverCommunication").contentType(MediaType.APPLICATION_JSON_VALUE).content(gson.toJson(BulkCommunicationRequestData.populateAllEmailDetail()))).andReturn();
        assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
    }
}

The error:
java.lang.NoSuchMethodError: org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StandaloneConfiguration.getInterceptors()[Ljava/lang/Object;
        at company.custcomm.service.communicationdelivery.controllers.CommunicationDeliveryControllerTest.setup(CommunicationDeliveryControllerTest.java:45)

Are there compatibility issues between our versions of spring-webmvc, mockito, and JUnit?
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.10.19</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.3.RELEASE</version>
</dependency>

A: I upgrade all spring dependencies to 4.3.18-RELEASE, then there is no error any more.

A: Is there a specific version of spring-test in your dependencies?
I ran into a similar problem a while ago - turned out that there was a strict version limit for spring-test, and upgrading it to 5.2.3-RELEASE resolved the issue.

A: If you do not want to change the version of your Junit and spring-webmvc then you can specify spring-test version explicitly in your pom.xml. This works for me.
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-test</artifactId>
           <version>5.2.0.RELEASE</version>
           <scope>test</scope>
      </dependency>


text:
Q: Reading a python UUID byte string in C++? I have a string of 16 bytes in python created from the uuid.bytes method, something like:
    'I\x9e|T\r\xad@\x80\x986m\x00\x1c\x07z0'
for example, that I am passing to a C++ file.
Is there a way for me to read that from the C++ side and reconstruct the UUID? I was going to read it into a 16-char array since a char = 1 byte, but not sure where to go from there.

A: Something like this (untested)
char to_hex(int x)
{
  return x < 10 ? x + '0' : (x - 10) + 'A';
}

char bytes[16];
...
std::string uuid;
for (int i = 0; i < 16; ++i)
{
  uuid += to_hex((bytes[i] >> 4) & 0x0F);
  uuid += to_hex(bytes[i] & 0x0F);
}

A: I'd use:
UUID.hex

unless you need it in a binary representation.  No use converting back and forth.


text:
Q: "Welcome to Nginx!" - Docker-Compose, using uWSGI, Flask, nginx My Problem:

I am using Ubuntu 18.04 and a docker-compose based solution with two Docker images, one to handle Python/uWSGI and one for my NGINX reverse proxy. No matter what I change, it always seems like WSGI is unable to detect my default application. Whenever I run docker-compose up, and navigate to localhost:5000 I get the above default splash.
The complete program appears to work on our CentOS 7 machines. However, when I try to execute it on my Ubuntu test machine, I can only get the "Welcome to NGINX!" page.
Directory Structure:
 /app
  - app.conf
  - app.ini
  - app.py
  - docker-compose.py
  - Dockerfile-flask
  - Dockerfile-nginx
  - requirements.txt
  /templates

(All code snippets have been simplified to help isolate the problem)
Here is an example of my docker traceback:
clocker_flask_1
[uWSGI] getting INI configuration from app.ini
current working directory: /app
detected binary path: /usr/local/bin/uwsgi
uwsgi socket 0 bound to TCP address 0.0.0.0:5000 fd 3
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
*** Operational MODE: preforking+threaded ***
WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0x558072010e70 pid: 1 (default app)

clocker_nginx_1
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Configuration complete; ready for start up

Here is my docker-compose.yaml:
# docker-compose.yml
version: '3'
services:

  flask:
    image: webapp-flask
    build:
      context: .
      dockerfile: Dockerfile-flask
    volumes:
      - "./:/app:z"
      - "/etc/localtime:/etc/localtime:ro"
    environment:
      - "EXTERNAL_IP=${EXTERNAL_IP}"

  nginx:
    image: webapp-nginx
    build:
      context: .
      dockerfile: Dockerfile-nginx
    ports:
      - 5000:80
    depends_on:
      - flask

Dockerfile-flask:
FROM python:3
ENV APP /app
RUN mkdir $APP
WORKDIR $APP
EXPOSE 5000
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD [ "uwsgi", "--ini", "app.ini" ]

Dockerfile-nginx
FROM nginx:latest
EXPOSE 80
COPY app.conf /etc/nginx/conf.d

app.conf
server {
    listen 80;
    root /usr/share/nginx/html;
    location / { try_files $uri @app; }
    location @app {
        include uwsgi_params;
        uwsgi_pass flask:5000;
    }
}

app.py
# Home bit
@application.route('/')
@application.route('/home', methods=["GET", "POST"])
def home():
    return render_template(
        'index.html',
        er = er
    )

if __name__ == "__main__":
    application.run(host='0.0.0.0')

app.ini
[uwsgi]
protocol = uwsgi
module = app
callable = application
master = true
processes = 2
threads = 2
socket = 0.0.0.0:5000
vacuum = true
die-on-term = true
max-requests = 1000

A: The nginx image comes with a main configuration file, /etc/nginx/nginx.conf, which loads every conf file in the conf.d folder -- including your nemesis in this case, a stock /etc/nginx/conf.d/default.conf. It reads as follows (trimmed a bit for concision):
server {
  listen 80;
  server_name localhost;

  location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
  }
}

So, your app.conf and this configuration are both active. The reason why this default one wins, though, is because of the server_name directive that it has (and yours lacks) -- when you're hitting localhost:5000, nginx matches based on the hostname and sends your request there.
To fix this easily, you can just remove that file in your Dockerfile-nginx:
RUN rm /etc/nginx/conf.d/default.conf


text:
Q: Having Falling block display glass pane that is not just a pole (Java 1.14) I've been trying to make falling blocks in minecraft to show glass panes that contains properties such as north, south, east and west.
I can get the facing property on commandblocks to work when I display them as a falling block but not on glass pane.
The following shows my attempt to do so
/summon falling_block ~ ~1 ~ {Time:0,BlockState:{Name:"minecraft:glass_pane",Properties:{south:true,north:true}},NoGravity:1}

A: All block states in NBT have string values.
Properties:{south:"true",north:"true"}}


text:
Q: how to use" $ ln -sf ../models" in windows command line i am trying to use
$ ln -sf ../models but its giving me error :
'ln' is not recognized as an internal or external command,
operable program or batch file.
Not sure how to use this command on windows
So baiscally i am following the intstruction in "full stack webdevelopment in backbone"..
i want to execute :
$ mkdir -p app/models
$ mkdir -p app/node_modules

$ cd app/node_modules
$ ln -sf ../models
$ cd app
$ node

> Movie = require('models/movie');
> movie = new Movie({title: "The Artist"})

and output should be :
> movie = new Movie({title: "The Artist"})
{ cid: 'c1',
attributes:
{ title: 'The Artist',
year: 0,
description: 'empty',
selected: false },
_changing: false,
_previousAttributes: {},
changed: {},
_pending: false }

My folder app/models/movie.js
moive.js contain :
var Backbone = require("Backbone");
var Movie = Backbone.Model.extend({
defaults: {
title: "default",
year: 0,
description: "empty",
selected: false
}
});
module.exports = Movie;


text:
Q: Using Rouche's theorem Let $p>1$.
Consider $\phi(p)=\int_0^{\infty}\left|\frac{\sin t}{t}\right|^pdt$.
Function $\phi(p)$ is analytic on its domain.
It's derivative, $\phi'(p)=\int_0^{\infty}\left|\frac{\sin t}{t}\right|^p\ln\left|\frac{\sin t}{t}\right|dt$.
Let $g(p)=\frac{1}{2\sqrt p}\phi(p)$ and $f(p)=\sqrt p \phi'(p)$.
Using Rouche's theorem http://en.wikipedia.org/wiki/Rouch%C3%A9's_theorem
, show that
$f(p)+g(p)$ has one zero.
Thank you.


text:
Q: Как перенести информацию массива в следующий элемент tr Возникла такая проблема.
Как перенести информацию массива в следующий tr, если в одной tr может содержаться только четыре td.

window.onload = function() {
  var cell = [0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1];
  var tableContainer = document.querySelector("table");
  var tbodyContainer = tableContainer.querySelector("tbody");
  cell.forEach(function(Onecell) {
    if (Onecell === 0) {
      var dead = document.createElement("tr");
      tbodyContainer.appendChild(dead);
      var cellCreate = document.createElement("td");
      // добавляем только что созданый элемент в дерево DOM
      cellCreate.classList.add("dead");
      dead.appendChild(cellCreate);
    } else {
      var live = document.createElement("tr");
      tbodyContainer.appendChild(live);
      var cellCreate = document.createElement("td");
      // добавляем только что созданый элемент в дерево DOM
      cellCreate.classList.add("live");
      live.appendChild(cellCreate);
    }
  });

}
td {
  width: 20px;
  height: 20px;
}
.dead {
  background-color: red;
}
.live {
  background-color: green;
}

https://jsfiddle.net/zvb4c3a0/1/

A: Переписал немного и оптимизировал https://jsfiddle.net/zvb4c3a0/5/
var cell = [0,1,1,0,1,0,1,0,1,0,1,1,0,1,1,1,0,1];
var tableContainer = document.querySelector("table");
var tbodyContainer = tableContainer.querySelector("tbody");
var tr = document.createElement("tr");
var counter = 0;

cell.forEach(function(Onecell) {

  //% - это остаток от деления
  if(counter%4 == false) {
    tbodyContainer.appendChild(tr);
    tr = document.createElement("tr");
  }

  var cell = document.createElement("td");
  // добавляем только что созданый элемент в дерево DOM
  cell.classList.add(Onecell == 0 ? "dead" : "live");
  tr.appendChild(cell);
  counter++;

});

A: Для начала, стоит определиться с исходными данными. Сейчас это плоский массив, поэтому не ясно где происходит деление на строки.
Если его предварительно обработать и получить двумерный массив, то вложенные массивы будут непосредственно строками и сразу станет понятно какие данные отображаются на какую строку.
Например, для текущего массива можно получить следующий двумерный
[
    [0, 1, 1, 0],
    [1, 0, 1, 0],
    [1, 0, 1, 1],
    [0, 1, 1, 1],
    [0, 1]
];

Получить такой вид можно используя функцию reduce
var maxCountInRow = 4;
var processedCells = cells.reduce(function(acc,el,index){
    var rowIndex = Math.floor(index/maxCountInRow);
    acc[rowIndex] = acc[rowIndex] || [];
    acc[rowIndex].push(el);
    return acc;
}, []);

Теперь данный массив легко спроецировать на список строк с ячейками
processedCells.reduce(function(tbody, cells){
    tbody.appendChild(// добавляем создаваемую строку
        cells.reduce(function(tr, el){ // создаем ячейки
            var td = document.createElement('td');
            td.classList.add(el==0?'dead':'live');
            tr.appendChild(td);
            return tr;
        }, document.createElement('tr')/*создаем строку*/);
    );
    return tbody;
}, tbodyContainer);

Если все собрать, получится следующее:

var cell = [0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1];
var tableContainer = document.querySelector("table");
var tbodyContainer = tableContainer.querySelector("tbody");

var maxCountInRow = 4;
var processedCells = cell.reduce(function(acc, el, index) {
  var rowIndex = Math.floor(index / maxCountInRow);
  acc[rowIndex] = acc[rowIndex] || [];
  acc[rowIndex].push(el);
  return acc;
}, []);

processedCells.reduce(function(tbody, cells) {
  tbody.appendChild( // добавляем создаваемую строку
    cells.reduce(function(tr, el) { // создаем ячейки
      var td = document.createElement('td');
      td.classList.add(el == 0 ? 'dead' : 'live');
      tr.appendChild(td);
      return tr;
    }, document.createElement('tr') /*создаем строку*/ )
  );
  return tbody;
}, tbodyContainer);
td {
  width: 20px;
  height: 20px;
  background-color: green;
}
.dead {
  background-color: red;
}
.live {
  background-color: green;
}

Как можно заметить, подряд выполняются две свертки над одними данными, и их можно объединить:

var cell = [0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1];
var tableContainer = document.querySelector("table");
var tbodyContainer = tableContainer.querySelector("tbody");

var maxCountInRow = 4;
cell.reduce(function(tbody, cell, index) {
  if (index % maxCountInRow == 0) {
    var tr = document.createElement('tr');
    tbody.appendChild(tr);
  } else {
    var tr = tbody.querySelector('tr:last-child');
  }
  var td = document.createElement('td');
  td.classList.add(cell == 0 ? 'dead' : 'live');
  tr.appendChild(td);
  return tbody;
}, tbodyContainer);
td {
  width: 20px;
  height: 20px;
  background-color: green;
}
.dead {
  background-color: red;
}
.live {
  background-color: green;
}


text:
Q: Node.js crashing when client sends invalid packet I'm making a multiplayer game with node.js but it crashes when client sends invalid packet.
Server:
msg.readFloatLE(1, true);

Client:
msg.setUint8(1, 1);

So, if server is waiting for a float but client sends an int, it crashes with this error:

C:\Program Files\nodejs\node.exe: src\node_buffer.cc:752: Assertion
  `(offset + sizeof(T)) <= (ts_obj_length)' failed.

I'm using ws library but i'm pretty sure that it's about node.js. How can i fix this?

A: You can handle exception using try catch
try {
  msg.readFloatLE(1, true);
}
catch(e) {
  console.log(e,"error)
}

A: As @Ved pointed in his answer - try/catch would be the best approach.
Just to suggest something not standard:
const defaultCriticalValue = 0.0;
const floatNum = parseFloat('a') || defaultCriticalValue;
msg.readFloatLE(floatNum, true);

A: If you take a look at the node documentation for readFloatLE it clearly says it throws exception for your example.
// Throws an exception: RangeError: Index out of range
console.log(buf.readFloatLE(1));

You can take a look at documentation here
The question is what exactly do you try to accomplish? and is readFloatLE right tool for that?


text:
Q: No module named _core when using mailer.py on Windows/Python 2.7 I'm trying to configure and run SVN post-commit hook sending mails. I've downloaded class mailer.py, installed Python 2.7 and svn-win32 bindings for svn. The machine is Windows-7 64 bit, the Python is 32 bit. Now the mailer.py ends with error, which is caused by import problem.
When I in python console type "import svn.core" I have following error:
>>> import svn.core
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\tools\Python27\lib\site-packages\svn\core.py", line 19, in <module>
    from libsvn.core import *
  File "c:\tools\Python27\lib\site-packages\libsvn\core.py", line 5, in <module>
    import _core
ImportError: No module named _core

while in directory site-packages/libsvn are files such as: _core.dll
I've installed other bindings, pysvn, that was installed correctly, but as far as I've noticed, it's the totally other API so I can't use that for python.py
Does someone had similar problem and knows how to deal with it?

A: The Python bindings need to load the native Subversion libraries (DLL's).  If your Python is 32-bit then you would need 32-bit versions of the native Subversion libraries on PATH.

A: I have problem like this. Trouble was that python just can not import this library (svn.core and other).
I just make:
 import sys
 sys.path.append("C:\csvn\lib\svn-python").
My file core.pyc was in C:\csvn\lib\svn-python\svn. Hope it helps somebody. Such behacior for me is strange because there is no "init.py" or "init.pyc" file in svn-python directory. But it works.


text:
Q: Outputting same name as input using Copy Features in ModelBuilder? I am using ModelBuilder to iterate Closest Facility analysis for every building at an archaeological site (OD Cost Matrix is not what I need--I need the geometry output, not just a cost matrix table). My draft model is below. One question: at the end of the model, it takes the routes generated from the Closest Facility analysis and copies it to a new feature class. However, the Copy Features tool seems to require a specific name for the output. When I iterate to the next facility, it will either overwrite or break the model.
So the question is simple: how do I configure Copy Features tool to output the name from the corresponding iteration (taken form the ObjectID field from the Iterate Feature Selection)?

A: In line variable substitution is what your looking for. You can use the 'Value' output from the iterate feature selection to uniquely label the output. In the Output Feature class in the Copy Features, use the %Value% to assign a different name for each iteration.
For example, set the output to [your output location]\%Value%'
See ESRI's help page for more info on how this works. Example 2 is what you want


text:
Q: How to delete a row without using OnRowDeleted/OnRowDeleting in gridview Code Behind
public void lbDelete_Click(object sender, EventArgs e)
{
    LinkButton lb = sender as LinkButton;
    GridViewRow gvrow = lb.NamingContainer as GridViewRow;
    gvsize.DeleteRow(gvrow.RowIndex);
}

GridView:
<asp:GridView ID="gvsize" runat="server" ShowFooter="True" CellPadding="1" CellSpacing="2" AutoGenerateColumns="false" GridLines="Horizontal">
    <asp:TemplateField HeaderText="Action">
       <ItemTemplate>
          <asp:LinkButton ID="lnkdelete" runat="server" ForeColor="Blue" OnClick="lbDelete_Click">Delete</asp:LinkButton>
       </ItemTemplate>
    </asp:TemplateField>
</asp:GridView >

There are 2 rows in my gridview which I need to delete the row using the function above.
It throws an error "gvsize" RowDeletingEvent was not handled properly.
Is that necessary to use OnRowDeleted/OnRowDeleting in gridview which I feel not necessary??

A: As stated in How to delete row from gridview?

You are deleting the row from the gridview but you are then going and
  calling databind again which is just refreshing the gridview to the
  same state that the original datasource is in.
Either remove it from the datasource and then databind, or databind
  and remove it from the gridview without redatabinding.

You can use row databound event to accomplish this task.
  <asp:LinkButton ID="lnkBtnDel" runat="server" CommandName="DeleteRow" OnClientClick="return confirm('Are you sure you want to Delete this Record?');"">Delete</asp:LinkButton>

and in the rowdatabound event you can have
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "DeleteRow")
    {
        //incase you need the row index
        int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
        //followed by your code
    }
}

A: Try this to delete row
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
dt.Rows.RemoveAt(e.RowIndex);
GridView1.DataSource = dt;
GridView1.DataBind();
 }

You can also delete row from another method using Template Column
ASPX
<asp:TemplateField HeaderText="Delete">
                                <ItemTemplate>
                                <asp:ImageButton ID="imgDelete" runat="server" CommandName="deletenotice" ImageUrl="~/images/delete1.gif" alt="Delete"
                                    OnClientClick="return confirm('Are you sure want to delete the current record ?')">
                                    </asp:ImageButton>

                                </ItemTemplate>
                            </asp:TemplateField>

C# Code
 protected void gvNoticeBoardDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
if (e.CommandName.ToLower().Equals("deletenotice"))
                {

                    GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
                    NoticeBoard notice = new NoticeBoard();
                    HiddenField lblCust = (HiddenField)row.FindControl("hdngvMessageId");//Fetch the CourierId from the selected record

                    auditTrail.Action = DBAction.Delete;
                    Service simplyHRClient = new Service();
                    MessageClass messageClass = simplyHRClient.SaveNoticeBoard(notice, auditTrail);
                    if (messageClass.IsSuccess)
                    {

                        this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
                        showSummary.Style["display"] = string.Empty;
                        showSummary.Attributes["class"] = "success-message";

                        if (messageClass.RecordId != -1)
                            lblCust.Value = messageClass.RecordId.ToString();

                    }
                    else
                    {
                        this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
                        showSummary.Style["display"] = string.Empty;
                        showSummary.Attributes["class"] = "fail-message";
                    }
                    //Bind Again grid
                    GetAllNoticeBoard();
                    }
             }

Hope it helps you


text:
Q: VM Player Ubuntu upgrade from 12.04 to 16.04 failed - entering into emergency mode I'm upgrading Ubuntu from 12.04 to 16.04 in VM Ware Player version 5.0.4.
When using Ubuntu 12.04, i increased Hard disk size from 150GB to 300GB manually in VM player by mistake.(VM ware located in D:/ drive, which is 232GB in size).
However, I couldn't see 300GB replicated in Ubuntu(was not knowing that i should use Gparted to increase partition from 150GB to 300GB).
After installation Ubuntu is entering into Emergency mode as shown:
Emergency mode
Someone, please point out where am i going wrong?
1). I cannot install successfully because hard disk wrong increment to 300GB out of 232GB?
2). If I remove old 12.04 files and install 16.04, is it still possible to access data from 12.04's DSU.vmdk file?
3). Is it possible to reduce 300GB to 150GB using Gparted in VMWare player?
(150GB is still unallocated)

A: If I get you correctly your trying to upgrade Ubuntu from 12.04 to 16.04 in a virtual machine. I don't think that's possible in a Virtual device, only real installs can get upgraded. You have to store those files using a folder in you host system, then install the new version using a newly downloaded Ubuntu 16.04.


text:
Q: Adding an OverflowError side effect with patch - Python I'd like to mock an OverflowError because I'd like to test the value of a variable is after that exception is raised. However, I do not know how to replicate an OverflowError with the libraries I am using. Libraries I am using in this specific test is pysolar.solar specifically the get_altitude, get_azimuth and radiation methods
After mindlessly trying out different numbers to try to simulate an OverflowError I decided to try out Mocking the function and introducing a side effect.
Code I am testing sunposition.py
import numpy as np
import pandas as pd
from pysolar.solar import get_altitude, get_azimuth, radiation as radiation_module

def sun_position(lat: float, lon: float, time: pd.Timestamp = None) -> List[float]:

    if time is None:
    time = pd.Timestamp.now(tz='UTC')

    dt = time.to_pydatetime()

    altitude = get_altitude(lat, lon, dt)
    azimuth = get_azimuth(lat, lon, dt)

    try:
        radiation = radiation_module.get_radiation_direct(dt, altitude)
    except OverflowError:
        radiation = np.nan

    return pd.Series([altitude, azimuth, radiation], index=['Alt', 'Azi', 'Rad'])

**What I started to do with patch **
"""Test sunposition module"""
import unittest
import numpy as np
import pandas as pd
from unittest.mock import MagicMock, patch, Mock

from bigfolder.sun import sunposition

class TestSunposition(unittest.TestCase):
"""Test functions in sunposition."""

def test_sun_position_overflow_error(self):

    error_lat = 23
    error_lon = 12
    error_time = pd.Timestamp('2007-02-18 15:13:05', tz="UTC")

    mock_args = {'side_effect': OverflowError}
    with patch('bigfolder.sun.sunposition.sun_position', **mock_args):
        # run the test

        self.assertRaises(OverflowError,  sunposition.sun_position(lat=error_lat, lon=error_lon, time=error_time))

if __name__ == '__main__':
    unittest.main()

I was expecting it to give me and OverFlow error... and it did, however my assertion failed anyways with an OverflowError My guess is that I patched at the wrong place? I don't really understand why the test failed regardless when the error was still an OverFlow Error
This is what was printed out
_mock_self = <MagicMock name='sun_position' id='102333856'>, args = ()
kwargs = {'lat': 23, 'lon': 12, 'time': Timestamp('2007-02-18 15:13:05+0000', tz='UTC')}
self = <MagicMock name='sun_position' id='102333856'>, _new_name = ''
_new_parent = None
_call = call(lat=23, lon=12, time=Timestamp('2007-02-18 15:13:05+0000', tz='UTC'))
seen = set(), skip_next_dot = False, do_method_calls = False
name = 'sun_position'

    def _mock_call(_mock_self, *args, **kwargs):
        self = _mock_self
        self.called = True
        self.call_count += 1
        _new_name = self._mock_new_name
        _new_parent = self._mock_new_parent

        _call = _Call((args, kwargs), two=True)
        self.call_args = _call
        self.call_args_list.append(_call)
        self.mock_calls.append(_Call(('', args, kwargs)))

        seen = set()
        skip_next_dot = _new_name == '()'
        do_method_calls = self._mock_parent is not None
        name = self._mock_name
        while _new_parent is not None:
            this_mock_call = _Call((_new_name, args, kwargs))
            if _new_parent._mock_new_name:
                dot = '.'
                if skip_next_dot:
                    dot = ''

                skip_next_dot = False
                if _new_parent._mock_new_name == '()':
                    skip_next_dot = True

                _new_name = _new_parent._mock_new_name + dot + _new_name

            if do_method_calls:
                if _new_name == name:
                    this_method_call = this_mock_call
                else:
                    this_method_call = _Call((name, args, kwargs))
                _new_parent.method_calls.append(this_method_call)

                do_method_calls = _new_parent._mock_parent is not None
                if do_method_calls:
                    name = _new_parent._mock_name + '.' + name

            _new_parent.mock_calls.append(this_mock_call)
            _new_parent = _new_parent._mock_new_parent

            # use ids here so as not to call __hash__ on the mocks
            _new_parent_id = id(_new_parent)
            if _new_parent_id in seen:
                break
            seen.add(_new_parent_id)

        ret_val = DEFAULT
        effect = self.side_effect
        if effect is not None:
            if _is_exception(effect):
>               raise effect
E               OverflowError

So then I thought I must have patched in the wrong place and introduced the side effect earlier than I should have? So I instead patched the method int the try block. This was my following code.
def test_sun_position_overflow_error(self):

    error_lat = 23
    error_lon = 12
    error_time = pd.Timestamp('2007-02-18 15:13:05', tz="UTC")

    mock_args = {'side_effect': OverflowError}
    with patch('bigfolder.sun.sunposition.sun_position.radiation_module.get_radiation_direct', **mock_args):
    # run the test

    self.assertRaises(OverflowError,  sunposition.sun_position(lat=error_lat, lon=error_lon, time=error_time))

And now my error is " ModuleNotFoundError: No module named 'bigfolder.sun.sunposition.sun_position'; 'bigfolder.sun.sunposition' is not a package"
I then just changed the path to 'sun_position.radiation_module.get_radiation_direct' but there's no module found.
So my questions are: How to replicate an OverflowError so that then I can check the value of a variable I set once that Exception is raised. Why is the first OverflowError I introduce still not pass my assertion?
Thanks
UPDATE TEST passes
After following @Gang 's suggestion, the OverFlowError was reproduced. I realized that in order to test the block for the exception, specifically that radiation was then np.nan I had to patch the method that I wanted to have the OverFlowError and not the whole method of sun_position. When I tried doing that I imported it incorrectly, as I thought the external library was part of the code. So I changed bigfolder.sun.sunposition.sun_position.radiation_module.get_radiation_direct to pysolar.solar.radiation.get_radiation_direct which is the external library that has the get_radiation_direct method I wanted to mock.
def test_sun_position_overflow_error(self):
    lat = 23
    lon = 12
    time = pd.Timestamp('2007-02-18 15:13:05', tz="UTC")

    # get_radiation_direct will now produce an OverFlowError(regardless of coordinates)
    mock_args = {'side_effect': OverflowError}
    # mock get_radiation_direct and produce OverFlowError
    with patch('pysolar.solar.radiation.get_radiation_direct', **mock_args):
        # Check radiation column is nan value
        assert math.isnan(sunposition.sun_position(lat=lat, lon=lon, time=time)[2])

A:
Why is the first OverflowError I introduce still not pass my assertion?

Almost there. The right way to assertRaises:
def test_sun_position_overflow_error(self):
    # This has to be here first and without func call
    with self.assertRaises(OverflowError):
        # patch the function to have an exception no matter what
        mock_args = {'side_effect': OverflowError}
        with patch('bigfolder.sun.sunposition.sun_position', **mock_args):
            # call this func to trigger an exception
            sunposition.sun_position(lat=error_lat, lon=error_lon, time=error_time)

After review the document, it is how to call a func inside assertRaises

assertRaises(exception, callable, *args, **kwds)
fun(*args, **kwds) raises exc

This usage is wrong:
self.assertRaises(OverflowError,  sunposition.sun_position(lat=error_lat, lon=error_lon, time=error_time))

It should be a func name with kwargs:
self.assertRaises(OverflowError,  sunposition.sun_position, lat=error_lat, lon=error_lon, time=error_time)


text:
Q: function inside functions in coffeescript How do I write this in coffee script?
function setUpDialogForms() {
    setUpListForm();
    setUpUpdateForm();
}

I have tried
setUpDialogForms -> setUpListForm(); setUpUpdateForm()

A: Provided the setUpListForm and setUpUpdateForm functions are defined somewhere, you can use:
setUpDialogForms = ->
  setUpListForm()
  setUpUpdateForm()

setUpDialogForms()

A: Found it out.
setUpDialogForms = () ->
    setUpListForm()
    setUpUpdateForm()
    return

Which returns
var setUpDialogForms;

setUpDialogForms = function() {
  setUpListForm();
  setUpUpdateForm();
};


text:
Q: Reverse current drain source on MOSFET triggering in LTspice I want to unterstand the process of firing a MOSFET und used an LTspice simulation to see the current flowing into gate capacitance und the resulting drain-source current. For this I used a simplified circuit in LTspice with two voltage sources, one permanent source of 10 V and one single-pulse voltage source for the gate.
I do not understand the simulation result as it shows a negative drain-source current in the first short time interval after pulling the gate to 2.5 V. Notice that I used such a low gate voltage for the MOSFET IRLH5036 to research switching behaviour on low voltage gate inputs e.g. from logic sources.
Here is the waveform. Notice that I multiplied I(R4) with factor 10 to make the effect more visible. The blue waveform drops to -84mA (-8.4 mA without factor mupltiplication) in the beginng. Ig(M1) presents the gate current on triggering at 100ms. I'm well aware that these MOSFETs have an internal reverse diode, but there should be no negative voltage bias over the MOSFET.

Attached here also the used circuit:

Any idea why this is occuring? Do you have literature hints?

A:
I do not understand the simulation result as it shows a negative
Drain-Source current in the first short time interval after pulling
the gate on 2.5 V.

It actually shows a negative drain current (the drain-source current is a meaningless quantity). This drain current will be somewhat mirrored by a positive source current that may be several times bigger (dependent on the MOSFET type).
The current you see is the injection of charge, from the gate into both drain and source pins. This will be seen as a short pulse of negative current in the drain. The charge injection is due to inter-electrode capacitances. These are well-known phenomena in MOSFETs.

Image from here.

A: I suspect that current flowing into the gate to charge its capacitance, current which has to exit somewhere (by KCL), is leaving via both source (downwards) and drain (upwards), momentarily, as the gate charges.
At some point (probably before the gate has fully charged) the channel becomes conductive enough for current due to V2 to begin to rise, and net drain current crosses zero.
Eventually the gate is charged, all current flowing in the channel is purely due to the EMF of V2 (downwards into the drain), and this "anomaly" is over.


text:
Q: Determine the greatest interval where the function is invertible The assingment is to determine the greatest interval around $x=0$ where the function:
$$f(x)=x^5-5x+3$$
is invertible. After that, determine $(f^{-1})'(3)$
I have totally forgotten all about invertible functions, how do I do it and when is it not possible?

A: The function $f$ has the following properties:

*

*$\lim_{x\to-\infty}f(x)=-\infty$

*$\lim_{x\to\infty}f(x)=\infty$

*$f'(x)=5x^4-5=5(x-1)(x+1)(x^2+1)$

Thus $f$ has a relative maximum at $-1$, with $f(-1)=7$ and a relative minimum at $1$, with $f(1)=-1$.

 Then $f$ is invertible in $[-1,1]$ and no largest interval around $0$, because in a larger interval around $0$ it will not be monotonic.Thus $f^{-1}$ is defined on $[-1,7]$ and, by the inverse function theorem,$\displaystyle(f^{-1})'(3)=\frac{1}{f'(a)}$where $a\in[-1,1]$ is the unique point such that $f(a)=3$. The equation is then $a^5-5a+3=3$ or $a=0$. Thus$$(f^{-1})'(3)=\frac{1}{f'(0)}=-\frac{1}{5}.$$

A: Hint: The function has a local maximum and a local minimum near 0. Find those. That will give you the requested interval.

A: If a continuous function is invertible, then it is monotonic. Since you're dealing with a differentiable function, this is equivalent to finding the greatest interval around 0 where the sign of $f'$ does not change.
Find the zeros of $f'$, splice $\mathbb{R}$ into intervals with these, and you should have your solution.


text:
Q: What are these tools in Word? Grid in ruler and pins Can somebody tell what are these tools? I watched a video about ruler but that grid wasn't covered.
Pin
Grid

A: Gridlines can help you align objects on a page. Their value is primarily for objects that you want text wrapping around them, and again, you want the objects all aligned evenly. Below is an example.

Gridlines will not print nor will they transfer to a PDF version of the document.


text:
Q: Unexpected element while unmarshalling I have to pull information from a webservice. Here's an example of a response:
<myServices>
<myService name="A" serviceId="a" type="rest" version="1.0">
<entryPoints/>
</myService>
<myService name="B" serviceId="b" type="rest" version="1.0">
<entryPoints/>
</myService>
<myService name="C" serviceId="C" type="rest" version="1">
<entryPoints>
<entryPoint realm="external" wadl="http://myURL.com/1/app.wadl>http://myURL.com/1</entryPoint>
</entryPoints>
</myService>
<myService name="D" serviceId="d" type="rest" version="1.0">
<entryPoints/>
</myService>
</myServices>

Here's my xsd:
<?xml version="1.0" encoding="windows-1252" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns="http://www.nisoars.myservices.1.com"
            targetNamespace="http://www.nisoars.myservices.1.com"
            elementFormDefault="qualified">

    <xsd:element name="myServices">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="myService" type="ServiceType" minOccurs="1" maxOccurs="unbounded"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>

    <xsd:complexType name="ServiceType">
        <xsd:sequence>
            <xsd:element name="entryPoints">
                <xsd:complexType>
                    <xsd:sequence>
                        <xsd:element name="entryPoint" type="EntryPointType" minOccurs="1" maxOccurs="unbounded"/>
                    </xsd:sequence>
                </xsd:complexType>
            </xsd:element>
        </xsd:sequence>
        <xsd:attribute name="name" type="xsd:string" use="required"/>
        <xsd:attribute name="serviceId" type="xsd:string" use="required"/>
        <xsd:attribute name="type" type="ServiceTypeEnum" use="required"/>
        <xsd:attribute name="version" type="xsd:string" use="required"/>
    </xsd:complexType>

    <!-- <entryPoint wadl="myWadl" realm="external">myURL</entryPoint> -->
    <xsd:complexType name="EntryPointType">
        <xsd:simpleContent>
            <xsd:extension base="xsd:anyURI">
                <xsd:attribute name="realm" type="RealmEnum" use="required"/>
                <xsd:attribute name="wadl" use="optional" type="xsd:anyURI"/> <!-- Required for REST endpoints, but not for SOAP -->
            </xsd:extension>
        </xsd:simpleContent>
    </xsd:complexType>

    <xsd:simpleType name="RealmEnum">
        <xsd:restriction base="xsd:string">
            <xsd:enumeration value="internal"/>
            <xsd:enumeration value="external"/>
        </xsd:restriction>
    </xsd:simpleType>

    <xsd:simpleType name="ServiceTypeEnum">
        <xsd:restriction base="xsd:string">
            <xsd:enumeration value="rest"/>
            <xsd:enumeration value="soap"/>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:schema>

The error I'm getting is this one:
unexpected element (uri:"", local:"myServices"). Expected elements are <{http://www.nisoars.myservices.1.com}myServices>
I can't remove the namespace from the xsd because I need it for other objects. I'm using the javax.bind.xml.Unmarshaller.
Any ideas?

A: Apply a Namespace
In the case where the input XML does not have a namespace you can leverage a SAX XMLFilter to apply a namespace.
import org.xml.sax.*;
import org.xml.sax.helpers.XMLFilterImpl;

public class NamespaceFilter extends XMLFilterImpl {

    private static final String NAMESPACE = "http://www.nisoars.myservices.1.com/";

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        super.endElement(NAMESPACE, localName, qName);
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes atts) throws SAXException {
        super.startElement(NAMESPACE, localName, qName, atts);
    }

}

Do the Unmarshal
The unmarshalling is done leveraging JAXB's UnmarshallerHandler as the ContentHandler
import javax.xml.bind.*;
import javax.xml.parsers.*;
import org.xml.sax.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Create the JAXBContext
        JAXBContext jc = JAXBContext.newInstance(Customer.class);

        // Create the XMLFilter
        XMLFilter filter = new NamespaceFilter();

        // Set the parent XMLReader on the XMLFilter
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        filter.setParent(xr);

        // Set UnmarshallerHandler as ContentHandler on XMLFilter
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        UnmarshallerHandler unmarshallerHandler = unmarshaller
                .getUnmarshallerHandler();
        filter.setContentHandler(unmarshallerHandler);

        // Parse the XML
        InputSource xml = new InputSource("input.xml");
        filter.parse(xml);
        Customer customer = (Customer) unmarshallerHandler.getResult();

        // Marshal the Customer object back to XML
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(customer, System.out);
    }

}

For More Information

*

*http://blog.bdoughan.com/2012/11/applying-namespace-during-jaxb-unmarshal.html


text:
Q: Plotly-Generate JSON in R, save and reuse in html/javascript It there a simple example of how to:

*

*Export the plotly json file from an R plotly plot

*Save this file

*Reuse this file to generate a plot in a webpage using the plotly.js library

I have generated the a json file for a plot (p1):
json<-plotly_json(p1,FALSE)
write(json,'test.json')

But I have been unable to generate the plot in a simple html/java script test. I have been able to generate plots in html/javascipt, just not from a json file saved from R. This seems simple but I am new to html and clearly am missing something obvious.

A: I think I finally have what the OP and I was looking for.
The below function outputs two files.

*

*Javascript file containing everything you need from Plotly

*Optional HTML file with appropriate code to draw the plot.

rm(list = ls())

library(tidyverse)
library(stringi)
library(plotly)

plotly_to_js <- function(

  plotly.object
  , div.id = 'plot1'
  , output.html = FALSE
  , output.file = NULL
  , output.dir = NULL
  , output.url = NULL

){

  if(is.null(output.file)){
    output.file <- div.id %s+% '.js'
  }

  if(is.null(output.dir)){
    js.filename <- getwd() %s+% '/' %s+% output.file
  }else{
    js.filename <- output.dir %s+% '/' %s+% output.file
  }

  if(is.null(output.url)){
    output.url <- div.id %s+% '.html'
  }

  json <- plotly_json(plotly.object,FALSE)

  js.output <-
    "(function(){ \n
        window.PLOTLYENV={'BASE_URL': 'https://plotly.com'}; \n
        \n
        var gd = document.getElementById('%div.id%') \n
        var resizeDebounce = null; \n

        function resizePlot() { \n
          var bb = gd.getBoundingClientRect(); \n
          Plotly.relayout(gd, { \n
            width: bb.width, \n
              height: bb.height \n
            }); \n
          } \n

          Plotly.plot(gd,  \n
              %json%
           \n
                  ); \n
           }()); \n
  "

  js.output <- gsub('%div.id%', div.id, js.output)
  js.output <- gsub('%json%', json, js.output)

  fileConn<-file(js.filename)
    writeLines(js.output, fileConn)
  close(fileConn)

  if(output.html){

    output.html <-
      " \n
         \n
            <meta charset=\"utf-8\"/> \n
         \n

         \n
        \n
           \n
        \n

 \n
         \n

        \n
        \n"

    output.html <- gsub('%div.id%', div.id, output.html)
    output.html <- gsub('%js.filename%', js.filename, output.html)

    fileConn <- file(output.url)
      writeLines(output.html, fileConn)
    close(fileConn)

  }

}

x <- c(1:100)
random_y <- rnorm(100, mean = 0)
data <- data.frame(x, random_y)

fig <- plot_ly(data, x = ~x, y = ~random_y, type = 'scatter', mode = 'lines')

plotly_to_js (
  fig
  , output.html = TRUE
)


text:
Q: Sorry, but we can't start this add-in because it isn't set up properly - Word Web Add-in I am trying to deploy my Word web add-in using the Sideloading technique. I created the add-in using Visual Studio 2019, but i'd like to run the add-in using this method instead of running it through VS.
When I upload the manifest file there are no error messages. However, when I click 'show taskpane' the add-in fails with:
Add-In Error: Sorry, but we can't start this add-in because it isn't set up properly.
I followed the sideloading method by changing the source location DefaultValue to:
<SourceLocation DefaultValue="https://wordwebaddin1web20190612034303.azurewebsites.net/Home.html" />
I am able to navigate to the URL using a web browser, and the page loads successfully.
The Whole Manifest file looks like:
<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp
          xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0"
          xmlns:ov="http://schemas.microsoft.com/office/taskpaneappversionoverrides"
          xsi:type="TaskPaneApp">

  <Id>0c420d45-c2da-4d36-aac4-eabc0a30844c</Id>

  <Version>1.0.0.0</Version>
  <ProviderName>Harry Levick</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>

  <DisplayName DefaultValue="My Office Add-In" />
  <Description DefaultValue="A task pane add-in for Word"/>

  <IconUrl DefaultValue="~remoteAppUrl/Images/Button32x32.png" />

  <SupportUrl DefaultValue="http://www.contoso.com" />

  <AppDomains>
    <AppDomain>AppDomain1</AppDomain>
    <AppDomain>AppDomain2</AppDomain>
    <AppDomain>AppDomain3</AppDomain>
  </AppDomains>

  <Hosts>
    <Host Name="Document" />
  </Hosts>
  <DefaultSettings>
    <SourceLocation DefaultValue="https://wordwebaddin1web20190612034303.azurewebsites.net/Home.html" />
  </DefaultSettings>

  <Permissions>WriteDocument</Permissions>

  <VersionOverrides xmlns="http://schemas.microsoft.com/office/taskpaneappversionoverrides" xsi:type="VersionOverridesV1_0">

    <Hosts>
      <Host xsi:type="Document">
        <DesktopFormFactor>
          <GetStarted>
            <Title resid="Contoso.GetStarted.Title"/>

            <Description resid="Contoso.GetStarted.Description"/>

            <LearnMoreUrl resid="Contoso.GetStarted.LearnMoreUrl"/>
          </GetStarted>
          <FunctionFile resid="Contoso.DesktopFunctionFile.Url" />

          <ExtensionPoint xsi:type="PrimaryCommandSurface">

            <OfficeTab id="TabHome">
              <Group id="Contoso.Group1">
                <Label resid="Contoso.Group1Label" />
                <Icon>
                  <bt:Image size="16" resid="Contoso.tpicon_16x16" />
                  <bt:Image size="32" resid="Contoso.tpicon_32x32" />
                  <bt:Image size="80" resid="Contoso.tpicon_80x80" />
                </Icon>

                <Control xsi:type="Button" id="Contoso.TaskpaneButton">
                  <Label resid="Contoso.TaskpaneButton.Label" />
                  <Supertip>

                    <Title resid="Contoso.TaskpaneButton.Label" />

                    <Description resid="Contoso.TaskpaneButton.Tooltip" />
                  </Supertip>
                  <Icon>
                    <bt:Image size="16" resid="Contoso.tpicon_16x16" />
                    <bt:Image size="32" resid="Contoso.tpicon_32x32" />
                    <bt:Image size="80" resid="Contoso.tpicon_80x80" />
                  </Icon>

                  <Action xsi:type="ShowTaskpane">
                    <TaskpaneId>ButtonId1</TaskpaneId>
                    <SourceLocation resid="Contoso.Taskpane.Url" />
                  </Action>
                </Control>
              </Group>
            </OfficeTab>
          </ExtensionPoint>
        </DesktopFormFactor>
      </Host>
    </Hosts>

    <Resources>
      <bt:Images>
        <bt:Image id="Contoso.tpicon_16x16" DefaultValue="~remoteAppUrl/Images/Button16x16.png" />
        <bt:Image id="Contoso.tpicon_32x32" DefaultValue="~remoteAppUrl/Images/Button32x32.png" />
        <bt:Image id="Contoso.tpicon_80x80" DefaultValue="~remoteAppUrl/Images/Button80x80.png" />
      </bt:Images>
      <bt:Urls>
        <bt:Url id="Contoso.DesktopFunctionFile.Url" DefaultValue="~remoteAppUrl/Functions/FunctionFile.html" />
        <bt:Url id="Contoso.Taskpane.Url" DefaultValue="~remoteAppUrl/Home.html" />
        <bt:Url id="Contoso.GetStarted.LearnMoreUrl" DefaultValue="https://go.microsoft.com/fwlink/?LinkId=276812" />
      </bt:Urls>
      <bt:ShortStrings>
        <bt:String id="Contoso.TaskpaneButton.Label" DefaultValue="Show Taskpane" />
        <bt:String id="Contoso.Group1Label" DefaultValue="Commands Group" />
        <bt:String id="Contoso.GetStarted.Title" DefaultValue="Get started with your sample add-in!" />
      </bt:ShortStrings>
      <bt:LongStrings>
        <bt:String id="Contoso.TaskpaneButton.Tooltip" DefaultValue="Click to Show a Taskpane" />
        <bt:String id="Contoso.GetStarted.Description" DefaultValue="Your sample add-in loaded succesfully. Go to the HOME tab and click the 'Show Taskpane' button to get started." />
      </bt:LongStrings>
    </Resources>
  </VersionOverrides>

</OfficeApp>

A: Also for a more general purpose solution, there's a validator for this, it comes with the office-toolbox which also allows for sideloading.
https://github.com/OfficeDev/office-toolbox
> office-toolbox validate -m manifest.xml

Calling validation service. This might take a moment...
-------------------------------------
Validation: Failed

Error #1:
Malformed Manifest Icon URL: The manifest icon URL must be well formed.
Please see https://aka.ms/oackicon for details. (link: https://aka.ms/oackicon)
-------------------------------------


text:
Q: Looping around to front of map I have a map with timeslots as a key, pointing to the assigned client. Not all timeslots have an assigned client, and it could be both a sparse and dense population, so I stuck with a map<int, int> implementation. A key exists only if an assignation exists.
A counter counts from slot 1 to slot x,  and at each slot I check for the assignation.
e.g.
map<int, int> slot_info;

while (1)
{
    for (int i = 1; i =< 500; i++) //iterates through slots - 500 here as an example
    {
        map<int /*slot*/, int/*node*/>::iterator it = slot_info.find(i);

        if (it != slot_info.end())
        {
            int node = it->second;

            //find the next slot that is assigned to node
        }
    }
}

I need to do the following

*

*At slot X, check if there exists and assignation -> if yes, get node Y that was assigned

*Search map for the next slot after X that references Y.

Part 2 is the part I am unsure about - if Y is referenced at slot 480 (out of 500), and the next slot that references Y is slot 20 (I am running through the slot numbers in an infinite loop), then how do I get it to return 20?
My understanding of the map .begin() and '.end()` is that it is literal - i.e. it will not return 20 to me in this case as it would have reached the end.

A: Hold a reference to the place you originally found i.
If you get to the end of the map and you haven't found what you're looking for, go back to .start().

A: Why don't you just have another for loop inside?
PS:You are having while(1) but where is the break condition to come out?
 map<int, int> slot_info;

 while (1)
 {
  for (int i = 1; i =< 500; i++)
  {
    map<int, int>::iterator it = slot_info.find(i);

    if (it != slot_info.end())
    {
        int node = it->second;

        //find the next slot that is assigned to node
        for(map<int, int>::iterator it2 =++it;it2!=slot_info.end();it2++)
          if(it2->second==node)
          {
           //This is the next slot which refers to the same client
          }
    }
  }
 }

A: I'm not entirely clear what the for(i in 0..500) is for, but if that's what you need to do:
#include <map>
#include <iostream>
#include <algorithm>

using std::map;

int main(int argc, const char** argv)
{
    map<int /*time*/, int /*client*/> slot_info;

    slot_info[123] = 1;
    slot_info[125] = 2;
    slot_info[480] = 3;
    slot_info[481] = 1;
    slot_info[482] = 3;

    for (int timeKey = 0; timeKey <= 500; ++timeKey) {
        auto it = slot_info.find(timeKey);
        if (it != slot_info.end()) {

            auto nextIt = ++it;
            nextIt = std::find_if(nextIt, slot_info.end(), [=] (const std::pair<int, int>& rhs) { return rhs.second == it->second; });
            if (nextIt != slot_info.end()) {
                std::cout << "found " << it->second << " with " << it->first << " and " << nextIt->first << std::endl;
            }
        }
    }
}

But it also seems more likely that you would probably want to just iterate across the map in the first place checking each value.
The second part of your question "My understanding of the map .begin() and '.end()` is that it is literal - i.e. it will not return 20 to me in this case as it would have reached the end."
"begin()" and "end()" are absolutes, irrespective of any current iterators you might have.
#include <map>
#include <iostream>
#include <algorithm>

using std::map;

std::ostream& operator<<(std::ostream& os, const std::pair<int, int>& item) {
    std::cout << "[" << item.first << "," << item.second << "]";
    return os;
}

int main(int argc, const char** argv)
{
    map<int /*time*/, int /*client*/> slot_info;

    slot_info[123] = 1;
    slot_info[125] = 2;
    slot_info[480] = 3;
    slot_info[481] = 1;
    slot_info[482] = 3;

    for (auto it = slot_info.begin(); it != slot_info.end(); ++it)
    {
        std::cout << "*it = " << *it << ", but *begin = " << *(slot_info.begin()) << std::endl;
    }

    return 0;
}

So the other option you have is a - rather costly
for (int timeKey = 0; timeKey <= 500; ++timeKey) {
    auto firstIt = slot_info.find(i); // find a slot for this time.
    if (firstIt == slot_info.end())
        continue;
    auto secondIt = std::find(slot_info.begin(), slot_info.end(), [=](const std::pair<int, int>& rhs) { return firstIt->second == rhs.second && firstIt->first != rhs.first; });
    if ( secondIt != slot_info.end() ) {
        // we found a match
    }
}

A: // wrapper that performs a `find_if()` on two ranges, returning
//  an iterator to the first match found.
//
//  If no match is found, `last_2` is returned
template <typename InputIterator, typename Predicate>
InputIterator find_if_in_ranges(
                    InputIterator first_1, InputIterator last_1,
                    InputIterator first_2, InputIterator last_2,
                    Predicate pred)
{
    InputIterator ret = std::find_if( first_1, last_1, pred);

    if (ret == last_1) {
        ret = std::find_if( first_2, last_2, pred);
    }

    return ret;
}

Call the above with two ranges:

*

*it + 1 and slot_info.end()

*slot_info.begin() and it
and pass in a predicate which compares the second member of the pair a map<> iterator refers to.  You can use a functor or function pointer as the predicate if you're using C++03, or use a lambda if you're using C++11.


text:
Q: Como passar mensagem da exceção para uma página HTML a partir de uma JSP? Eu tenho um exercício da faculdade no qual tenho que criar uma pagina .jsp que recebe como parâmetro um "id" e roda uma query para deletar o registro dentro da classe produtos com esse id e caso de alguma exceção que eu mande o usuário para pagina erro.html passando como parâmetro o texto do erro.
O código que fiz até agora foi esse:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import="web.acesso.bd.*,web.acesso.bd.dao.*"%>
<html>
<head><title>Insert title here</title></head>
<body>
<%
int myId=request.getParameter("id")
try{
    bd.execComando ("DELETE FROM Filme id="+myId+");
}
catch(Exception e)
{
   response.sendRedirect("erro.html");
}%>
</body>
</html>

Até aqui acho que está certo, mas eu não sei passar como parâmetro a mensagem da exceção que está na variável "e".
Alguém poderia ajudar?

A: Talvez algo assim resolva:
<%
   int myId=request.getParameter( "id" );

   try{
      bd.execComando ( "DELETE FROM Filme WHERE id=" + myId );
   }
   catch( Exception e )
   {
      response.sendRedirect( "erro.html?excecao=" + URLEncoder.encode( e, "ISO-8859-1" ) );
   }
%>

O URLencoder vai servir para converter espaços e caracteres especiais sa mensagem em algo que possa ser transmitido justamente por URL, bastando você acertar a conversão para o que necessitar. Pus ISO-8859-1 por ser o mesmo que você usou na primeira linha do código original.
Isto é claro, supondo que intenção seja de a página de erro processar o parâmetro excecao para exibir para o usuário final.


text:
Q: Open a window browser from a vaadin table I'm developìng an app in Vaadin and I've found a problem.
I would like to open a new browser window from the action handler added to a vaadin table, and I don't know how to do that. Is that possible?.
table.addActionHandler(new Handler() {

    public void handleAction(Action action, Object sender, Object target) {
        if (action == ACTION_OPEN_WINDOW) {
            // code to open a new browser window
            BrowserWindowOpener opener = new BrowserWindowOpener....
            /// is it possible open oit here?
        }
    }

    public Action[] getActions(Object target, Object sender) {
        return ACTIONS;
    }

});

A: you still can run JavaScript:
JavaScript.getCurrent().execute("window.open('http://google.com', 'Google', 'height=800,width=600');");


text:
Q: What application launchers are available for Ubuntu? What are some alternative launchers that can be used to launch programs in Ubuntu's default Unity desktop?

A: Here are some more ways to launch and organize applications:
GnomeDO
sudo apt-get install gnome-do gnome-do-plugins

Duck Launcher
sudo add-apt-repository ppa:the-duck/launcher
sudo apt-get update
sudo apt-get install duck-launcher

Launcher Folders:
sudo add-apt-repository ppa:asukhovatkin/unity-launcher-folders
sudo apt-get update
sudo apt-get install unity-launcher-folders

Slingscold Launcher
sudo add-apt-repository ppa:noobslab/apps
sudo apt-get update
sudo apt-get install slingscold

A: You also have dockbarx. You can install it with:
sudo add-apt-repository ppa:dockbar-main/ppa
sudo apt-get update
sudo apt-get install dockbarx

More info here.

A: My personal favorite is the Classic Menu Indicator

In addition to other answers, me and @JacobVlijm  have tried to script launchers as an answer to  Launch app only if not already open question

A: Gnome-Do works with the keyboard as Unity. Press Super + Space and then you type the name of the program you want to run. Don't know about the project status and haven't used it since 2009. Hope this can help.

A: Consider Synapse:

Just start typing the program, file or directory you're looking for.
Installation:
sudo apt install synapse

A: One that I use and like is Albert.
It's very similar to OS X's Spotlight Search, especially in how it looks, but I've found it to be invaluable if you're a keyboard-heavy power user.

You have to install it via a PPA (not in the official repos yet):
sudo apt-add-repository ppa:flexiondotorg/albert
sudo apt-get update
sudo apt-get install albert

On the first launch you will have to set the hotkey to launch Albert, but that's fairly easy:

I've set it to Ctrl-Space.

A: Docky is a great app, you can install it with:
sudo apt-get install docky

GNOME Pie is another great one that can be installed with:
sudo apt-get install gnome-pie

(Launch with CTRL + ALT + A - this hot key is customizable.)

Cairo-Dock is also good, and can be installed with:
sudo apt-get install cairo-dock

Plank is another good one that can be installed with:
sudo apt-get install plank

A: lxqt-runner is an option:

Installation: sudo apt install lxqt-runner

A: Cairo Dock has launchers too.
To install it click below
Cairo Dock
I use Compiz with Cairo dock so I use it in fall back mode. It adds a session for cairo only environment if you don't want to use Unity

A: My recent favorite: the very very lightweight dmenu
Installation:
sudo apt install dmenu

Improve that tool with dmenu-extended to be able to find files and directories from dmenu, too. Very useful.
sudo apt install suckless-tools xfonts-terminus
git clone git@github.com:MarkHedleyJones/dmenu-extended.git
cd dmenu-extended
sudo python setup.py install


text:
Q: IPC shared memory vs posix shared memory I am currently implementing a small C function that uses posix shared memory (shm_open(), ftruncate(), mmap() and shm_unlink().
The problem I am facing is that normaly my application exists gracefully and my cleanup routine calls shm_unlink().
But if my process got kill -9 I am facing the issue that the shm segment is still there. My application uses fork() and can even be started in several instances. So, if during startup I detect there is a shared memory segment, how can I decide if it is a leftover from a crash, so I can reset it or some other process may be still using it?
In SystemV IPC shared memory set of function, once I do a shmget() and a subsequent shmat() I have shm_nattch.
Is there something similar with posix shared memory?

A: POSIX shared memory is actually a variation of mapped memory. The major differences are to use shm_open() to open the shared memory object (instead of calling open()) and use shm_unlink() to close and delete the object (instead of calling close() which does not remove the object). The options in shm_open() are substantially fewer than the number of options provided in open().
IPC Shared Memory is an efficeint means of passing data between programs. One program will create a memory portion which other processes (if permitted) can access.
IMHO, the difference between them is not huge or even large since POSIX shared memory is just latter and more standard implementation of shared memory concept. The kill -9 problem is really problem. You cannot setup any handler and even atexit is not called. But you can set handler for SIGTERM and terminate your process with command:
kill -SIGTERM <pid>

Sample code for atexit and signal handler:
#include <signal.h>
#include <unistd.h>
#include <cerrno>
#include <system_error>
#include <iostream>

static sigset_t theMask;

static void
signalWrapper(
    int         theSignalNumber,
    siginfo_t*  theSignalDescription,
    void*       theUserContext)
{
  if (theSignalNumber == SIGTERM)
  {
    std::cerr << "Clear shared memory and exit" << std::endl;
    exit(1);
  }

  // Reinstall handler (usefull for other signals)
  struct ::sigaction sa;
  sa.sa_sigaction = &signalWrapper;
  sa.sa_mask = theMask;
  sa.sa_flags = SA_SIGINFO;

  try
  {
    if (::sigaction(theSignalNumber, &sa, NULL) == -1)
      throw std::error_code(errno, std::system_category());
  }
  catch (const std::error_code& ec)
  {
    std::cerr << ec << std::endl;
  }
}

void
setupSignalHandlers()
{
  struct ::sigaction sa;

  // Prepare mask
  sigemptyset(&theMask);
  sigaddset(&theMask, SIGTERM);
  // Add some more if you need it to process

  sa.sa_mask      = theMask;
  sa.sa_flags     = SA_SIGINFO;
  sa.sa_sigaction = &signalWrapper;

  // Perform setup
  try
  {
    if (::sigaction(SIGTERM, &sa, NULL) == -1)
      throw std::error_code(errno, std::system_category());
  }
  catch (const std::error_code& ec)
  {
    std::cerr << ec << std::endl;
  }
}

void
bye()
{
  std::cout << "Bye!" << std::endl;
}

int
main()
{
  std::cout << "Set handler!" << std::endl;
  setupSignalHandlers();
  if (std::atexit(bye))
  {
    std::cerr << "Failed to register atexit" << std::endl;
    return 2;
  }

  std::cout << "Emit SIGTERM signals" << std::endl;
  kill(getpid(), SIGTERM);
  sleep(100);

  return 0;
}

Another interesting approach is shm_unlink() right after shm_open() and use of O_CLOEXEC. I wrote small code sample to illustrate use of unlink and POSIX shared memory reopen:
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <cerrno>
#include <cstring>

#include <system_error>
#include <iostream>

// Simple ShMem with RAII
struct ShMem
{
  ShMem(
    const std::string& theName)
  : _handle(-1),
    _mode(S_IRUSR | S_IWUSR),
    _name(theName)
  {
    // Here we try to create the object with exclusive right to it
    // If the object exists - it must fail.
    // File opened as 0600. The open mode might be set with
    // class enum and additional paramter to constructor
    if ((_handle = shm_open(_name.c_str(), O_CREAT | O_RDWR | O_EXCL, _mode)) < 0)
    {
      std::cerr << strerror(errno) << std::endl;

      std::cout << "File " << _name << "exists. Try to reopen it!" << std::endl;
      if ((_handle = shm_open(_name.c_str(), O_RDWR | O_TRUNC, _mode)) < 0)
      {
        std::cerr << strerror(errno) << std::endl;
        throw std::error_code(errno, std::system_category());
      }
      else
        std::cout << _name << " reopened OK";
    }
    else
      std::cout << _name << " created OK";

    // Unlink but keep descriptor
    shm_unlink(_name.c_str());
  }

 ~ShMem()
  {
  }

  const int
  handle()
  {
    return _handle;
  }

private:

  int         _handle;
  mode_t      _mode;
  std::string _name;
};

With O_CLOEXEC you can remove shm_unlink() at all and see what happens on kill -9 .


text:
Q: The command i tried implementing won't work for some reason. Is there anyway to fix this? (discord.py) I asked for some help to create a command script in which the discord bot would reply to the command with a sentence and randomized percentile.
This is the script given to me in question:
import discord
from discord.ext import commands
import random
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=".", intents=intents, help_command=None)
@bot.command()
async def strenght(ctx):
    await ctx.send(f"Your strength is at {random.choice(range(1, 100))} %")
bot.run("")

I already had different parts of the script written, so i just tried my best to implement all the lines into my main script:
import discord
from discord.ext import commands
import responses
import random

async def send_message(message, user_message):
    try:
        response = responses.get_response(user_message)
        await message.channel.send(response)

    except Exception as e:
        print(e)

def run_discord_bot():
    TOKEN = 'i removed my token'
    intents =  discord.Intents.all()
    bot = commands.Bot(command_prefix=".", intents=intents, help_command=None)
    intents.message_content = True
    client = discord.Client(intents=intents)

    @client.event
    async def on_ready():
        print(f'{client.user} is now running!')

    @client.event
    async def on_message(message):
        if message.author == client.user:
            return

        username = str(message.author)
        user_message = str(message.content)
        channel = str(message.channel)

        print(f'{username} said: "{user_message}" ({channel})')

        if user_message[0] == '?':
            user_message = user_message[1:]
            await send_message(message, user_message)
        else:
            await send_message(message, user_message)

    @bot.command()
    async def strength(ctx):
        await ctx.send(f"Your strength is at {random.choice(range(1,100))} %")
        bot.run("")

    client.run(TOKEN)

The terminal would then give me successful prints, as in the bot successfully logs in, connects to the gateway, goes online, and even receives the command itself. The problem being that even though it "receives" it, it gives me an error to the lines of " 400 Bad Request (error code: 50006): Cannot send an empty message "
Full Terminal for perspective:
2023-02-24 23:11:13 INFO     discord.client logging in using static token
2023-02-24 23:11:15 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 4ed57f0b5b4bf87f1a7a1535a6182a52).
hirojiro#3698 is now running!
hirojiro#1357 said: ".strength" (dank-memer)
400 Bad Request (error code: 50006): Cannot send an empty message

I've already asked on Python dedicated forums, yet to get an answer. But i hope to be able to find out what i can change so that the response isn't an "empty message". I'm also open to change my line distribution in my main script if necessary. I want the strength command to work. Thanks a lot!

A: The problem is that the on_message event is "catching" the message, preventing the command from working. See this post for more on that.
Then, the responses.get_response(user_message) is returning an empty string, which rises the error you are seeing in your console.


text:
Q: How to sort HashMap entries in alphabetic order? I have made a program which will read in text from the user, and then display the letter frequencies of the user's text. I am experimenting with hashmaps and I am not sure how to display my results in alphabetical order.
I currently have:
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < user.length(); i++) {
  Integer count = map.get(user.charAt(i)); // if not in map
  if (count == null)
    map.put(user.charAt(i), 1);
  else
    map.put(user.charAt(i), count + 1);
}

As my code for storing the values, but when I print the result
System.out.println(map.entrySet());
I get [a=1, r=2, h=1, y=1]. (For printing "Harry")

A: What you're looking for is a collection that would implement the SortedMap interface. Try using TreeMap, which guarantees the natural ordering of its keys.
This question describes differences between various implementations of Map: Difference between HashMap, LinkedHashMap and TreeMap

A: Use TreeMap instead of HashMap.


text:
Q: How to replace an array of characters in a column of text in PostgreSQL? I have 2 text columns where I need to replace (on update) chars from array 1 ('q','x','y','z') to their index-equivalent value in array 2 ('a','b','c','d').
The closest I've come to atm is to nest the replace calls within each other like so
UPDATE
    mytable
SET
    col1=replace(
            replace(
                replace(
                    replace(
                        col1,'q','a'
                    ),'x','b'
                ),'y','c'
            ),'z','d'
        ),
    col2=replace(
            replace(
                replace(
                    replace(
                        col2,'q','a'
                    ),'x','b'
                ),'y','c'
            ),'z','d'
        )

but surely there must be a better way to do this? In my live case I have 14 of those char pairs. If it has any relevance - the chars are a mix of japanese hieroglyphs and accented letters from Swedish alphabet.

A: PostgreSQL have special function for this, translate():
update mytable set
    col1 = translate(col1, 'qxyz', 'abcd'),
    col2 = translate(col2, 'qxyz', 'abcd')

sql fiddle example


text:
Q: How can I build a 32bit (i386) .deb on a 64bit box? I have applications which successfully compile with the -m32 switch (in DMD and/or GCC) to produce:
appname: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked
(uses shared libs), for GNU/Linux 2.6.15, not stripped

The source packages I have created work fine, on both 32 bit and 64 bit Ubuntu to build the appropriate binary .debs.
I would like to produce the i386 .deb on the same 64 bit machine i use to produce the 64 bit .deb.
Is this possible, and where should I look for instructions?

A: It starts with calling debuild with the -ai386 option, which will
change the architecture that the package is built for.
Of course you have to ensure that the package contains the i386 build of the application.

A: The answer depends on the complexity of your build. When the normal 64 bit userland tools suffice for a build, simply specify the architecture via -a
debuild -ai386

However, there are often cases where this doesn't work, and in these cases you'll need pbuilder. pbuilder builds a clean Debian/Ubuntu system in a chroot-ed environment. man pbuilder is a good introduction. To get started, you'll need:
sudo pbuilder --create --architecture i386
sudo pbuilder --build mypackage.dsc

A: You don't do anything thing different from building a 64bit .deb. Except that you include a 32bit build of your application.
The control file specifies the architecture, so be sure you select the correct one.


text:
Q: How to add IMethodInterceptor Listener to the testng suite programmatically without using  tag in xml file I have implemented IMethodInterceptor listener in my framework to apply test groups at run time from Jenkins. I had to use <listener> tag in all my testing xmls to include this listener. It will be a huge task for me. I want to assign it via JAVA itself.
I tried this:
iTestContext.getSuite().addListener(new MethodInterceptorListener());
iTestContext.getSuite().addListener(new InvokedMethodListener());

This is working for InvokedMethodListener but not for MethodInterceptorListener.

*

*Any idea how can I make it work?

*Why this addListener() method which is working for InvokedMethodListener is not working for MethodInterceptorListener?

A: iTestContext.getSuite().addListener(new MethodInterceptorListener());

This does not work because listener of type IMethodInterceptor (as well as few other types) is not handled in ISuite.addListener(). Whereas you could add a listener to TestRunner which is the implementation of ITestContext.
You could try the below code and it would work.
if(iTestContext instanceof TestRunner) {
    ((TestRunner) iTestContext).addListener(new MethodInterceptorListener());
}

If you are using java 16 do:
if(iTestContext instanceof TestRunner t) {
    t.addListener(new MethodInterceptorListener());
}


text:
Q: Rewrite rule: change a portion of text in URL to another I want to change the url of my wordpress, I have read that I can make that with rewrite rule but it does not work me unfortunately. Here are the details:
I have a wordpress theme, which got me that kind of URL:
www.my-theme.pl/portfolio_category/red-flower/
www.my-theme.pl/portfolio_category/blue-flower/
www.my-theme.pl/portfolio_category/black-trees/
www.my-theme.pl/portfolio_category/white-roses/

I want to rewrite the URL via .htaccess to receive:
www.my-theme.pl/gardens/red-flower/
As you see, I just want to replace /portfolio_category/ with /gardens/ text in the URL since after that are different post names but the /portfolio_category/ always stays the same.
I entered this rule:
RewriteRule ^/portfolio_category/$ /gardens/$ [NC]

And it does not work unfortunately. Can you clarify how to use properly ?
Below is my entire .htaccess code:
Options -Indexes
AuthType Basic
AuthName "password"
AuthUserFile /home/*******************/.htpasswd
Require valid-user

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^/portfolio_category/$ /gardens/$ [NC]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

</IfModule>
# END WordPress

The ******* are replaced with working path to my htpasswd.
It is my first time to make any rewrite changes and I am not familiar with it. I think I have read the tutorials correctly but the change still does not work.
Best regards from Poland,
Jacek

A: If I understand correctly what you want, your rewrite rule is reversed and you are not including the following directory. Try:
RewriteRule ^/gardens/(.*)$ /portfolio_category/$1 [NC]

This changes /gardens/ to /portfolio_category/. The (.*)$ collects everything to the end of the URL, then the $1 adds it at the end of the new one.

A: Thank you mr bodye, I think my problem is solved and I simply need to code the change into my theme to get different URL by the theme engine so the URL is proper from the start without need of the rewrite.


text:
Q: bulk update by Stored procedures of complex type cosmosDB azure I try to update bulk of complex documents in cosomosdb via stored procedures in server side.
My client side is developed in C#.
I want to implement stored procedure, that update the details of course to list of students, I want to update the course details for all students that belong to list of ids with given courseDetiels

*

*How I create query that return all the document with id that contain in the ids parameter.

2.How I can update complex-object for example:
   public class CourseDetiels : Microsoft.Azure.Documents.Resource
{
    [JsonProperty("name")]
    public String CName { get; set; }

    [JsonProperty("finalGrade")]
    public double FinalGrade{ get; set; }
    [JsonProperty("GradesInWorks")]
    public double[] GradesInWorks{ get; set; }

}
I need to update the only the courses that taken by the user in specific semester in Courses dictionary in Student class:
    public class Student: Microsoft.Azure.Documents.Resource
{
    [JsonProperty(PropertyName = "id")]
    public String ID { get; set; }
    [JsonProperty(PropertyName = "Courses")]
    public Dictionary<string, CourseDetiels> Courses{ get; set; }

}

This is the pseudo code I want to write....
function UpdateCourses(ids,courseDetiels) {

   var collection = getContext().getCollection();
   var collectionLink = collection.getSelfLink();
   var response = getContext().getResponse();
   var docCount = 0;
   var counter = 0;

   UpdateCoursesByIds(ids,complexObject);

   function UpdateCoursesByIds(ids,complexObject,continuation) {
        var query = {
            query: "select * from root c where ...." **//how to select only documents that contains in ids??**
        };

        var requestOptions = {
            continuation: continuation
        };

        var isAccepted =
            collection
            .queryDocuments(collectionLink,
                            query,
                            requestOptions,
                            function queryCallback(err, documents, responseOptions) {
                                     if (err) throw err;
                                     if (documents.length > 0) {
                                        // If at least one document is found, update it.
                                        docCount = documents.length;
                                        for (var i=0; i<docCount; i++){
                                            UpdateDoc(documents[i]);
                                        }
                                        response.setBody("Updated " + docCount + " documents");
                                      }
                                      else if (responseOptions.continuation) {
                                        UpdateCoursesByIds(responseOptions.continuation);
                                      } else {
                                             throw new Error("Document not found.");
                                             }
                            });

        if (!isAccepted) {
            throw new Error("The stored procedure timed out");
        }
    }

    function UpdateDoc(document) {
        //Optimistic concurrency control via HTTP ETag.
        var requestOptions = { etag: document._etag };

        **//I NEED TO UPDATE ONLY THE COURSES THAT TAKEN ....**

        var isAccepted = collection
                         .replaceDocument(document._self,
                                          document,
                                          requestOptions,
                                          function replaceCallback(err, updatedDocument, responseOptions) {
                                                   if (err) throw err;
                                                   counter++;
                                           });

        // If we hit execution bounds - throw an exception.
        if (!isAccepted) {
            throw new Error("The stored procedure timed out");
        }
    }
}

Thanks.

A:
1.How I create query that return all the document with id that contain in the ids parameter.

You could use IN operator in Azure Cosmos SQL APIs as below :

SELECT *
      FROM c
      WHERE c.id in ("1","2",....,"10")

var idsArrString="";
for(var i = 0;i<ids.length;i++){
   idsArrString+="'"+ids[i]+"',";
}

idsArrString=idsArrString.substr(0,idsArrString.length-1);

var query = {
   query: "select * from root c where c.id in ("+ idsArrString + ")";
};

2.How I can update complex-object

According to your need , I created a stored procedure as below :
    function sample(idsArrayString,courses) {
        var collection = getContext().getCollection();

        // Query documents as you want
        var isAccepted = collection.queryDocuments(
            collection.getSelfLink(),
// 1:Please replace the ("1","2") with your idsArrayString

            'SELECT * FROM root r where r.id in ("1","2")',
            function (err, feed, options) {
                if (err) throw err;
                if (!feed || !feed.length) getContext().getResponse().setBody('no docs found');
                else {
                    for(var i = 0;i<feed.length;i++){
                        var doc = feed[i];
// 2:Please replace "maths" with your courses obj
                        doc.course = "maths";
                        collection.replaceDocument(doc._self,doc,                           function(err) {
                                 if (err) throw err;
                     });
                    }
                    getContext().getResponse().setBody(JSON.stringify("success"));
                }
            });

        if (!isAccepted) throw new Error('The query was not accepted by the server.');
    }

Note that two comments in the code replace them with your own arguments.
Then you could execute Stored Procedure in your C# code:
// execute the stored procedure
client.executeStoredProcedureAsync('dbs/testdb/colls/testColl/sprocs/<your stored procedure id>')
    .then(function (response) {
        console.log(response.result);
    }, function (err) {
        console.log("Error", error);
    });

More details , please refer to this official tutorial.
Hope it helps you.

Update Answer :
You could update your courseDetails in doc as below with the above comment 2 :
doc.courseDetails.finalGrade = "50";

Please refer to the sample code as below which mentioned in the document I provided
client.executeStoredProcedureAsync('dbs/testdb/colls/testColl/sprocs/createMyDocument',
              <your arguments>);

Update Answer 2:
I created sample document as you offered.
{
    "id": "4",
    "StudenName": "Jay",
    "Courses": {
        "Math": {
            "Grade": "A",
            "Place": "NYU"
        },
        "Phys": {
            "Grade": "B",
            "Place": "MIT"
        }
    },
    "Rank": "AA"
}

Then I modify the comment 2 in above stored procedure javascript code to replace the Grade with "C".
for(var i = 0;i<feed.length;i++){
                    var doc = feed[i];
                    var cources = doc.Courses;
                    for (var key in cources) {
                        if (cources.hasOwnProperty(key)) {
                            console.log(key + " -> " + cources[key]);
                            cources[key].Grade ="C";
                        }
                    }
                    doc.Courses = cources;
                    collection.replaceDocument(doc._self,doc,
                    function(err) {
                             if (err) throw err;
                 });
                }

Changed document:
{
    "id": "4",
    "StudenName": "Jay",
    "Courses": {
        "Math": {
            "Grade": "C",
            "Place": "NYU"
        },
        "Phys": {
            "Grade": "C",
            "Place": "MIT"
        }
    },
    "Rank": "AA"
}


text:
Q: What's wrong with .flv file? I have .flv file which has a pretty long runtime.
But VLC player indicates runtime as 48 min. (in reality it's more than 2 hours)
The questions: What is the maximum runtime for .flv file?
What causes this error? Why can't it display the actual runtime?

A: FLV is a container format and has no real limit on runtime.
The problem in your case is most likely that the index or the metadata (where duration, codec info, resolution, keyframes etc are stored) has been corrupted.
There are programs that can rebuild or repair the index for you.