text:
Q: Easymock doesn't preserve annotations of methods I'm try to mock a class that has some public methods with annotations (it's actually a SpringBoot @RestController type of class).
When I mock it and use expect for few of the methods that have annotations I see that Easymock loses the annotation and my code breaks.
Is that EasyMock limitation or I need to do something to make it work?
EDIT:
Here is a snippet of the class I'm trying to mock:
@CrossOrigin
@RestController
@RequestMapping(path = "/users")
public class UsersController {

    @RequestMapping(
            path = "/getUsers",
            method = RequestMethod.GET,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public List<User> getUsers(@RequestBody UserRequest userRequest, HttpServletRequest request) {
...
}
...
}

Mocking Test Code:
@Test
    public void testGetUsers() throws Exception {
UserController controller = createMock(UserController.class);
        expect(controller.getUsers(userRequest, httpRequest)).andReturn(Collections.emptyList());

        replay(controller);

        ...

        verify(controller);
}

I did a simple check and instead of passing the mocked instance I passed an instantiated instance and it worked well! so my conclusion is that somehow when mocking a class that has annotations on methods it loses the annotations.
btw, I'm using easymock 3.4
EDIT 2:

*

*I've upgrade to v4.2 but it didn't help.

*The way to reproduce it is simply by running this code
public void testGetUsers() throws Exception {

   UserController controller = createMock(UserController.class);

 expect(controller.getUsers(userRequest,httpRequest)).andReturn(Collections.emptyList());

   replay(controller);

   Method[] methods = controller.getClass().getMethods();
   if(methods[0].isAnnotationPresent(RequestMapping.class) == false) {
   System.out.println("FOUND THE PROBLEM!!");
}

Thank you!

A: A mock is a simple thing. It extends a class and overrides all the methods. The annotations are not added to the generated class. Because you are mocking a behavior. The mock is not meant to be passed to an annotation processor.
Nothing is preventing from doing it, it's just that nobody has needed that feature for 20 years. I am curious to see a full example of why you need it.


text:
Q: AngularJS Accordian Tag not working I am new to AngularJS and tried to learn the tutorial/code sample from the link below.
http://angular-ui.github.io/bootstrap/
I downloaded the latest version of Angularjs script and the bootstrap as suggested on above link and placed the code something as below just to test it out in Netbeans.

Also, the code I have written as below.

but it is throwing an error as below. Also when I hit control+Space (intellisense), it is not even listing Accordion tag.

Am i missing something here?

A: You forgot to add bootstrap module to your app
angular.module('myModule', ['ui.bootstrap'])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reprojecting list of latitude/longitude values in .csv to points using ArcPy I am creating a tool using Python to convert .csv files into points. However, the points were collected in EPSG: 2274 and not WGS84 (EPSG:4326), so in order to create the points I have to convert the lat/long values into WGS84 for them to plot correctly I believe. I have created a script that does this and it works, but the points are not placed correctly geographically. They end up all clustered and in Arkansas (highlighted points) instead of Tennessee (blue pins).

Is there something I need to change in the code to project these values into points?
import csv
import arcpy
import ogr, osr

#set input variables
spreadsheet = "C:\\Monument_Surveyors\\ControlPointInformation_Test_oldconfiguration.csv"
fc = r"C:\Monument_Surveyors\Monuments\Monuments_copying.gdb\Monuments_STAGE_editing_SPCS"

# Spatial Reference System
inputEPSG = 4326
outputEPSG = 2274

#open csv file
with open(spreadsheet, "r") as monument_sheet:
    #create reader
    csvReader = csv.reader(monument_sheet)
    #call header
    header = next(csvReader)

#grab index position by using field name
#not necessary if index is already known
    latIndex = header.index("Latitude:")
    longIndex = header.index("Longitude")

#create empty list for string coordinates
    coords = []

#parse through rows and call data in each row index
    for row in csvReader:
        lat = float(row[latIndex])
        long = float(row[longIndex])
        coords.append([lat, long])

print("Coords: " + str(coords))

# Spatial Reference System
inputEPSG = 2274
outputEPSG = 4326

#convert string coordinates to float coordinates
coordsFloat = []
for coord in coords:
    for i in coord:
        coordsFloat.append(float(i))
xypoints = [coordsFloat[x:x+2] for x in range(0, len(coordsFloat),2)]

projCoords = []
projXcoords = []
projYcoords = []
latList = []
longList = []
i = 0
while i < len(xypoints):
    #define lat and long index within each coordinate pair
    pointY = xypoints[i][0]
    pointX = -abs(xypoints[i][1])

    # create a geometry from coordinates
    point = ogr.Geometry(ogr.wkbPoint)
    point.AddPoint(pointX, pointY)

    # create coordinate transformation
    inSpatialRef = osr.SpatialReference()
    inSpatialRef.ImportFromEPSG(inputEPSG)

    outSpatialRef = osr.SpatialReference()
    outSpatialRef.ImportFromEPSG(outputEPSG)

    coordTransform = osr.CoordinateTransformation(inSpatialRef, outSpatialRef)

    # transform point
    point.Transform(coordTransform)

    #define lat and long
    lat = point.GetY()
    long = point.GetX()
    latList.append(lat)
    longList.append(long)
    #print("long: " + str(long))
    #print("GetX: " + str(point.GetX()))

    #concatonate list element-wise
    projCoords = [None]*(len(latList)+len(longList))
    projCoords[::2] = latList
    projCoords[1::2] = longList
    #print("latList: " + str(latList))
    #print("longList: " + str(longList))

    i+=1

#group coordinates
projCoordsTuple = zip(projCoords[0::2], projCoords[1::2])

#convert tuple to a list within a list
projCoordsList = []
for row in projCoordsTuple:
    latIndex = row[0]
    longIndex = row[1]
    projCoordsList.append([longIndex, latIndex])
print(projCoordsList)

try:
    #create cursor
    cur = arcpy.da.InsertCursor(fc, ("SHAPE@X", "SHAPE@Y"))
    #iterate through rows to insert point
    for i in projCoordsList:
        cur.insertRow(i)

    print ("feature created")

except:
    print(arcpy.GetMessages())
    print ("feature not created")

finally:
    del cur

EDIT: I would like to update this specific script as a simple Append will not do the trick - I need to do some additional field calculations that do not exist in the .csv spreadsheet.

A: You could do this in a few lines using arcpy.management.XYTableToPoint (or arcpy.management.MakeXYEventLayer) then arcpy.management.Project. Much simpler. The initial feature class (in EPSG:2274) can be an in-memory FC to speed up processing.
in_csv = "test.csv"
out_fc = "test.shp"  # or "path/to/file.gdb/somefc"
x_field, y_field = "X", "Y"

arcpy.management.XYTableToPoint(in_csv , "memory/testcsv", x_field, y_field, coordinate_system=arcpy.SpatialReference(2274))
arcpy.management.Project("memory/testcsv", out_fc , arcpy.SpatialReference(4326))

Some demo points in EPSG:2274:
X,Y,id,
1718965.95131462,590521.042027273,1
1817376.99676817,592536.415227254,2
1807030.13644896,517453.796786448,3
1722344.26104266,456262.307004273,4

Result:

And if you need the InsertCursor because you are appending to an existing FeatureClass with existing features:
in_csv = "test.csv"
out_fc = "test.shp"  # or "path/to/file.gdb/somefc"
x_field, y_field = "X", "Y"

arcpy.management.XYTableToPoint(in_csv , "memory/testcsv", x_field, y_field, coordinate_system=arcpy.SpatialReference(2274))
arcpy.management.Project("memory/testcsv", "memory/testfc" , arcpy.SpatialReference(4326))
arcpy.management.Append("memory/testfc", out_fc)  # may need to specify schema_type="NO_TEST" and field_mapping

A: If your points are showing up in the wrong place, have you verified that your OGR coordinate transformation is working correctly?
coordTransform = osr.CoordinateTransformation(inSpatialRef, outSpatialRef)

Since you are doing the coordinate transformation outside of ArcGIS, it is very unlikely that ArcGIS is responsible for the location being wrong in the map you are viewing.
Using OGR to do the coordinate transformation is unnecessary since you are already using ArcPy and have access to ArcGIS code to do the transformation.  Why bring more Python packages into the mix if you don't need to.
Instead of attempting to modify your script, especially since I don't think using OGR for coordinate transformation is necessary, I will provide a solution using ArcPy insert cursor that you can adapt to your situation.
import arcpy
import csv

# set input variables
spreadsheet =       # path to CSV file containing coordinates with "X,Y,ID" header
fc = #              # path to pre-existing feature class in WGS 84 spatial reference

# EPSG codes for CSV coordinates and feature class
epsg_in = 2274
epsg_out = 4326

inSpatialRef = arcpy.SpatialReference(epsg_in)
outSpatialRef = arcpy.SpatialReference(epsg_out)
datum_transformation = arcpy.ListTransformations(inSpatialRef, outSpatialRef)[0]

with open(spreadsheet, newline='') as file:
    with arcpy.da.InsertCursor(fc, "SHAPE@", datum_transformation) as cur:
        csvfile = csv.reader(file)
        next(csvfile)
        for x, y, oid in csvfile:
            pointGeom = arcpy.PointGeometry(arcpy.Point(float(x), float(y)), inSpatialRef)
            cur.insertRow([pointGeom])

The InsertCursor can do the datum transformation for you, so there is no need to do it ahead of time.  Although I created a PointGeometry first, it may be the cursor could be defined with ["SHAPE@X", "SHAPE@Y"] instead "SHAPE@" and just have the coordinates passed in separately.

A: Finally found a method that works...
import csv
import arcpy

#set input variables
spreadsheet = "C:\\Monument_Surveyors\\ControlPointInformation_Test_oldconfiguration.csv"
fc = r"C:\Monument_Surveyors\Monuments\Monuments_copying.gdb\Monuments_STAGE_editing_SPCS"

# Spatial Reference System
inputEPSG = 2274
outputEPSG = 4326

#open csv file
with open(spreadsheet, "r") as monument_sheet:
    #create reader
    csvReader = csv.reader(monument_sheet)
    #call header
    header = next(csvReader)

#grab index position by using field name
#not necessary if index is already known
    latIndex = header.index("Latitude:")
    longIndex = header.index("Longitude")
    elevIndex = header.index("Elev.:")

#create empty list for string coordinates
    coords = []

#parse through rows and call data in each row index
    for row in csvReader:
        lat = float(row[latIndex])
        long = float(row[longIndex])
        elev = float(row[elevIndex])
        coords.append([lat, long, elev])

#convert string coordinates to float coordinates
coordsFloat = []
for coord in coords:
    for i in coord:
        coordsFloat.append(float(i))
xypoints = [coordsFloat[x:x+3] for x in range(0, len(coordsFloat),3)]
print(xypoints)

try:
    #create cursor
    cur = arcpy.da.InsertCursor (fc, ["SHAPE@Y", "SHAPE@X", "SHAPE@Z"])
    for i in xypoints:
        cur.insertRow(i)
    print("feature created")

except Exception as e:
    print(e)
    print(arcpy.GetMessages())
    print ("feature not created")

finally:
    del cur


text:
Q: WCF One ServiceHost for many WCF Libraries How can I host services from different wcf library at one place?
Supposed I have 2 WCF liberary dlls, look like this
.DLLA
 Public Class clientA : InterfaceA

.DLLB
 Public class clientB : InterfaceB

Both interfaces have service contract attribute and their own operation contract(s).
Both dlls I placed in a shared folder so I can load them dynamically and host them as services
Now I want to create a  "AutoHosting" console app as the middle layer but using only ONE SINGLE ServiceHost to host both of these services and assign with the same UriListen.
PS: Also I want the solution as flexible as it can. For example in the future I add DLLC I hope ServiceHost can pick up the DLLC service automatically without modifying "AutoHosting" part
please let me know the best approach if you have.

A: Based on your comments in your question I think I finally understand your main issue.

Scott, yes I thought this approach but when clients dlls count more than 50+ I will have example.org/MyServices/Client01 ... example.org/MyServices/Client50 exposed. then you will fine the app.config is horrible if one client want to consume all of them

If you want one master class that everything can talk through at once (and I am not saying this is a good idea, I would just go with the giant client app.config file) you will need to dynamically generate a class that will act as a service endpoint, implementing all of the interfaces defined and proxying the calls to the DLLs.
So in theory the master class would look something like
[ServiceContract]
public interface IMasterInterface : InterfaceA, InterfaceB
{
}

public class MasterClass : IMasterInterface
{
    public MasterClass()
    {
        aInstance = new DllA.clientA();
        bInstance = new DllB.clientB();
    }

    DllA.InterfaceA aInstance; //Use full namespaces to prevent conflicts.
    DllB.InterfaceB bInstance;

    public void DllA.InterfaceA.Foo() //Use explicit interfaces to prevent name conflicts
    {
        aInstance.Foo();
    }

    public bool DllB.InterfaceB.Foo()
    {
       return bInstance.Foo();
    }
}

Now for the requirement having to re-compile your program every time you add or remove a DLL, and the thing is, you still will do that but not at development time.
.NET provides classes that allow you to generate assemblies on the fly at runtime with CodeDOM. You would need to recreate the MasterClass and IMasterInterface classes every time the program started up (or at least whenever you detected a change in the DLLs). Just enumerate the DLLs and build up your single master class and interface.
IMPORTANT NOTE: I have no idea if this will break the contracts with clients when you rebuild with a new DLL added or removed. Also I have no idea how name conflicts will look at the client side. I still recommend you do not do this approach and just have a large app.config instead pointing at multiple endpoints. If you hand generate the app.config with a tool like SvcConfigEditor.exe that comes with Visual Studio you can make it a lot smaller by re-using configuration sections between multiple similar services.


text:
Q: How do I save the page state with JavaScript execution results and restore it later? I'm developing a chrome extension for YouTube. The extension writes alternative subtitles with different behavior. The subtitle file is taken from YouTube by the link.
In order for me to be able to show subtitles by the time the video starts playing, I have to download the subtitle files before the video loads.
At low Internet speed, JSON files of subtitles are loaded simultaneously with the YouTube page for a very long time.
I use this approach. To prevent my extension from competing with YouTube scripts, my extension:

*

*calls window.stop() at the very beginning of page loading.

*After stopping the download, I download the files I need.

*Then the extension reloads the page.

But I would not want to reload the page if there are entries in window.history.
Of course, I would just like to block the page rendering thread for example by window.renderPause() and then resume by window.renderResume(). I would not use window.stop(). But JavaScript does not provide such an opportunity.
How do I save the page state with JavaScript execution results and restore it later?
This code doesn't work for youtube. JavaScript of YouTube does not start.
let clonedHtml = document.documentElement.cloneNode(true);
let clonedWindow = Object.assign({}, window);
document.documentElement.innerHTML = "";
window = clonedWindow;
document.replaceChild(clonedHtml, document.documentElement);

I can not use window.history.back() or window.history.forward() because window.stop() does not allow to load a page.

A: Do you want to prevent the video from starting before your subtitle files are loaded? Restoring the page state itself will be very complex, there is no generic solution which works for all websites.
To load your subtitles before youtube scripts load:

*

*Use [chrome.webRequest.onBeforeRequest][1] and replace youtube's subtitle URL with your own subtitle URL (or replace the file content afterRequest)

*Checkout this answer which hooks the page load event where you can fetch and inject your subtitles before anything else loads.
Both methods won't require an additional page reload.
[1]: https://developer.chrome.com/docs/extensions/reference/webRequest/


text:
Q: Specific spring-core jar to be included in project Ive included following lines in my pom.xml
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>4.1.6.RELEASE</version>
</dependency>

The specific spring-core JAR version I want is 4.1.6, but whenever I do an mvn clean install, the dependencies folder under my project in netbeans shows a downgraded version (currently 3.0.7.RELEASE).
I want to know how I can force maven to put 4.1.6.RELEASE jar in my dependencies folder. I've done
mvn dependency:purge-local-repository -DactTransitively=false -DreResolve=false

And I've the folder 4.1.6.RELEASE with correct jar in my local /.m2/repositories folder. I need to access org.springframework.util.MimeType class which is not available in spring-core 3.0.7.RELEASE jar.

A: See the result of mvn dependency:tree to know if another jar bring back the version 3.0.7. and exclude from this dependency the spring-core
See the same result to know if the right version is present
Add the pom.xml and the result of mvn dependency:tree in the question

A: Please follow these steps:

*

*Check in .m2 local repository where the Spring 3.0.7 jar is downloaded(It should be under folder org->springframework)

*Delete the folder present inside springframework, so that mvn will try to fetch required dependencies.
Let me know if it helps

A: The issue is that spring-core is a mandatory dependenecy of most spring artifacts. Most likely you are using a dependent artifact e.g spring-context which is of version  3.0.7. Then Maven is fetching spring-core of the same version as the dependent artifact using its transitive dependency mechanism.
To control the version of spring-core you need to move its declaration from the dependencies section to the dependency management section of your pom.xml as follows
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>4.1.6</version>
            </dependency>
       </dependencies>
</dependencyManagement>


text:
Q: How to lighten or darken a Flex 4 image Is there a way to darken or lighten an image or actually any display object on mouse over and then restore it back on mouse out? I would prefer to use filters if possible just because I am already applying a filter on mouse over and removing it on mouse out. I would then be able to add it to the filters list. If not that's fine. In my code I'm using a Flex 4 Spark Image component.

A: You should use ColorTransform for this. Below is shown how you can utilise this.
image.addEventListener(MouseEvent.MOUSE_OVER, checkTransform);
image.addEventListener(MouseEvent.MOUSE_OUT, checkTransform);

private function checkTransform(e:event):void
{
    if(e.type == MouseEvent.MOUSE_OVER)
        image.transform.colorTransform = new ColorTransform(0.5, 0.5, 0.5); //multiplies all RGB-values by 0.5
    else
        image.transform.colorTransform = new ColorTransform(1, 1, 1); //restores to default image
}

this should do the trick. For more information on ColorTransform: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/geom/ColorTransform.html?filter_flash=cs5&filter_flashplayer=10.2&filter_air=2.6

A: The easiesy way to do is, create a colorfilter, and apply this colorfilter to the image on rollover and remove the filter on rollout.
For details visit :
http://cookbooks.adobe.com/post_Convert_images_to_grayscale_using_ActionScript_-12769.html
Thanks


text:
Q: NaN produced in Tukey I'm having problems with Tukey..
I really don't understand why...
I've tried several codes, I also had the problem of the factor variable I solved using as.factor.. but the with NaN produced I don't know how to manage it
my data:
> zz2
   id Mean group
1   1 1.17     1
2   2 1.57     2
3   3 1.16     2
4   4 1.14     1
5   5 1.81     4
6   6 1.33     1
7   7 1.27     1
8   8 1.57     1
9   9 1.56     3
10 10 1.36     1
11 11 1.09     1
12 12 1.05     1
13 13 1.43     3
14 14 1.48     2
15 15 1.60     3
16 16 1.78     4
17 17 1.55     1
18 18 1.36     2
19 19 1.06     3
20 20 1.50     2

Here is my code:
install.packages("multcompView")

library(multcompView)

model=lm( zz2$Mean ~ as.factor(zz2$group))

ANOVA=aov(model)

TUKEY <- TukeyHSD(x=ANOVA, 'zz2$group', conf.level=0.95)

here's the error message:
> library(multcompView)
> model=lm( zz2$Mean ~ zz2$group )
> ANOVA=aov(model)
> TUKEY <- TukeyHSD(x=ANOVA, 'zz2$group', conf.level=0.95)
Error in TukeyHSD.aov(x = ANOVA, "zz2$group", conf.level = 0.95) :
  nessun factor nel modello stimato
Inoltre: Warning message:
In replications(paste("~", xx), data = mf) : non-factors ignored: zz2$group
> model=lm( zz2$Mean ~ as.factor(zz2$group) )
> ANOVA=aov(model)
> TUKEY <- TukeyHSD(x=ANOVA, 'zz2$group', conf.level=0.95)
Warning message:
In qtukey(conf.level, length(means), x$df.residual) : NaNs produced

RStudio Version 1.2.5033
How can I solve? thank you!

A: zz2$group <- factor(zz2$group)

model=lm(Mean ~ group, data=zz2)

ANOVA=aov(model)

summary(ANOVA)

            Df Sum Sq Mean Sq F value Pr(>F)
group        3 0.4396 0.14653   4.098 0.0246 *  # <- p-value (F-test)
Residuals   16 0.5721 0.03576

TUKEY <- TukeyHSD(x=ANOVA, "group", conf.level=0.95)
TUKEY

 Tukey multiple comparisons of means
    95% family-wise confidence level

Fit: aov(formula = model)

$group
          diff         lwr       upr     p adj
2-1  0.1328889 -0.16887514 0.4346529 0.5998626
3-1  0.1313889 -0.19372097 0.4564987 0.6615618
4-1  0.5138889  0.09095761 0.9368202 0.0148342
3-2 -0.0015000 -0.36442423 0.3614242 0.9999994
4-2  0.3810000 -0.07164605 0.8336460 0.1155457
4-3  0.3825000 -0.08603317 0.8510332 0.1312203


text:
Q: Adicionar SOAP Header em SOAP C# Estou tentando adicionar um header customizado em um serviço SOAP usando C#. Já procurei por tudo e não encontrei uma solução que funciona.
Estou adicionando o serviço por Web References do C#.
Já tentei fazer override do método GetWebRequest, porém ele não consegui.
O WSDL é este http://app.omie.com.br/api/v1/geral/produtos/?WSDL
Exemplo como deve ficar
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsdl="http://app.omie.com.br/api/v1/geral/clientes/?WSDL">
       <soapenv:Header>
          <app_key>123456789</app_key>
          <app_secret>topSecret</app_secret>
       </soapenv:Header>
   ....

Código de testes
static void Main(string[] args)
{
    var servico = new omie.Produto.ProdutosCadastro();
    servico.autenticacao = new omie.Produto.Autenticacao();
    servico.autenticacao.app_key = "123456";
    servico.autenticacao.app_secret = "123456789";

    var dados = new omie.Produto.produto_servico_list_request();
    dados.pagina = "1";
    dados.registros_por_pagina = "50";
    dados.apenas_importado_api = "N";
    dados.filtrar_apenas_omiepdv = "N";

    var produtos = servico.ListarProdutosResumido(dados);

    Console.WriteLine(produtos.total_de_registros.ToString());
}

O código de teste, foi uma sugestão deste post
https://bytes.com/topic/net/answers/560786-how-add-soap-header-soap-message
Procurar por texto:

That was already described in my previous post

Além disto foi estendida a classe do SOAP com estes elementos:
namespace omieTestes.omie.Produto
{
    public partial class ProdutosCadastro : System.Web.Services.Protocols.SoapHttpClientProtocol
    {
        public Autenticacao autenticacao;
    }

    //[XmlRoot(Namespace = "http://app.omie.com.br/autenticacao")]
    public class Autenticacao : SoapHeader
    {
        public string app_key;
        public string app_secret;
    }
}

O que achei ruim é que se atualizar a referência, perde a implementação:
[System.Web.Services.Protocols.SoapRpcMethodAttribute("http://app.omie.com.br/api/v1/geral/produtos/?WSDLListarProdutosResumido", RequestNamespace="http://app.omie.com.br/api/v1/geral/produtos/?WSDL", ResponseNamespace="http://app.omie.com.br/api/v1/geral/produtos/?WSDL")]
    [SoapHeader("autenticacao", Direction = SoapHeaderDirection.In)]
    [return: System.Xml.Serialization.SoapElementAttribute("produto_servico_list_response")]
    public produto_servico_list_response ListarProdutosResumido(produto_servico_list_request produto_servico_list_request) {
        object[] results = this.Invoke("ListarProdutosResumido", new object[] {
                    produto_servico_list_request});
        return ((produto_servico_list_response)(results[0]));
    }

Linha colocada na mão
[SoapHeader("autenticacao", Direction = SoapHeaderDirection.In)]

A: Parece meio complicada essa implementação.
Eu tenho vários serviços aqui que usam valores no Header, vou te mostrar duas soluções que podem te atender:
Atribuir valores no Header diretamente no Endpoint do arquivo de configuração:
Isso é legal pois serviços que tem arquivos de configuração, não precisam ter as configuração de Header no código, a não ser que seu serviço crie o ServiceHost no código. Serviços hosteados no IIS podem enviar informações no Header apenas adicionando isso no Endpoint.
<client>
  <endpoint address="http://dominio/NomeServico.svc"
      binding="basicHttpBinding" contract="Contrato" name="NomeConfiguracao">
    <headers>
        <app_key>123456789</app_key>
        <app_secret>topSecret</app_secret>
    </headers>
  </endpoint>
</client>

Esta é a maneira mais simples de fazer.
Manipulando o Endpoint no código:
Você pode manipular o Endpoint depois de criar o seu cliente e antes de chamar uma operação. Isso é interessante pois você pode passar valores variáveis e também que não ficam expostos no arquivo de configuração, mas tem que compilar o código:
ServicoWcf cliente = new ServicoWcf();
var endpointPersonalizado = new EndpointAddressBuilder(cliente.Endpoint.Address);
endpointPersonalizado.Headers.Add( AddressHeader.CreateAddressHeader("app_key", string.Empty, "123456789"));
endpointPersonalizado.Headers.Add( AddressHeader.CreateAddressHeader("app_secret", string.Empty, "topSecret"));
cliente.Endpoint.Address = endpointPersonalizado.ToEndpointAddress();

Você também pode manipular o OperationContextScope no cliente e adicionar o Header, mas eu prefiro as implementações acima. Espero que ajude.

A: Tente fazer da seguinte forma:
  ProdutoCadastroService.ProdutosCadastroSoapClient produtoCadastroWS = new    ProdutoCadastroService.ProdutosCadastroSoapClient();
  autenticaWsHeader(produtoCadastroWS);

  private static void autenticaWsHeader(ProdutosCadastroSoapClient produtoCadastroWS)
  {
        new OperationContextScope(produtoCadastroWS.InnerChannel);

        HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
        requestMessage.Headers["Username"] = "admin";
        requestMessage.Headers["Password"] = "123";
        OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
  }

A: using (Endpoint1WS.MeuObjectClient proxy = new Endpoint1WS.MeuObjectClient("BasicHttpBinding_IMeuObject1"))
            {
                using (new System.ServiceModel.OperationContextScope(proxy.InnerChannel))
                {
                    MessageHeader head = MessageHeader.CreateHeader("app_hey", "https://meuenderecoNamespace/", "123456");
                    OperationContext.Current.OutgoingMessageHeaders.Add(head);
                    var fatura = proxy.ObterAlgo();
            }
        }


text:
Q: Variable inside quotes I'm trying to pass a variable into an Ansible playbook.
ansible-playbook script.yml --extra-vars "status=false"

Here is my playbook:

- name: Enable fact
    set_fact:
      facts: '{{ facts | combine({ "configured_status": "{{status}}" })}}'
    vars:
      facts: '{{ facts_raw.content|b64decode }}'

  - debug:
      var: facts

However, The debug output is:
 "configured_status": "{{status}}"

Instead of:
"configured_status": "false"

Anyone knows what could be the issue?

A: Try
facts: '{{ facts | combine({ "configured_status": status })}}'

Why are you decoding facts? If you used slurp then
  - name: Enable fact
    set_fact:
      facts: "{{ facts_raw.content|b64decode|from_json|default([])| combine({ 'configured_status': status }) }}"

  - debug:
      var: facts

A: Because of the way you are passing your variables to extra-vars this can be as simple as
facts: '{{ facts | combine({ "configured_status": status }) }}'

This is actually pointed in the documentation:

Values passed in using the key=value syntax are interpreted as strings. Use the JSON format if you need to pass in anything that shouldn't be a string (Booleans, integers, floats, lists etc).

Source: https://docs.ansible.com/ansible/2.9/user_guide/playbooks_variables.html#passing-variables-on-the-command-line
So you don't even have to protect you from Ansible treating it as a boolean, as in the playbook below.

Now, would you pass it as a real boolean:
ansible-playbook script.yml --extra-vars '{ "status": false }'

Then, nesting Jinja delimiters would never lead you to any good.
Here, what you want to use is the contatenation operator of Jinja ~, so you can concatenate a string and the variable that status holds.
Given the playbook, play.yml:
- hosts: all
  gather_facts: no

  tasks:
    - debug:
        msg: '{{ facts | combine({ "configured_status": "" ~ status ~ "" })}}'
      vars:
        facts:
          foo: bar

Run with the command
ansible-playbook play.yml --extra-vars "status=false"

This yields the recap:
PLAY [all] *******************************************************************************************************

TASK [debug] *****************************************************************************************************
ok: [localhost] => {
    "msg": {
        "configured_status": "false",
        "foo": "bar"
    }
}

PLAY RECAP *******************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


text:
Q: GRANT ALL ON ALL TABLES TO user; in Postgres < 9 PostgreSQL 9 brought the new GRANT Option "...ON ALL TABLES...".
How can I do the same in PostgreSQL 8.2?
I have a Database 'myDatabase'
In myDatabse are 2 Schemas 'public' and 'myschema' with each around 20 Tables.
Now I created a new user for testing which needs to have all privileges on 'myschema'.
I already tried:
GRANT ALL ON SCHEMA myschema TO testuser;
GRANT ALL ON DATABASE myDatabse TO testuser;
GRANT ALL ON ALL TABLES IN SCHEMA myschema; (Which doesn't work in postgres 8)

What would work is the following. But I'm sure there must be a better way:
GRANT ALL ON myschema.table1 TO testuser;
GRANT ALL ON myschema.table2 TO testuser;
...
GRANT ALL ON myschema.tableN TO testuser;


text:
Q: Django I need upload file button only remove choose file and don't need refresh page when upload I want to upload only button  and don't need refresh when upload how to fix this
model_form_upload.html
<form method="post"  enctype="multipart/form-data">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit" >Upload</button>
</form>

forms.py
class DocumentForm(forms.ModelForm):
    class Meta:
        model = DocumentFile
        fields = ['document']

views.py
def model_form_upload(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = DocumentForm()
        print(form)
    return render(request, 'model_form_upload.html', {'form': form})


text:
Q: Ideals prime to the conductor in the ideal class group of an order Let $K$ be a number field, $\mathcal{O}_K$ its ring of integers and $\mathcal{O}$ an order in $K$.
I'm going through the proof for the formula linking the cardinality of the class group $Cl(\mathcal{O})$ to that of the class group $Cl(\mathcal{O}_K)$. I'm following the proof given here by Keith Conrad. At the end of page 11 he makes the following statement:

From the proof that $Cl(\mathcal{O})\longrightarrow Cl(\mathcal{O}_K)$ is surjective, we can represent each ideal class in $Cl(\mathcal{O})$ by an ideal $\mathfrak{b}$ of $\mathcal{O}$ which is relatively prime to the conductor $\mathfrak{c}$

and the fact that $Cl(\mathcal{O})\longrightarrow Cl(\mathcal{O}_K)$ is surjective is Theorem 5.1, which uses the fact that the same statement is true in the maximal order $\mathcal{O}_K$. However, although I can easily prove the statement for $\mathcal{O}_K$ using unique factorization and the Chinese Remainder Theorem, I can't really see how this implies that the same statement is true for $\mathcal{O}$. From the proof of Theorem 5.1 I can see that every coset of the kernel of the map $\psi:Cl(\mathcal{O})\longrightarrow Cl(\mathcal{O}_K)$ contains a class verifying the statement (just take $\mathfrak{a}$ in any class of $Cl(\mathcal{O}_K)$ such that $\mathfrak{a}$ is prime to the conductor and consider $\mathfrak{a}\cap\mathcal{O}$), and if I could use the explicit description of $\ker(\psi)$ which Conrad gives soon after that statement, then the statement would follow easily, as is done here on MathOverflow. However this description depends on the statement itself, so we can't use it.
So I guess I'm probably missing some trivial step, but I can't really see that, hence even hints are really appreciated.
Edit: The statement in the question is also mentioned by Pete L. Clark here, in the last 3 lines. The reference is Neukirch, but I can't find this claim in his book. Moreover I'm wondering wheter this question is more appropriate for MathOverflow, since I've only seen this claim in MO posts so far.
Edit 2: I've just found another claim which implies the aforementioned statement. It is Proposition 20.13 from these notes by Pete L. Clark:

Let $R$ be a Dedekind domain, $I$ a fractional ideal of $R$ and $J$ a nonzero integral ideal of $R$. Then there exists $a\in I$ such that $aI^{-1}+J=R$.

This is stated for Dedekind domains, but it seems to me that the proof given in the notes should still work even if $R$ is a non-maximal order, provided that we assume $I$ to be invertible. Indeed, using the same notations as in the original proof, there should be finitely many distinct prime ideals $\mathfrak{p}_1,...,\mathfrak{p}_r$ containing $J$, because if $\mathfrak{p}\supseteq J$, then $\mathfrak{p}$ is minimal on $J$, since $\dim R=1$, and in a noetherian ring there are finitely many minimal prime ideals on each ideal. Moreover $I\mathfrak{p}_1\cdots\mathfrak{p}_n\subsetneq I\mathfrak{p}_1\cdots\mathfrak{p}_{i-1}\mathfrak{p}_{i+1}\cdots\mathfrak{p}_n$ for all $1\leq i\leq r$, for otherwise, using the invertibility of $I$, we would find $\mathfrak{p}_1\cdots\mathfrak{p}_n=\mathfrak{p}_1\cdots\mathfrak{p}_{i-1}\mathfrak{p}_{i+1}\cdots\mathfrak{p}_n$, and considering that these are comaximal ideals, this implies $\mathfrak{p}_i\supseteq\mathfrak{p}_j$ for some $j\neq i$,  which is clearly impossible. Then the rest of the proof should work without any modification.
This is quite different from the proof I had found for the maximal order, since that proof relied too much on unique factorization to be extended to the non-maximal case. Although this should solve my question, I'm not closing it since I'm still interested in knowing if there is a way to prove the statement in non-maximal orders as a consequence of the fact that the same property holds true in the maximal order, which is what K. Conrad seemed to suggest in his notes. Moreover it would be nice if someone could confirm that what I wrote above is correct.

A: The original way I had written up what you asked about was rather garbled, but now I have updated the file. The task of representing each ideal class for an order by an ideal relatively prime to the conductor of the order is now a special case of the first part of Theorem 5.3. The proof of that has now been changed to an argument given by Will Sawin here, which is similar in some ways to the argument you describe.


text:
Q: tweepy.stream is giving 'None Type' object has no attribute 'on_exception' in streaming.py I am using this function to read Tweets from Twitter, and I am getting an error on line 6 in filter:
def sendData (c_socket):
    authorization = OAuthHandler(consumer_key, consumer_secret)
    authorization.set_access_token(access_token, access_secret)

    twitter_stream = Stream(authorization, Twitter(c_socket))
    twitter_stream.filter(languages=['en'], track=["#"])

A: Without a full traceback it's difficult to determine the exact issue, but whatever Twitter(c_socket) is, it's likely returning None instead of a StreamListener.


text:
Q: Can this do-able using regular expressions patterns (capture groups)? In JS, I have a set of strings that need to break down into an array. Each string can be breakdown up to 5 groups (Some have less). I'm using regex to break all.
In the below string sets if it includes aa bb orcc it needs to go into the capture group2.
Im not very familiar with regex unfortunately and stuck at this point.
Is this pattern doable only using regex or do I have to break the from :: to | and explode it later?
My regex pattern ^[ \t]*(?:(?:(\w+)\|)?(?:(\w+):(?:(\w+):)?)?)?(\w+)::(\w+)$ DEMO
String sets (each line run on a loop in JS):
                 group4::group5
              aa:group4::group5
              bb:group4::group5
              cc:group4::group5
          group1|group4::group5
       group1|aa:group4::group5

          group3:group4::group5
       aa:group3:group4::group5
   group1|group3:group4::group5
group1|aa:group3:group4::group5

Final results should be able to produce this...
var groups = {1:"group1", 2:"group2", 3:"group3", 4:"group4", 5:"group5"};

Regex pattern would be sufficient if anyone can help me on this

A: You may use this PCRE regex comprising a branch reset group, 5 separate capture groups, few optional matches and non-capturing groups:
^\h*(?:(?:(\w+)\|)?(?|(?:(aa|bb|cc):(?:(\w+):)?)|(?:((?2)):)?(\w+):)?)?(\w+)::(\w+)$

Updated RegEx Demo
PS: branch reset group doesn't work in Javascript.


text:
Q: how to encode data from database into a qr and then retrieve same data using a specific android application connected to your web based application Am a novice,and am trying to make this web based application in php that stores data to mysql database and then creates a qr code image for every entry.i want also to query this data using using a specific android application by scanning the embedded qr code.how will the two application connect.

A: Helo there,
You can create a unique id for each entry in database and save The QRCode image on server. You can use Endroid QRCode PHP Library for creating QRCode images. Now the android app should be able to scan the QR Code and When QR Code is detected it should call the webserver with the QRCode data. You should match this data with id in your database and return the results.


text:
Q: Dimension of the tangent space This question is regarding the dimension of the tangent space $T_p\mathbb{R}^n$ as it is defined in the context of smooth manifolds. One the one hand, $T_p \mathbb{R}^n$ can just be interpreted as a copy of $\mathbb{R^n}$ based at a chosen point $p \in \mathbb{R}^n$. Now, since this is just $\mathbb{R}^n$ translated through $p$, clearly $T_p \mathbb{R}^n$ has the same dimension as $\mathbb{R}^n$. To see this, just take the canonical basis $\{e_1, \dots, e_n \}$ translate it through $p$ and note that this will yield a basis of $T_p \mathbb{R}^n$. Thus, $dim( T_p \mathbb{R}^n) = n$
On the other hand though, for a given $p$, it is common to define the tangent space of $\mathbb{R}^n$ at $p$ as $T_p\mathbb{R}^n = \{(p,x) | x \in \mathbb{R}^n \}$ Here, $T_p\mathbb{R}^n$ is effectively a Cartesian product of the one point vector space $\{p\}$ and $\mathbb{R}^n$. By this reasoning,
$$
\displaystyle dim(T_p\mathbb{R}^n) = dim(\{p\} \times T_p \mathbb{R}^n) = dim(\{p\}) + dim(\mathbb{R}^n) = 1 + n
$$
Obviously, this last equation can't be correct but I'm not really sure where my reasoning is off. So, specifically, my question is where is the error in my logic?

A: After having convinced ourselves that a point should by all means have dimension $0$, we should still think a little bit more. I'm not going to answer the dimension question, as this seems to be settled by now.
There are actually two notions of tangent spaces, but in order to see it, we should look at a better example than $\mathbb{R}^n$ itself, so let us look at the $n$-sphere $$S^{n} = \{(x_0,\ldots,x_n)\in \mathbb{R}^{n+1}\,:\,x_{0}^2 + \cdots + x_{n}^2 = 1\},$$
which is only slightly more complicated for this issue.

*

*The tangent space at a point $p \in S^{n}$ is $T_p S^{n} = \{x \in \mathbb{R}^{n+1}\,:\, p \cdot x = 0 \} = p^{\perp}$. For instance, this can be seen by computing that $f(p) = \sum x_{i}^2$ has derivative $df(p)h = 2 p \cdot h$ and by definition $T_{p}S^{n} = \ker{df(p)}$. Note that this is a vector space (in particular it contains $0$). While it's not the space actually tangent to $S^{n}$ at the point $p$, it is this space that is usually called the tangent space (because vector spaces are very convenient to work with).

*The affine tangent space is the space $p + T_{p} S^{n}$ and is actually the plane tangent to $S^{n}$ at the point $p$. This is not a vector space, but an affine subspace of $\mathbb{R}^{n+1}$.


text:
Q: C++ how to compact fancy for-loops If one is too lazy to rewrite a fancy loop on some variable u, one can define a macro like this:
#define forloop(u) for (int u = 0; u < N; u++)

Now, let's say I want to do this
for (int u = 0; u < N; u++) {
    Class& var_u = someFunctionOf(u)
    ... code using var_u ...
}

And let's say I need to do that at several places in the code, and I am too lazy to rewrite it, because the loop involves complicated conditions on multiple variables. How can I compress it into a macro ? I feel it is annoying to put only one { in the macro because whatever IDE you are using it will break syntax highlighting and everything...
I actually just had an idea:
Define a template:
template <typename Loop> void forloop(int u, const Loop& loop) {
    for (int u = 0; u < N; u++) {
        Class& var_u = someFunctionOf(u)
        loop(u, var_u);
    }
}

So that I only have to write:
forloop([&](int u, Class& var_u){
    ... code using var_u ...
});

I know, I'm weird. Is that a good idea? Will everything be inlined 100% of the time? Do I not lose any performance by doing that instead of regular for loop? Performance is critical in my case.
Other way I thought about:
#define forloop(u, var_u) for (int u = 0; u < N; u++) { Class& var_u = someFunctionOf(u)
#define forloop_end }

Now call:
forloop(u, var_u)
... code using var_u ...
forloop_end

Now it is not so good because {} disappeared, so an IDE syntax checker can get confused if I use same variable names inside the loop as variables defined earlier outside of the loop. So I thought maybe one can do this:
forloop(u, var_u) {
... code using var_u ...
} forloop_end

But then does the extra layer of { } reduces performance (even very slightly)?
Feels like the two } will mean 2 rounds of object destruction. Is that slower than destroying the same set of objects in one round only? Intuitively it feels like some stack pointer would have to move twice instead of once, but maybe compiler is smart enough to optimize that?
Yes I care about speed and don't want my loops to be slower than the regular way, but I feel it would help code readability to remove those annoying reference initializations at the beginning of every loop in my code.
Thank you for comments and suggestions.

A: Write index_range.  Write map_range.
for (auto& var_u: map_range(someFunctionOf)( index_range(0,N) ) ){
  ... code using var_u ...
}

compress by storing map_range(someFunctionOf) somewhere shared, or even the index range.
You never have guarantees that things are inlined.  Write clean compile-time abstract code and profile if it matters.


text:
Q: UDP client now listening if server has send muliple ip Currently i have facing one problem in portrestrictedcone nattype.When my udp client hit the server with test1.dns.com (to sepcific IP 111.111.111.111 and this ip is bind with DNS test1.dns.com) where i am getting response from different IP and not with 111.111.111.111, however the same scenario is working for fullcone nattype. If the server response from the same above ip i am able to get the response.
Currently there are two services running on the server on UDP, one is which is working in portrestrictedcone and send response on same IP as a result i am getting the response, however second service is not behaving in same was as first service works.
i am running both the services on same DNS as i have describe above.
Can i get the help what i need to change on the server or client side to get this resolve?

A: I think your problem is that you are not sending the packet to the port you received it from (Allocated by NAT). When you receive a packet, check the port that was used to send it then send your response to that port and not to a predefined port because the NAT might change it.


text:
Q: Use public class from Activity in xml with attrbs (ClassNotFoundException) I have created a public class in my main activity e.g.:
public class ActivityMain extends FragmentActivity {
     // ...

    public class MyClass extends Something implements SomethingListener{

        public MyClass(Context context) {
            super(context);
        }

        public MyClass(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public MyClass(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

        // Listener overrides

    }
}

And I use it in my layout xml like:
<my.package.ActivityMain.MyClass
   app:pstsShouldExpand="true"
   //parameters
/>

That way I get a ClassNotFoundException just on the setContentView(R.layout.my_layout) line in Activity's onCreate().
Also the xml design editor on Android Studio complains about this class:
Exception Details java.lang.NoSuchMethodException:
my.package.ActivityMain$MyClass.<init>(android.content.Context, android.util.AttributeSet)

If I used in the xml the class which I extend, all render good. E.g:
xml:
<external.package.Something
   android:id="@+id/object"
   app:pstsShouldExpand="true"
   //parameters
/>

ActivityMain:
Something something = (Something) findViewById(R.id.object)
something.setSomethingListener(new SomethingListener( ... ))

Of course the above solves this issue but is it possible to use a class created in an Activity in my XML?

Update:
The Something class has custom attributes e.g. app:pstsShouldExpand="true" not sure if they are passed down to it from my MyClass. It might be the issue.


text:
Q: How to update/upgrade a Facebook App API version on Facebook's Developers Panel? I even need to do it? I received, recently, an e-mail from Facebook telling me that my APP is doing some deprecated calls that will stop working on August, 8th
Using the Facebook API Migration Tool, it shows me no calls to older APIs, so, I am good to go
I use the Facebook PHP SDK in my application and all places where "graph_version" appears, it is forced to v2.5
In Facebook's Developers Dashboard, my APP is showing API version 2.0 (was the API at the creation time)
So, do I need to worry? When the date comes, will my APP API Version change automaticly? How can I update my APP info on Dashboard to set the API version to 2.5 or above?
Thank you in advance

A: You can upgrade the Facebook API version of your app simply by going to the app dashboard, then Settings -> Advanced (in a drop-down menu under Settings) or use the URL: https://developers.facebook.com/apps/YOUR_APP_ID_HERE/settings/advanced/

A: If you press on the "?" mark, you will see that this is the oldest version your app can call. It means you can use any versions that newer than this version, all older versions can not be used.
So you'll be ok.


text:
Q: Convergence of series, using big oh or little oh notation. Let $p\in \mathbb{R}$ and $a_n=(e-(1+1/n)^n)^p$. For which $p$ will $\sum_{n=1}^{\infty} a_n$ converges?
Because of the "additive look" of $a_n$, I tried to use taylor expansion and big oh, little oh notation to solve the problem but I couldnt solve it, please helps. Below is what i have done so far:
Observe that $\ln (1+x)=x+O(x^2)$ and $1-e^x \sim -x$. Hence
$$(1+1/n)^n=e^{n \ln (1+1/n)}=e^{n(1/n+O(1/n^2))}$$ and
$$e-(1+1/n)^n=e-e^{1+O(1/n)}=e(1-e^{O(1/n)}) \sim e(-O(1/n))=O(1/n).$$
So
$$a_n= (e-(1+1/n)^n)^p \sim O(1/n)^p=O(1/n^p)$$
But then I dont know how to move on...

A: That was quite good, but you need to go deeper if you want to solve by just using asymptotics.
$\displaystyle e^1-\exp\left(n\ln\left(1+\frac{1}{n}\right)\right)=\\e^1-\exp\left(n\left(\frac{1}{n}-\frac{1}{n^2}+o\left(\frac{1}{n^2}\right)\right)\right)=\\e^1\times\left(1-\exp\left(\frac{-1}n+o\left(\frac{1}{n}\right)\right)\right)=\\\displaystyle e^1\times\left(1-\left(1-\frac{1}{n}+o\left(\frac{1}{n}\right)\right)\right)=\\e^1\times \left(\frac{1}{n}+o\left(\frac{1}{n}\right)\right). $
Therefore, $\displaystyle a_n\sim\frac{e^1}{n^p}$, which is more powerful than a mere $a_n=O(1/n^p)$
You should already know that when $a_n\sim b_n$ and $a_n > 0$ then $\sum a_n$ converges iff $\sum b_n$ converges.
Therefore, $\sum a_n$ converges iff $\sum 1/n^p$, that is iff $p>1$.


text:
Q: Groovy-Issue: recalling a closure inside of a vbox again, when a spinner's stateChanged fires an action If you take the numPanels as a fixed value of e.g. 20, it's really a nice and groovy swinging.
But I try since two days to add more or less panels with a groovy.swing.Spinner dynamically  (my program will be used to connect to different databases and exchange values from different db-tables). I tried with binding, revalidating, repainting - but I can't bring the closure to take the new value from the spinner...
import groovy.swing.SwingBuilder
import javax.swing.WindowConstants as WC
import javax.swing.JOptionPane
import javax.swing.JScrollPane
import javax.swing.BoxLayout as BXL
import javax.swing.SpinnerNumberModel

int numPanels = 2

swing = new SwingBuilder()

def setPanelAmount = swing.action(name:'Amount of Panels in vbox-element',  closure: this.&setPanelAmount )

frame = swing.frame(title:'test', pack:true, visible:true, defaultCloseOperation:WC.HIDE_ON_CLOSE) {
panel(id:'mainPanel'){
scrollPane( verticalScrollBarPolicy:JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ) {
  vbox {
    (1..numPanels).each { num ->
      def panelID = "panel$num"
      def pane = panel( alignmentX:0f, id:panelID, background:java.awt.Color.GREEN ) {
        label('description')
        textField( id: "description$num", text:panelID, columns: 70 )
        button( id: "buttonpanel$num", text:panelID, actionPerformed:{
          swing."$panelID".background = java.awt.Color.RED
        } )
      }
    }
  }
}

boxLayout(axis: BXL.Y_AXIS)
panel(id:'secondPanel' , alignmentX: 0f){
 hbox(){
 label 'Change amount of panels:'
 hstrut(10)
  spinner(id: 'numPanelSpinner', stateChanged: this.&setPanelAmount, model: new SpinnerNumberModel(2, 2, 10, 1))
  hstrut(50)
  button('Quit', actionPerformed:{
    frame.visible = false
  })
  }
}
}
}
frame.size = [ frame.width, 600 ]

def setPanelAmount(event) {
    numPanels = swing.numPanelSpinner.getValue()
    }

A: It has to be combined with the following code - but unfortunately, it's not working with an included closure - at least as far as I know now...
import groovy.swing.*
import javax.swing.*
import java.awt.*
import java.awt.BorderLayout as BL

new SwingBuilder().edt {
  frame(defaultCloseOperation: JFrame.EXIT_ON_CLOSE, visible: true, size: [600,500]) {
   panel(id:'main') {
    panel {
      button(name:'x', action: action(name:'add', closure:{p.add(label('new')); p.revalidate()}))
      button(action: action(name:'remove', closure:{p.removeAll();p.revalidate();scroll.repaint()}))
}

panel() {
  scrollPane(id:'scroll',preferredSize: [200,200], constraints: context.CENTER) {
    panel(id:'p') {
      checkBoxList(listData: (1..20).collect([]){"Option $it"} as Object[])
    }
  }
}
  }
 }
}

BTW.: do you like to improve in programming groovy, too?
I would be glad to start a git-based "engineering" with my program.
This program will compare a user given amount of lists with articles coming from one or more databases or excel-files, save them and every result in PostgreSQL or MSSQL.
Every list may have zero, one or more articles listed identified by their article-numbers, with varying amounts in each entity.
And the user can - guided by a GUI - decide in which order to add or subtract the entities from another. The other (zero to infinite) attributes beside of article-number and amount will be carried through the lists.
Not too complicated but for a first project...


text:
Q: How to linearise constraint including summation and min in an optimisation problem? I have the following constraint to an optimisation problem:
Σ min(wj,0) ≥ −30 for j = 1,...,n

How can I linearise it introducing only n new non-binary decision variables?

A: sum(j, min(w(j),0)) >= -30

can be linearized with additional continuous variables y(j):
y(j) <= w(j)
y(j) <= 0
sum(j, y(j)) >= -30

Note that the interpretation of y(j) is a bit difficult. It is y(j) <= min(w(j),0) and not y(j) = min(w(j),0). As long as the limit of -30 is not reached it may be less than expected. So you probably should not report y(j) to the user.
I hope this was not a homework question.


text:
Q: How to perform XSLT Transformation with Java extension from within OSGi Bundle We are in the process of converting existing code to an OSGi environment. In one of our (yet to be) OSGi bundles we have code that perform an XSLT transformation. A piece of the XSLT includes a java extension function to create a unique numeric value. The Java class also resides within the bundle. This is a fragment of the style sheet:
<xsl:template match="m:property">
   <xsl:variable name="uniqueDataStreamName" select="concat(../@id,'/',@name)" />
   <xsl:variable name="uniqueDataStreamId"
       select="java:com.xyz.TransformationUtils.makeDataStreamIdFromUniqueName($uniqueDataStreamName)" />
   <data id="{number($uniqueDataStreamId)}">
   <tag>
      <xsl:value-of select="$uniqueDataStreamName" />
   </tag>
   <current_value>
     <xsl:value-of select="@value" />
  </current_value>
</data>

For reference, this is how the transformation is set up and called:
protected Templates createTemplates(Source xsltSource) {
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Templates templates = tf.newTemplates(xsltSource);
        return templates;
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}

protected byte[] transform(byte[] input) throws TransformerException {
    ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
    templates.newTransformer().transform(
            new StreamSource(new ByteArrayInputStream(input)),
            new StreamResult(out));
    return out.toByteArray();
}

When run in a non OSGi environemnt, it works. When run in an OSGi framework, it fails because the stylesheet cannot be compiled because the class TransformationUtils cannot be found. I kind of understand that--the class loader loading the jaxp transformer implementation does not see the extension class in our bundle. However, I'm stumped at finding a solution. I've tried using OSGi:fied Xalan and Xerces bundles to no avail.
My question is: How can this be solved? Can it?

A: The answer depends on how the XSLT processor looks up the extension class. You might need to read the source code and/or run it through a debugger to find this out.
For example, if the XSLT processor uses the Thread Context ClassLoader (TCCL) then this would normally fail because the TCCL is undefined in OSGi. You can work around this by explicitly setting the TCCL for the duration of the call to the XSLT processor, e.g.:
ClassLoader orig = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(MyClass.class.getClassLoader());
try {
    // invoke XSLT processor
} finally {
    Thread.currentThread.setContextClassLoader(orig);
}

where MyClass is a class from your bundle and has visibility of the extension class.
In the worst case, the processor might look up the extension using its own classloader, i.e. with a simple call to Class.forName(). The best thing to do here is to beat up the developer of the library for being so stupid. After you've done that, you could use a fragment to attach the extension class to the processor bundle... it's a nasty hack but better than some of the other possible nasty hacks.


text:
Q: SocketIO Server doesnt handle fired event from client In the event handler window.onunload the client fires event:
function onPageUnload() {
   userSocket.emit('command', "{'cloudBackup': 'cancel'}");
}

On the server I have a listener:
io.on('connect', function(socket) {
    console.log("RIKO ::: SocketIO connected!");

    socket.on('command', function(msg) {
        console.log("RIKOO ::: command with msg : " + msg);
        backupOnceProcCanceled = true;
        console.log("PC = " + backupOnceProcCanceled)
        // throw new Error("RIKO ::: Thrown Error at backup2.js line 106")
    });

    socket.on( 'disconnect', function(reason) {
        console.log("RIKO ::: SocketIO disconnected! Reason : " + reason );
    })
})

When the client refresh/leave/navigate the page I see that the browser fires the event
('command', "{'cloudBackup': 'cancel'}")
But the server doesn't detect the event. Only when the port is closed:

RIKO ::: SocketIO disconnected! Reason : transport close

A: The wildcard you are using isn't a valid way of catching all events. You can write a little middleware to catch those:
io.on('connect', function(socket) {
    console.log("RIKO ::: SocketIO connected!");

    socket.use((packet, next) => {
        console.log("RIKOO ::: command with msg : " + msg);
        backupOnceProcCanceled = true;
        console.log("PC = " + backupOnceProcCanceled)
        // throw new Error("RIKO ::: Thrown Error at backup2.js line 106")
        next();
    });

    socket.on( 'disconnect', function(reason) {
        console.log("RIKO ::: SocketIO disconnected! Reason : " + reason );
    })
})

The socket.use() function has been added for this purpose specifically. You can take a look at the documentation at the following link: https://socket.io/docs/server-api/#socket-use-fn
Or alternatively you can catch this particular event by just changing the * to command.

A: Very strange but inserting delay in "onPageUnload" function solved the problem.
function waitMs(ms) {
   var start = Date.now()
   var now = start;
   while(now - start < ms){
       now = Date.now()
   }
}

function onPageUnload() { //window.onunload = onPageUnload;
   userSocket.emit('command', "{'cloudBackup': 'cancel'}");
   waitMs(50);
   console.log("SOCKET send cloudBackup cancel 1 ");
}

I am saying strange because the event should be handled despite the delay.
May be when the page is being reloaded the Server load is high and before it can handle the event the port is already closed.
Still not sure.


text:
Q: orientation_histogram[:, :, i] = temp_filt[subsample] TypeError: slice indices must be integers or None or have an __index__ method def hof(flow, orientations=9, pixels_per_cell=(8, 8),
        cells_per_block=(3, 3), visualise=False, normalise=False, motion_threshold=1.):

    """Extract Histogram of Optical Flow (HOF) for a given image.

    Key difference between this and HOG is that flow is MxNx2 instead of MxN

    Compute a Histogram of Optical Flow (HOF) by

        1. (optional) global image normalisation
        2. computing the dense optical flow
        3. computing flow histograms
        4. normalising across blocks
        5. flattening into a feature vector

    Parameters
    ----------
    Flow : (M, N) ndarray
        Input image (x and y flow images).
    orientations : int
        Number of orientation bins.
    pixels_per_cell : 2 tuple (int, int)
        Size (in pixels) of a cell.
    cells_per_block  : 2 tuple (int,int)
        Number of cells in each block.
    visualise : bool, optional
        Also return an image of the hof.
    normalise : bool, optional
        Apply power law compression to normalise the image before
        processing.
    static_threshold : threshold for no motion

    Returns
    -------
    newarr : ndarray
        hof for the image as a 1D (flattened) array.
    hof_image : ndarray (if visualise=True)
        A visualisation of the hof image.

    References
    ----------
    * http://en.wikipedia.org/wiki/Histogram_of_oriented_gradients

    * Dalal, N and Triggs, B, Histograms of Oriented Gradients for
      Human Detection, IEEE Computer Society Conference on Computer
      Vision and Pattern Recognition 2005 San Diego, CA, USA

    """
    flow = np.atleast_2d(flow)

    """
    -1-
    The first stage applies an optional global image normalisation
    equalisation that is designed to reduce the influence of illumination
    effects. In practice we use gamma (power law) compression, either
    computing the square root or the log of each colour channel.
    Image texture strength is typically proportional to the local surface
    illumination so this compression helps to reduce the effects of local
    shadowing and illumination variations.
    """

    if flow.ndim < 3:
        raise ValueError("Requires dense flow in both directions")

    if normalise:
        flow = sqrt(flow)

    """
    -2-
    The second stage computes first order image gradients. These capture
    contour, silhouette and some texture information, while providing
    further resistance to illumination variations. The locally dominant
    colour channel is used, which provides colour invariance to a large
    extent. Variant methods may also include second order image derivatives,
    which act as primitive bar detectors - a useful feature for capturing,
    e.g. bar like structures in bicycles and limbs in humans.
    """

    if flow.dtype.kind == 'u':
        # convert uint image to float
        # to avoid problems with subtracting unsigned numbers in np.diff()
        flow = flow.astype('float')

    gx = np.zeros(flow.shape[:2])
    gy = np.zeros(flow.shape[:2])
    # gx[:, :-1] = np.diff(flow[:,:,1], n=1, axis=1)
    # gy[:-1, :] = np.diff(flow[:,:,0], n=1, axis=0)

    gx = flow[:,:,1]
    gy = flow[:,:,0]

    """
    -3-
    The third stage aims to produce an encoding that is sensitive to
    local image content while remaining resistant to small changes in
    pose or appearance. The adopted method pools gradient orientation
    information locally in the same way as the SIFT [Lowe 2004]
    feature. The image window is divided into small spatial regions,
    called "cells". For each cell we accumulate a local 1-D histogram
    of gradient or edge orientations over all the pixels in the
    cell. This combined cell-level 1-D histogram forms the basic
    "orientation histogram" representation. Each orientation histogram
    divides the gradient angle range into a fixed number of
    predetermined bins. The gradient magnitudes of the pixels in the
    cell are used to vote into the orientation histogram.
    """

    magnitude = sqrt(gx**2 + gy**2)
    orientation = arctan2(gy, gx) * (180 / pi) % 180

    sy, sx = flow.shape[:2]
    cx, cy = pixels_per_cell
    bx, by = cells_per_block

    n_cellsx = int(np.floor(sx // cx))  # number of cells in x
    n_cellsy = int(np.floor(sy // cy))  # number of cells in y

    # compute orientations integral images
    orientation_histogram = np.zeros((n_cellsy, n_cellsx, orientations))
    subsample = np.index_exp[cy / 2:cy * n_cellsy:cy, cx / 2:cx * n_cellsx:cx]
    for i in range(orientations-1):
        #create new integral image for this orientation
        # isolate orientations in this range

        temp_ori = np.where(orientation < 180 / orientations * (i + 1),
                            orientation, -1)
        temp_ori = np.where(orientation >= 180 / orientations * i,
                            temp_ori, -1)
        # select magnitudes for those orientations
        cond2 = (temp_ori > -1) * (magnitude > motion_threshold)
        temp_mag = np.where(cond2, magnitude, 0)

        temp_filt = uniform_filter(temp_mag, size=(cy, cx))
        orientation_histogram[:, :, i] = temp_filt[subsample]

    ''' Calculate the no-motion bin '''
    temp_mag = np.where(magnitude <= motion_threshold, magnitude, 0)

    temp_filt = uniform_filter(temp_mag, size=(cy, cx))
    orientation_histogram[:, :, -1] = temp_filt[subsample]

    # now for each cell, compute the histogram
    hof_image = None

my error is like
orientation_histogram[:, :, i] = temp_filt[subsample]
TypeError: slice indices must be integers or None or have an __index__ method

i tried giving as int(i) but still get same error
I tried to re-install numpy versions but couldnt
What to do

A: I can reproduce the error message with:
In [213]: np.arange(10)[np.s_[1:[1,2]]]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-213-1eef9127a94e> in <module>
----> 1 np.arange(10)[np.s_[1:[1,2]]]

TypeError: slice indices must be integers or None or have an __index__ method

In [214]: np.s_[1:[1,2]]
Out[214]: slice(1, [1, 2], None)     # a poorly defined slice object

A float slice value would also produce this error: np.s_[1:1.23]
So the error is in:
subsample = np.index_exp[cy / 2:cy * n_cellsy:cy, cx / 2:cx * n_cellsx:cx]
temp_filt[subsample]

I'm not going to try to figure out the inputs that np.index_exp.  You can do that, and verify whether the resulting slice, or tuple of slices, looks valid.


text:
Q: GifImageView: как и где указать источник анимации В общем, проблема с подключением библиотеки GifImageView,
мне нужно поместить анимацию gif.
Создаю элемент
<com.felipecsl.gifimageview.library.GifImageView
    android:id="@+id/gifImageView"
    android:layout_gravity="center"
    android:scaleType="fitCenter"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

но как и где указать мою gif анимацию? В примере там только загрузка из сети.
может кто знает? Или может есть лучше библиотека?

A: Как через разметку не знаю, но программно так:
gifView.setBytes(bitmapData);

Получение Bitmap:
InputStream is = context.getResources().openRawResource(R.drawable.my_image);
bitmapData = BitmapFactory.decodeStream(is);

A: В ByteArrayHttpClient там просто читается файл в byte[], дальше этот массив отдается в gifImageView.setBytes(byte[] bytes).
Наверное, будет что-то похожее на
@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gifImageView = (GifImageView) findViewById(R.id.gifImageView);

    InputStream ins = getResources().openRawResource(R.raw.gif_file);
    gifImageView.setBytes(org.apache.commons.io.IOUtils.toByteArray(in));
    gifImageView.startAnimation();
}

Файл должен быть в /res/raw/.


text:
Q: Get all forms data from input field in codeigniter I have 200 input field in my page. All are radio button of group of 5. How can I get the data of input field. Names of all input field are created dynamically from database.
My code is as follows
$attributes = array('class' => 'result', 'id' => 'result', 'name' => 'result');
                        echo form_open('exam/result',$attributes);
                    $a = array(
                            'name'          => 'aptitude-'.$value->question_id,
                            'id'            => 'answer1',
                            'value'         => 'a',
                            'checked'       => FALSE,
                        );
                    $b = array(
                            'name'          => 'aptitude-'.$value->question_id,
                            'id'            => 'answer2',
                            'value'         => 'a',
                            'checked'       => FALSE,
                        );
                    $c = array(
                            'name'          => 'aptitude-'.$value->question_id,
                            'id'            => 'answer3',
                            'value'         => 'a',
                            'checked'       => FALSE,
                        );
                    $d = array(
                            'name'          => 'aptitude-'.$value->question_id,
                            'id'            => 'answer4',
                            'value'         => 'a',
                            'checked'       => FALSE,
                        );
                    $e = array(
                            'name'          => 'aptitude-'.$value->question_id,
                            'id'            => 'answer5',
                            'value'         => 'a',
                            'checked'       => FALSE,
                        );
                    $f = array(
                            'name'          => 'aptitude-'.$value->question_id,
                            'id'            => 'answer6',
                            'value'         => 'a',
                            'checked'       => TRUE,
                            'style'         => 'display:none'
                        );

                    echo form_radio($a);
                    echo form_label($value->a, 'a');
                    echo "
";

                    echo form_radio($b);
                    echo form_label($value->b, 'b');
                    echo "
";

                    echo form_radio($c);
                    echo form_label($value->c, 'c');
                    echo "
";

                    echo form_radio($d);
                    echo form_label($value->d, 'd');
                    echo "
";

                    echo form_radio($e);
                    echo form_label($value->e, 'e');
                    echo "
";

                    echo form_radio($f);

                    echo form_close();

This code will run for 200 times

A: Use array name aptitude[]:
$a = array(
        'name'          => 'aptitude['.$value->question_id.']',
        'id'            => 'answer1',
        'value'         => 'a',
        'checked'       => FALSE,
    );
$b = array(
        'name'          => 'aptitude['.$value->question_id.']',
        'id'            => 'answer2',
        'value'         => 'b',
        'checked'       => FALSE,
    );
$c = array(
        'name'          => 'aptitude['.$value->question_id.']',
        'id'            => 'answer3',
        'value'         => 'c',
        'checked'       => FALSE,
    );
$d = array(
        'name'          => 'aptitude['.$value->question_id.']',
        'id'            => 'answer4',
        'value'         => 'd',
        'checked'       => FALSE,
    );
$e = array(
        'name'          => 'aptitude['.$value->question_id.']',
        'id'            => 'answer5',
        'value'         => 'e',
        'checked'       => FALSE,
    );
$f = array(
        'name'          => 'aptitude['.$value->question_id.']',
        'id'            => 'answer6',
        'value'         => 'f',
        'checked'       => TRUE,
        'style'         => 'display:none'
    );

Get POST value:
$aptitudes = $this->input->post('aptitude');

print_r($aptitudes);

// example output
[7] => a
[5] => c
[3] => f
// where [7] [5] [3] are the $value->question_id

Get specific POST
$aptitudes[5]; // output => c


text:
Q: Attempt to insert record on page where this table is not allowed I get the message above (Attempt to insert record on page where this table is not allowed) when trying to create a new record from an extension.

*

*The "page" i try to create the record in is a sysfolder and not a page

*t3lib_extMgm::allowTableOnStandardPages('user_myext_categories'); is set

*there are already records of categories on this page

*there is no 'type' => definition in TCA, but the table itself is registered in TCA like the other tables from this extension (and they work)

Any hints on this?

A: Perhaps the creation of tables of this type is deactivated via Page-TS-Config? Via mod.web_list.allowedNewTables / deniedNewTables it is possible to disable the creation of new tables.
You need to check each Page-TS-Config in the rootline or have a look at the info module.
Perhaps try to create a new "root" page and add your table there. If that works, it is a Page-TS-Config configuration:)

A: in the ext_table you need this: \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::allowTableOnStandardPages('XXXXXX');


text:
Q: blk_update_request: I/O error, dev mmcblk1, - it is possible skip or disable disk ubuntu 21.10? I have problem with my device with drive eMMC, disk is corrupted and when I install Ubuntu on SD Card i see below problem when system starts.
blk_update_request: I/O error, dev mmcblk1, sector ************ op: (READ) flags 0x0 pyhs_seg 1 prio class 0
System's start takes about 2 hours even and during this time many errors like above one appears.
My question is, is it possible to disable this disk at the beginning of boot system, or skip  detecting device/drive?
I have installed and setup UDEV but unfortunately it didn't solve my issue.
Bellow my installation comand.
sudo apt-get update
sudo apt-get install udev
I use after that comand:
dmesg | grep
mmcblk1 - 8 GB SD Card
mmcblk2 - 32 GB eMMC Internal Drive
mmcblk2boot0 - ?
mmcblk2boot1 - ?
Below is my configuration for udev.
cat /etc/udev/rules.d/hide-mmcblk.rules
KERNEL=="mmcblk2", ENV{UDISKS_IGNORE}="1"
KERNEL=="mmcblk2boot0", ENV{UDISKS_IGNORE}="1"
KERNEL=="mmcblk2boot1", ENV{UDISKS_IGNORE}="1"
I would really appreciate any help.


text:
Q: Analogy of $[0,1]^n$ A probability maps a set (such as 1 dimensional path) to $[0,1]$. Is there a sufficient and necessary analogy of $[0,1]^n$ to a $n-$dimensional cube ? or to $n-$dimensional other well known objects ?
To clarify:
(1)From probability theory, is it sufficient and necessary to obtain the map to $[0,1]^n$ ? This can start with a function or other structures or objects to preserve or generalize the properties in one dimensional case.
(2)From other theory, is it sufficient and necessary to obtain an algebraic object mapping to $[0,1]^n$ ?  There is a special case lifting cubes, but I need to know how to obtain the map to $[0,1]^n$.


text:
Q: How to define the electric and magnetic fields of an EM Wave in a vacuum? After learning about the production and propagation of electromagnetic waves I've become a bit stuck in my understanding of how to think of the electric and magnetic fields that make up an electromagnetic wave.
I thought what if someone sent an EM wave out into space, a perfect vacuum where there is nothing else around. How do the electric and magnetic fields of the EM wave still exist if there is nothing there?
I'm not sure if I'm right in saying that light travels in photos, so is there an equivalent to the photon that all Em waves travel in?
I understand that EM waves are self-perpetuated due to the interactions between changing electric and magnetic fields as described by Maxwell's third and fourth equations, but I'm stuck conceptually on what they are if there are no electrons or conductors around.
I hope I've explained myself well enough, and would really appreciate a new perspective.

A: You've come to a long time phyilosophical question: does a field actually "exist"? We cannot measure fields.
There is no instrument able to measure a "field". The instrument you use to measure electric field is actually based on forces. The instrument detects an electric force and then it deduces the value of the $E$ field.

*

*In an empty space, there's nothing.

*With one charge, there's electric field everywhere $(E=K\frac{Qq}{r^2})$

*As soon as there are more than one charge, two forces appear between every pair of charges. Those forces are such that $F=q\cdot E$
And there are tons of charges everywhere. The measurign instrument itself is made up of charges. What the instrument measures is forces between charges. Then $E=F/q$.
What I mean is that we cannot observe fields, we can only detect their effect on matter.
So, regardless of whether they actually exist or not... the reality works LIKE if they were real.
And a field is nothing more than a mathematical idea. It's a function of space,
$$\vec{E}: \mathbb{R}^3 \rightarrow \mathbb{R}^3$$
$$\vec{r}\in \mathbb{R}^3 \rightarrow \vec{E}(\vec{r})$$
For every point $(x,y,z)$ in the space, there is a vector $\vec{E}$ in that point (unless there is a charge in that point).
So fields are just vectors in space, in the same way as you study geometry in mathematics: there are ideal objects (points, lines, planes...). In the same way, there are electric force vectors, defined at some point in space.
And we cannot observe that vectors, they are mathematical constructs. We can observe their effects on matter. Do those effects come from that vector? We don't know, but it's LIKE IF they did.

A:
I understand that EM waves are self-perpetuated due to the
interactions between changing electric and magnetic fields as
described by Maxwell's third and fourth equations, but I'm stuck
conceptually on what they are if there are no electrons or conductors
around.

people were stuck like you begininning of the 20th century thinking the EM waves required a medium. But the medium couldnt be detected, so Einstein said there was none, then said it was spacetime.
The magnetic force is a relativistic effect of the electric force, so we are left with the electric force.

but I'm stuck conceptually on what they are if there are no electrons
or conductors around.

The electric force is a concept like eveything in physics (what is potential energy you could ask similarly), and the concept is defined by its effects (the electric force accelerates charged particles). I'd be more interested in knowing why it sticks to electrons rather than what it is without it.
Finally I doubt you'll get the meaningful answer you are looking for, simply because I don't think we understand what's below electromagnetism yet, for now it's just a primitive unbreakable lego brick of physics

A: Electromagnetic radiation is the emission of photons from excited subatomic particles. The light from a heated wire is an example of the stochastic emission of photons from the excited electrons in the wire.
The concept of EM radiation as a stream of quanta was a by-product of Planck's equation for blackbody radiation. He did not initially believe that the energy packets introduced were real particles. Later, Einstein interpreted the photoelectric effect with the existence of such quanta, later called photons.
If you move far enough away from such a heat source or dim the radiation with filters, you end up measuring single incoming photons. They could be made visible by photoemulsion plates or electronic devices (CCD chip).
It has long been known that light does not need a medium. Otherwise, light from celestial bodies would not reach us. Light travels through the vacuum, every single photon does so.
In short, photons are indivisible particles from emission to absorption and spread out in empty space between emission and absorption.
The fact that photons consist of an electric and a magnetic field component can be observed in radio waves. Synchronously accelerated electrons in the antenna emit photons with an electric field component all aligned parallel to the antenna and with a magnetic field component aligned perpendicular to the antenna. Hertz was the first to measure these components.

How to define the electric and magnetic fields of an EM Wave in a vacuum?

In a vacuum, the electric and magnetic field components of each photon in EM radiation are perpendicular to the direction of motion and perpendicular to each other. The Cartesian coordinate system is useful for illustration. If X is the direction of propagation of the photon, then Y and Z are the directions of the field components.
For photons from thermal sources, the direction of the Y-Z pair is random with respect to X. For radio waves, free-electron lasers or cyclotron radiation, for example, the electric field component is parallel to the acceleration direction of the electrons involved.


text:
Q: Graphic Spark User Interface :4040 in SSH VM I am executing Spark in cluster mode in 2 Azure VMs. As usual, I'm connected to these machines through SSH and I can access to http://localhost:4040 through a command line browser and "see" job progress.
Since command line browsers are really poor, I'd like to see the classical Web User Interface offered by Spark, in order to appreciate the Graphical details. Is there a solution to reach this goal?

A: You might try to run a modern browser via ssh with x11 forwarding. Use the compression option to speed up the experience.

A: I believe the most straightforward way to go is to open port 4040 and just connect from your browser locally to the Web UI on the remote machine.
Be advised, of course, that you may want to pay extra-attention to how the node is secured once it's open for connection from the external world.
As mentioned in a comment, opening ports on Azure is documented here.


text:
Q: If Else regex matching I want to build a regex where it searches for a string containing 12 digits in a row. If there's no match, look for a string with only 10 digits in a row.
For example:
a123456789012a
a1234567890a

Would return:
123456789012

And if the input is:
a1234a
a1234567890a

It would return:
1234567890

I managed to create the regex for the individual operations, beeing (?<!\d)\d{10}(?!\d) for 10 digits and (?<!\d)\d{12}(?!\d) for 12 digits, but I can't group them up in a if-else style.
I tried the following:
(?(?<!\d)\d{12}(?!\d)|((?<!\d)\d{10}(?!\d)))

but if the first pattern don't match, the regex don't try to match the second, returning nothing

A: You can use a simple regex like this:
\d{12}|\d{10}

working demo
Look that I have not used multiline nor global flags. This way the pattern is going to find the first match you want.
Case 1:

Case 2:

BTW, use capturing groups if you want to capture the content:
(\d{12}|\d{10})


text:
Q: Number of ways to assign scores A test consisting of $12$ questions is scored with $200$ points. How many ways can the $200$ points be assigned if each question must be worth at least $10$ points but no more than $25$ and the scores must be a multiple of $5$?
I'm thinking about a possible combination with repetition. $15$ points ($80/5$) out of $12$ questions. But I don't know how to apply the maximum restriction of $25$.$3$ to each question $\frac{25-10}{3}$.
But it may not be a combination with repetition either, as I interpret the statement as meaning that it doesn't matter if the first question is worth $30$ points and the second is worth $10$, which is the other way around. I understand that this specific example is a unique way, isn't it?

A: Since each score must be a multiple of $5$, we might as well divide all of the point values by $5$ and have $12$ questions worth a total of $40$ points, each question being worth at least $2$ and at most $5$ points. If $p_k$ is the point value of the $k$-th question, we're looking for the number of solutions to
$$\sum_{k=1}^{12}p_k=40\tag{1}$$
in integers $p_k$ satisfying the condition that $2\le p_k\le 5$ for $k=1,\ldots,12$. Let $x_k=p_k-2$ for $k=1,\ldots,12$; then the number of solutions to $(1)$ subject to the stated restriction is the same as the number of solutions to
$$\sum_{k=1}^{12}x_k=16$$
in non-negative integers $x_k$ satisfying the condition that $x_k\le 3$ for $k=1,\ldots,12$. If it weren't for the upper limit on the numbers $x_k$, this would be a standard stars-and-bars problem, and there would be $\binom{16+12-1}{12-1}=\binom{27}{11}$ of them. Unfortunately, many of those solutions violate the upper limit on one or more of the numbers $x_k$, so $\binom{27}{11}$ is a significant overestimate. To correct this you will need to make an inclusion-exclusion calculation. My answer to this question includes such a calculation; try to use it as a model to complete the solution of your problem.

A: Since all scores are a multiple of $5$ we can divide by it, resulting in $40$ points total and question scores from $2$ to $5$ points. Since each question must be at least $2$ points, we can think of the questions as holding $24$ "base points", leaving the problem of how many ways there are to distribute $16$ "extra points" to the $12$ questions with no question having more than $3$ of them.
As a generating function problem, this is the $x^{16}$ coefficient of $(1+x+x^2+x^3)^{12}$. And the answer turns out to be $1501566$.


text:
Q: If $\frac{5m-1}{4} =n$ m,n $\in$ Z integer then find general solution If $\dfrac{5m-1}{4} =n$ m,n $\in$ Z (integer) then find general solution. Answer is m = 4k -3, n= 5k-4. $k\in$ Z(integer)
According to me answer should be 1+4n=5k , 5m-1=4k.
Can you please explain where did I go wrong ?
I am a high school students who is self studying for college entrance exam. Original problem was a trigonometric equation which I solved but didn't get the correct answer.
Thanks you.

A: If $\dfrac{5m-1}{4} =n$ with  $m,n \in \mathbb Z $ , then  $m$ and $n$ are not independent of each other;
they satisfy $1+4n=5m$ (you wrote $5k$) or  $5m-1=4n$ (you wrote $4k$).
From $1+4n=5m$ we see $5$ divides $4n+1$  so $5$ divides $4n+1+15=4n+16=4(n+4)$
so $5$ divides $n+4$ (since $5$ is prime and does not divide $4$) so $5k=n+4$ so $n=5k-4$ with $k\in\mathbb Z$.
Therefore $m=\dfrac{1+4n}5=\dfrac{1+4(5k-4)}5=\dfrac{20k-15}5 =4k-3.$


text:
Q: Bug or misuse : docker layer content not available in final image I am having a hard time trying to build a docker image for some python project, but at some point a RUN command resulting content is not available in the next RUN.
I mean I have a RUN command that generate a directory with some content and that directory is not available for the next RUN command.
Here is the Dockerfile snippet :
RUN poetry config virtualenvs.create true && \
    poetry config virtualenvs.in-project true && \
    poetry install -n --no-root --no-dev && \
    ls -la
RUN ls -la

The first ls -la shows a .venv directory (see below) while it is not present anymore in the second one.
And here is the build output:
Step 9/14 : RUN poetry config virtualenvs.create true &&     poetry config virtualenvs.in-project true &&     poetry install -n --no-root --no-dev &&     ls -la
 ---> Running in 3a93a4994133
      ...
drwxrwxr-x 4 root odoo  4096 Sep 29 20:08 .
drwxr-xr-x 1 root root  4096 Sep 16 02:35 ..
drwxr-xr-x 4 odoo odoo  4096 Sep 29 20:08 .venv
-rw-rw-r-- 1 odoo odoo 15824 Sep  2 23:18 poetry.lock
-rw-rw-r-- 1 odoo odoo  2057 Sep  2 23:50 pyproject.toml
drwxr-xr-x 3 odoo odoo  4096 Sep 29 20:08 src
Removing intermediate container 3a93a4994133
 ---> 694c4e54863c
Step 10/14 : RUN ls -la
 ---> Running in 5d0ebcf8f1e9
total 32
drwxrwxr-x 3 root odoo  4096 Sep 29 20:08 .
drwxr-xr-x 1 root root  4096 Sep 16 02:35 ..
-rw-rw-r-- 1 odoo odoo 15824 Sep  2 23:18 poetry.lock
-rw-rw-r-- 1 odoo odoo  2057 Sep  2 23:50 pyproject.toml
drwxr-xr-x 3 odoo odoo  4096 Sep 29 20:08 src
Removing intermediate container 5d0ebcf8f1e9
 ---> 750255eac6bb

If someone can provide any lead, it would be really appreciated.
Thanks


text:
Q: Thinkpad T61 in 2011 I've just bought a used T61 for a good price ($200). The laptop is still on good condition,
and plan to use for another 1 or 2 years (so from 2011 to 2012). Main uses are doing web development, and probably a .NET development.
Is the machine (C2D 2.40ghz, 3GB DDR2 RAM, 250HD) could handle these tasks? I'm saving for a new X or W Series Thinkpad and it would probably take me year to get one.

A: I have a T61 with just about the same spec - I use it for a full Visual Studio Development suite running emulators for Windows Phone 7 and ASP Web development.  It also has enough grunt to run a basic VM for some testing.  The only issue you might come across is if you want to do any high end 3D development.


text:
Q: `rm` everything in dir A that also exists in dir B I accidentally cp'd a bunch of stuff from B into A without including the folder.  I.e. I copied the contents of B into A, and I meant to copy B into A to get A/B.  A already had a bunch of stuff in it, so now I have to sort it all out.  However, B still exists in its original location, so I can ls B to see what is in B.  Can I use this info to rm the stuff in A that is also in B?

A: got it.
from A:
find B -maxdepth 1 -printf "%P\n" | xargs -d '\n' rm -rf

A: fdupes -d A B

fdupes is a really helpful utility for discovering and removing duplicate files.


text:
Q: What's the most efficient method that I can 'image' all my programs and bulk install them later? I currently have a virus that I have not been able to fix. Thus, I am restoring to the factory default of Windows 7. I have had many applications installed on my current OS image, which would be a pain to reinstall all over again. Are there any utilities from which I can create an 'image' of all my programs, and easily install them again.
I am using Windows 7 Pro x64.

A: I'm going to suggest you don't do that at all. It would be difficult, and most likely give you new and interesting problems down the line, in addition to giving you a real risk of not getting rid of your virus at all.
However, in order to save some pain, you could shrink the existing partition and move it somewhere out of the way. (Or copy all the files onto some other filesystem or something) Then you can easily copy over any configuration files & c. you would like to bring along with you to your new install.

A: What you are trying to is a short cut, that I am afraid will backfire on you. Remember any version of Windows is not that stable to deal with the assault that you are proposing. My solution would be to reformat reinstall one by one all of your programs. This will insure that all upgrades and files have been properly installed. With a virus you never know where it might be hiding, so shortcuts just don't work.
But here is you saving point. Once installed and properly updated then create an image of your newly configured computer. There are two free ways to do this relatively easily. One is to download an MS package of high end free utilities called SysInternalsSuite. These are programs that MS uses internally for various reasons and has made them available through their developer network. There is a program in there to create a VDI of your existing hardware and software. Then there is the Paragon Software Back & Recovery Suite (free) out of Germany. In part of their backup options you can create 3 different VM formats. I would suggest all three as they all have strengths and weaknesses. Also I like having a backup to my backup so this software will give the option of trying 4 different VM with either VMWare or Virtualbox. I like VB as when you finally set it up you can't tell the difference between VM and Physical.

A: It depends, if you just want your programs? or your program data and personal settings?
If programs: it's possible, but it needs a reasonable amount of expertise to migrate all your installed programs folders, and their registry keys (Even though, there's still a chance that you missed a Class or Shell Extension key), and in some cases, the driver or service they registered at the installation. But, the problem is viruses usually install in one or more of these locations (especially as a driver or service), and chances are high That you inadvertently migrate the virus to new OS. So, to be honest, the only possible way for an average user (and even the safest for an advanced user!) is to reinstall all of them.
If personal settings: (called UserState by microsoft), can be backed up and migrated using Easy Transfer. However, it might not migrate everything. There's also a command-line tool called USMT (User State Migration Tool) that is suitable for advanced users and can be customized to migrate the settings you need, and exclude the ones you don't. Those include folders under %AppData%, %LocalAppData%, %ProgramData% and the registry keys of programs usually available under "HKCU\Software" and "HKLM\Software" (every program uses a different set of those).
My Advice: Back up with easy transfer, reinstall your windows and all of your programs.


text:
Q: Is there a way to verify a file contains a class, interface or function before including it for FileReflection()? We've got a tree traversal loop running which identifies PHP files all well and good, but for each file we run PHP's FileReflection against it which requires the file to be included first. For the purpose of this script, we're only interested in files that contain Class, Interface or Function declarations.
Is there a way to identify whether a file includes a Class, Interface or Function declaration before running include() on it?
My guess is that it'll have to be a regex against the get_file_contents() value, but I was hoping for a more elegant (read: consistent and reliable) solution.

A: Found the answer myself, for those interested...

$tokens = token_get_all(file_get_contents($file,TRUE));
$valid = FALSE;
foreach($tokens as $token) {
    if (isset($token[0]) && in_array($token[0],array(T_CLASS,T_FUNCTION,T_INTERFACE))) {
        $valid = TRUE;
        break;
    }
}
if (!$valid) { return NULL; }
include_once $file;
$reflection = new FileReflection($file);
...


text:
Q: node js docker-compose volume empty I've written an app that download some images to a folder called storage in src/storage path. everything works great in development mode (without container) and in production mode (container) it works but the volume will be empty.
docker-compose:
version: "3.2"

services:
  app:
    build: .
    volumes:
      - ./storage-data:/src/storage
    depends_on:
      - db
    env_file:
      - prod.env
    networks:
      - app_network

networks:
  app_network:

Dockerfile:
FROM node:14
WORKDIR /usr/src/app
COPY package.json yarn.lock ./

RUN npm install

COPY ./src .

CMD [ "node", "app.js" ]

and this is my download function:
const { createWriteStream } = require("fs");
const { pipeline } = require("stream");
const { promisify } = require("util");
const fetch = require("node-fetch");

const download = async ({ url, path }) => {
  const streamPipeline = promisify(pipeline);
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`unexpected response ${response.statusText}`);
  }

  await streamPipeline(response.body, createWriteStream(path));
};

module.exports = download;

and finally the code:
    for (const [i, product] of products.entries()) {
      const { thumbnail, name } = product;
      const ext = thumbnail.slice(thumbnail.lastIndexOf("."));
      const filePath = `${path.join(__dirname, "../storage")}/${
        brand.text
      }-${slugify(name)}-thumbnail${ext}`;

      try {
        await download({
          url: thumbnail,
          path: filePath,
        });
        products[i].thumbnail = filePath.slice(filePath.indexOf("src"));

        logger.info(`"${name}" thumbnail saved to ${filePath}`);
      } catch (error) {
        logger.error(error);
      }
    }

as I said, it downloads files in container but volume folder is empty and there is no error.
if I check docker container with docker exec i can see downloaded files.

A: Update:
You need to mount the volume to the absolute path you see when you execute pwd from a terminal within the container in the images directory.

You need to change your docker-compose file's volumes like below:
volumes:
      - ./storage-data:/usr/src/app/src/storage


text:
Q: JavaFX LineChart loop values Somehow my chart does not want to get values from loop.
The bufferedReader gets values from file and is splitted into parts with ";". The String[] parts list is field variable.
XYChart.Series series = new XYChart.Series();
for(int i = 1; i < 5; i++) {
        series.getData().add(new XYChart.Data(i, parts[i]));
        }

If I put System.out.println into loop, then the values are printed out correctly.
With ordinary values, the program works correctly.
The console puts out java.lang.reflect.InvocationTargetException.

A: Managed to get the answer myself.
The XYChart data cannot be String list type, but double or int.
Is there any way to make String[] list to double[] list ?