text:
Q: robot framework: test case cannot load keyword in resource file that import in the test suite's parent test suite folder
Hi, I am using robot framework to automate testing of a website, and the image above is the structure of test in the RIDE:

*

*Test: a test suite folder, and I import resource file here, which is in the "init.robot" under the folder

*Sub1: a sub test suite, import nothing

*test: a test case

My problem is: in the test case "test", robot cannot recognize the keyword that imported in the "Test" test suite folder, because there will be more sub test suites, like sub2, sub3, how can I import resource in one place? I don't want to import the resource file in every test suite, is there a way to do that?

A: You can chain an imports. Below is an example of such a chain and reuse. In this example we have a single resources.robot that imports all of the different sub*.robot files. This is the only file that imports these.
Then there are two testcases*.robot files that proceed to import resources.robot and are able to access the content of the sub*.robot keywords.
resources.robot
*** Settings ***
Resource    ../resources/sub1.robot
Resource    ../resources/sub2.robot
Resource    ../resources/sub1.robot

testcases1.robot
*** Settings ***
Resource    ../resources/resources.robot

*** Test Cases ***
TC
   No Operation

testcases2.robot
*** Settings ***
Resource    ../resources/resources.robot

*** Test Cases ***
TC
   No Operation

As discussed in the comments, that any keyword imported in the __init__.robot file is not available beyond that file. This is clearly described in the Robot Framework User Guide section on Initialization files.
That said, if the effort of including the master resource file in each suite file undesirable, then an alternative approach is to load the resource file using a listener at the start of each Suite. The documentation on Listeners can be found here: Docs
A new example:
AddResourceListener.py
from robot.libraries.BuiltIn import BuiltIn

class AddResourceListener(object):
    ROBOT_LISTENER_API_VERSION = 2

    def __init__(self):
        pass

    def start_suite(self, name, attributes):
        BuiltIn().import_resource('${EXECDIR}/resource.robot')

resource.robot
*** Keywords ***
Resource Keyword
    Log    "Keyword Executed from Resource File"

TestCase.robot
*** Test Cases ***
TC
    Resource Keyword

Then run your regular robot command with the additional argument --listener AddResourceListener.py and you'll be able to use the keyword regardless if it's imported or not.


text:
Q: Distorted canvas shape when using dynamic dimensions I'm trying to create a guillotine-blade shaped trapezium using the canvas element, based on the current viewport dimensions full width, half height), but every time I do this the coordinates seem to be out of proportion (and sometimes the shape that I draw seems magnified - the edges are pixelated as though I've zoomed in x10)
My code currently looks like this (I'm using jquery 1.5.x) - it's on jsfiddle
//Get the page dimensions:
var page = {
    width:$(window).width(),
    height:$(window).height()
};
var halfHeight = page.height/2;
var canvas = $('<canvas />', {width:page.width, height:page.height});
var blade1 = canvas[0].getContext('2d');
blade1.fillStyle = "#000";
blade1.beginPath();
blade1.moveTo(0,0); // topleft
blade1.lineTo(page.width, 0); //topright
blade1.lineTo(page.width,halfHeight/2); //right, quarterway down
blade1.lineTo(0,(halfHeight)); //left, halfway down
blade1.closePath();
blade1.fill();
$(canvas[0]).css({backgroundColor:'#fc0'});
$(canvas[0]).prependTo('body');

I think my calculations make sense as it's a simple shape, but it's not fitting inside the canvas at all.
Can anyone help me make this shape work inside a dynamically generated canvas element? THe reason I'm doing it all in JS is that I only want to do this if the referrer is outside the current domain.

A: Edit: It looks like you have to set display: block; on the canvas element in jsfiddle to eliminate the additional spacing that's causing the scrollbars. Here's the corrected version: http://jsfiddle.net/LAuUh/3/
You will probably want to hook into the window resize event so that you can re-draw the guillotine and resize the canvas. Otherwise, if the user resizes their browser the background won't fit anymore.

I'm not quite sure where the extra few pixels of spacing are coming from in the jsfiddle example, but tested on a standalone page this code seems to achieve what you're looking for:
    var vpW = $(window).width();
    var vpH = $(window).height();
    var halfHeight = vpH/2;
    var canvas = document.createElement("canvas");
    canvas.width = vpW; canvas.height = vpH;
    var blade1 = canvas.getContext('2d');
    blade1.fillStyle = "#000";
    blade1.beginPath();
    blade1.moveTo(0,0); // top left
    blade1.lineTo(vpW, 0); // top right
    blade1.lineTo(vpW,halfHeight / 2.0); // right, quarterway down
    blade1.lineTo(0,halfHeight + halfHeight / 2.0); // left, threequarters down
    blade1.closePath();
    blade1.fill();

    $(canvas).css('backgroundColor','#fc0');
    $(canvas).prependTo('body');

With this CSS:
html, body {
    width: 100%;
    height: 100%;
    margin: 0px;
    padding: 0px;
}

The main issue that I fixed was the coordinates you were using for your guillotine shape. In addition, using this syntax:
var canvas = $('<canvas />', {width:page.width, height:page.height});

when you create your canvas element is not good as it applies the width and height as style attributes. With canvas elements, the CSS width and height controls magnification while the DOM-level object width and height attributes control the actual dimensions of the canvas.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Go: how to not remove double quotes on cookies Go removes double quotes in cookies.  Is there a way to keep double quotes in cookies in Go?
For example, I'm sending a small JSON message and "SetCookie" strips double quote.
w.SetCookie("my_cookie_name", small_json_message)

More about Cookies:

*

*The HTTP RFC defines quoted string values.  See https://www.rfc-editor.org/rfc/rfc7230#section-3.2.6

*The proposed cookie RFC explicitly says double quotes are allowed in cookie values: cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )

*Go currently has a condition to insert double quote into cookies, so obviously double quotes are allowed.

*;  is the cookie delimiter.

*Values with ASCII characters outside the limited ASCII range may be quoted (The RFC calls this the quoted_string) which expands the allowed character set.

*JSON does not contain the ; character, so for ; to appear in JSON it can only appear in string values.  In JSON, string values are already quoted.

*I've confirmed testing using a simple k:v JSON payload and it works fine on all major browsers with no issues.

*Cookies are typically generated by server data, not user data.  This means well structured, not arbitrary, JSON may be used
JSON easily can conform to the cookie RFC.  Additionally, even though it's not an issue with this example of JSON, regarding the hypothetical concern of not conforming to the RFC:

*

*A cookie is transmitted as a HTTP headers.  Many HTTP headers commonly disregard the RFC.  For example, the Sec-Ch-Ua header created by Chrome, includes several "bad" characters.

Sec-Ch-Ua: "Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"

*

*"comma" is "disallowed" and it's used all the time.

*Even if double quotes were "wrong", which they are not, but if they were, there are lots of in-the-wild examples of cookies containing quotes.

For reference, here's the relevant section of RFC 6265
set-cookie-header = "Set-Cookie:" SP set-cookie-string
 set-cookie-string = cookie-pair *( ";" SP cookie-av )
 cookie-pair       = cookie-name "=" cookie-value
 cookie-name       = token
 cookie-value      = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
 cookie-octet      = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
                       ; US-ASCII characters excluding CTLs,
                       ; whitespace DQUOTE, comma, semicolon,
                       ; and backslash

Where one can see whitespace DQUOTE is disallowed and DQUOTE is allowed.

A:
HTTP cookies are allowed to have double quotes.

Are you sure? rfc6265 states:
set-cookie-header = "Set-Cookie:" SP set-cookie-string
set-cookie-string = cookie-pair *( ";" SP cookie-av )
cookie-pair       = cookie-name "=" cookie-value
cookie-name       = token
cookie-value      = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
cookie-octet      = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
                       ; US-ASCII characters excluding CTLs,
                       ; whitespace DQUOTE, comma, semicolon,
                       ; and backslash

So it appears that Go is following the specification (the spec previously definesDQUOTE to mean double quote).
See this issue for further information.

A: Yes.  Double quotes are allowed in cookies and other HTTP headers.  Double quotes are also used to escape characters that would be otherwise invalid.
Here's a way to manually set a cookie, where w is the http.responseWriter and b is the bytes of the cookie. Max-Age is in seconds and 999999999 is ~31.69 years.
w.Header().Set("Set-Cookie", "your_cookie_name="+string(b)+"; Path=/; Domain=localhost; Secure; Max-Age=999999999; SameSite=Strict")

Since you'll probably use cURL to test sending cookies to the server, here's a useful test:
curl --insecure --cookie 'test1={"test1":"v1"}; test2={"test2":"v2"}'  https://localhost:8081/

Which results in a HTTP header like the following:
GET / HTTP/2.0
Host: localhost:8081
Accept: */*
Cookie: test1={"test1":"v1"}; test2={"test2":"v2"}
User-Agent: curl/7.0.0

Also note, many of the RFC rules are ignored all the time, especially commas.  For example, Chrome sets this header:
Sec-Ch-Ua: "Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"

Gasp!  Is uses commas and other things!  It is well established that commas in HTTP headers are okay, even though the RFC appears to say otherwise.
Note that the Chrome header uses spaces, many double quotes, commas, special characters, and semi colon.  Chrome here uses double quotes around many values needing escaping, and that's the right way to be compliant with the RFC.
Note that the cookie RFC 6265 is a proposal and has been for 11 years.  There are reasons for that.  Knowing that cookies are just a HTTP header, look at the accepted HTTP RFC for quoted string semantic for header values:
HTTP RFC 7230 3.2.6.
These characters are included for quoted-string:
HTAB, SP
!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~
%x80-FF
The characters " and / may be included if escaped.


text:
Q: Double variables give unexpected result I am not sure about what is going on with these two variables. "milliV" is a double, "param1a" is a double, being param1a= 65, I should get out 1.588. The result I get instead is = 0. How is that possible?
  double milliV=0.0;
  milliV= (5/1023*param1a/200*1000);

A: Because 5/1023 that's an integer division so the result is integer too. Try with this
milliV= (5.0/1023*param1a/200.0*1000);

As long as one of the elements of the operation is double, the result will be double too

A: 5/1023 is problem 5 and 1023 are integers so 5/1023 = 0

A: it looks that 5/1023 = 0 since both 5 and 1023 are integers
try change 5/1023*param1a/200*1000 into
5.0 / 1023.0 * param1a / 200.0 * 1000.0


text:
Q: Edits not reflected in JPA backing bean I've been following the @BalusC examples at Creating master-detail table and dialog, how to reuse same dialog for create and edit
 and Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes, trying to get a small form to edit some data and then persist. But, I can't see the changes reflected in the backing bean when I try to save the data.
I have a simple form that I pre-populate with some data and that I might edit before saving:
<h:form id="productSummaryForm">
    <h:panelGrid columns="2" columnClasses="label, value">
        <h:outputText value="Product name:" />
        <p:inputText id="productNameInputText" value="#{editProduct.product.productName}" required="true" requiredMessage="Enter Product Name" size="32">
            <p:watermark value="The name of the product" for="productNameInputText"/>
        </p:inputText>

        <h:outputText value="Output name:" />
        <p:inputText id="outputNameInputText" value="#{editProduct.product.outputName}" size="32">
            <p:watermark value="Output name" for="outputNameInputText"/>
        </p:inputText>
    </h:panelGrid>

    <h:panelGrid columns="3" styleClass="buttonPanelGrid">
        <p:commandButton value="Cancel"  immediate="true" action="#{productController.cancel}"/>
        <p:commandButton id="saveButton" value="Save" process="@this" immediate="true" action="#{editProduct.saveProduct}"/>
    </h:panelGrid>
</h:form>

The controller is:
@Named
@ViewScoped
public class EditProduct implements Serializable {

    private Product product;  // JPA Entity

    @Inject
    protected ProductService productService;

    public String saveProduct() {
        productService.saveProduct(product);
        return "/product?faces-redirect=true";
    }
}

When I debug on saveProduct(), any edits I made I've made through UI are not reflected in the product that I save. I've tried adding the inputText ids to the process attribute (for example process="@this outputNameInputText"), still the changes aren't reflected.
None of the different combinations of attributes I tried on saveButton have changed anything, which makes me think Product is the problem: it's a JPA entity. Does that sound right?

A: So, there was a validation error on one of my components, which I found by working through the list in commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated. In the process of working through this and Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes
, I discovered there was more than one way to do what I needed:
Relying in the default PrimeFaces process="@form" behaviour:
<p:commandButton id="saveButton" value="Save" action="#{editProduct.saveProduct}"/>

Or, just to make it explicit:
<p:commandButton id="saveButton" value="Save" process="@form"
    action="#{editProduct.saveProduct}"/>

Processing only certain form fields the PrimeFaces way:
<p:commandButton id="saveButton" value="Save"
    process="@this outputNameInputText productNameInputText"
    action="#{editProduct.saveProduct}"/>

And, doing it without PrimeFaces:
<h:commandButton id="saveButton" value="Save" action="#{editProduct.saveProduct}">
    <f:ajax execute="@form" render="@all"/>
</h:commandButton>


text:
Q: Calculating output impedance without measuring open-loop output voltage of a push-pull Class AB MOSFET Amplifier So I am building and analyzing a Class AB / push-pull amplifier implemented with MOSFET as depicted in the following schematic:

R2 is the load. The input is an AC signal with 3V amplitude and 1KHz frequency. I am trying to determine output impedance and doing the usual way where I turn off the input signal and inject a test voltage to measure the current and then calculate impedance, I get around 150 \$\Omega\$. However, I am also trying to do it the way my professor suggested, which is what I'm having issues with.
He said to think of the load as a voltage divider and that I could measure the output impedance by just simply changing the load.
So that makes sense to me. After all, looking at the following image:

The load and the output impedance can be modelled as a voltage divider network.
I can put the amplifier under the same two known loads and solve both equations simultaneously and solve for \$Z_{out}\$. I can rewrite the equation for \$Z_{out}\$ using \$V_{L1}, V_{L2}, R_{L1}, R_{L2}\$ (voltage over load for the first and second load) without involving \$V_{out}\$.
This is where I'm stuck. Doing the above, I get:
\$V_{L1} = V_{out} \times {R_{L1} \over Z_{out} + R_{L1}} \Longrightarrow Z_{out} = V_{out} \times {R_{L1} \over V_{L1}} - R_{L1}  \$
and obviously the same is true for the second load:
\$ Z_{out} =  V_{out} \times {R_{L2} \over V_{L2}} - R_{L2}\$
Now, since the output impedance doesn't change regardless of the load, the two equations are equal:
\$ V_{out} \times {R_{L1} \over V_{L1}} - R_{L1} = V_{out} \times {R_{L2} \over V_{L2}} - R_{L2} \$ and so \$ V_{out} \$ cancels out on both sides.
However, I don't know where to go from here. I can't solve that equation cause there isn't enough information to solve it; I would need a second constraint because obviously that equation has an infinite number of solutions.
So I tried a different route:
\$ Z_{out} = V_{out} \times {R_{L2} \over V_{L2}} - R_{L2} \$
&&
\$ V_{out} = {(Z_{out} + R_{L1})V_{L1} \over R_{L1}} \$
Solving both of these together by replacing the \$ V_{out}\$ expression in the \$Z_{out}\$ equation I get:
\$ Z_{out} = { R_{L1}R_{L2}(V_{L1}-V_{L2}) \over R_{L1}V_{L2} - R_{L2}V_{L1} } \$
I tested this out with two loads and measured the voltages:
\$R_{L1} = 10k\Omega  \text{ & } V_{L1} = 5.9V\$
\$R_{L2} = 1k\Omega \text{ & } V_{L2} = 5.4V \$
Using the values above, I get \$ Z_{out} = 103.95 \Omega\$ which is close enough to the value I got with the original method.
But then I repeated the calculation with a different load:
\$R_{L1} = 1k\Omega  \text{ & } V_{L1} = 5.4V\$
\$R_{L2} = 100\Omega \text{ & } V_{L2} = 3.3V \$
and I got a different value \$Z_{out} = 76.09\Omega\$
So, I don't know where to go from here.
Is my derivation wrong?
What should I try next?
I'm not asking for anybody to do my homework, just for guidance
Thank you!
EDIT: Am I not supposed to repeat the calculations with such a low load? I retried with loads of 1k or higher and I get the same impedance of about 103. I'm thinking maybe since the load is so small that it's close to the output impedance, that's affecting the calculations. I've read that an effective damping factor is chosen so that \$ R_{load} >> R_{out}\$ so I do get the right result when I use a load that's much higher than the output impedance.

A: Something seems to have gone wrong in your derivation. I used a symbolic math package (sympy) to solve the equations:
$$V_{out}\frac{R_1}{R_1+Z_{out}} = V_1$$
$$V_{out}\frac{R_2}{R_2+Z_{out}} = V_2$$
and this results in this expression for \$Z_{out}\$:
$$Z_{out} = \frac{R_1R_2(V_1-V_2)}{R_1V_2-R_2V_1}$$
Plugging in your values results in \$104\Omega\$.


text:
Q: Setting a property list with Titanium Appcelerator I'm working with the latest Mobile SDK (1.6) on OS X.
I have this piece of code:
var globalArray = [
        {title:'foo',value:'yes'},
        {title:'bar',value:'no'}
];

Titanium.App.Properties.setList('globalArrayProperty',globalArray);
Titanium.App.Properties.getList('globalArrayProperty')[0].value = 'it works!';
Titanium.API.info('first value : ' + Titanium.App.Properties.getList('globalArrayProperty')[0].value);

I simplified it so that I can explain you where the problem stands.
So, I create an array with a couple of objects.
Then, I'm setting a property depending on this array and then affecting a new value to the first object.
But when I call the display the property, instead of showing the 'it works!' string, it shows the initial one 'yes'.
I tried by adding a couple of lines:
Titanium.App.Properties.setList('globalArrayProperty',globalArray);
var arr = Titanium.App.Properties.getList('globalArrayProperty');
arr[0].value = 'it works!';
// This works
Titanium.API.info('first value with arr: ' + arr[0].value);
// This doesn't work
Titanium.API.info('first value : ' + Titanium.App.Properties.getList('globalArrayProperty')[0].value);

So the intermediate var 'arr' get the property, set it but cannot apply the modification on the property.
Am I missing something?
Thanks,
Regards.

A: i think you need to set the property list again after updating the array
Titanium.App.Properties.setList('globalArrayProperty',globalArray);
var arr = Titanium.App.Properties.getList('globalArrayProperty');
arr[0].value = 'it works!';
// This works
Titanium.API.info('first value with arr: ' + arr[0].value);

// save changes to property list
Titanium.App.Properties.setList('globalArrayProperty',arr);

// This doesn't work
Titanium.API.info('first value : ' + Titanium.App.Properties.getList('globalArrayProperty')[0].value);


text:
Q: javascript function to accept only 4 digit number I have a html form with a javascript script defined default value. I am trying to add another javascript that would deny the form being submitted if its empty and on its default value but I cant get to work to deny the form being submitted if the input is characters or non-numeric.
This is the javascript
$('#form1').submit(function(e) {
  if ($.trim($('#store').val()) === "" || $.trim($('#store').val()) === "Enter store number'(nnnn)'" || $.trim($('#store').val()) === isNaN(e)) {
    e.preventDefault();
    alert('Please type in store number');
  }
});

A: try this on form tag <form onSubmit="return validation()">
$('document').ready(function(){
function validate(){
        if ($.trim($('#store').val()) === "" || $.trim($('#store').val()) === "Enter store number'(nnnn)'" || $.trim($('#store').val()) === isNaN(e) ) {

   alert('Please type in store number');
return false;
        }
else{
return true;
}

}
});

return false to prevent from submitting form


text:
Q: Calling multiple functions from within function I am trying to call a function from within a function, and the former calls more functions etc.
import ROOT as root
import sys, math

class SFs():
    def __init__(self):
        self.get_EfficiencyData = None
        self.get_EfficiencyMC = None
        self.get_ScaleFactor = None
        self.eff_dataH = None
        self.eff_mcH = None
        self.get_ScaleFactor = None
        self.get_EfficiencyMC = None

    def ScaleFactor(self,inputRootFile):
        self.eff_dataH = root.std.map("string", root.TGraphAsymmErrors)()
        self.eff_mcH = root.std.map("string", root.TGraphAsymmErrors)()
        EtaBins=["Lt0p9", "0p9to1p2","1p2to2p1","Gt2p1"]

        fileIn = root.TFile(inputRootFile,"read")
        HistoBaseName = "Label"
        etaBinsH = fileIn.Get("Bins")
        # etaLabel, GraphName
        nEtaBins = int(etaBinsH.GetNbinsX())
        for iBin in range (0, nEtaBins):
            etaLabel = EtaBins[iBin]
            GraphName = HistoBaseName+etaLabel+"_Data"
        print GraphName,etaLabel

        self.eff_dataH[etaLabel]=fileIn.Get(str(GraphName))
        self.eff_mcH[etaLabel]=fileIn.Get("histo")

        print self.eff_mcH[etaLabel].GetXaxis().GetNbins()
        print self.eff_mcH[etaLabel].GetX()[5]
        self.get_ScaleFactor(46.8,2.0)

    def get_ScaleFactor(self,pt, eta):

        efficiency_mc = get_EfficiencyMC(pt, eta)
        if  efficiency_mc != 0.:
            SF = 1/float(efficiency_mc)
        else:
            SF=1.

        return SF

    def get_EfficiencyMC(self,pt, eta):

        label = FindEtaLabel(eta,"mc")
        # label= "Lt0p9"
        binNumber = etaBinsH.GetXaxis().FindFixBin(eta)
        label = etaBinsH.GetXaxis().GetBinLabel(binNumber)
        ptbin = FindPtBin(eff_mcH, label, pt)
        Eta = math.fabs(eta)
        print "eff_mcH ==================",eff_mcH,binNumber,label,ptbin
        # ptbin=10
        if ptbin == -99: eff =1
        else: eff= eff_mcH[label].GetY()[ptbin-1]

        if eff > 1.: eff = -1
        if eff < 0: eff = 0.
        print "inside eff_mc",eff
        return eff

    sf = SFs()
    sf.ScaleFactor("Muon_IsoMu27.root")

I want to call the get_ScaleFactor() which in turn calls the get_EfficiencyMC() etc, but I once trying calling the former, I get TypeError: 'NoneType' object is not callable

A: in your class init you define:
self.get_EfficiencyMC = None
and later define a function (i.e. class method)
def get_EfficiencyMC(self,pt, eta):
when you create an instance of the class, the init part is executed shadowing the class method.  Just either remove it from the init, or change the method name.


text:
Q: CURL XHR Google App Script - I cannot figure it out I tried for hours now, can someone just deliver me from the pain and rewrite this, so it works with Google App Script?
The requests below are working in my windows CMD and in plain Javascript. But I need it on Google App Script.
curl -X POST https://rpc-mainnet.maticvigil.com/ -H "Content-Type: application/json" -d "{\"jsonrpc\" : \"2.0\",\"id\":\"dontcare\",\"method\":\"eth_call\",\"params\": [{\"from\":\"0x0000000000000000000000000000000000000000\",\"data\":\"0x7b84daec00000000000000000000000000000000000000000000000000000000000000280000000000000000000000009fd15feb6f86d2da6a3ac17372debd1db4e02e93\",\"to\":\"0xbda1f897e851c7ef22cd490d2cf2dace4645a904\"},\"latest\"]}"

var url = "https://rpc-mainnet.maticvigil.com/";

var xhr = new XMLHttpRequest();
xhr.open("POST", url);

xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      console.log(xhr.status);
      console.log(xhr.responseText);
   }};

var data = '{"jsonrpc" : "2.0","id":"dontcare","method":"eth_call","params": [{"from":"0x0000000000000000000000000000000000000000","data":"0x7b84daec00000000000000000000000000000000000000000000000000000000000000280000000000000000000000009fd15feb6f86d2da6a3ac17372debd1db4e02e93","to":"0xbda1f897e851c7ef22cd490d2cf2dace4645a904"},"latest"]}';

xhr.send(data);

I got this far:
let response = UrlFetchApp.fetch("https://rpc-mainnet.maticvigil.com/", {
    "headers": {
      "accept": "*/*",
      "accept-language": "en-US,en;q=0.9,de;q=0.8",
      "content-type": "application/json",
      "sec-fetch-dest": "empty",
      "sec-fetch-mode": "cors",
      "sec-fetch-site": "cross-site",
      "sec-gpc": "1"
    },
    "referrer": "https://polygonscan.com/",
    "referrerPolicy": "origin-when-cross-origin",
    "body": "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"eth_call\",\"params\":[{\"from\":\"0x0000000000000000000000000000000000000000\",\"data\":\"0x7b84daec00000000000000000000000000000000000000000000000000000000000000280000000000000000000000009fd15feb6f86d2da6a3ac17372debd1db4e02e93\",\"to\":\"0xbda1f897e851c7ef22cd490d2cf2dace4645a904\"},\"latest\"]}",
    "method": "POST",
    "mode": "cors",
    "credentials": "omit"
  });
  Logger.log(response.getContentText());

The error I am getting is:
"Exception: Request failed for https://rpc-mainnet.maticvigil.com returned code 403. Truncated server response: {"error":{"details":"Unrecognized JSONRPC command","code":-32005},"jsonrpc":"2.0","id":1} (use muteHttpExceptions option to examine full response)"

P.S.: I have "oauthScopes": ["https://www.googleapis.com/auth/script.external_request"] in my appscript.json.


text:
Q: How to add multiple responses into a single json object I am making some request to another site from my flask api. Basically my flask api is a proxy. So initially I substitute the parameters with the known company id and and get all the workers id. Given the workers id, I try to make another request which helps me get all their details. However with the code below I am only getting the last response which means only the details of the last worker. You can ignore the j==1 for now I did it for testing purposes.
tempDict={}
updateDic={}
dictToSend={}
 j=0
#i = companyid

#id=workerid

# I make several calls to url2 depending on the number of employee ids in number

for id in number:
    url2="someurl/" + str(i)+ "/contractors/"+str(id)
                r = requests.get(url2, headers={'Content-type': 'application/json',"Authorization":authenticate,'Accept': 'application/json'})
    print("id"+str(id))
    print(url2)

    loadJsonResponse2=json.loads(r.text)
    print(loadJsonResponse2)
    key = i

    tempDict.update(loadJsonResponse2)
    # I want to have all of their details and add the company number before

    print(tempDict)

    if(j==1):
        dictToSend[key]=tempDict
        return jsonify(dictToSend)

    j=j+1

     return jsonify(dictToSend)

So I have all the workers ids and I request the other url to get all their details. The response is in json format. However I am only getting the last response with the above code. I did something like j==1 because I wanted to check the return.
dictToSend[key]=tempDict
return jsonify(dictToSend)

The key is the company id so that I can identify which company the worker is from.
How can I get to concatenate all the json responses and at the end add a key like "5":{concatenation of all json requests}
Thank you,

A: Your key for json object is
#i = companyid
.
.
.
 key = i
.
.
.
# You are adding all your responses to companyid,
# better make a key with companyid and workerid
# key = str(companyid) + ":" + str(workerid)
dictToSend[key]=tempDict

And here
# you may not need this, since there is already a loop iterating on workerid
if(j==1):
    dictToSend[key]=tempDict
    return jsonify(dictToSend)

j=j+1

# then only useful line would be
dictToSend[key]=tempDict


text:
Q: Como deixar as td das tabelas aumentando ou diminuindo automaticamente o tamanho conforme a quantidade de caracteres? Como deixar as td da table aumentando ou diminuindo automaticamente o tamanho conforme a quantidade de caracteres? Para evitar que o texto acabe quebrando linha?

A: Não sei se entendi muito bem, mas pra que não haja quebra de linhas, basta definir a propriedade white-space do CSS como nowrap:

table tr > th,
table tr > td
{
  padding: 10px;
  border: #bbb 1px solid;
}

tr > td:first-child
{
  white-space: nowrap;
}

      Texto sem quebrar
      Texto comum

      Texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto
      Texto texto texto texto texto texto texto texto


text:
Q: NET::ERR_CERT_COMMON_NAME_INVALID error on email reset using SendGrid I have a Django site which is hosted on GCP App Engine with SendGrid as email host. When resetting the password and clicking on the link in the following email, the subsequent error is thrown:

Your connection is not private
NET::ERR_CERT_COMMON_NAME_INVALID

I've looked into several potential causes (linked at the end) but haven't been able to find a solution.
password_reset_email.html (only displaying the reset_link block)
{% block reset_link %}
{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
{% endblock %}

settings.py
ALLOWED_HOSTS = ['*']
# Also tried with
#ALLOWED_HOSTS = ['*', 'website.com', 'www.website.com']

# HTTPS settings
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True

# HSTS settings
SECURE_HSTS_SECONDS = 31536000 # 1 year
SECURE_HSTS_PRELOAD = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True

# Email backend settings (SendGrid)
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = 'some@email.com'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = 'EMAIL_HOST_PASSWORD'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

I have authenticated the domain and branded the link on SendGrid which have been verified over the DNS records on Namecheap.
When I look at the certificate in the browser it still refers to *.sendgrid.net though. Perhaps this might be causing it? I thought authentication and link branding would solve that. I've also tried emptying the cache and opening the link in a private window.
I've looked into this, this and this SO question as well.
Any help would be appreciated.
EDIT
Turns out it's related with this SO question as well.

A: Twilio SendGrid developer evangelist here.
You will need to get SSL Click Tracking turned on so that your CDN can forward SSL content onto SendGrid with a valid certificate for your domain.


text:
Q: WMI TerminalServices __SystemSecurity.GetSecurityDescriptor() Unexpected Error Summary: Execution of WMI Method against remote server returns "Unexpected Error". Command returns expected results when executed locally on either server (Server1 against Server1, Server2 against Server2) but returns "Unexpected Error" when running against any remote server (Server1 vs Server2 or Server2 against Server1).
Outlier: When executing method against any other namespace, the command executes without error.
Environment: Two 2008R2 servers, in the same subnet, on the same domain, with equal (managed) patching levels; Commands run by domain user in admin group on each server; There are no firewall, software or otherwise known rules that would inhibit inter-server traffic.
Command: WMIC.EXE /NODE:"SERVER2" /AUTHLEVEL:Pktprivacy /NAMESPACE:\\ROOT\CIMV2\TERMINALSERVICES Class __SystemSecurity Call GetSecurityDescriptor
Executed Locally (From SERVER1 to SERVER1) Success:
d:\>WMIC.EXE /NODE:"SERVER1" /AUTHLEVEL:Pktprivacy /NAMESPACE:\\ROOT\CIMV2\TERMINALSERVICES Class __SystemSecurity call GetSecurityDescriptor
Executing (__SystemSecurity)->GetSecurityDescriptor()
Method execution successful.
Out Parameters:
...

Executed against remote Server (Server1 to Server2) ERROR:
d:\>WMIC.EXE /NODE:"SERVER2" /AUTHLEVEL:Pktprivacy /NAMESPACE:\\ROOT\CIMV2\TERMINALSERVICES Class __System
Security call GetSecurityDescriptor
Executing (__SystemSecurity)->GetSecurityDescriptor()
ERROR:
Description = Unexpected error
Executed to alternate Namespace (Server1 to Server2) Success:
d:\>WMIC.EXE /NODE:"SERVER2" /AUTHLEVEL:Pktprivacy /NAMESPACE:\\ROOT\CIMV2\SECURITY\MICROSOFTTPM Class __SystemSecurity call GetSecurityDescriptor
Executing (__SystemSecurity)->GetSecurityDescriptor()
Method execution successful.
Out Parameters:
...
Debugging Steps (WMIDiag.vbs v2.1): There was nothing in the log that indicated additional issues with the ROOT\CIMV2\TERMINALSERVICES namespace, however it did specifically identify the namespace as requiring PACKET PRIVACY (AUTHENTICATION level 6), which does allow for the query of the class but not execution of the method.
73751 09:28:50 (0) ** INFO: WMI namespace(s) requiring PACKET PRIVACY: .................................................................... 4 NAMESPACE(S)!
73752 09:28:50 (0) ** - ROOT/CIMV2/SECURITY/MICROSOFTTPM.
73753 09:28:50 (0) ** - ROOT/CIMV2/TERMINALSERVICES.
73754 09:28:50 (0) ** - ROOT/WEBADMINISTRATION.
73755 09:28:50 (0) ** - ROOT/SERVICEMODEL.
73756 09:28:50 (0) ** => When remotely connecting, the namespace(s) listed require(s) the WMI client to
73757 09:28:50 (0) **    use an encrypted connection by specifying the PACKET PRIVACY authentication level.
73758 09:28:50 (0) **    (RPC_C_AUTHN_LEVEL_PKT_PRIVACY or PktPrivacy flags)
73759 09:28:50 (0) **    i.e. 'WMIC.EXE /NODE:"SERVER2" /AUTHLEVEL:Pktprivacy /NAMESPACE:\\ROOT\SERVICEMODEL Class __SystemSecurity'

Plea for help: Suggestions for further debugging this issue or alterations to the command that would allow successful remote execution of the method.


text:
Q: Deploy archive with JFrog CLI without overwriting existing packages I'm trying to set up an automated process for uploading archives of artifacts to a repo, without overwriting any existing packages. (to keep custom properties, original uploader metadata, etc.)
When I do this through the UI using an "underpriveleged" user (Only has Read, Annotate, and Deploy/Cache permissions, as confirmed by looking at that user in the Effective Permissions tab for the relevant repo), by clicking Deploy then selecting Deploy as Bundle Artifact it works fine, and appears to only upload the packages that don't exist.
But when I try to do the same, with the same user, through the JFrog CLI I keep on getting errors.
JFrog CLI:
jfrog rt u --explode=true --props="..." <path to zip> <repo name>

JFrog CLI Response:
[Error] [Thread 2] Artifactory response: 403 Forbidden

When attempting the same with a user that has Delete/Overwrite permissions the requests work fine, but they overwrite any existing packages and all those package's metadata.
Is there a way to upload only the artifacts that don't exist using the CLI like this?


text:
Q: Can not figure out how to delete local storage I tried making a reset button to delete everything but when you refresh page the list reappears...Any ideas?
http://jsfiddle.net/y8Uju/12/
EDITL: Sorry, you are right, stupid me I forgot to change my storage's name...duh..haha...thanks a lot! I am not very familiar with html 5, still learning it.
    var saved = JSON.parse(localStorage["numbers"] || "[]");
for(var i = 0; i < saved.length; i++) {
    storage.removeItem('saved[i]');
    add(false);
}

A: localStorage has two ways to remove data:
storage.removeItem('key'); // remove one item
storage.clear();           // remove everything


text:
Q: AWS SSL Configuration with google doamin I have problem with aws SSL configuration with google domain. Follwing is the configuration my website have.
www.abc.com  Google domain
myloadbalancer-XXXXXX.elb.amazon.com  aws load balancer
I have created SSL certificate on ACM as shown in image attached AWS ACM screenshot
Then i create loadblancer with Lister HTTPS and pointed to HTTP 80 port (EC2 instance on which website is running)  Screen shot of AWS load balancer
My google domain abc.com is pointing to loadbalancer url
Problem is when i open load balancer URL in browser it show error NET::ERR_CERT_COMMON_NAME_INVALID as showing in attached imageLoad balancer browser screenshot
When i open google domain abc.com it doesn't even show HTTPS. It works for http:abc.com
I am not able to find-out why abc.com not works with HTTPS.
Also i have confusion that on aws we set SSL in ACM for domain (abc.com) and then use this certificate in aws load balancer. Again load balancer is attached to google domain . Then google domain know get SSL via load balancer .Is there anything i am missing in whole setup

A: You should request a new certificate and add both *.abc.com and abc.com as its domain names.
According to the documentation:

When you request a wildcard certificate, the asterisk (*) must be in
  the leftmost position of the domain name and can protect only one
  subdomain level. For example, *.example.com can protect
  login.example.com and test.example.com, but it cannot protect
  test.login.example.com. Also note that *.example.com protects only the
  subdomains of example.com, it does not protect the bare or apex domain
  (example.com). However, you can request a certificate that protects a
  bare or apex domain and its subdomains by specifying multiple domain
  names in your request. For example, you can request a certificate that
  protects example.com and *.example.com.


text:
Q: Can't close dialog when DevExpress maskedit error is showing I'm doing the following to a TextEdit which is on a dialog form with a save and cancel button.
_underlyingEditor.Properties.Mask.EditMask = @"\((\d{3})\)-(\d{3})-(\d{4})";
_underlyingEditor.Properties.Mask.MaskType = MaskType.RegEx;
_underlyingEditor.Properties.Mask.UseMaskAsDisplayFormat = true;
_underlyingEditor.Properties.AutoHeight = false;

The problem is that if the user types a bad value into the editor then clicks Cancel the validation error shows and the screen doesn't close.  I've tried tying into the cancel buttons click event to try to clear the value from the editor but it's not firing.
Has anyone figured out a way to handle this?

A: Handle the FormClosing event and set the e.Cancel parameter to False. This should help.
The e.CloseReason parameter provides information about the reason of closing. You cah check it if it is necessary.

A: The dialog can't be closed if validation failed, this is a standard behavior and isn't related on DevExpress controls. However, you can workaround it by using DXErrorProvider to display these errors. This allows the form to be closed in spite of incorrect data. Please handle the editor's Validating event as shown below:
void textEdit1_Validating(object sender, System.ComponentModel.CancelEventArgs e) {
    if(e.Cancel) {
        dxErrorProvider1.SetError(textEdit1, "Error");
        e.Cancel = false;
    }
    else dxErrorProvider1.SetError(textEdit1, null);
}

Note, that you can use the DXErrorProvider.HasErrors property within the FormClosing event to avoid a form closing if it nesessary.


text:
Q: Use of Activator.CreateInstance(...) in ASP.NET MVC Unit Test Today I started adding unit tests to an ASP.NET MVC project we are developing for some time now. I created a new Test project and let VS 2010 generate all the test classes.
After running the resulting tests, all tests are failing. Debugging shows that most tests are failing because of a TargetInvocationException (Exception has been thrown by the target of an invocation.) that occurs at the line
object context = Activator.CreateInstance(type);

...which is used to initialize the DataContext of the application. Why is this exception thrown during test runs, and how can it be prevented?

A: TargetInvocationException, when thrown from Activator.CreateInstance, usually means the code inside the constructor is throwing an exception.  As Justin mentioned, the inner exception can help you determine what exactly went wrong.

A: I assume you are using Entity Framework alongside (or maybe Linq to Sql). Could it be that you need to configure a connection string in your test project (through App.config)?


text:
Q: ArrayList not initializes with predefined size I have an ArrayList of type my model, which conatins 3 items, that is the ArrayList size is 3.
ArrayList<Model> mModels; // mModels.size() = 3

I have to copy this ArrayList in to another ArrayList, so for that I have created another ArrayList of same type as follows.
ArrayList<Model> localModels = new ArrayList<>(mModels.size());

next step is to copy data from member variable to local variable, since I dont want to copy the reference of member variable I have used Collections.copy()
Collections.copy(localModels,mModels);

but I am getting ArrayOutOfBoundException by telling destination size should be greater than source size. so I have logged both variable size. then for the member I got the size as 3 and for the localVariable logged the size as 0.
UPDATE
and I have tried copiying member ArrayList to local one. but it copies only reference. is there any way to copy the data instead of reference ?
I have tried these methods
 //1
       for(Model model: mModels){
             localModels.add(model);
        }

 //2
       for(Model model: mModels){
          localModels.add((Model)model.clone());
       }

 //3
       Collections.copy(localModels, mModels);

 //4
       localModels = (ArrayList<Model>)mModels.clone();

 //5
       localModels = new ArrayList<>(mModels);

so my questions are
1- how can I copy (value change should not reflect) value from one ArrayList to another ?
2- why java/android always copiying the reference
3- how to intialize ArrayList with predefined size (already answered)

A: ArrayList<Model> localModels = new ArrayList<>(mModels.size());

creates an ArrayList whose initial capacity is equal to mModels.size() (3 in your example), but it contains 0 elements.
You have to add elements to the ArrayList in order for it to have a positive number of elements.
If you want your localModels ArrayList to contain the same elements as mModels, you can initialize it with :
ArrayList<Model> localModels = new ArrayList<>(mModels);

This will give you a shallow copy of the original ArrayList though.

A: You can copy the ArrayList directly using its constructor:
ArrayList<Model> localModels = new ArrayList<>(mModels);

Then there is no need to use Collections.copy.

A: Array Lists have dynamic size, so you don't need to initialize it with a pre-defined size. You can just use ArrayList.addall() to add the contents of one List object to another.
See the Docs here - http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#addAll(java.util.Collection)

A: finally I found the answer:
I have to copy each fields in the Models separately to second ArrayList
like
ArrayList<Model> localModels = new ArrayList<>(mModels.size());

for(Model model: mModels){
 Models tempModel = new Model();
 tempModel.setId(model.getId());
 tempModel.setName(model.getName());
 ....
 ....
 localModels.add(tempModel);
}

return localModels();

this is the way to copy contents inside one ArrayList to another ArrayList. any other method posted in question will copy only reference


text:
Q: Could it be an issue if I remove/replace the heatsink and don't clean the thermal paste? I removed my heatsink and didn't clean off the existing thermal paste.
I reattached it then left it for 4 days -  will cause any problems?

A: It really depends on the 'paste'.  Some of them are really just paste.  Others are designed to reflow when heated (so they will fill in all the spots you miss when applying it and the imperfections in the heatsink and CPU package lid).  Still others reflow and then harden like an adhesive to help keep the heatsink in place.
For the kind that hardens, always replace it, simply because once it's hardened, you can't easily put the two pieces back together again after taking them apart without significantly impacting the thermal conductivity.
For the first kind (just paste), you should usually just replace it.  It's very easy if you're not careful to accidentally introduce air bubbles that will then impact thermal conductivity, and because it doesn't reflow the bubbles will usually not dissipate over time.
For the kind that reflows though, it depends on whether it's dried out or not, and whether or not you have reason to believe it's been physically contaminated.  If it's dried out, just clean it off and reapply new paste (after decontaminating the surfaces too).  If you think it might be contaminated (sat in open air for a couple of days, was exposed in a really dusty room, touched it with an ungloved hand or something that could leave behind particulates), you should probably replace it too.


text:
Q: the difference of Autofac delegate factory and RegisterGeneratedFactory() Accordding to autofac doc, when a service constructor has duplicate types like the following:
public class DuplicateTypes
{
  public DuplicateTypes(int a, int b, string c)
  {
    // ...
  }
}

Func<X,Y,B> will not work, you should use a custom delegate type instead:
public delegate DuplicateTypes FactoryDelegate(int a, int b, string c);

with the delegate factory,we can resolve the FactoryDelegate without registering anything else:
builder.RegisterType<DuplicateTypes>();
var container = builder.Build();
var scope = container.BeginLifetimeScope();
var func = scope.Resolve<FactoryDelegate>();

But in the autofac doc,we can register that delegate using RegisterGeneratedFactory():
builder.RegisterType<DuplicateTypes>();
builder.RegisterGeneratedFactory<FactoryDelegate>(new TypedService(typeof(DuplicateTypes)));

after that we can also resolve the FactoryDelegate.
var func = scope.Resolve<FactoryDelegate>();

So what's the difference of delgate factory and RegisterGeneratedFactory?
Is RegisterGeneratedFactory redundant?
If not, which case suites RegisterGeneratedFactory?

A: The short version is you really don't need RegisterGeneratedFactory ever. If you look at the API docs on it, you can see it says:

These features are in this namespace because they will remain accessible to applications originally written against Autofac 1.4. In Autofac 2, this functionality is implicitly provided and thus making explicit registrations is rarely necessary.

So, basically, it's there for people who were using it before so we don't break them, but we're into Autofac 6 now and there's no value in using it in new applications.
We should probably look at deprecating those methods in Autofac so we can remove them in the next major release or so and reduce confusion.


text:
Q: Can not use EJB's in a Restful Webservice I have a pretty simple class that is a Restful web service. I want to use a EJB in the web service. I used the @EJB annotation to inject my EJB. The only problem was, the EJB was always null. I then made my web service a Stateless EJB itself. This fixed the null problem. However, when I try to call any function on my EJB, I get the following error:

EVERE: EJB5070: Exception creating stateless session bean : [CasperLoggingDao]
WARNING: EJB5184:A system exception occurred during an invocation on EJB CasperLoggingDao, method: public boolean com.dv.model.dao.CasperLoggingDao.log(com.dv.model.entity.CasperLogMessage)
WARNING: javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
    at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:454)
    at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2547)
    at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1899)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
    at $Proxy319.log(Unknown Source)
    at com.dv.model.dao.__EJB31_Generated__CasperLoggingDao__Intf____Bean__.log(Unknown Source)
    at com.dv.ws.casper.logging.CasperLoggingResource.putXml(CasperLoggingResource.java:64)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5388)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
    at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(Int
...

This is my class. Notice all I am doing is calling the log():
@Stateless
@Path("casper/logging")
public class CasperLoggingResource {

private static final Logger logger = Logger.getLogger(CasperLoggingResource.class.getName());

@Context
private UriInfo context;

@EJB
private CasperLoggingDao casperLogger;

/**
 * Creates a new instance of GenericResource
 */
public CasperLoggingResource() {
}

/**
 * PUT method for updating or creating an instance of GenericResource
 * @param content representation for the resource
 * @return an HTTP response with content of the updated or created resource.
 */
@PUT
@Consumes("application/xml")
public void putXml(String content) {
    try
    {
        CasperLogMessage message = CasperLogMessageConverter.convertXMLToEntity(content);
        casperLogger.log(message);
    }
    catch(Exception e)
    {
        logger.log(Level.SEVERE, "Could not execute", e);
    }
}

}

I had this working before. Do I need to do something special in order to access EJB's from a Restful web service? Any other ideas?
EDIT: Here is the code for CasperLoggingDao
@Stateless
@LocalBean
public class CasperLoggingDao extends BaseDao<CasperLogMessage> {

private static final Logger logger = Logger.getLogger(CasperLoggingDao.class.getName());

public CasperLoggingDao()
{
    super(CasperLogMessage.class);
}

public CasperLoggingDao(EntityManager em)
{
    super(CasperLogMessage.class, em);
}

public boolean log(CasperLogMessage casperLogMessage)
{
    return create(casperLogMessage) != null;
}

}

A: Is it safe to assume that your BaseDao has the call to EntityManager like so:
@PersistenceContext(unitName = "somePU")
protected EntityManager entityManager;

Also you don't need @LocalBean on CasperLoggingDao. And you also need @Stateless on BaseDao


text:
Q: function works correctly from MATLAB, but not when called from .NET I'm using MATLAB Builder NE for interoperability to call MATLAB functions from a C# .NET program built as a plug-in for the open source application ClearCanvas.  When I run the code normally from the .NET program, I usually (but not always) get the error message

MWMCR::EvaluateFunction error ... Reference to non-existent element of a cell array. Error in => ComputeT1Maps.m at line 178.

The line of MATLAB code in question is as follows:
seriesHeader = currentSlab.Slice{1}.MetaData{1}.Header;

Header is a struct of the form given by MATLAB's dicominfo function and MetaData{n} is a struct that contains the filename and image header struct for the nth image file.
The function signature for the ComputeT1Maps function is:
function ComputeT1Maps(data, options)

To try to figure out this bug I put the following line in at the beginning of the ComputeT1Maps function in order to preserve state so I could see what values were passed to MATLAB from .NET:
save(fullfile('F:\MATLAB\T1Mapping', 'T1_debug.mat'), 'data', 'options', ...
    '-mat', '-v7.3');

So, having preserved the inputs to this function (received from the .NET program that called it), I then tried running my ComputeT1Maps function from an interactive MATLAB session after loading in the saved variables, so that I could utilize MATLAB's debugging tools to figure out why I was getting the error.  That's when things got really bizarre.  The function works just fine from the interactive MATLAB session when given the exact same operands that were given to it when it was called from my .NET program.  How can this be?  How can the function fail when called from C# .NET, but run properly when given the exact same input in an interactive MATLAB session?  Also, this same code used to work before and the error only began to happen after I updated both my local installation of MATLAB and the MCR to the latest version (2011b).
On the .NET side, the data that is passed to MATLAB is constructed by the following function:
    public void ExchangeData(MultidimensionalDataCollection mdc, string outputPath, bool generateAncillaryTestImages,
        bool excludeAcquisitions, double[] exclusionList, bool showProgressBar, bool displayComputedImages,
        bool pauseAtEachSlice, bool softwareDiagnostics, bool displayProgressBar)
    {
        try
        {
            int subspaceIndex = 0;
            int slabIndex = 0;
            int sliceIndex = 0;
            int imageIndex = 0;

            MWStructArray topLevelGrouping;
            MWCellArray geometricSubspaceList;
            MWStructArray geometricGrouping;
            MWCellArray slabList;
            MWStructArray slabGrouping;
            MWCellArray sliceList;
            MWStructArray sliceGrouping;
            MWCellArray imageMetaData;
            MWStructArray perImageData;
            MWArray[] result;
            MWLogicalArray successFlag;
            MWStructArray header;
            MWCellArray sopInstanceUids;
            MWStructArray t1MapOptions;

            topLevelGrouping = new MWStructArray(1, 1, new string[] { "GeometricSubspace",
                "GeometricSubspaceCount" });
            topLevelGrouping["GeometricSubspaceCount", 1] = mdc.Count;
            geometricSubspaceList = new MWCellArray(1, mdc.Count);

            subspaceIndex = 0;
            foreach (GeometricSubspace subspace in mdc)
            {
                subspaceIndex++;

                geometricGrouping = new MWStructArray(1, 1, new string[] { "Slab",
                    "SlabCount" });
                geometricGrouping["SlabCount", 1] = subspace.Count;
                slabList = new MWCellArray(1, subspace.Count);

                slabIndex = 0;
                foreach (Slab slab in subspace)
                {
                    slabIndex++;

                    slabGrouping = new MWStructArray(1, 1, new string[] { "Slice",
                        "SliceCount" });
                    slabGrouping["SliceCount", 1] = slab.Count;
                    sliceList = new MWCellArray(1, slab.Count);

                    sliceIndex = 0;
                    foreach (Slice slice in slab)
                    {
                        sliceIndex++;

                        sliceGrouping = new MWStructArray(1, 1, new string[] {
                            "ImageCount", "MetaData", "MultidimensionalPixelData",
                            "SliceLocation", "SopInstanceUids" });
                        sliceGrouping["ImageCount", 1] = slice.Count;
                        imageMetaData = new MWCellArray(1, slice.Count);

                        int rows, columns;
                        short[,,,] multidimensionalPixelData = null;

                        imageIndex = 0;
                        foreach (Image image in slice)
                        {
                            imageIndex++;
                            short[,] imageMatrix = null;

                            if (!image.ImageSopClass.DicomUid.Equals(DicomUids.MRImageStorage))
                                throw new NotSupportedException("SopClass " + image.ImageSopClass.Name + " is not supported.");
                            else
                            {
                                DicomUncompressedPixelData rawPixelData = image.PixelData;

                                imageMatrix = GetCCImageMatrix(rawPixelData, out rows, out columns);

                                if (imageIndex == 1)
                                {
                                    multidimensionalPixelData = new short[slice.Count, 1, columns, rows];
                                }

                                for (int i = 0; i < rows; i++)
                                {
                                    for (int j = 0; j < columns; j++)
                                    {
                                        // Remember that C# array indices start with 0 while in MATLAB they start with 1
                                        multidimensionalPixelData[imageIndex - 1, 0, i, j] = imageMatrix[i, j];
                                    }
                                }
                            }
                            perImageData = new MWStructArray(1, 1, new string[] { "FileName", "Header" });
                            perImageData["FileName", 1] = image.FileName;

                            result = _mlT1Mapping.QT1GetDicomHeader(2, image.FileName);

                            if (result == null)
                                throw new Exception("GetDicomHeader failed to read the header file for filename:  " +
                                    image.FileName);
                            else
                            {
                                // MWStructArray
                                successFlag = (MWLogicalArray)result[0];
                                bool[] headerObtained = successFlag.ToVector();
                                if (headerObtained[0])
                                {
                                    header = (MWStructArray)result[1];
                                    perImageData["Header", 1] = header;

                                    imageMetaData[1, imageIndex] = perImageData;
                                }
                                else
                                {
                                    Console.WriteLine("GetDicomHeader failed to read the header file for filename:  " +
                                        image.FileName);
                                }
                            }
                        }
                        sliceList[1, sliceIndex] = sliceGrouping;
                        sliceGrouping["MetaData", 1] = imageMetaData;
                        sliceGrouping["SliceLocation", 1] = slice.SliceLocation;

                        List<string> theSops = slice._sopList;
                        sopInstanceUids = new MWCellArray(1, slice._sopList.Count);

                        int count = 0;
                        foreach (string sop in theSops)
                        {
                            count++;
                            sopInstanceUids[1, count] = sop;
                        }
                        sliceGrouping["SopInstanceUids", 1] = sopInstanceUids;
                        sliceGrouping["MultidimensionalPixelData", 1] = (MWNumericArray)multidimensionalPixelData;
                    }
                    slabList[1, slabIndex] = slabGrouping;
                    slabGrouping["Slice", 1] = sliceList;
                }
                geometricSubspaceList[1, subspaceIndex] = geometricGrouping;
                geometricGrouping["Slab", 1] = slabList;
            }
            topLevelGrouping["GeometricSubspace", 1] = geometricSubspaceList;

            t1MapOptions = new MWStructArray(1, 1, new string[] { "DirectoryPath",
                "ComputeDifferenceImages", "ComputeMultiplicationImages", "DisplayComputedImages", "PauseAtEachSlice",
                "SoftwareDiagnostics", "DisplayProgressBar"
            });

            t1MapOptions["DirectoryPath"] = (MWCharArray)outputPath;
            t1MapOptions["SaveS0Maps"] = (MWLogicalArray)generateAncillaryTestImages;
            t1MapOptions["ExcludeAcquisitions"] = (MWLogicalArray)excludeAcquisitions;
            t1MapOptions["ExclusionList"] = (MWNumericArray)exclusionList;
            t1MapOptions["DisplayComputedImages"] = (MWLogicalArray)displayComputedImages;
            t1MapOptions["PauseAtEachSlice"] = (MWLogicalArray)pauseAtEachSlice;
            t1MapOptions["SoftwareDiagnostics"] = (MWLogicalArray)softwareDiagnostics;
            t1MapOptions["DisplayProgressBar"] = (MWLogicalArray)displayProgressBar;

            _mlT1Mapping.ComputeT1Maps(topLevelGrouping, t1MapOptions);
        }
        catch (Exception)
        {
            throw;
        }
    }

A: I'm not yet 100% certain that I've fixed everything, but so far the tests appear to be succeeding after a few changes.  It seems that the crux of the problem was that the order of some assignments was transposed.  This occurred in a few places.  For example, instead of:
sliceList[1, sliceIndex] = sliceGrouping;
sliceGrouping["MetaData", 1] = imageMetaData;

it should have been ordered as:
sliceGrouping["MetaData", 1] = imageMetaData;
sliceList[1, sliceIndex] = sliceGrouping;

The strange thing about this bug was that the code worked just fine in the previous version of MATLAB.  It should have never worked at all!


text:
Q: Dynamically changing form action I'm trying to change the form action on the fly, but think I'm having a syntax problem, that I just can't figure out.
This works:
<?php
echo "<input type='submit' id='answerbutton' name='$buttonname'
value='$buttonvalue' onclick=\"this.form.action='linktogoto.php'\">";
?>

This doesn't work:
<?php
$variable = "linktogoto.php";
echo "<input type='submit' id='answerbutton' name='$buttonname'
value='$buttonvalue' onclick=\"this.form.action=$variable\">";
?>

I need to eventually change $variable depending on the situation, so need to get this to work.

A: <?php
$variable = "linktogoto.php";
echo "<input type='submit' id='answerbutton' name='$buttonname'
value='$buttonvalue' onclick=\"this.form.action=$variable\">";
?>

Should be:
<?php
$variable = "linktogoto.php";
echo "<input type='submit' id='answerbutton' name='$buttonname'
value='$buttonvalue' onclick=\"this.form.action='$variable'\">";
?>

Notice the ' around $variable.


text:
Q: А можно упростить XML файл конфигураци Spring? Ну я сразу скажу, что только начинаю изучать Spring, так что не судите очень строго.
Поймал себя на том, что пишу в файле конфигурации одно и то же.
<bean id="sorttask"
        class="Arhitecture.Sort.Sort_Task"
        factory-method="getTaskInstance" />

<bean id="timer"
      class="Arhitecture.ClockWork"
      scope="prototype"/>

<bean id="bubblesort"
      class="Solutions.Bubble_Sort">
    <constructor-arg ref="sorttask"/>
</bean>

<bean id="bubbleclock"
      class="Arhitecture.ClockWork"/>

<bean id="bubblesortwrapper"
      class="Arhitecture.Sort.Sort_SolutionWrapper">
    <constructor-arg index="0" ref="bubblesort"/>
    <constructor-arg index="1" ref="bubbleclock"/>
</bean>

<!--Feel like doing the same thing-->
<!--Need to find a way like <context:component-scan> and for each solution bean do new wrapper (solution, timer) -->

<bean id="mergesort"
      class="Solutions.Sort_by_Merge">>
    <constructor-arg ref="sorttask"/>
</bean>

<bean id="mergeclock"
      class="Arhitecture.ClockWork"/>
<bean id="mergesortwrapper"
      class="Arhitecture.Sort.Sort_SolutionWrapper">
    <constructor-arg index="0" ref="mergesort"/>
    <constructor-arg index="1" ref="mergeclock"/>
</bean>

<aop:config>
     <aop:pointcut id="runBubble" expression="execution(* Solutions.Bubble_Sort.run(..))"/>
     <aop:aspect ref="bubbleclock">
         <aop:before pointcut-ref="runBubble" method="clockStart"/>
         <aop:after  pointcut-ref="runBubble" method="clockEnd"/>
     </aop:aspect>

    <aop:aspect ref="bubblesortwrapper">
        <aop:after pointcut-ref="runBubble" method="setCorrectness"/>
    </aop:aspect>
</aop:config>

В конфигурации аспекта придется добавлять те же строки для других id.
Чтобы не повторяться, в голову приходит использовать <context:component-scan base-package="Solutions"/>, но я не придумал как создать для каждого отсканеного bean новый wrapper.
Подскажите, пожалуйста где искать решение.
Потом можно получить ссылки на все компоненты класса SolutionWrapper из объекта контекста, это я разобрался как сделать.


text:
Q: XML link into a PHP array I'm having trouble getting this page (http://ventrilostatus.net/xml/V98.DARKSTARLLC.COM:3789/) to array into php. I'm not very good with xml and I currently can only get it to display:
Server
Channel
Channel
Channel
(etc)
Could anyone help me get it to show the channel name and the users?
if there are not clients when you look at it it will be:
<client admin="1" cid="994" phan="0" ping="186" sec="56935" name="WHERE USER'S NAME HIS HERE" comm=""/>

A: U can use the simple_xml functions of PHP to load the xml file into a class.
http://php.net/manual/de/book.simplexml.php
Edit with an example:
// XML example
$xmlContent = '<server name="GuiltyofDestruction" phonetic="God" comment="http://guiltyofdestruction.com" auth="1" maxclients="25" uptime="137600" platform="Linux-i386" version="3.0.6" channelcount="36" clientcount="1" voicecodec="GSM 6.10" voiceformat="44 KHz, 16 bit"><channel cid="0" pid="-1" prot="0" name="Lobby" comm="">
    <channel cid="1033" pid="0" prot="1" name="Admin" comm=""/>
        <channel cid="1030" pid="0" prot="0" name="AFK Channel" comm="AFK">
            <client admin="1" cid="1030" phan="0" ping="182" sec="67575" name="US_ChairForce" comm=""/>
        </channel>
    </channel>
</server>';

// Loading XML information as object

//$xml = simplexml_load_file('http://ventrilostatus.net/xml/V98.DARKSTARLLC.COM:3789/'); // for files
$xml = simplexml_load_string($xmlContent); // for strings
foreach($xml->channel->channel as $channel) {
    if($channel->client)
        echo $channel->client->attributes()->name; // returns "US_ChairForce"
}

I think it's clear now. You have to iterate through every channel and look for clients.

A: sorry this is the code I updated:
<?PHP
echo "
";
$xml = simplexml_load_file('http://ventrilostatus.net/xml/V98.DARKSTARLLC.COM:3789/'); // for files
//$xml = simplexml_load_string($xmlContent); // for strings

foreach($xml->channel as $lobby) {
echo "
";
echo "";
echo "";
echo $lobby->attributes()->name;
echo "";
echo "
";
}

foreach($xml->channel->channel as $channel) {
if($channel->attributes()->prot == "0"){
echo "
  ";
echo "";
echo "";
echo $channel->attributes()->name;
echo "";
echo "
";
                                        }else{
echo "
  ";
echo "";
echo "";
echo $channel->attributes()->name;
echo "";
echo "
";
  }

if($channel->client){
for ( $i = 0; $i < count($channel->client); $i++ ){
$client = $channel->client[ $i ];

        if ( $client->attributes()->cid != $client->attributes()->cid )

            continue;
echo "
  ";
echo "";
if($client->attributes()->admin == "1"){

     echo $client->attributes()->name;
     echo " (Admin)";
     }else{
     echo $client->attributes()->name;
     }

echo "
";
}
}

foreach($channel->channel as $subchannel) {
if($subchannel->attributes()->prot == "0"){
echo "
    ";
echo "";
echo "";
echo $subchannel->attributes()->name;
echo "";
echo "
";
                                        }else{
echo "
    ";
echo "";
echo "";
echo $subchannel->attributes()->name;
echo "";
echo "
";
  }

if($subchannel->client){
for ( $i = 0; $i < count($subchannel->client); $i++ ){
$client = $subchannel->client[ $i ];

        if ( $client->attributes()->cid != $client->attributes()->cid )

            continue;
echo "
    ";
echo "";
if($client->attributes()->admin == "1"){

     echo $client->attributes()->name;
     echo " (Admin)";
     }else{
     echo $client->attributes()->name;
     }

echo "
";
}
}

foreach($subchannel->channel as $subchannel2) {
if($subchannel2->attributes()->prot == "0"){
echo "
      ";
echo "";
echo "";
echo $subchannel2->attributes()->name;
echo "";
echo "
";
                                        }else{
echo "
      ";
echo "";
echo "";
echo $subchannel2->attributes()->name;
echo "";
echo "
";
  }

if($subchannel2->client){
for ( $i = 0; $i < count($subchannel2->client); $i++ ){
$client = $subchannel2->client[ $i ];

        if ( $client->attributes()->cid != $client->attributes()->cid )

            continue;
echo "
      ";
echo "";
if($client->attributes()->admin == "1"){

     echo $client->attributes()->name;
     echo " (Admin)";
     }else{
     echo $client->attributes()->name;
     }

echo "
";
}
}

foreach($subchannel2->channel as $subchannel3) {
if($subchannel3->attributes()->prot == "0"){
echo "
        ";
echo "";
echo "";
echo $subchannel3->attributes()->name;
echo "";
echo "
";
                                        }else{
echo "
        ";
echo "";
echo "";
echo $subchannel3->attributes()->name;
echo "";
echo "
";
  }

if($subchannel3->client){
for ( $i = 0; $i < count($subchannel3->client); $i++ ){
$client = $subchannel3->client[ $i ];

        if ( $client->attributes()->cid != $client->attributes()->cid )

            continue;
echo "
        ";
echo "";
if($client->attributes()->admin == "1"){

     echo $client->attributes()->name;
     echo " (Admin)";
     }else{
     echo $client->attributes()->name;
     }

echo "
";
}
}
}

}
}
}
echo "
";
?>

which shows

*

*lobby

*channel

*subchannel

*subchannel


text:
Q: Can a user without admin rights manage object access privileges in hive? I am working with hive 0.14 mainly using beeline.
I am not an admin but I am looking to create a couple of views that the team can use.
We've got a common hive database where everyone has read+write. If I am creating certain tables/views that I don't want other people to be able to drop or modify, is it possible for me to revoke drop/write access for others?

A: The access to hive tables depends on HDFS access rights.
Whenever you create a new table tbl in database located in  db, a new directory db/tbl will be created.
If you want to restrict write group access to that directory use hadoop fs -chmod, for example:
hadoop fs -chmod 750 db/tbl
If you want to find out where tables are located in a database, you can create a table without specifying a location, and run describe formated tbl.
You can always check what are the access rights of the tables by running hadoop fs -ls db
Regarding views:

Although Storage Based Authorization can provide access control at the level of Databases, Tables and Partitions, it can not control authorization at finer levels such as columns and views because the access control provided by the file system is at the level of directory and files. A prerequisite for fine grained access control is a data server that is able to provide just the columns and rows that a user needs (or has) access to. In the case of file system access, the whole file is served to the user. HiveServer2 satisfies this condition, as it has an API that understands rows and columns (through the use of SQL), and is able to serve just the columns and rows that your SQL query asked for.
SQL Standards Based Authorization (introduced in Hive 0.13.0, HIVE-5837) can be used to enable fine grained access control. It is based on the SQL standard for authorization, and uses the familiar grant/revoke statements to control access. It needs to be enabled through HiveServer2 configuration.
Note that for Hive command line, SQL Standards Based Authorization is disabled. This is because secure access control is not possible for the Hive command line using an access control policy in Hive, because users have direct access to HDFS and so they can easily bypass the SQL standards based authorization checks or even disable it altogether. Disabling this avoids giving a false sense of security to users.

So, in short, SQL Standards Based Authorization needs to be enabled in the config.
Then you'll be able to use: REVOKE on views.


text:
Q: Standalone Jenkins build integration with Kubernetes Cluster I am working on running a build job on my Jenkins to deploy an image to Kubernetes cluster.
I have a Java Microservice application and I am using fabric8 to build the docker image and push it to a private repository.
I am facing issues while running fabric8:deploy. Below are the error messages.
[ERROR] F8: Could not connect to kubernetes cluster!
[ERROR] F8: Have you started a local cluster via `mvn fabric8:cluster-   start` or connected to a remote cluster via `kubectl`?
  [INFO] F8: For more help see: http://fabric8.io/guide/getStarted/
 [ERROR] F8: Connection error: %s: java.net.UnknownHostException: kubernetes.default.svc

I cannot install kubectl on my Jenkins host due to corporate regulations. I'd like to be able to make my fabric8:deploy work. How can I achieve connection between Jenkins and Kubernetes? I am not sure if Jenkins nodes is an option. Appreciate your ideas.
TIA

A: Another way to provide authentication credential for Kubernetes/OpenShift cluster is to set environment variables.
KUBERNETES_MASTER - > Master URL for k8s
KUBERNETES_AUTH_BASIC_USERNAME
KUBERNETES_AUTH_BASIC_PASSWORD

Can you try this?
Since Jenkins is running with some corporate restrictions. In case it's running behind firewall and getting connection issues, optionally you may like to configure proxy with the following environment variables
HTTPS_PROXY
HTTPS_PROXY
PROXY_USERNAME
PROXY_PASSWORD
NO_PROXY


text:
Q: Customized series title in openpyxl python I am trying to modify the existing xlsx sheet and adding graphs to it using openpyxl module in python.
But while creating a line chart, the series title is shown as Series 1,Series 2,Series 3,Series 4 where as I need to rename the series title as "A", "B", "C", D". (Note: this name are not fetched from any cell)
Another possible solution would to give series name from another worksheet apart from row/column of the same worksheet. But not sure whether it is doable.
Below code give me the series name from row/column of worksheet 'ws'.
But I need to rename it (customize name) or assign the series name from another sheet.
Can any one help me on this.?
c1 = LineChart()
c1.title = worksheet
c1.x_axis.title = "Average depth"
c1.y_axis.title = "Average Response time (ms)"
c1.y_axis.majorGridlines = None

refseries1 = Reference(ws, min_col=5, min_row=2, max_col=5, max_row=9)
seriesdata1 = Reference(ws, min_col=6, min_row=10, max_col=6, max_row=15)

c1.add_data(data=seriesdata1,titles_from_data=False)
c1.set_categories(refseries1)

In above code, refseries1 is xaxis data and seriesdata1 is y axis data.

A: I found a solution in a different question that works for me:
from openpyxl.chart import LineChart, Reference, Series

chart1 = LineChart()
# setup and append the first series
values = Reference(dprsheet, min_col=2, min_row=1, max_row=34)
series = Series(values, title="First series of values")
chart1.append(series)

# setup and append the second series
values = Reference(dprsheet, min_col=3, min_row=1, max_row=34)
series = Series(values, title="Second series of values")
chart1.append(series)

#set x-axis
dates = Reference(dprsheet, min_col=2, min_row=1, max_row=34)
chart1.set_categories(dates)

It's a bit more fiddly than the chart.add_data method, I'm going to assume that if you dig around in the code for that method you'll find something a bit more... pythony.


text:
Q: MegaRaid LSI-9271-8i random drive failure Anyone have tips on figuring out if I have a bad megaraid card? No matter how I configure with bbu or without. I am using wd red drives and even with brand spanking new drives it marks random drives as failed. While moving data do it. I fear I have a faulty card, but it is brand new as well. So any help in debugging would be great. It's running a home server
Specs:
MB: SUPERMICRO MBD-X10SLM+-F-O uATX Server Motherboard LGA 1150 Intel
OS: Windows 10 Pro workstation on SAMSUNG 840 EVO SAMSUNG 840 EVO 2.5" 120GB
PS:Athena Power AP-U2ATX80FEP8 800W Single 2U IPC Server Power Supply
Mem: 2x Kingston 8GB 240-Pin DDR3 1600 (PC3 12800) ECC Unbuffered blades
CPU: Intel Pentium G3258 3.20GHz

A: Thanks D.Fritz for the tips. Took a bit, but it's the server case. It's a 2u case with on onboard power distribution block for the hd's so the psu(power supply) wasn't directly connected. It was failing to distribute the correct juice and would dip low at times causing things to look like a drive/card issue. Tested it on another server mb and direct connection to psu and and then dumped 4tb's on it without issue. Went back to the original server and set the drives outside the case and direct psu connection raid 50, bbu installed and haven't had a problem. So time to see if I can replace that case power distro or gonna mod the case for direct psu connection.

A: Don't set the BBU if you don't have one.  That can cause problems like what you are describing.
Try a simple RAID 0 on two drives and measure your I/O.  Make sure you are with-in specs of your card. Bad performance is a good indicator of a faulty card.
I've deployed hundreds of these cards across different configurations. Avoid the lowest end versions as I have thrown many of them in the trash.


text:
Q: wraptext a hyperlink in a given cell I'm trying to wraptext in the hyperlink cell, but am unable to get it to work correctly.  I get the "object doesn't support this property" error.  I realize the format is incorrect, but can't find the proper syntax.  If you have a link to a site or suggestion, greatly appreciated.  Thanks!
With wbk.Sheets(1)
Set rngResults = .Range("A" & .Rows.Count).End(xlUp).Offset(1, 0)
    bingo = fld.Path & "\" & fl.Name
    ActiveSheet.Hyperlinks.Add Anchor:=rngResults, Address:=bingo, SubAddress:=aCell.Address, TextToDisplay:=strJackpot
    .WrapText = True
End With

A: WrapText is used with the range, not the hyperlink or the worksheet, so you need to fully qualify it.
Change the .WrapText = True line to the following to make it work:
rngResults.WrapText = True


text:
Q: ChartJS - TypeError: Cannot read property '_model' of null - Angular I'm on a project to display data in a ChartJS graph in real time.
From a service, I get data from an external webserver. I success to have 6 array (they are changing in real time) with always 10 values :
for (const module of parsedListResults) {
  this._consoAir[module.id - 1].shift();
  this._consoAir[module.id - 1].push(module.consoAir);
}

So every 5 secondes, the array of data are changing :
0: (10) [0, 0, 0, 0, 0, 0, 6.865885, 6.865885, 6.865885, 6.865885]
1: (10) [0, 0, 0, 0, 0, 0, 6.865885, 6.865885, 6.865885, 6.865885]
2: (10) [0, 0, 0, 0, 0, 0, 6.865885, 6.865885, 6.865885, 6.865885]
3: (10) [0, 0, 0, 0, 0, 0, 6.865885, 6.865885, 6.865885, 6.865885]
4: (10) [0, 0, 0, 0, 0, 0, 6.865885, 6.865885, 6.865885, 6.865885]
5: (10) [0, 0, 0, 0, 0, 0, 4.654, 4.654, 4.654, 4.654, _chartjs: {…}, push: ƒ, pop: ƒ, shift: ƒ, splice: ƒ, …]
length: 6

The graph is display on a page with an id. For the page 3, we have localhost:4200/lines/3, so we want the 3rd array for the graph, and I do that here :
import {Component, Input, OnDestroy, OnInit} from '@angular/core';
import { ChartType } from 'chart.js';
import { LineService } from '../services/line.service';
import {ActivatedRoute, Data} from '@angular/router';
import {combineLatest, Subscription} from 'rxjs';
import {filter, map} from 'rxjs/operators';

@Component({
  selector: 'app-conso-graph',
  templateUrl: './conso-graph.component.html',
  styleUrls: ['./conso-graph.component.scss']
})
export class ConsoGraphComponent implements OnDestroy{

  lineSubscription: Subscription;
  id: number;
  consoAir: number;
  chartType: ChartType;
  chartOptions: any;
  _time: any[] = Array(10).fill(0);
  _consoAir: any[];
  dataType: Data;

  constructor(private lineService: LineService,
              private route: ActivatedRoute) {
    this.chartIt();
    setInterval(() => {
     this.chartIt();
    }, 5000);
  }

  _focusedData$ = combineLatest(
    this.lineService.lineSubject.pipe(filter(x => x.length > 0)),
    this.route.params.pipe(filter(x => !!x.id), map(x => x.id - 1))
  ).pipe(
    map(([csvs, id]) => csvs[id])
  );

  gestionData(): void {
    this.lineSubscription = this._focusedData$.subscribe(x => this.id = x.id);
    this._consoAir = this.lineService._consoAir;
  }

  async chartIt(): Promise<void> {
    await this.gestionData();

    this.chartType = 'line';
    this.dataType = [{
      data: this._consoAir[this.id - 1],
      label: 'Consommation Air'
    }];

    console.log(this._consoAir[this.id - 1]);
  }

  chartClicked(e: any): void { }
  chartHovered(e: any): void { }

  ngOnDestroy(): void {
    this.lineSubscription.unsubscribe();
  }

}

And for the HTML, we have :
<div class="doubleTrp">
    <canvas baseChart
            [chartType]="chartType"
            [datasets]="dataType"
            [labels]="this._time"
            [colors]="[{
              backgroundColor: ['rgb(255, 182, 0)'],
              hoverBackgroundColor: ['rgb(185, 30, 30)'],
              borderWidth: 1
            }]"
            [options]="{
              responsive: true,
              cutoutPercentage: 100,
              animation: {
                duration: 0
              },
              title : {
                display: true,
                text: 'Consommation Air',
                fontSize: 25
              }
            }"
            [legend]="true"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)">
    </canvas>
</div>

The probleme isn't when I am in page with the graph is display, the probleme is when I go to other page (like localhost4200/), I have this error "ERROR TypeError: Cannot read property '_model' of null" and I don't know how I can resolve that.
Thanks for your responses, I'm completely lost.

A: To find the problems, I write the array of data in my html template ...
I replace this :
this.dataType = [{
  data: this._consoAir[this.id - 1],
  label: 'Consommation Air'
}];

By this in HTML :
<canvas baseChart
            [datasets]="[{
      data: this._consoAir[0],
            this._consoAir[1],
            ...
            this._consoAir[9],
      label: 'Consommation Air'
    }]"
...


text:
Q: ERROR Response must contain the AMP-Access-Control-Allow-Source-Origin header Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token
Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Origin:https://www-example-com.cdn.ampproject.org
AMP-Access-Control-Allow-Source-Origin:https://www.example.com
AMP-Control-Expose-Headers:AMP-Access-Control-Allow-Source-Origin
AMP-Same-Origin:true
Cache-Control:no-cache
Content-Length:3
Content-Type:text/html; Charset=utf-8
Date:Thu, 18 Jan 2018 11:47:52 GMT
Server:Microsoft-IIS/8.5
X-Powered-By:ASP.NET
X-Powered-By-Plesk:PleskWin

Request Headers
Accept:application/json
Accept-Encoding:gzip, deflate, br
Accept-Language:tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7
Connection:keep-alive
Content-Length:707
Host:www.example.com
Origin:https://www-example-com.cdn.ampproject.org
Referer:https://www-example-com.cdn.ampproject.org/v/s/www.example.com/amp/gc/hbt.html?usqp=adadadas&amp_js_v=0.1
User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1

Query String Parameters
__amp_source_origin:https://www.example.com

not working
https://www.google.com.tr/amp/s/www.example.com/amp
working
www.example.com/amp
ERROR CODE

*

*Response must contain the AMP-Access-Control-Allow-Source-Origin header

*Form submission failed: Error: Response must contain the AMP-Access-Control-Allow-Source-Origin header
waiting for your help

A: In PHP we ca do like this:
if(!empty($_POST)){
        $domain_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
        header("Content-type: application/json");
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Origin: ". str_replace('.', '-','https://example.com') .".cdn.ampproject.org");
        header("AMP-Access-Control-Allow-Source-Origin: " . $domain_url);
        header("AMP-Redirect-To: https://example.com/thankyou.amp.html");
        header("Access-Control-Expose-Headers: AMP-Redirect-To, AMP-Access-Control-Allow-Source-Origin");
        echo json_encode(array('successmsg'=>'data post'));
        exit;
}

Please make sure that domain url should be https

Replace https://example.com/ to your desired url


text:
Q: Error 1064 in stored procedure I'm not an expert with MySQL and I've problems with this Stored Procedure.
I'm trying to do the SP with conditions but I don't know what is wrong here, I have a mistake:

Error Code: 1064. You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near 'declare done int default 0;    declare continue
  handler for sqlstate '02000' set' at line 16

delimiter $$
create procedure getListPrsn(IN idEquipo INT, IN tipo char, IN Puesto INT)
begin
declare varJefe int;
declare eqpSupJefe int;
declare jefeONo cursor for select tblpuesto.PtoLiderEqp from tblequipo
    inner join tblpuesto   on (tblequipo.EqpID=tblpuesto.PtoEqp)
    inner join tblplaza    on (tblpuesto.PtoID=tblplaza.PzaPto)
    inner join tblpersona on (tblplaza.PzaPrsn=tblpersona.PrsnID)
    where tblequipo.EqpID=idEquipo and tblpuesto.PtoID=Puesto;
declare equipoSuperiorDeMiJefe cursor for select tblequipo.EqpEqpSup
    from tblequipo
    inner join tblpuesto on(tblequipo.EqpID=tblpuesto.PtoEqp)
    where tblpuesto.PtoID=Puesto;
if tipo="jefe"
    then
        declare done int default 0;
        declare continue handler for sqlstate '02000' set done=1;
        open jefeONo;
            begin
                repeat
                    fetch jefeONo into varJefe;
                until done end repeat;
            end;
        close jefeONo;
        if varJefe=1
            then
                declare done int default 0;
                declare continue handler for sqlstate '02000' set done=1;
                open equipoSuperiorDeMiJefe;
                    begin
                        repeat
                            fetch equipoSuperiorDeMiJefe into eqpSupJefe;
                        until done end repeat;
                    end;
                close equipoSuperiorDeMiJefe;
                call getLider(eqpSupJefe);
        else
            if varJefe=0
                then
                    call getLider(idEquipo);
            end if;
        end if;
end if;
end $$
delimiter ;

A: Problem is in the part as pointed below, where you are trying to declare a local variable inside IF .. ELSE block. You can set the variable inside if .. else block but you should declare them in the beginning
   if varJefe=1
        then
            declare done int default 0; <-- Here

You should declare the variable at the beginning like
create procedure getListPrsn(IN idEquipo INT, IN tipo char, IN Puesto INT)
begin
declare varJefe int;
declare eqpSupJefe int;
declare done int default 0; <-- declare it here

A: A DECLARE has to be at the beginning of a BEGIN ... END block. You can either move them to the beginning of the procedure (the variable declaration has to be before the cursors, the handler declaration has to be after them):
delimiter $$
create procedure getListPrsn(IN idEquipo INT, IN tipo char, IN Puesto INT)
begin
declare varJefe int;
declare eqpSupJefe int;
declare done int default 0;
declare jefeONo cursor for select tblpuesto.PtoLiderEqp from tblequipo
    inner join tblpuesto   on (tblequipo.EqpID=tblpuesto.PtoEqp)
    inner join tblplaza    on (tblpuesto.PtoID=tblplaza.PzaPto)
    inner join tblpersona on (tblplaza.PzaPrsn=tblpersona.PrsnID)
    where tblequipo.EqpID=idEquipo and tblpuesto.PtoID=Puesto;
declare equipoSuperiorDeMiJefe cursor for select tblequipo.EqpEqpSup
    from tblequipo
    inner join tblpuesto on(tblequipo.EqpID=tblpuesto.PtoEqp)
    where tblpuesto.PtoID=Puesto;
declare continue handler for sqlstate '02000' set done=1;

if tipo="jefe"
    then
        open jefeONo;
            begin
                repeat
                    fetch jefeONo into varJefe;
                until done end repeat;
            end;
        close jefeONo;
        if varJefe=1
            then
                open equipoSuperiorDeMiJefe;
                    begin
                        set done = 0;
                        repeat
                            fetch equipoSuperiorDeMiJefe into eqpSupJefe;
                        until done end repeat;
                    end;
                close equipoSuperiorDeMiJefe;
                call getLider(eqpSupJefe);
        else
            if varJefe=0
                then
                    call getLider(idEquipo);
            end if;
        end if;
end if;
end $$
delimiter ;

or put them after the BEGIN statements before the REPEAT statements:
delimiter $$
create procedure getListPrsn(IN idEquipo INT, IN tipo char, IN Puesto INT)
begin
declare varJefe int;
declare eqpSupJefe int;
declare jefeONo cursor for select tblpuesto.PtoLiderEqp from tblequipo
    inner join tblpuesto   on (tblequipo.EqpID=tblpuesto.PtoEqp)
    inner join tblplaza    on (tblpuesto.PtoID=tblplaza.PzaPto)
    inner join tblpersona on (tblplaza.PzaPrsn=tblpersona.PrsnID)
    where tblequipo.EqpID=idEquipo and tblpuesto.PtoID=Puesto;
declare equipoSuperiorDeMiJefe cursor for select tblequipo.EqpEqpSup
    from tblequipo
    inner join tblpuesto on(tblequipo.EqpID=tblpuesto.PtoEqp)
    where tblpuesto.PtoID=Puesto;
if tipo="jefe"
    then
        open jefeONo;
            begin
                declare done int default 0;
                declare continue handler for sqlstate '02000' set done=1;
                repeat
                    fetch jefeONo into varJefe;
                until done end repeat;
            end;
        close jefeONo;
        if varJefe=1
            then
                open equipoSuperiorDeMiJefe;
                    begin
                        declare done int default 0;
                        declare continue handler for sqlstate '02000' set done=1;
                        repeat
                            fetch equipoSuperiorDeMiJefe into eqpSupJefe;
                        until done end repeat;
                    end;
                close equipoSuperiorDeMiJefe;
                call getLider(eqpSupJefe);
        else
            if varJefe=0
                then
                    call getLider(idEquipo);
            end if;
        end if;
end if;
end $$
delimiter ;

A: I fix my SP
We have to check the declaration order
1.- variables
2.- conditions
3.- cursors
4.- handlers
delimiter $$
create procedure getListPrsn(IN idEquipo INT, IN tipo CHAR, IN Puesto INT)
begin
declare varJefe int;
declare eqpSupJefe int;
declare done int default 0;
case tipo
    when "jefe" then
        begin
            declare jefeONo cursor for select tblpuesto.PtoLiderEqp from tblequipo
                inner join tblpuesto   on (tblequipo.EqpID=tblpuesto.PtoEqp)
                inner join tblplaza    on (tblpuesto.PtoID=tblplaza.PzaPto)
                inner join tblpersona on (tblplaza.PzaPrsn=tblpersona.PrsnID)
                where tblequipo.EqpID=idEquipo and tblpuesto.PtoID=Puesto;
            declare continue handler for sqlstate '02000' set done=1;
            open jefeONo;
                repeat
                    fetch jefeONo into varJefe;
                until done end repeat;
            close jefeONo;
            set done=0;
            if varJefe=1
                then
                    begin
                        declare equipoSuperiorDeMiJefe cursor for select tblequipo.EqpEqpSup
                            from tblequipo
                            inner join tblpuesto on(tblequipo.EqpID=tblpuesto.PtoEqp)
                            where tblpuesto.PtoID=Puesto;
                        declare continue handler for sqlstate '02000' set done=1;
                        open equipoSuperiorDeMiJefe;
                            repeat
                                fetch equipoSuperiorDeMiJefe into eqpSupJefe;
                            until done end repeat;
                        close equipoSuperiorDeMiJefe;
                        call getLider(eqpSupJefe);
                    end;#begin del if varJefe=1
            else
                if varJefe=0
                    then
                        call getLider(idEquipo);
                end if;
            end if;
        end;#begin del case JEFE
end case;
end $$
delimiter ;


text:
Q: Gitignore config - how to make git aware I configured git with:
git config --global core.excludesFile ~/.gitignore

I added new rules:
*.png
*.h5
*.mat
each one on a different line (consecutive lines)
then saved.
Then went to my git folder (with my source code, other files etc.). I do git add *, but git still wants to add h5 files!!. Do I have to do something else? How to make git aware of the new ignore rules before git add?
I have read that creating a .gitignore file and running the aforementioned command was enough to force git to be aware of the ignored files in a global way?

A: You can remove the git cache and then add all files again
git rm -r --cached .

Add all files again
git add .

And then commit changes
git commit -m ".gitignore is now working"

Note: be aware to commit all your changes before, otherwise you will lose control on all the changed files
See here for more info


text:
Q: Continous daily development with Scala on OSX without IDEs How do I continuously compile and run my scala code whenever one of my source files has changed?

A: Use sbt tool for this.
# install sbt with homebrew
brew install sbt

# - create a new scala project
# - name your project name when asked like: hello-world
sbt new sbt/scala-seed.g8

# go to the new project directory that you named
cd hello-world

# run sbt to open the sbt shell
sbt

# run your project in continuous running mode
~ run

# to continuously see the test outputs
# open up a new terminal tab, run sbt, and in sbt shell, type:
~ test

This will greatly simplify your edit-compile-run cycles.


text:
Q: Qt server / Java Client communication problems I am currently trying to get a little network communication going between a qt server and a java client.
In my example, the client wants to send an image to the Server. My problem is now, that the server never sees the data, so bytesAvailable() returns 0.
I already tried QDataStream, QTextStream and readAll(), still no data.
Server:
QTcpServer* tcpServer;
QTcpSocket* client;
tcpServer = new QTcpServer();

if(!tcpServer->listen(QHostAddress::Any, 7005)){
    tcpServer->close();
    return;
}
...
tcpServer->waitforNewConnection();
client = tcpServer->nextPendingConnection();
client->waitForConencted();
while(client->state()==connected){
    // Syntax here might be iffy, did it from my phone
    if(client->bytesAvailable()>0){
    //do stuff here, but the program doesnt get here, since bytesAvailable returns 0;
}

}
CLient:
    public SendPackage() {
    try {
        socket = new Socket(ServerIP, Port);
        socket.setSoTimeout(60000);
        output = new BufferedOutputStream(socket.getOutputStream());
        outwriter = new OutputStreamWriter(output);
    } catch (ConnectException e) {
        System.out.println("Server error, no connection established.");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public void Send(BufferedImage img) {

    try {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, GUI.imageType, baos);
        baos.flush();
        byte[] imgbyte = baos.toByteArray();
        System.out.println(imgbyte.length);
        System.out.println("sending");

        outwriter.write(imgbyte.length);
        outwriter.flush();
        // here i'd send the image, if i had a connection ...
        output.flush();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

The connection and everything builds up fine, the code even tells me when the socket was disconnected when trying to send, so I guess connection isn't a problem.
I just started using Qt, so if you guys have any idea to why this wouldn't work, I'd be pleased to try it.

A: client->waitForConencted();

// At this point the client is connected, but it is likely that no data were received yet

client->waitForReadyRead(-1); // <- Add this

// Now there should be at least 1 byte available, unless waitForConencted or waitForReadyRead failed (you should check that)

if(client->bytesAvailable() > 0) {
    // ...
}

Note that you can not expect all the data to arrive at once. The TCP stream can get fragmented in any way and the data will be received in randomly sized pieces. You must repeat waiting and reading until you receive everything. This also means that you must somehow know when you did receive everything. So you need to know how much data is coming, or somehow recognize the end of it. You can for example disconnect right after the data transfer, or send the data length first. Depends on your application.
Also have a look at QIDevice::readyRead signal which would allow you to handle reading asynchronously.