text:
Q: python win32com shell.SHFileOperation - any way to get the files that were actually deleted? In the code I maintain I run across:
from win32com.shell import shell, shellcon
# ...
result,nAborted,mapping = shell.SHFileOperation(
        (parent,operation,source,target,flags,None,None))

In Python27\Lib\site-packages\win32comext\shell\ (note win32comext) I just have a shell.pyd binary.

*

*What is the return value of shell.SHFileOperation for a deletion (operation=FO_DELETE in the call above) ? Where is the code for the shell.pyd ?

*Can I get the list of files actually deleted from this return value or do I have to manually check afterwards ?

EDIT: accepted answer answers Q1 - having a look at the source of pywin32-219\com\win32comext\shell\src\shell.cpp I see that static PyObject *PySHFileOperation() delegates to SHFileOperation which does not seem to return any info on which files failed to be deleted - so I guess answer to Q2 is "no".

A: ActiveState Python help contains SHFileOperation description:

shell.SHFileOperation
int, int = SHFileOperation(operation)
Copies, moves, renames, or deletes a file system object.

Parameters
operation : SHFILEOPSTRUCT
Defines the operation to perform.

Return Value
The result is a tuple containing int result of the
  function itself, and the result of the fAnyOperationsAborted member
  after the operation. If Flags contains FOF_WANTMAPPINGHANDLE, returned
  tuple will have a 3rd member containing a sequence of 2-tuples with
  the old and new file names of renamed files. This will only have any
  content if FOF_RENAMEONCOLLISION was specified, and some filename
  conflicts actually occurred.

Source code can be downloaded here: http://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/ (pywin32-219.zip)

Just unpack and go to .\pywin32-219\com\win32comext\shell\src\


text:
Q: MVC 4: Why is "_Layout.cshtml" not rendering on Home View? I'm new to MVC Development and have started a new MVC 4 application to build a sort of Personal Portfolio for practice. I cannot figure out why my _Layout.cshtml is not rendering within my home or default View though. I've already checked the following:

*

*The App_Start/RouteConfig.cs file has not been modified since the
application was created.

*The Views/Shared/_ViewStart.cshtml has
the following (default):
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Views/Shared/_Layout.cshtml:
        <!DOCTYPE html>

            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale = 1.0" />
            <title>Portfolio</title>
            @Styles.Render("~/Content/css")
            @Scripts.Render("~/bundles/jquery")
            @Scripts.Render("~/bundles/bootstrapjs")
            @Scripts.Render("~/bundles/customJs")
            <link href="~/Content/bootstrap.css" rel="stylesheet" />
            <link href="~/Content/bootstrapMod.css" rel="stylesheet" />
            <link href="~/Content/Site.css" rel="stylesheet" />

                    @Html.Partial("_Header")

                            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
                                ☰
                            </button>
                            Portfolio

                           @*@Html.MvcSiteMap().Menu()*@

                    @RenderSection("scripts", required:false)

                        @ViewBag.HeaderTitle

                    @RenderBody()

                Copyright 2014 - Portfolio - Website Terms & Conditions of Use

~/Views/Shared/_Header.cshtml

        @if (Request.IsAuthenticated)
        {

                My Projects
                |
                Contact Profile

                        Hi, @User.Identity.Name
                        @Html.ActionLink("Log Off", "LogOff", "Account", new {},new { @class = "btn btn-primary btn-sm" })

        }
        else
        {

                        <input type="text" id="username" placeholder="E-mail" required tabindex="1"/>

Forgot your username?

                        <input type="password" id="password" placeholder="Password" required tabindex="2" onkeyup="EnterKeyPressed()"/>

Forgot your password?

                        <input type="button" id="loginButton" value="Login" onclick="login()" class="btn btn-primary btn-sm" tabindex="3" onkeyup="EnterKeyPressed()"/>

                        <input type="checkbox" id="rememberMe">Remember Me

        }

My Default View below loads, but with nothing present. The title changes to "Index", and the rest is a blank page. Shouldn't the ~/Views/Shared/_Layout.cshtml be rendering within this page in some manner?
With what I have currently set-up, when the shared _Layout.cshtml loads within my Home/Index/ View, I should see the Header image I have created and sourced on the shared view.
Views/Home/Indx.cshtml
@{
    Layout = null;
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

When I try Layout = "~/Views/Shared/_Layout.chtml"; it errors out saying it could not be found at the designated path. I was semi-working off an example a Developer friend sent me, and with it they are not explicitly setting the Layout?

A: Couple of things...
If you have a view you are trying to render in a shared view then you do not need any of the HTML layout elements contained within the view you are putting it into. Lets start with really basic.
View start
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

_Layout.cshtml
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
        <title>@ViewBag.Title</title>

    @RenderBody()

Home View
@{
    ViewBag.Title = "Index";
}

Index

Now the home view gets plonked into where @RenderBody() appears. So index will be a heading 2 in the page. The title is passed in the ViewBag object and set as the page title in the _Layout.cshtml file with the following @ViewBag.Title

A: Get rid of the following in your Index.cshtml
@{
    Layout = null;
}

This code is telling the rendering engine to use no shared layout. You also won't need any of the HTML pre-amble (HTML, HEAD or BODY tag) in the Index.

A: Remove
@{ Layout = null }

or explicitly set it to "~/Views/Shared/_Layout.cshtml";  This is less preferable though.
It is overriding the _ViewStart behavior.
Also, you will not need to include the  tags in your index.cshtml view because they are included with your _Layout.cshtml.
Essentially what is happening is you are creating a wrapper page with _Layout where you put content that is common across your website (e.g. Header, footer, some navigation).  Then you create a view, in this case index.cshtml, that forms the body of the page.  _Layout.cshtml and Index.cshtml get compiled into a single page, with _Layout.cshtml acting like a wrapper around Index.cshtml.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to put column headers in each group inside dataframe in R? I want to split data frame by group and put headers for each of them.
For example:

c1
c2
c3
group

1
2
3
A

c1
c2
c3
group

1
2
3
B

c1
c2
c3
group

1
2
3
C

Maybe you can do it with the example below:
df <- data.frame(
  "c1" = seq(1,5,1),
  "c2" = seq(1,5,1),
  "c3" = seq(1,5,1),
  "c4" = seq(1,5,1),
  "c5" = seq(1,5,1),
  "group" = c("A","A","B","B","C")
)

This group_split() function may help you.
Thanks in advance.

A: library(tidyverse)

df <- df %>%
  gather("variable", "value", -group)

A: try :
df <- data.frame(
  "c1" = seq(1,5,1),
  "c2" = seq(1,5,1),
  "c3" = seq(1,5,1),
  "c4" = seq(1,5,1),
  "c5" = seq(1,5,1),
  "group" = c("A","A","B","B","C")
) %>% group_by(group)
gl<- group_split(df)

this should create a list gl with as many groups as in df
To name the elements of your gl list, (not sure this is what you mean by adding a header?), do :
names(gl) <- unique(df$group)


text:
Q: Does $\nabla \phi = \nabla\times A$ have non-trivial solutions As stated in the title. Is there a non-trivial solution for $n=\nabla \phi$ and $n=\nabla \times A$. With the information that $|n|=1$
\begin{eqnarray}
\nabla \times A = \nabla \phi
\end{eqnarray}
We can condense it to simpler expressions
\begin{eqnarray}
&\nabla^2 \phi =& \;0\\
\nabla \times(\nabla \times A) =0\Rightarrow  &\nabla^2 A=\;&\nabla (\nabla \cdot A)\\
\nabla\times \nabla^2 A = \nabla^2(\nabla\times A)=&\nabla^2 n =&\;0
\end{eqnarray}
So we have Laplace/Poisson equations. What would be the next step without digging into some representation?

A: Since the given conditions imply that $n$ is both divergence-free and curl-free, you are looking for a harmonic vector field; so in particular $\Delta n = \nabla \cdot \nabla n = 0$ as you deduced. The additional condition $|n|^2 = 1$ is now very powerful: the product rule gives $$\Delta |n|^2 = 2|\nabla n|^2 +2 n \cdot \Delta n = 2|\nabla n|^2,$$ so since we know $|n|^2$ is constant we conclude that $\nabla n = 0$ everywhere; i.e. $n$ is constant.


text:
Q: SQL query to update table columns where input parameters are not Null? I have a table which has the below columns.
Ticket_id (Primary key, Int)
Attachment1 (varchar)
Attachment2 (varchar)
Attachment3 (varchar)
Attachment4 (varchar)
Attachment5 (varchar)

I am writing a stored proc to update this table. there are 6 input parameters for the above 6 columns.
@Attached_File1 VARCHAR(MAX),
@Attached_File2 VARCHAR(MAX),
@Attached_File3 VARCHAR(MAX),
@Attached_File4 VARCHAR(MAX),
@Attached_File5 VARCHAR(MAX),
@Ticket_ID BIGINT

I want to write a sql query which will update the table with the values specified in the input parameters. BUT I must not overrite the attachment columns with null. I mean I need to use only those parameters which contains data.
For example, if the table ha a row [10, "aaa", "bbb", null, null, null] and the input parameters are (10, null, null, "ccc", "ddd", null) then after the update the row will become [10, "aaa", "bbb", "ccc", "ddd", null]
How to check for null/empty strings and generate the update query accordingly to achieve this?

A: You can use ISNULL
UPDATE table_name SET
  Attachment1 = ISNULL(Attachment1, @Attached_File1),
  Attachment2 = ISNULL(Attachment2, @Attached_File2),
  Attachment3 = ISNULL(Attachment3, @Attached_File3),
  Attachment4 = ISNULL(Attachment4, @Attached_File4),
  Attachment5 = ISNULL(Attachment5, @Attached_File5)
WHERE Ticket_id = @Ticket_ID

This solution does not overwrite an existing value with a new. If you want to do that, you should switch the values around:
ISNULL(@Attached_File1, Attachment1)

A: You could try this:
update MY_TABLE set Attached_File1 = ISNULL(@parameter1, Attached_File1);

A: You can simply;
SET
   AttachmentX = ISNULL(AttachmentX, @Attached_FileX)

or if the params can be empty strings
   AttachmentX = ISNULL(AttachmentX, NULLIF(@Attached_FileX, ''))

A: In your UPDATE statement you could use the COALESCE statement, example:
SET Attachment1 = COALESCE(@Attached_File1, Attachment1)

If @Attached_File1 is NULL then the current value of Attachment1 will effectively remain unchanged.


text:
Q: How would i convert this bat file to shell script for linux loading a java program This is the bat file:
@echo off
"I:\Program Files\Java\jdk1.7.0_17\bin\java" -Xmx1300m -cp data/CompiledFiles;deps/poi.jar;deps/mysql.jar;deps/mina.jar;deps/slf4j.jar;deps/slf4j-nop.jar;deps/jython.jar;log4j-1.2.15.jar; server.Server
pause

What would the shell script equivalent be? This bat file loads up a java server program that should be compatible with linux but I am not good with shell script. Thanks for the help.

A: In case you are fine with the default Java interepreter on the system:
#! /bin/sh
java -Xmx1300m -cp data/CompiledFiles;deps/poi.jar;deps/mysql.jar;deps/mina.jar;deps/slf4j.jar;deps/slf4j-nop.jar;deps/jython.jar;log4j-1.2.15.jar; server.Server

Otherwise:
#! /bin/sh
/path/to/executable/java -Xmx1300m -cp data/CompiledFiles;deps/poi.jar;deps/mysql.jar;deps/mina.jar;deps/slf4j.jar;deps/slf4j-nop.jar;deps/jython.jar;log4j-1.2.15.jar; server.Server

A: should be very similar:
#!/bin/sh
java -Xmx1300m -cp data/CompiledFiles;deps/poi.jar;deps/mysql.jar;deps/mina.jar;deps/slf4j.jar;deps/slf4j-nop.jar;deps/jython.jar;log4j-1.2.15.jar; server.Server
read

the pause keeps the window open, I dont know if thats really intended, so maybe remove the 'read'


text:
Q: Split function in HIVE I want to split the address into two columns as streetno and streetname, say for ex
select address1 from customer
address for ex-look like
2719 STONE CREEK DR

and store them into street no as 2719 and streetname as  STONE CREEK DR.
using split(address1 ,'[\ ]')[0] just split the street no only.
it's just select statement we are using to view the data.
Sample data:
address1
100 HORACE GREELEY RD
55 School Street
2893 MASHIE CIR
1200 JEWEL DR
201 W RIVER RD

Expected output
+--------------+---------------------+
| streetnumber |     streetname      |
+--------------+---------------------+
|          100 | HORACE GREELEY RD   |
|           55 | School Street       |
|         2893 | MASHIE CIR          |
|         1200 | JEWEL DR            |
|          201 | W RIVER RD          |
+--------------+---------------------+

A: select  regexp_extract(address1,'(.*?)\\s',1)   as streetnumber
       ,regexp_extract(address1,'\\s(.*)' ,1)   as streetname

from    mytable
;

+----------------+--------------------+
| streetnumber   |     streetname     |
+----------------+--------------------+
| 100            | HORACE GREELEY RD  |
| 55             | School Street      |
| 2893           | MASHIE CIR         |
| 1200           | JEWEL DR           |
| 201            | W RIVER RD         |
+----------------+--------------------+

or
select  regexp_extract(address1,'.*?(?=\\s)',0) as streetnumber
       ,regexp_extract(address1,'(?<=\\s).*',0) as streetname

from    mytable
;

+----------------+--------------------+
| streetnumber   |     streetname     |
+----------------+--------------------+
| 100            | HORACE GREELEY RD  |
| 55             | School Street      |
| 2893           | MASHIE CIR         |
| 1200           | JEWEL DR           |
| 201            | W RIVER RD         |
+----------------+--------------------+

or
select  split(address1,'\\s')[0]      as streetnumber
       ,split(address1,'^.*?\\s')[1]  as streetname

from    mytable
;

+----------------+--------------------+
| streetnumber   |     streetname     |
+----------------+--------------------+
| 100            | HORACE GREELEY RD  |
| 55             | School Street      |
| 2893           | MASHIE CIR         |
| 1200           | JEWEL DR           |
| 201            | W RIVER RD         |
+----------------+--------------------+


text:
Q: Spin-c Structures viewed w.r.t. Cell Decomposition In my quest to understand spin representations, I am looking at the equivalent views of spin structures (on some oriented Riemannian $n$-manifold).  Given such a manifold $M$, its tangent bundle $TM$ is described by gluing cocycles $g_{ab}:U_{ab}\rightarrow SO(n)$.
A spin structure would be some lift of $g_{ab}$ to $U_{ab}\rightarrow Spin(n)$, or in other words, that there is a $Spin(n)$-equivariant lift of the frame bundle $F_{SO}(M)\rightarrow M$ with respect to the double cover $Spin(n)\rightarrow SO(n)$.
A spin-c structure would likewise be a combination of a principal $U(1)$-bundle $F_{U(1)}$ and a $Spin^c(n)$-bundle $F_{spinc}$ (over $M$) with a bundle map $F_{spinc}\rightarrow F_{SO}(M)\times F_{U(1)}$.
Now apparently, assuming our manifold admits some sort of cell decomposition, a spin structure corresponds to a [homotopy class of a] trivialization of $TM\oplus \mathbb{R}^k$ over the 1-skeleton of $M$ which extends over the 2-skeleton.  Here, $k$ is taken to be $0$ for $n\ge 3$, but for $n=1,2$ we stabilize the tangent bundle appropriately.
Is there an analogous description for a spin-c structure?

A: A spin-c structure on a vector bundle $\pi : E \to B$ can be thought of as two things:
(1) A complex line bundle $c : C \to B$
together with
(2) A spin structure on $\pi \oplus c : E \oplus C \to B$.  $\pi \oplus c$ is meant to be the fibrewise direct sum.
This appears in the Gompf reference given in the comments above.  It's also on the Wikipedia page: http://en.wikipedia.org/wiki/Spin_structure
So from an obstruction theory point of view, you can view a complex spin structure on a vector bundle as (1) an element of $H^2(B;\mathbb Z)$ (a cocycle) together with (2) a trivialization of the vector bundle $\pi$ over the 1-skeleton $B^1$ such that the obstruction to extending over the 2-skeleton agrees modulo two with the value of the above cocycle.
(1) is because line bundles over $B$ are given by maps to $K(\mathbb Z, 2)$, i.e. 2-dimensional cohomology classes.
Note, Paul Siegel's comment is explained the the Gompf reference, as well.  I prefer the above formalism, myself.


text:
Q: React Native viro react VR SkyBox is not working I am developing a VR application using ViroReact, https://viromedia.com/viroreact. But I am having problem with using SkyBox (Cubemap) VR scene. Everything is working fine when I used Viro360Image view.
This is my VR scene using Viro360Image view
export default class HotelRoomVRScene extends Component {
    constructor() {
        super();
        this.state = {} // Set initial state here
    }

    render() {
      return (
        <ViroScene>
          <Viro360Image source={require('./res/hotel-room.jpg')} />
        </ViroScene>
      )
    }
}

module.exports = HotelRoomVRScene;

The above scene is working fine. I can view the VR experience in the VR headset as well. But when I changed it to the Skybox version as below. It stopped working.
export default class HotelRoomVRScene extends Component {
    constructor() {
        super();
        this.state = {} // Set initial state here
    }

    render() {
      return (
        <ViroScene>
          <ViroSkybox source={{nx: require('./res/px.jpg'),
                       px: require('./res/px.jpg'),
                       ny: require('./res/px.jpg'),
                       py: require('./res/px.jpg'),
                       nz: require('./res/px.jpg'),
                       pz: require('./res/px.jpg')}} />
        </ViroScene>
      )
    }
}

module.exports = HotelRoomVRScene;

The above code is throwing the following error.

So why is the Skybox version not working?

A: On your render method:
render() {
  return (
    <ViroScene>
      <ViroSkybox source={{nx: require('./res/px.jpg'),
                   px: require('./res/px.jpg'),
                   ny: require('./res/px.jpg'),
                   py: require('./res/px.jpg'),
                   nz: require('./res/px.jpg'),
                   pz: require('./res/px.jpg')}} />
    </ViroScene>
  )
}

you have a typo for the skybox, its  instead of
referring to: https://docs.viromedia.com/docs/viroskybox1
and also you are exporting the same class two times, one in:
export default class HotelRoomVRScene extends Component {

the other one in :
module.exports = HotelRoomVRScene;

I suggest you remove the latter one.


text:
Q: Publishing site and left menu In Sharepoint 2010 I have a publishing site and when ever I create a new page I want the new page to appear as a menu item in the left menu.
Something like this:
Department 1

*

*Page 1

*Page 2
Can I please have some pointers?
Thanks :)

A: This is a default behavior of SharePoint 2010's publish site.
If you can't see the newly created page's link shown at the left panel, you can goto "Site Actions-->Site Settings-->Look and Feel-->Navigation-->Current Navigation" and make sure that you have the option "Show Pages" checked.


text:
Q: nominal value not declared in header, read Token[X], line Y. I keep getting this popup on my Weka @relation WILEligibilityPerFaculty
@attribute YesFPW [Yes-Engineering,Yes-Computing&Informatics,Yes-HumanSciences,Yes-ManagementSciences,Yes-Health&AppliedSciences,Yes-NaturalResources&SpatialSciences]
@attribute NoFPW [No-Engineering,No-Computing&Informatics,No-HumanSciences,No-ManagementSciences,No-Health&AppliedSciences,No-NaturalResources&SpatialSciences]
@data
Yes-Engineering
Yes-Engineering
Yes-Engineering
No-Engineering
No-Engineering
No-Engineering
No-Engineering
Yes-Engineering
Yes-Engineering
No-Computing&Informatics,
No-Engineering

A: If I understand your intent correctly, you actually have one attribute, not two. That attribute is FPW and can have the value of "Yes..." or "No...".
I've rearranged your data below and it loads into Weka correctly.
@relation WILEligibilityPerFaculty

@attribute FPW {Yes-Engineering,Yes-Computing&Informatics,Yes-HumanSciences,Yes-ManagementSciences,Yes-Health&AppliedSciences,Yes-NaturalResources&SpatialSciences,No-Engineering,No-Computing&Informatics,No-HumanSciences,No-ManagementSciences,No-Health&AppliedSciences,No-NaturalResources&SpatialSciences}

@data

Yes-Engineering
Yes-Engineering
Yes-Engineering
No-Engineering
No-Engineering
No-Engineering
No-Engineering
Yes-Engineering
Yes-Engineering
No-Computing&Informatics
No-Engineering

But I may not be interpreting your intent correctly. It's possible that you want to know the department, and Yes/No. In this case, you should separate Department and Yes/No into separate attributes:
@relation WILEligibilityPerFaculty

@attribute Department {Engineering, Computing&Informatics}
@attribute YesNo {Yes, No}
@data

Engineering,   Yes
Engineering,   Yes
Engineering,   Yes
Engineering,   No
Engineering,   No
Engineering,   No
Engineering,   No
Engineering,   Yes
Engineering,   Yes
Computing&Informatics,  No
Engineering,  No


text:
Q: Storing user generated leaflet data to map We are trying to save user generated markers to our leaflet map. We have the marker information (coordinates, name etc) all stored in our database. We know how to call database info and apply it to our page if it is plain text, but not as a marker to a map. Has anybody had experience with this?
sidenote: we are using pug and mongodb.

A: It does not sound any complicated to write inline JavaScript with pug:
How can I render inline JavaScript with Jade?
Docs: https://pugjs.org/language/plain-text.html#block-in-a-tag
Then follow the Leaflet tutorial to write the appropriate JavaScript to create Markers on a Map.

var map = L.map('map').setView([48.86, 2.35], 11);

L.marker([48.86, 2.35]).addTo(map);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '© OpenStreetMap contributors'
}).addTo(map);
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />

You could translate in pug:
doctype html
html(lang="en")
  head
    link(rel='stylesheet', href='https://unpkg.com/leaflet@1.3.1/dist/leaflet.css')
    script(src='https://unpkg.com/leaflet@1.3.1/dist/leaflet-src.js')
    style.
      #map {height: 180px;}
  body
    #map
    script.
      var map = L.map('map').setView([48.86, 2.35], 11);

      L.marker([48.86, 2.35]).addTo(map);

      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
      }).addTo(map);

Interpolation should also work within the script. block (e.g. L.map([#{lat}, #{lng}])), but you might prefer handling arrays / objects, in which case you need unescaped interpolation, with other tools to stringify.
See for example: https://github.com/pugjs/pug/issues/396
!{stringify(variable)}

pug.renderFile('template.pug', {stringify: require('js-stringify')});

(using js-stringify)


text:
Q: Render or update a page while still running inside a method I was wondering if you could render or update a page while you still inside a method;
here is an example:
the .xhtml file:
<h:form id="form">
    <h:commandButton value="change" actionListener="#{bean.changeText}">
        <f:ajax render="out" />
    </h:commandButton>
    <h:outputLabel id="out" value="#{bean.text}" />
</h:form>

and here is the changeText Method:
public void changeText() throws InterruptedException{
    text = "test1";
    FacesContext.getCurrentInstance().renderResponse();
    Thread.sleep(2000);
    text = "test2";
}

Now is it possible to set the output label (id = out) to be rendered (or changed) to "test1", then after the 2 second have elapsed it changes to "test2"?
Well looking at the JSF life cycle i thought it isnt possible, but maybe i got the life cycle wrong, or one of you guys know a work around.

A: No, that's not possible. The render response only starts once the action method returns.
There are basically 2 ways to achieve the desired behavior: polling or pushing. Based on your question history, you're using Java EE 7 + JSF 2.2 + PrimeFaces. You could for pushing use PrimeFaces <p:socket> or homegrow one using Java EE 7's new WebSocket API (JSR-356).


text:
Q: Uncaught (in promise) TypeError: Failed to fetch dynamically imported module I'm trying to fetch SVG images dynamically in my react component, but so far I'm getting this error Uncaught (in promise) TypeError: Failed to fetch dynamically imported module. This is my code sample

import React from 'react';
import { CustomSvgIcon } from '../../util/CustomSvgIcon';

const Icon = ({ iconName }: IconProps) => {
  const [menuIcon, setIcon] = React.useState<string | null>(null);

  React.useEffect(() => {
    if (iconName) {
      import(`../../../assets/svg/${iconName}.svg`)
        .then((bla) => setIcon(bla.default))
        .catch((error) => console.log(error));
    }
  }, []);
  return (
    <CustomSvgIcon>
      {menuIcon ? menuIcon : null}
    </CustomSvgIcon>
  );
};

This code works perfectly in the storybook, but when I use it in the react component it won't load images and that error pops. What am I doing wrong?

A: This issue is solved with setting some rules in webpack.config. It was issue with .svg. This is the rule that solved the issue:
{
      test: /\.svg$/,
      use: [
        {
          loader: '@svgr/webpack',
          options: {
            icon: true,
          },
        },
      ],
    }


text:
Q: Method forwarding with composition instead of inheritance (using C++ traits) I would like to use composition and to write good forwarding methods for every possible overload (noexcept, const, volatile) using C++ capabilities.
The idea is to use traits in order to determine whether a method is declared {noexcept / const / volatile / etc.} and to behave accordingly.
Here is an example of what I would like to achieve :
struct User{
    UsedObject& obj;
    User(UsedObject& obj) : obj(obj) {}

    FORWARD_METHOD(obj, get); //here is where the forwarding happens
};

struct UsedObject{
    string m{"Hello\n"};

    string& get(double d){
        cout << "\tUsed :const not called...\n";
        return m;
    }
    const string& get(double d) const{
        cout << "\tUsed :const called...\n";
        return m;
    }
};

Here is what I have so far** :
// forward with noexcept attribute
// I'm not 100% sure about : std::declval<std::add_lvalue_reference<decltype(obj)>::type

template<typename... Args>
constexpr decltype(auto) get(Args && ... args)
noexcept(
         noexcept(std::declval<std::add_lvalue_reference<decltype(obj)>::type>().get(  std::forward<Args>(args)...  ))
         and
         std::is_nothrow_move_constructible<decltype( std::declval<std::add_lvalue_reference<decltype(obj)>::type>().get(  std::forward<Args>(args)...  ) )>::value
         )
{
    cout << "const called...\n";
    return obj.get(std::forward<Args>(args)...);
}

// forward with noexcept and const attributes
// I'm not sure that this one behave properly.

template<typename... Args>
constexpr decltype(auto) get(Args && ... args)
const noexcept(
         noexcept(std::declval< std::add_const<decltype(obj) &>::type >().get(  std::forward<Args>(args)...  ))
         and
         std::is_nothrow_move_constructible<decltype( std::declval< std::add_const<decltype(obj) &>::type >().get(  std::forward<Args>(args)...  ) )>::value
         )
{
    cout << "const not called...\n";
    using const_type = std::add_lvalue_reference<std::add_const<std::remove_reference<decltype(obj)>::type>::type>::type;
    return const_cast<const_type>(obj).get(std::forward<Args>(args)...);
}

Please note that this question is different from the following one, because I know that we can use c++ traits in order to inspect an object interface : Composition: using traits to avoid forwarding functions?
** inspired by a thread of comments with @David Stone here : When should I use C++ private inheritance?.

A: Let's start with the solution and explain it piece by piece.
#define FORWARDING_MEMBER_FUNCTION(Inner, inner, function, qualifiers) \
    template< \
        typename... Args, \
        typename return_type = decltype(std::declval<Inner qualifiers>().function(std::declval<Args &&>()...)) \
    > \
    constexpr decltype(auto) function(Args && ... args) qualifiers noexcept( \
        noexcept(std::declval<Inner qualifiers>().function(std::forward<Args>(args)...)) and \
        ( \
            std::is_reference<return_type>::value or \
            std::is_nothrow_move_constructible<return_type>::value \
        ) \
    ) { \
        return static_cast<Inner qualifiers>(inner).function(std::forward<Args>(args)...); \
    }

#define FORWARDING_MEMBER_FUNCTIONS_CV(Inner, inner, function, reference) \
    FORWARDING_MEMBER_FUNCTION(Inner, inner, function, reference) \
    FORWARDING_MEMBER_FUNCTION(Inner, inner, function, const reference) \
    FORWARDING_MEMBER_FUNCTION(Inner, inner, function, volatile reference) \
    FORWARDING_MEMBER_FUNCTION(Inner, inner, function, const volatile reference)

#define FORWARDING_MEMBER_FUNCTIONS(Inner, inner, function) \
    FORWARDING_MEMBER_FUNCTIONS_CV(Inner, inner, function, &) \
    FORWARDING_MEMBER_FUNCTIONS_CV(Inner, inner, function, &&)

Inner represents the type of the object you are forwarding to, and inner represents its name. Qualifiers is the combination of const, volatile, &, and && that you need on your member function.
The noexcept specification is surprisingly complicated just because you need to handle the function call as well as constructing the return value. If the function you are forwarding returns a reference, you know it is safe (references are always noexcept constructible from the same type), but if the function returned by value, you need to make sure that object's move constructor is noexcept.
We were able to simplify this a little bit by using a defaulted template argument return_type, otherwise we would have had to spell out that return type twice.
We use the static_cast in the body of the function to handle properly adding cv and reference qualifiers to the contained type. This is not automatically picked up by reference qualifiers on the function.
Using inheritance instead of composition
Using private inheritance, the solution looks more like this:
struct Outer : private Inner {
    using Inner::f;
};

This has the advantage of

*

*Readability

*Faster compile times

*Faster code in debug builds (nothing to inline)

*Not using up your constexpr recursion depth

*Not using up your template instantiation depth

*Working with returning non-movable types by value

*Working with forwarding to constructors


text:
Q: A functional equation $\log f(x,y) = f(\log x, \log y) $ Solve the functional equation
$$\log f(x,y) = f(\log x, \log y) $$
The motivation comes from generalizing the arithmetic and geometric means, but I have no idea how to find a simpler expression for the function $f(x,y)$ with $f(x,y) = f(y,x)$
What I have tried:

*

*$f(ax,y) = e^{f(\log x +\log a, y)}$

*$f(1,x) = e^{f(0,\log x)}$

*$f(x,y) \equiv \infty $ solves the equation, so I am looking for non-trivial solutions.

*Letting
$$f(1+x,1+y) = \sum_{m,n=0}^\infty \frac {a_{m,n}}{x^my^n} = a_{0,0} + \frac {a_{1,1}}{xy} + \frac {a_{2,0}}{x^2}+ \frac {a_{0,2}}{y^2}+\cdots$$
Using the functional equation $f(1+x,1+y) = e^{f(\log (1+x), \log (1+y))}$ we have
$$ a_{0,0} + \frac {a_{2,0}}{x^2}+ \frac {a_{0,2}}{y^2}+\cdots = 1+f\left(x-\dfrac{x^2}2 + \dfrac{x^3}3 - \cdots, y-\dfrac{y^2}2 + \dfrac{y^3}3 - \cdots\right) + \cdots$$
which does not give anything pleasant.

*If I consider a recursive definition $f_{n+1} (x,y) = e^{f_n (\log x, \log y)}$, then modulo convergence issues, $f_n$ converges to $f$. Motivated by AM and GM, I consider $f_0 (a,b) = \frac{a+b}2$. Then $f_1 (a,b) = \operatorname{GM}(a,b)$.

*Test: $f_0 = \dfrac{x+y}2, f_1 = \sqrt {xy}, f_2 = e^{\operatorname{GM}(\log x,\log y)} = \exp\sqrt{(\log x)(\log y)}$, $f_3 = \exp(\exp\sqrt{(\log\log x)(\log\log y)})$. I guess the pattern is
$$\exp(\exp\cdots(\exp\sqrt{(\log\log\cdots \log x)(\log\log\cdots \log y)})$$

*Note that by AM$\geq$ GM, $f_n (x,y) \leq \underbrace{\exp(\exp\cdots(\exp}_n\dfrac{\underbrace{\log\log\cdots \log}_n x+\underbrace{\log\log\cdots \log}_n y}2)$ = $ \underbrace{\exp(\exp\cdots(\exp}_{n-1}\sqrt{(\underbrace{\log\log\cdots \log}_{n-1} \,x)(\underbrace{\log\log\cdots \log}_{n-1}\,y)}) = f_{n-1}(x,y)$.

*I have tested out some explicit values: for $x = 2000, y= 8000$, $f_0 = 6000, f_1 = 4000, f_2 = 3832.6491..., f_3 = 3762.9980...$ by Wolfram Alpha. Some larger $n$'s give complex numbers. If $f_n$ is real, it is a priori apparent that $f_n\geq 0$.

But I have no idea how to go on further.

A: Take any function $g(x,y):A\to \Bbb R$ where $A = \{(x,y) \mid x \le 0 \text{ or } y \le 0\}$.
Now define $f(x,y)$ as follows: $$f(x,y) =
\begin{cases}
g(x,y) &\text{if } (x,y)\in A\\
\exp(f(\log x, \log y))& \text{otherwise}
\end{cases}$$
This function satisfies the equation. Moreover, all solutions of the equation can be constructed this way.


text:
Q: Liferay 7 cannot add or edit page,portlet and sites I installed Liferay on my server, and i get problem of not being able to add, update the site, page, and portlet. Only in View mode.
Just FYI i'm using:

*

*Liferay 7.0 CE GA6

*Linux OS v 3.10.0-693.21.1.el7.x86_64

*Architecture : amd64

*JAVA 1.8.0

The main page of my liferay only displays the Hello World portlet, and the navigation portlet and the configure page displaying message:

This portlet has been undeployed. Please redeploy it or remove it from
  the page.

I have read some literature, saying that my liferay bundle is corrupted.
I already downloaded bundle liferay with wget or drag and drop bundle.zip via FTP. But always get the same result.
Resulting errors in tail -f ../logs/catalina.out :
When starting liferay :
Caused by: java.lang.RuntimeException: org.portletbridge.portlet.GUIDException: error - failure to instantiate GUIDGeneratorjava.net.UnknownHostException: portal: portal: Name or service not known
---
ERROR [localhost-startStop-1][com_liferay_portal_osgi_web_portlet_tracker:97] [com.liferay.portal.osgi.web.portlet.tracker.internal.PortletTracker(22)] The activate method has thrown an exception
java.lang.ExceptionInInitializerError
        at org.portletbridge.portlet.PortletBridgePortlet.createViewPortlet(PortletBridgePortlet.java:219)

When access navigation portlet or the configure page:
ERROR [http-nio-8080-exec-6][BaseJSPPortletConfigurationIcon:59] Unable to include JSP /configuration/icon/copy_applications.jsp
ERROR [localhost-startStop-1][com_liferay_portal_osgi_web_portlet_tracker:97] [com.liferay.portal.osgi.web.portlet.tracker.internal.PortletTracker(22)] The activate method has thrown an exception
Caused by: java.lang.NullPointerException
        at org.apache.jsp.configuration.icon.copy_005fapplications_jsp._jspService(copy_005fapplications_jsp:410)

Does any one know how to fix this?
I mean, Liferay can work normally as usual, as in the myliferay on localhost.
Thank you for your attention.

A: We faced this issue as well recently. Because of an unsatisfied reference, not all of GroupPagesPortlet's services started. In our case, there were an entry in the release_ table which state_ was not 0, it was 1. Value 1 means a failed upgrade.
In our case the workaround/solution was to change the value to 0 then restart the server.
In more details:
1) Connected to Gogo shell
2) Ran scr:list
Found:
  [ 389]   com.liferay.layout.admin.web.internal.portlet.GroupPagesPortlet  enabled
    [2746] [unsatisfied reference]
3) Running scr:info on the component ID (2746 in the above output), it reported the following unsatisfied references:
UnsatisfiedReference: MDRActionLocalService
  Target: null
  (no target services)
UnsatisfiedReference: MDRActionService
  Target: null
  (no target services)
UnsatisfiedReference: MDRRuleGroupInstanceLocalService
  Target: null
  (no target services)
UnsatisfiedReference: MDRRuleGroupInstanceService
  Target: null
  (no target services)

4) Ran dm wtf and it reported that com.liferay.mobile.device.rules.service doesn't have a proper release state, or is at the wrong version:

*

*com.liferay.portal.kernel.model.Release (&(release.bundle.symbolic.name=com.liferay.mobile.device.rules.service)(&(release.schema.version>=1.0.0)(!(release.schema.version>=1.1.0)))(|(!(release.state=*))(release.state=0))) is not found in the service registry

So to summarize, com.liferay.mobile.device.rules.service failed to upgrade, which resulted in all of its transitive dependencies failing to start. GroupPagesPortlet happens to be one of those dependencies.


text:
Q: Using PHP with a MySQL db, how can I select everything from a row if i dont know what the columns are? I have a table but I dont know what the columns are except for 1 column. There is only 1 permanent data value for each row, the rest of the columns are added and removed elsewhere. This isnt a problem for the query, i just do:
SELECT * FROM table

but for the php function bind_result() i need to give it variables for each column, which i do not know.
I think that once I have the columns in an array, I can do anther query and use call_user_func_array to bind the result to the array.
This seems like it would come up a lot so im wondering is there a standard way of doing this?

A: Couldn't you just do:
$result = mysql_query("SELECT * FROM table");

while ($row = mysql_fetch_assoc($result))
{
    foreach ($row as $field => $value)
    {
       ...
    }
}

A: You could do
show columns from table;

And then parse that string to grab your column names.

A: You can also try the describe command, which is used to list all of the fields in a table and the data format of each field. Usage:
describe TableName;

A: you can use
$metadata = $prep_statement->result_metadata()

after you executed the statement and then loop through all result fields using something like
while( $field = $metadata->fetch_field() ) { }

the properties of $field are documented here: http://www.php.net/manual/en/mysqli-result.fetch-field.php


text:
Q: Looking for Fiddler2 help. connection to gateway refused...just got rid of a virus? I use Fiddler2 for facebook game items, and it's been a great success. I accessed a website to download some dat files I needed. I think it was eshare, ziddu or megaupload, one of those. Anyway, even before the rar file had downloaded, I got this weird green shield in the bottom right hand corner of my computer. It said a Trojan was trying to access my computer, or something to that extent. It prompted me to click the shield to begin anti-virus scanning. It turns out this rogue program is called Antivirus System Pro and is pretty hard to get rid of. After discovering the rogue program, I tried using Fiddler and got the following error:
[Fiddler] Connection to Gateway failed.
Exception Text: No connection could be made because the target machine actively refused it 127.0.0.1:5555
I ended up purchasing SpyDoctor + Antivirus, which I'm told is designed specifically for getting rid of these types of programs. Anyway, I did a quick-scan last night with spydoctor and malware bytes. Malware picked up 2 files, and Spydoctor found 4. Most were insignificant, but it did find a worm called Worm.Alcra.F, which was labeled high-priority. I don't know if that's the Anti-Virus Pro or not, but SpyDoctor said it got rid of all of those successfully. I tried to run Fiddler again before leaving home, but was still getting the "gateway failed" error.
Im using the newest version of firefox. When I initially set up the Fiddler 2.2.8.6, I couldn't get it to run at first, so I found this faq on the internet that said I needed to go through Tools>Options>Settings and set up an HTTP Proxy to 127.0.0.1 and my Port to 8888. Once I set that up and downloaded this fiddler helper as a firefox add-on, it worked fine. When I turn on fiddler, it automatically takes my proxy setting from no proxy (default) to the 127.0.0.1 with Port 8888 set up. It worked fine until my computer detected this virus.
Anyway, hopefully I've given you sufficient information to offer me your best advice here. Like I said, Spydoctor says the bad stuff is gone, so maybe the rogue program made some type of change in my fiddler that I could just reset or uncheck or something like that? Or will I need to completely remove fiddler and those dat files and rar files I downloaded? Any help would be greatly appreciated. Thanks for your time.

A: The problem is that the malicious software changed your system proxy settings (which are configured inside IE).

*

*Close Fiddler.

*Open IE. (the factthat you normally use Firefox isn't relevant.)

*Click Tools > Internet Options > Connections > LAN Settings.

*Uncheck everything.

*Click Ok, Ok.

*Reopen Fiddler.


text:
Q: when i send email using PHP mail function then getting in Form header abc@xyz.com via asd.com I am using PHP mail function for send email. But when I send email I get this in Form Header " info@aarthlogistic.com via blue.truehostdns.com ".
This is my code:
$from="info <info@aarthlogistic.com>";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= 'From: ' . $from . "\r\n";
mail('xxxxxp@xxx.com','NoReply', $clent_emailbody,$headers);

How to remove my hosting provider domain (blue.truehostdns.com) from my emails?

A: You should use PHPMailer, it will be much easier to accomplish what you are looking for this way
require('PHPMailer.php');
$mail = new PHPMailer;
    //$mail->SMTPDebug = 3;                               // Enable verbose debug output

    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'user@example.com';                 // SMTP username
    $mail->Password = 'secret';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    $mail->addAddress('ellen@example.com');               // Name is optional
    $mail->addReplyTo('info@example.com', 'Information');
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');

    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
    $mail->isHTML(true);                                  // Set email format to HTML

    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body in bold!';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    if(!$mail->send()) {
        echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }

With this it should look like :
From : Mailer ( from@example.com )
To : Joe User ( joe@example.net ) , ellen@example.com
Object : Here is the subject
------------------------------------------------------
This is the HTML message body in bold!

And if you hit reply, it will automatically reply to the mailer
You can find PHPMailer here : https://github.com/PHPMailer/PHPMailer


text:
Q: How to force docker-compose to use specific port Hey I don't know if the title is right, but I'm working on my project. Tools that I use are symfony and docker. When I start pgsql database on my other machines, they're using port 5432, but I just installed fresh linux on my new computer and it uses port 49153 it took me quiet some time to figure out that the port was the problem. Same thing happens if I start new project don't change anything and pg database still runs on port 49153, it's a bit annoying while working on few machines. So is it possible to force docker to setup database on port 5432 for all of my future projects or everytime I have to change port in .env file?
My docker-compose.yml
services:
  database:
    image: postgres:${POSTGRES_VERSION:-14}-alpine
    environment:
      POSTGRES_DB: ${POSTGRES_DB:-app}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-!ChangeMe!}
      POSTGRES_USER: ${POSTGRES_USER:-app}
    volumes:
      - db-data:/var/lib/postgresql/data:rw

.env file
DATABASE_URL="postgresql://app:!ChangeMe!@127.0.0.1:5432/app?serverVersion=14&charset=utf8"

A: For exemple if you want to map your pgsql database :
From the local docker container port 5432
To your local env 5432 port.
Add
 ports:
    - "5432:5432"

I forgot which one is the container and which one is the local but you will find out pretty easier now.
services:
  database:
    image: postgres:${POSTGRES_VERSION:-14}-alpine
    environment:
      POSTGRES_DB: ${POSTGRES_DB:-app}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-!ChangeMe!}
      POSTGRES_USER: ${POSTGRES_USER:-app}
    volumes:
      - db-data:/var/lib/postgresql/data:rw
    ports:
        - "5432:5432"


text:
Q: How to insert php codes into database? I'm testing my mysql codes vulnerability.
This is the php injection:
$myvar = "varname";
$x = $_GET['arg'];
eval("\$myvar = \$x;");

Or any other php code, like blow:
<?php mysqli_close($conn); ?>

My purpose is to insert them into DB but don't execute them.
Actualy these codes are gonna inserted into DB from an html input form by a user and I wan to display them for the user.(sth like messaging)
Problem:
The problem is that when I try to insert them into DB it fails, my insert query is this:
mysqli_query($conn,"INSERT INTO table (usr,id,message,date) VALUES ($usr,'$id','$message','$date')");

The codes are in $message.
I also should add this validation function:
function validate($data)
{
    stripslashes($data);
    htmlspecialchars($data);
    htmlentities($data);
    strip_tags($data);
    addslashes($data);
    return($data);
}

Before inserting $message into DB I have validated it by this function validate($message)  but even this can't fix the problem.
I have searched but there's no results for this question in google!
Any one knows how to insert codes into mysql database?

A: Escape your input data with a real_escape_string function: http://php.net/manual/en/mysqli.real-escape-string.php
Now you can safely create a legal SQL string that you can use in an SQL statement.

A: To insert code php in database, following this options :
1. To insert data, use htmlspecialchars. example :
$string = '<?php echo "Hello world"; ?>';
htmlspecialchars($string);

*Before read/get data, use htmlspecialchars_decode. Example : htmlspecialchars_decode($string);
Hope this maybe can help you :-)


text:
Q: Defining means on closed, unital subalgebras of $\mathscr{C}_{b}(X)$ In what follows, $X$ is a topological space and $\mathscr{C}^{b}(X)$ is the space of bounded, continuous functions on $X$ (with values in $\mathbb{C}$). I give you an adaptation of the definition of a mean as stated in Reiter, H. - Classical Harmonic Analysis and Locally Compact groups:

A mean $\mathscr{M}$ on $\mathscr{C}^{b}(X)$ is a positive, linear functional $\phi\mapsto\mathscr{M}(\phi)$ such that $\mathscr{M}(1_{X})=1$.

I wanted to define a mean on a closed, unital subalgebra, i.e. assume that $\mathcal{A}\subseteq\mathscr{C}^{b}(X)$ is a closed subspace of $\mathscr{C}^{b}(X)$ which is closed under multiplication and contains $1_{X}$, then I say that:

A mean $\mathscr{M}$ on $\mathcal{A}$ is a positive, linear functional such that $\mathscr{M}(1_{X})=1$.

No magic up to now. However I have the following problem: in Reiter's definition it follows quite easily (by using the same standard tricks as for integration), that $|\mathscr{M}(\phi)|\leq\lVert\phi\rVert_{\infty}$ for all $\phi\in\mathscr{C}^{b}(X)$ so that $\mathscr{M}$ is of norm less than 1. Unfortunately I do not necessarily have the functions $|\phi|$, $\Re(\phi)$ (real part) and $\Im(\phi)$ (imaginary part) available in $\mathcal{A}$. It works for real-valued functions because $-\lVert\phi\rVert_{\infty}\leq \phi\leq\lVert\phi\rVert_{\infty}$ but I do not know how to extend this to $\mathbb{C}$-valued functions. Do I need that $\mathcal{A}$ is a $C^{\ast}$-subalgebra (i.e. closed under conjugacy)?
Follow-up question:

Is the assumption of positivity sufficient to guarantee that $\mathscr{M}(f)\in\mathbb{R}$ whenever $f$ is real-valued? I can not guarantee $\max\{f,0\}$, $\min\{-f,0\}\in\mathcal{A}$ anymore.


text:
Q: NAnt - Check if process exists We use NAnt to stop the service, replace the files and start it backup.
<echo message="Waiting for Service to stop."/>
<property name="stopWait" value="360" />
<call target="stopServiceWait" />

... which calls below block
<!--Waits specified number of seconds or until service is stopped.-->
<target name="stopServiceWait">
    <if test="${int::parse(stopWait) > 0}">
        <echo message="Stopping Service... Waiting ${stopWait} more seconds..."/>
        <property name="stopWait" value="${int::parse(stopWait) - 1}" />
        <property name="isStopped" value="${service::is-stopped(bf.serviceName, bf.serverName)}" />
        <echo message="isStopped - ${isStopped}"/>
        <if test="${isStopped == 'False'}">
            <sleep seconds="1" />
            <echo message="Service is still not stopped"/>
            <call target="stopServiceWait" />
        </if>
    </if>
</target>

However after stopping the service the process often continues running for quite a few seconds, blocking the files. So we just wait some more time right now:
<!--Wait another 60 sec.-->
<echo message="Sleeping additional 60 seconds to ensure that process shuts down after stop."/>
<sleep seconds="60" />

Often long wait is not necessary and just extends outage, or sometimes it is not enough and the deployment has to be restarted.
Question:
Is there a way to check from NANT if the process with the certain name exists?


text:
Q: Determine whether it's a vector subspace I have a hard time understanding the question, that my math-prof gave it to me. The question is about proving whether the below given construct
$$ \{ f \in V \mid \exists B \geq 0 \forall a \in \mathbb{R}: |f(a)| \leq B \} $$
is a vector subspace, where $V = \mathcal{F}(\mathbb{R}, \mathbb{R})$
I tried to understand the question, and I kinda proved it, that the given construct is in fact a vector subspace. But I have no idea, if it's true, or not.
Any help is appreciated.
Let $|f(a)|$ and $|g(a)|$ element of $V$
Addition: $|f(a)| + |g(a)|$ (According to Definition: $|f(a)| \leq B$) which means $\Rightarrow |f(a)| + |g(a)| \leq B$
Let $\lambda$ element of $\mathbb{R}$
$$ \lambda \times |f(a)| \leq B \times \lambda $$
(According to Definition: $|f(a)| \leq B$) which means $\Rightarrow \lambda \times (\leq B) \leq \lambda times B$

A: Yes, it is a vector space, but not for those reasons. I will denote your space by $\mathcal B$.
First of all, you must check that $\mathcal B$ is not empty. Easy: just take the null function.
Then you must prove that if $f,g\in\mathcal B$, then $f+g\in\mathcal B$. There are numbers $B_f$ and $B_g$ such that$$(\forall a\in\Bbb R):|f(a)|\leqslant B_f\text{ and }|g(a)|\leqslant B_g.$$But then$$(\forall a\in\Bbb R):|(f+g)(a)|=|f(a)+g(a)|\leqslant|f(a)|+|g(a)|\leqslant B_f+B_g.$$So, $f+g$ is bounded.
Finally, you must prove that if $\lambda\in\Bbb R$ and $f\in\mathcal B$, then $\lambda f\in\mathcal B$ too. Take a number $B$ such that$$(\forall a\in\Bbb R):|f(a)|\leqslant B.$$Then$$(\forall a\in\Bbb R):|\lambda f(a)|=|\lambda||f(a)|\leqslant|\lambda|B,$$and therefore $\lambda f$ is bounded too.


text:
Q: The meaning of `this` in JS template method pattern Why does the marked line fail to find protectedACMember?
var Module = (function (ns) {

    function AbstractClass() {
        this.protectedACMember = "abstract";

        this.abstractPublicACMethod = function (input) {
            this.methodToImplement();
        }
    }

    ConcreteClass.prototype = new AbstractClass();
    function ConcreteClass(){
        var privateCCMember = "private CC";

        var privateCCMethod = function(){
            alert(this.protectedACMember); // cant find protectedACMember
        }

        this.methodToImplement = function(){
            privateCCMethod();
            console.log('Implemented method ');
        }

    }

    ns.ConcreteClass = ConcreteClass;

    return ns;

})(Module || {});

//somewhere later
var cc = new Module.ConcreteClass();
cc.abstractPublicACMethod();

are there any good patterns for simulating private, protected and public members? Static/non-static as well?

A: You should change that part of code like this:
    var self = this;
    var privateCCMethod = function(){
        alert(self.protectedACMember); // this -> self
    }

This way you get the reference in the closure.
The reason is, that "this" is a reserved word, and its value is set by the interpreter. Your privateCCMethod is an anonymous function, not the object property, so if you call it simply by privateCCMethod() syntax, this will be null.
If you'd like "this" to be bound to something specific you can always use .call syntax, like this:
privateCCMethod.call(this)

A: It fails to find protectedACMember because what the this keyword means changes when you enter the function privateCCMethod. A common practice is to store the outer this for use inside the functions:
function ConcreteClass(){
    var privateCCMember = "private CC";

    // store the outer this
    var that = this;
    var privateCCMethod = function(){
        alert(that.protectedACMember);
    }
    ...

The rest of your questions are fairly loaded and should probably be posted as a separate question.

A: Another way to ensure that this means what you want is to use bind. Bind allows you to ensure a function is called with a specific value of this.
Most newer browsers support it (even IE9!) and there's a workaround for those that don't.
Bind - MDN Documentation


text:
Q: Pandas: Looking back in time I am looking at the velocity of a vehicle and the only data I have is that the velocity is stable, slowing down or stopped (see df below). There is another one (speeding up) but this one is not found in the current df.
As you can see there are 2 "slowing down" periods. I am only interested in the data starting from the last "slowing down" period before stopped.
How do I filter the data in such a way that I can drop the first x rows that I am not interested in? Since the velocity values are always different, I cannot simply filter on values.
Hope you can help!
import pandas as pd

data = {
  "Date and Time": ["2020-06-07 00:00", "2020-06-07 00:01", "2020-06-07 00:02", "2020-06-07 00:03", "2020-06-07 00:04", "2020-06-07 00:05", "2020-06-07 00:06", "2020-06-07 00:07", "2020-06-07 00:08", "2020-06-07 00:09", "2020-06-07 00:10", "2020-06-07 00:11", "2020-06-07 00:12", "2020-06-07 00:13", "2020-06-07 00:14", "2020-06-07 00:15", "2020-06-07 00:16", "2020-06-07 00:17", "2020-06-07 00:18", "2020-06-07 00:19", "2020-06-07 00:20"],

  "Values": ["Stable","Stable","Stable","Stable", "Slowing down","Slowing down","Slowing down","Stable", "Stable", "Stable", "Slowing down","Slowing down","Slowing down","Slowing down","Slowing down","Slowing down","Slowing down","Slowing down", "Stopped", "Stopped", "Stopped"]
}

df = pd.DataFrame(data)

df.head()

A: You can get the sequence of slowing down period by using .cumsum() then filter by .loc with Values equals Slowing down and the newly created sequence is the max:
df['SlowDownSeq'] = df['Values'].ne(df['Values'].shift()).cumsum()
df_selected = df.loc[df['SlowDownSeq'] ==  df.loc[df['Values'] == 'Slowing down', 'SlowDownSeq'].max()].drop('SlowDownSeq', axis=1)

Result:
print(df_selected)

         Date and Time        Values
10 2020-06-07 00:10:00  Slowing down
11 2020-06-07 00:11:00  Slowing down
12 2020-06-07 00:12:00  Slowing down
13 2020-06-07 00:13:00  Slowing down
14 2020-06-07 00:14:00  Slowing down
15 2020-06-07 00:15:00  Slowing down
16 2020-06-07 00:16:00  Slowing down
17 2020-06-07 00:17:00  Slowing down

A: So from my understanding, you want the rows where 'Value' is 'Slowing down', followed immediately by 'Stopped'.
*Note: I see I misunderstood. You not only want that last row, but all previous sequential rows that start the "Slowing down" sequence. I'll still leave this solution up, but looks like SeaBean got you what you needed.
What you can do is create another column, which I called 'Next_Value' that is a shift up 1 row. then you can do a query/filter and find the rows that have a 'Value' == 'Slowing down' and 'Next_Value' == 'Stopped'
import pandas as pd

data = {
  "Date and Time": ["2020-06-07 00:00", "2020-06-07 00:01", "2020-06-07 00:02", "2020-06-07 00:03", "2020-06-07 00:04", "2020-06-07 00:05", "2020-06-07 00:06", "2020-06-07 00:07", "2020-06-07 00:08", "2020-06-07 00:09", "2020-06-07 00:10", "2020-06-07 00:11", "2020-06-07 00:12", "2020-06-07 00:13", "2020-06-07 00:14", "2020-06-07 00:15", "2020-06-07 00:16", "2020-06-07 00:17", "2020-06-07 00:18", "2020-06-07 00:19", "2020-06-07 00:20"],

  "Values": ["Stable","Stable","Stable","Stable", "Slowing down","Slowing down","Slowing down","Stable", "Stable", "Stable", "Slowing down","Slowing down","Slowing down","Slowing down","Slowing down","Slowing down","Slowing down","Slowing down", "Stopped", "Stopped", "Stopped"]
}

df = pd.DataFrame(data)

df['Next_Value'] = df['Values'].shift(-1)

filtered_df = df.query('Values == "Slowing down" and Next_Value == "Stopped"')

If you are more familiar with this syntax rather than df.query(), use the below line:
filtered_df = df[(df['Values'] == "Slowing down") & (df['Next_Value'] == "Slowing down")]
Output:
print(filtered_df)
       Date and Time        Values Next_Value
17  2020-06-07 00:17  Slowing down    Stopped

A: import pandas as pd

data = {
  "Date and Time": ["2020-06-07 00:00", "2020-06-07 00:01", "2020-06-07 00:02", "2020-06-07 00:03", "2020-06-07 00:04", "2020-06-07 00:05", "2020-06-07 00:06", "2020-06-07 00:07", "2020-06-07 00:08", "2020-06-07 00:09", "2020-06-07 00:10", "2020-06-07 00:11", "2020-06-07 00:12", "2020-06-07 00:13", "2020-06-07 00:14", "2020-06-07 00:15", "2020-06-07 00:16", "2020-06-07 00:17", "2020-06-07 00:18", "2020-06-07 00:19", "2020-06-07 00:20"],

  "Values": ["Stable","Stable","Stable","Stable", "Slowing down","Slowing down","Slowing down","Stable", "Stable", "Stable", "Slowing down","Slowing down","Slowing down","Slowing down","Slowing down","Slowing down","Slowing down","Slowing down", "Stopped", "Stopped", "Stopped"]
}

df = pd.DataFrame(data)

df["slow_count"] = df.groupby("Values").cumcount()

a = df[(df["slow_count"] == df["slow_count"].max()) & (df["Values"] == "Slowing down" )]


text:
Q: What does this error message "Received discontinuity error" mean? From Apple's mediastreamvalidator Using Apple's mediastreamvalidator to validate the m3u8 file, I got an error message: "Received discontinuity error", but I didn't find any explanation for this error message in https://developer.apple.com/library/ios/technotes/tn2235/_index.html
Does anybody know what this error mean, and whether this error will cause any issues?
My mediastreamvalidator's version is: Beta Version 1.1(150608)
Below is the mediastreamvalidator's result:

--------------------------------------------------------------------------------
test_1444446455_hls_64944_116-10.m3u8
--------------------------------------------------------------------------------

Playlist Syntax:    OK

Processed 15 out of 15 segments:

test_1444446455_hls_64944_116-10_00003.ts:

    ERROR: (-12976) Received discontinuity error
    --> Track ID: 258

test_1444446455_hls_64944_116-10_00007.ts:

    ERROR: (-12976) Received discontinuity error
    --> Track ID: 258

test_1444446455_hls_64944_116-10_00010.ts:

    ERROR: (-12976) Received discontinuity error
    --> Track ID: 258

test_1444446455_hls_64944_116-10_00014.ts:

    ERROR: (-12976) Received discontinuity error
    --> Track ID: 258

Average segment duration: 2.00 seconds
Playlist target bitrate: Average:  3.24 Mbits/sec, Max:  3.72 Mbits/sec
Segment bitrate: Average:  3.04 Mbits/sec, Max:  3.65 Mbits/sec
Average segment structural overhead: 76.21 kbits/sec (2.50 %)

Thank you.

A: A discontinuity can be caused by:

*

*changes in encoding such as: different file format, number, type and identifiers of tracks, different encoding parameters

*non-consistent timestamp sequences such as gaps or roll-overs

Such cases must/should be indicated with an EXT-X-DISCONTINUITY tag.
Check if your encoder is producing valid output.


text:
Q: In windows 8.1 How to stop an application from killing other applications? I have a distant learning course for an entrance exam. They've provided me a pendrive which has all the course material videos etc.
It can be accessed only after I install the software that comes with it.
Now the thing is it will expire after a couple of months and the software won't allow me to login.
For this reason, I want to record all the video lectures and save them on my disk.
I tried to use some third party softwares like camstudio etc. But the problem is, the pendrive application detects if there is any other software running while it is running and kills it.
Even a browser will be closed if opened while the pendrive softaware is running.
Now, how do I record the screen? is there any way to make the pendrive application stop killing other processes? By restricting its permissions or something like that?

A: I know it's a bit strange but have you checked where the video files are in the pendrive and copying it to your PC ?.
Also try disconnecting the internet connection and pushing your date back.
Rgds,
Rtrj

A: one easy way to get around the limitation would be to run windows in a vm and record the video from the host operating system. this way the "service" won't be able to kill apps running on the host. the question is, does the app check if it's running in a virtualized environment?


text:
Q: PHP print_r not returning json request The following code runs without any errors, however it doesn't return anything.
If I paste it into my browser it returns the information I'm looking for, I can also replace it with another URL and it works perfectly.
$ch = curl_init();

$url = 'https://api.coronavirus.data.gov.uk/v1/data?filters=areaName=Somerset&structure={"date":"date","areaName":"areaName","areaCode":"areaCode","newCasesByPublishDate":"newCasesByPublishDate","cumCasesByPublishDate":"cumCasesByPublishDate","newDeathsByDeathDate":"newDeathsByDeathDate","cumDeathsByDeathDate":"cumDeathsByDeathDate"}';

curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$resp = curl_exec($ch);

$decode =json_decode($resp);
print_r($decode);

curl_close($ch);

A: You can use following generated code by the postman
<?php

    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://api.coronavirus.data.gov.uk/v1/',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'GET',
      CURLOPT_POSTFIELDS =>'{"date":"date","areaName":"areaName","areaCode":"areaCode","newCasesByPublishDate":"newCasesByPublishDate","cumCasesByPublishDate":"cumCasesByPublishDate","newDeathsByDeathDate":"newDeathsByDeathDate","cumDeathsByDeathDate":"cumDeathsByDeathDate"}',
      CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json'
      ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    echo $response;

A: This code is worked. Reason is encoding of received content.
try {
    $ch = curl_init();

    // Check if initialization had gone wrong*
    if ( $ch === false ) {
        throw new RuntimeException( 'failed to initialize' );
    }

    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL,
        'https://api.coronavirus.data.gov.uk/v1/data?filters=areaName=Somerset&structure={"date":"date","areaName":"areaName","areaCode":"areaCode","newCasesByPublishDate":"newCasesByPublishDate","cumCasesByPublishDate":"cumCasesByPublishDate","newDeathsByDeathDate":"newDeathsByDeathDate","cumDeathsByDeathDate":"cumDeathsByDeathDate"}' );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Solution is here. Response is the compressed content which your curl failed to detect. Empty encoding means to handle any type of encoding. It should solve your issue.
    curl_setopt($ch, CURLOPT_ENCODING, '');
    $content = curl_exec( $ch );
    curl_close( $ch );
    if ( $content === false ) {
        throw new RuntimeException( curl_error( $ch ), curl_errno( $ch ) );
    }

    /* Process $content here */

    $decode = json_decode( $content );

    var_dump( $decode );

    // Close curl handle
    curl_close( $ch );
} catch ( RuntimeException $e ) {

    trigger_error(
        sprintf(
            'Curl failed with error #%d: %s',
            $e->getCode(),
            $e->getMessage()
        ),
        E_USER_ERROR
    );

}


text:
Q: How to get Input Value from masterpage how can i get the value of input control from masterpage ?
my master page:
.......

          <form id="formsearch" name="formsearch" method="post" action="#">

            <input name="editbox_search" class="editbox_search" id="editbox_search" maxlength="80" value="Code Client:" type="text" />

            <input name="button_search" src="images/search_btn.gif" class="button_search" type="image" />
          </form>

               <form id="form1" runat="server">

        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

        </asp:ContentPlaceHolder>

    </form>

.....

and my default.aspx that use MasterPAge:
protected void Page_Load(object sender, EventArgs e)
{
    Label ClientId = (Label)Master.FindControl("editbox_search");

    ASPxLabel_Err.Text = ClientId.Text;
}

i try to convert input Control into Label, because i can not find input control.
but i got nullReference that logic because i can not convert input control into label control.

A: var editbox = (HtmlInputControl)Master.FindControl("editbox_search");
Response.Write (editbox.Value);

A: try this
     var mastertxt = (System.Web.UI.HtmlControls.HtmlInputText)Master.FindControl("ctl00$editbox_search");
     ASPxLabel_Err.Text = mastertxt.Value;

A: first you need to make this tag as "runat= server" then only you can use:
var txtEditBox =(System.Web.UI.HtmlControls.HtmlInputText)this.Page.Master.FindControl("editbox_search");
ASPxLabel_Err.Text = txtEditBox.Value ;


text:
Q: What is "WARNING 'syslog' option is deprecated"? Hi all have been trying to make a samba ubuntu server and I ran testparm and it came up with ---- WARNING "syslog" option is deprecated' ----
In smb.conf I have syslog set to 0 (I have no idea what that means)
If anyone has any ideas. Thank Nic

A: I had the same warning. It went away when I commented out the line
syslog = 0

in the file smb.conf.

A: As a supplement to @user760430 answer, You can use multiple log "backends". In my example: syslog and file.
# log file
log file = /var/log/samba/log.%m

# no log to syslog (0-level), log 2-level to file
logging = syslog@0 file@2

# overall log level
log level = 3

A: Newer versions of Samba have a more powerful parameter named logging which provides finer control over logging. The warning tells you that in future versions the parameter syslog may be considered for removal in favor of the newer logging. See man smb.conf for details.

A: The syntax you are looking for is: logging = syslog@1 /var/log/samba/log.%m
Just comment out or remove syslog = 0. The number is the severity mapping for which logs the errors go into. 0=> log_err, 1=> log_warning, 2=> log_notice.
The number parameter sets a threshold for sending messages to syslog.
Only messages with debug level less than this value will be sent to syslog.
Default is 1. If you are setting up a development sandbox I would just whack that stuff unless you are having problems and need to see the logs.
I'm using Debian and the above syntax shows no errors running testparm.


text:
Q: ArrayList inside HashTable is thread safe Simple question. Is following code is thread safe...?

*

*If yes, is there is any better way..?

*If no, why.? and how can I make it thread safe.

My main doubt because of ArrayList inside Hashtable because ArrayList is not thread safe. So same thing will happen if its part of Hashtable.
Hashtable<Thread, List<String>> threadObjects = new Hashtable<Thread, List<String>>();
 // lets assume some object is added.
 synchronized (threadObjects)
  {
     thread = Thread.currentThread();
     List<String> v =  threadObjects.get(thread);
     if (null != v)
     {
       // do something
     }
  }

Thanks

A:
If yes, is there is any better way..?

Yes, but use a ThreadLocal>

My main doubt because of ArrayList inside Hashtable because ArrayList is not thread safe.

Normally you would be right, however this code ensures that an ArrayList is only accessed by one thread.  Of course if you didn't following this pattern it would be thread safe.
Note: The synchronized (threadObjects) doesn't make any difference in this case.

A:
Is following code is thread safe...?

Yes ... provided that:

*

*the code that creates the map and adds entries to the map is also thread-safe,

*no other code uses the map without synchronizing on it (as per your code), and

*no code updates the list objects without synchronizing on the map.

Thread-safety of an externally synchronized data structure can only be determined by examining all of the code that uses the data structure.
As Peter states, ThreadLocals would be a better solution, but there is still a potential thread-safety issue if the list objects are mutated without appropriate locking.

A: You can use a ThreadLocal to store thread-specific data. For example:
private final ThreadLocal<List<String>> threadObjects =
    new ThreadLocal<List<String>>() {
        @Override protected List<String> initialValue() {
            return new ArrayList<String>();
        }
    };

public void foo() {
    for (String s : threadObjects.get()) {
        // do something with each string in this thread's list
    }
}

This is a much better way of tracking thread-specific data than the Hashtable approach because the table is maintained for you inside the ThreadLocal implementation itself, including the synchronization. No additional synchronization is needed on the ArrayList instance as long as you don't publish the reference to other threads;  each thread will have its own ArrayList instance to do with as it pleases without concurrency concerns.
The overriding of initialValue() is a convenience because it allows you to avoid the check for null on the result of threadObjects.get(), assuming of course that you don't explicitly set the thread local to null.


text:
Q: INSERT HIVE SQL in loop in Spark We are trying to run an INSERT SQL for HIVE with data coming out of a dataframe in Spark. The session used has  etc everything.
Have 2 issues:
Question) Even though we create session inside forEach loop, the INSERT is still failing when tried with both
1) Dataframes
2) Straight Spark SQL
Below is the code (Spark SQL Approach):
import java.time.Instant

import org.apache.spark.sql.{DataFrame, Row, types}
import org.apache.spark.sql.functions.{current_timestamp, first, isnull, lit, max}
import org.apache.spark.sql.types.{StringType, StructField, StructType, TimestampType}

import scala.collection.mutable.ListBuffer

class Controller extends DatabaseServices
  with Loggers {
  val session = createSparkSession(ConfigFactory.load().getString("local.common.spark.app.name"))
  val producer = session.sparkContext.broadcast(KafkaWrapper())

  def doIt(TranIDs: DataFrame): Unit = {
    import session.sqlContext.implicits._

    val TranID = TranIDs
      .withColumnRenamed("TranID", "REFERENCE_TranID")
      .select($"REFERENCE_TranID")
      .union(session.table(BANK_ROLLBACK_TXN_PRODUCER_LOG_VIEW)
        .withColumnRenamed("TranID", "REFERENCE_TranID")
        .select($"REFERENCE_TranID"))
      .where($"REFERENCE_TranID".isNotNull)

    if (TranID.count() == 0) {
      throw new Exception("No rows.")
    }

    val core = session
      .table(BANK_TRANS_MASTER_CORE)
      .withColumnRenamed("TranID", "MASTER_REFERENCE_TranID")
      .withColumnRenamed("CLIENTID", "REF_CLIENT_ID")
      .withColumnRenamed("SUBCLIENTID", "REF_SUBCLIENT_ID")
      .select($"MASTER_REFERENCE_TranID",
        $"TranIDDATE")
      .join(TranID, TranID.col("REFERENCE_TranID") === $"MASTER_REFERENCE_TranID")

    val ref = session
      .table(BANK_RBI_REF_CLIENT)
      .select($"CLIENTID", $"SUBCLIENTID", $"FLAGTRE")
      .join(core, $"CLIENTID" === core.col("REF_CLIENT_ID")
        && $"SUBCLIENTID" === core.col("REF_SUBCLIENT_ID")

    val details = session
      .table(BANK_TRANS_MASTER_DETAILS)
      .select($"TranID",
        $"REALFRAUD",
        $"REALFRAUDDATEBAE",
        $"REALFRAUDYYYYMMDD"
      )
      .join(ref, ref.col("MASTER_REFERENCE_TranID") === $"TranID"
        && $"REALFRAUD" === lit("Y"))
      .where($"TranID".isNotNull
        && $"TranIDDATE".isNotNull)
      .groupBy($"TranID")
      .agg(first($"TranID").as("TranID"),
        first(core("TranIDDATE")).cast("String").as("TranIDDATE"),
        max($"REALFRAUDDATEBAE").as("REALFRAUDDATEBAE"),
        max($"REALFRAUDYYYYMMDD").as("REALFRAUDYYYYMMDD"),
        first($"REALFRAUD").as("REALFRAUD"),
        first($"ABA").as("ABA"))

    details.foreach(row => {

      import scala.collection.JavaConversions._
      val transaction = TxUpdate.newBuilder().setTranID(row.getAs("TranID").toString)
        .setTranIDDATE(row.getAs("TranIDDATE").toString)
        .setAttributes(ListBuffer(
          Attribute.newBuilder.setKey("REALFRAUD").setValue(if (row.getAs("REALFRAUD") != null) row.getAs("REALFRAUD").toString else null).build(),
          Attribute.newBuilder.setKey("REALFRAUDDATEBAE").setValue(if (row.getAs("REALFRAUDDATEBAE") != null) if (row.getAs("REALFRAUDDATEBAE") != null) row.getAs("REALFRAUDDATEBAE").toString else null else null).build(),
          Attribute.newBuilder.setKey("REALFRAUDYYYYMMDD").setValue(if (row.getAs("REALFRAUDYYYYMMDD") != null) row.getAs("REALFRAUDYYYYMMDD").toString else null).build(),
          Attribute.newBuilder.setKey("ABA").setValue(if (row.getAs("ABA") != null) row.getAs("ABA").toString else null).build(),
        .build()

      if (producer.value.sendSync(ConfigFactory.load().getString("local.common.kafka.rollbackKafkaTopicName"),
        transaction.getTranID.toString,
        transaction)) {
        session.sqlContext.sql("insert into " + BANK_ROLLBACK_TXN_PRODUCER_LOG + "(TranID, when_loaded, status) values('" + transaction.getTranID.toString + "', 'current_timestamp()', 'S')")
      } else {
        session.sqlContext.sql("insert into " + BANK_ROLLBACK_TXN_PRODUCER_LOG + "(TranID, when_loaded, status) values('" + transaction.getTranID.toString + "', 'current_timestamp()', 'F')")
      }

    })

  }
}

A: The error is not clear here.
At a high level you can use the approach of enabling hivecontext within Spark and then directly do persist into Hive table using append option. This will be much faster than doing Insert operation. The flow will be something like this:
step 0- all this has to happen in a single spark session. You don't need to create multiple sessions for each insert. In a way this is meaningless to do.
a. Create a data frame having the columns of the underlying table of Hive.
b. During spark processing data frame gets its data to be persisted eventually in Hive.
c. Initiate Dataframe saveastable with append option
Insert Into Hive
Hope this helps to understand how you need to approach this problem.

A: We had used df.write.insertInto with Append option which gave errors. Finally made that to work.


text:
Q: Understanding Netflix Eureka Leases - Service Keeps Unregistering I keep having this intermittent issue with one of my Spring Cloud Eureka clients, but none of the others.  When I start my "NCLSEARCHSERVICE" it registers itself with Eureka, shows "UP" in Eureka for about 30 seconds to a minute, then unregisters itself.  Here are the logs from the Eureka server that show it registering all of my other services, but then failing to register my search service because "Lease is not registered".  Sorry for the poor formatting of the log file copy/paste.

2015-10-01 09:48:55.144  WARN 6470 --- [nio-8761-exec-4] com.netflix.eureka.InstanceRegistry      : DS: Registry: lease doesn't

exist, registering resource: CONFIGSERVICE - 172.18.100.120 2015-10-01
  09:48:55.145  WARN 6470 --- [nio-8761-exec-4]
  c.n.eureka.resources.InstanceResource    : Not Found (Renew):
  CONFIGSERVICE - 172.18.100.120 2015-10-01 09:48:55.147  WARN 6470 ---
  [nio-8761-exec-2] com.netflix.eureka.InstanceRegistry      : DS:
  Registry: lease doesn't exist, registering resource: ZUULSERVER -
  eXploit-Zuul 2015-10-01 09:48:55.147  WARN 6470 --- [nio-8761-exec-2]
  c.n.eureka.resources.InstanceResource    : Not Found (Renew):
  ZUULSERVER - eXploit-Zuul 2015-10-01 09:48:55.419  INFO 6470 ---
  [nio-8761-exec-7] com.netflix.eureka.InstanceRegistry      :
  Registered instance id 172.18.100.120 with status UP 2015-10-01
  09:48:55.423  INFO 6470 --- [nio-8761-exec-8]
  com.netflix.eureka.InstanceRegistry      : Registered instance id
  eXploit-Zuul with status UP 2015-10-01 09:48:55.778  INFO 6470 ---
  [nio-8761-exec-9] com.netflix.eureka.InstanceRegistry      :
  Registered instance id 172.18.100.120 with status UP 2015-10-01
  09:48:55.809  INFO 6470 --- [io-8761-exec-10]
  com.netflix.eureka.InstanceRegistry      : Registered instance id
  eXploit-Zuul with status UP 2015-10-01 09:49:05.416  WARN 6470 ---
  [nio-8761-exec-3] com.netflix.eureka.InstanceRegistry      : DS:
  Registry: lease doesn't exist, registering resource: GEOSERVER -
  172.18.100.155 2015-10-01 09:49:05.418  WARN 6470 --- [nio-8761-exec-3] c.n.eureka.resources.InstanceResource    : Not Found
  (Renew): GEOSERVER - 172.18.100.155 2015-10-01 09:49:05.441  INFO 6470
  --- [nio-8761-exec-5] com.netflix.eureka.InstanceRegistry      : Registered instance id 172.18.100.155 with status STARTING 2015-10-01
  09:49:05.607  INFO 6470 --- [nio-8761-exec-4]
  com.netflix.eureka.InstanceRegistry      : Registered instance id
  172.18.100.155 with status STARTING 2015-10-01 09:49:05.948  INFO 6470 --- [nio-8761-exec-8] com.netflix.eureka.InstanceRegistry      : Registered instance id 172.18.100.197 with status UP 2015-10-01
  09:49:06.107  INFO 6470 --- [nio-8761-exec-9]
  com.netflix.eureka.InstanceRegistry      : Registered instance id
  172.18.100.197 with status UP 2015-10-01 09:49:11.175  WARN 6470 --- [io-8761-exec-10] c.n.eureka.resources.InstanceResource    : Time to
  sync, since the last dirty timestamp differs - ReplicationInstance id
  : 172.18.100.155,Registry : 1443651207024 Incoming: 1443651408538
  Replication: false 2015-10-01 09:49:11.197  INFO 6470 ---
  [nio-8761-exec-3] com.netflix.eureka.InstanceRegistry      :
  Registered instance id 172.18.100.155 with status UP 2015-10-01
  09:49:11.562  WARN 6470 --- [nio-8761-exec-5]
  c.n.eureka.resources.InstanceResource    : Time to sync, since the
  last dirty timestamp differs - ReplicationInstance id :
  172.18.100.155,Registry : 1443651408538 Incoming: 1443651207024 Replication: true 2015-10-01 09:49:11.607  INFO 6470 ---
  [nio-8761-exec-4] com.netflix.eureka.InstanceRegistry      :
  Registered instance id 172.18.100.155 with status UP 2015-10-01
  09:50:03.859  INFO 6470 --- [nio-8761-exec-6]
  c.n.eureka.resources.InstanceResource    : Found (Cancel):
  NCLSEARCHSERVICE - 172.18.100.197 2015-10-01 09:50:03.870  INFO 6470
  --- [io-8761-exec-10] com.netflix.eureka.InstanceRegistry      : Registered instance id 172.18.100.197 with status UP 2015-10-01
  09:50:04.120  INFO 6470 --- [nio-8761-exec-2]
  com.netflix.eureka.InstanceRegistry      : Registered instance id
  172.18.100.197 with status UP 2015-10-01 09:50:04.130  INFO 6470 --- [nio-8761-exec-5] c.n.eureka.resources.InstanceResource    : Found
  (Cancel): NCLSEARCHSERVICE - 172.18.100.197 2015-10-01 09:50:04.745
  WARN 6470 --- [nio-8761-exec-3] com.netflix.eureka.InstanceRegistry
  : DS: Registry: cancel failed because Lease is not registered for:
  NCLSEARCHSERVICE:172.18.100.197

The logs for my search service don't seem to show anything interesting, only that it saw in Eureka that it was previously down and now it's changing the status to up:

2015-09-30 17:59:14.164  INFO 9056 --- [           main]
  c.n.e.EurekaDiscoveryClientConfiguration : Unregistering application
  nclSearchService with eureka with status DOWN 2015-09-30 17:59:14.164
  INFO 9056 --- [           main] com.netflix.discovery.DiscoveryClient
  : Saw local status change event StatusChangeEvent [current=DOWN,
  previous=UP] 2015-09-30 17:59:14.208  INFO 9056 --- [nfoReplicator-0]
  com.netflix.discovery.DiscoveryClient    :
  DiscoveryClient_NCLSEARCHSERVICE/172.18.100.197: registering
  service... 2015-09-30 17:59:14.217  INFO 9056 --- [nfoReplicator-0]
  com.netflix.discovery.DiscoveryClient    :
  DiscoveryClient_NCLSEARCHSERVICE/172.18.100.197 - registration status:
  204 2015-09-30 17:59:14.218  INFO 9056 --- [           main]
  com.netflix.discovery.DiscoveryClient    :
  DiscoveryClient_NCLSEARCHSERVICE/172.18.100.197 - deregister  status:
  200 2015-09-30 17:59:14.218  INFO 9056 --- [           main]
  c.n.e.EurekaDiscoveryClientConfiguration : Registering application
  nclSearchService with eureka with status UP

My config is a mess right now, because I keep experimenting with different values and configurations, but here is the basic values I'm working with:
spring:
  cloud:
    config:
#      uri: http://${CONFIG_SERVER_URL:172.18.100.120:8888}
      discovery:
        enabled: true
        serviceId: CONFIGSERVICE
  application:
    name: nclSearchService

eureka:
  client:
    enable-self-preservation: false
#    registerWithEureka: true
#    fetchRegistry: true
    serviceUrl:
      defaultZone: http://172.18.100.120:8761/eureka/
#    healthcheck:
#      enabled: true
  instance:
    leaseRenewalIntervalInSeconds: 30

# items below are listed in the config server
service:
    name: nclSearchService

security:
  sessions: NEVER

#instance:
#  preferIpAddress: true
#server:
#  port: 8080
#  contextPath: /

You can see that I'm also loading config dynamically from a config service, but that just loads application specific variables.
In the past, if I keep randomly messing with the config on my search service, I can get it to stabilize on Eureka.  But then the problem re-appears and I can never pin point what is actually causing it.  It seems to be an issue with Eureka and it's instance registry, but I can't quite figure out what to do to fix it.
UPDATE 1:
The NCLSEARCHSERVICE is using spring-boot-dependencies 1.2.5.RELEASE and spring-cloud-netflix 1.1.0.M1.  My Eureka server is using the same version of the spring boot dependencies, but spring-cloud-netflix 1.0.3.RELEASE.  I tried updating the search service to see if that had any effect on my issue.  If it is recommended that all services use the same version, I can move either up/down a version.
Only once in my troubleshooting did I attempt to call /refresh on my search service.  If I remember correctly, it went through the same process of showing up temporarily and then being removed from the registry again.
UPDATE 2:
I may have narrowed down the issue... I had a config server running on port 8888 on the same VM as the Eureka server running on port 8761.  I disabled the dynamic configuration in my search service and moved the contents of the nclSearchService.yml from the config server to application.yml on my search service.  The search service has registered with Eureka and has been stable for about 10 minutes.
This is odd because even though my search service is no longer configured to use the config service, the config service is still deployed and running.  Also, even when the search service was deregistering, you could see in the logs that it was successfully pulling the nclSearchService.yml file from the config service, and it would boot all the way up and be usable with the properties that were pulled from the config service.
Not sure what any of that means :)

A: Increasing the docker memory from 2GB to 4GB fixed this for me. Maybe increasing the VM memory will fix this for you as well.


text:
Q: Find matches between two string columns in R In order for me to solve a tag migration problem, I have to compare between two character columns and assess whether there are coincidences between both columns or not.
To sum up, given a dataframe like this:
old_tags            new_tags
burger              burger, american
italian, pizza      italian
latin, peruvian     peruvian, latin
french              pizza

I'd like to add a third column like this one:
old_tags            new_tags            match
burger              burger, american    TRUE
italian, pizza      italian             TRUE
latin, peruvian     peruvian, latin     TRUE
french              pizza               FALSE

Until now I've unsuccessfully tried with functions such as str_match, str_detect and so on. It usually returns me FALSE when comparing pairs of strings that should be actually TRUE such the example I've put in [3,].
Thanks a lot in advance.

A: One base R approach could be to split the string on comma. Using Map find intersecting words and create a logical value if there is at least one value which intersects.
df$match <- lengths(Map(intersect, strsplit(df$old_tags, ", "),
                    strsplit(df$new_tags, ", "))) > 0

df
#         old_tags         new_tags match
#1          burger burger, american  TRUE
#2  italian, pizza          italian  TRUE
#3 latin, peruvian  peruvian, latin  TRUE
#4          french            pizza FALSE

data
df <- structure(list(old_tags = c("burger", "italian, pizza", "latin, peruvian",
"french"), new_tags = c("burger, american", "italian", "peruvian, latin",
"pizza")), row.names = c(NA, -4L), class = "data.frame")

A: A tidyverse-base possibility:
library(dplyr)
library(stringr)

df %>%
   mutate(patterns = map_chr(strsplit(old_tags, ", "),paste,collapse="|"),
          Match = str_detect(new_tags, patterns)) %>%
   select(-patterns)
         old_tags         new_tags Match
1          burger burger, american  TRUE
2  italian, pizza          italian  TRUE
3 latin, peruvian  peruvian, latin  TRUE
4          french            pizza FALSE

A: Or we can do str_extract with any
library(tidyverse)
df %>%
   mutate(match = map2_lgl(str_extract_all(old_tags, "\\w+"),
               str_extract_all(new_tags, "\\w+"),  ~ any(.x %in% .y)))
#         old_tags         new_tags match
#1          burger burger, american  TRUE
#2  italian, pizza          italian  TRUE
#3 latin, peruvian  peruvian, latin  TRUE
#4          french            pizza FALSE

data
df <- structure(list(old_tags = c("burger", "italian, pizza", "latin, peruvian",
"french"), new_tags = c("burger, american", "italian", "peruvian, latin",
"pizza")), row.names = c(NA, -4L), class = "data.frame")


text:
Q: Данные с поля в сторе приходят не сразу, а спустя некоторое время, с чем это может быть связано? У меня есть компонент TopLane, ему с reducer пробрасывает поле в котором должны быть данные, но они приходят не сразу, лишь только после 2-го раза, не могу понять почему так((

Код самого TopLane
    import React, { Component } from 'react';
import PropTypes from 'prop-types';

import a_icon_arrow_back from '../../../../../../assets/img/product/a_icon_arrow_back.svg';
import arrow_default from '../../../../../../assets/img/product/_a.icon.arrow.default blue.svg'
import export_blue from '../../../../../../assets/img/product/_a.icon.export_blue.svg';

import '../../../../../../assets/scss/pages/product/_top_lane_audit.scss';
import {ProgressBarColored} from 'serpstat-components/Common/ProgressBars/ProgressBarColored';
import ProgressBarSimple from 'serpstat-components/Common/ProgressBars/ProgressBarSimple';
import Dropdown from 'serpstat-components/Common/Dropdowns/Dropdown';
// import index from 'serpstat-components/Common/dropdown-select/index';

import {connect} from 'react-redux';
import {fetchRequest} from 'serpstat-actions/audit2.0/fetchRequest';

import DataRange from 'serpstat-components/Projects/Audit_2.0/common/DataRange/DataRange';
import DataPicker from 'serpstat-components/Common/Datepicker/DateRange';
import {isActiveCompare, isActiveExport, isActiveDropBox} from 'serpstat-actions/audit2.0/isActive';
import {
    getErrorInfoOneRequest,
    getErrorInfoOTwoRequest,
    getErrorInfoThreeRequest,
    getErrorInfoFourRequest,
    getErrorInfoFiveRequest,
} from 'serpstat-actions/audit2.0/getErrorInfo';
import {getLimitRequest} from '../../../../../../redux/actions/audit2.0/getLimit';

import MainTitle from 'serpstat-components/Projects/Audit_2.0/common/components/MainTitle/MainTitle';
class TopLane extends Component {

    componentDidMount(){
        this.props.fetchRequest();
        // console.log(this.props.errorTypeOne);
        // this.props.getErrorInfoOneRequest();
        // this.props.getErrorInfoOTwoRequest();
        this.props.getErrorInfoThreeRequest();
        this.props.getLimitRequest();
        // this.props.getErrorInfoFourRequest();
        // this.props.getErrorInfoFiveRequest();
    }

    // componentWillMount(){
    //     this.props.getErrorInfoOneRequest();

    // }

    render() {
        // console.log(this.props);
        const {addLimit} = this.props;
        const {result} = addLimit;
        console.log(addLimit);
        return (

                {/* <MainTitle data={this.props.toggleClass}/> */}
                {/* <DataRange/> */}

Site audit summary / All errors and recommendations

                        Errors:
                        dropbox
                        |
                        dropbox2

                    {/* {result.used < 100 ? лимиты исчерпаны:
                    `${<p>Limits: {result.left}/{result.total}</p>} ${<div className='widthProgress'><ProgressBarColored curr={result.left} max={result.total} color={"green"} /></div>}`
                    } */}

                {/* <DataPicker/> */}

                            Compare with: 17 Sep

                        {/*
<DataRange/>
 */}

                             Export

        );
    }
}

TopLane.propTypes = {

};

function mapStateToProps (store){
    return {
        toggleClass: store.allErrorAudit.toggleClass,
        errorTypeOne: store.allErrorAudit.dataErrorList.errorTypeOne,
    }
}

function mapDispatchToProps(dispatch){
    return {
        getErrorList: function (){
            dispatch(getErrorList());
        },

        getErrorInfoOneRequest: function (){
            dispatch(getErrorInfoOneRequest())
        },
        getErrorInfoOTwoRequest: function (){
            dispatch(getErrorInfoOTwoRequest())
        },
        getErrorInfoThreeRequest: function (){
            dispatch(getErrorInfoThreeRequest())
        },
        getErrorInfoFourRequest: function (){
            dispatch(getErrorInfoFourRequest())
        },
        getErrorInfoFiveRequest: function (){
            dispatch(getErrorInfoFiveRequest())
        },

        getErrorInfoOne: function (){
            dispatch(getErrorInfoOne())
        },
        fetchRequest: function (){
            dispatch(fetchRequest())
        },
        isActiveCompare: function (){
            dispatch(isActiveCompare())
        },
        isActiveExport:function (){
            dispatch(isActiveExport())
        },
        isActiveDropBox: function (){
            dispatch(isActiveDropBox())
        },
        // getDataSetError: function (){
        //     dispatch(getDataSetError())
        // }
        getLimitRequest: function (){
            dispatch(getLimitRequest())
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(TopLane);

worker in saga
    import { getMockData } from "serpstat-api";
import { call, put } from 'redux-saga/effects';
import {getLimitSucceed} from '../../../../actions/audit2.0/getLimit';

import p from '../../procedures';

  export default function*() {
    try {
      const data = yield call(getMockData, p["limits.getLimit"]);

        yield put(getLimitSucceed(data));

    } catch (err) {
            console.log(err);

    }
  }

Reducer`
import * as t from '../../../constants/audit2.0';
export default function addLimitReducer (state = [], action){
    switch(action.type){
        case t.GET_LIMIT_SUCCEED:
        return action.data;
        default: return state;
    }
}`

Actions
import * as t from "../../constants/audit2.0";

export const getLimitRequest = () => ({
    type: t.GET_LIMIT_REQUEST,
  });

  export const getLimitSucceed = (data) => ({
    type: t.GET_LIMIT_SUCCEED,
    data,
  });

A: как я понял, ты делаешь 3 запроса в componentDidMount. Тебе нужно создать метку, которая переходит в true, когда получаешь ответ по всем трем запросам и рендерить компонент только тогда. До получения ответа можно отрендерить какой-нибуль лоадер


text:
Q: Подскажите пожалуйста, КАК сделать загрузку img в laravel 5.3 Подскажите пожалуйста, КАК сделать загрузку img  в laravel 5.3

A: 1. Добавить Route
routes/web.php
Route::get('image-upload','ImageController@imageUpload');
Route::post('image-upload','ImageController@imageUploadPost');

2. Добавить controller
app/Http/Controllers/ImageController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;

class ImageController extends Controller
{

    /**
    * Create view file
    *
    * @return void
    */
    public function imageUpload()
    {
        return view('image-upload');
    }

    /**
    * Manage Post Request
    *
    * @return void
    */
    public function imageUploadPost(Request $request)
    {
        $this->validate($request, [
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $imageName = time().'.'.$request->image->getClientOriginalExtension();
        $request->image->move(public_path('images'), $imageName);

        return back()
            ->with('success','Image Uploaded successfully.')
            ->with('path',$imageName);
    }

}

3. Создать файл Blade
resources/views/image-upload.blade.php
<!DOCTYPE html>

    <title>Laravel 5.3 Image Upload with Validation example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Laravel 5.3 Image Upload with Validation example

        @if (count($errors) > 0)

                Whoops! There were some problems with your input.

                    @foreach ($errors->all() as $error)

{{ $error }}

                    @endforeach

        @endif

        @if ($message = Session::get('success'))

            <button type="button" class="close" data-dismiss="alert">×</button>
                {{ $message }}

        @endif

        <form action="{{ url('image-upload') }}" enctype="multipart/form-data" method="POST">
            {{ csrf_field() }}

                    <input type="file" name="image" />

                    <button type="submit" class="btn btn-success">Upload</button>

        </form>

Примерно так.