text:
Q: Download JSON object as a file from browser I have the following code to let users download data strings in csv file.
exportData = 'data:text/csv;charset=utf-8,';
exportData += 'some csv strings';
encodedUri = encodeURI(exportData);
newWindow = window.open(encodedUri);

It works just fine that if client runs the code it generates blank page and starts downloading the data in csv file.
So I tried to do this with JSON object like
exportData = 'data:text/json;charset=utf-8,';
exportData += escape(JSON.stringify(jsonObject));
encodedUri = encodeURI(exportData);
newWindow = window.open(encodedUri);

But I see only a page with the JSON data displayed on it, not downloading it.
I went through some research and this one claims to work but I don't see any difference to my code.
Am I missing something in my code?
Thanks for reading my question:)

A:     downloadJsonFile(data, filename: string){
        // Creating a blob object from non-blob data using the Blob constructor
        const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        // Create a new anchor element
        const a = document.createElement('a');
        a.href = url;
        a.download = filename || 'download';
        a.click();
        a.remove();
      }

You can easily auto download file with using Blob and transfer it in first param downloadJsonFile. filename is name of file you wanna set.

A: If you prefer console snippet, raser, than filename, you can do this:
window.open(URL.createObjectURL(
    new Blob([JSON.stringify(JSON)], {
      type: 'application/binary'}
    )
))

A: The download property of links is new and not is supported in Internet Explorer (see the compatibility table here).  For a cross-browser solution to this problem I would take a look at FileSaver.js

A: Found an answer.
var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));

$('download JSON').appendTo('#container');

seems to work fine for me.
** All credit goes to @cowboy-ben-alman, who is the author of the code above **

A: You could try using:

*

*the native JavaScript API's Blob constructor and

*the FileSaver.js saveAs() method

No need to deal with any HTML elements at all.
var data = {
    key: 'value'
};
var fileName = 'myData.json';

// Create a blob of the data
var fileToSave = new Blob([JSON.stringify(data)], {
    type: 'application/json'
});

// Save the file
saveAs(fileToSave, fileName);

If you wanted to pretty print the JSON, per this answer, you could use:
JSON.stringify(data,undefined,2)

A: React: add this where you want in your render method.
• Object in state:

  DOWNLOAD DATA AS JSON

• Object in props:

  DOWNLOAD DATA AS JSON

className and style are optional, modify the style according to your needs.

A: This is how I solved it for my application:
HTML:

JS (pure JS, not jQuery here):
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(storageObj));
var dlAnchorElem = document.getElementById('downloadAnchorElem');
dlAnchorElem.setAttribute("href",     dataStr     );
dlAnchorElem.setAttribute("download", "scene.json");
dlAnchorElem.click();

In this case, storageObj is the js object you want to store, and "scene.json" is just an example name for the resulting file.
This approach has the following advantages over other proposed ones:

*

*No HTML element needs to be clicked

*Result will be named as you want it

*no jQuery needed

I needed this behavior without explicit clicking since I want to trigger the download automatically at some point from js.
JS solution (no HTML required):
  function downloadObjectAsJson(exportObj, exportName){
    var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
    var downloadAnchorNode = document.createElement('a');
    downloadAnchorNode.setAttribute("href",     dataStr);
    downloadAnchorNode.setAttribute("download", exportName + ".json");
    document.body.appendChild(downloadAnchorNode); // required for firefox
    downloadAnchorNode.click();
    downloadAnchorNode.remove();
  }

A: This would be a pure JS version (adapted from cowboy's):
var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));

var a = document.createElement('a');
a.href = 'data:' + data;
a.download = 'data.json';
a.innerHTML = 'download JSON';

var container = document.getElementById('container');
container.appendChild(a);

http://jsfiddle.net/sz76c083/1

A: ES6+ version for 2021; no 1MB limit either:
This is adapted from @maia's version, updated for modern Javascript with the deprecated initMouseEvent replaced by new MouseEvent() and the code generally improved:
const saveTemplateAsFile = (filename, dataObjToWrite) => {
    const blob = new Blob([JSON.stringify(dataObjToWrite)], { type: "text/json" });
    const link = document.createElement("a");

    link.download = filename;
    link.href = window.URL.createObjectURL(blob);
    link.dataset.downloadurl = ["text/json", link.download, link.href].join(":");

    const evt = new MouseEvent("click", {
        view: window,
        bubbles: true,
        cancelable: true,
    });

    link.dispatchEvent(evt);
    link.remove()
};

If you want to pass an object in:
saveTemplateAsFile("filename.json", myDataObj);

A: Simple, clean solution for those who only target modern browsers:
function downloadTextFile(text, name) {
  const a = document.createElement('a');
  const type = name.split(".").pop();
  a.href = URL.createObjectURL( new Blob([text], { type:`text/${type === "txt" ? "plain" : type}` }) );
  a.download = name;
  a.click();
}

downloadTextFile(JSON.stringify(myObj), 'myObj.json');

A: The following worked for me:
/* function to save JSON to file from browser
* adapted from http://bgrins.github.io/devtools-snippets/#console-save
* @param {Object} data -- json object to save
* @param {String} file -- file name to save to
*/
function saveJSON(data, filename){

    if(!data) {
        console.error('No data')
        return;
    }

    if(!filename) filename = 'console.json'

    if(typeof data === "object"){
        data = JSON.stringify(data, undefined, 4)
    }

    var blob = new Blob([data], {type: 'text/json'}),
        e    = document.createEvent('MouseEvents'),
        a    = document.createElement('a')

    a.download = filename
    a.href = window.URL.createObjectURL(blob)
    a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
    a.dispatchEvent(e)
}

and then to call it like so
saveJSON(myJsonObject, "saved_data.json");

A: Try to set another MIME-type:
exportData = 'data:application/octet-stream;charset=utf-8,';
But there are can be problems with file name in save dialog.

A: I recently had to create a button that would download a json file of all values of a large form. I needed this to work with IE/Edge/Chrome. This is what I did:
function download(text, name, type)
    {
        var file = new Blob([text], {type: type});
        var isIE = /*@cc_on!@*/false || !!document.documentMode;
        if (isIE)
        {
            window.navigator.msSaveOrOpenBlob(file, name);
        }
        else
        {
            var a = document.createElement('a');
            a.href = URL.createObjectURL(file);
            a.download = name;
            a.click();
        }
     }

download(jsonData, 'Form_Data_.json','application/json');

There was one issue with filename and extension in edge but at the time of writing this seemed to be a bug with Edge that is due to be fixed.
Hope this helps someone

A:
const exportToJson = (data: {}) =>{
const link = document.createElement("a");
link.href =
data:text/json;charset=utf8,${encodeURIComponent(JSON.stringify(data))}; link.download = 'example.json';    link.click();  }

Make sure to clean up the the created link after if you don't want a random element that does nothing.


text:
Q: How to cache JAX-WS stub/port in Java? The use case is that the application (running on JBoss 5) must operate on very limited bandwidth. Currently every time we go to make a webservice call we request the wsdl and recreate the stub using JAX-WS. Each time the stub is created the wsdl and schema is redownloaded. Idealy the wsdl would never be downloaded since we already have a copy of the schema, but even caching would work. Bonus points if the cache is Serializable!
Is it possible to cache a JAX-WS stub/port?

A: Best answer found so far:
Tell the service to look at a local wsdl:
JAX-WS client : what's the correct path to access the local WSDL?
Change the endpoint on the fly:
JAX-WS Loading WSDL from jar

I don't see a way to cache, but using a local copy can be done as specified on this page on metro: Developing client application with locally packaged WSDL
(found on SO question : How to cache a WSDL with Java-WS)

A: I think we can cache stub using org.apache.commons.pool2.impl.GenericObject lirbrary.
Please see the below link for the same.
https://github.com/vikashnitk50/fasypay-webservice-client/tree/master/fasypay-webservice-client/src/main/java/com/fastpay/webservice/client

redpajama_set_name: RedPajamaStackExchange


text:
Q: Load html file in typescript I have an html file in the same directory of the typescript file. IO have to load it and return it from the function.
public ...(... ) :  angular.IHttpPromise<string> {
   ...
   return $http({
            method: 'GET',
            url: 'help.html'
   });

Error: NetworkError: 404 Not Found - http://localhost:3000/help.html

A: The directory does not matter. Why?

*

*The typescript file is actually javascript and this runs on the browser ie. the client's machine and not your server. The client has no clue what the structure is on the server so placing these files in the same folder is a convenience for the developer and nothing more.

*The HTM / HTML file is hosted on your server and the server knows nothing about the client.
To fix it - You have to specify the path to your html file in the $http command so the server knows where to pick it up from. The path always starts at the root of the folder that is hosted by IIS (or appache or whatever). So if you are hosting it in a folder named someFolder in the root of the web site folder then your url that you would use in the typescript file would be /someFolder/help.html.
If you want to manually test that the url is correct you should be able to put it directly in the URL of your web browser (along with the host) and it should return the content.


text:
Q: Flutter not re-building widget after invoking SetState() In the processForm() function the widget should re-build and show the loading progress indicator but isn't working right, what am I doing wrong?
The value for isLoading does get updated but the widget doesn't update
This is the function:
processForm() {
      if (formKey.currentState.validate()) {
        setState(() {
          isLoading = true;
        });
        auth.signUpWithEmailAndPassword(
            uiEmailController.text, uiPasswordController.text);
      }
    }

This is the entire code for the Widget:
class SignUp extends StatefulWidget {
  @override
  _SignUpState createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {
  @override
  Widget build(BuildContext context) {
    bool isLoading = false;
    AuthMethods auth = AuthMethods();
    final formKey = GlobalKey<FormState>();
    TextEditingController uiUsernameController = TextEditingController();
    TextEditingController uiEmailController = TextEditingController();
    TextEditingController uiPasswordController = TextEditingController();
    processForm() {
      if (formKey.currentState.validate()) {
        setState(() {
          isLoading = true;
        });
        auth.signUpWithEmailAndPassword(
            uiEmailController.text, uiPasswordController.text);
      }
    }

    return Scaffold(
      appBar: myAppBar(),
      body: isLoading
          ? Center(
              child: CircularProgressIndicator(),
            )
          : Center(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(25.0),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        "Sign Up",
                        style: TextStyle(color: Colors.white, fontSize: 20),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Form(
                        key: formKey,
                        child: Column(
                          children: [
                            TextFormField(
                              validator: (username) {
                                return username.length > 5
                                    ? null
                                    : "Invalid Username";
                              },
                              controller: uiUsernameController,
                              style: myInputTextStyle(),
                              decoration: myTextFieldDecoration("Username"),
                            ),
                            TextFormField(
                              validator: (mail) {
                                return RegExp(
                                            r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
                                        .hasMatch(mail)
                                    ? null
                                    : "Not a valid Email Address";
                              },
                              controller: uiEmailController,
                              style: myInputTextStyle(),
                              decoration: myTextFieldDecoration("Email"),
                            ),
                            TextFormField(
                              validator: (password) {
                                return password.length >= 6
                                    ? null
                                    : "password too short";
                              },
                              controller: uiPasswordController,
                              style: myInputTextStyle(),
                              obscureText: true,
                              decoration: myTextFieldDecoration("Password"),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              GestureDetector(
                                onTap: () {
                                  Navigator.pushReplacementNamed(
                                      context, '/SignIn');
                                },
                                child: Text(
                                  "Already have an account?",
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                              SizedBox(
                                height: 5,
                              ),
                              FlatButton(
                                  shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(20)),
                                  color: Colors.white,
                                  onPressed: () {
                                    processForm();
                                  },
                                  textColor: Colors.indigoAccent,
                                  child: Text("Sign up")),
                              FlatButton(
                                  shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(20)),
                                  color: Colors.white,
                                  onPressed: () {},
                                  textColor: Colors.indigoAccent,
                                  child: Text("Sign up with Google")),
                            ],
                          ),
                        ],`enter code here`
                      ),
                    ],
                  ),
                ),
              ),
            ),
    );
  }

A: The problem is that you've placed your variables inside build.
Don't do that and instead place as property of State:
class _SignUpState extends State<SignUp> {
  bool isLoading = false;
  AuthMethods auth = AuthMethods();
  final formKey = GlobalKey<FormState>();
  TextEditingController uiUsernameController = TextEditingController();
  TextEditingController uiEmailController = TextEditingController();
  TextEditingController uiPasswordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: myAppBar(),
      body: isLoading
          ? Center(
              child: CircularProgressIndicator(),
            )
          : Center(...),
    );
  }
}


text:
Q: Alamofire send array with multiform data Code:
 var arrType = ["first", "second","thrird"]

   upload(
            .POST,
            urlString,
            multipartFormData: { multipartFormData in

            multipartFormData.appendBodyPart(data: strDescription.dataUsingEncoding(NSUTF8StringEncoding)!, name:"business_description")
                for (var i = 0; i < arrType.count; i++){

                      multipartFormData.appendBodyPart(data: arrType[i].dataUsingEncoding(NSUTF8StringEncoding)!, name:"vehicle_types[]")
                }
            },
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .Success(let upload, _, _):
                    upload.responseJSON { response in

                        print("A JSON Result :\(response.result.value)")
                        if let JSON = response.result.value
                        {
                            print("A JSON Result :\(JSON)")
                        }
                        else
                        {
                            print("A JSON parsing error occurred, here are the details: %@" ,response.result.error)
                            delegate.API_CALLBACK_Error(0,errorMessage:c_Server_error)
                        }
                    }
                case .Failure( _):
                    break
                }
        })

I try to send an array through multiform data.
when try to execute this code getting failure response from server
is it correct way of sending array with multiform data?
any help will be appreicated.thanks in advance


text:
Q: How to expose your local server for webhooks during development without third part services? How can I expose my localhost server for webhooks during development without third part services like ngrok?
I was watching this video on how to create a simple telegram bot and they have used ngrok to expose their localhost server to the internet for webhooks. I am trying to understand what problem ngrok and other services like this do.
How hard is it to expose your localhost server to the internet without third party services like ngrok and what are the disadvantages of doing that yourself?

A: Use NAT to expose a local server to the public internet. Your router should have a UI where you can map an external WAN port to a port on an internal machine.
It's straight forward to configure. The main disadvantage is that (unless you have purchased a static IP from your ISP) your WAN IP address will change occassionally. Meaning, you can't simply share/publish the public IP for your local dev server as it will change.


text:
Q: Verifiy iOS Receipt with Node.js After struggling a few days trying to get something to work and getting no where, I was wondering if someone has gotten iOS Receipt Validation working on Node.js. I have tried the node module iap_verifier found here but I could not get it to work properly for me. the only response I received back form Apples servers is 21002, data was malformed.
One thing that has worked for me was a client side validation request to apples servers that I got directly from the tutorials provided by Apple here, with the code shown below.
// The transaction looks ok, so start the verify process.

// Encode the receiptData for the itms receipt verification POST request.
NSString *jsonObjectString = [self encodeBase64:(uint8_t *)transaction.transactionReceipt.bytes
                                         length:transaction.transactionReceipt.length];

// Create the POST request payload.
NSString *payload = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\", \"password\" : \"%@\"}",
                     jsonObjectString, ITC_CONTENT_PROVIDER_SHARED_SECRET];

NSData *payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];

// Use ITMS_SANDBOX_VERIFY_RECEIPT_URL while testing against the sandbox.
NSString *serverURL = ITMS_SANDBOX_VERIFY_RECEIPT_URL;

// Create the POST request to the server.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverURL]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:payloadData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];

I have a bunch of different code I have been using to send a wide array of things to my node server. and all of my different attempts have failed. I have even tried just funneling the "payloadData" I constructed in the client side validation example above to my server and sending that to Apples servers with the following code:
function verifyReceipt(receiptData, responder)
{

var options = {
    host: 'sandbox.itunes.apple.com',
    port: 443,
    path: '/verifyReceipt',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(receiptData)
    }
};

var req = https.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(receiptData);
req.end();
}

Where the function is passed the payloadData. The response received from Apple is always 21002. I'm still basically a node novice,so I can't figure out what exactly is going wrong. I think there might be some data corruption happening when I am sending the data from ObjC to my Node server, so perhaps I am not transmitting right.
If anyone can point me in the right direction, or provide some example of how they got receipt validation to work in node for them, it would be a great help. It would be great if anyone has had any experience with the iap_verifier module, and exactly what data it requires. I'll provide any code example I need to, as I have been fighting this process for a few days now.
Thanks!

A: For anyone using the npm library "request", here's how to  avoid that bothersome 21002 error.
formFields = {
  'receipt-data': receiptData_64
  'password': yourAppleSecret
}

verifyURL = 'https://buy.itunes.apple.com/verifyReceipt' // or 'https://sandbox.itunes.apple.com/verifyReceipt'

req = request.post({url: verifyURL, json: formFields}, function(err, res, body) {
    console.log('Response:', body);
})

A: This is my working solution for auto-renewable subscriptions, using the npm request-promise library.
Without JSON stringify-ing the body form, I was receiving 21002 error (The data in the receipt-data property was malformed or missing)
const rp = require('request-promise');

var verifyURL = 'https://sandbox.itunes.apple.com/verifyReceipt';
// use 'https://buy.itunes.apple.com/verifyReceipt' for production

var options = {
    uri: verifyURL,
    method: 'POST',
    headers: {
        'User-Agent': 'Request-Promise',
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    json: true
};

options.form = JSON.stringify({
    'receipt-data': receiptData,
    'password': password
});

rp(options).then(function (resData) {
    devLog.log(resData); // 0
}).catch(function (err) {
    devLog.log(err);
});

A: Do you have composed correctly receiptData? Accordlying with Apple specification it should have the format
{"receipt-data": "your base64 receipt"}

Modifying your code wrapping the base64 receipt string with receipt-data object the validation should works
function (receiptData_base64, production, cb)
{
    var url = production ? 'buy.itunes.apple.com' : 'sandbox.itunes.apple.com'
    var receiptEnvelope = {
        "receipt-data": receiptData_base64
    };
    var receiptEnvelopeStr = JSON.stringify(receiptEnvelope);
    var options = {
        host: url,
        port: 443,
        path: '/verifyReceipt',
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': Buffer.byteLength(receiptEnvelopeStr)
        }
    };

    var req = https.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log("body: " + chunk);
            cb(true, chunk);
        });
        res.on('error', function (error) {
            console.log("error: " + error);
            cb(false, error);
        });
    });
    req.write(receiptEnvelopeStr);
    req.end();
}


text:
Q: Python: Append Dictionary new element Convert PHP code:
$this->plane[$slice_id][$f][] = array('x' => $y, 'y' => $z);
To python:
self.plane = {};
self.plane[slice_id][f][] = {'x' : y, 'y' : z};
Does not work.
1) self.plane[slice_id][f] -> not yet initialized. Only create this element if necessary.
2) [] -> push element to array
3) Python dictionary are not usually multi-dimensional

A: Try like this
self.plane[slice_id][f] = []
self.plane[slice_id][f].append( {'x' : y, 'y' : z} )

The method append() appends a passed obj into the existing list.
self.plane[slice_id][f][] = {'x' : y, 'y' : z}; is not valid syntax for the python
Demo
>>> new_list = []
>>> new_list[] = 'test'
  File "<stdin>", line 1
    new_list[] = 'test'
             ^
SyntaxError: invalid syntax


text:
Q: svn-tag Hudson plugin not working I started using Hudson a week ago. I was able to add various plugins to my build cycle (like ci-game, email-ext and Sonar) but i am unable to get the svn-tag to work.
I am using the latest version of the Hudson war (2.2.0) and the version 1.16 of the Subversion Tagging Plugin.
When a build fails test the plugin tells me that it didn't do anything (since the build failed) but, when the build runs fine the plugin tells me nothing.
Checking http://myserver/hudson/log/all i can see the following stacktrace:
SEVERE: Executor threw an exception
java.lang.NoSuchMethodError:     hudson.model.AbstractBuild.getRootBuild()Lhudson/model/AbstractBuild;
    at hudson.plugins.svn_tag.SvnTagPlugin.perform(SvnTagPlugin.java:79)
    at hudson.plugins.svn_tag.SvnTagPublisher.perform(SvnTagPublisher.java:79)
    at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:36)
    at hudson.model.AbstractBuild$AbstractRunner.perform(AbstractBuild.java:630)
    at     hudson.model.AbstractBuild$AbstractRunner.performAllBuildSteps(AbstractBuild.java:608)
    at     hudson.maven.MavenModuleSetBuild$RunnerImpl.cleanUp(MavenModuleSetBuild.java:835)
    at hudson.model.Run.run(Run.java:1409)
    at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:414)
    at hudson.model.ResourceController.execute(ResourceController.java:88)
    at hudson.model.Executor.run(Executor.java:145)

Does anyone know how to fix this ? Am i missing something ?
Thanks in advance!

A: It looks like there's a difference between hudson CI and jenkins CI. Jenkins provides the method hudson.model.AbstractBuild.getRootBuild() while, according to the java doc, it is not part of hudson.

*

*JavaDoc for AbstractBuild at jenkins

*JavaDoc for AbstractBuild at hudson
The plugin may not be compatible with oracle hudson CI.


text:
Q: Knockout custom binding update function not firing I have a custom knockout binding that animates a toggle switch to an 'on' or 'off' position. My problem is the update function only fires immediately after the init and not when the observable value changes. Any ideas what I'm doing wrong?
ko.bindingHandlers.toggleSwitch = {

    init: function (element, valueAccessor) {
        var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
        var value = valueUnwrapped.value;
        var target = $(element);
        var disabled = valueAccessor().disabled;

        var id = 'ul' + (++ko.bindingHandlers['uniqueId'].currentIndex);
        var html = ['

', '
' + valueAccessor().on + '
', '

', '
' + valueAccessor().off + '
', '

'].join('');

        target.replaceWith(html);

        var mainTarget = $('#' + id);
        if (value()) {
            mainTarget.children('.on-switch').animate({ 'margin-left': '0px' });
            mainTarget.children('.on-off-knob').animate({ 'margin-left': '0px' });
        }
        else {
            mainTarget.children('.on-switch').animate({ 'margin-left': '-28px' });
            mainTarget.children('.on-off-knob').animate({ 'margin-left': '-1px' });
        };

        if (!disabled) {
            mainTarget.on('click', function() {
                //this fires every time the toggle switch is clicked.
                var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
                if (value()) {
                    mainTarget.children('.on-switch').animate({ 'margin-left': '0px' });
                    mainTarget.children('.on-off-knob').animate({ 'margin-left': '0px' });
                    value(false);
                } else {
                    mainTarget.children('.on-switch').animate({ 'margin-left': '-28px' });
                    mainTarget.children('.on-off-knob').animate({ 'margin-left': '-1px' });
                    value(true);
                }

                value.valueHasMutated();
            });
        }
    },
    update: function (element, valueAccessor) {
        var value = valueAccessor();
        var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
        console.log('update called');
    }
};

ko.virtualElements.allowedBindings.toggleSwitch = true;

This is my binding:

A: The update event is not being fired because you're not binding directly to the observable, but to an object containing a property named value set to the observable. How I've accomplished this in the past is to omit the update function on the custom binding and just set a subscription on the observable in the in the init function, like this:
ko.bindingHandlers.toggleSwitch = {

  init: function (element, valueAccessor) {
    var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
    var value = valueUnwrapped.value;

   /// logic omitted for clarity

    value.subscribe(function(newValue) {
        console.log('update called');
    });

    if (!disabled) {
       /// omitted for clarity
    }
  }
};


text:
Q: Identify only non duplicated rows I have a dataset with many duplicated rows, and I would like to isolate only non duplicated values.
my df looks something like this
df <- data.frame("group" = c("A", "A", "A","A","A","B","B","B"),
                    "id" = c("id1", "id2", "id3", "id1", "id2","id1","id2","id1"),
                    "Val" = c(10,10,10,10,10,12,12,12))

What I would like to extract are only the rows that do not have a duplicate. i.e. my final dataset should look like this
final <- data.frame("group" = c("A","B"),
                 "id" = c("id3","id2"),
                 "Val" = c(10,12))

Note I am not interested in finding unique values, but rather non duplicated ones.
I know how to find unique values, for instance df %>% distinct() does the job. it is individuating non-duplicated rows that I am struggling with

A: Here is one option.
library(dplyr)
df %>%
   group_by(group) %>%
   filter(!(duplicated(id)|duplicated(id, fromLast = TRUE)))

Or with dplyr alone
df %>%
     group_by_all %>%
     filter(n() ==1)

Or in the newer version of dplyr (suggested by @Pål Bjartan)
df %>%
  group_by(across(everything())) %>%
  filter(n() ==1)

Or using base R
df[!(duplicated(df[1:2])|duplicated(df[1:2], fromLast = TRUE)),]


text:
Q: Problem with Recyclerview not always loading items Greetings to all the experts.
I have the following problem, I have implemented Billing Subscriptions in Android, the code works well, the problem is that the Recyclerview sometimes loads and many others it doesn't, sometimes it loads first, sometimes you have to enter the atricity a few times, I don't understand why it makes that bug, if you could check the code and guide me I would appreciate it
suscription.java
public class suscripcion extends AppCompatActivity implements PurchasesUpdatedListener {

    private TextView statuspremium, rangopremium;

    private BillingClient billingClient;
    private AcknowledgePurchaseResponseListener acknowledgePurchaseResponseListener;
    private RecyclerView recyclerView_sub;
    private DocumentReference documentReference;
    private FirebaseFirestore mFirestore;
    private FirebaseUser user;
    private FirebaseAuth fAuth;
    private String userID;
    private MySubAdapter adapter;
    private Button cargarpremium;
    private ImageView ayudapremium, txtclose;
    private String status;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_suscripcion);
        this.setFinishOnTouchOutside(false);

        mFirestore = FirebaseFirestore.getInstance();
        fAuth = FirebaseAuth.getInstance();
        user = fAuth.getCurrentUser();
        ayudapremium = findViewById(R.id.ayudapremium);

        ayudapremium.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(suscripcion.this, ofrecepremium.class));
            }
        });

        if (user !=null)
        {
            userID = fAuth.getCurrentUser().getUid();
        }

        documentReference = mFirestore.collection("users").document(userID);
        documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {

                status = value.getString("status");

            }
        });

        setupSubClient();
        iniciador();

        txtclose = findViewById(R.id.txtclosesub);
        txtclose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                documentReference.update("premiumverificar", "no");
                finish();
                startActivity(new Intent(suscripcion.this, MainActivity.class));
            }
        });
    }

    private void iniciador() {

        statuspremium = findViewById(R.id.statuspremium);
        rangopremium = findViewById(R.id.rangopremium);
        recyclerView_sub = findViewById(R.id.recyclerview_sub);
        recyclerView_sub.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView_sub.setLayoutManager(layoutManager);
        recyclerView_sub.addItemDecoration(new DividerItemDecoration(this, layoutManager.getOrientation()));
        cargarpremium = findViewById(R.id.cargarpremium);

        cargarpremium.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                startActivity(getIntent());
            }
        });

    }

    private void loadAllSubPackage() {

        if (billingClient.isReady())
        {
            Log.d("ERROR20", "onSkuDetailsResponse: ");
            SkuDetailsParams params = SkuDetailsParams
                    .newBuilder()
                    .setSkusList(Arrays.asList("vf_sub_unmes", "vf_sub_tresmes"))
                    .setType(BillingClient.SkuType.SUBS)
                    .build();
            billingClient.querySkuDetailsAsync(params, new SkuDetailsResponseListener() {
                @Override
                public void onSkuDetailsResponse(@NonNull BillingResult billingResult, @Nullable List<SkuDetails> list) {

                    if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK)

                    {

                            adapter = new MySubAdapter(suscripcion.this, list, billingClient);
                            recyclerView_sub.setAdapter(adapter);
                            recyclerView_sub.setVisibility(View.VISIBLE);

                        Log.d("ERROR5", "onSkuDetailsResponse: " + billingResult.getResponseCode());

                    }else
                    {
                        Log.d("ERROR6", "onSkuDetailsResponse: " + billingResult.getResponseCode());

                    }
                }
            });
        }else
        {
            loadAllSubPackage();
            Log.d("ERROR7", "loadAllSubPackage: Billing cliente not ready" );

        }

    }

    private void setupSubClient() {
        acknowledgePurchaseResponseListener = new AcknowledgePurchaseResponseListener() {
            @Override
            public void onAcknowledgePurchaseResponse(@NonNull BillingResult billingResult) {
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK)
                {
                    Log.d("ERROR1", "onAcknowledgePurchaseResponse: " +
                            billingResult.getResponseCode());
//                    rangopremium.setVisibility(View.VISIBLE);
//                    tiemposub.setVisibility(View.VISIBLE);
                }else
                {
                    Log.d("ERROR21", "onAcknowledgePurchaseResponse: " +
                            billingResult.getResponseCode());
                }
            }
        };

        billingClient = BillingClientSetup.getInstance(this, this);
        billingClient.startConnection(new BillingClientStateListener() {
            @Override
            public void onBillingServiceDisconnected() {
                setupSubClient();
                Log.d("ERROR2", "onBillingServiceDisconnected: " );

            }

            @Override
            public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK)
                {
                    Log.d("ERROR3", "onBillingSetupFinished: " +
                            billingResult.getResponseCode());

//                    //Query
//                    List<Purchase> purchases = billingClient.queryPurchases(BillingClient.SkuType.SUBS)
//                            .getPurchasesList();

                    billingClient.queryPurchasesAsync(BillingClient.SkuType.SUBS, new PurchasesResponseListener() {
                        @Override
                        public void onQueryPurchasesResponse(@NonNull BillingResult billingResult, @NonNull List<Purchase> list) {

                            if (list.size() > 0)
                            {

                                for (Purchase purchase:list)

                                    handleSubAlreadyPurchase(purchase);

                                Log.d("ERROR16", "onBillingSetupFinished: " +
                                        billingResult.getResponseCode());

                            }else
                            {

                                loadAllSubPackage();
                                documentReference.update("status", "user");
                                statuspremium.setVisibility(View.VISIBLE);

                                Log.d("ERROR17", "onBillingSetupFinished: " +
                                        billingResult.getResponseCode());
//                            rangopremium.setVisibility(View.GONE);
//                            tiemposub.setVisibility(View.GONE);
//                            statuspremium.setVisibility(View.VISIBLE);
//                            recyclerView_sub.setVisibility(View.VISIBLE);

                            }

                        }
                    });

                }
                else
                {
                    Log.d("ERROR4", "onBillingSetupFinished: " +
                            billingResult.getResponseCode());

                }
            }
        });
    }

    private void handleSubAlreadyPurchase(Purchase purchases) {

        if (purchases.getPurchaseState() == Purchase.PurchaseState.PURCHASED)
        {

            documentReference = mFirestore.collection("users").document(userID);
            documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
                @Override
                public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {

                    if (value != null && value.exists()) {
                        status = value.getString("status");
                        rangopremium.setVisibility(View.VISIBLE);
                        rangopremium.setText(status);
                    }
                }
            });

            Log.d("ERROR11", "handleSubAlreadyPurchase: ");
            if (!purchases.isAcknowledged())
            {
                Log.d("ERROR12", "handleSubAlreadyPurchase: ");
                AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
                        .setPurchaseToken(purchases.getPurchaseToken())
                        .build();
                billingClient.acknowledgePurchase(acknowledgePurchaseParams, acknowledgePurchaseResponseListener);
            }else
            {
                Log.d("ERROR13", "handleSubAlreadyPurchase: ");

            }
        }
        if (purchases.getPurchaseState() == Purchase.PurchaseState.UNSPECIFIED_STATE){
            Log.d("ERROR14", "handleSubAlreadyPurchase: ");
        }

    }

    @Override
    public void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List<Purchase> list) {

        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && list !=null)
        {

            SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss", Locale.getDefault());
            String currentDateandTime = formatter.format(new Date());

            documentReference = mFirestore.collection("users").document(userID);
            documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
                @Override
                public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {

                    if (value != null && value.exists()){
                        status = value.getString("status");
                        rangopremium.setVisibility(View.VISIBLE);
                        rangopremium.setText(status);
                    }

                }
            });

            statuspremium.setVisibility(View.GONE);
            recyclerView_sub.setVisibility(View.GONE);
            documentReference.update("status", "PREMIUM");
            documentReference.update("bloqueo", 3);
            documentReference.update("premiumfecha", currentDateandTime);
            Log.d("ERROR8", "onPurchasesUpdated: " + billingResult.getResponseCode());

            for (Purchase purchase:list)

                handleSubAlreadyPurchase(purchase);

        }else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.USER_CANCELED)
        {
            Log.d("ERROR9", "onPurchasesUpdated: " + billingResult.getResponseCode());
            rangopremium.setVisibility(View.GONE);
            statuspremium.setVisibility(View.VISIBLE);
            recyclerView_sub.setVisibility(View.VISIBLE);
            documentReference.update("status", "user");
        }else
        {
            Log.d("ERROR10", "onPurchasesUpdated: " + billingResult.getResponseCode());

        }

    }

    @Override
    public void onBackPressed() {

    }

}

MySubAdapter.java
public class MySubAdapter extends RecyclerView.Adapter<MySubAdapter.MyViewHolder> {

    AppCompatActivity appCompatActivity;
    List<SkuDetails> skuDetailsList;
    BillingClient billingClient;

    public MySubAdapter(AppCompatActivity appCompatActivity, List<SkuDetails> skuDetailsList, BillingClient billingClient) {
        this.appCompatActivity = appCompatActivity;
        this.skuDetailsList = skuDetailsList;
        this.billingClient = billingClient;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(appCompatActivity.getBaseContext())
                .inflate(R.layout.listado_sub, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        holder.txt_sub_name.setText(skuDetailsList.get(position).getTitle());
        holder.txt_precio_sub.setText(skuDetailsList.get(position).getPrice());

        holder.setListener(new IReciclerClickListener() {
            @Override
            public void onClick(View view, int position) {
                BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
                        .setSkuDetails(skuDetailsList.get(position))
                        .build();
                int reponse = billingClient.launchBillingFlow(appCompatActivity, billingFlowParams)
                        .getResponseCode();

                switch(reponse)
            {
                case BillingClient.BillingResponseCode.BILLING_UNAVAILABLE:
                    Log.d("ERROR11", "BILLING_UNAVAILABLE");
                    break;
                case BillingClient.BillingResponseCode.DEVELOPER_ERROR:
                    Log.d("ERROR12", "DEVELOPER_ERROR");

                    break;
                case BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED:
                    Log.d("ERROR13", "FEATURE_NOT_SUPPORTED");

                    break;
                case BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED:
                    Log.d("ERROR14", "ITEM_ALREADY_OWNED");

                    break;
                case BillingClient.BillingResponseCode.SERVICE_DISCONNECTED:
                    Log.d("ERROR15", "SERVICE_DISCONNECTED");

                    break;
                case BillingClient.BillingResponseCode.SERVICE_TIMEOUT:
                    Log.d("ERROR16", "SERVICE_TIMEOUT");

                    break;
                case BillingClient.BillingResponseCode.ITEM_UNAVAILABLE:
                    Log.d("ERROR17", "ITEM_UNAVAILABLE");

                    break;
                default:
                    break;
            }
            }
        });

    }

    @Override
    public int getItemCount() {
        return skuDetailsList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        TextView txt_sub_name, txt_precio_sub;
        IReciclerClickListener listener;

        public void setListener(IReciclerClickListener listener) {
            this.listener = listener;
        }

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            txt_sub_name = itemView.findViewById(R.id.txt_sub_name);
            txt_precio_sub = itemView.findViewById(R.id.txt_precio_sub);

            itemView.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {

            listener.onClick(v, getBindingAdapterPosition());

        }
    }
}

activity_suscription
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/Snackbar_apoyo"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/fondocurva"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center">

    <ImageView
        android:contentDescription="@string/app_name"
        android:id="@+id/txtclosesub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_close_black"
        android:layout_gravity="start"
        android:layout_marginStart="20dp"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:gravity="center"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/statuspremium"
            style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:gravity="center"
            android:shadowColor="@color/negro"
            android:shadowDx="2"
            android:shadowDy="5"
            android:visibility="gone"
            android:shadowRadius="10"
            android:text="@string/no_premium"
            android:textColor="@color/colorAccent"
            android:textSize="25sp"
            android:textStyle="bold|italic" />

        <com.hanks.htextview.rainbow.RainbowTextView
            android:id="@+id/rangopremium"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:visibility="gone"
            android:textSize="25sp"
            android:textStyle="bold"
            app:colorSpace="150dp"
            app:colorSpeed="10dp"/>

        <ImageView
            android:contentDescription="@string/app_name"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:src="@drawable/vinoayuda"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/haste_premium"
            android:textSize="18sp"
            android:textColor="@color/colorAccent"
            android:layout_gravity="center"
            android:gravity="center"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:layout_marginBottom="20dp"
            android:textStyle="bold"
            android:fontFamily="sans-serif-smallcaps"
            android:shadowColor="@color/negro"
            android:shadowRadius="10"
            android:shadowDx="2"
            android:shadowDy="5"/>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:gravity="center"
            android:layout_gravity="center"
            android:orientation="horizontal">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/que_ofrece_el_premium"
                android:textSize="16sp"
                android:textColor="@color/blanco"
                android:layout_gravity="center"
                android:gravity="center"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:textStyle="bold"
                android:fontFamily="sans-serif-smallcaps" />

            <ImageView
                android:id="@+id/ayudapremium"
                android:background="@drawable/curvas"
                android:contentDescription="@string/app_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginEnd="10dp"
                android:src="@drawable/ic_baseline_help"/>

        </LinearLayout>

        <Button
            android:id="@+id/cargarpremium"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="@string/cargar_botones"
            android:padding="10dp"
            android:textColor="@color/colorPrimary"
            android:background="@drawable/btn_desing"/>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerview_sub"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:layout_marginBottom="20dp">

        </androidx.recyclerview.widget.RecyclerView>

    </LinearLayout>

</LinearLayout>

PD: I have placed a button to reload the Activity, and only then sometimes it loads and sometimes it doesn't, just to half solve that bug, but the ideal is that the recyclerview loads me the first time


text:
Q: Find a particular integral for $y''+y'+y = 2+x+\cos(x)$ If it were merely $y''+y'+y = \cos(x)$, then I know that I would try $a\cos(kx) + b\sin(kx)$, but with the added $2 + x$, I am not entirely sure.

A: You simply have to add $ax+b$ for the part $2+x$ of the right side. So a particular solution would be of the form $ax+b+c\cos(x)+d\sin(x)$.

A: You can also treat this kind of equations ($y"+y'+y=f(x)+g(x)$) the following way:
Find the solution $y_1$ for $y"+y'+y=f(x)$ and the solution $y_2$ for $y"+y'+y=g(x)$.
Then your solution is $y=y_1+y_2$
Beware! This does not mean this is always the best way to solve such an equation... But since you are dealing with LINEAR equations, you can use that fact!

A: You can solve for every term independently.
For $2$ you obviously have $2''+2'+2=2$.
For $x$, try $x$ itself, which gives $x''+x'+x=1+x\ne x$. But the fix is easy: $x-1$ yields $(x-1)''+(x-1)'+(x-1)=x$. (More generally, for a given polynomial of degree $d$, try an arbitrary polynomial of degree $d$.)
For the cosine, it is convenient to use the complex representation and consider the real part of $e^{ix}$.
We have $(e^{ix})''+(e^{ix})'+e^{ix}=(i^2+i+1)e^{ix}=ie^{ix}$ so that the solution is the real part of $-ie^{ix}$ or $\sin x$.
Hence
$$x+1+\sin x.$$

A: $$y''+y'+y = 2+x+\cos(x)$$
The characteristic polynomial is
$$r^2+r+1=0 \implies  r=\frac {-1\pm i\sqrt 3}2$$
$$\implies y=e^{-1/2}(c_1 \cos(\sqrt 3 x/2)+c_2 \sin(\sqrt 3x/2))$$
So  for $\cos(x)$ try $a\cos(x)+b\sin(x)$ it gives $\sin(x)$
And $ax+b$ for $x+1$
$$a+ax+b=x+2 \implies (a,b)=(1,1)$$
Therefore
 $$\implies y=e^{-1/2}(c_1 \cos( \frac {\sqrt 3}2x)+c_2 \sin( \frac {\sqrt 3}2x)+x+1+\sin(x)$$


text:
Q: Error: Assembly file '' does not exist! Load failed. - when trying to start .Net Micro 4.2 Project I get the error "Error: Assembly file '' does not exist! Load failed." when I try to start a .Net Micro 4.2 Framework Project (in the emulator) in Visual Studio 2010.
I cannot set debug points to my main procedure (it crashes before it reaches it). And I have another micro project in the same solution, that starts without any problems.
Any idea where this meaningful error message comes from?

A: Ok, I found it by myself:
There have been unsupported/wrong version (.Net) assemblies in the references of this project. I could use the "Unused References..." check and remove the unnecessary assemblies and now it works.


text:
Q: Access `sun.security.x509` in JDK 11 without modules? (tl,dr at the end)
We have a small method that generates self-signed SSL certificate and it obviously depends on sun.security.x509. Currently we are still building it using JDK8 because of that, even though the rest of the codebase (it's only small, single library) is build using JDK11 and run with JVM11.
Unfortunately there aren't replacement in the main JDK, as per (and CertificateFactory has little to nothing with generating certificates, contrary to what it's javadoc states…):

*

*https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8165481

*https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8058778
One option would be to use BouncyCastle, but that's additional 4MB that we really don't need, especially for such small task so I was pondering ways to access it while
From what I saw, the package and required classes are still package and relevant classes are still there (see sun.security.x509 on github but when building it (using maven) I get error:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project: Compilation failure: Compilation failure:
[ERROR] OldSelfSignedCertificateGenerator.java:[20,25] package sun.security.x509 does not exist
[ERROR] OldSelfSignedCertificateGenerator.java:[71,45] cannot find symbol
[ERROR]   symbol:   class X509CertInfo
[ERROR]   location: class OldSelfSignedCertificateGenerator

I was searching a bit and adding:
<arg>--add-exports</arg><arg>java.base/sun.security.x509=ALL-UNNAMED</arg>

to maven-compiler-plugin and it somewhat worked - I only get WARNING not regarding sun.security.x509 package:
[WARNING] OldSelfSignedCertificateGenerator.java:[20,25] sun.security.x509.AlgorithmId is internal proprietary API and may be removed in a future release

BUT! Now it seems I entered (unwillingly!) module system and it complains about access to other, basic Java classes (and one more our dependency):
[ERROR] CertificateUtil.java:[35,17] package java.util.logging is not visible
  (package java.util.logging is declared in module java.logging, but module java.base does not read it)

I tried adding java.logging module in the same manner to exports but without much success. It also seems that I would have to convert both this library and it's dependency to module system, which is not really desired.
The question is somewhat related to How to generate a self-signed certificate using only JDK supported classes?

tl,dr;
is there a way to compile library using sun.security.x509 package under JDK 11 without module system? Some simple switch?

A: To include sun.security.[somePackage] classes in gradle you may add:
tasks.withType(AbstractCompile) {
    options.compilerArgs += ["--add-exports", "java.base/sun.security.util=ALL-UNNAMED"]
    options.compilerArgs += ["--add-exports", "java.base/sun.security.pkcs=ALL-UNNAMED"]
}

A: It turns out that presumably it has to do with the fact that builds produced by newer JDK (9+) Versions won't be executable under JDK8:
<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>9</source>
        <target>9</target>
        <release combine.self="override"></release>
        <compilerArgs>
            <arg>--add-exports</arg><arg>java.base/sun.security.x509=ALL-UNNAMED</arg>
        </compilerArgs>
    </configuration>
</plugin>


text:
Q: Python packet sniffer problems running I created a python code that is meant to be a basic packet sniffer.  The code compiles however when it runs it gives no errors but there is no output either.   My main question is what went wrong with the code.  Open to suggestions.  I have used IDLE and coderunner on OS X to attempt to get a running program.
Here is what I have so far thanks.
import socket
import struct
import textwrap

TAB_1 = '\t - '
TAB_2 = '\t\t - '
TAB_3 = '\t\t\t - '
TAB_4 = '\t\t\t\t - '

DATA_TAB_1 = '\t   '
DATA_TAB_2 = '\t\t   '
DATA_TAB_3 = '\t\t\t   '
DATA_TAB_4 = '\t\t\t\t   '

def main():
    pcap = Pcap('capture.pcap')
    conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))

    while True:
        raw_data, addr = conn.recvfrom(65535)
        pcap.write(raw_data)
        eth = Ethernet(raw_data)

        print('\nEthernet Frame:')
        print(TAB_1 + 'Destination: {}, Source: {}, Protocol: {}'.format(eth.dest_mac, eth.src_mac, eth.proto))

        # IPv4
        if eth.proto == 8:
            ipv4 = IPv4(eth.data)
            print(TAB_1 + 'IPv4 Packet:')
            print(TAB_2 + 'Version: {}, Header Length: {}, TTL: {},'.format(ipv4.version, ipv4.header_length, ipv4.ttl))
            print(TAB_2 + 'Protocol: {}, Source: {}, Target: {}'.format(ipv4.proto, ipv4.src, ipv4.target))

            # ICMP
            if ipv4.proto == 1:
                icmp = ICMP(ipv4.data)
                print(TAB_1 + 'ICMP Packet:')
                print(TAB_2 + 'Type: {}, Code: {}, Checksum: {},'.format(icmp.type, icmp.code, icmp.checksum))
                print(TAB_2 + 'ICMP Data:')
                print(format_multi_line(DATA_TAB_3, icmp.data))

            # TCP
            elif ipv4.proto == 6:
                tcp = TCP(ipv4.data)
                print(TAB_1 + 'TCP Segment:')
                print(TAB_2 + 'Source Port: {}, Destination Port: {}'.format(tcp.src_port, tcp.dest_port))
                print(TAB_2 + 'Sequence: {}, Acknowledgment: {}'.format(tcp.sequence, tcp.acknowledgment))
                print(TAB_2 + 'Flags:')
                print(TAB_3 + 'URG: {}, ACK: {}, PSH: {}'.format(tcp.flag_urg, tcp.flag_ack, tcp.flag_psh))
                print(TAB_3 + 'RST: {}, SYN: {}, FIN:{}'.format(tcp.flag_rst, tcp.flag_syn, tcp.flag_fin))

                if len(tcp.data) > 0:

                    # HTTP
                    if tcp.src_port == 80 or tcp.dest_port == 80:
                        print(TAB_2 + 'HTTP Data:')
                        try:
                            http = HTTP(tcp.data)
                            http_info = str(http.data).split('\n')
                            for line in http_info:
                                print(DATA_TAB_3 + str(line))
                        except:
                            print(format_multi_line(DATA_TAB_3, tcp.data))
                    else:
                        print(TAB_2 + 'TCP Data:')
                        print(format_multi_line(DATA_TAB_3, tcp.data))

            # UDP
            elif ipv4.proto == 17:
                udp = UDP(ipv4.data)
                print(TAB_1 + 'UDP Segment:')
                print(TAB_2 + 'Source Port: {}, Destination Port: {}, Length: {}'.format(udp.src_port, udp.dest_port, udp.size))

            # Other IPv4
            else:
                print(TAB_1 + 'Other IPv4 Data:')
                print(format_multi_line(DATA_TAB_2, ipv4.data))

        else:
            print('Ethernet Data:')
            print(format_multi_line(DATA_TAB_1, eth.data))

# Returns MAC as string from bytes (ie AA:BB:CC:DD:EE:FF)
def get_mac_addr(mac_raw):
    byte_str = map('{:02x}'.format, mac_raw)
    mac_addr = ':'.join(byte_str).upper()
    return mac_addr

def ipv4_packet(self, raw_data):
        version_header_length = raw_data[0]
        self.version = version_header_length >> 4
        self.header_length = (version_header_length & 15) * 4
        self.ttl, self.proto, src, target = struct.unpack('! 8x B B 2x 4s 4s', raw_data[:20])
        self.src = self.ipv4(src)
        self.target = self.ipv4(target)
        self.data = raw_data[self.header_length:]

# Returns properly formatted IPv4 address
def ipv4(self, addr):
    return '.'.join(map(str, addr))

def icmp_packet(self, raw_data):
        self.type, self.code, self.checksum = struct.unpack('! B B H', raw_data[:4])
        self.data = raw_data[4:]

def tcp_segment(self, raw_data):
        (self.src_port, self.dest_port, self.sequence, self.acknowledgment, offset_reserved_flags) = struct.unpack(
            '! H H L L H', raw_data[:14])
        offset = (offset_reserved_flags >> 12) * 4
        self.flag_urg = (offset_reserved_flags & 32) >> 5
        self.flag_ack = (offset_reserved_flags & 16) >> 4
        self.flag_psh = (offset_reserved_flags & 8) >> 3
        self.flag_rst = (offset_reserved_flags & 4) >> 2
        self.flag_syn = (offset_reserved_flags & 2) >> 1
        self.flag_fin = offset_reserved_flags & 1
        self.data = raw_data[offset:]

def udp_segment(self, raw_data):
        self.src_port, self.dest_port, self.size = struct.unpack('! H H 2x H', raw_data[:8])
        self.data = raw_data[8:]

# Formats multi-line data
def format_multi_line(prefix, string, size=80):
    size -= len(prefix)
    if isinstance(string, bytes):
        string = ''.join(r'\x{:02x}'.format(byte) for byte in string)
        if size % 2:
            size -= 1
    return '\n'.join([prefix + line for line in textwrap.wrap(string, size)])

curiosity... thenewboston

A:
I have used IDLE and coderunner on OS X to attempt to get a running program.

...

conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))

That's not going to work on OS X; OS X doesn't have AF_PACKET as an address family.  I'm surprised your program didn't fail with an exception.
If you're going to capture packet traffic, you should use pcap; you're already using it to write the capture file, you should use it to capture packets.  It will use the OS's mechanism (BPF, on OS X, *BSD, AIX, and Solaris 11; AF_PACKET sockets on Linux; etc.) to capture packets.


text:
Q: problem in sleep mode of xbee series 2 I am having some trouble dealing with xbee s2 sleep mode. Hope you all can give me some help.
The following is my setup:
The network composes of one coordinator and several end devices, all in transparent mode The coordinator is connected to X-CTU and a computer and receives all the messages.
End devices are connected to another MCU(MSP430), MCU wakes up xbee periodically(8 seconds, 16 seconds, 48 seconds etc), writes a short message (11 bytes) to xbee through UART, then immediately asserts sleep_rq pin of xbee.
Here is the problem:
if I set the wakeup interval at 8 seconds, then all messages from the same end device will come in two messages batch at roughly 16 seconds interval instead of one message every 8 seconds.
If I set the wakeup interval at 48 seconds, then again, all message still tend come in two messages batch roughly every 96 seconds, plus the last two bytes of the second message constantly get lost.
The SN, SP on both coordinator and end devices are set properly. The RO is at default value 3.
If I don't assert sleep_rq pin of xbee and keep xbee awake all the time, then no matter what the interval between two messages is, all the messages come in one by one at defined interval.
I believe this has something to do with packetization but I could figure out the exact problem.
Edit: I believe at certain conditions, when sleep_rq is asserted, message up to certain length will be retained in the transmit buffer of xbee until xbee being waken up next time. I am wondering if there is any way to force xbee to send out everything before entering into sleep. One way of doing this is to write enough dummy byte to fill up the entire transmission buffer(84 byte in transparent mode without encryption). But this is really a waste of limited throughput of xbee network. So I hope someone can come up with something better.
This is driving me crazy. Some one please direct me to some relevant literature.
Thanks in advance,
ZL

A: I had the same problem, it was caused by not waiting long enough after sending the message before re-asserting the sleep_rq pin. (@Dzarda got it). Experiment with different delays until it works.
Edit: I know you have already set up SN and SP properly, but I'll leave this part of the answer in for others:
The other thing to know is that you have to set SN and SP in the always-on router so that it doesn't timeout and forget the end devices. If it does, the connection can take up to 6 seconds to renegotiate when the end device came out of sleep. See http://www.digi.com/wiki/developer/index.php/XBee_Sleeping_Problems


text:
Q: The best database table layout/design for a custom ticket system I'm developing a custom trouble ticket system for network management and trying to find the best database table layout for following scenario:
There are tables representing PON, T1 and T3 lines. Each line may have one or more trouble tickets, but every trouble ticket has some unique fields depend on what type of line this tiket belongs.
Here is my approach:
pon:
  pon_id, pk
  ....
  #here other unique pon table columns

t1:
  t1_id, pk
  ....
  #here other unique t1 table columns

t3:
  t3_id, pk
  ....
  #here other unique t3 table columns

ticket:
  ticket_id, pk
  type, string # t1, t3, pon
  type_id, int # id of pon, t1 or t3
  ....
  #here other columns, which are common for all ticket types

ticket_pon_type:
  ticket_id, pk, fk
  ....
  #here unique pon ticket columns

ticket_t1_type:
  ticket_id, pk, fk
  ....
  #here unique t1 ticket columns

ticket_t3_type:
  ticket_id, pk, fk
  ....
  #here unique t3 ticket columns

I'm building my application using Symfony 1.4 PHP framework with Doctrine ORM.
Any other ideas? Thank you for any help.

A: pon, t1 and t3 should be consolidated into a single table.  Add a line column to the table so that you can tell whether each record is a pon, t1 or t3.
I think you will find that this will also allow you to consolidate your ticket_type tables.


text:
Q: Proving a constructed approximating sequence in a Banach space converges Suppose that $(V,\|\cdot\|)$ is a Banach space. Let $S_n$ be a sequence of closed sets such that $\bigcup_{n\in\mathbb{N}} S_n = V$ and $S_n \subseteq S_m$ for $n\leq m$.
Let $(x_n)_{n\in\mathbb{N}}$ be a converging sequence in $V$ and define a new sequence $(\hat{x}_n)_{n\in\mathbb{N}}$ where each $\hat{x}_n\in S_n$ such that $\|x_n - \hat{x}_n\| = \min_{x\in S_n}\|x_n-x\|$.
Does it follow that $\| x_n - \hat{x}_n\|\rightarrow 0$?

A: I suppose you meant that $\hat {x_n} \in S_n$ and  $\|x_n-\hat {x_n}\|=\inf_{y \in S_n} \|x_n-y\|$. Let $x_n \to x$. Then $x \in S_k$ for some $k$. For $n   \geq k$ we have $x \in S_n$ so  $\|x_n-\hat {x_n}\|\leq \|x_n-x\| \to 0$.


text:
Q: Nagios client tcp connection to Nagios Server using NSCA, how to make this connection stay up forever I have setup a nagios distributed monitoring system environment and i am able to send passive checks to Nagios server using send_nsca. When i look at the handshake between Nagios Client and Nagios Server, i see that Nagios Client is establishing a tcp connection to Nagios server whenever it has something to send and terminating the connection once the client is done sending the information. I want the tcp connection to stay up forever instead of terminating every time after data transfer is done. Could anyone please let me the know the process to make this happen?

A: You cannot do this without modifying the standard NSCA daemon.  Normally, it will time out and that's why the NSCA client reestablishes the connection.
I've implemented send_nsca in both Perl and Ruby, and in both cases cannot make a persistent connection work.
A better solution, though, if you are using Nagios 3.x is to install the livestatus module (part of check_mk).  This allows passive checks to be submitted, but supports a persistent connection and a whole lot more.  We've moved to using this instead for many cases.


text:
Q: How to append JSON array with specific data I am trying to run :
- name: Describe config aggregator
  shell: >
    aws configservice describe-configuration-aggregators --configuration-aggregator-name test-config
  register: config_ouput

below is the data generated.
    {
        "ConfigurationAggregators": [
            {
                "ConfigurationAggregatorName": "test-config",
                "ConfigurationAggregatorArn": "arn:aws:config:us-east-1:4567:config-aggregator/config-aggregator-uw2o9pzf",
                "AccountAggregationSources": [
                    {
                        "AccountIds": [
                            "895677"
                        ],
                        "AllAwsRegions": true
                    }
                ],
                "CreationTime": 1624454176.124,
                "LastUpdatedTime": 1626426755.504
            }
        ]
    }

Now I want to append the accountIds above with any new account say 1234567 which should give me result such as
{
    "ConfigurationAggregators": [
        {
            "ConfigurationAggregatorName": "test-config",
            "ConfigurationAggregatorArn": "arn:aws:config:us-east-1:8778:config-aggregator/test-config-pzf",
            "AccountAggregationSources": [
                {
                    "AccountIds": [
                        "895677,1234567"
                    ],
                    "AllAwsRegions": true
                }
            ],
            "CreationTime": 1624454176.124,
            "LastUpdatedTime": 1626426755.504
        }
    ]
}

I am trying to do is:
- name: Export results to JSON
  set_fact:
    config_ouput_json: "{{ config_ouput + [{"AccountIds": "1234567","AllAwsRegions": true}]}}"

but this doesn't work, please let me know the right syntax.

A: Basically you require bit of JSON manipulation to achieve your task.
Steps :

*

*Store output of first command in some json file. In your case you can keep that as registered variable of ansible.

*Get existing account_ids in some variable.

*Create a list of new accounts as variables in ansible.

*Iterate over new account_ids and add to existing account_ids.

*Update the aws config command.
Sample Code :
- name: initial validation
  hosts: localhost
  connection: local
  vars:
    newAccountIds:
      - "123456"
      - "566544"
      - "555445"

  tasks:
  - name: register json file
    include_vars:
      file: 'abc.json'
      name: bundle

  - name: set value
    set_fact:
      values: "{{ bundle['ConfigurationAggregators'][0]['AccountAggregationSources'][0]['AccountIds'] }}"

  - set_fact:
      values: "{{ (values | default([])) + [item] }}"
    with_items: "{{ newAccountIds }}"

  - debug:
      msg: "{{ values }}"

  - debug:
      msg: '"aws configservice put-configuration-aggregator --configuration-aggregator-name test-config --account-aggregation-sources "[{"AccountIds": {{ values | to_json }},"AwsRegions": ["us-east-1"]}]\""'

Sample Output :
PLAY [initial validation] ********************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************
ok: [localhost]

TASK [register json file] ********************************************************************************************
ok: [localhost]

TASK [set value] *****************************************************************************************************
ok: [localhost]

TASK [set_fact] ******************************************************************************************************
ok: [localhost] => (item=123456)
ok: [localhost] => (item=566544)
ok: [localhost] => (item=555445)

TASK [debug] *********************************************************************************************************
ok: [localhost] => {
    "msg": [
        "895677",
        "123456",
        "566544",
        "555445"
    ]
}

TASK [debug] *********************************************************************************************************
ok: [localhost] => {
"msg": "\"aws configservice put-configuration-aggregator --configuration-aggregator-name test-config --account-aggregation-sources \"[{\"AccountIds\": [\"895677\", \"123456\", \"566544\", \"555445\"],\"AwsRegions\": [\"us-east-1\"]}]\\\"\""}

PLAY RECAP ***********************************************************************************************************
localhost                  : ok=6    changed=0    unreachable=0    failed=0


text:
Q: Launch Third-party IOS app with Unity3D I want for my Unity3D Professionnal application launch a Third-Party IOS App on a Ipad but I didn't found a correct way to do it.
I'm not the developper of the IOS App so I don't have the URL Type to launch it with "Application.OpenURL("awesomeapp://")"
Did someone already do something like this ?
Thanks in advance.


text:
Q: How to use set-header with a variable concatenated with req.hdr() I am using set-header to rename an incoming header from an existing one.  My problem is that in addition to renaming the header using req.hdr(my-old-header-name) I want to concatenate the interpreted value from the req.hdr() function with another static value (Bearer).
http-request set-header Authorization %[req.hdr(my-old-header-name)] if some-condition-applies

I want to be able to add a value "Bearer " in front of the interpreted %[req.hdr(my-old-header-name)] so that it ends up looking like this: Authorization: Bearer my-old-header-value-interpreted-from-req-hdr
Thanks for helping

A: Managed to make it work with replace-header as following:
http-request replace-header Authorization (.*) Bearer\ \1 if some_condition_applies
This basically takes the value of the Authorization header and prefixes it with Bearer.


text:
Q: IntelliJ IDEA not recognizing SQL dialect We use IntelliJ IDEA actively and we have our wrappers for work with DB (PostgreSQL). The thing is that when we use placeholders, SQL is stopped being highlighted.
"select * from " + schema + ".users where id = " + id + ";";
This code is not recognised as SQL, so highlighting doesn't work.

A: I agree with Jesper, you should try using preparedStatements, not only would your Statements get more secure, also the problem which you are currently having should be solved by it.


text:
Q: How to reduce my redundant code, creating generic methods? I have a code to insert and update entities, but the logic are very similar: instance a controller, validate de request, if error, resturns Failed, else execute the operation.

        /// <summary>
        /// Method Add with similar code in Update method
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public PersonResponse Add(PersonInsertRequest item)
        {
            var result = new PersonResponse();

            var controller = new PersonController(classmates);

            result.Messages = controller.ValidateInsert(item);

            if (result.Messages != null && result.Messages.Any())
            {
                result.Status = "failed";
            }
            else
            {
                result = controller.ExecuteInsert(item);
            }

            return result;
        }

        /// <summary>
        /// Method Update with similar code in Add method
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public PersonResponse Update(PersonUpdateRequest item)
        {
            var result = new PersonResponse();

            var controller = new PersonController(classmates);

            result.Messages = controller.ValidateUpdate(item);

            if (result.Messages != null && result.Messages.Any())
            {
                result.Status = "failed";
            }
            else
            {
                result = controller.ExecuteUpdate(item);
            }

            return result;
        }

-
I have tried to use delegates, but I can't use them, because I cannot assign a delegate to controller.ValidateInsert(item);
public class BaseLogic
    {
        public delegate List<Message> Validator(BaseRequest request);

        public delegate BaseResponse Executor(BaseRequest request);

        public BaseResponse Execute(BaseRequest request, Validator funcValidator, Executor funcExecutor)
        {
            var result = new BaseResponse();

            result.Messages = funcValidator(request);

            if (result.Messages != null && result.Messages.Any())
            {
                result.Status = "failed";
            }
            else
            {
                result = funcExecutor(request);
            }

            return result;
        }
    }

I want to reduce Add method and Update method in another more generic.

A: using System;
using System.Collections.Generic;
using System.Linq;

class Test
{
    private object classmates;

public PersonResponse Add(PersonInsertRequest item)
{
    var controller = new PersonController(classmates);
    return ValidateAndExecute(() => controller.ValidateInsert(item),
    () => controller.ExecuteInsert(item));
}

public PersonResponse Update(PersonUpdateRequest item)
{
    var controller = new PersonController(classmates);
    return ValidateAndExecute(() => controller.ValidateUpdate(item),
    () => controller.ExecuteUpdate(item));
}

private PersonResponse ValidateAndExecute(Func<IEnumerable<string>> validator,
Func<PersonResponse> execute)
{
    var result = new PersonResponse();

    result.Messages = validator();

    if (result.Messages != null && result.Messages.Any())
    {
        result.Status = "failed";
    }
    else
    {
        result = execute();
    }

    return result;
}

}

A: With my generic method in my base class, I can refactorize my methods
/// <summary>
        /// Method Add with similar code in Update method
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public PersonResponse Add(PersonInsertRequest item)
        {

            var controller = new PersonController(classmates);

            Validator myValidator = request => controller.ValidateInsert((PersonInsertRequest)request);
            Executor myExecutor = request => controller.ExecuteInsert((PersonInsertRequest)request);

            var result = Execute(item, myValidator, myExecutor);

            return result as PersonResponse;
        }

        /// <summary>
        /// Method Update with similar code in Add method
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public PersonResponse Update(PersonUpdateRequest item)
        {
            var controller = new PersonController(classmates);

            Validator myValidator = request => controller.ValidateUpdate((PersonUpdateRequest)request);
            Executor myExecutor = request => controller.ExecuteUpdate((PersonUpdateRequest)request);

            var result = Execute(item, myValidator, myExecutor);

            return result as PersonResponse;
        }


text:
Q: MV.NET calls much slower when website accessed remotely vs locally I have an asp.net webforms page that makes calls to pick/d3 through mv.net.
I've logged the server side performance by surrounding the mv.net calls with timing code, for example:
logTimeElapsed()
getDataFromPick()  'gets 5 rows of test data
logTimeElapsed()
When I call this page from the hosting iis server, I get quick response times such as:
newAC elapsed:  2.9297 total: 2.9297                Dim Acct As mvAccount = New mvAccount("...")
row 1 elapsed:  20.5078 total: 23.4375              Acct.FileOpen("...").ReadV(strID, 17)
row 2 elapsed:  9.7657  total: 33.2032              same as above
row 3 elapsed:  11.7187 total: 44.9219              same as above
row 4 elapsed:  11.7188 total: 56.6407              same as above
row 5 elapsed:  9.7656  total: 66.4063              same as above
Logout elapsed:  1.9531 total: 68.3594              Acct.Logout()
However, when I call this same page from another location on the network or on the web, I get response times that are roughly 7 times longer:

new acct elapsed: 0   total: 0                      Dim Acct As mvAccount = New mvAccount("...")
row 1 elapsed: 156.25 total: 156.25                 Acct.FileOpen("...").ReadV(strID, 17)
row 2 elapsed: 78.125 total: 234.375                same as above
row 3 elapsed: 78.125 total: 312.5                  same as above
row 4 elapsed: 78.125 total: 390.625                same as above
row 5 elapsed: 78.125 total: 468.75                 same as above
Logout elapsed: 0     total: 468.75                 Acct.Logout()
From the results above it looks like:
When Accessed Locally:
mv.net is taking a couple milliseconds to create and logout of an account and each FileOpen call is fast.
When Access Remotely:
mv.net is taking 0 time to create and logout of an account(reusing a shared account?), but each FileOpen call is slow.
How can I bring the remote performance in line with the local performance?  Are there changes to the mv.net or iis setup to make?
Is there something going on with user permissions that is different when iis is called locally vs remotely?
Any help appreciated

A: I'm thinking your account profile is configured for a fairly rapid termination. So when you're testing locally you hit it a few times and it looks fast. Then you gear up to use a remote connection, during this time the connection to D3 terminates. Then you do the connection and it has to login to D3 again, incurring a performance hit.
My suggestion is to set the account profile to not terminate on logout. So all connections hitting it at that point will use the same persistent session. Your local connection will terminate and then when the remote connection comes in, the login session with D3 will still be active and you won't feel the pain of a new login. If that's Not it, let me know and we'll work it through. :)

A: I encountered the same issue at a previous job earlier this year. There, IIS was on a separate server from the BlueFinity Session and License Managers. Additionally, the Pick system was D3. What we observed was that the machine that hosted the Session and License Managers had the best response times, and any other server experienced response times that were 2x longer. Moving the Session and License Managers to the IIS server brought the increased speed to that server; moving them to another server brought the speed to that server. Strange indeed because all of the requests were going out through the internet, through the WAF and into IIS before being processed.
The BlueFinity team observed the behavior on our test application and attempted to recreate but were unable. The main differences in their tests:
1) We used D3 and they were using jBASE
2) We used mv.NET 4.4 and they were using 4.5
3) We used SSH and they used standard telnet
I'm aware this doesn't really answer your question but I don't have enough reputation yet to leave a comment. Though I am no longer with that company, it is interesting to note that this issue was not unique to their stack and more to do with something likely beneath the surface with BlueFinity. Unfortunately, finding the cause did not seem to be high on their list of priorities.


text:
Q: Server Document Root Path in PHP I have a php code line like below
$files = glob('myFolder/*');

I want to use absolute path to myFolder in above by using server document root, like below
$_SERVER["DOCUMENT_ROOT"]."/myFolder/"

It should be like below
$files = glob('$_SERVER["DOCUMENT_ROOT"]."/myFolder/*"');

But this is not working
How to correct this?
Actually I am trying to do this:
<?php
//Delete All files from folder
// $files = glob('myFolder/*');

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

foreach($files as $file){
if(is_file($file))
unlink($file);
}
?>

Code below is working
$files = glob('myFolder/*');

This below is not working
$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

I want to use absolute path to myFolder

A: $files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");


text:
Q: How to check variable is set and exists from javascript? I am getting below json data:
{
  "ID": [
    "The i d field is required."
  ],
  "terms_condition": [
    "The terms condition field is required."
  ]
}

and stored in variable:
var DataJson = data.responseText;
var Json = JSON.parse(DataJson);

var IdError = Json.ID[0];
var TermsConditionError = Json.terms_condition[0];

Now I am getting this error Uncaught TypeError: Cannot read property '0' of undefined when ID is not exists
I have tried with this example to prevent error handling.
if (typeof Json.ID[0] !== 'undefined') {
    alert('validation message found');
} else {
    alert('validation message not found');
}

but this is not working any idea what i am doing wrong?
Thanks.

A: Try this.
 if (Json !=undefined && typeof Json.ID[0] != undefined ) {
        alert('validation message found');
    } else {
        alert('validation message not found');
    }

TypeError: Cannot read property '0' of undefined

This error occurs when main json object is either empty or undefined. This happens when there is no data in json object.

A: To check whether a variable or a field is defined you can compare it with undefined
if ((Json !== undefined) && (Json.ID !== undefined) && (Json.ID[0] !== undefined)) {
    alert('validation message found');
} else {
    alert('validation message not found');
}

I don't see any issue in your code. See the snippet below.

var Json = JSON.parse('{"ID": ["The i d field is required."], "terms_condition": ["The terms condition field is required."]}');

var IdError = Json.ID[0];
var TermsConditionError = Json.terms_condition[0];

document.writeln(IdError + '
');
document.writeln(TermsConditionError + '
');
document.writeln('==================
');

function isDefined(Json) {
  return (Json !== undefined) && (Json.ID !== undefined) && (Json.ID[0] !== undefined);
}

var inputData = [
  undefined,
  {},
  {ID: ''},
  {ID: ['value']}
];

inputData.forEach(function(inputDaten) {
  document.writeln(JSON.stringify(inputDaten) + ': ' + isDefined(inputDaten) + '
');
});

Probably the issue is with data.responseText


text:
Q: Facing issue of single quotes in fckeditor I want to enter single quotes in database through fckeditor..but My code is not work for me.
"insert into $user
            (id,question,option1,option2,option3,option4,correctAnswer,category,section,chapter)
            VALUES
            ("
            . ",$newstd," .
            "','". htmlspecialchars($_POST['FCKeditor0'],ENT_QUOTES) .
            "','" . htmlspecialchars($_POST['FCKeditor1'],ENT_QUOTES) .
            "','" . htmlspecialchars($_POST['FCKeditor2'],ENT_QUOTES) .
            "','" . htmlspecialchars($_POST['FCKeditor3'],ENT_QUOTES) .
            "','" . htmlspecialchars($_POST['FCKeditor4'],ENT_QUOTES) .
            "','" . htmlspecialchars($_REQUEST['correctans'],ENT_QUOTES) .
            "'," . htmlspecialchars($_REQUEST['MyRadio'],ENT_QUOTES) .
            "'," . htmlspecialchars($_REQUEST['section'],ENT_QUOTES) .
            "'," . htmlspecialchars($_REQUEST['chapter'],ENT_QUOTES) .
            ")";
Thank You ...

A: You can use it like this
insert into $user(id,question,option1,option2,option3,option4,correctAnswer,category,section,chapter)
values
(
"'.$newstd.'",
'".htmlspecialchars([\'$question1\'],ENT_QUOTES)."'
)

A: "insert into $user (id,question,option1,option2,option3,option4,correctAnswer,category,section,chapter) VALUES ("'$newstd'" , "',
    '" . htmlspecialchars(['$question1'],ENT_QUOTES) . "',
    '" . htmlspecialchars(['$question2'],ENT_QUOTES) . "',
    '" . htmlspecialchars(['$question3'],ENT_QUOTES) . "',
    '" . htmlspecialchars(['$question4'],ENT_QUOTES) . "',
    '" . htmlspecialchars($_REQUEST['correctans'],ENT_QUOTES) . "',
    " . htmlspecialchars($_REQUEST['MyRadio'],ENT_QUOTES) . "',
    " . htmlspecialchars($_REQUEST['section'],ENT_QUOTES) . "',
    " . htmlspecialchars($_REQUEST['chapter'],ENT_QUOTES) .
")";

A: Your query should be like
"insert into $user(id,question,option1,option2,option3,option4,correctAnswer,category,section,chapter)
            VALUES
            (
            '".$newstd."' ,
            '" . htmlspecialchars($question1,ENT_QUOTES) ."'
            )";

You have problem with double quotes

A: Correct code is
"insert into $user (id,question,option1,option2,option3,option4,correctAnswer,category,section,chapter) VALUES ('$newstd','" . htmlspecialchars($question1, ENT_QUOTES) . "','" . htmlspecialchars($question2, ENT_QUOTES) . "','" . htmlspecialchars($question3, ENT_QUOTES) . "','" . htmlspecialchars($question4, ENT_QUOTES) . "','" . htmlspecialchars($_REQUEST['correctans'], ENT_QUOTES) . "'," . htmlspecialchars($_REQUEST['MyRadio'], ENT_QUOTES) . "'," . htmlspecialchars($_REQUEST['section'], ENT_QUOTES) . "','" . htmlspecialchars($_REQUEST['chapter'], ENT_QUOTES) . "')";

A: To maintain the readability to the code, you can use it this way
$question1= htmlspecialchars(['$question1'],ENT_QUOTES);
$question2= htmlspecialchars(['$question2'],ENT_QUOTES);
$question3= htmlspecialchars(['$question3'],ENT_QUOTES);
$question4= htmlspecialchars(['$question4'],ENT_QUOTES);
$correctans= htmlspecialchars($_REQUEST['correctans'],ENT_QUOTES);
$MyRadio= htmlspecialchars([$_REQUEST['MyRadio'],ENT_QUOTES);
$section= htmlspecialchars($_REQUEST['section'],ENT_QUOTES);
$chapter= htmlspecialchars($_REQUEST['chapter'],ENT_QUOTES);

"insert into $user (id,question,option1,option2,option3,option4,correctAnswer,category,section,chapter) VALUES (' ','$newstd','$quertion1','$quertion2','$quertion3','$quertion4','$correctans','$MyRadio','$section','$chapter')";


text:
Q: Lista de puntos 3D a partir de 2D Quiero conocer la dirección de la cara (head pose) y saber sus movimientos de translación y rotación.
Lo primero que hago es detectar si hay cara en la imagen y obtener todos los puntos que la representan mediante la librería dlib. A continuación muestro un mapa de los puntos de la cara.

Cada punto me da dos valores, los cuales son sus coordendas XY en una lista, por ejemplo para dos puntos aleatorios si los imprimo obtengo:
(201, 203) (213, 187)

Según la documentación de OpenCV debo emplear la función cv2.solvePnP() y a esta introducirle los siguientes parámetros:

*

*objectPoints: Puntos 3D a trabajar.

*imagePoints: Puntos 2D.

*cameraMatrix: Matriz cámara.

*distCoeffs:coeficientes de distorsión.

Para los dos últimos si no leo mal en esta otra documentación (la previa a la primera mostrada) los obtengo de aplicar cv2.calibrateCamera() pero resulta que a estos hay que volver a defnirle objectPoints y imagePoints.
Ahora mis dudas,

*

*imagePoints son los puntos 2D, ¿debo entonces aquí introducirle los puntos obtenidos de las diferentes coordenadas de la cara?

*objectPoints. Sinceramente, ni idea que es lo que debo introducir aquí, puesto que son la representación de los valores 3D de mis valores 2D y no entiendo cómo obtenerlos.
Mi código:
import dlib
import numpy as np
import cv2

detector = dlib.get_frontal_face_detector() # DETECTAR CARA DE FRENTE
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # Puntos de la cara
imgpoints = []
objpoints = []

cap = cv2.VideoCapture(0)
while(True):
    # 1. Preparo la imagen
    _, frame = cap.read()
    frame = cv2.flip(frame, 1)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # 2. Detecto cara y puntos dlib
    faces = detector(gray)
    if len(faces) > 0:  # mirar lo del not none
        for face in faces:
            # Dibujo rectangulo cara
            x1, y1 = face.left(), face.top()
            x2, y2 = face.right(), face.bottom()
            cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
            # Obtengo puntos de estudio
            landmarks = predictor(gray, face)
            p17 = (landmarks.part(17).x, landmarks.part(17).y)
            p18 = (landmarks.part(18).x, landmarks.part(18).y)
            # Dibujo puntos
            cv2.circle(frame, p17, 1, (0, 0, 255), -1)
            cv2.circle(frame, p18, 1, (0, 0, 255), -1)
            imgpoints.append(p17)
            imgpoints.append(p18)
            print(imgpoints)

    # 3. Empiezo FACE POSE
    ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
    ret, rvecs, tvecs = cv2.solvePnP(objpoints, imgpoints, mtx, dist)

    # 99. Muestro resultados
    cv2.imshow('frame',frame)

    #
    key = cv2.waitKey(1)
    if key == 27: # Esc
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

¡Salud y gracias!


text:
Q: JDO Exception: "Query requires 1 parameters, yet 2 values have been provided." Despite the fact that my JDO query contains TWO declareParameters statements, the code below produces an error claiming only one parameter is accepted:
Query requires 1 parameters, yet 2 values have been provided.
The two parameters are amountP and taxP:
 javax.jdo.Query query= pm.newQuery(Main.class);
 query.setFilter("amount == amountP && tax < taxP");
 query.declareParameters("int amountP");
 query.declareParameters("int taxP");
 List<Main> results = (List<Main>)query.execute (amountP, taxP);

However, with the following changes, it works.
 javax.jdo.Query query= pm.newQuery(Main.class);
 query.setFilter("amount == amountP && tax < taxP");
 query.declareParameters("int amountP, int taxP");
 List<Main> results = (List<Main>)query.execute (amountP, taxP);

My question is: What was wrong with the original syntax?
Update: This problem has been reported by others but without explanation.

A: The JDO API seems to require that all parameters are set at once. The method is called declareParameters, which seems to be a "setter", and not an "adder". The method name may be misleading, and the documentation is not that great, but it seems to be just the way it is.
This is different from "extensions" that both supports a setter and an adder: addExtension(), setExtensions().

A: It seems pretty obvious that the second call to declareParameters replaces the parameter declared in the first call.  The correct way to declare more than one parameter is shown in your second example.

A: The explanation taken from the official documentation:
link here
void declareParameters(java.lang.String parameters)

*

*Declare the list of parameters query execution. The parameter
declaration is a String containing one or more query parameter
declarations separated with commas. Each parameter named in the
parameter declaration must be bound to a value when the query is
executed.

The String parameter to this method follows the syntax for formal parameters in the Java language.

*

*Parameters: parameters - the list of parameters separated by commas.