text:
Q: Retransform data into original form? I have a time series data which consist of 24 hours of the electricity demand. I transform the data into stationary from through differences, Now after forecasting for one year, I want to transform the data into its original form to check the accuracy of the model. I want to explain my question by an example
    dat <- c(5,24,23,12,14,15,16,17,18,22,24)
    sat<- diff(dat)
 sat
 [1]  19  -1 -11   2   1   1   1   1   4   2
 ori <- diffinv(sat)
> ori
 [1]  0 19 18  7  9 10 11 12 13 17 19

By using the diffinv which is the inverse of the difference, but the result I obtain is the original data dat. Know can any one help me that how I obtain the original data dat, mean the result of dat and ori are different.

A: In diffing you loose information about the first value, in your example $5$
This will work:
dat <- c(5,24,23,12,14,15,16,17,18,22,24)
sat<- diff(dat)
5 + diffinv(sat)

or in the general case
dat <- c(5,24,23,12,14,15,16,17,18,22,24)
print(dat[1] + diffinv(dat))

alternatively you can use the xi argument
print(diffinv(diff(dat), xi = 5))

You can also see xi being used in
example(diffinv)


text:
Q: MYSQL Avg the last 100 values not sorted correctly. Sort before avging I have written a SQL query to find the average number of hours between 2 date and times
SELECT  labtestdate, ROUND(AVG(TIME_TO_SEC(TIMEDIFF(concat(labtestdate, ' ', labtesttime),arrivedatlabdatetime))/ 3600), 0 ) AS timediff
FROM    results WHERE labtestdate IS NOT NULL AND labtesttime IS NOT NULL and testresult IS NOT NULL and arrivedatlabdatetime IS NOT NULL
GROUP BY sampleref
ORDER BY labtestdate DESC
LIMIT 100

This works brilliantly giving me 100 rows giving me an average of 14 hours of each of the last 100 (some more, some less) however if I don't group by sampleref i don't get a value and instead get only one row (which is what I want) but with a really old test date, like it's getting 100 rows then ordering them?
I also get a lot of instances of
Warning: #1292 Truncated incorrect time value: '-2689:43:01'
what am I missing here? How can I tweak this so that it gives me the avg hours between arrivedatlabdatetime and labtestdate labtesttime for just the most recent tested samples by labtestdate labtesttime and where arrivedatlabdatetime, labtestdate,labtesttime and testresult is not null or empty ?
thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mongodb geospatial indexes, 2d vs 2dsphere According to the docs it says about 2d indexes:

The 2d index supports calculations on a flat, Euclidean plane. The 2d index also supports distance-only calculations on a sphere, but for geometric calculations (e.g. $geoWithin) on a sphere, store data as GeoJSON objects and use the 2dsphere index type.

Few things I do not understand..

*

*I do not understand what is meant by distance-only, does it mean the Chord (that line which connects two surface points through a line "inside" the surface)?

*How does that calculation work against Earth Longitude and Latitude? If that was designed for Euclidean space, how does it express distance in radians?

*Instead, using the 2dsphere indexes, it calculates the surface distance correctly between two points, but it works without specifying the 360 longitude lines and the 180 latitude lines. Is it programmed to specially for Earth longitude and latinudes?

*If 3. above is correct. does it takes into account that Earth is oblate spheroid and not a perfect sphere?

A: *

*No. It means the surface distance using the Haversine formula.

*I'm not sure what you are trying to ask in regards to "how does it express distance in radians" but if you mean how are lat/lon angle values and deltas converted into radians it is: PI * angle / 180.0. For the full Haversine formula, check out this link for implementations in 84 languages: http://rosettacode.org/wiki/Haversine_formula

*2dsphere indexes use the WGS84 datum (which defines the bounds) See: http://spatialreference.org/ref/epsg/4326/.

*Without looking at their code it is impossible to say. But given that they use WGS84 and talk about an "earth-like sphere" it is highly doubtful. I'm guessing they use Haversine (so distance calculations are only an approximation).


text:
Q: I need to copy all selected datagridview row to another datagridview when checkboxcolumn is checked I am attempting to copy datagridview rows to another datagridview when checkboxcolumn is checked. I am loading datagridview1 from treeview when child node is selected. However, when I select another childnode, the previous checkedbox disappears
 private void BtnAdd_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Product Name");
        dt.Columns.Add("Qty");
        dt.Columns.Add("Unit Price");

        foreach (DataGridViewRow row in dgvSelect1.Rows)
        {
           bool isSelected = Convert.ToBoolean(row.Cells["checkBoxColumn"].Value);
            if (isSelected)
                {
               dt.Rows.Add(row.Cells[2].Value);
                }
                dgvSelect2.DataSource = dt;

A: Heres your Code snippet
In your main class:
private DataTable dt;

In the constructor for the main class:
dt = new DataTable();
dt.Columns.Add("Product Name");
dt.Columns.Add("Qty");
dt.Columns.Add("UnitPrice");
dgvSelect2.DataSource = dt;

Setting dt as DataSource for the DataGrid links the content of the DataTable to the DataGrid so you have to do it just once.
In button click:
dt.Clear();
foreach(var row in dgvSelect1.Rows)
{
   if ((row.Collumns["checkBoxColumn"].Content as CheckBox).IsChecked)
   {
      var newRow = dt.NewRow();
      newRow["Product Name"] = row["Product Name"];
      /*yadayada*/
      dt.Rows.Add(newRow);
   }
}

Let the data grid create the new row so that the columns are defined so that you just have to fill them individually, and then add it to the DataTable which will then sync to the DataGrid.


text:
Q: echo json_encode($return_data, JSON_NUMERIC_CHECK); character 'e' in digits not working one of row of my db has contacts table has character varying column as phone with value 3162e6313358
$return_data = array('phone' => $contact_phone);
echo json_encode($return_data, JSON_NUMERIC_CHECK);

this code does not give me any output.
I searched for this people gave solutions like ('phone' => '".$contact_phone."')
this is working.
I don't want to typecast for every array element
But i need generic solution.
Thanks.

A: Option 1 (the best)

*

*Convert numeric values (IDs, counts, numeric status codes, booleans a.s.o.) to numbers as soon as you get them from user input ($_GET[], $_POST[]) or from database. When they are extracted from user input the conversion should be part of the data validation anyway.

*Keep phone "numbers" as strings; they are not numbers, after all, they are just strings of digits, with or without starting zeroes and non-digit characters in the middle or at the end. Also keep as strings other values that looks numeric but are, in fact, not numbers: credit card numbers, for example.

*Remove the JSON_NUMERIC_CHECK parameter from the call to json_encode(); if you implement #1 above you don't need it any more.
Option 2 (workaround)
Append a space character (' ') to the phone number when you get it from the database. It won't make much difference (if any at all) when it is displayed in a web page.
json_encode() won't believe it is a floating point number any more, not even if it starts with + or 0.


text:
Q: psutil AttributeError: 'ModuleWrapper' object has no attribute 'NoSuchprocess' for myprocess in psutil.process_iter():
    try:
        myexe = myprocess.cmdline()
    except psutil.NoSuchprocess:
    myexe = None

This show an error
AttributeError: 'ModuleWrapper' object has no attribute 'NoSuchprocess'


text:
Q: how to implement flutter web push notification I'm wondering if I can implement push notification in flutter web?
I saw that I can create push notification for mobile app with firbase_messaging but is it possible to use it for web app? or any other alternative to accomplish it?

A: To implement push notifications and open the app on notification click you need to Change in three files.

1) Firebase-Messaging-sw.js

importScripts("https://www.gstatic.com/firebasejs/7.23.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.23.0/firebase-messaging.js");
firebase.initializeApp({
         apiKey: "",
           authDomain: "",
           projectId: "",
           storageBucket: "",
           messagingSenderId: "",
           appId: "",
           measurementId: ""
});
const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function (payload) {
    const promiseChain = clients
        .matchAll({
            type: "window",
            includeUncontrolled: true
        })
        .then(windowClients => {
            for (let i = 0; i < windowClients.length; i++) {
                const windowClient = windowClients[i];
                windowClient.postMessage(payload);
            }
        })
        .then(() => {
            const title = payload.notification.title;
            const options = {
                body: payload.notification.score
              };
            return registration.showNotification(title, options);
        });
    return promiseChain;
});
self.addEventListener('notificationclick', function (event) {
    console.log('notification received: ', event)
});

index.html

<!DOCTYPE html>
<html>
<head>
    <!--
      If you are serving your web app in a path other than the root, change the
      href value below to reflect the base path you are serving from.

      The path provided below has to start and end with a slash "/" in order for
      it to work correctly.

      Fore more details:
      * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
    -->
    <base href="/">

    <meta charset="UTF-8">
    <meta content="IE=Edge" http-equiv="X-UA-Compatible">
    <meta name="description" content="Share pictures and information with other collectors of historical artifacts">

    <!-- iOS meta tags & icons -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="Militrade">
    <link rel="apple-touch-icon" href="icons/Icon-192.png">

    <!-- Favicon -->
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico"/>
    <link rel="icon" type="image/x-icon" href="favicon.ico"/>

    <title>Militrade</title>
    <link rel="manifest" href="manifest.json">
</head>
<body>
<script>
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', function () {
     navigator.serviceWorker.register("/firebase-messaging-sw.js");
   });
  }
 </script>
<!-- This script installs service_worker.js to provide PWA functionality to
     application. For more information, see:
     https://developers.google.com/web/fundamentals/primers/service-workers -->
<!-- The core Firebase JS SDK is always required and must be listed first -->

<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
   https://firebase.google.com/docs/web/setup#available-libraries -->

<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-analytics.js"></script>

<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js"></script>

<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-auth.js"></script>

<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-messaging.js"></script>

<script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-storage.js"></script>

<script>
  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  var firebaseConfig = {
     apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  firebase.analytics();
</script>
<script src="main.dart.js" type="application/javascript"></script>
<script type="text/javascript">
    let useHtml = true;
    if(useHtml) {
      window.flutterWebRenderer = "html";
    } else {
      window.flutterWebRenderer = "canvaskit";
    }
  </script>

<script>
    if ("serviceWorker" in navigator) {
      window.addEventListener("load", function () {
        navigator.serviceWorker.register("/flutter_service_worker.js");
        navigator.serviceWorker.register("/firebase-messaging-sw.js");
      });
    }
  </script>

</body>
</html>

then create push_notification_services.dart file for send push notification

import 'dart:async';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;

final String serverToken =
    '';

Future<Map<String, dynamic>> sendPushNotification(
    {@required String message,
    @required String fcmToken,
    @required String title}) async {
  print(fcmToken);

  await http.post(
    Uri.parse('https://fcm.googleapis.com/fcm/send'),
    headers: <String, String>{
      'Content-Type': 'application/json',
      'Authorization': 'key=$serverToken',
    },
    body: jsonEncode(
      <String, dynamic>{
        'notification': <String, dynamic>{
           "click_action" : ".EditPostPage",
          'body': message,
          'title': '$title',
          'sound': 'default'
        },
        'priority': 'high',
        'data': <String, dynamic>{
          'click_action': 'FLUTTER_NOTIFICATION_CLICK',
          'id': '1',
          'status': 'done'
        },
        'to': fcmToken.toString().trim(),
      },
    ),
  );
  final Completer<Map<String, dynamic>> completer =
      Completer<Map<String, dynamic>>();

  return completer.future;
}

After 3 days I can do it and it's properly working well for me. hope it's helpful for you.

A: I'm considering that you've already set up a flutter-web project and have a firebase project.
In the flutter project folder, open index.html and place these scripts in the head section.
<script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-messaging.js"></script>

Then, in the body, append the code before main.dart.js script is loaded.
  <script src="./firebase-messaging-sw.js"></script>
  <script src="myjs.js"></script>
  <script src="main.dart.js" type="application/javascript"></script>

(where myjs.js is any file where you want to write code, but firebase-messaging-sw.js must be there.)
Now, create two files in the index.html directory:

*

*firebase-messaging-sw.js

*myjs.js (whatever name you chose)

In firebase-messaging-sw.js, just write
console.log("")

In myjs.js (again, whatever file name you chose), write following code:
var firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "~~~~~~",
    databaseURL: "~~~~~",
    projectId: "~~~~~~",
    storageBucket: "~~~~~~",
    messagingSenderId: "~~~~~~",
    appId: "~~~~~~~~~~~~~",
    measurementId: "~~~~~~~~~~~"
};

firebase.initializeApp(firebaseConfig);
firebase.analytics();

var messaging = firebase.messaging()

messaging.usePublicVapidKey('Your Key');

messaging.getToken().then((currentToken) => {
    console.log(currentToken)
})

You can find these credentials from the firebase console's project settings. You will find the firebaseConfig details in the web app you'd have added.
For the key, you'll have to generate a new pair. Go to the Cloud Messaging in the project settings, and there you can generate a new pair.
When you'll run your app (flutter run -d chrome), you can find your token in the console log. Copy that token.
From the Cloud Messaging Section from the side drawer, we can compose a new notification.
Enter whatever you like in title and text.
Click on send test message.
Paste the token you copied from console and click on Test.

You can see the notification popped up.
You can refer this article
and firebase documentation
for more info.


text:
Q: Regex: Difference Between [^A-Za-z\s] and \W\d When doing a regex search for alphabetical characters are [^A-Za-z\s] and \W\d equivalent? Is there a difference performance wise?

A: No, they aren't equivalent. \w is the equivalent to of A-Za-z0-9_.
The performance would depend on the engine that you are using, but I can't imagine there being much difference between the two.

A: No, they are not the same.  Try it with some test data and prove it to yourself.
\W is the negation of \w.  \w is "word character".  It does not include spaces, punctuation, etc.
[A-Za-z\s] is "The letters A-Z, upper and lower case, plus whitespace".  [^A-Za-z\s] is the negation of that.
Why are you asking about the difference between the two?  Are you hoping to speed up a search by using one instead of the other?  If so, it's very likely that your search is slow because of factors other than which of two very simple regexes you are using.


text:
Q: Full clear or fully clear I was describing the weather conditions. I used the following sentence:

The clouds were floated away by the wind.It was a fully clear sky.

I checked this sentence on Grammarly, which suggested me that this sentence should be:

The clouds were floated away by the wind. It was a full clear sky.

I think "fully" is more appropriate here, as it shows a degree of completeness. Since sky can be partially clear as well. Need suggestion for the suitable sentence out of two aforementioned ones.


text:
Q: Conditions for M to be a Positive-definite matrix let $M$ be a symetric $n$ by $n$ real matrix
on wikipedia it is said that all the eigenvalues of M are positve is equivalent  to $M$ being positive definite. which means that if a matrix $M$ is positive definite then $det(M)>0$ but our teacher told us today that the reciprocal is also true ($M$ is said to be a symetric positive definite matrix if and only if  $det(M)>0$) and I'm pretty sure this is wrong because $M$ could have some negative eigenvalues and at the same time a positive determinant.
please can someone shed some light on this and give me a solid counter exemple and tell when the reciprocal is true.
thank you

A: Determinant is just one of the leading principal minors. For $M$ to be positive definite all its leading principal minors have to be positive. I think, this is the easiest way to check positive definiteness. In the example above, the first leading principal minor is $-1$, thus this matrix is not positive definite.
Just as an example from Wikipedia:
$\begin{bmatrix}2&-1&0\\-1&2&-1 \\ 0 & -1 &2 \end{bmatrix}$.
First principal minor is just $\Delta_1 = 2 >0$. The second one is:
$\Delta_2 = \det\begin{bmatrix}2&-1\\-1 &2\end{bmatrix} = 4-1=3 > 0$
And finally, the last one is just the determinant of the whole matrix:
$\Delta_3 = \det \begin{bmatrix}2&-1&0\\-1&2&-1 \\ 0 & -1 &2 \end{bmatrix} = 4 > 0$

A: The matrix $\begin{bmatrix}-1&0\\0&-1\end{bmatrix}$ is not positive definite.


text:
Q: How to remove top comment lines with sed? I know how to delete all comments or delete specified row in file, but don't know how to delete only first top comment lines that hold author, copyright and etc. I can't just use delete first lines because there might be source files that does not con taint top comment block at all. Any suggestion?
UPDATE: The source files are objective-c files, and all top comment lines start with //. Probably the rule "delete all comment lines until first non-comment line will be found then stop" best describes what I would like to achieve.
Second question: Also, looking for a way to tell sed to loop recursively though all project directories and files.
UPDATE2. Here's an example of the comment block of objective-c file I'm trying to modify:
//
//  MyProjectAppDelegate.m
//  MyProject
//
//  Created by Name Surname on 2011-09-20.
//  Copyright 2012 JSC MyCompany. All rights reserved.
//

A: if awk is accepted as well, take a look at following:
 awk 'BEGIN{f=1}f&&/^\/\//{next;}{f=0}1' yourFile

test
kent$  cat test.txt
//
//  MyProjectAppDelegate.m
//  MyProject
//
//  Created by Name Surname on 2011-09-20.
//  Copyright 2012 JSC MyCompany. All rights reserved.
//
real codes come here...

// comments in codes should be kept

foo bar foo bar

kent$  awk 'BEGIN{f=1}f&&/^\/\//{next;}{f=0}1' test.txt
real codes come here...

// comments in codes should be kept

foo bar foo bar

you could combine find and the awk one-liner to do a recursive processing.
well sed can do that with same idea too. need to write a mark in Hold space, and check hold space for every line. It has an advantage with -i option, which allows you change your original file(s). however I feel awk is more straightforward to do the job. And saving changed text back to original file is not a hard thing either.

A: Here's a sed solution that works with Kent's test.txt:
sed -n '/^ *\/\//! { :a;p;N;s/.*\n//;ba}'

Output:
real codes come here...

// comments in codes should be kept

foo bar foo bar

Explanation
sed -n '/^ *\/\//!{    # if line does not start with //
  :a                   # label a
  p                    # print line
  N                    # append next line to PS
  s/.*\n//             # remove previous line
  ba                   # branch to a
}' < test.txt

A: try it:
sed '0,\#^\([^/]\|/[^/]\)\|^$# d'


text:
Q: In Python, what happens when you import inside of a function? What are the pros and cons of importing a Python module and/or function inside of a function, with respect to efficiency of speed and of memory?
Does it re-import every time the function is run, or perhaps just once at the beginning whether or not the function is run?

A: Importing inside a function will effectively import the module once.. the first time the function is run.
It ought to import just as fast whether you import it at the top, or when the function is run. This isn't generally a good reason to import in a def. Pros? It won't be imported if the function isn't called.. This is actually a reasonable reason if your module only requires the user to have a certain module installed if they use specific functions of yours...
If that's not he reason you're doing this, it's almost certainly a yucky idea.

A: The very first time you import goo from anywhere (inside or outside a function), goo.py (or other importable form) is loaded and sys.modules['goo'] is set to the module object thus built.  Any future import within the same run of the program (again, whether inside or outside a function) just look up sys.modules['goo'] and bind it to barename goo in the appropriate scope.  The dict lookup and name binding are very fast operations.
Assuming the very first import gets totally amortized over the program's run anyway, having the "appropriate scope" be module-level means each use of goo.this, goo.that, etc, is two dict lookups -- one for goo and one for the attribute name.  Having it be "function level" pays one extra local-variable setting per run of the function (even faster than the dictionary lookup part!) but saves one dict lookup (exchanging it for a local-variable lookup, blazingly fast) for each goo.this (etc) access, basically halving the time such lookups take.
We're talking about a few nanoseconds one way or another, so it's hardly a worthwhile optimization.  The one potentially substantial advantage of having the import within a function is when that function may well not be needed at all in a given run of the program, e.g., that function deals with errors, anomalies, and rare situations in general; if that's the case, any run that does not need the functionality will not even perform the import (and that's a saving of microseconds, not just nanoseconds), only runs that do need the functionality will pay the (modest but measurable) price.
It's still an optimization that's only worthwhile in pretty extreme situations, and there are many others I would consider before trying to squeeze out microseconds in this way.

A: It imports once when the function is called for the first time.
I could imagine doing it this way if I had a function in an imported module that is used very seldomly and is the only one requiring the import. Looks rather far-fetched, though...

A:
Does it re-import every time the function is run?

No; or rather, Python modules are essentially cached every time they are imported, so importing a second (or third, or fourth...) time doesn't actually force them to go through the whole import process again. 1

Does it import once at the beginning whether or not the function is run?

No, it is only imported if and when the function is executed. 2, 3
As for the benefits: it depends, I guess. If you may only run a function very rarely and don't need the module imported anywhere else, it may be beneficial to only import it in that function. Or if there is a name clash or other reason you don't want the module or symbols from the module available everywhere, you may only want to import it in a specific function. (Of course, there's always from my_module import my_function as f for those cases.)
In general practice, it's probably not that beneficial. In fact, most Python style guides encourage programmers to place all imports at the beginning of the module file.

A: It imports once when the function executes first time.
Pros:

*

*imports related to the function they're used in

*easy to move functions around the package

Cons:

*

*couldn't see what modules this module might depend on

A: Might I suggest in general that instead of asking, "Will X improve my performance?" you use profiling to determine where your program is actually spending its time and then apply optimizations according to where you'll get the most benefit?
And then you can use profiling to assure that your optimizations have actually benefited you, too.


text:
Q: IotHub message routed to Service Bus losing ContentType property? I'm trying to route device messages coming to IotHub using message routing based on message properties. I'm routing them to a service bus topic. However, I'm seeing that despite setting the ContentType property of the

Microsoft.Azure.Devices.Client.Message

class before sending to IoTHub, the same property is not seen populated for the Brokered message that comes after message routing succeeds.
Is there something I'm missing here?
Code at device side:
Message message = new Message(payload);
message.ContentType = "application/jsonstream";
await this.deviceClient.SendEventAsync(message);

Code at receiver side:
BrokeredMessage msgFromDevice = MessageReceiver.ReceiveAsync();

Now the problem is

msgFromDevice.ContentType

is null.
Any ideas or guidance in this?
Thanks!

A: this is a bug and it has been already reported - see more details here.


text:
Q: how to create custom object in salesforce using soap api in java I have a requirement to create custom object using soap API.
                        Please help me
                                   Thanks

A: Using Metadata API you can create new Objects.
Please refer http://www.salesforce.com/us/developer/docs/api_meta/


text:
Q: Web Inspector network tab shows Laravel resonse in two different colors: red and black I am using laravel 5.5. When I send response back from the controller in the console the response has been split into two different colors, red and black. when I loop through the response it only shows me those data which is red color, however, for the black it shows undefined in my view.
One more things friends, I have already used the Response facades in my controller.I have never encountered such error before while using laravel. This is my first time to face such type of error.
I have attached an image of my console section of my browse. Thank you very much.
**My Route:**
Route::post('/orders/change',[
            'uses'=> 'ProductController@change',
             'as'  => 'order.change'
        ]);

**My Ajax code:**
$("#sidebar_list li>a").on('click',function(e){
            e.preventDefault();
            var clickk  = $(this).attr('id');
            var clickk  = $(this).attr('id');
            var clickk  = $(this).attr('id');
            var clickk  = $(this).attr('id');
            var url_change = "{{ route('order.change') }}";
            $.ajaxSetup({
                headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $.ajax({
                url: url_change,
                type: 'POST',
                dataType: 'html',
                data: {clickk:clickk},
                success: function (data) {
                data = JSON.parse(data);
                var html;
                data = data.data;
                var numOfCols = 6;
                var rowCount = 0;
                var bootstrapColWidth = 12 / numOfCols;
                $.each(data, function (i, obj) {
                    var id = obj.id;
                    var name = obj.name;
                    html +='
';

                                html += '';
                                    html +='
';
                                        html +='
'+name;

                                        html +='
';
                                    html +='
';
                                html +='';
                            rowCount++;
                        if (rowCount % numOfCols == 0){
                         html+='

';
                        }

                    });

                     html +='
';
                $('#panel-name').html(html);
                }
             });
        });

**Controller Code:**
public function change(Request $request){
        if ($request->ajax()) {
            $clickk = $request->get('clickk');

              return  $result = DB::select("SELECT * FROM slots WHERE slot_type

Console Output
So what is the reason please help me out. Thanks in Advance.


text:
Q: Application in the background I have a code for communicating between a phone and an Arduino to make an alarm for a scooter. My problem is that I don't know how to make the program run in the background (when the phone is in sleep mode or the app is closed).this application will be improved as at the moment it only receives and sends messages.
Sorry for the mistakes, I speak Russian.
Processing Code:
import hypermedia.net.*;
UDP udp;

void setup() {
  fullScreen();
  udp = new UDP( this, 8888);
  udp.listen( true );
}

void draw()
{
  background(0,49,83);
  delay(1000);
  send();
}

void send() {
  String ip       = "192.168.4.1";
  int port        = 8888;

  udp.send("01100111 01100101 01110100 01110110 01100001 01101100 01110101 01100101", ip, port );
}

void receive( byte[] data ) {
  String value=new String(data);
  println(value);
}


text:
Q: Canonical way to represent idea of sum type of records that all extend a "base" record I'm new to PureScript. I was searching for sealed classes in Purescript to get an idea of how one would implement this, but I don't think I have the necessary PS jargon yet.
What is the canonical way in PureScript to have a bunch of records that extend a "base" record, but then have one sum type representing a "sealed" collection of those.
Something like in Kotlin,
sealed class Glazing(val name: String, val area: Int) {
  class Window(val name: String, val area: Int, val frameMaterial: String): BaseGlazing(name, area)
  class Door(val name: String, val area: Int, val isPreHung: Boolean): BaseGlazing(name, area)
}

in TypeScript, you'd probably do something like
interface BaseGlazing { ... }
interface Door extends BaseGlazing { ... }
interface Window extends BaseGlazing { ... }
type Glazing = Door | Window

and then you'd either take `A extends BaseGlazing` or `Glazing` (and use type guards) to do either of those two above functions.

Essentially I want a base class (that is technically abstract), things that extend it, and then a sum type/discriminated union of the extensions so that way I can both write, say, changeName:: Glazing -> Glazing (premised on the base class having a name prop) but also do something like calculateTotalLightPenetration :: Array Glazing -> Number (premised on the discriminated union being one of Door or Window since light penetration will be a different formula for doors vs windows)

A: The idea of "inheritance" (aka "is-a" relationship) is technically possible to model in PureScript, but it's hard and awkward. And there is a good reason for it: inheritance is almost never (and I am tempted to say "never, period") the most convenient, efficient, or reliable way of modeling the domain. Even OOP apologists tend to recommend aggregation over inheritance these days.
One useful thing to observe is that you don't actually need inheritance. What you need is to solve some specific problem in your domain, and inheritance is just a solution that you naturally reach for, which is probably informed by your past experience.
And this leads us to an insight: the particular way to model whatever it is you're modeling would depend on what the actual problem is. Chances are, PureScript has a different mechanism for modeling that.

But if I base my thinking on the specifics you gave in your question (i.e. the changeName and calculateTotalLightPenetration functions), I would model it via aggregation: the "glazing" would be the surrounding type, and it would have, as one of its parts, the specific kind of glazing. This would look something like this:
type Glazing = { name :: String, area :: Int, kind :: GlazingKind }

data GlazingKind = Window { frameMaterial :: String } | Door { isPreHung :: Boolean }

changeName :: Glazing -> Glazing
changeName g = g { name = "new name" }

calculateTotalLightPenetration :: Array Glazing -> Number
calculateTotalLightPenetration gs = sum $ individualPenetration <$> gs
  where
    individualPenetration g = case g.kind of
      Door _ -> 0.3
      Window _ -> 0.5


text:
Q: Maintain value in Fileupload control in asp.net,C# i am using Fileupload and 3 dropdown control in update panel, 3 dropdown will be post back on dropdown selected index change event (i.e like Country,states and city... get the value from db as per country,states and city)
THE PROBLEM IS
While postback the filename path is gone from the file upload control(as expected/ or Default property).
I am converting the file to byte array, to store in the database from file upload control.
How can i retain the value or Is there any way to solve this issue.
Is there any ajax control for file upload or any free controls which retain the value after postback also...?
Or it is possible to set the value to file upload control during postback ?
Thnks in Advance

A: You can try to persist file upload value in hidden field between async post-backs using asp.net ajax event handlers.
Sys.WebForms.PageRequestManager.instance.add_beginRequest(BeginRequestHandler)
Sys.WebForms.PageRequestManager.instance.add_endRequest(EndRequestHandler)

function BeginRequestHandler(sender, args) {
  var fileUpload = document.getElementById('fileUpload');
  var hiddenUpload = document.getElementById('hiddenUpload');
  hiddenUpload.value = fileUpload.value;
}

function EndRequestHandler(sender, args) {
  var fileUpload = document.getElementById('fileUpload');
  var hiddenUpload = document.getElementById('hiddenUpload');
  fileUpload.value = hiddenUpload.value;
}

A: On post back you could hide the FileUpload control and show a Literal that displays the value of the file.
Then, if the user wants to change the uploaded file have them click a button and display the FileUpload control again.
This is how gmail does it.

A: You could wrap the drop down lists in their own update panel (either a separate panel, or a nested panel).
That would sidestep the problem neatly because only the panel with the drop down lists would be re-rendered when their events fire.
You may have to control which triggers cause which kinds of postback for the panels though, and you may have to set the update mode to conditional and manually manage when each panel updates. That depends on how you have the page arranged and all though. Most of the time though, you don't have to do anything special when using multiple panels.

A: The FileUpload provides a Property for the filename. Just cache it.
UploadedFile.FileName or something like this


text:
Q: On convergence of a series of expectations given almost sure convergence. Let $\{ X_n \}_{n \in \mathbb{N}}$ be a positive valued stochastic process that converges almost surely to an integrable random variable $X_{\infty}$ then is it true that
$$ -\infty < \sum_{n= 1}^{\infty} E[ X_{n+1} - X_n | X^n  ] < \infty $$
where $X^n= \{ X_n, X_{n-1}, \dots, X_1 \}$.  I know that almost sure convergence does not guarantee convergence in mean but I believe this statement is being used in a proof I am trying to understand, is it true?
EDIT: as pointed out by Marcus M, there are trivial counterexamples if some bounds on the means is not assumed. So I would add the assumption that $E[ X_{n+1} | X^n  ]  < \infty \ \forall{n \in \mathbb{N}}$ and $E[X_1] < \infty$ to keep the question relevant.

A: I think you can come up with a super basic that breaks this: let $X_1$ be any random variable with $E[X_1] = +\infty$, and let $X_j = 1$ for all $j \geq 2$.


text:
Q: Deadlock with System.out.println and a suspended thread The following code causes a deadlock on my OSX Mavericks, I do not see the "resuming" string printed so expecting that to be the reason. I understand suspend, resume may cause deadlocks but didn't expect it to be so simple to get there.
Any obvious reasons why?
Java version
java version "1.8.0_66"
Java(TM) SE Runtime Environment (build 1.8.0_66-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.66-b17, mixed mode)
class TestThread {
    public static void main(String args[]) throws InterruptedException {
        Thread t = new Thread() {
            public void run() {
                while (!isInterrupted()) {
                    System.out.println("looping");
                }
            }
        };

        t.start();
        Thread.sleep(1000);
        t.suspend();
        Thread.sleep(5000);
        System.out.println("resuming");
        t.resume();
        Thread.sleep(2000);
        t.interrupt();
    }
}

A: I has just read a book, and know why it makes deadlock.System.out.println() method is a synchronized method, here is its code:
/**
 * Prints a String and then terminate the line.  This method behaves as
 * though it invokes {@link #print(String)} and then
 * {@link #println()}.
 *
 * @param x  The String to be printed.
 */
public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
}

so when the thread t is suspending, it maybe run into the println method, and lock the PrintStream instance, so when the main thread runs System.out.println("resuming");, the main thread will be blocked.
chang your code to this:
    //System.out.println("resuming");
    t.resume();
    Thread.sleep(2000);
    t.interrupt();
    System.out.println("end");

you will get it normal, hope to help you.

A: First of all, suspend and resume are deprecated, the compiler is telling you not to use them. Expect the unexpected.
Now, you're spamming the console with "looping" as fast as possible, so "resuming" is getting spammed off screen. So you never see it, and it leaves the buffer of the console.
If I comment out the printing of "looping", or print in intervals of 500 milliseconds, I can see "resuming" just fine.


text:
Q: Proof of the Weierstrass M-Test Our book denotes the Weierstrass M-Test as :
Let $M_n > 0$ be a real number satisfying $|f_n(x)| \leq M_n$. If $\sum M_n$ converges, then $\sum f_n$ converges uniformly on A.
Is the M chosen in the test presumed to be a constant for all terms, or a sequence of constants? Because I know if the M is a constant the entire time, I can use that it is Cauchy and prove the test relatively simply.

A: $M_n$ is a sequence dependent on $n$ bounding $f_n(x)$
for all $n \in \mathbb{N}$ so $M_n$ can be a constant sequence as long as it can bound $f_n(x)$.


text:
Q: Accidentally changed wp url in settings I accidentally changed wp url in settings and now I am locked out of my wp-admin dashboard for WP. I have found a lot of tutorials on fixing, however they only work if your host is supporting cpanel for database. My question is, how can I access database if I was given name, password, host etc. I have also access to a server with all the stored data. Thanks in advance.

A: Already got it! I just needed to download sql buddy to the server and access the database then just change the url.

A: You can recover from this with FTP access; you can use MySQL/database access, but it's not required.
With FTP access, you can add a few lines to either wp-config.php or the theme's functions.php file.
Use this in wp-config.php to "hardcode" the URLs you need, i.e. the site URLs before you changed them in settings:
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');

Or in the theme's functions.php file:
update_option( 'siteurl', 'http://example.com' );
update_option( 'home', 'http://example.com' );

See Changing The Site URL « WordPress Codex for more details about these and other recovery methods.


text:
Q: Problems creating a custom volume control for HTML5 Video I have a fairly complex project in the works that requires a custom volume slider to control an HTML5 video element.  I've boiled the volume control down to a very simple example and I see no reason why it should not be working.  I would love any insight regarding the following code:
jQuery:
<script>
$(function() {
    $('#volume').change(function () {
        newvolume = $('#volume').attr("value") / 100;
        $('#video').attr("volume", newvolume);
        console.log($('#video').attr("volume"));
    });
});
</script>

HTML:
<video id="video" controls="controls">
    <source src="http://dev.domain.com/media/16514.m4v">
</video>

<input id="volume" type="range" min="0" max="100" value="100" />

It should be noted that every aspect of this appears to work except an audible change in volume on the video clip.  Even the console.log result is returning the correct value (0 through 1.00)  I have also tried the strictly Javascript version of this, i.e. videoElement.volume = newvolume
If it's significant, I am testing in Safari 5.1.2.

A: Instead of $('#video').attr("volume", newvolume);, try this:
$('#video')[0].volume = newvolume;

If memory serves, volume is not an attribute of video in HTML5, it is only accesible via the DOM element itself.


text:
Q: How to interpret the direct comparison of Continuous Rank Probability Score (CRPS) and Mean Absolute Error (MAE)? Say I have a trained Random Forest (RF) consisted of $m$ decision trees and I am interested to estimate $y$ from $t_1$ to $t_n$. The good thing about RF is that I have an ensemble of estimators and a deterministic estimator in one place.
After using RF for estimation, I calculate the MAE for RF, and I calculate the CRPS for ensemble members of RF: $m$ decision tree regressors.
CRPS is a probabilistic measure that seeks to evaluate the accuracy of the ensemble, and MAE targets the same quality but for the deterministic model.
Is there any point in comparing these two metrics? What could be the intuition behind say: my CRPS is slightly smaller than MAE in this case.
I don't have any statistical muscle, but my gut feeling is that this is a vague comparison: Accuracy of an ensemble vs accuracy of single model. They are not meant to compete, they don't belong to the same world. ensemble is targeting to resemble the distribution of y, while the deterministic model is after the average of y.
I hope I could express my confusion in a not confusing way.

A: You are mistaken. The CRPS ("Continuous Ranked Probability Score") is an example of proper scoring-rules. It evaluates a full predictive density.
But your $m$ trees do not output a full density! Instead, each separate tree gives you its best forecast for a single point prediction (which will depend on the loss function it minimizes, so it will probably be an estimate of the future expected value, cf. Kolassa. 2020, IJF). So the variation you see in your $m$ tree forecasts is not an estimation of the future variability in the observables, but the variability in the (unobservable!) mean!
Thus, it doesn't make sense to apply the CRPS to the ensemble point predictions of your $m$ trees in the first place, because these do not form a density forecast for the observables!


text:
Q: How to Fixing error that outputs ? I'm currently making a small game, and I'm working on the points system. I put this at the beginning of the program:
points = 0

Then, I made a function so that the player can call it at any time to see how many points they have gathered:
def points():
    print(f'You have {points} points.')

It all seems fine, until I call the function. Instead of the output I want, which would be 0 since no points have been accumulated, it prints this out:
You have <function points at 0x000001DF208A9D30> points.

I've tried to use str() and string concatenation, but either it doesn't work at all, or it prints out the exact same type of error. Any help would be appreciated, and I'm sorry if it seems like too much of a basic question, I am just a beginner! :)

A: You need to rename either the variable or the function name.

A: Try doing something like this:
userPoints=0
# ... More functions and variables here
def callPoints():
    return userPoints

Thanks, Robin Zigmond and azro for pointing out the error!


text:
Q: Lenovo IdeaPad A1 Tablet - Micro USB or Mini USB? What kind of USB port does the Lenovo IdeaPad A1 tablet have? The title description says "micro usb" but "mini usb" is mentioned in the info text below: http://www.amazon.ca/Lenovo-7-Inch-Ideapad-Tablet-Micro-USB/dp/B005UBT7LW

A: http://www.lenovo.com/products/us/tablet/ideapad/a1/ says

Micro-USB connector

I would go with lenovo's specs.

A: It says a mini USB... But the picture is a micro USB...
Here is the product sheet, Here is a link to the wikipedia about micro and mini usb

A: From the photos, I'd say Micro-B.


text:
Q: Subsets of sets containing empty set Why is $\{\emptyset\}$ not a subset of $\{\{\emptyset\}\}$?
It contains this element, but why is it not a subset?

A: It is not a subset because its element $\emptyset$ does not belong to the set $\{\{\emptyset\}\}$.

A: The element $\{\emptyset\}$ and the element $\emptyset$ are different.
$\{\emptyset\}$ is an element of $\{\{\emptyset\}\}$, whereas $\emptyset$ is not.
A subset is a set whose every element is also a part of the given set.
Thus, the subsets of $\{\{\emptyset\}\}$ are $\{\{\emptyset\}\}$ and the empty set $\{\}$, also denoted by $\emptyset$.
EDIT:
In one sentence, (Thanks to @Henry)
$\{\{∅\}\}$  has a single element $\{∅\}$ and two subsets $\{\{∅\}\}$ and $∅$, while $\{∅\}$ has a single element $∅$ and two subsets $\{∅\}$ and $∅$.

A: You can think of sets like plastic bags if you want; the empty set is just a plastic bag with nothing in it, $\{\emptyset\}$ is a plastic bag with another plastic bag in it, and $\{\{\emptyset\}\}$ is three layers of plastic bags.
The element relation $A\in B$ means that you could open up bag $B$ and take out $A$.
The subset relation $A\subset B$ means that every object that you could directly take out of $A$ can also be directly taken out of $B$.
So, look at $\{\emptyset\}$. You can "open it up and" take out $\emptyset$, but you can't do that with $\{\{\emptyset\}\}$. Therefore, $\{\emptyset\}\not\subset \{\{\emptyset\}\}$.


text:
Q: A parallelism issue I've written 3 different ways of computing a sum of an array of integer, however, I'm getting a different result for the third method.
Initialization:
        int n = 100;
        int[] mArray = new int[n];
        for (int i = 0; i < mArray.Length; i++)
            mArray[i] = 1;

First:
        int sum1 = mArray.Sum();
        Console.WriteLine("sum1 " + sum1);

Second:
        int sum2 = 0;
        for (int i = 0; i < mArray.Length; i++)
            sum2 += mArray[i];
        Console.WriteLine("sum2 " + sum2);

Third:
        int sum3 = 0;
        Parallel.ForEach(mArray, item =>
        {
            sum3 += item;
        });
        Console.WriteLine("sum3 " + sum3);

Obviously, the 3 approaches gave the same output as seen below :

However, when n is increased (e.g., n = 30000), the third approach gives surprisingly false results

NB: I've tested the approaches using ConcurrentBag which is a thread-safe collection. I suppose, there is no overflow issue. The code is tested on a windows 10 x64 computer (Intel core I-7 @ 3.30ghz)
It would be interesting to understand why Parallel.For behaves differently.

A: The problem is that sum3 is accessed by multiple threads when you use Parallel.ForEach. sum3 += item; would normally involve three operations:
1. Read the value of sum3 into a temporary storage.
2. Increment the value of that storage with item;
3. Store the result back to sum3.
When multiple threads to this concurrently, it is very likely that operations will get mixed.  For example, if you have two threads, A and B, both may read the same value from sum3, then do their adding and store the new values back.
To overcome this issue, you need to protect you access to sum3.  The code should look like this:
 object objLock = new object();
 int sum3 = 0;
 Parallel.ForEach(mArray, item =>
 {
     lock (objLock) { sum3 += item; }
 });
 Console.WriteLine("sum3 " + sum3);

But, that will totally negate the effect of the parallel execution.

A: I'have Nick's solution and it fixed the problem, however, there was a performance issue when using
lock (objLock) { sum3 += item; } directly in the Parallel.ForEach, as shown in the figure below

Fortunatly, using Parallel Aggregation Operations, as properly defined in .Net solved the issue. Here is the code
        object locker = new object();
        double sum4= 0;
        Parallel.ForEach(mArray,
                        () => 0.0,                 // Initialize the local value.
                        (i, state, localResult) => localResult + i, localTotal =>   // Body delegate which returns the new local total.                                                                                // Add the local value
                            {
                                lock (locker) sum4+= localTotal;
                            }    // to the master value.
                        );


text:
Q: Create a dictionary by filtering two lists with LINQ I need a way to create a Dictionary<key, value> by filtering data from two lists using a linq statement. For example:
list1: { 1, 2, 3 }
list2: { <apple, 1>, <peach, 3> }

final dictionary should look like this: { <1, <apple, 1>>, <3, <peach, 3>> }
2 in list1 shall be skipped
Please any ideas how to solve this issue by using linq?

A: Join lists and put result into a dictionary
var d = list1.Join(list2, i=>i, o=>o.Id, (i,o)=>o)
             .ToDictionary(o=>o.Id);

try if with a fiddle

A: You can use SelectMany if you want:
var result = (from l1 in list1
              from l2 in list2
              where l1 == l2.Id
              select new
              {
                  Id = l1,
                  Name = l2.Name
              }).ToDictionary(k=>k.Id, v=>v.Name);

A: You can use Enumerable.Zip to merge two lists into one, and then Enumerable.ToDictionary to generate the dictionary.
Something like:
var result = list1.Zip(list2, (l, r) => Tuple.Create(l, r))
                  .ToDictionary(v => v.Item1, v => v.Item2);


text:
Q: SSRS Subreport's dataset run multiple times I have a subreport which use a parameter from main report to filter the data. The subreport's dataset is the same but SSRS keep making call to SQL to get it for every parent in main report.
I already set the cache for all dataset and set the parameter as not used by query.
Is there anyway to set the subreport's dataset run only one and then filter the data in subreport using the parameter?
Here is an example of my query
Main Report: Select ClassID, ClassName from Class (Dataset 1)
Sub Report: Select ClassID, StudentName from Student (Dataset 2)
Main report will pass ClassID as parameter to Sub report. Sub report will use it as a filter for Dataset 2 and return StudentName with same ClassID in subreport
My issue is if Dataset 1 return 8 rows, then the Subreport will run Dataset 2 8 times.

A: Have you tried using a separated dataset? I had a similar problem once and it turned out being some kind of loop.

A: If you use a dataset filter instead of a report parameter, it will be able to take advantage of the report cache.


text:
Q: Uniqueness problem for surfaces with given Gauss curvature We know that the curvature and the torsion of a curve determine uniquely the curve itself (up to position in space). Now what about surfaces. E.g., are there connected surfaces with constant positive Gaussian curvature $ +1 $ which are not (isometric to a subset of) the sphere?
And, more in general, under which additional conditions is a surface uniquely determined?
This is a question that arose in my personal thoughts, and I have no clue on how this problem can be solved; I think it is something that exceeds the status of "exercise".
Thank you in advance.

A: Except for translations/rotations a surface  is uniquely defined in space if the first and second fundamental forms are given. If the first form (FF) alone is given a set of inter-bendable surfaces is defined.They share anything you can define or name from the coefficients of FF, for example Gauss or geodesic curvature, integral curvature, the geodesic lines, Christoffel symbols and any object that can be assembled with them, which are all invariant in isometric mappings.

A: Liebmann's theorem states that any compact surface which has constant Gaussian curvature is (isometrically) a sphere.
As the other answer states, this is a special case; most surfaces need not so rigid. Probably the two most famous specific examples are:

*

*Any developable surface (such as a cylinder or a cone) has Gaussian curvature everywhere zero, but need not be planar.

*The helicoid and the catenoid have the same Gaussian curvature as each other, meaning they have the same intrinsic geometry despite being clearly non-isometric as surfaces embedded in $\Bbb{R}^3$.


text:
Q: Minus value from python list dob_list = ['01-Jan-1990', '11-Aug-1995', '15-Apr-1982', '20-Mar-1988', '25-Nov-1976', '07-Dec-1965',
         '18-Dec-1977', '25-May-1994', '09-Oct-1981', '19-Feb-1981']

I have split up each element within the list to obtain the year
how do i deduct the birth year from current year?  (Eg 2021-1990)
results to be copied into the empty dictionary age[]
Heres my code:
year = 2021
age =[]
dob = []

for x in dob_list:
    age +=x[7:11].split("-")
print(age)

A: I suggest using datetime module in order to be able to compute the exact date and avoid splitting issues of your date strings.
The function calculate_age allows you to compute the exact age of a person. Credits to this answer.
Below is the full code.
import datetime

dob_list = ['01-Jan-1990', '11-Aug-1995', '15-Apr-1982', '20-Mar-1988', '25-Nov-1976', '07-Dec-1965', '18-Dec-1977', '25-May-1994', '09-Oct-1981', '19-Feb-1981']

date_now = datetime.datetime.now()

age =[]

def calculate_age(date_now, born_date):
    return date_now.year - born_date.year - ((date_now.month, date_now.day) < (born_date.month, born_date.day))

for x in dob_list:
    date = datetime.datetime.strptime(x, '%d-%b-%Y')
    age.append(calculate_age(date_now, date))

print(age)
# Output: [31, 26, 39, 33, 44, 55, 43, 27, 40, 40]

A: You can use datetime and relativedelta from the dateutil package like below:
(you need to install pip install python-dateutil)
>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta

>>> dob_list = ['01-Jan-1990', '11-Aug-1995', '15-Apr-1982', '20-Mar-1988', '25-Nov-1976', '07-Dec-1965', '18-Dec-1977', '25-May-1994', '09-Oct-1981', '19-Feb-1981']

>>> [relativedelta(datetime.now(),datetime.strptime(dob, '%d-%b-%Y')).years for dob in dob_list]
[31, 26, 39, 33, 44, 55, 43, 27, 40, 40]

# for more explanation
>>> [relativedelta(datetime.now(),datetime.strptime(dob, '%d-%b-%Y')) for dob in dob_list]

[relativedelta(years=+31, months=+9, days=+13, hours=+16, minutes=+50, seconds=+14, microseconds=+585158),
 relativedelta(years=+26, months=+2, days=+3, hours=+16, minutes=+50, seconds=+14, microseconds=+585268),
 relativedelta(years=+39, months=+5, days=+29, hours=+16, minutes=+50, seconds=+14, microseconds=+585325),
 relativedelta(years=+33, months=+6, days=+24, hours=+16, minutes=+50, seconds=+14, microseconds=+585379),
 relativedelta(years=+44, months=+10, days=+19, hours=+16, minutes=+50, seconds=+14, microseconds=+585426),
 relativedelta(years=+55, months=+10, days=+7, hours=+16, minutes=+50, seconds=+14, microseconds=+585469),
 relativedelta(years=+43, months=+9, days=+26, hours=+16, minutes=+50, seconds=+14, microseconds=+585504),
 relativedelta(years=+27, months=+4, days=+19, hours=+16, minutes=+50, seconds=+14, microseconds=+585546),
 relativedelta(years=+40, days=+5, hours=+16, minutes=+50, seconds=+14, microseconds=+585587),
 relativedelta(years=+40, months=+7, days=+25, hours=+16, minutes=+50, seconds=+14, microseconds=+585620)]

A: You can simply get the last 4 characters of each string like this:
for i in dates:
    date = i[-4:]

But you must remember that year1-year2 doesn't return an age.
datetime

Otherwise, you can use the datetime module in the scope of getting the date, in particular a datetime.datetime.date object.
The input format should be something like dd-mm-yyyy.
from datetime import datetime

You can find a tutorial about this module here, and the documentation there.
Then you can look at this answer to better understand how to get how many year passed between two dates (in that case your date and datetime.datetime.now()).

A: If you dont want to use date time, and all you care about is the birth year, then you can simply convert it to an Integer and subtract it from the birth year.
year = 2021
age = [year - int(birthdDate[-4]) for birthDate in dob_list]


text:
Q: Link Netsuite Saved Search to Custom Field on Sales Order I am trying to create 2 custom fields on a Sales Order; to show the total number of items that are unfulfilled, and the total combined $ amount of those items.
I have been searching for awhile and the only help I could find is that this should be possible with a saved search.
So, I have created a saved search;

And I have created a custom transaction field (see below) which I believe is referencing my saved search, but how do I select which value it refers to? The field underneath where I selected my saved search BACKORDERS SUMMARY, doesn't appear to be related at all.

A: The Field dropdown below the Search is not for selecting from the search results field.  Summary Searches provide 1 summary value only.  If you want 2 different values, you need 2 different searches.
The Field dropdown is used to select the field from the current record to use as the filter for the saved search.  Assuming your custom fields are placed on the Sales Order, you'll want to set your Available Filters criteria to Internal ID and leave the Field dropdown on the custom summary search field blank. (ie: just select your search from the Search dropdown. NS will pass in the internal id when the record is loaded.)
Try splitting your Backorders Summary search into 2 different searches, each with a single summary result type, update the filters, and set the Search drop downs to the appropriate values.  Should work just fine.


text:
Q: Condition the execution of a flatmap in rxjs - angular 5 In rxjs I want to make a condition over multiple flatmap so I don't execute the second and third flatmap and I go directly to the subscribe :
this.authenticationAPI.getUser()
       .flatmap(response1 => if(response1 != null) // I want to go directly to subscribe
       .flatmap(response2 => return observable2(response2))
       .flatmap(response3 => return observable3(response3))
       .subscribe(response 4 => console.log(response4));

I thought about passing null observables to the second and third flatmap but is there any other solution?

A: You should separate to 2 cases: failure and success using filter. This way is more declarative and easier to read
const response$ = this.authenticationAPI.getUser();

// failure
response$
  .filter((res) => !res)
  .subscribe(() => {
    console.log('Unauthentication')
  });

// success
response$
  .filter((res) => res)
  .flatmap(response2 => return observable2(response2))
  .flatmap(response3 => return observable3(response3))
  .subscribe(response 4 => console.log(response4));

A: You'd be best served by nesting your flatmaps slightly - this example uses RxJS 5.5/6 "pipe" operators, if you're using an earlier version of RxJS you'll need to translate this slightly to map to the older syntax (comment if needed and I'll add an example):
this.authenticationAPI.getUser().pipe(
    map((response1) => {
        if (response1 != null) return of(response1);
        else return of(response1).pipe(
            flatMap((response2) => observable2(response2)),
            flatMap((response3) => observable3(response3))
        )
    })
).subscribe(response1or4 => console.log(response1or4));


text:
Q: Setting up psgreek fonts for betababel I'm using TeX Live (Debian) with betababel to insert ancient greek text. Since I'm required to use a sans-serif font, I wanted to change the greek font with the psgreek package to find one that fits Helvetica.
For some reason, choosing a font from psgreek has no effect at all.
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[polutonikogreek, english]{babel}
\usepackage[greek]{betababel}
\usepackage[
regular
%garamond
%oxonia
%oldface
%milan
%kerkis
%cmr
%cmss
%cmtt
]{psgreek}

\begin{document}
Test.
\begin{betacode}
*e)ge/neto de! e)n tai=s h(me/rais e)kei/nais e)ch=lqen

do/gma para! *kai/saros *au)gou/stou

a)pogra/fesqai pa=san th!n oi)koume/nhn.
\end{betacode}
\end{document}

Everythings seems to be installed correctly, no error message is shown. The document compiles without any problem, except it always shows the default greek font, whatever option from psgreek I coose.
Whether latex or pdflatex is used, makes no difference.
Anyone got an idea how to solve this? Thanks!

A: May I gently point out that package authors spend a great deal of time and effort to document their packages so that users can use them effectively? When something does not work, therefore, it is almost always a good idea to start by looking at the manuals of the packages you are using.
For the record, I'd never heard of betababel or psgreek before. So if I can identify a problem in your example code in 2 minutes by opening the documentation, you probably could have done the same thing in a fraction of the time it took to write the question.
Also for the record, yours is a far, far, far better question than many, especially most first questions. So this is really by way of expressing a general gripe.
betababel's manual notes the following on page 3:

Since betababel internally loads the babel package by itself, there
  must not be a \usepackage[...]{babel} command in your document
  preamble.

The manual totals a whopping 7 pages, including the abstract and contents on page 1 and the change log on the last 1.5 pages. So it is hardly in that class of manuals so overwhelming you need another manual to help you find your way through the first one.
EDIT
If you load the options for Babel as class options, betababel can still load babel as it wants. Alternatively, you can pass the options for babel as options when loading betababel.
I don't have psgreek. However, the Greek Font Society offers several options, some of which support Latin script as well as Greek.
For example,
\documentclass[polutonikogreek, british]{article}
\usepackage[utf8]{inputenc}
\usepackage[LGR,T1]{fontenc}
\usepackage[default]{gfsneohellenic}
\usepackage[greek]{betababel}

\begin{document}
Test.
\begin{betacode}
*e)ge/neto de! e)n tai=s h(me/rais e)kei/nais e)ch=lqen

do/gma para! *kai/saros *au)gou/stou

a)pogra/fesqai pa=san th!n oi)koume/nhn.
\end{betacode}
\end{document}

A: If your goal is only to typeset your text with a sans font, and you don't mind the CM family, you may try this preamble:
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[polutonikogreek,english]{babel}
\usepackage{betababel}
\let\rmdefault\sfdefault

The trick is in the last line.
Both betababel and psgreek are rather old (2005 and 2007, respectively), and the babel/greek interface has changed in the meanwhile, so they need a major overhaul. Please file a bug report to the corresponding maintainers.
As a workaround, you may try to add the textalpha (for LGR encoding) and substitutefont packages and say, v.gr.
\substitutefont{LGR}{\sfdefault}{hml}

to setup the milan Greek font, which is the only "sans" font in the psgreek bundle, afaik.
\usepackage{textalpha,substitutefont}
\substitutefont{LGR}{\sfdefault}{hml}
\begin{document}
With the LGR encoding:

\ensuregreek{>en >arq'h <=hn <o l'ogoc}

And with Beta Code:

\begin{betacode}
*e)ge/neto de! e)n tai=s h(me/rais e)kei/nais e)ch=lqen

do/gma para! *kai/saros *au)gou/stou

a)pogra/fesqai pa=san th!n oi)koume/nhn.
\end{betacode}
\end{document}

You may need to fix a small bug in betababel.sty, line 386: it says
      $ifnum$suffix@=58$@ddToText{s}%

it should say
      $ifnum$suffix@=58$@ddToText{c}%

Output:

A: I'm aware this does not directly answer the question, and involves using Unicode, which apparently is not possible ... but XeLaTeX would be so much easier, e.g.:
\documentclass[12pt]{article}
\usepackage{fontspec,xunicode}

\newfontfamily{\Gksf}{Gentium Plus}
\newfontfamily{\Gksa}{Fira Sans}

\begin{document}

Serif (Gentium Plus):\\
{\Gksf Ἐγένετο δὲ ἐν ταῖς ἡμέραις ἐκείναις ἐξῆλθεν δόγμα παρὰ Καίσαρος Αὐγούστου ἀπογράφεσθαι πᾶσαν τὴν οἰκουμένην.}

Sans (Fira Sans):\\
{\Gksa Ἐγένετο δὲ ἐν ταῖς ἡμέραις ἐκείναις ἐξῆλθεν δόγμα παρὰ Καίσαρος Αὐγούστου ἀπογράφεσθαι πᾶσαν τὴν οἰκουμένην.}

\end{document}

Producing:

Posted just in case OP's restrictions might be relaxed.


text:
Q: Spark Job Chaining using Azure Data Factory V1 Suppose we have three spark jobs say S1,S2 and S3 .
I want to configure these two jobs in a way so that once S1 is complete successfully, then S2 should be invoked .
On the other hand ,if S1 is failed then S3 should be invoked .
How this can be done using Azure Data Factory V1 ?

A: If you could use v2, this is the v2 doc for activity dependency.


text:
Q: Trying to connect to Sentry ver 1.7.30 with Spring Boot ver 1.5.7 Hi I am getting confused with setting up old version of Sentry(ver 1.7.30) with current Spring Boot project(ver 1.5.7).
Here's my part of Gradle:
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-logging")
    compile("org.springframework.boot:spring-boot-starter-actuator")

    ...

    implementation 'io.sentry:sentry-spring:1.7.30'
    implementation 'io.sentry:sentry-logback:1.7.30'
}

application-local.yml
sentry:
  dsn: https://dsnPath

logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>

<!-- sentry -->
<configuration>
  <appender name="Sentry" class="io.sentry.logback.SentryAppender">
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
      <level>WARN</level>
    </filter>
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="info">
    <appender-ref ref="FILE"/>
    <appender-ref ref="Sentry" />
  </root>
</configuration>

When I run the project on local laptop, I can see some exception logs on console but they don't show up on Sentry. One thing I'm sure is..there's log4j2-spring.xml before I created logback-spring.xml file only for Sentry and this might be a problem?
(I followed the instruction on official page - https://docs.sentry.io/platforms/java/legacy/spring/ - and it didn't work. Maybe I made mistake regarding resolver.)
Thanks in advance!


text:
Q: End Javascript script after the code run 1000 times I'd like to know how can I stop Javascript script after it run 1000 times. Any suggestions appreciated.
Here's my code:

function run(){
  var first = document.querySelector(".stats-label");
  var next = document.querySelector(".shot-nav-next");

function simulateClick (elem) {
  var evt = new MouseEvent('click', {
    bubbles: true,
    cancelable: true,
    view: window
  });
  var canceled = !elem.dispatchEvent(evt);
  };

  if (first-pic.innerHTML == "View"){
    simulateClick(first);
    simulateClick(next);
  }
  else {
    simulateClick(next);
  }
}

setInterval((run),20000);

void 0;

A: something like this ?

var counter = 0;

function run(){
  var first = document.querySelector(".stats-label");
  var next = document.querySelector(".shot-nav-next");

  if(counter < 1000){
    if (first-pic.innerHTML == "View"){
      simulateClick(first);
      simulateClick(next);
    }
    else {
       simulateClick(next);
    }
   }
   counter++;
}

function simulateClick (elem) {
   var evt = new MouseEvent('click', {
      bubbles: true,
      cancelable: true,
      view: window
    });
    var canceled = !elem.dispatchEvent(evt);
 };

 setInterval((run),20000);


text:
Q: Convert a string of float arrays into an ndarray Imagine one has to convert an ndarray into a string, then he has to convert the string back into an ndarray. For example, you have this string:
[1.1463377809323188, -5.631205546574898, 2.2669977232047676][4.579898563059968, 7.903827618691004, -6.286433358859447]

How could one conver this into an ndarray like so:
[[ 1.14633778 -5.63120555  2.26699772]
 [ 4.57989856  7.90382762 -6.28643336]]

I was thinking of converting the str into a list, then convert the list into an ndarray. However, the str.split() method yield me this:
['[1.1463377809323188,', '-5.631205546574898,', '2.2669977232047676][4.579898563059968,', '7.903827618691004,', '-6.286433358859447]']

When I try split('[]') now i'm left with only one element in the list:
['[2.182687926670855, -6.165595264315509, 2.0514527771233135][-1.9916686860482642, 6.353279016100898, -2.237430822379459]']

A: This would work:
string = "[1.1463377809323188, -5.631205546574898, 2.2669977232047676][4.579898563059968, 7.903827618691004, -6.286433358859447]"
>>> [[float(x.strip()) for x in row.replace("[","").split(",")] for row in string.split("]") if len(row.strip())>0]
[[1.1463377809323188, -5.631205546574898, 2.2669977232047676],
 [4.579898563059968, 7.903827618691004, -6.286433358859447]]


text:
Q: How do I assign multiple issues to a project in github I cannot find an option for me to bulk select multiple issues and assign them to an project. I can only bulk assign labels and other stuff.

A: The quickest way I have found...
Projects -> [Your Project] -> + Add cards
(you can change the search filters to find any issues from here)
Click and drag is less intensive than clicking into each issue and assigning it but there should be a better way to do this

A: Github has added a way to bulk add issues to Beta Projects now. However, you still cannot bulk add issues to non-Beta Projects.


text:
Q: Rename a specific user's copy of a duplicate PostgreSQL database? According to PostgreSQL documentation you can rename a database by:
ALTER DATABASE name RENAME TO newname

When I type:
ALTER DATABASE popbio-v4.1.1-VB-2014-04-prod-03 RENAME TO popbio-v4.1.1-VB-2014-04-prod-04

There is no error and nothing changes. Maybe it is because there are two databases with the same name but with different users, and PostgreSQL does not know which user's database I am trying to rename?
How do I specify to PostgreSQL which user's database I am trying to rename? Or is this even the problem?

A: Please try:
ALTER DATABASE "popbio-v4.1.1-VB-2014-04-prod-03" RENAME TO "popbio-v4.1.1-VB-2014-04-prod-04";

this should work. At least it did locally:
postgres=# create database "popbio-v4.1.1-VB-2014-04-prod-03";
CREATE DATABASE
postgres-# \l
...
 popbio-v4.1.1-VB-2014-04-prod-03 | postgres      | UTF8      | de_DE.UTF-8  | de_DE.UTF-8 |
...
postgres=# ALTER DATABASE "popbio-v4.1.1-VB-2014-04-prod-03" RENAME TO "popbio-v4.1.1-VB-2014-04-prod-04";
ALTER DATABASE
postgres=# \l
...
 popbio-v4.1.1-VB-2014-04-prod-04 | postgres      | UTF8      | de_DE.UTF-8  | de_DE.UTF-8 |
...

Also on PostgreSQL you don't have user databases. Users can only have rights on special databases or can own them. Of course you cannot do this as a normal user without any gratings.


text:
Q: Can't use something like "me" or "this" keyword in wf4 xaml activity? We have implemented a class ActivityException, where the constructor accepts (amongst others) an argument of type System.Activities.Activity. This argument is used to create an error message that contains Activity.DisplayName and Activity.Id.
This works very fine for WF4 activities written in C#. Here I can use something like:
throw new ActivityException(this, ...)

But now I am implementing a WF4 activity in xaml format (i.e. using workflow editor). If I throw an exception here, I have to use the System.Activities.Statements.Throw activity. I filled the Exception parameter of this activity as follows:
new ActivityException(Me, ...)

But the workflow editor says: "'Me' is valid only within an instance method".
I also tried 'this' instead of 'Me', but this produces an error message, too.
Does anybody have an idea how to solve this problem?

A: If the form name is MainWindow for example you could do:
MainWindow mw = new MainWindow;
new ActivityException(mw, ...)

A: Even if such a thing eventually worked, the Me you were trying to access would be the Thrown activity and not any other. Moreover, it seems you're using exceptions to log something (?). That's not how you do such a thing.
Not knowing what you're trying to do I would advice you to take a step back a consider other approach. Two options:
1) Create your own activity, which receives said DisplayName and throws an exception:
public class ThrownActivityException : CodeActivity
{
    [RequiredArgument]
    public InArgument<string> ActivityDisplayName { get; set; }

    public override void Execute(CodeActivityContext context)
    {
        var displayName = ActivityDisplayName.Get(context);

        throw new ActivityException(displayName);
    }
}

2) Second option, and probably what you want. Considering you're trying to access runtime information (activity's Id) for logging purposes, check Workflow Tracking and its capabilities.


text:
Q: How do I delete the last printed line on Python? I've seen answers for deleting single characters, but that would take up a lot of room and I'd like this to work in a decent number of lines. I wish to make the impression of a moving cursor. This is the problem:
sys.stdout.write ('virus_prevention.fix_virus.attempt_enter')
sys.stdout.write('\033[2K\033[1G')
time.sleep(2)
print ('virus_prevention.fix.virus.|attempt_enter')
time.sleep(2)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.virus|.attempt_enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.viru|s.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.vir|us.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.vi|rus.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.v|irus.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.|virus.attempt.enter')

And this is the output:
virus_prevention.fix_virus.attempt_enter
[2K[1Gvirus_prevention.fix.virus.|attempt_enter
[2K[1Gvirus_prevention.fix.virus|.attempt_enter
[2K[1Gvirus_prevention.fix.viru|s.attempt.enter
[2K[1Gvirus_prevention.fix.vir|us.attempt.enter
[2K[1Gvirus_prevention.fix.vi|rus.attempt.enter
[2K[1Gvirus_prevention.fix.v|irus.attempt.enter
[2K[1Gvirus_prevention.fix.|virus.attempt.enter

Which is NOT what I'm looking for. All I ask for is what code do I replace the sys.stdout.write line with? As you can see if I choose to put sys.stdout.write rather than print it gets rid of the extra text at the beginning.


text:
Q: The Visual Studio Bitbucket extension is not pulling changes from repo My partner has set up a Bitbucket repo. I have setup the Bitbucket extension for Visual Studio 2017:

When I PULL or SYNC it only is bringing in the local code and not the changes from the repo.
What am I doing wrong? How do I fix it?


text:
Q: Vertical aligning text in overlay of image Having some trouble getting the desired effect on an image overlay with responsive image. What I want is upon hovering over the image, the colour block and text to appear as shown, but for the text to be in the vertical centre of the div. I have tried vertical-middle but it doesn't seem to be working. Can't make the width and height set value as need to collapse and expand. If anyone can help i'd appreciate it. Thanks
Code, CSS below

.overlay-box {
   position: relative;
}
.overlay {
  display: none;
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   bottom: 0;
   background-color: rgba(38,150,198,0.5);
}
.overlay p {
   color: #ffffff;
   text-align: center;
}
.overlay-box:hover .overlay {
     display: block;
}

1st line
2nd line

                          3rd line

A:

img{
max-width: 100%;
height: auto;
}
.overlay-box {
   position: relative;
}
.overlay {
  display: none;
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   bottom: 0;
   background-color: rgba(38,150,198,0.5);
}
.overlay:before {
content: '';
display: inline-block;
width: 1px;
height: 100%;
vertical-align: middle;
border: 1px solid;
}
.overlay p {
   color: #ffffff;
   text-align: center;
display: inline-block;
vertical-align: middle;
width: 90%;
}
.overlay-box:hover .overlay {
 display: block;
}

1st line
2nd line

                      3rd line

A: You need to wrap the overlay with another div(since tables seem to ignore their height and width when they're absolute) and add position:absolute to it. Then add dislpay:table and dislpay:table-cell; vertical-align:middle for the child divs.
Check out this fiddle: https://jsfiddle.net/65cvzcev/


text:
Q: Building an arc (an array of segments) at three points I have the coordinates of three points. I want to build an arc on them
An arc (non-ideal) consists of segments (let 10 segments).
I need having the coordinates of three points to get an array of arc segments at these points
How can I do this?

A: A way, definitely no the shortest way, could be the following.
You have 3 point, thus you can write the circonference equation(x2+y2+ax+by+c=0) (for three points pass only a circonference). This is a matter of solving a system of 3 equations in three unknowns. Now given the 2 outermost points,(x1,y1) and (x2,y2), you can calculate the cord length with Pitagora theorem:
cord = √(y2-y1)2+(x2-x1)2
Now use the theorem of the cord to find the angle in the center that I call alpha  thus:
sin(alpha/2) = cord/2*radius

Having the circonference equation is easy to calculate the radius.
Now that you have alpha you can split the angle in 20 parts. For example if alpha is 160 you get Beta=8
Now you can do:
P0 x1,y1
P1 cos(180-8),sin(180-8)
P2 cos(180-16),sin(180-16)
.
.
.

and so on until to 160 in my example.
But Attention!  Those above are relative coordinates, relative to the center of the circonference. Called the center (c1,c2) the coordinates will be:
P0 x1,y1
P1 c1+cos(180-8),c2+sen(180-8)
P2 c1+cos(180-16),c2+sin(180-16)
.
.
.


text:
Q: Как сделать такую структуру блоков? Ребята... помогите.
Постараюсь объяснить. К примеру на сайте есть два вида блоков.

Как вы видите на картинке блоки идут подряд 1,2,3,4,5
К примеру блок 3 стал в ширину как две обычные, и вверху получилось пустое место.
Как сделать так что бы в таких случаях блок 4 перемешался на пустое место.
masonry
isotop
Это все понятно. Как то это делается без этого?
Можно js css jquery как?


text:
Q: Return the same word repeated twice, followed by the length of the new doubled word I want to define a function
def double_word(word)
    return

where
print(double_word('Hello'))  # should be 'HelloHello10'
print(double_word('abc'))    # should be 'abcabc6'

A: def double_word(word):
    return word + word + str(len(word) * 2)

A: def double_word(word):
    result=word*2
    return result + str(len(result))

print(double_word("hello"))  # Should return hellohello10
print(double_word("abc"))  # Should return abcabc6
print(double_word(""))  # Should return 0

Output:
hellohello10
abcabc6
0

A: def double_word(word):
    word = word * 2
    return word + str(len(word))

A: def double_word(word):
    return word * 2 + str(len(word * 2))

print(double_word("hello")) # Should return hellohello10
print(double_word("abc"))   # Should return abcabc6
print(double_word(""))      # Should return 0

A: def double_word(word):
    return word + word +str(2*len(word))
print(double_word("hello")) # Should return hellohello10
print(double_word("abc"))   # Should return abcabc6
print(double_word(""))      # Should return 0
Here is your output:
hellohello10
abcabc6
0

A: all the above codes lead to pass the question, in my opinion to understand what u are doing to play around strings so I prefer to assign variable for how many time it ask me to repeat the word,
total_repeat = 2

and another variable for the length of word
total_len = word

and now call back them all together
return word * total_repeat + str(len(total_len*total_repeat))

and final code will be
def double_word(word):
  total_repeat = 2
  total_len = word
     return word*total_repeat + str(len(total_len*total_repeat))

A:    def double_word(word):
    return str(word*2)+str(len(word*2))

print(double_word("hello")) # Should return hellohello10
print(double_word("abc"))   # Should return abcabc6
print(double_word(""))      # Should return 0

A: def double_word(word):

 word=word*2

 return str(word)+str(len(word))

A: def double_word(word):
    return (word * 2) + str(len(word*2))

print(double_word("hello")) # Should return hellohello10

A: def double_word(word):

      word = word *2

      return word + srt(len(word))


text:
Q: How do divergences of vector fields generate distributions? Just to clarify the title before I start, there are some "fuzzy" words that I want to get out of the way:

*

*Divergence here is in the sense of the divergence theorem, the operator sometimes written $\operatorname{div} \vec F = \nabla \cdot \vec F = \partial_i F^i.$

*Distributions here are in the sense of generalized functions used to model, e.g., the Dirac $\delta$-function: linear functionals $(\mathbb R^n \to \mathbb R) \to \mathbb R$.

In a post on Physics.SE a user was asking about the first Maxwell equation, $$\operatorname{div} \vec E = 4\pi\rho.$$The central point of confusion is this: we are using this to generalize Coulomb's law, which states that in 3D, for a point source of charge $q$ located at a point $\vec r'$, the resulting electric field is $$\vec E_q(\vec r) = q~\frac {\vec r - \vec r'}{|\vec r - \vec r'|^3},$$ but unfortunately here $\vec E_q$ is an ordinary function (albeit from $\mathbb R^3 \to \mathbb R^3$) and its divergence, defined traditionally, is also an ordinary function, $\operatorname{div} \vec E_q : (\mathbb R^3 - \{\vec 0\})\to \mathbb R.$ However the right hand side above is not an ordinary function.
The right hand side above can, however, be interpreted as a distribution where the distribution-product for "ordinary functions" $\langle f, g\rangle = \int_{\mathbb R^3} dx~dy~dz~ f(x, y, z) ~g(x, y, z).$ We can apparently more or less extend this to vector spaces by just allowing some unit vectors $\hat x, \hat y, \hat z$ and assuming that they and their products commute on both sides with distribution products $\langle,\rangle.$
The problem here is essentially a type error in the physics: in this scenario $\rho$ can only be interpreted as a distribution, which seems to imply that either $\operatorname{div}$ maps vector fields to distributions, or else $\vec E$ is a distribution and $\operatorname{div}$ maps distributions to distributions.
Either way, we need a slightly different definition for divergence from the physicist's pragmatic version. How can we prove the divergence theorem under a type-corrected definition for $\operatorname{div}$ that can properly return a distribution for the Coulomb field $\vec E_q$? Are there any subtleties that appear as a result of the new definition?

A: In THIS ANSWER, I discuss regularizing the Electric Field of a point charge to assign meaning to the Dirac Delta for use in the Divergence Theorem. This provides a rigorous way forward where Dirac Delta is interpreted in terms of the limit of the regularized function $\vec \psi$ given by
$$\vec \psi(\vec r;a)=\frac{\vec r}{(r^2+a^2)^{3/2}} \tag 1$$
Taking the divergence of $(1)$ reveals that
$$\nabla \cdot \vec \psi(\vec r; a)=\frac{3a^2}{(r^2+a^2)^{5/2}}$$
Now, in the Aforementioned Answer, I showed that for any sufficiently smooth test function $\phi$, we have that
$$\lim_{a \to 0}\int_V \nabla \cdot \vec \psi(\vec r; a)\phi(\vec r)dV=
\begin{cases}
0&, \text{V does not include the origin}\\\\
4\pi \phi(0)&,\text{V includes the origin}
\end{cases}$$
and it is in this sense that
$$\bbox[5px,border:2px solid #C0A000]{\lim_{a\to 0} \nabla \cdot \vec \psi(\vec r;a)=4\pi \delta(\vec r)}$$


text:
Q: Ussing reCAPTCHA on HTML5 whit contact-form.php I have a website Html5 and try adding the reCaptcha still sending messages without activating the reCaptcha and last night I received over 300 messages a boot.
Help me please how to add so that only sent when the button is activated reCaptcha.
Send sends works well but not activation reCaptcha.
To start contact.html within my template I have put this way:

Formulario de contacto

                            <form action="php/contact-form.php" id="contact-form">

                                    Mensaje enviado correctamente!  Muchas gracias, pronto nos pondremos en contacto con usted, normalmente nuestro tiempo de respuesta es inferior a 2 horas.

                                    Error! A sucedido un error si lo desea puede contactarnos directamente en XXXX@tize.XXXX

                                            Nombre *
                                            <input type="text"
                                                value=""
                                                data-msg-required="Por favor introduzca su nombre"
                                                class="form-control"
                                                name="name" id="name">

                                            eMail *
                                            <input type="email"
                                                value=""
                                                data-msg-required="Por favor introduzca su eMail"
                                                data-msg-email="Por favor introduzca un eMail válido"
                                                class="form-control"
                                                name="email"
                                                id="email">

                                            Asunto *
                                            <input type="text"
                                                value=""
                                                data-msg-required="Por favor introduzca el asunto"
                                                class="form-control"
                                                name="subject"
                                                id="subject">

                                            Mensaje *
                                            <textarea
                                                data-msg-required="Por favor introduzca su mensaje"
                                                rows="10"
                                                class="form-control"
                                                name="message"
                                                id="message"></textarea>

                                        <input type="submit" value="Enviar mensaje" class="btn btn-primary" data-loading-text="Cargando...">

                            </form>

And in php form to send the messages have this post with contact-form.php :
    <?php
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));

header('Content-type: application/json');

// Enter your email address
$to = 'XXXX@tize.XX';

$subject = $_POST['subject'];

if($to) {
    $name = $_POST['name'];
    $email = $_POST['email'];

    $fields = array(
        0 => array(
            'text' => 'Name',
            'val' => $_POST['name']
        ),
        1 => array(
            'text' => 'Email address',
            'val' => $_POST['email']
        ),
        2 => array(
            'text' => 'Message',
            'val' => $_POST['message']
        )
    );

    $message = "";

    foreach($fields as $field) {
        $message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "
\n";
    }

    $headers = '';
    $headers .= 'From: ' . $name . ' <' . $email . '>' . "\r\n";
    $headers .= "Reply-To: " .  $email . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

    if (mail($to, $subject, $message, $headers)){
        $arrResult = array ('response'=>'success');
    } else{
        $arrResult = array ('response'=>'error');
    }

    echo json_encode($arrResult);

} else {

    $arrResult = array ('response'=>'error');
    echo json_encode($arrResult);

}
?>

Picture of my form, If anyone wants to see my website please let me know and send you the link. Thank you very much.
sending without activating the reCaptcha http://goo.gl/oSLQG9


text:
Q: Можно ли выгружать Json в несколько разных блоков? Всем добрый вечер.
столкнулся с проблемой и не знаю как ее решить, поэтому прошу помощи у вас.
есть некий Json файлик, который я вывожу вот таким вот образом.
var out = '';
    for (var key in data) {
        out += '
';

        out += `<img class="goods_img" src="${data[key].image}">`;

        out += `<p class="show_goods-category">${data[key].category}</p>`;
        out += '
';
    }
    $('#goods').html(out);    //вывод  информации в ('#goods')

на выходе получается вот такая картина.

'

Акция

'

в наличии

'

под заказ

и все выгружается в один блок ('#goods'). но это не совсем то что нужно
можно ли сделать что бы
все блоки у которых $('.goods-category') == "Акция" выгружались в контейнер с классом $('.stock-goods');
все блоки у которых $('.goods-category') == "в наличии" выгружались в контейнер с классом $('.in-stock-goods');
все блоки у которых $('.goods-category') == "под заказ" выгружались в контейнер с классом $('.order-goods');

буду очень благодарен за помощь.

A: можете попробовать так:
var out = '';
    for (var key in data) {
        out = '
';

        out += `<img class="goods_img" src="${data[key].image}">`;

        out += `<p class="show_goods-category">${data[key].category}</p>`;
        out += '
';

      // 1 варинт = тут через if выгружаете куда нужно
      if(data[key].category == 'action')
        $('.stock-goods').html(out);
      if(data[key].category == 'order')
        $('.order-goods').html(out);

      // 2 вариант формирует сразу класс
      $('.' + data[key].category '-goods').html(out);
    }

суть надеюсь понятна, в каждом цикле обновляете формируемый блок, и в конце итерации добавляете куда нужно.


text:
Q: Box2d objects with no friction somehow gaining velocity when colliding What my simulation looks like: image
all the circles just bounce around within the rectangle. The restitution for all objects is set to 1.f and friction is set 0.f.
Somehow though, because of the large amount of collisions that take place objects seem to be speeding up over time.
Is this due to floating point inaccuracies? How could I go about fixing this?

A: Use a greater than zero damping factor and/or drop the restitution from 1.f. Tweak these two settings till you get the desired effect. And yes, numerical inaccuracies will play into the effects seen.
The online Box2D 2.3.0 manual also offers the following insight:

When a shape develops multiple contacts, restitution is simulated approximately. This is because Box2D uses an iterative solver. Box2D also uses inelastic collisions when the collision velocity is small. This is done to prevent jitter. See b2_velocityThreshold in b2Settings.h.


text:
Q: Fix "invalid host header" in Angular I have an app in Angular v4 which have to change the scss dependong of the url of access.
For example:
if link in the browser is "example.com" then the app have background-color: black
if the link is"example2.com" then the background-color: red
I have the next problem:
when I go to the hosts in C:\Windows\System32\drivers\etc and I set the next configuration in hosts
127.0.0.1   example.com
127.0.0.1   example2.com
then I run the app with "example.com:4200" the app doesn't run... the browser show me this message
"invalid host header"
How do I fix this problem?

A: This appeared for me under angular 7.2.1
Assuming you're using the Angular CLI, the solution was to add the following line in angular.json under architect>serve>options:
"disableHostCheck": true

A: The Reason -
Most development-oriented application servers (such as ng, webpack-dev-server, or WAMPP) default to only binding to localhost (or in some cases blocking traffic directly).  Essentially, only traffic directed to your machine from itself is allowed to pass through, meaning that traffic passing through the tunnel will not work the same as traffic coming from your machine directly.  Even though it works on your machine, the way the server is set up makes it so that even other local machines cannot connect to it.
How do I fix it?
In most cases, the fix is to tell the server to restart and allow connections from outside localhost.

*

*ng (Angular) =>
Kill the server and restart it, adding
--host 0.0.0.0 --disableHostCheck true

to the command.

*Angular2 =>
Same as above, but add
--host 0.0.0.0  --disable-host-check

instead

*webpack-dev-server =>
Kill the server and restart it, adding
--host 0.0.0.0

to the command.
--disable-host-check is sometimes needed here as well.

A: You are probably using the webpack dev server.
It has options to set in webpack.config.js within devServer:

*

*host

*allowedHosts

*disableHostCheck
Perhaps one of those works for you?
Sources:

*

*I am getting an "Invalid Host header" message, when running my React app in a Webpack dev server on Cloud9.io

*https://webpack.js.org/configuration/dev-server/


text:
Q: How to select children but not the root element (with same name) in jQuery in my XML I have some child elements with the same name as the root element. I am looking for a way to select just those child elements, but not the root element. I've been looking through the jQuery selector documentation, and googled a bunch, but the only thing I can find is people who are facing the opposite problem: selecting children AND root, which is what is working perfectly fine (too fine :) ) for me!
Here is some example XML:
<myElement>
    <someElementWithVariableName>
        <someMoreVariationElement>
            <myElement>
                <leafNode1/>
                <leafNode2/>
            </myElement>
            <myElement/>
        </someMoreVariationElement>
    <someElementWithVariableName>
</myElement>

Now when I do the following I will get 2 objects: the root element and the 2 child elements of someMoreVariationElement:
$(inputXml).find("myElement")

I was wondering, maybe I can use
$(inputXml).find("myElement > *")

But that only works just in the cases where myElement is actualy the root element, but that is not guaranteed. It can be something else. Just like someElementWithVariableName and someMoreVariationElement, which can both be anything. So basically... I need a selector that will only get myElement if it is a child of something.
(It would be even better if it only selects all instances of myElement at level 3 (counting root as level 0, someElementWithVariableName as level 1, and someMoreVariationElement as level 2))

A: In this particular case, you should be able to use the following code. (Example using Divs)
$(inputXml).find("myElement:not(:first)")

A: Actually if myElement is the root element then it will not get included in the result set, as the find look under the selected node.
Quoting from the documentation of .find() docs

Description: Get the descendants of
  each element in the current set of
  matched elements, filtered by a
  selector.

What you need is $(inputXml).find("* > myElement")
But if the myElement is indeed nested (at any depth) under another myElement you will get both of those (assuming the parent is not the root as well..)


text:
Q: Nonsingularity of a matrix I have a smooth function $g(x) \colon \mathbb{R}^n \to \mathbb{R}$ that is homogeneous of order one: $g(\lambda x) = \lambda g(x)$. Let $(x_1,...,x_n) \circ (y_1,...,y_n) = (x_1 y_1,...,x_n y_n)$. Are there some sufficient conditions for
$$
  h(x,y) = \det \left\| \frac{\partial^2 g(x \circ y)}{\partial x_i \partial y_j} \right\| > 0
$$
I found that
$$
 h(x,y) = \det \left( \left\| \partial_{i,j} g(x \circ y) x_i y_j \right\| + \left\| \partial_{i} g(x \circ y) \delta_{i,j} \right\| \right)
$$
where $\partial_i g(x) = \frac{\partial g(x)}{\partial x_i}$.