text:
Q: Issues installing data.table in R 3.6.3 (Oct 2020) I'm using a Mac with OS Sierra 10.12.5. I'm having trouble with installing the R package "data.table," including if I try to install via install.packages("Hmisc"), or install.packages("data.table"). Both result in:
installing to /Library/Frameworks/R.framework/Versions/3.6/Resources/library/00LOCK-data.table/00new/data.table/libs
** R
** inst
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
** building package indices
** installing vignettes
** testing if installed package can be loaded from temporary location
Error: package or namespace load failed for 'data.table' in library.dynam(lib, package, package.lib):
 shared object 'datatable.so' not found
Error: loading failed
Execution halted
ERROR: loading failed
* removing '/Library/Frameworks/R.framework/Versions/3.6/Resources/library/data.table'

The downloaded source packages are in
    '/private/var/folders/bl/lgd7_j2j087f24tcly84xg580000gn/T/RtmpbM5EaD/downloaded_packages'
Warning message:
In install.packages("data.table") :
  installation of package 'data.table' had non-zero exit status

I then tried installing directly from the .zip at: https://github.com/Rdatatable/data.table, but got the following "not available for R 3.6.3" message:
> install.packages("~/Downloads/data.table-master.zip")
Warning message:
package '~/Downloads/data.table-master.zip' is not available (for R version 3.6.3)

I tried the approaches in this thread, but none worked :\ : Problems installing data.table for R
Any advice for what I can try next, or where I can access a version of data.table specifically for R 3.6.3?


text:
Q: How do big companies apply machine learning? I was wondering how recommendation on youtube work for example? How are the algorithms applied, because every user gets different recommendations depending on his location, his past liked videos etc... So it would seem like a training model is applied to every single user but I know that can't be possible so how are these recommendations so user-specific without applying a unique training model to every single user?

A: This may not be an exceptionally useful answer for you, but the specific question you are asking relates directly to what I do at my job, which is not really machine learning.
If I wanted to customize recommendations for a YouTube user, I would start with a graph. My graph would have two types of nodes, users and videos, and edges that only connect users and videos, representing videos that user has seen. To get a recommendation for a user, I would start at the last X videos that user has watched and do two traversals, one to users, and one back to videos. Then I would count how many times I ended up at each video, and recommend those videos that I ended up at the most. This would give you a list of most watched videos by people who also watched the same videos you did. From here you can refine it in various ways, but that is how you would start.
I don't know if this is what YouTube does, but it is what shopping sites do, and it is what I do at work for a 'big company,' though it is not machine learning.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trace of roots of unity has valuation more than 1 in uramified field Let $F$ be a finite extension of $\mathbb{Q}_p$ (p is prime) and $K/F$ be a unramified extension of prime degree $\ell (\neq p)$. Denote $\mu_K$ be the group of roots of unity in $K.$ Does there exist an element $\zeta\in\mu_K$ such that $tr_{K/F}\zeta\in P^t_F$ for $t\ge 1$?
If the answer is yes, what is the largest $t$ with the above property?


text:
Q: How can I take the id value from a tag KML? I wnat to take the "id" value that is inside a KML tag, eg.:
    <Style id="icon-1899-0288D1-labelson-nodesc">

What can I do in python, I'm using fastkml:
from fastkml.kml import KML
from pykml import parser
from bs4 import BeautifulSoup

def read_kml():

with open('./geo//Talhoes.kml', 'r') as f:
    root = parser.parse(f).getroot()
namespace = {"kml": 'http://www.opengis.net/kml/2.2'}
pms = root.xpath(".//kml:Placemark[.//kml:Polygon]", namespaces=namespace)
for p in pms:
    print(p.Polygon.outerBoundaryIs.LinearRing.coordinates)

kml = open('./geo//Talhoes.kml', 'r')
soup = BeautifulSoup(kml, 'xml')

if (root.Document.Style.IconStyle.id == "id value"):
    print(f'Estilo Color {root.Document.Style.IconStyle.color}')
    print(f'Estilo Scale: {root.Document.Style.IconStyle.scale}')
    print(f'Estilo Icon: {root.Document.Style.IconStyle.Icon}')
    print(f'Estilo Hotspot: {root.Document.Style.IconStyle.hotSpot}')

read_kml()


text:
Q: Python Webdriver doesn't wait until the page is downloaded in Firefox when used with proxy when I set the Firefox proxy with python webdriver, it doesn't wait until the page is fully downloaded, this doesn't happen when I don't set one. How can I change this behavior? Or how can I check that the page download is over?

A: The simplest thing to do is to poll the page looking for an element you know will be present once the download is complete. The Java webdriver bindings offer a "Wait" class for just this purpose, though there isn't (yet) an analogue for this in the python bindings.


text:
Q: Indirectly referencing equal modules twice I have the following file structure:
(You can clone my GitHub repo to reproduce the error.)
client.ts
|
|-- references lib-a/lib-a.ts
|             |
|             |-- references lib-a/lib-c.d.ts
|
|-- references lib-b/lib-b.ts
              |
              |-- references lib-b/lib-c.d.ts (equal to lib-c.d.ts)

lib.c.d.ts:
declare module "lib-c" {
    interface LibC {
        dummyAttribute: number;
    }
}

Compiling client.ts obviously leads to an error because the same dummyAttribute is declared twice.
lib-b/lib-c.d.ts(3,9): error TS2300: Duplicate identifier 'dummyAttribute'.

Is there any way to force the TypeScript compiler to ignore this error or to "limit" the search for duplicates to one level?
Without touching the compiler, I can only imagine a solution which leads to a situation where lib-a and lib-b are pointing to the same (not to an equal) lib-c file. This is possible via:

*

*Changing lib-a or lib-b. This is a dirty hack since updates will overwrite the changes.

*Deleting lib-a/lib-c.d.ts and placing a symlink to point to lib-b/lib-c.d.ts.

Point 1 works, of course.
Point 2 didn't work for me. After executing mklink lib-b/lib-c.d.ts lib-a/lib-c.d.ts (on Windows), the TypeScript compiler still outputted the same duplicate identifier error.
How can I reference two modules referencing equal (but not the same) dependencies themselves?

A: The solution to this is to ensure that dependencies are managed in a predictable way.
For example, if you use .d.ts files from Definitely Typed and load them through NuGet, they use package dependencies to ensure you only get one copy of each dependency.
Let's take jQuery as an example.
If we packaged jQuery along with each library that needed it, we would end up exactly in the situation you describe:
- /Scripts
- - /jqueryui
- - - jquery.ui.d.ts
- - - jquery.d.ts
- - /jquerymobile
- - - jquerymobile.d.ts
- - - jquery.d.ts

This causes a problem because this introduces duplicate definitions. In the case of "they are both the same library" you might argue that you want to ignore them, but if two entirely different libraries were competing for the same name in the global namespace, you are going to get runtime problems.
To solve the case that you describe, when installing the NuGet packages for jQuery UI and jQuery mobile (as in the example above), you actually end up with the following result:
- /Scripts
- - /jqueryui
- - - jquery.ui.d.ts
- - /jquerymobile
- - - jquerymobile.d.ts
- - /jquery
- - - jquery.d.ts

And this is the correct way to share a dependency.
This structure is also reflected in the Definitely Typed repository, so both jQuery UI and jQuery mobile point to the same relative jQuery definition.
I'm not sure how something can be "equal but not the same" as in your question - perhaps you have libraries depending on different versions of the same thing... the answer to that question will largely depend on how you are solving the runtime problem (for example, if you are using two versions of jQuery, you are probably assigning one version to a different name in the global scope to avoid the clash, in which case you'd need a modified version of jquery.d.ts with that global name too).


text:
Q: Using AChartEngine, can left axis grid be a different color than the right axis grid? I am using AChartEngine to have two Y-Axis. The problem I'm having is that the two axis do not line up, and it is extremely confusing what line is for what axis. The 0 points don't even line up.
    renderer.setApplyBackgroundColor(true);
    renderer.setBackgroundColor(Color.BLACK);

    renderer.setAxesColor(Color.LTGRAY);
    renderer.setPointSize(14);

    renderer.setChartTitle( "Waves" );

    renderer.setShowGrid(true);
    renderer.setXLabels( 10 );
    renderer.setYLabels( 10 );
    renderer.setXLabelsAlign(Align.RIGHT);
    renderer.setYLabelsAlign(Align.RIGHT, 0);
    renderer.setZoomButtonsVisible(true);
    renderer.setPanLimits(new double[] { vdiMin, vdiMax, netMin, netMax });
    renderer.setZoomLimits(new double[] { vdiMin, vdiMax, netMin, netMax });
    renderer.setZoomRate(1.05f);

    renderer.setLabelsColor(Color.WHITE);
    renderer.setXLabelsColor(Color.WHITE);
    renderer.setYLabelsColor(0, Color.WHITE);
    renderer.setYLabelsColor(1, Color.WHITE);

    if( spinnerChoice == 0 ) {
        renderer.setYTitle("Diff Volts", 1);
    } else {
        renderer.setYTitle( "Current", 1 );
    }
    renderer.setYTitle( "Net Volts", 0 );
    renderer.setYAxisAlign(Align.RIGHT, 1);
    renderer.setYLabelsAlign(Align.LEFT, 1);

Does anyone know a way to line up the two axis at 0, or draw the gridlines different colors?
Using renderer.setAxesColor( Color.LTGRAY ), I tried adjusting it to use the scaling number, but it did not work.
renderer.setAxesColor( Color.LTGRAY, 1 );
    or
renderer.setAxesColor( 1, Color.LTGRAY );

A: As of now, there is no way to have the separate Y-axis have different color grid lines.

A: You can set some Y fixed ranges for both such as they line up. For instance:
renderer.setYAxisMin(0, 0);
renderer.setYAxisMax(10, 0);
renderer.setYAxisMin(0, 1);
renderer.setYAxisMax(100, 1);

For setting the grid color you need to call renderer.setGridColor(color), but this has no support for multiple scales yet.


text:
Q: Error Acces Violation al tratar de consumir un Servicio Web SOAP desde un IOS de 64-Bits He tenido un problema desde marzo de este año y es que al tratar de consumir un Web Service hecho en C# desde una App hecha en Delphi me manda una Access Violation siempre que hago la llamada a cualquier método de dicho servicio. La unidad del servicio web se importó utilizando el Wizard de Embarcadero Rad Studio, lo que me genera varios métodos ttremotable.
No obstante la aplicación funciona en Windows, MacOS, Android y dispositivos IOS de 32-Bits, pero siempre falla en dispositivos IOS de 64-Bits. He actualizado las versiones de Embarcadero Rad Studio pero el problema persiste.
El código lo dejo a continuación, omití algunos métodos porque el cuerpo era demasiado grande para publicar.
  ArrayOfClDetallePedidoComercial = array of clDetallePedidoComercial;   { "http://tempuri.org/"[GblCplx] }

  // ************************************************************************ //
  // XML       : clPagoMaestroComercial, global, <complexType>
  // Namespace : http://tempuri.org/
  // ************************************************************************ //
  clPagoMaestroComercial = class(TRemotable)
  private
    FIdFormaPago: Integer;
    FReferenciaPago: string;
    FReferenciaPago_Specified: boolean;
    FFechaHoraPago: TXSDateTime;
    FImporte: TXSDecimal;
    FIdReferencia: Integer;
    FTipoReferencia: string;
    FTipoReferencia_Specified: boolean;
    FFormaPago: string;
    FFormaPago_Specified: boolean;
    procedure SetReferenciaPago(Index: Integer; const Astring: string);
    function  ReferenciaPago_Specified(Index: Integer): boolean;
    procedure SetTipoReferencia(Index: Integer; const Astring: string);
    function  TipoReferencia_Specified(Index: Integer): boolean;
    procedure SetFormaPago(Index: Integer; const Astring: string);
    function  FormaPago_Specified(Index: Integer): boolean;
  public
    destructor Destroy; override;
  published
    property IdFormaPago:    Integer      read FIdFormaPago write FIdFormaPago;
    property ReferenciaPago: string       Index (IS_OPTN) read FReferenciaPago write SetReferenciaPago stored ReferenciaPago_Specified;
    property FechaHoraPago:  TXSDateTime  read FFechaHoraPago write FFechaHoraPago;
    property Importe:        TXSDecimal   read FImporte write FImporte;
    property IdReferencia:   Integer      read FIdReferencia write FIdReferencia;
    property TipoReferencia: string       Index (IS_OPTN) read FTipoReferencia write SetTipoReferencia stored TipoReferencia_Specified;
    property FormaPago:      string       Index (IS_OPTN) read FFormaPago write SetFormaPago stored FormaPago_Specified;
  end;

  // ************************************************************************ //
  // XML       : clDetallePedidoComercial, global, <complexType>
  // Namespace : http://tempuri.org/
  // ************************************************************************ //
  clDetallePedidoComercial = class(TRemotable)
  private
    FIdPedido: Integer;
    FIdProducto: Integer;
    FCantidad: TXSDecimal;
    FPrecioUnitario: TXSDecimal;
    FInicial: TXSDecimal;
    FActual: TXSDecimal;
    FCambios: TXSDecimal;
    FNumeroProducto: string;
    FNumeroProducto_Specified: boolean;
    FProducto: string;
    FProducto_Specified: boolean;
    FDescripProducto: string;
    FDescripProducto_Specified: boolean;
    FPorcDescuento: TXSDecimal;
    FImpuestos: TXSDecimal;
    FSubTotal: TXSDecimal;
    FImporte: TXSDecimal;
    FIdDetallePedido: Integer;
    FIEPS: TXSDecimal;
    FDescuento: TXSDecimal;
    procedure SetNumeroProducto(Index: Integer; const Astring: string);
    function  NumeroProducto_Specified(Index: Integer): boolean;
    procedure SetProducto(Index: Integer; const Astring: string);
    function  Producto_Specified(Index: Integer): boolean;
    procedure SetDescripProducto(Index: Integer; const Astring: string);
    function  DescripProducto_Specified(Index: Integer): boolean;
  public
    destructor Destroy; override;
  published
    property IdPedido:        Integer     read FIdPedido write FIdPedido;
    property IdProducto:      Integer     read FIdProducto write FIdProducto;
    property Cantidad:        TXSDecimal  read FCantidad write FCantidad;
    property PrecioUnitario:  TXSDecimal  read FPrecioUnitario write FPrecioUnitario;
    property Inicial:         TXSDecimal  read FInicial write FInicial;
    property Actual:          TXSDecimal  read FActual write FActual;
    property Cambios:         TXSDecimal  read FCambios write FCambios;
    property NumeroProducto:  string      Index (IS_OPTN) read FNumeroProducto write SetNumeroProducto stored NumeroProducto_Specified;
    property Producto:        string      Index (IS_OPTN) read FProducto write SetProducto stored Producto_Specified;
    property DescripProducto: string      Index (IS_OPTN) read FDescripProducto write SetDescripProducto stored DescripProducto_Specified;
    property PorcDescuento:   TXSDecimal  read FPorcDescuento write FPorcDescuento;
    property Impuestos:       TXSDecimal  read FImpuestos write FImpuestos;
    property SubTotal:        TXSDecimal  read FSubTotal write FSubTotal;
    property Importe:         TXSDecimal  read FImporte write FImporte;
    property IdDetallePedido: Integer     read FIdDetallePedido write FIdDetallePedido;
    property IEPS:            TXSDecimal  read FIEPS write FIEPS;
    property Descuento:       TXSDecimal  read FDescuento write FDescuento;
  end;

  // ************************************************************************ //
  // XML       : clZonaComercial, global, <complexType>
  // Namespace : http://tempuri.org/
  // ************************************************************************ //
  clZonaComercial = class(TRemotable)
  private
    FIdZona: Integer;
    FNombre: string;
    FNombre_Specified: boolean;
    procedure SetNombre(Index: Integer; const Astring: string);
    function  Nombre_Specified(Index: Integer): boolean;
  published
    property IdZona: Integer  read FIdZona write FIdZona;
    property Nombre: string   Index (IS_OPTN) read FNombre write SetNombre stored Nombre_Specified;
  end;

  ArrayOfClZonaComercial = array of clZonaComercial;   { "http://tempuri.org/"[GblCplx] }

  // ************************************************************************ //
  // XML       : clPedidoComercial, global, <complexType>
  // Namespace : http://tempuri.org/
  // ************************************************************************ //
  clPedidoComercial = class(TRemotable)
  private
    FIdPedido: Integer;
    FFechaHora: TXSDateTime;
    FIdCliente: Integer;
    FFotoA: TByteDynArray;
    FFotoA_Specified: boolean;
    FFotoD: TByteDynArray;
    FFotoD_Specified: boolean;
    FLatA: Single;
    FLonA: Single;
    FLatD: Single;
    FLonD: Single;
    FFechaHoraTermino: TXSDateTime;
    FImporteTotal: TXSDecimal;
    FSaldo: TXSDecimal;
    FImportePagado: TXSDecimal;
    FRazonSocial: string;
    FRazonSocial_Specified: boolean;
    FReferencia: string;
    FReferencia_Specified: boolean;
    FSubTotal: TXSDecimal;
    FImporteImpuestos: TXSDecimal;
    FImporteImpuestosEsp: TXSDecimal;
    Fobservaciones: string;
    Fobservaciones_Specified: boolean;
    procedure SetFotoA(Index: Integer; const ATByteDynArray: TByteDynArray);
    function  FotoA_Specified(Index: Integer): boolean;
    procedure SetFotoD(Index: Integer; const ATByteDynArray: TByteDynArray);
    function  FotoD_Specified(Index: Integer): boolean;
    procedure SetRazonSocial(Index: Integer; const Astring: string);
    function  RazonSocial_Specified(Index: Integer): boolean;
    procedure SetReferencia(Index: Integer; const Astring: string);
    function  Referencia_Specified(Index: Integer): boolean;
    procedure Setobservaciones(Index: Integer; const Astring: string);
    function  observaciones_Specified(Index: Integer): boolean;
  public
    destructor Destroy; override;
  published
    property IdPedido:            Integer        read FIdPedido write FIdPedido;
    property FechaHora:           TXSDateTime    read FFechaHora write FFechaHora;
    property IdCliente:           Integer        read FIdCliente write FIdCliente;
    property FotoA:               TByteDynArray  Index (IS_OPTN) read FFotoA write SetFotoA stored FotoA_Specified;
    property FotoD:               TByteDynArray  Index (IS_OPTN) read FFotoD write SetFotoD stored FotoD_Specified;
    property LatA:                Single         read FLatA write FLatA;
    property LonA:                Single         read FLonA write FLonA;
    property LatD:                Single         read FLatD write FLatD;
    property LonD:                Single         read FLonD write FLonD;
    property FechaHoraTermino:    TXSDateTime    read FFechaHoraTermino write FFechaHoraTermino;
    property ImporteTotal:        TXSDecimal     read FImporteTotal write FImporteTotal;
    property Saldo:               TXSDecimal     read FSaldo write FSaldo;
    property ImportePagado:       TXSDecimal     read FImportePagado write FImportePagado;
    property RazonSocial:         string         Index (IS_OPTN) read FRazonSocial write SetRazonSocial stored RazonSocial_Specified;
    property Referencia:          string         Index (IS_OPTN) read FReferencia write SetReferencia stored Referencia_Specified;
    property SubTotal:            TXSDecimal     read FSubTotal write FSubTotal;
    property ImporteImpuestos:    TXSDecimal     read FImporteImpuestos write FImporteImpuestos;
    property ImporteImpuestosEsp: TXSDecimal     read FImporteImpuestosEsp write FImporteImpuestosEsp;
    property observaciones:       string         Index (IS_OPTN) read Fobservaciones write Setobservaciones stored observaciones_Specified;
  end;

  ArrayOfClPagoComercial = array of clPagoComercial;   { "http://tempuri.org/"[GblCplx] }
  ArrayOfClPagoMaestroComercial = array of clPagoMaestroComercial;   { "http://tempuri.org/"[GblCplx] }

  // ************************************************************************ //
  // XML       : clPagoComercial, global, <complexType>
  // Namespace : http://tempuri.org/
  // ************************************************************************ //
  clPagoComercial = class(TRemotable)
  private
    FIdReferencia: Integer;
    FIdFormaPago: Integer;
    FFechaHoraPago: TXSDateTime;
    FReferenciaPago: string;
    FReferenciaPago_Specified: boolean;
    FImporte: TXSDecimal;
    FFormaPago: string;
    FFormaPago_Specified: boolean;
    procedure SetReferenciaPago(Index: Integer; const Astring: string);
    function  ReferenciaPago_Specified(Index: Integer): boolean;
    procedure SetFormaPago(Index: Integer; const Astring: string);
    function  FormaPago_Specified(Index: Integer): boolean;
  public
    destructor Destroy; override;
  published
    property IdReferencia:   Integer      read FIdReferencia write FIdReferencia;
    property IdFormaPago:    Integer      read FIdFormaPago write FIdFormaPago;
    property FechaHoraPago:  TXSDateTime  read FFechaHoraPago write FFechaHoraPago;
    property ReferenciaPago: string       Index (IS_OPTN) read FReferenciaPago write SetReferenciaPago stored ReferenciaPago_Specified;
    property Importe:        TXSDecimal   read FImporte write FImporte;
    property FormaPago:      string       Index (IS_OPTN) read FFormaPago write SetFormaPago stored FormaPago_Specified;
  end;

  // ************************************************************************ //
  // Namespace : http://tempuri.org/
  // soapAction: http://tempuri.org/%operationName%
  // transport : http://schemas.xmlsoap.org/soap/http
  // style     : document
  // use       : literal
  // binding   : wsComercialSoap
  // service   : wsComercial
  // port      : wsComercialSoap
  // URL       : http://www.ideasys.com.mx/ideaposws/wsComercial.asmx
  // ************************************************************************ //
  wsComercialSoap = interface(IInvokable)
  ['{1A05E5F4-63DC-6861-5FB7-9D690032A85A}']
    function  ObtenerClientes(const licencia: string; const usuario: string; const clave: string; const nombreCliente: string; const idDispositivo: string): ArrayOfClClienteComercial; stdcall;
    function  ObtenerProductos(const licencia: string; const usuario: string; const clave: string; const descripProducto: string; const idDispositivo: string): ArrayOfClProductoComercial; stdcall;
    function  AgregarCliente(const licencia: string; const usuario: string; const clave: string; const nombre: string; const lista: Integer; const CNOMBRECALLE: string;
                             const CNUMEROEXTERIOR: string; const CNUMEROINTERIOR: string; const CCOLONIA: string; const CCODIGOPOSTAL: string; const CTELEFONO1: string;
                             const CTELEFONO2: string; const CTELEFONO3: string; const CEMAIL: string; const CDIRECCIONWEB: string; const CPAIS: string;
                             const CESTADO: string; const CCIUDAD: string; const CMUNICIPIO: string; const FrecuenciaVisita: Integer; const idDispositivo: string;
                             const idZona: Integer): respuesta; stdcall;
    function  AgregarPedido(const licencia: string; const usuario: string; const clave: string; const FechaHora: TXSDateTime; const idCliente: Integer; const fotoA: TByteDynArray;
                            const fotoD: TByteDynArray; const latA: Single; const lonA: Single; const latD: Single; const lonD: Single;
                            const FechaHoraTermino: TXSDateTime; const observaciones: string; const idDispositivo: string): respuesta; stdcall;
    function  AgregarDetallePedido(const licencia: string; const usuario: string; const clave: string; const idPedido: Integer; const idProducto: Integer; const cantidad: TXSDecimal;
                                   const precioUnitario: TXSDecimal; const cantidadInicial: TXSDecimal; const cantidadActual: TXSDecimal; const cantidadCambios: TXSDecimal; const idDispositivo: string
                                   ): respuesta; stdcall;
    function  AgregarPagoMaestro(const licencia: string; const usuario: string; const clave: string; const formaPago: string; const referenciaPago: string; const fechaPago: TXSDateTime;
                                 const importe: TXSDecimal; const idReferencia: Integer; const tipoReferencia: string; const idDispositivo: string): respuesta; stdcall;
    function  ObtenerSaldoPorClienteyPedido(const licencia: string; const usuario: string; const clave: string; const idCliente: Integer; const idPedido: Integer; const idDispositivo: string
                                            ): respuesta; stdcall;
    function  ObtenerPedidosConSaldo(const licencia: string; const usuario: string; const clave: string; const idDispositivo: string): ArrayOfClPedidoComercial; stdcall;
    function  ObtenerPagosPorPedido(const licencia: string; const usuario: string; const clave: string; const idPedido: Integer; const idDispositivo: string): ArrayOfClPagoComercial; stdcall;
    function  ObtenerPagosMaestros(const licencia: string; const usuario: string; const clave: string; const idDispositivo: string): ArrayOfClPagoMaestroComercial; stdcall;
    function  ObtenerDetallesPedidoPorPedido(const licencia: string; const usuario: string; const clave: string; const idPedido: Integer; const idDispositivo: string): ArrayOfClDetallePedidoComercial; stdcall;
    function  ModificarReferenciaPedido(const licencia: string; const usuario: string; const clave: string; const idPedido: Integer; const referencia: string; const idDispositivo: string
                                        ): respuesta; stdcall;
    function  ObtenerPedidosConSaldoPorFechas(const licencia: string; const usuario: string; const clave: string; const fechaInicial: TXSDateTime; const fechaFinal: TXSDateTime; const idDispositivo: string
                                              ): ArrayOfClPedidoComercial; stdcall;
    function  ObtenerProductosPorVendedor(const licencia: string; const usuario: string; const clave: string; const descripProducto: string; const idDispositivo: string): ArrayOfClProductoComercial; stdcall;
    function  ObtenerZonas(const licencia: string; const usuario: string; const clave: string; const idDispositivo: string): ArrayOfClZonaComercial; stdcall;
    function  AgregarCliente2(const licencia: string; const usuario: string; const clave: string; const nombre: string; const lista: Integer; const CNOMBRECALLE: string;
                              const CNUMEROEXTERIOR: string; const CNUMEROINTERIOR: string; const CCOLONIA: string; const CCODIGOPOSTAL: string; const CTELEFONO1: string;
                              const CTELEFONO2: string; const CTELEFONO3: string; const CEMAIL: string; const CDIRECCIONWEB: string; const CPAIS: string;
                              const CESTADO: string; const CCIUDAD: string; const CMUNICIPIO: string; const FrecuenciaVisita: Integer; const idDispositivo: string;
                              const idZona: Integer): Integer; stdcall;
  end;

function GetwsComercialSoap(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): wsComercialSoap;

implementation
  uses System.SysUtils;

function GetwsComercialSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): wsComercialSoap;
const
  defWSDL = 'http://www.ideasys.com.mx/ideaposws/wsComercial.asmx?WSDL';
  defURL  = 'http://www.ideasys.com.mx/ideaposws/wsComercial.asmx';
  defSvc  = 'wsComercial';
  defPrt  = 'wsComercialSoap';
var
  RIO: THTTPRIO;
begin
  Result := nil;
  if (Addr = '') then
  begin
    if UseWSDL then
      Addr := defWSDL
    else
      Addr := defURL;
  end;
  if HTTPRIO = nil then
    RIO := THTTPRIO.Create(nil)
  else
    RIO := HTTPRIO;
  try
    Result := (RIO as wsComercialSoap);
    if UseWSDL then
    begin
      RIO.WSDLLocation := Addr;
      RIO.Service := defSvc;
      RIO.Port := defPrt;
    end else
      RIO.URL := Addr;
  finally
    if (Result = nil) and (HTTPRIO = nil) then
      RIO.Free;
  end;
end;

initialization
  { wsComercialSoap }
  InvRegistry.RegisterInterface(TypeInfo(wsComercialSoap), 'http://tempuri.org/', 'utf-8');
  InvRegistry.RegisterDefaultSOAPAction(TypeInfo(wsComercialSoap), 'http://tempuri.org/%operationName%');
  InvRegistry.RegisterInvokeOptions(TypeInfo(wsComercialSoap), ioDocument);
  { wsComercialSoap.ObtenerClientes }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'ObtenerClientes', '',
                                 '[ReturnName="ObtenerClientesResult"]', IS_OPTN);
  InvRegistry.RegisterParamInfo(TypeInfo(wsComercialSoap), 'ObtenerClientes', 'ObtenerClientesResult', '',
                                '[ArrayItemName="clClienteComercial"]');
  { wsComercialSoap.ObtenerProductos }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'ObtenerProductos', '',
                                 '[ReturnName="ObtenerProductosResult"]', IS_OPTN);
  InvRegistry.RegisterParamInfo(TypeInfo(wsComercialSoap), 'ObtenerProductos', 'ObtenerProductosResult', '',
                                '[ArrayItemName="clProductoComercial"]');
  { wsComercialSoap.AgregarCliente }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'AgregarCliente', '',
                                 '[ReturnName="AgregarClienteResult"]', IS_OPTN);
  { wsComercialSoap.AgregarPedido }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'AgregarPedido', '',
                                 '[ReturnName="AgregarPedidoResult"]', IS_OPTN);
  { wsComercialSoap.AgregarDetallePedido }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'AgregarDetallePedido', '',
                                 '[ReturnName="AgregarDetallePedidoResult"]', IS_OPTN);
  { wsComercialSoap.AgregarPagoMaestro }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'AgregarPagoMaestro', '',
                                 '[ReturnName="AgregarPagoMaestroResult"]', IS_OPTN);
  { wsComercialSoap.ObtenerSaldoPorClienteyPedido }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'ObtenerSaldoPorClienteyPedido', '',
                                 '[ReturnName="ObtenerSaldoPorClienteyPedidoResult"]', IS_OPTN);
  { wsComercialSoap.ObtenerPedidosConSaldo }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'ObtenerPedidosConSaldo', '',
                                 '[ReturnName="ObtenerPedidosConSaldoResult"]', IS_OPTN);
  InvRegistry.RegisterParamInfo(TypeInfo(wsComercialSoap), 'ObtenerPedidosConSaldo', 'ObtenerPedidosConSaldoResult', '',
                                '[ArrayItemName="clPedidoComercial"]');
  { wsComercialSoap.ObtenerPagosPorPedido }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'ObtenerPagosPorPedido', '',
                                 '[ReturnName="ObtenerPagosPorPedidoResult"]', IS_OPTN);
  InvRegistry.RegisterParamInfo(TypeInfo(wsComercialSoap), 'ObtenerPagosPorPedido', 'ObtenerPagosPorPedidoResult', '',
                                '[ArrayItemName="clPagoComercial"]');
  { wsComercialSoap.ObtenerPagosMaestros }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'ObtenerPagosMaestros', '',
                                 '[ReturnName="ObtenerPagosMaestrosResult"]', IS_OPTN);
  InvRegistry.RegisterParamInfo(TypeInfo(wsComercialSoap), 'ObtenerPagosMaestros', 'ObtenerPagosMaestrosResult', '',
                                '[ArrayItemName="clPagoMaestroComercial"]');
  { wsComercialSoap.ObtenerDetallesPedidoPorPedido }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'ObtenerDetallesPedidoPorPedido', '',
                                 '[ReturnName="ObtenerDetallesPedidoPorPedidoResult"]', IS_OPTN);
  InvRegistry.RegisterParamInfo(TypeInfo(wsComercialSoap), 'ObtenerDetallesPedidoPorPedido', 'ObtenerDetallesPedidoPorPedidoResult', '',
                                '[ArrayItemName="clDetallePedidoComercial"]');
  { wsComercialSoap.ModificarReferenciaPedido }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'ModificarReferenciaPedido', '',
                                 '[ReturnName="ModificarReferenciaPedidoResult"]', IS_OPTN);
  { wsComercialSoap.ObtenerPedidosConSaldoPorFechas }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'ObtenerPedidosConSaldoPorFechas', '',
                                 '[ReturnName="ObtenerPedidosConSaldoPorFechasResult"]', IS_OPTN);
  InvRegistry.RegisterParamInfo(TypeInfo(wsComercialSoap), 'ObtenerPedidosConSaldoPorFechas', 'ObtenerPedidosConSaldoPorFechasResult', '',
                                '[ArrayItemName="clPedidoComercial"]');
  { wsComercialSoap.ObtenerProductosPorVendedor }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'ObtenerProductosPorVendedor', '',
                                 '[ReturnName="ObtenerProductosPorVendedorResult"]', IS_OPTN);
  InvRegistry.RegisterParamInfo(TypeInfo(wsComercialSoap), 'ObtenerProductosPorVendedor', 'ObtenerProductosPorVendedorResult', '',
                                '[ArrayItemName="clProductoComercial"]');
  { wsComercialSoap.ObtenerZonas }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'ObtenerZonas', '',
                                 '[ReturnName="ObtenerZonasResult"]', IS_OPTN);
  InvRegistry.RegisterParamInfo(TypeInfo(wsComercialSoap), 'ObtenerZonas', 'ObtenerZonasResult', '',
                                '[ArrayItemName="clZonaComercial"]');
  { wsComercialSoap.AgregarCliente2 }
  InvRegistry.RegisterMethodInfo(TypeInfo(wsComercialSoap), 'AgregarCliente2', '',
                                 '[ReturnName="AgregarCliente2Result"]');
  RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfClPedidoComercial), 'http://tempuri.org/', 'ArrayOfClPedidoComercial');
  RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfClClienteComercial), 'http://tempuri.org/', 'ArrayOfClClienteComercial');
  RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfClProductoComercial), 'http://tempuri.org/', 'ArrayOfClProductoComercial');
  RemClassRegistry.RegisterXSClass(clClienteComercial, 'http://tempuri.org/', 'clClienteComercial');
  RemClassRegistry.RegisterXSClass(respuesta, 'http://tempuri.org/', 'respuesta');
  RemClassRegistry.RegisterXSClass(clProductoComercial, 'http://tempuri.org/', 'clProductoComercial');
  RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfClDetallePedidoComercial), 'http://tempuri.org/', 'ArrayOfClDetallePedidoComercial');
  RemClassRegistry.RegisterXSClass(clPagoMaestroComercial, 'http://tempuri.org/', 'clPagoMaestroComercial');
  RemClassRegistry.RegisterXSClass(clDetallePedidoComercial, 'http://tempuri.org/', 'clDetallePedidoComercial');
  RemClassRegistry.RegisterXSClass(clZonaComercial, 'http://tempuri.org/', 'clZonaComercial');
  RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfClZonaComercial), 'http://tempuri.org/', 'ArrayOfClZonaComercial');
  RemClassRegistry.RegisterXSClass(clPedidoComercial, 'http://tempuri.org/', 'clPedidoComercial');
  RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfClPagoComercial), 'http://tempuri.org/', 'ArrayOfClPagoComercial');
  RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfClPagoMaestroComercial), 'http://tempuri.org/', 'ArrayOfClPagoMaestroComercial');
  RemClassRegistry.RegisterXSClass(clPagoComercial, 'http://tempuri.org/', 'clPagoComercial');

end.

A: Si el Webservice funciona para otros dispositivos, tu problema no va a estar en el Webservice sino en cómo te conectas o comunicas desde el dispositivo que falla.
Hace tiempo hice una aplicación en Delphi (.NET), tenía que consumir un Webservices (Java) y me encontré con un caso parecido. Asegúrate de esto:

*

*En el fichero de configuración de tu aplicación para dispositivos iOS de 64-bit, verifica los "bindings" en la sección: <system.serviceModel>, son distintos dependiendo del tipo de conexión.

*A mí lo que me dio solución fue en vez de conectarme al Webservice utilizando los bindings, enviar las peticiones en un fichero XML mediante un WebRequest con cabeceras de autenticación.
Espero haberte ayudado.

A: Muchas gracias por sus comentarios, me comunique con la gente de Apple para que me platicaran el proceso que seguían para probar mi App. Por fin pude dar con el problema, este era que mi aplicación no soporta IPV6 por lo que en cada llamado al WS fallaba mandando un Acces Violation. Sin embargo, al estar conectado a una red IPV4 si funcionaba correctamente. La gente en Apple se ha puesto bastante estricta en este tema ya que si tu quieres tu App en el AppStore tienes que soportar ambos estándares, pues bueno no me queda de otra que realizar cambios generales. Muchas gracias a todos nuevamente por sus comentarios.


text:
Q: Create tags file for latex for labels and bib items I'm using ctags to create a tags file for use in Vim, so that I can jump to definitions of labels and citations. However, I have two problems:

*

*ctags includes \ref in the tags file, so when I hit jump on a \ref label, I don't necessarily jump to the definition of the label, but might end up on another reference to that label.

*I'd like to be able to jump to the corresponding entry in a .bib file from a \cite command, but ctags doesn't generate entries for that (I'm using ctags *.tex *.bib).

I wanted to redefine ctags's definition for tex files, so that I could remove \ref entries, but that didn't work.
My ~/.ctags file:
--langdef=tex2
--langmap=tex2:.tex
--regex-tex2=/\\label[ \t]*\*?\{[ \t]*([^}]*)\}/\1/l,label/

A: I realized that I didn't use exuberant ctags, but another ctags program, so the content in ~/.ctags was never used.
I also managed to add another entry in ~/.ctags for bib entries:
--langdef=tex2
--langmap=tex2:.tex
--regex-tex2=/\\label[ \t]*\*?\{[ \t]*([^}]*)\}/\1/l,label/

--langdef=bib
--langmap=bib:.bib
--regex-bib=/^@[A-Za-z]+\{([^,]*)/\1/b,bib/

ctags *.tex *.bib works now as I want it.
You can put a regex into an online regex explainer to understand what it is doing, like https://regexr.com/.


text:
Q: trivial and POD types with user-defined constructors First of all, this is more of a sanity check question to get some approval by people better-versed in the depths of the language standard than me.
Let's say I have the following types (though I left out any non-constructor and non-assignment member functions):
template<typename E> struct half_expr
{
};

class half : public half_expr<half>
{
public:
    half();
    explicit half(float);
    template<typename E> half(const half_expr<E>&);

    half& operator=(float);
    template<typename E> half& operator=(const half_expr<E>&);

private:
    half(std::uint16_t, bool);

    std::uint16_t data_;
};

Well, on any reasonable implementation a half shouldn't be anything else in memory than a plain std::uint16_t. But I'm interrested in the guarantees from the standard. Here is my rationale according to the C++98/03 defition of POD:

*

*half cannot be a POD type, since it is has non-public fields, base-classes and user-defined constructors.

and the C++11 losened/extended definitions:

*

*It should be trivially copyable, since it has only implicitly generated copy/move constructors/assignments, but only as long as those float and template versions don't count in any way, which I'm not completely sure of.

*It should also be standard layout, since it only has a single private field of fundamental type and a single empty non-virtual base class (which should be POD in any standard, right?)

*The only thing that hinders a POD-classification is that it is not trivially default constructible, which might IMHO be overcome by using C++11's half() = default syntax.
My quite simple question is just: Is my rationale entirely correct or are there any things I overlooked or misinterpreted in the definitions, especially in light of the user-defined constructors and assignments somehow hindering a classification as trivially copyable?
Note: Even if you feel the urge to delegate this to some possible duplicate about POD and standard-layout types (which I could prefectly understand), a simple comment answering my actual question would still be nice, since this is a mere sanity check, which might occur simple or superflous to you, but I just want to be on the safe side.

A: Yes, half is standard-layout (9/7): the base class is empty, the derived class has the same access control for all non-static data, there's nothing virtual and no non-standard-layout bases or members, and the base is a different type from the first non-static data member.
The constructors and assignment operators that you define are not copy (or move) constructors and assignments, so they have no bearing on whether the class is trivially copyable.
The default constructor is non-trivial because it is user-provided (12.1/5), and so the class is not trivial.
The copies/moves are all trivial because the data member and the empty base have trivial copies/moves (12.8/12). Same for the destructor, and so the class is trivially copyable.
So I believe your analysis is correct - remove the no-arg constructor and you have a POD class in C++11 (but not in C++98).
As Luc says, there is no guarantee in the standard that a POD class contains no padding, even if it has only one data member.
In C++03, the empty base class optimization is permitted, not required, so a poor-quality but conforming C++03 implementation could certainly give you sizeof(half) == sizeof(half_expr<half>) + sizeof(uint16_t). It is guaranteed that sizeof(half_expr<half>) > 0, and if it's smaller than uint16_t you could reasonably expect padding too.
In C++11, the rules on layout-compatibility in effect require that the empty base class optimization is applied -- two standard-layout types in which one has a base class and the other does not, are layout compatible (9.2/17), and layout-compatible types can be read through a union (9.2/19) which means they must have the same layout. Padding is still permitted, but pointless.
The standard aside, your implementation may or may not be working from a C++ ABI that tells you what POD classes look like. If so, I would expect that although the ABI might not be up-to-date for C++11 yet, surely the implementation will make all standard-layout classes look the way POD classes are defined to look, regardless of whether they are also trivial (and it will do the EBC optimization). That's kind of the point of standard-layout: "classes laid out like C structs".
I think that implementations are also permitted to arbitrarily decide that all class types must be 4-aligned, in which case again you'd get padding. I don't think it's reasonable to expect this, though, since the only motivation I can think of for doing it is that you're on some bizarre architecture where 4-aligned pointers can be smaller than char*.


text:
Q: How to force linux to print full path along with timestamp while using find I need to store the full path of a specific file found through find (and successive piped operations on find results). I'm using this:
find "$PWD" . -iname p_*.raw -printf "%Tc %p\n" | sort  | cut -f 7 -d " "

However, as it is it produces shortened file paths "$PWD" doesn't seem to have any effect. Is there any way to force it to show full path?

A: Your solution is close.
You are telling find where to look twice, "$PWD" and .. Drop the second one and add a slash to the first. Add quotes around the name pattern as well.
find "$PWD/" -iname "p_*.raw" ....
You might have an issue with the cut command as well, since it's only selecting one field rather than name and time. Still, your attempt is almost there.


text:
Q: Offline Here maps with MapLoader I'm trying to install the maps here in the application, but when running mapLoader.getMapPackages (); I get nullpointerexception error.
At what point should I do the installation of maps to be available offline?

A: Has the system been initialized via:
com.here.android.mpa.common.MapEngine#init( OnEngineInitListener listener )
or
com.here.android.mpa.mapping.MapFragment#init( OnEngineInitListener listener ) ?
Without initialization, the map loader will not be able to start correctly.


text:
Q: Does the Internal Iterator use the hasNext() and next() to iterate in Java? I'm learning about internal iterators and I understand that an internal iterator manage the iterations in the background:
   public void internalIterator(){
      List<String> namesList = Arrays.asList("Tom", "Dick", "Harry");
      namesList.forEach(name -> System.out.println(name));
   }

But I think that enhanced for loop does the same thing:
 public void enhancedForLoop(){
  List<String> namesList = Arrays.asList("Tom", "Dick", "Harry");
  for(String name : namesList){
    System.out.println(name);
  }
 }

I know that enhanced for loop uses hasNext() and next() methods in the background. And enhanced for loop is an external iterator. Then why forEach() method is an internal iterator? Doesn't forEach() method use hasNext() and next() methods in the background? How the iterations are managed in the backgorund in a different way than enhanced for loop? And is the iteration faster using forEach() than using enhanced for loop? Any feedback will be apreciated?

A: See also the definition of forEach on the interface Iterable.
Both constructs use different methods of the same interface.
Conceptually, the difference is that in an "enhanced for loop" the class implementing the Iterable only creates the Iterator, and the loop construct is responsible for advancing it (see also this related question).
When calling forEach, the class controls the entire process of iteration, and can pick whatever is most suitable for its underlying data structure. For example, it could avoid creating an Iterator object, and instead use some internal array index or similar.
Other than that, they should be equivalent. In most cases I wouldn't expect any difference in performance.
See this excellent answer for some additional reasons why you might want to use forEach, e.g. additional consistency guarantees when iterating synchronized collections, and this one mentioning things that it does not provide, such as flow control (e.g. short-circuiting using break) or support for checked exceptions.

A: The difference is what the user of the API has to do.

Differences
External
When using iterator(), it's the user's job (your job) to manage the traversal: when to call hasNext() and when to call next(). The iteration is handled externally from the API, by the user of the API. The user both iterates through the elements & consumes the elements.
Internal
When using forEach, it's the API's job to manage the traversal. The iteration is handled internally instead of by the user; the user only consumes the elements.

Conclusion
It doesn't matter if hasNext() and next() are being called. What does matter is who calls hasNext() and next() - who handles the iteration, who is in charge of the iterator.
forEach is internal because the user doesn't have control over how the elements are iterated through. The API handles it; the iterator is internal.
iterator() is external because the user must define how iteration will occur. The API passes you the iterator, and that's all the API does. The iterator is external.
Even though forEach uses iterator() in some cases, that iterator is still internal to the API you're using (the List). Whoever calls forEach still only worry about consuming elements. The user doesn't control how the elements are traversed through, so it doesn't matter what forEach uses.

Suggestions on when to use a strategy
You'd use an enhanced loop when you need the most basic of sequential iteration.
You'd use an iterator() when you need more complex iteration.
You'd use forEach when you're only worried about consuming the elements, and don't mind if the API decides on how to traverse through the collection.

A: I don't know where you got that "enhanced for loop is an external iterator", but Iterable.forEach just does the same thing as your second example (could be overridden, though I don't see any reason to).
default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}


text:
Q: PHP: E_RECOVERABLE_ERROR: Instantiation of 'Closure' is not allowed? Hello unfortunatly I cannot find much information on this error on Google and I wonder what the problem is. I have an array containing a lot of information, including some closures (code example is shortened):
$create_info = array (
'foo' => 'bar',
'create_connection_object' => function ($my_key,$foreign_key) {
     return new ApConnection(intval($my_key), intval($foreign_key));
},
'hello' => 'world'
);

Then I have a method using this array depending on the context:
$create_connection_object = $create_info['create_connection_object'];
$con = new $create_connection_object(intval($request->first_id),intval($request->second_id));

When executing this code I get the following error:
"E_RECOVERABLE_ERROR: Instantiation of 'Closure' is not allowed"

In another context I got something working which looks quite similar (closure from array) and instantiated dynamically. Does anybody know a reason why this may fail?

A: 4 o'clock projects are usually the most productive. And this is actually a pretty neat reference question on this specific error message.
Your $create_connection_object() closure is misunderstood by PHP.
 = new $create_connection_object(..)

Would indeed look like = new Closure() to the interpreter, because $create_con_ is already an anonymous function. (It would only work if your variable contained a literal classname string).
The new was redundant, because the callback itself already returns a new ApConnection. So just calling it with $con =new$create_con_() was sufficient to return the object your closure instantiates beforehand.


text:
Q: How to block AWS SQS FIFO while having a message in the deadletter queue? Imagine the following lifetime of an Order.
Order is Paid
Order is Approved
Order is Completed
We chose to use an SQS FIFO to ensure all these messages are processed in the order they are produced, to avoid for example changing the status of an order to Approved only after it was Paid and not after has been Completed.
But let's say that there is an error while trying to Approve an order, and after several attempts the message will be moved to the Deadletter queue.
The problem we noticed is the subsequent message, that is "Order is completed", it is processed, even though the previous message, "Approved", it is in the deadletter queue.
How we should handle this?
Should we check the contents of deadletter queue for having messages with the same MessageGroupID as the consuming one, assuming we could do this?
Is there a mechanism that we are missing?

A: You don't have to block the queue, but rather only add messages when they are good to be processed. If you have a flow in which certain steps (messages to be processed) depend on the success of previous steps, you should make these messages only be added after the previous step (message) succeeds.
Let's say you have an SQS queue with a handler to process the message, it could look something like below.
Since you're using the same FIFO queue for all steps, I'm using the STEP as the MessageGroupId to allow messages of different steps to be processed in parallel (as they could belong to different orders), but the steps of one particular order are always processed in sequence and require the previous one to succeed.

On a side note, you shouldn't need FIFO queues with the approach below, and you could have separate queues with separate handlers for each step.

const sqs = new AWS.SQS();

const STEPS = {
  ORDER_PAID: "ORDER_PAID",
  ORDER_APPROVED: "ORDER_APPROVED",
  ORDER_COMPLETED: "ORDER_COMPLETED",
};

async function sendMessage(step: string, orderId: string) {
  return sqs
    .sendMessage({
      QueueUrl: process.env.YOUR_QUEUE_URL || "",
      MessageGroupId: step,
      MessageBody: JSON.stringify({
        currentStep: step,
        orderId,
      }),
    })
    .promise();
}

exports.handler = async function (event: any, context: any) {
  for (const message of event.Records) {
    const { currentStep, orderId } = JSON.parse(message.body);
    if (currentStep === STEPS.ORDER_PAID) {
      // process order paid, then add next step back to queue
      await sendMessage(STEPS.ORDER_APPROVED, orderId);
    }
    if (currentStep === STEPS.ORDER_APPROVED) {
      // process order approved, then add next step back to queue
      await sendMessage(STEPS.ORDER_COMPLETED, orderId);
    }
    if (currentStep === STEPS.ORDER_COMPLETED) {
      // process order completed
    }
  }
  return context.logStreamName;
};


text:
Q: pytorch nn loading checkpoint and steping scheduler Im trying to load a checkpoint in pytorch neural network and step down the learning rate with scheduler but it's not working and line #1 and line #2 print the same thing. sometimes it gives an error like this  1.1.0 changed this behavior in a BC-breaking way. If you use the learning rate scheduler (calling scheduler.step()) before the optimizer's update (calling optimizer.step()), this will skip the first value of the learning rate schedule. and Im using this code at the end of my training loop in an if statement. if further informations you think is necessary please make a comment. cause I think it's enough right now.
print('<<<back to the best>>>')
loaded_checkpoint=torch.load("checkpoint.pth")
model = NeuralNet(input_size, hidden_size, output_size)
model.load_state_dict(checkpoint['model_state'])
model.to(device)
model.eval()

optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
optimizer.load_state_dict(checkpoint['optim_state'])

print('lr',optimizer.state_dict()['param_groups'][0]['lr']) #1
losss=.9
scheduler.step(losss)
print('<<<back to the best>>>')
print('lr',optimizer.state_dict()['param_groups'][0]['lr']) #2


text:
Q: Why does a reference to a value in previous row throw this Expression.Error? I am trying to perform an operation in Excel using Powerquery.
I want to remove contacts in a list if they are connected to a certain CompanyID but are listed with a different CompanyName.
The fist step is to filter them out by comparing to the row above. They are always listed consecutively.
Next step is to remove all rows containing the value delete in the delete column but unfortunately I do not get to that step.
I have looked at this post and have tried with the following code:
= Table.AddColumn(#"Added index", "Delete", each if [CustomerID]= #"Added index"{[ContactID]-1}[CustomerID] and [CompanyName]<> #"Added index"{[ContactID]-1}[CompanyName] then "delete" else null)

But I get this error:
There were too many elements in the enumeration to complete the operation

I have googled the error and it seems to be connected with duplicated column names but I do not have any of those.
Please help!

A: If you have any steps after the #"Added Index" that manipulate the data, you need to be aware that the current step will refer to the data as it appears in the #"Added Index" step. Any manipulations that you performed after the #"Added index" step will not be available to the statement you posted.
You may want to adjust your posted step to use the latest representation of your data instead of #"Added index".
If #"Added index" is the most recent step in your M code, the statement runs fine, so the problem is that the data is manipulated in the steps in between. Adjust the statement to refer to the most recent data step instead of #"Added index".


text:
Q: Changing int array to char array Hello all I'm having difficulty running some code under various circumstances. I have code that finds how many prime numbers there are, of all the numbers in an array, times how long it takes, and prints how many prime numbers there are. This all works fine, but then I need to run the same code, but with a char array. That is where the problems come in. Here is the code, with an array of ints:
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <stdio.h>
using namespace std;

static const int N = 1000;

int main()
{
    int i, a[N];

    clock_t start = clock();

    for (i = 2; i < N; i++) a[i] = i;
    for (i = 2; i < N; i++)
        if (a[i])
            for (int j = i; j*i < N; j++) a[i*j] = 0;

    start = clock() - start;

    int primes = 0;
    for (i = 2; i < N; i++) {
        if (a[i]) {
            primes++;
            cout << " " << i;
            if (primes % 10 == 0)
                cout << "\n";
        }
    }
    printf("\nIt took %d clicks (%f seconds) to find all prime numbers.\n", start, ((float)start) / CLOCKS_PER_SEC);
    cout << "The number of primes out of " << N << " integers is " << primes << endl;
    return 0;
}

When I simply replace 'int' with "char" for the array, and set 'N' to something like 10, or 100 it works just fine, save for how the prime numbers look. Anything higher and nothing prints off. I know its not as simple as just changing where it says 'int' to 'char' but I am hopelessly lost on the subject. Doesnt help that I need to do this again, but changing the array to type bool (which doesnt make much sense to me either.)
Any kind of insight or simple solution would be wonderful. I will keep searching for something in the meantime. Thanks!

A: The problem is that you're storing i into a[i]. When a is a char array, the maximum value of an element is 127 (if char defaults to signed) or 255 (if it's unsigned), assuming a typical system with 8-bit bytes. If it's signed, overflow results in implementation-defined behavior; if it's unsigned, overflow wraps around modulo 256.
The only thing you care about is whether the value of the element is zero or non-zero, so there's no need to put different values in them. Just initialize them all to 1.
for (i = 2; i < N; i++) a[i] = 1;

This will also work when you change it to boolean.


text:
Q: Jenkins trigger started by user or cron In Jenkins, I want to differentiate between a job that was started by a user or a cron defined by me.
I tried using the:
is_run_by_user = currentBuild.rawBuild.getCause(hudson.model.Cause$UserIdCause)

but still it doesn't work.
Are there other expressions perhaps?

A: In declarative pipelines you can use the Built-in Conditions of the when directive to determine information about what or who triggered the build. In your case you can use the triggeredBy option to create your execution condition. Here is an example:
pipeline {
    agent any
    stages {
        stage('Timer Trigger') {
            when {
                triggeredBy 'TimerTrigger'
            }
            steps {
                echo "Running because triggered by a Timer Trigger (Cron)"
            }
        }
        stage('User Trigger') {
            when {
                triggeredBy cause: "UserIdCause"
            }
            steps {
                echo "Running because triggered by a user"
            }
        }
        stage('Specific User Trigger') {
            when {
                triggeredBy cause: "UserIdCause", detail: "eldarm"
            }
            steps {
                echo "Running because triggered by eldarm"
            }
        }
    }
}

If you don't want to use the build in mechanism you can extract the information yourself using scripted pipeline syntax (use inside a script block in declarative pipelines).
Something like:
// First find the upstream triggered job
def build = currentBuild.rawBuild
def upstreamCause
while (upstreamCause = build.getCause(hudson.model.Cause$UpstreamCause)) {
    build = upstreamCause.upstreamRun
}

// Check if job was triggered by a user
def userIdCause = build.getCause(hudson.model.Cause$UserIdCause)
if(userIdCause) {
   // build was triggered by a user
   def user = userIdCause.userName
   ...
}

See more info in the following answer


text:
Q: username doesn't show when we login login code
<?php
include("koneksi.php");

$email=$_POST['email'];
$password=md5($_POST['password']);

$q="SELECT * FROM `user` WHERE `user`.`email`='$email' AND `user`.`password`='$password'";
$qe=mysql_query($q);

while ($de=mysql_fetch_array($qe)) {
    $id_user=$de['id_user'];
}
if (mysql_num_rows($qe)>0) {
    session_start();
    $_SESSION['x']=$id_users;

    header('location:home.php');
    exit;
} else{
    header('location:login_user.php');
    exit;
}

?>
after login i wanna show or echo the username with this code
<?php
session_start();
$id_user=$_SESSION['x'];

$q="SELECT * FROM `user` WHERE `user`.`id_user`='$id_user'";
$qe=mysql_query($q);
$de=mysql_fetch_array($qe);
    $username=$de['username'];
    echo "

$username

    ";

?>
and the problem is the username doesn't show..
whats wrong.. help me ..

A: You have a typo in your  login search query. Change to $_SESSION['x'] = $id_user;
Not $id_users
A piece of advice,  use an IDE such as netbeans or eclipse or phpstorm.  They help in identifying unused variables and other minor syntax errors.


text:
Q: How to write a recursive function that calculates the net worth of coins after some years? I have a working code, although there's something I can't wrap my head around.
def stonks(coins, rate, years):
    """
    Each year your crypto-investment grows.

    Write a recursive function that calculates the net worth of coins after some years.
    Rate is in percents.
    Round the answer down to the nearest integer.

    stonks(1000, 10, 10) -> 2593
    stonks(100000, 12, 3) -> 140492

    :param coins: starting amount (0-100000)
    :param rate: starting amount (0-100)
    :param years: starting amount (0-50)
    :return: coins after years
    """
    if years is not 0:
        return stonks((coins * (1 + rate / 100)), rate, years - 1)
    else:
        return coins

Expected output:
print(stonks(1000, 10, 10))  # -> 2593
print(stonks(100000, 12, 3))  # -> 140492

My output:
print(stonks(1000, 10, 10))  # -> 2593.742460100001
print(stonks(100000, 12, 3))  # -> 140492.80000000005

If I add math.floor(coins * (1 + rate / 100)) -> My output:
print(stonks(1000, 10, 10))  # -> 2591 --- incorrect, needs to be 2593.
print(stonks(100000, 12, 3))  # -> 140492 --- correct

How is it possible, one of the outputs is floored correctly from 140492.80000000005 to 140492, but the other output 2593.742460100001 is floored incorrectly to 2591?
Is it due to the recursion count being larger and thus the math.floor applies on every event of recursion thus rendering the final output off?

A: You can simply do return stonks((coins * (1 + rate / 100)), rate, years - 1) // 1


text:
Q: Is this sentence in the Future Continuous? Would be obliged if someone could clarify whether the following is in the Future Continuous tense.

The Earth will be three degrees hotter by the year 2050.

It seems so but I need to be absolutely certain.
If it is the case, what rule would I use to describe the tense? So for Future Perfect I could say "The Future Perfect links a time in the future with a time before that". I'm looking for something along those lines if possible.

A: The verb (to be) in your sentence is in Simple Future (also known as Future Indefinite) tense. Some grammarians will argue that English does not have a future tense at all, but if we stick to the traditional EFL classification, will+infinitive means Simple Future. Future continuous is will+be+ing, as in

I will be sitting on this couch the whole day tomorrow.


text:
Q: To get all checked items from a while loop (HTML & PHP) I am hoping that you guys could give me some tips or help on how I should allow the codes to work.
Firstly, I am trying to get a list of names of those who have signed up for an event, and having to check/tick the checkbox to confirm that they are in. However, as there are many events, the number of people who have signed up for each event may be different, and thus I called and made it into a while loop, as seen below.
<?php
while ($row = mysqli_fetch_assoc($result)) {
    $firstName = $row['first_name'];
    $lastName = $row['last_name'];
    ?>

    <form id="shortlistPeople" action = "doShortlistPeople.php?id=<?php echo $id ?>" method = "post">
    <fieldset data-role="controlgroup" >
    <input type="checkbox" class="shortlist" name="shortlistPeople[]" id="shortlistPeople" value="<?php echo $id; ?>"/>

    <label for="shortlistPeople"><?php echo $firstName; ?> <?php echo $lastName; ?></label>
    </fieldset>
    <?php
    }
    ?>
    <input type="submit" class="btnSelect" data-theme="b" data-inline="true" name="shortlistPeople" value="Submit Shortlisted Persons"/>
    </form>

<?php
}
// end for loop

else {
    echo "No candidates to be selected";
}
mysqli_close($link);
?>

Thus, in the doShortlistPeople.php:
<?php
$theShortlist = "";
if (!empty($_POST['shortlistPeople'])) {
    foreach ($_POST['shortlistPeople'] as $candidate_id) {
        $theShortlist .= $candidate_id . " ";

        $query = "UPDATE application SET shortlist='true'
        WHERE job_id = $id AND candidate_id = $candidate_id";
        $result = mysqli_query($link, $query) or die('Error querying database');
    }
}
?>

Therefore, I really need your help.
/ = Checked/Ticked
EXAMPLE 1: (If there is only 1 candidate)
[/] Bob Lee
OUTPUT:
Selected:
Bob Lee
EXAMPLE 2: (If there is more than 1 candidate)
[/] Bob Lee
[/] Nicholas M.
OUTPUT:
Selected:
Bob Lee
Nicholas M.
EXAMPLE 3: (If there is more than 1 candidate)
[] Bob Lee
[/] Nicholas M.
OUTPUT:
Selected shown:
Nicholas M.

A: You are looking for something like this -
<form id="shortlistPeople" action="doShortlistPeople.php" method="post">
    while ($row = mysqli_fetch_assoc($result)) {
        $id = $row['id'];
        $firstName = $row['first_name'];
        $lastName = $row['last_name'];
        ?>

        <label >
            <input type="checkbox" class="shortlist" name="shortlistPeople[]" id="shortlistPeople" value="<?php echo $id; ?>" />
            <?php echo $firstName; ?>
            <?php echo $lastName; ?>
        </label>

    <?php } else {
        echo "No candidates to be selected";
    } ?>

    <input type="submit" class="btnSelect" data-theme="b" data-inline="true" name="shortlistPeople" value="Submit Shortlisted Persons"/>
</form>

Basically your loop should not create multiple forms, just create multiple input elements.
PS:

*

*Your initial code is too buggy, to point out a mistake.

*I haven't tested the above code, its just to push you in right direction.


text:
Q: Format Date to only Month and Year - "MMM-yyyy" I am working on MVC 4.0./C#/Razor view. In model I have a date
[Display(Name = "For Period")]
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}")]
public System.DateTime ForPeriod { get; set; }

and in View I am getting date using
@Html.DisplayFor(modelItem => item.ForPeriod)

and in result I am getting date in "12-May-2015" format. I want to skip the day from this date and in result I want "May-2015".
My question is what should I used in View to get this "MMM-yyyy" format?

A: [Display(Name = "For Period")]
[DisplayFormat(DataFormatString = "{0:MMM-yyyy}")]
public System.DateTime ForPeriod { get; set; }

More information on formatting dates in C# can be found on MSDN here.
There is an additional option of using a custom editor template which you can read this article on stack overflow for more details - ASP.NET MVC 4 Editor Template for basic types

A: You can format date in View file by following way
<span>@Convert.ToDateTime(item.EffectiveDate).ToString("MMM-yyyy")</span>

For can also format date from model
[Display(Name = "For Period")]
[DisplayFormat(DataFormatString = "{0:MMM-yyyy}")]
public System.DateTime ForPeriod { get; set; }

A: Code to Convert Current Date to Month-Year format in ASP.NET
CASE - 1
Dim Current_Date as String = DateAndTime.Now.ToString("dd/MM/yyyy")

msgbox(Current_Date) //THIS WILL DISPLAY CURRENT DATE IN SHORT STRING FORMAT

For Example = "05/07/2020"
CASE - 2
Dim Current_Date as String = DateAndTime.Now.ToString("MMMM-yyyy")

msgbox(Current_Date) //THIS WILL DISPLAY CURRENT MONTH & YEAR

For Example = "July-2020"


text:
Q: Finite vector space V,W so is L(V,W)
Preceding example:
If V,W are vector spaces then $Map\left ( V,W \right )$ is an infinite dimensional vector space with operation defined by $\left ( f+g \right )\left ( v \right ):=f\left ( v \right )+g\left ( v \right )$
   and
  $ \left ( \alpha f \right )\left ( v \right ):=\alpha f\left ( v \right )$.
  The linear map $L\left ( V,W \right )$ form a subspace of Map$\left ( V,W \right )$

I believe the question below is preceded by this example:

Prove that if V,W are finite dimensional then so is $L\left ( V,W \right )$.

Here's my attempt:
Let V,W be finite dimension n.
Hence, V,W contains a set of n linearly independent vectors but no n+1 linearly independent vectors.
Let $L:V\rightarrow W$
with
$
\left ( f+q \right )\left ( v \right ):=f\left ( v \right )+g\left ( v \right )$
and
$\left ( \alpha f \right )\left ( v \right ):=\alpha f\left ( v \right )$
Seemingly, I am unable to progress forward.
Hints are appreciated

A: When first learning about function structures like your $L(V,W)$, I felt it useful to think of matrices.
Remember all linear transformations $T:V\to W$ where $V$ and $W$ are finite-dimensional have matrix representations. Once you fix bases, you can find a matrix $M$ such that $T(x) = Mx$. If $T$ sends $n-$dimensional vectors to $m-$dimensional vectors then the size of $M$ is size $m\times n$. Specifically, $\dim(L(V,W)) = \dim(M_{m\times n}) = nm$.
So here's what you do. Fix bases $B_V$ and $B_W$ for $V,W$ respectively (you can even use a coordinate transformation to work in $R^k$ if you wish). Then count the number of transformations by counting the number of ways to map $B_V$ to $B_W$. Linear transformations are determined by what they do to a basis.

A: In case the following words make sense:
The category of finite-dimensional vector spaces over a field $k$ is symmetric monoidal closed and hence enriched over itself.


text:
Q: How do i do configuratioin for different jobs has to run on different VMs or slave parallely suppose that both the project are freestyle or one is freestyle and other is pipeline project
how do then we will configure such that we  will able to run both the jobs or project simultanously or parallely


text:
Q: inserting element to a sorted vector and keeping elements sorted So I have a vector, and I want the elements to be sorted at all times. How should I go about inserting an element into that vector and keeping the elements sorted when I pop them out. I looked into std::lower_bound, however, that gave the opposite of what I wanted.
For example, this is what I want: When I pop all the elements in the vector it should be:
1 2 3 4 5. That means the vector has to store them as 5 4 3 2 1. If use lower bound, the vector stores them as 1 2 3 4 5, and it is popped as 5 4 3 2 1. Also, a compare functor is going to be passed in so that the lower_bound function uses the compare functor. Is there a way to take the opposite of a compare functor?

A: To keep your vector sorted all the time, you should always insert new elements into proper position. As you want to pop elements in ascending order and vector provides only pop_back() method you should sort elements in descending order. so first you need to find proper position and then insert there:
typedef std::vector<int> ints;

void insert( ints &cont, int value ) {
    ints::iterator it = std::lower_bound( cont.begin(), cont.end(), value, std::greater<int>() ); // find proper position in descending order
    cont.insert( it, value ); // insert before iterator it
}


text:
Q: Alternatives to parental controls for Vista Business workgroup machine? How can I restrict access to the internet and execution of files on a Vista Business machine? The computer is part of a workgroup.

A: You make make a separate user account for your children to use and install Windows Live Family Safety 2011.


text:
Q: How to implement Administrator rights in Java Application? I am developing a Data Modeling Software that is implemented in Java. This application converts the textual data (stored in a database) to graphical form so that users can interpret the data in a more efficient form. Now, this application will be accessed by 3 kinds of persons:
1. Managers (who can fill the database with data and they can also view the visual form of the data after entering the data into the database)
2. Viewers (who can only view the visual form of data that has been filled by managers)
3. Administrators (who can create and manage other administrators, managers and viewers)
Now, how to implement 3 diff. views of the same application.

Note: Managers, Viewers and Administrators can be located in any part of the world and should access the application through internet.

One idea that came in my mind is as follows:
Step1: Code all the business logic in EJBs so that it can be used in distributed environment (means which can be accessed by several users through internet)
Step2: Code 3 Swing GUI Clients: One for administrators, one for managers and one for viewers. These 3 GUI clients can access business logic written in EJBs.
Step3: Distribute the clients corresponding to their users. For instance, manager client to managers.
=================================QUESTIONS=======================================
Q1. Is the above approach is correct?
Q2. This is very common functionality that various softwares have. So, Do they implement this kind of functionality through this way or any other way?
Q3. If any other approach would be more better, then what is that approach?

A: *

*no

*no

*yes

Making different clients for different security roles is a :

*

*security hole - what if a viewer obtains the administrator version?

*hard to maintain

The way to do this is:

*

*make the data transferred to the client dependent on a security check

*also make various parts of the UI visible/enabled depending on that security check

*the security check is made on the server

*the security check depends on the currently logged user

*the user logs in on startup, using his credentials (username/password or digital certificate)

*the security roles (administrator, moderator, viewer) are stored on the server side.

Then, if needed, you can extend the security model by adding:

*

*differentiation between per-user and per-role rights

*rights on specific resources

*transitive rights

*permissions for specific actions

But such a complex user rights and security model is perhaps not needed in your application.

A: I agree with @Bozho except for the following:

make various parts of the UI visible/enabled depending on a security check

You actually need to make sure that unwanted access to the data, etc is blocked on the server side, irrespective of whether the client-side UI is visible / enabled.  The reason for this is that any client-side UI disabling code can be subverted.  Indeed, a bad guy could even entirely bypass your UIs and reverse engineer the application-specific protocols between your client and server code.
This is not to say that you shouldn't also disable / hide parts of the UI that the user is not allowed to use.  It is just not a good basis for decent security / access control.
(UPDATE : @Bozho has ammended his answer now to add server-side blocking to his list.  So I now agree with it entirely. )

A: I agree with Bozho. Another points with the three client approach is: what if the user somehow figures out how to send the operations which isn't available in his client? What if the same user has two roles (hence is required to have two clients). And of course you will have plenty to do maintaining one client...


text:
Q: Displaying an image with dcc.Graph in Plotly-Dash I am trying to display an image with with dcc.Graph component in Plotly-Dash so I get its nice toolbars and built-in UI. However I am getting a bunch of errors. This is what my procedure is:

*

*Upload JPG image.

*Load image using np.array(Image.open(..)).

*Convert to figure with px.imshow().

*Pass this through dcc.Graph component and try to display it on page.

Below is my code:
import datetime
import dash
from dash.dependencies import Input, Output, State
from dash import dcc
from dash import html
import numpy as np
from PIL import Image
import plotly.express as px

app = dash.Dash(__name__)

app.layout = html.Div([

    html.Div(
        children=[
            dcc.Upload(
                id='upload-image',
                children=html.Div([
                    'Drag and Drop or ',
                    html.A('Select Files')
                ]),
                # Allow multiple files to be uploaded
                multiple=True)]),
    html.Div(
        children=[
            html.Div(id='output-image-upload'),
        ])
])

def parse_contents(contents, filename, date):
    img = np.array(Image.open(contents))
    fig = px.imshow(img)
    return html.Div([
        html.H5(filename),
        html.H6(datetime.datetime.fromtimestamp(date)),
        dcc.Graph(figure=fig)
    ])

@app.callback(Output('output-image-upload', 'children'),
              Input('upload-image', 'contents'),
              State('upload-image', 'filename'),
              State('upload-image', 'last_modified'))
def update_output(list_of_contents, list_of_names, list_of_dates):
    if list_of_contents is not None:
        children = [
            parse_contents(c, n, d) for c, n, d in
            zip(list_of_contents, list_of_names, list_of_dates)]
        return children

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

I get these errors below:
Callback error updating output-image-upload.children

Traceback (most recent call last):
  File "C:\Users\...\test.py", line 48, in update_output
    children = [
  File "C:\Users\...\test.py", line 49, in <listcomp>
    parse_contents(c, n, d) for c, n, d in
  File "C:\Users\...\test.py", line 34, in parse_contents
    img = np.array(Image.open(contents))
  File "C:\Users\...\AppData\Local\Programs\Python\Python38\Lib\site-packages\PIL\Image.py", line 2904, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'data:image/jpeg;base64,/9j/2wBDAAYEBQY...

A: As explained in this answer you need to remove data:image/png;base64, from the image string. If you update your parse_contents function as follows your app should work:
def parse_contents(contents, filename, date):

    # Remove 'data:image/png;base64' from the image string,
    # see https://stackoverflow.com/a/26079673/11989081
    data = contents.replace('data:image/png;base64,', '')
    img = Image.open(io.BytesIO(base64.b64decode(data)))

    # Convert the image string to numpy array and create a
    # Plotly figure, see https://plotly.com/python/imshow/
    fig = px.imshow(np.array(img))

    # Hide the axes and the tooltips
    fig.update_layout(
        plot_bgcolor='white',
        paper_bgcolor='white',
        margin=dict(t=20, b=0, l=0, r=0),
        xaxis=dict(
            showgrid=False,
            showticklabels=False,
            linewidth=0
        ),
        yaxis=dict(
            showgrid=False,
            showticklabels=False,
            linewidth=0
        ),
        hovermode=False
    )

    return html.Div([
        html.H5(filename),
        html.H6(datetime.datetime.fromtimestamp(date)),
        dcc.Graph(
            figure=fig,
            config={'displayModeBar': True} # Always display the modebar
        )
    ])

Full code:
import io
import base64
import datetime
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import numpy as np
import plotly.express as px
from PIL import Image

app = dash.Dash(__name__)

app.layout = html.Div([
    html.Div(
        children=[
            dcc.Upload(
                id='upload-image',
                children=html.Div(['Drag and Drop or ', html.A('Select Files')]),
                multiple=True
            )
        ]
    ),
    html.Div(
        children=[
            html.Div(id='output-image-upload'),
        ]
    )
])

def parse_contents(contents, filename, date):

    # Remove 'data:image/png;base64' from the image string,
    # see https://stackoverflow.com/a/26079673/11989081
    data = contents.replace('data:image/png;base64,', '')
    img = Image.open(io.BytesIO(base64.b64decode(data)))

    # Convert the image string to numpy array and create a
    # Plotly figure, see https://plotly.com/python/imshow/
    fig = px.imshow(np.array(img))

    # Hide the axes and the tooltips
    fig.update_layout(
        plot_bgcolor='white',
        paper_bgcolor='white',
        margin=dict(t=20, b=0, l=0, r=0),
        xaxis=dict(
            showgrid=False,
            showticklabels=False,
            linewidth=0
        ),
        yaxis=dict(
            showgrid=False,
            showticklabels=False,
            linewidth=0
        ),
        hovermode=False
    )

    return html.Div([
        html.H5(filename),
        html.H6(datetime.datetime.fromtimestamp(date)),
        dcc.Graph(
            figure=fig,
            config={'displayModeBar': True} # Always display the modebar
        )
    ])

@app.callback(
    Output('output-image-upload', 'children'),
    [Input('upload-image', 'contents')],
    [State('upload-image', 'filename'),
     State('upload-image', 'last_modified')])
def update_output(list_of_contents, list_of_names, list_of_dates):
    if list_of_contents is not None:
        children = [
            parse_contents(c, n, d) for c, n, d in
            zip(list_of_contents, list_of_names, list_of_dates)
        ]
        return children

if __name__ == '__main__':
    app.run_server(debug=True, host='127.0.0.1')


text:
Q: Changing the From field for an email activity in a plug-in When an email is sent to a queue and there is a contact associated with the "From" email in CRM, upon promoting an email to an email activity the system automatically fills in the "From" field with the contact information. However, if a user with the same email exists in CRM, too, then the system always picks up the system user instead of the contact. I need to override this behaviour to ALWAYS pick up the contact if one with the email exists.
I created a post-operation plug-in (tried a pre-operation plug-in, too) for the event Create for email, trying to override the From field. The problem is, it does not work. When I debug the plug-in, it goes quietly past the assignment without any errors and then the same plug-in fires for the same email again. And again. And again.
When I try instead to create a new email and use the same ActivityList[] I was trying to use for the entity that triggered the event, it works. It seems that the problem is that CRM does not allow changing the From field from a plug-in, or am I doing something wrong? If it's a limitation enforced by CRM, is there a way around it?
My code is below:
var email = ((Entity)context.InputParameters["Target"]).ToEntity<Email>();

...
var oldFrom = ((EntityCollection)email.Attributes["from"]).Entities;
List<ActivityParty> newFrom = new List<ActivityParty>();
foreach (Entity party in oldFrom)
{
   EntityReference entRef = (EntityReference)party.Attributes["partyid"];
   if (entRef.LogicalName == SystemUser.EntityLogicalName)
      user = userLogic.Get(new Guid(entRef.Id.ToString()));
   if (user == null) return;
   string emailAddress = user.InternalEMailAddress;
   Contact contact = contactLogic.LookupPASIndividual("", emailAddress);
   if (contact != null)
   { newFrom.Add(new ActivityParty() {PartyId = new EntityReference(Contact.EntityLogicalName, contact.ContactId.Value) });
   }
   else
      return;
}
email.From = newFrom;

Update: So I registered the plug-in on Pre-validation now and it's not triggered when an email activity is created by a router, it IS triggered when a user creates an email in CRM though...

A: The problem is that you aren't changing the email which is processed at all.
var email = ((Entity)context.InputParameters["Target"]).ToEntity<Email>();

This line converts the record which is currently processed to an object of type email. You modify the record which is not in scope of the operation. You have to modify the From of the target (either directly or write it back).
For the processing stages: take a look at the Event Execution Pipeline. Pre-Validation is to early for your task. I'am not quite sure when the address resolution is done, but I would try to do your conversion Pre-Create.

A: I ended up using a workaround: created an async Post-Event that associates the email activity with the contact if a contact with the same email exists, leaving the user associated with the email in the "From" field.


text:
Q: 2 JSON. Only 1 work. json_decode php I seriously got gray hair.
I would like to echo the [ask] data for https://api.gdax.com/products/btc-usd/ticker/
But it's return null.
When i try with to use another API with almost the same json, it work perfect.
This example works
<?php

$url = "https://api.bitfinex.com/v1/ticker/btcusd";
$json = json_decode(file_get_contents($url), true);
$ask = $json["ask"];
echo $ask;

This example return null
<?php

$url = "https://api.gdax.com/products/btc-usd/ticker/";
$json = json_decode(file_get_contents($url), true);
$ask = $json["ask"];
echo $ask;

Anybody there has an good explanation, whats wrong with the code returning null

A: the server of that null result is preventing php agent to connect thus returning http 400 error. you need to specify a user_agent value to your http request.
e.g.
$ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36';
$options  = array('http' => array('user_agent' => $ua));
$context  = stream_context_create($options);

$url = "https://api.gdax.com/products/btc-usd/ticker/";
$json = json_decode(file_get_contents($url, false, $context), true);
$ask = $json["ask"];
echo $ask;

you can also use any user_agent string you want on the $ua variable, as long as you make sure that your target server allows it.

A: You can't access this URL without passing arguments. It happen some time when the host is checking from where the request come.
$ch = curl_init();
$header=array('GET products/btc-usd/ticker/ HTTP/1.1',
    'Host: api.gdax.com',
    'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language:en-US,en;q=0.8',
    'Cache-Control:max-age=0',
    'Connection:keep-alive',
    'Host:adfoc.us',
    'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36',
    );

    curl_setopt($ch,CURLOPT_URL,"https://api.gdax.com/products/btc-usd/ticker/");
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,0);
    curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
    $result=curl_exec($ch);

Then you can use json_decode() on $result !


text:
Q: Which comparison methods are used by the built-in max function? sorted requires only __lt__ to be defined on the sorted iterable's contents. This is technically enough to calculate a maximum but sorted[-1] is slightly less efficient than the max function and I'd rather just use that, but I can't figure out what a minimal custom comparison implementation looks like.
Which methods does max require?
P.S. assume for some reason I cannot use the total_ordering decorator to bypass the issue altogether.

A: You will need any or both of __lt__ and __gt__ depending on the case. In the general case (number 2 below) you will need both.

*

*If you are doing a max() over an homogeneous collection (all the items are of the same class), or an heterogeneous collection where you have control over the definition of all the involved classes, then it does not matter. Either __lt__ or __gt__ is enough: regardless of the one you implement, any comparison of the form a < b will always be able to be evaluated using either a.__lt__(b) or b.__gt__(a), and any comparison of the form a > b will always be able to be evaluated using either a.__gt__(b) or b.__lt__(a). So if either one of the two methods is defined for both classes the comparison will always work.

*If instead your collection is not homogeneous and you do not have control over all the classes in the collection, you will need both. This is because a < b cannot be computed if a does not implement __lt__ for the class of b or vice-versa b does not implement __gt__ for the class of a (same reasoning goes for a > b). Suppose you cannot control b's class definition, then you cannot control whether b implements __lt__ or __gt__ for an instance of a (it most likely does not, e.g. if b is a simple int). Since you cannot know in which order the internal comparisons would happen (you also don't know the order of the items in the collection in general), you cannot guarantee that only implementing one of the two methods is enough.

A: TLDR: Having either of __lt__ or __gt__ defined between all items is fine.

The max, min and similar functions use the builtin equivalent of the < or > operators. Notably, these operators do not correspond directly to their special method – rather, a < b will try a.__lt__(b) first and fall back to b.__gt__(a)if needed.

Data model: object.__lt__
There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other's reflection […]

While the use of operators for max/min is not strictly specified, they generally fall under the umbrella of sorting operations. Various official sources guarantee the use of the < operator as opposed to directly using special methods.

sorted
The sort algorithm uses only < comparisons between items.

Sorting HowTo
The sort routines use < when making comparisons between two objects. [...], note that < can fall back to using __gt__() if __lt__() is not implemented


text:
Q: CakePHP Recursive Find Method In my CakePHP app, I have the following model association:

Offer -> Order -> Coupon

Then, at OffersController.php, i need to write a find method to output
the number of coupons sold on each offer, assuming that some orders can have multiple coupons.
The problem is that I'm in the OffersController, so when I try to use find('count'), I just get the number of offer entries. I want to count the number of coupon entries.
I tried to do something like $this->Offer->Order->Coupon->find('count'), but it does not work.
I tried to use the ContainableHelper as well, but got into the same problem of counting the wrong entries.
How can I proceed?

A: You need the resulting SQL query to do some magic with COUNT and GROUP BY. Try to add a field like this (untested):
$this->Offer->Order->Coupon->find(
     'all',
     array(
        // Generate a field that counts the coupons per Order
        'fields' => array(
            'COUNT(Coupon.id) AS coupon_count'
        ),
        // Only look at Orders for the given Offer
        'conditions' => array(
            'Order.offer_id' => $id
        ),
        // This is important: group by Order.
        'group' => ('Coupon.order_id')
     )
);

If your Order -> Coupon have a simple hasMany relationship, a more convenient approach would be to keep track of the existing Coupon count in every Order record using an extra coupon_count field and the counterCache function. CakePHP can automatically update that counter field for you.


text:
Q: Why does chkdsk produce "Correcting error in index $I30 for file 33267" and then freeze? I am running chkdsk like this:
chkdsk k: /x

I get this error:

Correcting error in index $I30 for file 33267.

What does it mean? Here's the full problem:
Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Windows\system32>chkdsk e: /r
The type of the file system is NTFS.
Volume label is RodDrobo.

CHKDSK is verifying files (stage 1 of 5)...
162048 file records processed.
File verification completed.
   0 large file records processed.
   0 bad file records processed.
   0 EA records processed.
   0 reparse records processed.
CHKDSK is verifying indexes
(stage 2 of 5)... 10 percent complete.
(167130 of 208124 index entries processed)
Correcting error in index $I30 for file 33267.
Correcting error in index $I30 for file 33267. <--- it always reaches this spot, then hangs forever

A: I think you just leave the chkdsk to finish what it started, Depending on the size if the drive and the number of files in it, chkdsk can take anywhere between a few hours to a few DAYS!!! It's best to be patient or risk losing the drive.

A: I'd suggest that's either MFT (master file table) corruption or some bad sectors it can't fix. I'd suggest getting the diagnostic tools from the HDD manufacturer and using those, sincee they're sometimes a bit more informative.
Also have a look at your windows event logs to see if there's messages about the disk failing/having bad sectors etc.
Last time I saw a disk doing that it died shortly afterwards. I'd get all your data off there and get yourself a new disk asap.

A: I had the same problem. You need a Symantec recovery disk[1][2].
Start your computer from the disk, go to Analyze and check the hard drive for errors. Be patient, it can take one hour. That will should it.

A: Was seeing this error to but only needed to wait 30mins for it to continue on


text:
Q: migrating files and shortcuts from old XP to NEW 7 I have a company who has got a new Windows 7 PC. Any recommendations on how to migrate all of the files over and also how to I bring the IE and Chrome shortcuts and setting over/
Are there any issues I should foresee when copying from a real old xp machine to new 64b windows 7 machine?
Thanks in advance

A: Chrome support bookmark setting sync'ing, so just setup the sync in chrome on the old computer... and open chrome on the new computer and turn the sync'ing on there too. Everything should be copied over for you.
You might want to export the IE bookmarks/cookies into chrome first. And set it up before the sync

A: There are many issues in transferring files between machines with different OSes; file paths are different, many apps install only files needed by the installed OS so moving it to a machine with another OS will break it. Some files, such as application config and installers, are hidden but can be migrated to new machines. Other files, such as application caches and registry settings, are machine or user specific and cannot be migrated, and it is not obvious which are which. Do not try to copy files manually.
The Windows Easy Transfer app will migrate user data and documents. The Windows User State Migration Tool can migrate some application settings to a new machine.


text: Q: ReactJS - Using a Search Bar to navigate to different pages im working on a project. I have a bunch of pages ive created and i want a user to be able to use a search bar to find those pages relating to their search. Does anyone have an idea on how to go about this?


text:
Q: Jersey JAX-RS: extend logging over resource-class dispatching I am using Jersey JAX-RS for a REST-service.
I a running it in SE-Deployment with GrizzlyHttp inside my programm.
I have also registered a logger that prints out the HTTP-request and the response.
What I am missing is logging "between" the HTTP-server and the resource-class.
I'd like to see log-entries if no path matches or if a path matches but the parameter did not or similar cases. Today I need to check my annotations and compare it to the logged HTTP-parameters. A bit more logging arround that would be helpful.
Is that possible?

A: You can achieve it by using a pre-matching filter.
A pre-matching filter is a filter that gets invoked before the JAR-RS runtime tries to match the request with a resource. This type of filter lets you log the requested URI even though it may not match with any of your resources. You annotate a filter with the @PreMatching annotation, and that is all you have to do to have the filter get invoked before the resource matching phase.
Note:: If you want your filter to be discoverable by JAX-RS runtime during the provider scanning phase, then you need to annotate it with the @Provider annotation. Alternatively, you can manually register it in your application set-up (as I have done, that's why in the example below I haven't annotated the filter with @Provider).
Here's a very simple example of a pre-matching filter.
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;

@PreMatching
public class PreMatchingFilterExample implements ContainerRequestFilter {

    private final static Logger LOG = LogManager.getLogger(PreMatchingFilterExample.class);
    @Context
    UriInfo uriInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        LOG.info("Resource not found: " + uriInfo.getAbsolutePath());
        LOG.info("Path params: " + uriInfo.getPathParameters());
        LOG.info("Query params: " + uriInfo.getQueryParameters());
    }
}


text:
Q: Kinetic energy of disc pivoting about its edge Suppose we have a disc of radius $R$ suspended vertically from a pivot on its edge. This disc is then given an initial angular displacement $θ$ and permitted to freely swing without friction.
A problem arises when I attempt to calculate the maximum velocity (at equilibrium, when $ θ$ is zero).
$$Mgh=\frac{1}{2}Mv^2$$
$$Mg(R-Rcos\theta)=\frac{1}{2}Mv^2$$
$$v=\sqrt{2gR(1-cos\theta)}$$
Using angular quantities, however, we have
$$ Mgh = \frac{1}{2}I\omega^2$$
$$Mg(R-Rcos\theta) = \frac{1}{2}(\frac{1}{2}MR^2 + MR^2)\omega^2$$
$$\omega = \sqrt{\frac{4g}{3R}(1-cos\theta)}$$
There is an obvious inconsistency between the results when we manipulate them using $\omega R = v$ to find the linear velocity from the angular result
$$v= \sqrt{\frac{4gR}{3}(1-cos\theta)}$$
My textbook derives the maximum velocity using angular quantities. My question is - is there not a translational component to the kinetic energy as well? (The centre of mass is certainly not stationary) Why is the first result incorrect?

A: The translational component is already taken into account by your use of the parallel axes theorem to derive the moment of inertia for a disk rotating about its edge. But if you just use translation you are not accounting for the rotation of the disk... At the lowest point in the arc the points are not all moving in the same direction: some move faster, some move slower, some have vertical components. None of that is taken into account if you assume only translation- but it is when you treat the disk as rotating (which it is, after all).