text:
Q: How to properly render server-side errors in the client for Node/Express? I've setup a simple Node/Express service that creates new bookmarks to a database.
In my Bookmark schema, one of the fields, url, has validations. When you try to create a new bookmark without the correct validations, it throws an error and a message.
E.g. if you don't provide a url to the request, then it will throw a message Please provide a url.
The route for the POST request to create a new bookmark:
app.post(
    '/api/bookmarks',
    (req, res) => {
      const { url, tags } = req.body;

      const bookmark = new Bookmark({
        url,
        tags
      });

      bookmark.save()
        .then(res => {
          res.send(result)
        })
        .catch(error => {
          console.log("err:", error);
          res.status(400).send(error)
        });
    }
  );

What my Bookmark schema looks like:
const bookmarkSchema = new Schema({
  url: {
    type: String,
    required: [true, "Please provide a URL."],
    match: [urlRegex, "Your URL is invalid. Please make sure to add www."]
  },
  tags: [String]
});

When I make an API call on the front end client (e.g. via React), I am able to catch the error and subsequent message (Please provide a URL.), but as you can see, I have to call err.response.data.errors.url.message which seems very verbose and long winded.
axios.post('http://localhost:5000/api/bookmarks', { tags: ["banana", "orange"] })
  .then(result => console.log('Result:', result.data))
  .catch(err => console.log('Error:', err.response.data.errors.url.message));

What has me thinking - is there a better way to render errors here? Would it be better handle errors in the client side instead?
I'm quite new to error handling so would like to know what is considered best practice.
Thanks!

A: Something like this. So you don't have to check it in schema.

app.post(
    '/api/bookmarks',
    (req, res) => {
      const { url, tags } = req.body;
      if (!url) {
        res.status(400).send({error: "URL is missing"})
        return;
      }
      if (!url.match(urlRegex) {
        res.status(400).send({error: "URL is not valid"})
        return;
      }
      const bookmark = new Bookmark({
        url,
        tags
      });

      bookmark.save()
        .then(res => {
          res.send(result)
        })
        .catch(error => {
          console.log("err:", error);
          res.status(500)
        });
    }
  );

It's a bad practice to send server side errors to frontend. It's a easy way to leak information about your database/backend. You should send your own string message instead of catched error.


text:
Q: Information about the Translation Engines I am interested in statistical machine translation. Can anyone suggest where can I find more information about state-of-the-art implementations like Google Translate, Microsoft Translate?
I would like to know about the following stuff:
1) The size of training data for different languages.
2) The quality of the translations for different languages.
and any other interesting point about engine implementation.

A: If you want to have more details about the state of the art, you should have a look on this book: http://www.statmt.org/book/
It is probably a little outdated but it interesting.
The famous tool in MT is Moses: http://statmt.org/moses/
You'll find an overview of this tool, and you can try a tutorial if you're brave.
With these documentation you'll have a more detailed comprehension of the task.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deserializing java date into Instant I need to deserialize below two foramt into java.time.Instant in a singe code
2020-04-23T10:51:24.238+01:00 and
2019-11-11T15:44:10.201Z
I'm getting belwow error in first case
nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type java.time.Instant from String "2020-04-23T10:51:24.238+01:00": com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.time.Instant from String "2020-04-23T10:51:24.238+01:00": Failed to deserialize java.time.Instant: (java.time.format.DateTimeParseException) Text '2020-04-23T10:51:24.238+01:00' could not be parsed at index 23
Is there any solution ?
Also Is there any way to deserialize java.util.Date into java.time.Instant
Note : Its an API response and  I can't use Date in deserialized class i.e consumer

A:     String dateString = "2020-04-23T10:51:24.238+01:00";

    Instant deserializedInstant = DateTimeFormatter.ISO_OFFSET_DATE_TIME
            .parse(dateString, Instant::from);
    System.out.println(deserializedInstant);

Output is:

2020-04-23T09:51:24.238Z

It works for your other string too:
    String dateString = "2019-11-11T15:44:10.201Z";

2019-11-11T15:44:10.201Z

Your JSON library may have still more elegant solutions. If not, you can probably wrap the above in a custom JSON deserializer.

A:
Also Is there any way to deserialize java.util.Date into java.time.Instant

Know your API:
final java.util.Date date = new Date();
final java.time.Instant instant = date.toInstant();


text:
Q: double space gets automatically replaced with single I have s file with the following commands in a file.
#!/bin/csh -f
echo "test  test"  //echo test [dobule space] test
set a = "test  test"  //set a = test [dobule space] test
echo $a

Output is as follows.
test [dobule space] test
test [single space] test
How does the double space get replaced with a single space when I set value to a?
Any help is appreciated.

A:
How does the double space get replaced with a single space when I set value to a?

No it doesn't get replaced by single space. It is because you didn't use quotes in your echo. Use:
echo "$a"

to get double spaced string.
Shell by default trims multiple white-spaces into a single space if you don't quote your variables. Even this will be single space:
s='a     b'
echo $s
a b

But with quotes:
echo "$s"
a     b

EDIT: Based on comments below you can do this in csh:
set QUERY = "select p.path from path p, file f where p.pathid=f.pathid and f.fileid=1234"
set dir = "`/usr/etc/venture/bin/mysql -BN -uroot -***** ****-e '$QUERY'`"
echo "$dir"

A: In bash, any runs of whitespace characters on the command line are by default replaced by a single space unless the value is quoted.
The bash man page tells this, but in a very roundabout way:
"Quoting" section:

Enclosing characters in single quotes preserves the literal value of each character within the quotes.
Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !

...Which implies whitespace characters! Since, as it turns out, they are "special":
"Word splitting" section:

If IFS is unset, or its value is exactly <space><tab><newline>, the default, then sequences of <space>, <tab>, and <newline> at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words.


text:
Q: Radio button can not be selected My problem is that I can not select radio buttons. I am using php mysql and create radio buttons in while loop for mysql_fetch_array function. Here is the code:

          <?php if($detailPage == TRUE && $detailType == "poll"){ ?>

<?php echo $pollData['pollContent']; ?>

                   <form id="pollForm" method="post" action="">

                             <?php while($pollAnswerData = $pollAnswerDataSql->fetch_assoc()) {
                                                echo '<input type="radio" id="' . $pollAnswerData['pollquestionId'] . '" name="pollAnswer" />' . $pollAnswerData['pollquestionContent'] . '
';
                                            } ?>

                       <input type="submit" name="submitButton" id="submitButton" value="Gönder"/>
                       </form>
                 <?php } else if($detailPage == TRUE && $detailType == "post") { ?>

<?php echo $postData['postContent']; ?>

             <?php } else {
                  listFlowData();
             } ?>

What is the problem in here?

A: Input elements (radio or checkbox) are not selected but checked. To show an element in checked state in the browser, you have to add a boolean "checked" attribute to the element.
<input type="radio" checked="checked" id="..." name="..." value="..."/>

Be aware that the browser only sends the values of the checked elements to your server side script. To recognize unchecked elements you have to use an internal list.
For radio inputs that means only if one of the elements was clicked by the user (or checked using the attribute) the named-parameter will exists in the form request.

A: seems like You are missing value attribute
http://www.w3schools.com/html/html_forms.asp
<input type="radio" name="sex" value="male">

A: You may change this line of code
echo '<input type="radio" id="' . $pollAnswerData['pollquestionId'] . '" name="pollAnswer" />' . $pollAnswerData['pollquestionContent'] . '
';

to this.
echo '<input type="radio" id="' . $pollAnswerData['pollquestionId'] . '" name="pollAnswer" value="' . $pollAnswerData['pollquestionId'] . '"/>' . $pollAnswerData['pollquestionContent'] . '
';

hope $pollAnswerData['pollquestionId'] is a unique value. Radio box is not selected because you do not insert value in radio box. You should insert value, which necessarily should be change on each loop repetition.
Thanks.

A: in Google chrome you may not be facing any problems. in Firefox, there is a problem. and the problem I figured out is that your form is within a label.
remove the label tag and it should be all fine.
even the non unique ID does not hurt in any browser(tested on chrome, Firefox and IE9)
below is the HTML I have been testing for you. uncomment the label and you will get the problem. hope it helps.
NOTE: The ID of each radio button is kept deliberately same to demonstrate that browser ignore this.

<form id="pollForm" method="post" action="">
<input type = "radio" id="rdo1" name = "poll_radio" value = "dsfsr"/>111

<input type = "radio" id="rdo1" name = "poll_radio" value = "rsddf"/>222

<input type = "radio" id="rdo1" name = "poll_radio" value = "rsfdf"/>333

<input type = "radio" id="rdo1" name = "poll_radio" value = "rshdf"/>444

<input type="submit" name="submitButton" id="submitButton" value="Gender"/>
</form>


text:
Q: During debug, step into background worker/thread. Possible? Out of curiosity. I'd like to know if its possible to step into (F11) a background worker during debugging. It usually just skips over to the next line of code. Is it a VS setting that needs to be changed? Is it just how its meant to be?
Any clarification would be much appreciated. Thanks.

A: As the comment says, you just have to set a breakpoint for the first line of code in your background task. (Or: Debugger.Break().)
Also, I recommend you to get a look for Debug > Windows > Threads window, it's quite useful in multithread debugging cases.

A:
It usually just skips over to the next line of code.

That's because the BackgroundWorker is being executed on a different thread, which has to be created and started first, and this takes some time. If you keep stepping, you will enter the worker at some point, but there's no telling when exactly.
Just put a breakpoint at the start of the worker code if you want to debug it.

A: Once the debugging is started, open the thread window mentioned in Sebestyén answer. When the desired thread is started, keep an eye in the column "Location" of the new row that appeared in the Thread window. Once it have the name of the thread you want, right-click it and select "Switch to Thread".
This solved the problem of the debugger cursor keep going to other points of the code (other threads running, I suppose) while I was trying to debug a specific thread.

A: from Haggisatonal answer
disable the VS hosting process (Project -> Properties -> Debug -> Enable the Visual Studio hosting process)
link
Visual Studio 2015 Debug doesn't work in multithread application


text:
Q: Send packet with scapy I'm trying to send a simple ICMP packet from HOST B to HOST A
This is my configuration:
HOST A
10.0.1.10 with gateway set to 10.0.1.24

Router
NIC 1 10.0.1.24
NIC 2 192.168.100.1

HOST B
192.168.100.3

A: 10.0.1.10 <---> 10.0.1.24 |NIC-1 Router NIC-2| 192.168.100.1 <---> 192.168.100.3: B

But when I try to send the packet with
send(IP(dst="10.0.1.10")/ICMP()/"Hello World")

nothing shows up on the tcpdump of the router .
With
sendp(IP(dst="10.0.1.10")/ICMP()/"Hello World")

instead, this shows up
09:41:16.398305 00:00:40:01:4b:20 (oui Unknown) > 45:00:00:27:00:01 (oui Unknown), ethertype Unknown (0xc0a8), length 60:
    0x0000:  6403 0a00 010a 0800 a631 0000 0000 4865  d........1....He
    0x0010:  6c6c 6f20 576f 726c 6400 0000 0000 0000  llo.World.......
    0x0020:  0000 0000 0000 0000 0000 0000 0000       ...........

It looks like a malformed packet, and nothing is forwarded to HOST A
The machines can ping correctly, what did I do wrong?
edit:sr1 output
13:25:58.235650 08:00:27:44:d7:c8 (oui Unknown) Null > Broadcast Unknown DSAP 0x08 Unnumbered, 27, Flags [Command], length 54
    0x0000:  0800 2701 507f 0800 2744 d7c8 0800 4500  ..'.P...'D....E.
    0x0010:  0028 0001 0000 4001 4b1f c0a8 6403 0a00  .(....@.K...d...
    0x0020:  010a 0800 26a8 0000 0000 4845 4c4c 4f20  ....&.....HELLO.
    0x0030:  574f 524c 440a

A: Solved. For someone that is a "noob" with this tool like me:
The router was not forwarding the packet to the subnet because it was malformed.
I sniffed a regular ICMP packet acting as a MiTM,and it worked. HOST 1 received the packet correctly.
Carcigenicate also guessed right, be sure to set the correct interface.


text:
Q: Using entryuuid virtual attribute in openLDAP doesn't read in other software When querying the LDAP in some third party software, I am not seeing the entry entryuuid.  On reading, I now understand that this is a virtual attribute.
As this is the only real guaranteed unique field, I was going to use this to map users.  However, since the third party software doesn't see it, it is not working as I had hoped (it sees the accounts, but also lists them as inactive).
Is there a way to make entryuuid a attribute in the LDAP instead?  I can find that certain implementations of ldap will allow this, but not how to implement it.
Am I barking up the wrong tree, or can I achieve this?

Edit: The same is true of "memberOf" it seems.


text:
Q: How to call a directive from a controller I have a directive which is depending on input. I want to call that directive from angular controller when ever that input changed. Here is my directive.
    var app = angular.module('App', ['ui.bootstrap']);

app.controller('fcController', function($scope, fcService, $uibModal) {
    $scope.formatType = '1';
});

app.directive('fcsaNumber', function($filter) {
    var addCommasToInteger, controlKeys, hasMultipleDecimals, isNotControlKey, isNotDigit, isNumber, makeIsValid, makeMaxDecimals, makeMaxDigits, makeMaxNumber, makeMinNumber;
    isNumber = function(val) {
        return !isNaN(parseFloat(val)) && isFinite(val);
    };
    isNotDigit = function(which) {
        return which < 45 || which > 57 || which === 47;
    };
    controlKeys = [0, 8, 13];
    isNotControlKey = function(which) {
        return controlKeys.indexOf(which) === -1;
    };
    hasMultipleDecimals = function(val) {
        return (val != null) && val.toString().split('.').length > 2;
    };
    makeMaxDecimals = function(maxDecimals) {
        var regexString, validRegex;
        if (maxDecimals > 0) {
            regexString = "^-?\\d*\\.?\\d{0," + maxDecimals + "}$";
        } else {
            regexString = "^-?\\d*$";
        }
        validRegex = new RegExp(regexString);
        return function(val) {
            return validRegex.test(val);
        };
    };
    makeMaxNumber = function(maxNumber) {
        return function(val, number) {
            return number <= maxNumber;
        };
    };
    makeMinNumber = function(minNumber) {
        return function(val, number) {
            return number >= minNumber;
        };
    };
    makeMaxDigits = function(maxDigits) {
        var validRegex;
        validRegex = new RegExp("^-?\\d{0," + maxDigits + "}(\\.\\d*)?$");
        return function(val) {
            return validRegex.test(val);
        };
    };
    makeIsValid = function(options) {
        var validations;
        validations = [];
        if (options.maxDecimals != null) {
            validations.push(makeMaxDecimals(options.maxDecimals));
        }
        if (options.max != null) {
            validations.push(makeMaxNumber(options.max));
        }
        if (options.min != null) {
            validations.push(makeMinNumber(options.min));
        }
        if (options.maxDigits != null) {
            validations.push(makeMaxDigits(options.maxDigits));
        }
        return function(val) {
            var i, number, _i, _ref;
            if (!isNumber(val)) {
                return false;
            }
            if (hasMultipleDecimals(val)) {
                return false;
            }
            number = Number(val);
            for (i = _i = 0, _ref = validations.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
                if (!validations[i](val, number)) {
                    return false;
                }
            }
            return true;
        };
    };
    addCommasToInteger = function(val) {
        var commas, decimals, wholeNumbers;
        decimals = val.indexOf('.') == -1 ? '.00' : val.replace(/^\d+(?=\.)/, '');
        wholeNumbers = val.replace(/(\.\d+)$/, '');
        commas = wholeNumbers.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
        return "" + commas + decimals.substring(0, 3);
    };
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            options: '@fcsaNumber',
        },
        link: function(scope, elem, attrs, ngModelCtrl) {
            var isValid, options;
            options = {};
            if (scope.options != null) {
                options = scope.$eval(scope.options);
            }
            isValid = makeIsValid(options);
            ngModelCtrl.$parsers.unshift(function(viewVal) {
                var noCommasVal;
                noCommasVal = viewVal.replace(/,/g, '');
                if (isValid(noCommasVal) || !noCommasVal) {
                    ngModelCtrl.$setValidity('fcsaNumber', true);
                    return noCommasVal;
                } else {
                    ngModelCtrl.$setValidity('fcsaNumber', false);
                    return void 0;
                }
            });
            ngModelCtrl.$formatters.push(function(val) {
                if ((options.nullDisplay != null) && (!val || val === '')) {
                    return options.nullDisplay;
                }
                if ((val == null) || !isValid(val)) {
                    return val;
                }
                ngModelCtrl.$setValidity('fcsaNumber', true);
                val = addCommasToInteger(val.toString());
                if (options.key == 1) {
                    options.prepend = 'S/.';
                }
                if (options.key == 2) {
                    options.prepend = '$';
                }
                if (options.prepend != null) {
                    val = "" + options.prepend + val;
                }
                if (options.append != null) {
                    val = "" + val + options.append;
                }
                return val;
            });
            elem.on('blur', function() {
                var formatter, viewValue, _i, _len, _ref;
                viewValue = ngModelCtrl.$modelValue;
                if ((viewValue == null) || !isValid(viewValue)) {
                    return;
                }
                _ref = ngModelCtrl.$formatters;
                for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                    formatter = _ref[_i];
                    viewValue = formatter(viewValue);
                }
                ngModelCtrl.$viewValue = viewValue;
                return ngModelCtrl.$render();
            });
            elem.on('focus', function() {
                var val;
                val = elem.val();
                if (options.prepend != null) {
                    val = val.replace(options.prepend, '');
                }
                if (options.append != null) {
                    val = val.replace(options.append, '');
                }
                elem.val(val.replace(/,/g, ''));
                return elem[0].select();
            });
            if (options.preventInvalidInput === true) {
                return elem.on('keypress', function(e) {
                    if (isNotDigit(e.which && isNotControlKey(e.which))) {
                        return e.preventDefault();
                    }
                });
            }
        }
    };
});

HTML
<input type ="text" ng-model ="currency" fcsa-number="{key : {{formatType}}}">

Here $scope.formatType = '1'; is the input. If this formatType changed then That directive need to call. How can I call that directive from angular controller.

A: You can set a watcher inside the link function you have written that will watch for the change of fcsa-number and group everything that you needs to be run into a function and call it inside the watcher .
link: function(scope,elem,attr,ctrl){
 scope.$watch('options', function(){
  // do your stuff
 });

A: you can use $broadcast to call directive from the controller
.controller("ctrl", function($scope) {
    $scope.$watch('formatType', function() {
        $scope.$broadcast("call_dir")
    })
})
return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
        options: '@fcsaNumber',
    },
    link: function(scope, elem, attrs, ngModelCtrl) {
        var isValid, options;
        options = {};
        scope.$on('call_dir', function(ev) {
            //your code
        })
    };


text:
Q: Python ? (conditional/ternary) operator for assignments C and many other languages have a conditional (AKA ternary) operator.  This allows you to make very terse choices between two values based on the truth of a condition, which makes expressions, including assignments, very concise.
I miss this because I find that my code has lots of conditional assignments that take four lines in Python:
if condition:
    var = something
else:
    var = something_else

Whereas in C it'd be:
var = condition ? something : something_else;

Once or twice in a file is fine, but if you have lots of conditional assignments, the number of lines explode, and worst of all the eye is drawn to them.
I like the terseness of the conditional operator, because it keeps things I deem un-strategic from distracting me when skimming the code.
So, in Python, is there a trick you can use to get the assignment onto a single line to approximate the advantages of the conditional operator as I outlined them?

A: Python has such an operator:
variable = something if condition else something_else

Alternatively, although not recommended (see karadoc's comment):
variable = (condition and something) or something_else

A: In older Python code, you may see the trick:
condition and something or something_else

However, this has been superseded by the vastly superior ... if ... else ... construct:
something if condition else something_else


text:
Q: HAPI FHIR try to use patch I've this resource of type Paramaters as follow:
{
  "resourceType": "Parameters",
  "parameter": [
    {
      "name": "operation",
      "part": [
        {
          "name": "type",
          "valueCode": "add"
        },
        {
          "name": "path",
          "valueString": "Organization"
        },
        {
          "name": "name",
          "valueString": "active"
        },
        {
          "name": "value",
          "valueString": "true"
        }
      ]
    }
  ]
}

Because I want to add active value on my Organization.
So I write, in according with HAPI FHIR documentation - 4.2.7 paragraph, this code to execute a patch:
fhirClientR4Configuration.clientFhihrR4().patch().withBody(body).withId("Organization/2381").execute();

But I have this error:

ca.uhn.fhir.rest.server.exceptions.InvalidRequestException: HTTP 400 :
Cannot deserialize instance of
java.util.ArrayList<com.github.fge.jsonpatch.operation.JsonPatchOperation>
out of FIELD_NAME token  at [Source: UNKNOWN; line: -1, column: -1]

I've noticed I must put in the same array all informations about patch (in the tag part), but I don't know I can resolve it.
Tha HAPI FHIR version is 4.2.0


text:
Q: Do databases always lock non-existent rows after a query or update? Given:
customer[id BIGINT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(30), count INT]
I'd like to execute the following atomically: Update the customer if he already exists; otherwise, insert a new customer.
In theory this sounds like a perfect fit for SQL-MERGE but the database I am using doesn't support MERGE with AUTO_INCREMENT columns.
https://stackoverflow.com/a/1727788/14731 seems to indicate that if you execute a query or update statement against a non-existent row, the database will lock the index thereby preventing concurrent inserts.
Is this behavior guaranteed by the SQL standard? Are there any databases that do not behave this way?
UPDATE: Sorry, I should have mentioned this earlier: the solution must use READ_COMMITTED transaction isolation unless that is impossible in which case I will accept the use of SERIALIZABLE.

A: This question is asked about once a week on SO, and the answers are almost invariably wrong.
Here's the right one.
insert customer (email, count)
select 'foo@example.com', 0
where not exists (
      select 1 from customer
      where email = 'foo@example.com'
)

update customer set count = count + 1
where email = 'foo@example.com'

If you like, you can insert a count of 1 and skip the update if the inserted rowcount -- however expressed in your DBMS -- returns 1.
The above syntax is absolutely standard and makes no assumption about locking mechanisms or isolation levels.  If it doesn't work, your DBMS is broken.
Many people are under the mistaken impression that the select executes "first" and thus introduces a race condition.  No: that select is part of the insert.  The insert is atomic.  There is no race.

A: Use Russell Fox's code but use SERIALIZABLE isolation. This will take a range lock so that the non-existing row is logically locked (together with all other non-existing rows in the surrounding key range).
So it looks like this:
BEGIN TRAN
IF EXISTS (SELECT 1 FROM foo WITH (UPDLOCK, HOLDLOCK) WHERE [email] = 'thisemail')
BEGIN
    UPDATE foo...
END
ELSE
BEGIN
    INSERT INTO foo...
END
COMMIT

Most code taken from his answer, but fixed to provided mutual exclusion semantics.

A: Answering my own question since there seems to be a lot of confusion around the topic. It seems that:
-- BAD! DO NOT DO THIS! --
insert customer (email, count)
select 'foo@example.com', 0
where not exists (
      select 1 from customer
      where email = 'foo@example.com'
)

is open to race-conditions (see Only inserting a row if it's not already there). From what I've been able to gather, the only portable solution to this problem:

*

*Pick a key to merge against. This could be the primary key, or another unique key, but it must have a unique constraint.

*Try to insert a new row. You must catch the error that will occur if the row already exists.

*The hard part is over. At this point, the row is guaranteed to exist and you are protected from race-conditions by the fact that you are holding a write-lock on it (due to the insert from the previous step).

*Go ahead and update if needed or select its primary key.

A: IF EXISTS (SELECT 1 FROM foo WHERE [email] = 'thisemail')
BEGIN
    UPDATE foo...
END
ELSE
BEGIN
    INSERT INTO foo...
END


text:
Q: Rolling window with offset different on Pandas DataFrame with PeriodIndex and DatetimeIndex When creating a pandas DataFrame with a daily PeriodIndex, and doing a rolling window calculation based on an offset (e.g. '5D') the result is not as expected.
I expect the rolling window to be the last 5 days, but instead the window seems to be from the start of the index, and growing for each item.
The rolling works as expected for a DataFrame with a DatetimeIndex
df_datetimeindex = pd.DataFrame([0.5]*10, columns=['data'], index=pd.date_range(start='2019', periods=10, freq='D'))
df_periodindex = pd.DataFrame([0.5]*10, columns=['data'], index=pd.period_range(start='2019', periods=10, freq='D'))
display(
    df_datetimeindex.data.rolling('5D', min_periods=1).sum(),
    df_periodindex.data.rolling('5D', min_periods=1).sum()
)

display(df_datetimeindex.index, df_periodindex.index)
display(df_datetimeindex.data.rolling('5D', min_periods=1), df_periodindex.data.rolling('5D', min_periods=1))

yields
2019-01-01    0.5
2019-01-02    1.0
2019-01-03    1.5
2019-01-04    2.0
2019-01-05    2.5
2019-01-06    2.5
2019-01-07    2.5
2019-01-08    2.5
2019-01-09    2.5
2019-01-10    2.5
Freq: D, Name: data, dtype: float64
2019-01-01    0.5
2019-01-02    1.0
2019-01-03    1.5
2019-01-04    2.0
2019-01-05    2.5
2019-01-06    3.0
2019-01-07    3.5
2019-01-08    4.0
2019-01-09    4.5
2019-01-10    5.0
Freq: D, Name: data, dtype: float64
DatetimeIndex(['2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04',
               '2019-01-05', '2019-01-06', '2019-01-07', '2019-01-08',
               '2019-01-09', '2019-01-10'],
              dtype='datetime64[ns]', freq='D')
PeriodIndex(['2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04',
             '2019-01-05', '2019-01-06', '2019-01-07', '2019-01-08',
             '2019-01-09', '2019-01-10'],
            dtype='period[D]', freq='D')
Rolling [window=432000000000000,min_periods=1,center=False,win_type=freq,axis=0]
Rolling [window=432000000000000,min_periods=1,center=False,win_type=freq,axis=0]

Is there an explanation for this behavior that I have missed?


text:
Q: python numpy : roll column wise with different values Is there a function that does the following?
Given a matrix
0 0 0
1 1 1
0 0 0

And a 1-D array of "shifting values"
0 1 2

The function would shift all the values, column wise, where each shift per column is specified by shifting_values ?
For example
> np.f(X, shifting_values,axis=1)
0 0 1
1 0 0
0 1 0

Does such a function exist? If not, is it possible to do this without using a for loop?


text:
Q: How are my arguments getting corrupted? So I recently took it upon myself to learn Lua for the game project I'm working on(targeting Windows 7 using Visual Studio 2010 and the Ogre3D engine), at around the same time I started implementing the library of choice for our GUI system, QuickGUI.  I decided to outsource font loading to lua as a learning experience and began to run into errors.  Thinking it was my inexperience with lua, I spent several days researching what the problem might be, but then upon reproducing the error in pure C++, I've run into the same issue.
To start up QuickGUI's FontManager, I first create an instance of the skin effect managers and resource managers, then use those to create the QuickGUI::Core object, then call the static singleton function to get a pointer to the FontManager object.  I then create a useable font by passing it a string with the requested name of the font, an Image object representing the rendered font in a *.png, an int to determine the baseline, and the name of an associated XML file describing the individual characters.  As follows:
      GUIResourceManager* mGuiResourceManager = new GUIResourceManager();
      GUISkinEffectManager* skinEffectMgr = new GUISkinEffectManager();

      QuickGUI::Core* GUICore = new QuickGUI::Core(mGuiResourceManager, skinEffectMgr);

      QuickGUI::FontManager* fontMgr = QuickGUI::FontManager::getSingletonPtr();

      fontMgr->createFont("TimesNewRoman.14", mGuiResourceManager->getImage("TimesNewRoman.14.png"), 10,"fonts/TimesNewRoman.14.xml");

Here is the relevant function from the QuickGUI::FontManager class:
Font* FontManager::createFont(const std::string& name, Image* i, unsigned int baseline, const std::string& fontXMLFile)
{
    if(mFontMap.find(name) != mFontMap.end())
    {
        Log::exception("FontManager::createFont : A font with name \"" + name + "\" already exists!");

        return NULL;
    }

    TiXmlDocument xmlDoc;
    xmlDoc.LoadFile(fontXMLFile);

    TiXmlElement* root = xmlDoc.LastChild()->ToElement();

    Font* newFont = new Font(name,i,baseline,root);

    mFontMap[name] = newFont;

    return newFont;
}

The QuickGUI library uses TinyXML for parsing.  My program was crashing on the  xmlDoc.LastChild()->ToElement() call, as the xml was invalid.  Upon investigating, I find something strange in debugging: my strings are somehow not making it into the createFont() function.  These are the values of the arguments after I set a breakpoint in the beginning of the above function:
    Font* FontManager::createFont(const std::string& name, Image* i, unsigned int baseline, const std::string& fontXMLFile)

name = "¤ð/"
i = 0x0308a738{mName="TimesNewRoman.14.png" mOgreImage=0x00ca3d28}
baseline = 10
fontXMLFile = "|ð/"

Once I noticed this, I first thought it might be trying to interpret a pointer as literal string data; the two values change from runtime to runtime, but they're always only off by each other by a single char. There were two problems with this, first, that Visual Studio was indicating they were strings with the "" markings, and second, that the Image object being created was getting its string just fine, and it accepted the same const std::string& type as an argument.  I then thought it might be an issue with my project and Ogre being compiled with Multi-Byte Character Set switched on, and QuickGUI having Unicode instead.  I recompiled, re-ran--same issue.
At this point, I don't know what to do.  It's not an issue I can see with my call syntax, I've looked through the QuickGUI code (available here), I've double, triple, quadruple-checked my compiling settings, investigated potential compiler-specific issues with implementation of std::string, and overall beaten my brain on this issue for nearly a week to no avail.  If anyone would be able to offer insight as to why in God's green earth my string's value is changing erratically like this, I would be most appreciative.


text:
Q: XSL duplicate parent element for each occurance of child I need to duplicate a parent element for each instance of a child element but I don't want to include the siblings of the child element in the output.
I would then like to sort the parents based on a field in the child node
Sample input:
<Customer>

  <Market>
    <MarketNumber>100</MarketNumber>
  </Market>
  <Market>
    <MarketNumber>200</MarketNumber>
  </Market>
  <c/>
</Customer>
<Customer>

  <Market>
    <MarketNumber>100</MarketNumber>
  </Market>
  <c/>
</Customer>

Desired output (3 customer with one market each):
<Customer>

  <Market>
    <MarketNumber>100</MarketNumber>
  </Market>
  <c/>
</Customer>
<Customer>

  <Market>
    <MarketNumber>100</MarketNumber>
  </Market>
  <c/>
</Customer>
<Customer>

  <Market>
    <MarketNumber>200</MarketNumber>
  </Market>
  <c/>
</Customer>

I have solved it by selecting all markets and copying its parent elements manually but would like to do it without naming them (its 33 elements in the parent node). The problem is I can't select "../." because then i also copy the sibling market.
<xsl:apply-templates select="Customer/Market">
    <xsl:sort select="MarketNumber" data-type="number" order="ascending"/>
</xsl:apply-templates>
...
<xsl:template match="Market">

    <Customer>
        <xsl:copy-of select="../a"/>
        <xsl:copy-of select="../b"/>
        <xsl:copy-of select="."/>
        <xsl:copy-of select="../c"/>
    </Customer>
</xsl:template>

I suspect this can be solved by copying parent element except Market and then copy Market with "." like i do above but I cant figure out how to.. Any hints welcome! Other solutions welcome as well but it needs to handle the sorting too.
Thanks!
Richard

A: <xsl:apply-templates select="Customer/Market">
    <xsl:sort select="MarketNumber" data-type="number" order="ascending"/>
</xsl:apply-templates>
...
<xsl:template match="Market">

    <Customer>
        <xsl:copy-of select="../*[not(self::Market)] | ."/>
    </Customer>
</xsl:template>

This will copy all siblings that are not Market elements, and will also copy the current (matched) Market element. Is that what you wanted?

A: I'm a few years late to the party, but just had this requirement myself.  The solution I came up with was to use named templates to recursively copy the XML tree, excluding element names which I didn't want copied, and using the generate-id function to identify the node which I still wanted to be copied.  See comments in the below code for more detail.
This solution works in XSLT 1.0.
An XSLT Fiddle example is available here: https://xsltfiddle.liberty-development.net/bnnZWm.
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:msxsl="urn:schemas-microsoft-com:xslt"
  exclude-result-prefixes="msxsl"
>
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="/">
    <Customers>
      <xsl:apply-templates select="//Market|//Customer[not(./Markets/Market)]" />

    </Customers>
  </xsl:template>

  <xsl:template match="Market">
    <xsl:call-template name="copyAllButMe">
      <xsl:with-param name="rootNode" select="../.." />
      <xsl:with-param name="ignoreElementName" select="local-name()" />
      <xsl:with-param name="includeNodeId" select="generate-id()" />
    </xsl:call-template>
  </xsl:template>

  <xsl:template name="copyAllButMe">
    <xsl:param name="rootNode" />
    <xsl:param name="ignoreElementName" />
    <xsl:param name="includeNodeId" />
    <xsl:if test="(local-name($rootNode) != $ignoreElementName) or (generate-id($rootNode) = $includeNodeId)">
      <xsl:element name="{local-name($rootNode)}" namespace="{namespace-uri($rootNode)}">
        <xsl:copy-of select="$rootNode/attribute::*" />
        <xsl:for-each select="$rootNode/child::node()">
          <xsl:choose>
            <xsl:when test="self::*">
              <xsl:call-template name="copyAllButMe">
                <xsl:with-param name="rootNode" select="self::node()" />
                <xsl:with-param name="ignoreElementName" select="$ignoreElementName" />
                <xsl:with-param name="includeNodeId" select="$includeNodeId" />
              </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy-of select="self::node()" />
            </xsl:otherwise>
          </xsl:choose>
        </xsl:for-each>
      </xsl:element>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>


text:
Q: Masking in ActionScript3 I am trying to understand masks in actionscript..Everything seems to make sense to me but one part of the code
function mouseM(event:MouseEvent):void {
if (mouseclick == 1) {
mask_mc.graphics.beginFill(0x000000);
mask_mc.graphics.drawEllipse(mouseX, mouseY, 70, 60);
mask_mc.graphics.endFill();
}
}

I am not sure how to exactly ask this question but here it goes. why does the mask have "begin fill" with a black color? wouldn't that paint the the image in black (I know it doesn't, it just reveals it)? what is the exact function of beginfill (besides revealing the image lool)? like how does it exactly work? sorry if it sounds ridiculously off.. but that part of the code was really screwing me up in understanding masks

A: What you are doing is drawing a shape to be used as a mask. In this case, a circle.
It doesn't matter what colour it is as Flash is only interested in the shape of the mask, not the colour.
Once the circle is drawn, Flash checks what part of the circle overlap the object you're masking so that every pixel the circle is not covering will be invisible. I guess it should really be called an anti-mask as the circle dictates which parts of your image wont be masked but it's just become the general convention to call the circle (or whatever shape you use) the mask.
Again, you're just creating a shape to be used as a mask. Setting the colour is just so the object can essentially exist.. because you can't exactly have a transparent circle.
Feel free to change the colour to anything and you'll see it makes no difference, the shape is all that matters.


text:
Q: Remove all characters before specific number in Nth column at first match NOT last I am trying to remove a random block of characters from the 5th column in a dataset.
Sample data:
A | 12 | AA | 24 | Test to go and keep 192.168.1.1 > 192.168.2.1 | B

Result should look like:
A | 12 | AA | 24 | 192.168.1.1 > 192.168.2.1 | B

I have this so far:
awk 'BEGIN{FS=OFS="|"} {gsub(".*? 192","", $5 )} 1' file.txt

However this removes everything in the 5th column before the last match.
What the code does now:
.168.2.11

I need to remove everything before the first match not last

A: With your shown samples, please try following awk code. Simple explanation would be: set field separator and output field separator as | for all lines of Input_file. Then globally substitute spaces AND alphabets with NULL in 5th field. Add spaces as per shown samples before and after 5th field and finally print the edited/non-edited current line.
awk 'BEGIN{FS=OFS="|"} {gsub(/[[:alpha:]]+|[[:space:]]+/,"",$5);$5=" "$5" "} 1' Input_file

EDIT: In case you want to match always IP address > IP address form in 5th field then simply try following.
awk 'BEGIN{FS=OFS="|"} match($0,/([0-9]+\.){3}[0-9]+ > ([0-9]+\.){3}[0-9]+/){$5=substr($0,RSTART,RLENGTH)} 1' Input_file

A: If IP address in column 5 of your file always starts with some particular numbers, for example " 192.168.", then, you can use: awk 'BEGIN{FS=OFS="|"}{$5=substr($5, index($5, " 192.168."))}1' file.txt


text:
Q: How to get image data from dart:html ImageBitmap? In HTML5 I can get an ImageBitmap's data by drawing it on a <canvas> using CanvasRenderingContext2D.drawImage() and then calling CanvasRenderingContext2D.getImageData():
function getBitmapData(bitmap) {
    const canvas = document.createElement("canvas");
    canvas.width = bitmap.width;
    canvas.height = bitmap.height;
    canvas.getContext("2d").drawImage(bitmap, 0, 0);
    return canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height);
}

I would like to do the same with dart:html but, unlike the HTML5 API, CanvasRenderingContext2D.drawImage() does not accept an ImageBitmap instance as parameter.
How can I get image data from an instance of dart:html ImageBitmap ?


text:
Q: Return of None not expected I have a small function as follows:
# Given the numerical value of a minute hand of a clock, return the number of degrees assuming a circular clock.
# Raise a ValueError for values less than zero or greater than 59.

def exercise_20(n):
    try:
        if n < 0 or n > 59:
            raise ValueError("Number supplied is less than 0 or greater than 59")
    except ValueError as ex:
        print(ex)
    else:
        return n * 6

print(exercise_20(-15))
print(exercise_20(30))
print(exercise_20(75))

Here is the output:
Number supplied is less than 0 or greater than 59
None
180
Number supplied is less than 0 or greater than 59
None

Why am I returning 'None' when I strike an exception?
The function correctly prints the exception for the appropriate values and it prints the correct answer for a value within the correct range.
I don't understand why it also printing 'None' when it strikes an exception.

A: You try a block, if it fails your condition if n < 0 or n > 59, you raise. You then catch your raise and just log it. Then you return nothing. Catch and release is for fishing :).
def exercise_20(n):
    if n < 0 or n > 59:
      raise ValueError("Number supplied is less than 0 or greater than 59")

    return n * 6

print(exercise_20(-15))
print(exercise_20(30))
print(exercise_20(75))

You might be interested on this too: https://softwareengineering.stackexchange.com/questions/187715/validation-of-the-input-parameter-in-caller-code-duplication#. When should you check for input conditions? Caller or callee?

A: your function should just raise the error. let the called to the catching:
def exercise_20(n):
    if n < 0 or n > 59:
        raise ValueError("Number supplied is less than 0 or greater than 59")
    return n * 6

for n in (-15, 30, 75, 30):
    print(f"{n=}:", end=" ")
    try:
        print(exercise_20(n))
    except ValueError as ex:
        print(ex)

it will output:
n=-15: Number supplied is less than 0 or greater than 59
n=30: 180
n=75: Number supplied is less than 0 or greater than 59
n=30: 180

you code returns None because you do not have an explicit return statement after print(ex). therefore python implicitly returns None.

A: It is because else: only happens when there is no error. So when there is an error, it skips the else block (also skipping the return inside it), therefore returning None. Within the function definition, you print the error, and outside it, you print what is returned, causing the format to be
Error (if there is one)
Return value (None (if nothing is returned) or n*6)

The docs have more information.


text:
Q: Subversion Apache2.2 LDAPS authentication failed OS: Redhat Linux
Subversion: 1.5.0
Apache: 2.2.17
httpd.conf:
LDAPSharedCacheSize 200000
LDAPCacheEntries 1024
LDAPCacheTTL 600
LDAPOpCacheEntries 1024
LDAPOpCacheTTL 600

<Location /svn>
DAV svn
SVNParentPath /home/svnroot/repository
AuthzSVNAccessFile /home/svnroot/repository/svn_access_file
AuthType Basic
AuthBasicProvider ldap
AuthzLDAPAuthoritative off
AuthLDAPURL "ldaps://master.ldap.ebupt.com:636/OU=staff,DC=ebupt,DC=com?uid?sub?(objectClass=*)" SS
L
AuthName "Subversion.resository"
Require valid-user
</Location>

Apache error_log:
[Thu Feb 24 16:48:00 2011] [debug] mod_authnz_ldap.c(403): [client 10.1.85.181] [25242] auth_ldap a
uthenticate: using URL ldaps://master.ldap.ebupt.com:636/OU=staff,DC=ebupt,DC=com?uid?sub?(objectCl
ass=*)
[Thu Feb 24 16:48:00 2011] [info] [client 10.1.85.181] [25242] auth_ldap authenticate: user jinjian
kang authentication failed; URI /svn [LDAP: ldap_simple_bind_s() failed][Can't contact LDAP server]

ping master.ldap.ebupt.com is OK.
My FTP LDAPS authentication is OK as below:
server:master.ldap.ebupt.com
port:636
Enable SSL:checked
Base DN:ou=staff,dc=ebupt,dc=com
anonymous:checked
Search Filter:(objectClass=*)
User DN attribute:uid
Search scope:subtree

A: "Can't contact LDAP server" can mean a bunch of things, but if your LDAP server is reachable and you're using simple bind over SSL as you are here, it means Apache doesn't trust the certificate the LDAP server is presenting.
You need to tell Apache about the certificate so that it can create the SSL connection.
This section of the Apache docs is what you need: http://httpd.apache.org/docs/2.2/mod/mod_ldap.html#usingssltls
The best way to do this is to obtain the CA certificate from the CA that signed the certificate on your LDAP servers, and use the LDAPTrustedGlobalCert directive. An example, from one of my boxes:
LDAPTrustedGlobalCert CERT_BASE64 /etc/openldap/cacerts/cacert.pem

How you go about obtaining the CA cert varies; my LDAP servers are running certs signed by our own CA, so I can easily get the CA cert. Your setup may be different; consult whoever looks after your LDAP server.
You can also obtain the certificate that the LDAP server presents using the OpenSSL tools:
openssl s_client -connect your.ldap.host:636 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'

That'll display the certificate. Copy everything (including BEGIN CERTIFICATE and END CERTIFICATE) into a file.
Now add the directive:
LDAPTrustedGlobalCert CERT_BASE64 /path/to/your/cert/file

to the top of your Apache configuration. Restart Apache, and you're done.


text:
Q: Array em PHP que se comunique com JavaScript Tenho esse programa que coloca o selected de acordo com o value:
<!--inicio if option = selected-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
    // frase que desejo localizar (pega o value do option )
    var frase      = "minAlarme4_analogico00",
        localizado = null;
    // loop que percorre cada uma das opções
    // e verifica se a frase da opção confere com o
    // valor de fase que está sendo procurado
    // valor de fase que está sendo procurado
    $('#Linha5 option').each(function() {
      // se localizar a frase, define o atributo selected
      if($(this).attr('value') == frase) {
        $(this).prop('selected', true);
      }
    });
});
        </script>

<!--Final if option = selected-->

Porém para gerar esses "values" eu tenho um programa que faz isso.
Obs: Infelizmente não posso postar esse código fonte e na verdade nem tenho acesso ao mesmo.
Mas tenho o seguinte conteúdo nos "values" do código que tenho acesso. O "value" esta assim value=\"%s\"%s>%s. Exemplo:
printf("<option value=\"%s\"%s>%s</option>\n", $nomeScript, $extra, $descricaoScript);.

Como criar um array em PHP que se comunique com JavaScript?
(Anteriormente eu postei uma pergunta falando que precisava do contrário, mas como os dados vem do banco de dados acho que eu preciso que o array seja em PHP para passar os valores para o JavaScript).

A: Pelo que eu entendi, você quer enviar um array em PHP para o Javascript entender.
Netse caso você poderia utiliar a função json_encode() para enviar um JSON para o JavaScript.
Exemplo:
echo json_encode(["a" => 10, "b" => 20, "c" => 30])
#vai imprimir {"a": 10, "b": 20, "c": 30}


text:
Q: Pass base64 encoded file from client-side JS to server-side JS to make API call Here is what I am trying to build:
I have a form with various fields, one of them is image upload. I took the image upload and base64 encode part from here and it works perfectly. This all happens on client-side:
    document.getElementById('button').addEventListener('click', function() {
      var files = document.getElementById('file').files;
      if (files.length > 0) {
        getBase64(files[0]);
      }
    });

    function getBase64(file) {
       var reader = new FileReader();
       reader.readAsDataURL(file);
       reader.onload = function () {
       };
       reader.onerror = function (error) {
       };
    }

Then, I would like to take the base64 encoded string and include it in JSON to make an api call. The api call needs to happen on server-side. It also includes authentication, and this bit alone is also working fine. The call creates a file in the selected location.
The bit that I am struggling with:
How do I pass the fileEncoded variable from the client-side part of the script to the server-side?
I tried the following:

*

*Passing it as query string to a separate page for making the api call: <form action="apicall.html?fileEncoded" method="post"> but I couldn't make this work

*Using localStorage, but that didn't work either: localStorage.setItem("fileEncoded", fileEncoded);
I would like to understand what I am missing here and I would appreciate an answer that would explain the concept, on top of providing a code snippet.
I would prefer to do it on two separate pages (1st with form and base64 encode, 2nd with the server-side api call).

A: You likely need to send a request to your server via POST request, with the encoded file data as the body in that request.
Then server-side, you will have to handle that POST request.
For example:
function getBase64(file) {
  var reader = new FileReader();

  reader.readAsDataURL(file);

  reader.onload = function () {
    console.log(reader.result);
    var fileEncoded = reader.result;
    fetch("/upload/file", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        data: fileEncoded,
        // Additional fields  here...
      })
    })
    .then(function(res) {
      console.log("Success!", res);
    })
    .catch(function(err) {
      console.log("Error!", err);
    });
  };

  reader.onerror = function (error) {
    console.log('Error: ', error);
  };
}

JS Bin

A: In your code you are using readAsDataURL which converts the file into a data URL which is typically used to display a selected image file. It doesn't access the server at all.  What you want to do is create an AJAX request to the server.
See related question: How to use FormData for ajax file upload


text:
Q: Scale fixed-width font to fit constant number of characters on a line I have a websocket based terminal session. I want the font size to increase to fill the div such that it is always 80 characters wide. What's the best way of doing this? I'd love it if there was a CSS-only way of doing this, but I'm already using jQuery, so a vanilla javascript or jQuery solution would be good too.

A: For browsers that support fractional font sizes or CSS text-rendering: geometricPrecision, you can get a fixed-width font to perfectly fit within any bounds.
In this screenshot, the fourth line is exactly 80 characters:

For browsers that don't support fractional font sizes , it is impossible to always make x characters fit within a given width.
Here's the same text with a 12px font:

… and with a 13px font:

Using the 12px font, the longest line is 83 characters, so it's too small.  Using the 13px font, the longest line is 77 characters, so it's too large.
In this situation, you must shrink or widen the container to match the font:

The code below places an 80-character wide span in divs of varying widths, using a style of word-wrap: break-word;.  It does a binary search for the best font size, using getClientRects() to determine upper and lower bounds for the binary search.
In case the browser doesn't support fractional font sizes, it adjusts the container's width to match the font size.
The span is then removed.
$('div').each(function() {
  var x= $(''+Array(80).join('x')+'').appendTo(this),
      lo= 0.1,
      hi= 50,
      mid;
  do {
    mid= (lo+hi)/2;
    $(this).css({
      fontSize: mid
    });
    if(x[0].getClientRects().length > 1) {
      hi= mid;
    }
    else {
      lo= mid;
    }
  } while(Math.abs(hi-lo)>0.001);
  while(x[0].getClientRects().length === 1) {
    $(this).css({
      width: '-=1'
    });
  }
  while(x[0].getClientRects().length === 2) {
    $(this).css({
      width: '+=1'
    });
  }
  x.remove();
});

Tested in Chrome, IE, Firefox, Safari, and Opera.
Fiddle

A: Here's a CSS-only example based on the8472's answer:
div,textarea{
    width:100%;
    max-width: 100%;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    font-family:  "Lucida Console", Monaco, monospace;
    font-size: 1.99vw; /* The text overflows in safari using (int)2 */
    white-space: nowrap;
    overflow-x:hidden;

    /* styling */
    background:#09f;
    min-height: 100px;
    margin-bottom: 30px;
}

How does it work?
To get the right font-size, divide 160 by the number of characters you want to fit per line, minus 0.01.
http://jsfiddle.net/mb2L4mee/1/
Tested in Chrome, FF and safari.

A: One approach would be to calculate the size of a 80 char line for a fixed font-size and register a function on resize event to adjust the font-size based on the terminal size.

        Some text

function scale(lineWith) { /* lineWidth based on 80char 10px font-size */
    var ratio = $('#terminal').width() / lineWith;
    $('.text').css('font-size', (10 * ratio) + 'px');
}
$(window).resize(function(){
    scale(lineWith)
});

Demo: http://jsfiddle.net/44x56zsu/
This seems to adjust pretty good in Chrome (Versión 39.0.2171.99 m)
But I don't think it's possible to adjust  the font-size to exactly fit the container size for all browsers because decimal values are rounded.
Font size test: http://jsfiddle.net/ahaq49t1/

This rounding issue in some browsers prevents to do an exact adjustment using font properties.

A: Within limits it might be possible in pure CSS. If you know the fraction of the viewport that the div will occupy then you can scale the font based on the view port width.
.terminal {font-size: 1vw;} would result in a font size (vertical) equivalent to 1% of the view port. Since a monospace font also has a fixed aspect ratio that results in a width depending on the aspect ratio of the font and the view port size.

A: Not sure if this is the most elegant solution, and it needs a bit more polishing too. But you can measure the font. Create a hidden measure bar to see how wide the font is in pixels.
Fill it with the desired amount of characters (using 20 here for demonstration purposes):
12345678901234567890

Keep increasing the font size of the measure bar and find the largest width that's still not wider than the div:

$(
  function() {
    var $measureBar = $('#measureBar');
    var $console = $('#console');
    $measureBar.css('font-size', '1px');
    for (i = 1; $measureBar.width() <= $console.width(); i++) {
      $measureBar.css('font-size', i + 'px');
    }
    $console.css('font-size', (i - 1) + 'px');
  }
)
#console {
  background-color: black;
  color: white;
}
#measureBar {
  display: none;
}
#measureBar,
#console {
  font-family: courier;
}

12345678901234567890

12345678901234567890 Text that should be twenty characters wide.

A: I was facing a very similar requirement and came up with a fairly straight forward solution.  As soon as I get some down time, I'll be writing a jQuery plugin around this example code.
As was mentioned in some of the other answers here, the key is using em as your font-size unit.  Additionally, to achieve a similar layout in all (modern) browsers, for a solution that must cope with various fixed-width fonts, the ruler method is the most reliable approach that I have found.

function fixieRemeasure() {
    var offset =  document.getElementById("fixie").offsetWidth,
        ruler = (document.getElementById("fixieRuler").offsetWidth * 1.01),
        fontSize = (offset / ruler);
    document.getElementById("fixie").style.fontSize = fontSize + "em";
}

function fixieInit(columns) {
    document.getElementById("fixieRuler").innerText =
            new Array(columns + 1).join("X").toString();
    fixieRemeasure();
}

(function () {
    fixieInit(80);
    window.onresize = function () { fixieRemeasure(); };
} ());
#fixie {
    padding: 0 2px 0 6px;
    font-size: 1em;
    background-color: #000;
    color: #0F0;
}

#fixieRuler {
    font-size: 1em;
    visibility: hidden;
}

+------------------------------------------------------------------------------+
|                                                                              |
|                   ,%%%,                                                      |
|                 ,%%%` %==--                                                  |
|                ,%%`( '|                                                      |
|               ,%%@ /\_/                                                      |
|     ,%.-"""--%%% "@@__                                                       |
|    %%/             |__`\                                                     |
|   .%'\     |   \   /  //                                                     |
|   ,%' >   .'----\ |  [/                                                      |
|      < <<`       ||                                                          |
|       `\\\       ||                                                          |
|         )\\      )\                                                          |
| ^^^jgs^^"""^^^^^^""^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        |
|          ASCII Art: http://www.chris.com/ascii/index.php?art=animals/horses  |
+------------------------------------------------------------------------------+

This is only a proof of concept and there are a few fairly obvious issues baked in.  Mainly, the resize method is called continuously and that should be replaced with something like onResizeEnd and properly attached to the DOM prior to production use.  To componentize, I'd use a class selector instead of an id, and would also dynamically insert/remove the ruler element on-the-fly.
Hope it helps.
UPDATE
I created a new project, fixie.js on github, based on this example code.  Still has a bit of work to be done in terms of performance and modularization, but it is works well in all browsers and I believe that it provides the simplest means to solve the issue with a minimal amount of boilerplate code.
The only requirements are that you set a font-size to your pre elements in em, and provide them a class name with the format of 'fixie_COLS':

I'll be 80 columns

jQuery & webcomponent implementations to follow.  It's MIT licensed and any contributions are welcome: https://github.com/dperish/fixie.js

A: This can be done using pure css using the vw (viewport width), vh (viewport height), vmin (relative to width or height, whichever is smaller), vmax (relative to width or height, whichever is larger) length Units.
For browser compatibility you can check this out.
For a simple tutorial check this out.


text:
Q: how do i format curlly bracket data in php i have this type of data store in mysql, how can i echo only the amount value from this?
{"1":{"amount":"700","date":"2022-10-31","amount_discount":"0","amount_fine":"0","description":"","collected_by":"John Doe","payment_mode":"Cash","received_by":"12","inv_no":1},"2":{"amount":"300","date":"2022-12-17","description":" Paid by: Jane Doe","amount_discount":0,"amount_fine":"0","payment_mode":"upi","received_by":"23","inv_no":2}}
this code looks like json data, if yes then should i be using jquery to echo the values or is there a way to do it in php?

A: You can use the json_decode function to turn it into a PHP object and then access its properties. For your example, you can do this to get the "amount" property:
<?php
$js='{"1":{"amount":"700","date":"2022-10-31","amount_discount":"0","amount_fine":"0","description":"","collected_by":"John Doe","payment_mode":"Cash","received_by":"12","inv_no":1},"2":{"amount":"300","date":"2022-12-17","description":" Paid by: Jane Doe","amount_discount":0,"amount_fine":"0","payment_mode":"upi","received_by":"23","inv_no":2}}';
echo json_decode($js)->{"1"}->amount;
?>

A: $data = json_decode('{"1":{"amount":"700","date":"2022-10-31","amount_discount":"0","amount_fine":"0","description":"","collected_by":"John Doe","payment_mode":"Cash","received_by":"12","inv_no":1},"2":{"amount":"300","date":"2022-12-17","description":" Paid by: Jane Doe","amount_discount":0,"amount_fine":"0","payment_mode":"upi","received_by":"23","inv_no":2}}');
Ex1: ((array) $data)[1]->amount
Ex2: $data->{'1'}->amount]);

A: Try this

$json_string = '{"1":{"amount":"700","date":"2022-10-31","amount_discount":"0","amount_fine":"0","description":"","collected_by":"John Doe","payment_mode":"Cash","received_by":"12","inv_no":1},"2":{"amount":"300","date":"2022-12-17","description":" Paid by: Jane Doe","amount_discount":0,"amount_fine":"0","payment_mode":"upi","received_by":"23","inv_no":2}}';

$json_data = json_decode($json_string, TRUE);


text:
Q: Azure, shut down all vm's when out of money I need to stop all my vm's in azure portal when my balance is 0$ How can i do it? maybe some script?

A: Unfortunately you can't do that with script for now... The balance (or billing) is not exposed via the Azure REST API (or Azure PowerShell).

A: For shutdown, we use a RUNBOOK with the follow code inside.
We run this everyday at 8PM. (You could trigger this from another alert http://www.matthewjbailey.com/create-azure-billing-alert-email/)
workflow ShutDown-AllVMs {
    param (
        [parameter(Mandatory=$true)]
        [String] $VMCredentialName = "ourcred@xyz.com"
    )

        $Credential = Get-AutomationPSCredential -Name $VMCredentialName

        if ($Credential -eq $null)  {
            throw "Could not retrieve '$VMCredentialName' credential asset. Check that you created this asset in the Automation service."
        }

        Add-AzureAccount -Credential $Credential

        Select-AzureSubscription BizSpark

        InlineScript {
            Get-azurevm | ? { $_.Status -ne "StoppedDeallocated"}  | Stop-AzureVM -Force
        }
}

For alerts
Setup the alert
http://www.matthewjbailey.com/create-azure-billing-alert-email/
Monitor the alert
http://blogs.technet.com/b/keithmayer/archive/2014/11/08/scripts-to-tools-automate-monitoring-alert-rules-in-microsoft-azure-with-powershell-and-the-azure-service-management-rest-api.aspx
I have not tried all this together, so you may have a 2+2=5 issue :) but have a read of the blogs and you may find that you get 4 :)


text:
Q: Boundedness of a value Is there any difference between assuming:
1) $f(x) \lt C$ for some finite constant $C$
and
2) $f(x) \leq C$ for some finite constant $C$?
Far more frequently you would write the former, so would I, but if the $C$ is undefined in any way and the only thing that matters is that it is finite - then what's the difference, technically? Obviously if $f(x) \leq C$ then there exists $\tilde C = C + 1$ for which $f(x) \lt \tilde C$, well you know. I understand that the question itself may be considered quite stupid, but it got stuck in my head. I had some thoughts on it but they're long since forgotten.

A: Both conditions mean that $f$ is bounded from above. As said in the comments, if $f(x)<C$ for all $x$ then of course also $f(x)\le C$ for all $x$. And if $f(x)\le C$ for all $x$ then for example $f(x)<C':=C+1$ for all $x$.
If you let $C=\sup f(x)$, you clearly only get $\le$. And if you want to use the expression $\frac1{C-f(x)}$ somewhere, you better use the definition with $<$.  So both variants have their advantages.
There are many similar instances of moot distinctions, for example defining $a_n\to a$ as $\forall\epsilon>0\colon \exists N\in\mathbb N\colon \forall n>N\colon |a_n-a|<\epsilon$ or $\forall\epsilon>0\colon \exists N\in\mathbb N\colon \forall n\ge N\colon |a_n-a|\le\epsilon$ doesn't really matter. But beware of starting with $\forall \epsilon\ge0$, and that may be one reason why $<$ throughout is widely preferred over $\le$.
In summary, you are free to use either definitions of "bounded from above", but should preferably use and show the exact property used in the explicit definition in your textbook.


text:
Q: iPhone dictation character appended:  Whenever I send a message on GroupMe from my iPhone and I use dictation, I always find this character at the end of my message when I open it on a Windows or on my Android: .  It only shows up on non-apple devices, so in case you're on one and it doesn't show up:

What does it mean, or what is this character used for?  Why does it not disappear, even when I press the end dictation button after I'm done speaking?


text:
Q: To extract only specific characters using Regex in python I need to extract specific characters like brackets (not the elements within it), *, # etc and replace it with ' '. So I compiled my pattern like below
p = re.compile(r'\s([\[]).*|\s([\(]).*|\s([#]).*|\s([\{]).*|\s([\*]).*|\s([\<]).*|\s.*(\>)\s|\s.*
      (\])\s|\s.*(\))\s|\s.*(#)\s|\s.*(\*)\s|\s.*(\})\s')
string = "hello (you) "
for match in re.finditer(p, string):
  print(match.group())

This gives the output:
(you)

But what I am expecting is match to give the output list with the captured group like below
["(",")"]

so that I can replace it with '  ' and have the desired output as
hello you

Input: Abnormal heart rate (with fever) should be monitored. Insert your <Name> here.
Output:Abnormal heart rate with fever should be monitored. Insert your Name here.

A: This answer assumes that you want to replace terms in parentheses or angle brackets with only the content inside them.  That is:
(with fever) -> with fever
<Name> -> Name

We can try using re.sub here with a callback function:
inp = "Abnormal heart rate (with fever) should be monitored. Insert your <Name> here."
print(re.sub(r'\(.*?\)|<.*?>', lambda x: re.sub(r'[()<>]', '', x.group(0)), inp))

This prints:
Abnormal heart rate with fever should be monitored. Insert your Name here.

The logic here is that we selectively target the (...) and <...> terms using an alternation.  Then, we pass the entire match to a lambda callback which then replaces the surrounding symbols with just the content.

A: Just list all the characters you want to remove in a single character set, and use re.sub() to remove them.
print(re.sub(r'[[\](){}<>#*]', '', string))

A: I think you can proceed with replace all with space expect A-Z a-z if you also want digits 0-9 you can specify.
public class MyClass {
    public static void main(String args[]) {
      String string = "hello (you) hai";
              String result =string.replaceAll("[^A-Z a-z]","");
      System.out.println(result);
    }
}

This will work but here we are using replaceAll();


text:
Q: Algorithm to minimize sample pooling to reach minimum mass trying to determine how I would address this problem using R code.
Brief description of problem:
There is a minimum mass required to run an analysis of samples. Previously collected samples are often less than this mass, which means that multiple samples within an experimental treatment must be pooled to reach the minimum requirement. However, samples should be pooled as little as possible to maximize biological replicates.
For example, samples within Treatment A may have these masses: 8g, 7g, 5g, and 10g. Another Treatment, B, has samples with masses of 20g, 21g, 24g, and 29g.
If the minimum mass required for the analysis is 15g, then each sample in Treatment B can be analyzed without pooling. However, in Treatment A, samples would need to be pooled to reach this minimum.
It would be best to combine the 5g and 10g sample and the 8g and 7g sample, because this maximizes the number of possible pooled samples by minimizing potential total masses (i.e., if I combined the 5g and 8g and also the 10g and 7g, I would only have one possible pooled sample that meets the minimum)
Data and R
The data is structured as this example follows:
sample_id = c(1:24)
treatments = c(rep("A",8),rep("B",8),rep("C",8))
mass = round(c(runif(8,4,10),runif(8,5,13),runif(8,15,18)),1)
df = data.frame(cbind(sample_id,treatments,mass))
df$mass = as.numeric(df$mass)
df$sample_id = as.numeric(df$sample_id)

> df
   sample_id treatments mass
1          1          A  8.6
2          2          A  8.9
3          3          A  7.5
4          4          A  4.5
5          5          A  7.9
6          6          A  4.5
7          7          A  7.7
8          8          A  6.6
9          9          B  5.0
10        10          B 12.0
11        11          B  7.4
12        12          B  8.4
13        13          B 12.2
14        14          B 10.0
15        15          B  6.5
16        16          B 12.1
17        17          C 15.6
18        18          C 16.5
19        19          C 16.8
20        20          C 17.5
21        21          C 15.6
22        22          C 17.6
23        23          C 18.0
24        24          C 15.8

So far my strategy has been:
# Step 1: separate out all samples that do not need to be pooled, for ease IRL
bigenough = df %>%
  filter(mass >= 15)

#Keep df with all the samples that will need to be pooled
poolneeded = df %>%
  filter(!(sample_id %in% bigenough$sample_id))

I am at a loss of how to best pool the samples algorithmically however. If anyone has any suggestions that would be helpful. I usually use tidyverse if that helps...

A: Here is a first attempt. It is made up of a function which takes a  split data.frame (split by treatment) of the data to be pooled.
In this function a new DF is created which contains all pairwise possibilities of the sample_id. This df2 is then 2 times left_join-ed with data and the sum of the two samples is calculated, filtered for being >= 15 and ordered.
This function is then called by map after group_split. The result is all the possible allowed sample combinations.
library(tidyverse)

fff <- function(data) {
  nn <- nrow(data)
  mm <- combn(seq(data$sample_id[1], data$sample_id[nn]), 2) |> t()
  df2 <- data.frame(mm) |> setNames(c("sample_id", "sample_id_2"))
  ddf <- df2 |>
    left_join(data) |>   # nolint: object_usage_linter.
    left_join(data, by = c("sample_id_2" = "sample_id", "treatments")) |>
    mutate(sum = mass.x + mass.y) |> # nolint: object_usage_linter.
    filter(sum >= 15) |>
    arrange(sample_id, sum) # nolint: object_usage_linter.
  return(ddf)
}

poolneeded |>
  group_split(treatments) |>
  map(fff)
#> Joining, by = "sample_id"
#> Joining, by = "sample_id"
#> [[1]]
#>   sample_id sample_id_2 treatments mass.x mass.y  sum
#> 1         1           2          A    9.4    6.2 15.6
#> 2         1           7          A    9.4    6.5 15.9
#> 3         1           4          A    9.4    6.8 16.2
#> 4         1           3          A    9.4    7.6 17.0
#> 5         1           8          A    9.4    8.9 18.3
#> 6         2           8          A    6.2    8.9 15.1
#> 7         3           8          A    7.6    8.9 16.5
#> 8         4           8          A    6.8    8.9 15.7
#> 9         7           8          A    6.5    8.9 15.4
#>
#> [[2]]
#>    sample_id sample_id_2 treatments mass.x mass.y  sum
#> 1          9          10          B   10.9    7.0 17.9
#> 2          9          14          B   10.9    7.2 18.1
#> 3          9          11          B   10.9    7.9 18.8
#> 4          9          16          B   10.9    8.5 19.4
#> 5          9          13          B   10.9   11.2 22.1
#> 6          9          12          B   10.9   11.7 22.6
#> 7          9          15          B   10.9   11.7 22.6
#> 8         10          16          B    7.0    8.5 15.5
#> 9         10          13          B    7.0   11.2 18.2
#> 10        10          12          B    7.0   11.7 18.7
#> 11        10          15          B    7.0   11.7 18.7
#> 12        11          14          B    7.9    7.2 15.1
#> 13        11          16          B    7.9    8.5 16.4
#> 14        11          13          B    7.9   11.2 19.1
#> 15        11          12          B    7.9   11.7 19.6
#> 16        11          15          B    7.9   11.7 19.6
#> 17        12          14          B   11.7    7.2 18.9
#> 18        12          16          B   11.7    8.5 20.2
#> 19        12          13          B   11.7   11.2 22.9
#> 20        12          15          B   11.7   11.7 23.4
#> 21        13          14          B   11.2    7.2 18.4
#> 22        13          16          B   11.2    8.5 19.7
#> 23        13          15          B   11.2   11.7 22.9
#> 24        14          16          B    7.2    8.5 15.7
#> 25        14          15          B    7.2   11.7 18.9
#> 26        15          16          B   11.7    8.5 20.2

Another way
This makes use of the same function fff as above but it needs to be called with a subset of the poolneeeded - in this case below it is a subset of treatments == "B" .
You see then a DF of all possible allowed combinations for pooling and can choose a first pair for pooling. Then the remaining choices for a second pooling are also shown.
sel2 <- function(data) {
  ddf <- fff(data)
  cat(paste("\n", "These are your possibilities for the FIRST pooling", "\n"))
  print(ddf)
  ask <- askYesNo("Do You want to make first choice?")
  if (ask) {
    s_1 <- readline(prompt = "Enter sample 1: ")
    s_2 <- readline(prompt = "Enter sample 2: ")
    ddf2 <- ddf |> filter(
      sample_id != s_1 & sample_id != s_2 &
        sample_id_2 != s_1 & sample_id_2 != s_2 # nolint: object_usage_linter.
    )
    cat(paste0("\n", "These are your possibilities for the SECOND pooling", "\n"))
    print(ddf2)
  } else {
    return()
  }
}

poolneeded_b <- poolneeded |> filter(treatments == "B")
sel2(poolneeded_b)

#> r$> sel2(poolneeded_b)
#> Joining, by = "sample_id"
#>
#>  These are your possibilities for the FIRST pooling
#>    sample_id sample_id_2 treatments mass.x mass.y  sum
#> 1          9          14          B    7.6    8.1 15.7
#> 2          9          12          B    7.6    8.7 16.3
#> 3          9          15          B    7.6    9.6 17.2
#> 4          9          10          B    7.6   10.3 17.9
#> 5          9          16          B    7.6   10.9 18.5
#> 6          9          13          B    7.6   12.3 19.9
#> 7         10          11          B   10.3    5.6 15.9
#> 8         10          14          B   10.3    8.1 18.4
#> 9         10          12          B   10.3    8.7 19.0
#> 10        10          15          B   10.3    9.6 19.9
#> 11        10          16          B   10.3   10.9 21.2
#> 12        10          13          B   10.3   12.3 22.6
#> 13        11          15          B    5.6    9.6 15.2
#> 14        11          16          B    5.6   10.9 16.5
#> 15        11          13          B    5.6   12.3 17.9
#> 16        12          14          B    8.7    8.1 16.8
#> 17        12          15          B    8.7    9.6 18.3
#> 18        12          16          B    8.7   10.9 19.6
#> 19        12          13          B    8.7   12.3 21.0
#> 20        13          14          B   12.3    8.1 20.4
#> 21        13          15          B   12.3    9.6 21.9
#> 22        13          16          B   12.3   10.9 23.2
#> 23        14          15          B    8.1    9.6 17.7
#> 24        14          16          B    8.1   10.9 19.0
#> 25        15          16          B    9.6   10.9 20.5
#>
#> Do You want to make first choice? (Yes/no/abbrechen) y
#> Enter sample 1: 9
#> Enter sample 2: 14
#>
#> These are your possibilities for the SECOND pooling
#>    sample_id sample_id_2 treatments mass.x mass.y  sum
#> 1         10          11          B   10.3    5.6 15.9
#> 2         10          12          B   10.3    8.7 19.0
#> 3         10          15          B   10.3    9.6 19.9
#> 4         10          16          B   10.3   10.9 21.2
#> 5         10          13          B   10.3   12.3 22.6
#> 6         11          15          B    5.6    9.6 15.2
#> 7         11          16          B    5.6   10.9 16.5
#> 8         11          13          B    5.6   12.3 17.9
#> 9         12          15          B    8.7    9.6 18.3
#> 10        12          16          B    8.7   10.9 19.6
#> 11        12          13          B    8.7   12.3 21.0
#> 12        13          15          B   12.3    9.6 21.9
#> 13        13          16          B   12.3   10.9 23.2
#> 14        15          16          B    9.6   10.9 20.5


text:
Q: What's wrong with the way I solved the complex equation $z^5=-16\overline{z} (z \in \mathbb{C})$
Solve the fallowing complex equation($z \in \mathbb{C})$: $z^5=-16\overline{z}$.

Here's how I tried to solve the equation:
$$ z^5=-16\overline{z} \rightarrow z^6=-16(x^2+y^2)$$
$$z= \varepsilon(\cos{\theta} +i\sin{\theta}) \rightarrow z^6=\varepsilon^6(\cos{6\theta} +i\sin{6\theta})$$
$$w=r(\cos{\varphi} +i\sin{\varphi})=-16(x^2+y^2) $$
$$r=\sqrt{(-16)^2(x^2+y^2)^2} = 16(x^2+y^2)$$
$$ \varphi = \arctan{0} = \pi$$
$$ 6\theta = \varphi + 2k\pi, k\in \mathbb{Z}\rightarrow \theta_0 = \frac{\pi}{6}; \theta_1 = \frac{\pi}{2}; \theta_2 = \frac{5\pi}{6} \theta_3 = \frac{7\pi}{6}; \theta_4 = \frac{3\pi}{2}; \theta_5 = \frac{11\pi}{6}$$
$$ z_0=16(x^2+y^2)e^{i\frac{\pi}{6}};z_1=16(x^2+y^2)e^{i\frac{\pi}{2}};z_2=16(x^2+y^2)e^{i\frac{5\pi}{6}};z_3=16(x^2+y^2)e^{i\frac{7\pi}{6}};z_4=16(x^2+y^2)e^{i\frac{3\pi}{2}};z_5=16(x^2+y^2)e^{i\frac{11\pi}{6}} $$
But my teacher told me that I didn't solve it correctly. Where am I wrong?

A: $x$ and $y$ are unknown, so it makes no sense saying $z_0=16(x^2+y^2)e^{i\pi/6}$. Recall that $z=x+iy$, according to what you wrote.
A proper way would be first noting that $z=0$ is a solution, so we can henceforth assume $z\ne0$.
Write $z=re^{i\varphi}$; then the equation becomes
$$
r^5e^{5i\varphi}=-16re^{-i\varphi}
$$
and therefore, being $r\ne0$,
$$
r^4e^{6i\varphi}=-16
$$
Then, as $r>0$, we get $r=2$ and $e^{6i\varphi}=-1=e^{i\pi}$, so
$$
6i\varphi=\pi+2k\pi
$$
You get six distinct solutions for $k=0,1,\dots,5$.
Alternatively, take the modulus of both sides:
$$
|z|^5=16|\bar{z}|=16|z|
$$
so $|z|^4=16$ and $|z|=2$ (we're still assuming $z\ne0$). Write $z=2u$; then the equation becomes $u^5=-\bar{u}=-u^{-1}$, since $|u|=1$. Thus we get $u^6=-1$ and so $u$ is one of the sixth roots of $-1$.


text:
Q: Floor function not returning correct value Something very strange is happening as I evaluate the Floor function:
(9.2 - 8)/1.2
Floor[(9.2 - 8)/1.2]

returns:
1.

0

so I did the following:
Floor[1]
Floor[1.0]
Floor[1.2/1.2]

returning
1

1

1

Does anybody know what is happening? Am I doing something wrong here?
I also tried the following and got the same confusing result:
x = (9.2 - 8)/1.2
Floor[x]

1.

0

and
In[57]:= Floor[(10.2 - 9.0)/1.2]

Out[57]= 0

but
In[59]:= Floor[(10.4 - 9.0)/1.4]

Out[59]= 1

I'm getting so confused that sometimes I doubt myself when doing this simple operations in my head...
Any information about this will be highly appreciated.

A: As it was suggested by @CarlWoll and @thorimur in the comments, I evaluated:
(9.2 - 8)/1.2 // FullForm

which returns:
0.9999999999999994`

I'm not really sure why, but I suspect that this is related to the order in which Mathematica evaluates each operation. Since 9.2/1.2 and 8/1.2 have no finite decimal expansion, apparently Mathematica truncates this expressions and rounds them when showing the final answer. So I decided to round them myself before plugging them in the Floor function as follows:
Floor[Round[(9.2 - 8)/1.2, 0.1]]

resulting in:
1

I still have no clue why Mathematica would distribute the 1/1.2 into the subtraction apparently ignoring the parenthesis, but I suppose it's usually better when working with large numbers...


text:
Q: Can my Azure Mobile Service run locally? I am new to Azure. I am following this tutorial in setting up my .Net server for azure and ios client.
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-ios-get-started/
I am testing my ios client on simulator. Can I run my .NET server on my location machine with put publish it to azure? If yes, how can I figure my client to talks to this location machine?
And in the tutorial, it creates a Database Table. If I run it locally, do I need to setup my location DB server?

A: Not on a mac (which you need for iOS development). With the .NET backend you can run the service locally on a Windows machine, but it will be running off of localhost.
For iOS development, you have two choices. If you use the JavaScript / node.js backend, where all of your development can be done in the Mac (you can configure the service via Git locally or directly in the portal). If you use the .NET backend (the link you mentioned), then you need the Mac for the client-side development, and a PC (or Windows running in the Mac on an emulator such as parallels) to develop the server (you need Visual Studio for that).
And regarding your question about the table, when you run it locally, it will use Entity Framework Code First (by default), so you don't need to create the table in your (local) database - it will create it automatically for you.


text:
Q: Specify xtick/ytick with multiplication in Pgfplots I often use plots with a second x/y-axis which is proportionally related to the first one. Therefore, I would like to calculate the tick-values by multiplication. Let's say the first one is a time and the second one a related distance, then I would like to have something like:
\begin{tikzpicture}

\begin{axis}[%
xmin=0,
xmax=1,
ymin=0*50,
ymax=1*50, % here it works
ytick = {0, .2, .4, .6, .8, 1} * 50, % this does not work
%ytick = {0, 10, 20, 30, 40, 50}, % this works, but it requires manual calculation
ylabel = {distance},
axis x line=none,
axis y line*=right,
]
\end{axis}

\begin{axis}[%
xmin = 0,
xmax = 1,
ymin=0,
ymax=1,
ytick = {0, .2, .4, .6, .8, 1},
ylabel={time},
]

\end{axis}

% add a plot here

\end{tikzpicture}%

I would like just to copy the ytick-values from the one axis to the second one and specify the factor. Is this possible somehow? Thank in advance.

A: The easy solution is to NOT specify the tick list.  ymin and ymax will do.
In any case, one can construct a list of scaled values using a foreach loop.
\documentclass{article}
\usepackage{pgfplots}
\usetikzlibrary{arrows.meta}

\newcommand{\yticklist}{}% reserve global name

\begin{document}

\begin{tikzpicture}

\let\yticklist=\empty% create scaled list
\foreach \y in {0, .2, .4, .6, .8, 1}
{
  \pgfmathmultiply{\y}{50}%
  \ifx\empty\yticklist\relax \xdef\yticklist{\pgfmathresult}%
  \else \xdef\yticklist{\yticklist,\pgfmathresult}%
  \fi
}
\begin{axis}[%
xmin=0,
xmax=1,
ymin=0*50,
ymax=1*50, % here it works
ytick/.expanded = {\yticklist},
axis x line=none,
axis y line=right,
y axis line style={-Butt Cap},
ylabel = {distance},
]
\end{axis}

\begin{axis}[%
xmin = 0,
xmax = 1,
ymin=0,
ymax=1,
ytick = {0, .2, .4, .6, .8, 1},
ylabel={time}
]

\end{axis}

% add a plot here

\end{tikzpicture}%

\end{document}


text:
Q: How can I use the size of an initialised vector in an external function, in C? I am a beginner at using C.
I have program that takes two vectors, finds their difference as a vector and computes its length. I am trying to generalise it so that any vectors of any size can be put in without any other change. I find an issue when trying to input the size of the vector into the external function, modulus. It will print off random numbers in the correct format, mostly zero, so the true error is unclear. What am I doing wrong?
int i, l;

float modulus(float vec[], int length);
void main() {
  /* declare and initialise a position vector */
  float positionVector1[] = {6.0, 3.0};
  float positionVector2[] = {3.0, 2.0};
  int L = sizeof(positionVector1);
  float positionVector[L];
  for (i = 0; i < L; i++) {
    positionVector[i] = positionVector2[i] - positionVector1[i];
  }
  float len;
  len = modulus(positionVector, L);
  printf("length is %.2e\n", len);
}

float modulus(float vec[], int length) {
  float mod = 0.0;
  for (i = 0; i < length; i++) {
    mod = mod + (vec[i] * vec[i]);
  }
  mod = sqrt(mod);
}


text:
Q: Order email template override in magento 2 Am trying to override the sales order email and I did that override but I have doubt in code, In that email template they called variable like
{{var payment_html|raw}}

in payment methods, I want to know in which file this variable is calling please tell me.

A: You can find payment_html in: \Magento\Sales\Model\Order\Email\Sender\OrderSender::prepareTemplate()


text:
Q: How to make DataGridColumn ReadOnly but with CaretVisible? Is there a way to have a DataGrid with a column in ReadOnly mode but with the Caret Visible? Similar to a Textbox when using the IsReadOnlyCaretVisible property?
If you set the IsReadOnly property the Column gets disabled and it is not possible to click on the cell.
<DataGrid ItemsSource="{Binding Customers}" AutoGenerateColumns="False">
         <DataGrid.Columns>
             <DataGridTextColumn Binding="{Binding Name}"></DataGridTextColumn>
             <DataGridTextColumn Binding="{Binding Income}" IsReadOnly="True"></DataGridTextColumn>
         </DataGrid.Columns>
</DataGrid>

A: You can create a DataGridTemplateColumn with TextBox. refer below code.
<DataGridTemplateColumn Header="Name">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox Text="{Binding Name}" IsReadOnly="True" IsReadOnlyCaretVisible="True"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>


text:
Q: Does $ \Bbb{Q}_2$ has $\sqrt{-1}$? Does $ \Bbb{Q}_2$ has $\sqrt{-1}$?
I tried to use Hensel lemma as usual.
Let $f(x)=x^2+1$.
But if some $a∈\Bbb{Z}$, $f(a)=0$, then $f'(a)$ can always divide by $2$.
So I cannot use Hensel lemma.
Could you help me?

A: No: if the monic polynomial $x^2+1$ had a root in $\Bbb Q_2$ then that root would be in the ring of integers $\Bbb Z_2$; but a root in $\Bbb Z_2$ implies that there is a root modulo $2^k$ for all $k\ge1$, contradicting the fact that $x^2+1$ has no root modulo $4$.

A: An alternative approach: consider $1+i$, and its minimal $\Bbb Q_2$-polynomial. You see that it's $X^2-2X+2$, clearly $\Bbb Q_2$-irreducible by Eisenstein. So $1+i\notin\Bbb Q_2$, and thus $i\notin\Bbb Q_2$.


text:
Q: Blotter package does not work when I run the code 2nd time I was playing with quanstrat code from Guy Yollin's notes. The sample code is provided below:
library(quantstrat)
library(blotter)

search()
currency("USD")
stock("SPY", currency = "USD", multiplier = 1)

ls(envir = FinancialInstrument:::.instrument)

ls(all=T)

initDate <- '1997-12-31'
startDate <- '1998-01-01'
endDate <- '2014-06-30'
initEq <- 1e6

Sys.setenv(TZ = "UTC")

options("getSymbols.yahoo.warning"=FALSE)

getSymbols('SPY', from = startDate, to = endDate, index.class = "POSIXct", adjust = T)

SPY$SMA10m <- SMA(Cl(SPY), 10)

#rm.strat(qs.strategy)

qs.strategy <- "qsFaber"

initPortf(qs.strategy, 'SPY', initDate = initDate)

When I ran it first time, I had no issues. When I ran it second time without modifying anything, I got the error message below:

Error in exists(paste("portfolio", name, sep = "."), envir = .blotter,  :
    object '.blotter' not found

I did the search() and the > "package:blotter" appeared. I have to restart RStudio in order to get this working. I am getting the same error every second time I run this code.
Any solutions or suggestions?

A: Hey again blackknight316,
I answered another one of your questions this morning and it seems you have questions related to getting started with quantstrat in general. Similar to that one, It seems that when trying to cut, paste, and recreate the code examples of others, you maybe using arguments that may not be relevant to your script.
In addition, the environment is likely getting cluttered with examples that have overlapping objects, which could be leading to some inconsistent behavior. But there is not enough information in the post to know if that is happening.
Might I suggest checking out the excellent quantstrat intro course at datacamp.com?
https://www.datacamp.com/courses/financial-trading-in-r
It walks one through an entire strategy with videos and examples from start to finish and discusses all the main functions, what their arguments do, and will give you a working example.
Good luck,
Justin
r

A: The easiest fix for this issue is to simply manually create the required environments within your script. If you're removing all global variables at the top of your script, you can insert the following code:
rm(list = ls(all.names = T))
.blotter <- new.env()
.strategy <- new.env()

Note, you must keep the .blotter and .strategy names as these are the default names used by the blotter and quantstrat packages, respectively.


text:
Q: Como adicionar o símbolo de real brasileiro (R$) no LaTex? Gostaria de saber como inserir o símbolo de R$ no LaTex utilizando o Overleaf? É algum pacote que tenho que inserir?

A: Para gerar o símbolo monetário brasileiro não é necessário nenhum pacote, apenas utiliza-se o \ da seguinte forma sem que ocorra nenhum erro:
Forma no LaTex:
R\$ 10,00 = R$ 10,00


text:
Q: how to check if a model is tagged by a specific tag I have model Entity and related model Tag. The later serves as tags, so the relation is serviced by a pivot table
I guess it is quite easy, but I am lost.
public function tags()
{
    return $this->belongsToMany('App\Models\Tag', 'entity_tags', 'entity_id', 'tag_id');
}

Now, in my view I can list all tags:
They are defined
{!!
               join(', ',
                    array_map(function($o) {
                        return link_to_route('entities.profile',
                        $o->name,
                        [$o->id],
                        ['class' => 'ui blue tag button']
                        );},
                        $object->tags->all())
            ) !!}

My question:
how in BLADE I can check if the Entity object has a specific capacity?
in my controller SHOW method I get one single Entity:
$object = Entity::find(34);

and then i wish to do sth if  the entity is tagged by a certain tag
@if($object->capacities .... has tag=  3
 // do things here
@endif

Thx

A: You could add a public method to your Entity class wich would let you check for an existing tag on this entity :
<?php
public function hasTag($tagToMatch)
{
   foreach ($this->tags as $tag)
   {
      if ($tag->id == $tagToMatch)
         return (true);
   }
   return (false);
}

This would allow you to use the following code in your views :
@if ($entity->hasTag(3))
   Do something
@endif

A: You can check if an Entity has a certain tag like this:
@if($entity->tags()->where('id', 3)->exists()) //.... has tag=  3
   // do things here
@endif


text:
Q: Slow initialization of rails 3.1 applications on nginx/passenger I have started learning and developing web applications with Rails 3.1.
I have 3 applications hosted on a "webby" by webbynode.com and I am using their webby gem.
Everything is going fairly ok except for one or two little things:
Whenever I push to the webbynode server the update of one of my apps, everything goes well, but the initialization of each of the three websites is really slow. Is this normal ( that all applications need to be reinitialized, even if only one has been updated)?
Also, after a while if the websites don't get any visits ( and they don't get too many of them...), it seems that the server shuts down, and again each website takes ages to be reinitialized at the next visit.
I understand it might be coming from "spawners", I was just wondering if someone could explain quickly why the server seems to go to sleep and/or point me to suitable settings for NGINX?
Thanks a lot!