text:
Q: Set current date for bootstrap calendar I'll have a restaurant reservation form with a date and time selection.
Now I have connected the bootstrap calendar here, everything works as it should and without problems.
The only thing I want is that initially when you go to the page where this form will be, the current day is automatically selected.
Now, when you click on the button, it shows the current day there, but it needs to be applied automatically.
I have a button, I renamed it to "click", when you press it, it opens the calendar and when you select the button, the date becomes, and I need the current date to be there automatically.
How can i do this?
I need to use datepicker('getDate') or something like this?

let restaurantReserve = {
  init: function() {
    let _self = this;

    $('#reservation-date').datepicker({
      startDate: '+0d'
    }).on('changeDate', function(e) {
      const arDate = e.date.toString().split(' ');
      $('#dayofweek').val(arDate[0]);
      filterTimes();
      let input = $('[name="RestaurantReservationForm[date]"]');
      input.val(arDate[3] + '-' + (e.date.getMonth() + 1) + '-' + arDate[2]);
      _self.unSetError(input);
      $('#reservation-date .js-value').text(arDate[2] + ' ' + arDate[1]);
    });

    $('[aria-labelledby="reservation-time"] li a').click(function() {
      $(this).closest('ul').find('a').removeClass('active');
      $(this).addClass('active');
      let input = $('[name="RestaurantReservationForm[time]"]');
      input.val($(this).data('value'));
      _self.unSetError(input);
      $('#reservation-time .js-value').text($(this).text());
    });
  },
  setError: function(ob) {
    $('#' + ob.data('btnId')).addClass('btn-error');
  },
  unSetError: function(ob) {
    $('#' + ob.data('btnId')).removeClass('btn-error');
  }
}
restaurantReserve.init();
let json = [{
  "id": 86,
  "restaurant_id": 1,
  "day": "Mon",
  "open": "4.30",
  "close": "6.30",
  "created_at": "2022-02-22 10:56:15"
}, {
  "id": 87,
  "restaurant_id": 1,
  "day": "Tue",
  "open": "4.30",
  "close": "6.30",
  "created_at": "2022-02-22 10:56:15"
}, {
  "id": 88,
  "restaurant_id": 1,
  "day": "Wed",
  "open": "4.30",
  "close": "6.30",
  "created_at": "2022-02-22 10:56:15"
}, {
  "id": 89,
  "restaurant_id": 1,
  "day": "Thu",
  "open": "4.30",
  "close": "6.30",
  "created_at": "2022-02-22 10:56:15"
}, {
  "id": 90,
  "restaurant_id": 1,
  "day": "Fri",
  "open": "4.30",
  "close": "6.30",
  "created_at": "2022-02-22 10:56:15"
}, {
  "id": 91,
  "restaurant_id": 1,
  "day": "Sat",
  "open": "4.30",
  "close": "6.30",
  "created_at": "2022-02-22 10:56:15"
}, {
  "id": 92,
  "restaurant_id": 1,
  "day": "Sun",
  "open": "4.30",
  "close": "6.30",
  "created_at": "2022-02-22 10:56:15"
}];

function getWorkHours(json, restaurant_id) {
  return json.filter(item => item.restaurant_id == restaurant_id);
}

function getWorkHoursForDay(json, restaurant_id, day) {
  return getWorkHours(json, restaurant_id).filter(item => item.day === day)[0];
}

function filterTimes() {
  let restaurantID = 1;
  let dayofweek = document.getElementById("dayofweek").value;
  if ((["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(dayofweek)) >= 0) {
    let workHours = getWorkHoursForDay(json, restaurantID, dayofweek);
    let items = document.querySelectorAll(".dropdown-menu.dropdown-menu-height-fixed li a");
    for (let item of items) {
      let itemValueParts = item.innerText.split(" ");
      itemValue = parseFloat(itemValueParts[0]) + (((itemValueParts[1] === "PM") && (itemValueParts[0] !== "00.00")) ? 12 : 0);
      item.parentNode.classList[((itemValue < parseFloat(workHours.open)) || (itemValue > parseFloat(workHours.close)) ? "add" : "remove")]("invisible");
    }
  }
}
.btn {
  border: none;
  border-radius: 8px;
  height: 40px;
  padding: 10px 15px;
  font-weight: 800;
  font-size: 14px;
  margin-right: 10px;
  cursor: pointer;
}

.btn-fourth {
  text-decoration: none;
  background: #e3e5e8;
  color: #747b8b;
}

.invisible {
  display: none;
}

ul.with-out>li:before,
.dropdown-menu li:before,
ul.whithout>li:before {
  display: none;
}

.dropdown-menu li {
  padding: 0;
}

.dropdown-menu-height-fixed {
  max-height: 200px;
  overflow-y: auto;
}

.dropdown-item.active,
.dropdown-item:active {
  background: red;
}

.block-shadow {
  box-shadow: 0 2px 8px 0 rgba(32, 35, 44, 0.05);
}

.block-white {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" rel="stylesheet">

<form id="reservation" action="/restaurants/123/" method="post">

Reserve a table

      ">
         click

      <select id="dayofweek" onchange="filterTimes()">
        <option>Please Select Day</option>
        <option value="Mon">Mon</option>
        <option value="Tue">Tue</option>
        <option value="Wed">Wed</option>
        <option value="Thu">Thu</option>
        <option value="Fri">Fri</option>
        <option value="Sat">Sat</option>
        <option value="Sun">Sun</option>
      </select>

04.30 AM

05.00 AM

05.30 AM

06.00 AM

06.30 AM

      <input type="hidden" id="restaurantreservationform-date" class="form-control" name="RestaurantReservationForm[date]" data-btn-id="reservation-date">

      <input type="hidden" id="restaurantreservationform-time" class="form-control" name="RestaurantReservationForm[time]" data-btn-id="reservation-time">

A: Add this in your script. The load function (or whatever name you give it) is here called upon once the window has loaded.
function load() {
  // stuff that should happen once the window has loaded
}
window.onload = load();

JQuery:
$( window ).on( "load", load() );

A: You can determine the current weekday and select the corresponding dropdown item.
Reference: https://stackoverflow.com/a/65588812/378779

$(document).ready(function() {
    $('a.btn').click(function() {
        let day = (new Date()).toLocaleString('en-us', {weekday: 'short'}); // E.g. 'Sat'
        $(`#dayofweek option[value="${day}"]`).attr('selected', true);
        // Might also need to call filterTimes() here
    })
});

Click

<select id="dayofweek">
    <option>Please Select Day</option>
    <option value="Mon">Mon</option>
    <option value="Tue">Tue</option>
    <option value="Wed">Wed</option>
    <option value="Thu">Thu</option>
    <option value="Fri">Fri</option>
    <option value="Sat">Sat</option>
    <option value="Sun">Sun</option>
</select>


text:
Q: Looking for specific UI controls on Android I need to create most effective UI for entering trailer inspection data.
THere is 8 wheels :) And for each wheel driver need to specify:

*

*Thread Depth - this goes in predefined values. Ideally I like some kind of up/down and view so driver can specify 5/6/7 instead of typing

*PSI - pressure. Same thing. Some kind of scroller or up/down numerical thingy?

*Tire brand - I will use Spinner for this.
Do you have any control suggestion for #1/2 ? I'm looking for something built-in but if not - I will appreciate pointer to source code of similar control
Thanks!

A: The problem with "up/down numerical thingys" is that they either aren't finger-friendly or are large. If you are planning on having all eight tires on one phone screen, size is an issue.
If you are limiting this to Honeycomb and higher, NumberPicker is available for the "up/down numerical thingy". But, again, it's large. SeekBar plus a TextView for the actual selected value is another possibility, one that will take up less screen space.
If you are going to use a Spinner for brand, be sure to have an "Other" option.

A: A data entry application/UI needs to be as easy to use as possible. If it is being used by truckers in rough environments, potentially in bright sunlight, with drivers wearing gloves, etc then the UI needs to be big, and extremely easy to use. By "big" I mean a typical smart phone sized screen should have, for example, the PSI number in large text in the middle of the screen and up/down rockers above/below (for portrait) or left/right for landscape. This way its easy to read, easy to manipulate and almost foolproof.
The UI can then be something as simple as two image views (up/down) rockers and a text view to display the current reading, and maybe an OK button. Put this in a separate activity and have that activity fill the parent view, ideally the whole screen.
Thus instead of a single UI view, perhaps you should consider multiple Activities for each sub screen and have a "home" activity that pictorially shows what has been gathered, what data has still to be gathered, and perhaps an indication of a problem - depending on your application's requirements/purpose.
Opinion: if the inspection is very procedural (left front tire, left rear tractor tire, left outer rear trailer tire, left inner trailer tire, etc) then the UI should "flow" in accordance with that procedure.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to watch (i.e. debug) extra-lambda variable inside lambda scope in C#/Visual-Studio/Unity3d? When using Visual Studio Professional 2015 with Unity, I've noticed that when I am stepping though the body of a lambda expression, I cannot watch variables which were declared/assigned outside of but are being read inside of the lambda expression.
    private IEnumerator DoTheThing(string filter)
    {
        TextureDownload texDl = new TextureDownload();
        texDl.OnCompleted += () =>
        {
            _log.Log("Mesh texture " + texDl.GetType() + ":" + texDl.GetHashCode());
            textures.Add(texDl);
        };
        yield break;
    }

I get the error

The identifier texDl is not in the scope

Obviously the variable is accessible in this scope, because the lambda function is using it.
Is there any remotely easy/convenient way to watch the value of such variables?

A: Turns out this is a variation of C# lambda call in for loop references to last object
There is an issue with Mono/Unity with coroutines and lambda expressions;

The coroutine itself is an implicit closure as well which moves all local variable to a seperate class as member variables. That means it's impossible to create a "real" local variable inside a generator method. That's why the explicit local variable declaration doesn't work.

See http://answers.unity3d.com/questions/974036/c-lambda-call-in-for-loop-references-to-last-objec.html


text:
Q: What are NFC dynamic tags and how are they different from encrypted and unencrypted NFC tags? Are these further categorizations of Tag Types 1-4? I am able to find results with NFC Type 1, Type 2 tags, etc. but I can't find any information on NFC dynamic tags, encrypted, and unencrypted NFC tags.
Can anyone please explain here and provide me with a relevant link of the source?

A: Sony has a product FeliCa Plug that they call a "dynamic tag". I am not aware of any other products that have similar functionality.
Some NFC tags offer, next to NFC Forum Type 1/2/3/4 Tag functionality, other functionality such as authentication and encrypted communication. However, the specifics of such functionality can be considered proprietary, as it is not standardized. Examples:

*

*NXP MIFARE Ultralight C: Type 2 Tag compatible, offers also password protection

*Sony FeliCa: Type 3 Tag compatible, offers also authentication and encryption

*NXP DESFire: Type 4 Tag compatible, offers also authentication and encryption

Details of such tags are usually only available under NDA, though.

A: Dynamic NFC tag is also known as dual interface tag, at the same time there is I2C and wireless support. Such as TI's RF430CL330H, you can modify the tag with I2C, such as Arduino board. Reference https://www.indiegogo.com/projects/dnfc-tag-nfc-that-interacts-with-microcontroller#/


text:
Q: How can I access GIMP's "Alpha to Logo" with the working functionlity it used to have? I am trying to make a book cover that uses GIMP to create stylized text via Cool Metal. In the past it has worked, but at present I haven't been able to find any way on two current systems to specify text that is to be stylized.
How can I get the old functionality back?

A: I figured out my problem. I wanted File -> Create -> Logos... and instead had pulled Alpha to Logo from under Script-Fu. The problem resolved immediately when I used File -> ...


text:
Q: Systemd Automount Failing on Program Execution I set up a systemd automount for an external drive by UUID. I basically just wanted the drive to mount whenever it's accessed. It was working fine but I noticed some issues when loading Evince first, then Inkscape. Both programs would just hang and I had to kill -9 to get them closed. After digging around, I found that both were somehow activating the mountpoint of the automount, without the drive even being plugged in. This caused the hang. Here is some output:
[chris@archpc ~]$ sudo cat /etc/systemd/system/mnt-external_drive.mount
[Unit]
Description=Mount external drive

[Mount]
What=/dev/disk/by-uuid/F474B7AA74B76DCC
Where=/mnt/external_drive
Type=ntfs
Options=rw,uid=1000,gid=1000,iocharset=utf8,nofail

[Install]
WantedBy=multi-user.target
[chris@archpc ~]$ sudo cat /etc/systemd/system/mnt-external_drive.automount
[Unit]
Description=External drive automount
ConditionPathExists=/mnt/external_drive

[Automount]
Where=/mnt/external_drive
TimeoutIdleSec=10

[Install]
WantedBy=multi-user.target

This is about all I can find as far as an error message that pointed me to this:
Mar 09 11:51:20 archpc systemd[1]: mnt-external_drive.automount: Got automount request for /mnt/external_drive, triggered by 124245 (evince)

Am I missing an option or something that has caused these programs to require the mountpoint? I've read through the options and I can't quite grasp why this automount would trigger from either of these programs (I'm sure others would cause it as well, I just started noticing the issue after adding the automount recently).


text:
Q: unable to paste conditional formattting to another workbook Excel 365 FR
Hello,
It seems impossible to paste conditional formatting to another workbook when there is a reference to another sheet, even if there is the same sheet in the the target workbook :
Source :
Target :
I'm stuck. It works when there is no reference to another worksheet.
Is there a workaround ?
Regards.


text:
Q: Conditional Interpretations of Linear Regression We estimate a linear regressor in the 1 dimensional with x and y random variables with zero mean:
y/x = $\alpha$ x
We can rewrite this using the variance of the variables as:
y/x = $\rho \frac{\sigma_y}{\sigma_x}$x
What can we say about x/y?
Looking at this deterministic, $\alpha$ is the rate of change of y w.r.t. x. So we could say that we x = $\frac{1}{\alpha}$y.
Can we say anything more concretely?


text:
Q: IUSR permissions removed from wwwroot? We had every website on one machine suddenly start returning 401.3 errors this morning.  After much poking around we fixed the problem by changing the IIS Anonymous Authentication to use the application pool identity.
From the IIS logs, we know exactly when the website switched from 200 to 401.3 responses, and there was a vendor in the machine at the time.  I have good reason to believe that the websites were using the IUSR previously, and that somehow, the vendor did something to remove IUSR from the IIS_IUSRS group, OR removed IUSR permissions.  However, when I try to replicate on a sister box, I see that the website on the sister box is running under IUSR but
1) None of the directories have IUSR permission (just IIS_IUSRS)
2) The IIS_IUSRS group only has a SID as a member + the Default Application Pool
Yet the website on the sister box is humming along just fine!
How could someone remove IUSR permissions from the directory when they are not listed, or from IIS_IUSRS when the user is not listed?

A: One tool that is helpful in troubleshooting would be process monitor.  From your description the USERS would be a good culprit.  The local users group contains 'authenticated users', which would contain a token for authenticated.
http://www.iislogs.com/articles/processmonitorw3wp/
btw - why are you letting a vendor access to your server? :)


text:
Q: Kolmogorov Smirnov test - correct data to compare against a standard normal distribution or not correct? The question arose from my analysis on Matlab.
The function kstest(x) compares data set x against a standard normal distribution (mean 0 and std 1)
My question is, do you correct the data set to have a mean of 0 and std of 1
y = (x - mean(x))/std(x)
or compare it without correcting?

A: I believe you need Lilliefors test. The Kolmogorov-Smirnov test uses a completely specified distribution, so in your case, you need to know exactly which normal distribution you're testing against (pre-specified values of mean and variance). Kolmogorov-Smirnov does not take into account the uncertainty involved in estimating the mean and variance. This is the issue that Lilliefors addressed in his paper. From the abstract:

The standard tables used for the Kolmogorov-Smirnov test are valid when testing whether a set of observations are from a completely-specified continuous distribution. If one or more parameters must be estimated from the sample then the tables are no longer valid.

See also the Wikipedia article for a summary. The "nortest" package in R has the function lillie.test() to perform a Lilliefors test. I don't use Matlab, but from a quick Google search it looks there is a lillietest(x) function from here.
By the way, you might be interested in this discussion where it's discussed when (and if) normality testing is really appropriate/useful or not.


text:
Q: How to pass data using javascript in html file, Django template? I am trying to fetch the data (details of the products ordered) from checkout page of HTML I designed. Tried implementing it using javascript but the values are empty when rendered through views.
checkout.html -

Checkout

 Your Cart Items

            Product Name
            Description
            Quantity
            Price

          {% for item in cart_items %}

              {{ item.product.name }}
              {{ item.product.description }}
              {{ item.quantity }}
              {{ item.product.price }}

          {% endfor %}

            Total
            {{ total }}

Enter Address & Other Details:

      <form method="post" action="/thankyou/">{% csrf_token %}
        <input type="hidden" name="itemsJson" id='itemsJson'>

                Name
                <input type="text" class="form-control" id="name" name="name" placeholder="Name">

                City
                <input type="text" class="form-control" id="city" name="city">

            Phone Number
            <input type="tel" class="form-control" id="phone" name="phone">

        <button type="submit" class="btn btn-primary">Place Order</button>
      </form>

views.py
def thankyou(request):
    if request.method == "POST":
        items_json = request.POST.get('itemsJson', '')
        name = request.POST.get('name', '')
        city = request.POST.get('city', '')
        phone = request.POST.get('phone', '')
        print (request.POST)

        order = Order(items_json= items_json, full_name=name, town_or_city=city, phone_number=phone)
        order.save()
        id = order.order_id
        return render(request, 'thankyou.html', {'thank':thank, 'id':id,})

The variable (id=itemsJson) is empty when rendered in views. This will be saved along with the form items to create a db entry.
The other form items are populated as expected.


text:
Q: Index Match across multiple columns I have two sheets one: with two columns of places and a third column with the mileage between those places:

On the other sheet I have a drop down list of the places in Sheet1 column A and another column with a drop down list of the places in Sheet1 column B, then a third column that match index looks up the mileage from Sheet 1 column C.

In my index match formula, I want to be able to look up the places no matter which column they are in on the first sheet.
For example, I want it to find a match for Office to Apple Blossom and Apple Blossom to Office.
Now I am using the formula:
=ArrayFormula(iferror(ArrayFormula(INDEX('Copy of Location to Location'!C:C, MATCH('Travel Form 17-18'!B8&'Travel Form 17-18'!C8,'Copy of Location to Location'!A:A&'Copy of Location to Location'!B:B,0))),""))
but this only looks up Office to Apple Blossom and not the reverse.  Is it possible to add another Match formula that would look up both columns without having to enter the data into both columns on Sheet 1?

A: First rule of rocket science: simple things are easier than complex things.
I recreated your problem on a single sheet,
so I wouldn't have to use sheet names everywhere.
Columns A-C correspond to Columns A-C on your Sheet1
(a.k.a. 'Copy of Location to Location')
and Columns AA-AE correspond to Columns A-E on your Sheet2
(a.k.a. 'Travel Form 17-18').
I reduced your formula (which you use in Sheet2!E8) to
=IFERROR(INDEX(C:C, MATCH(AB8&AC8, A:A&B:B, 0)), "")

which I put into my AE8.
It's a lot easier to understand when the clutter is stripped away.
And the logic is not rocket science.
If FROM&TO isn't in the "Location to Location" table,
we want to search for TO&FROM:
=IFERROR(INDEX(C:C, IFERROR(MATCH(AB8&AC8, A:A&B:B, 0), MATCH(AC8&AB8, A:A&B:B, 0))), "")

is the formula I have in cell AE8 in this screenshot:

We're apparently using different versions of Excel.
I can't say ArrayFormula(…) in mine (Excel 2013);
I just type Ctrl+Shift+Enter
after a formula to make it an array formula.
So I don't know exactly how this ArrayFormula(…) works
(are you sure you need to use it twice in your formula?).
But here's my solution (from above)
translated back into your sheet and column names:
=IFERROR(INDEX(C:C, IFERROR(MATCH('Travel Form 17-18'!B8&'Travel Form 17-18'!C8, 'Copy of Location to Location'!A:A&'Copy of Location to Location'!B:B, 0), MATCH('Travel Form 17-18'!C8&'Travel Form 17-18'!B8, 'Copy of Location to Location'!A:A&'Copy of Location to Location'!B:B, 0))), "")
I'll let you figure out where in there you need to say ArrayFormula(…).


text:
Q: Passing a PHP variable using ajax
I'm trying to pass a php variable from page1.html (which contains a php variable that I got from another form) to page2.php using ajax but it's not working, so I need your help.
code from page1.php:
<script>
var url = 'page2.php';
$("#save").click( function() {
    $.ajax({
        url : url,
        type: 'post',
        data : {
            admin : <?php echo $admin; ?>,
            gname : <?php echo $gname; ?>,
            filename : docname,
            content : encodeURIComponent(editor.getValue())
        }
    });
});
</script>

The datas filename and content are being sent successfully but admin and gname are not.
Thanks in advance.
UPDATE:
<?php
    if(isset($_GET['admin'])) {
    $admin = $_GET['admin'];
    }
    if(isset($_GET['gname'])) {
    $gname = $_GET['gname'];
    }
?>

This code is where I get the php variable that I want to send, from another form which is irrelevant to this question.

A: Here you go buddy, replace your script code with this.
<script>
var url = 'page2.php';
var admin = '<?php echo $admin; ?>';
var gname = '<?php echo $gname; ?>';
$("#save").click( function() {
    $.ajax({
        url : url,
        type: 'post',
        data : {
            admin : admin,
            gname : gname,
            filename : docname,
            content : encodeURIComponent(editor.getValue())
        }
    });
});
</script>

A: Youre using the type post so must use the $_POST in php
PHP
<?php
    if(isset($_POST['admin'])) {
    $admin = $_POST['admin'];
    }
    if(isset($_POST['gname'])) {
    $gname = $_POST['gname'];
    }
?>

A: You are using $_GET['admin'] which is used to fetch parameters delivered with GET method. You should be using $_POST['admin'] since you have set POST as your http request type in the JS code.

A: As everyone is saying you're mixing POST and GET. But it caught another thing that may bother you. Are those variables strings? If they are, maybe you're missing the apostrophe/single quote.
<script>
var url = 'page2.php';
$("#save").click( function() {
$.ajax({
   url : url,
    type: 'post',
    data : {
        admin : '<?php echo $admin; ?>',
        gname : '<?php echo $gname; ?>',
        filename : docname,
        content : encodeURIComponent(editor.getValue())
    }
});
});
</script>>

A: Your below code
<?php
    if(isset($_GET['admin'])) {
    $admin = $_GET['admin'];
    }
    if(isset($_GET['gname'])) {
    $gname = $_GET['gname'];
    }
?>

is to be replaced by
    <?php
    if(isset($_POST['admin'])) {
    $admin = $_POST['admin'];
    }
    if(isset($_POST['gname'])) {
    $gname = $_POST['gname'];
    }
?>

A: You are sending POST parameters,while using get in PHP script. And another issue is you are not using quotes with $admin and $gname variables in ajax request.
Try following :
<script>
var url = 'page2.php';
$("#save").click( function() {
    $.ajax({
        url : url,
        type: 'post',
        data : {
            admin : '<?php echo $admin; ?>',
            gname : '<?php echo $gname; ?>',
            filename : docname,
            content : encodeURIComponent(editor.getValue())

        }
    });
});
</script>

PHP Script:
<?php
    if(isset($_POST['admin'])) {
        $admin = $_POST['admin'];
    }
    if(isset($_POST['gname'])) {
        $gname = $_POST['gname'];
    }
?>

Check if it helps you.


text:
Q: Keras you are trying to load a weight file containing 2 layers into a model with 1 layers I have train a CNN model using Keras and store the weights. When I am trying to load them back to the same model I am receiving the following error:

ValueError: You are trying to load a weight file containing 2 layers into a model with 1 layers.

I figure out that this is a common error. However, the proposed remedies did not seem to work for me. I tried to downgrade my current Keras version of 2.2.4 to 2.1.6. My model looks like:
def build_model(self):

    model = Sequential()
    #pdb.set_trace()
    model.add(Dense(128 * 7 * 7, activation="relu", input_shape=(None, self.latent_dim)))
    model.add(Reshape((7, 7, 128)))
    model.add(UpSampling2D())
    model.add(Conv2D(128, kernel_size=4, padding="same"))
    model.add(BatchNormalization(momentum=0.8))
    model.add(Activation("relu"))
    model.add(UpSampling2D())
    model.add(Conv2D(64, kernel_size=4, padding="same"))
    model.add(BatchNormalization(momentum=0.8))
    model.add(Activation("relu"))

    model.add(UpSampling2D(size=(1, 2)))
    model.add(Conv2D(64, kernel_size=4, padding="same"))
    model.add(BatchNormalization(momentum=0.8))
    model.add(Activation("relu"))

    model.add(UpSampling2D(size=(1, 2)))
    model.add(Conv2D(64, kernel_size=4, padding="same"))
    model.add(BatchNormalization(momentum=0.8))
    model.add(Activation("relu"))

    model.add(Conv2D(self.channels, kernel_size=4, padding="same"))
    model.add(Activation("tanh"))

    model.summary()

    noise = Input(shape=(self.latent_dim,))
    img = model(noise)

    return Model(noise, img)

Then, for loading the weights I am doing something like:
self.my_model = self.build_model()

input = Input(shape=(self.latent_dim,))
img = self.my_model(input)
output = self.my_critic(img)

self.the_model = Model(input, output)
self.the_model.compile(loss= self.wasserstein_loss,optimizer=optimizer)

self.the_model.compile(...) # the same options as in case of training
self.the_model.load_weights('models/stored_weights')

EDIT:
I checked more carefully my code and I figured out that my issue was something different and more complicated. My code correspond to an implementation of Wasserstein GANs. The model that I am training is not directly build using only the build_model. However, it is a combination of that model and a critic (therefore a combination of these two models). Firstly, I define my model (is my generator) self.my_model = self.build_model() and then I have self.the_model = Model(input, output) where input is the input of my_model: input = Input(shape=(self.latent_dim,)) and output is the output of critic:
img = self.my_model(input)
output = self.my_critic(img)

Therefore, I am not training and storing the weights of my_model but the one of the the_model (since I want to train my_model and critic in the same time).
Thus, I tried to do: self.the_model.load_weights('models/gen_vv_face_feats__') instead of my_model.load_weights
Now I am receiving the following error:

ValueError: axes don't match array

A: Part of the problem may lie in Model(noise, img), where img is the entire Sequential model that could treated as a single layer when loading weights (see below) - depending on how the weights were saved.
To better understand the problem, it'd help seeing your save code - since your code provided as-is (w/ save code added) works for me. For a workaround you could try, see below.

Possible problem:
model = build_model()
model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 12)                0
_________________________________________________________________
sequential_1 (Sequential)    (None, 28, 112, 16)       623824
=================================================================
Total params: 623,824
Trainable params: 623,184
Non-trainable params: 640

What worked for me:
model_to_save = build_model()
model_to_save.compile()
model_to_save.save_weights(path)

model_to_load = build_model()
model_to_load.compile()
model_to_load.load_weights(path)

Workaround + tip:
To fix as-is, drop the noise =, image =, and Model(...) lines entirely, and simply do return model: your original Input should already do what you intend to with noise =.
Also, if you require advanced functionality with multiple inputs/outputs, use Model, lot easier to work with - and don't mix Model w/ Sequential unless for very specific reasons.


text: Q: How to use "export default { }" for component creation instead of "export default defineComponent({ })" in quasar v2? I am facing this situation after upgrading from Quasar v1 to v2. I am used to use "export default", but now while I am creating new Vue apps using Quasar, predefined components like App.vue, MainLayout.vue and Index.vue are initialized with "export default defineComponent". I am not at all familiar with this structure. So, how can I initialize Vue 3 apps in Quasar V2 with components using "export default {}" structure. I am aware that they can be manually changed, but how to make them as default structure for further apps?


text:
Q: ActiveMQ returns 503 when accessing admin panel When I run ActiveMQ as root I am able to access the admin panel. However I need to run it as the apache user so my web server can send messages to other programs on my machine. When I run it as the apache user and try to access the admin panel it responds with a 503 service unavailable.
Does anyone know of a fix for this? Thanks
Edit: Adding activemq.log output from the 503
2013-05-28 13:47:51,823 | WARN  | Committed before 503 null | org.eclipse.jetty.server.Response | qtp1146944158-23
2013-05-28 13:47:51,824 | WARN  | /admin/ | org.eclipse.jetty.server.AbstractHttpConnection | qtp1146944158-23
java.lang.IllegalStateException: Committed
     at org.eclipse.jetty.server.Response.resetBuffer(Response.java:1126)
     at org.eclipse.jetty.server.Response.sendError(Response.java:313)
     at org.eclipse.jetty.server.Response.sendError(Response.java:415)
     at org.eclipse.jetty.server.handler.ContextHandler.checkContext(ContextHandler.java:820)
     at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:916)
     at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
     at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)
     at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:521)
     at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)
     at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
     at org.eclipse.jetty.server.Server.handle(Server.java:363)
     at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:483)
     at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:920)
     at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:982)
     at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:635)
     at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)
     at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
     at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:627)
     at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:51)
     at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
     at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
     at java.lang.Thread.run(Thread.java:722)

Edit: I am now rerunning my script against the server while ActiveMQ is running as apache and server is root and the script hangs. It is getting stuck at creating a default session. When I step through in GDB it still works though...
Edit: I ran setenforce 0 and everything worked. Not sure why that would be. Any ideas?

A: Could be permission.
windows
Run as administrator

Linux
$] sudo bin/activemq start

A: I had this. Turned out that because I'd run it as root before, I had root-owned files in the activemq directories. Once I changed their ownership, my non-root user could run activemq, and the admin panel was available.

A: Well I managed to figure out the problem in case anyone who stumbles on this is curious.
I enabled selinux again and added ports 61616 (port for openwire connections), 61613 (port for stomp connections), and 8161 (port for admin console) to the allow list for http_port_t.
I used the command:
semanage port -a -t http_port_t -p tcp [port number]


text:
Q: How do I use an optional properties file in a Spring configuration file? I am using an XML configuration file that is loaded into my Java application using ApplicationContext.
The XML configuration file resolves its properties by reading from several property files using PropertyPlaceholderConfigurer.
I want to make each property file optional. I thought that this is done by setting ignoreUnresolsvablePlaceholders to true, however I am getting the following exception when I run the application (db-default.properties exists but db.properties does not):
Exception in thread "main" org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [db.properties] cannot be opened because it does not exist

This is what my XML configuration looks like:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="placeholder-configurer-1" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="order" value="1"/>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>

    <bean id="placeholder-configurer-2" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="order" value="2"/>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="location" value="classpath:/db-default.properties"/>
    </bean>

    <bean id="placeholder-configurer-3" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="order" value="3"/>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
            <list>
                <value>classpath:/db.properties</value>
            </list>
        </property>
    </bean>

    <bean id="MyDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

</beans>

What do I need to do to make db.properties an optional property file?

A: This should work too:
<context:property-placeholder ignore-resource-not-found="true" location="classpath:your.properties" ... />

A: <property name="ignoreResourceNotFound" value="true"/>

*

*spring blog article

*api docs


text:
Q: No such file or directory: Running Ruby as an interpreter script for execv() I'm writing a C program that passes data to a Ruby script. The snippet of code in main.c is below. Whenever I run, I receive an error from execv() that there is no such file or directory. I guessed that I didn't add my file to the PATH but I did and I still ended up with the same outcome.
int temp =  execv("#!/usr/bin/ruby xmlReader.rb", list);
if (spec == -1)
      printf("%s\n", strerror(errno));

A: The exec*() family of system calls are very low level, they replace the executing program with the program mentioned as the first argument, so there's no return value unless there's an error. Upon success, your program is entirely gone, overlaid with the new program. It's a one-way program-execution chain.
It doesn't know how to run command lines, and exec() is usually usually is done after a fork() operation. You almost certainly don't want to do this.
What you probably want is int temp = system("ruby xmlreader.rb"); which will run the command line given in a subprocess (ultimately using fork and exec, though this aspect is invisible to you), wait for it to complete, then return the exit value to you.


text:
Q: Generate webservice server from WSDL file first of all I know there is similar question but it has more than 11 years so it's not quite new.
I am trying to create mock webservice from WSDL (+xsd) file, but I cannot find any solution in python frameworks for it. I was trying to create Zeep client, but it dosen't support server side, only mocking requests provided in code. I was also trying to create SOAP server by spyne, but this on the other hand dosen't provide support for WSDL files. For it I was trying to find library which could translate WSDL file into compatible class but I wasn't able to find one.
Does anyone know framework/library which could help me with this? Either allowing to create webservice from wsdl as server(on localhost), or at least translate WSDL into class comptaible with Spyne.


text:
Q: Why is rotation much faster on Image than using BitmapEncoder? Rotating an Image using
image.RenderTransform = new RotateTransform()...

is almost immediate.
On the other hand, using
bitmapEncoder.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees...

is much slower (in the FlushAsync()) - more than half a second.
Why is that? And is there a way to harness the fast rotation in order to rotate bitmaps?

A: The first one image.RenderTransform will render the bitmap by using hardware rendering. (GPU) The image isn't rotate but will be displayed rotated/scaled. (will access only visible pixels directly from/in the videomemory)
The second one will rotate the image itself by the CPU (all pixels). It will create new memory for the result. (non-video memory)

update:

Is there a way to use the GPU to edit bitmaps?
  Depends on what you need:

If you want to use a GPU. You could use an managed wrapper (like Slim DX/Sharp DX) This will take much time to get results. Don't forget, rerasterizing images via gpu could lead to quality lost.
If you want to rotate images only (0, 90, 180, 270)? you could use a Bitmap class with de ScanLine0 option. (this is to preserve quality and size) and you could create a fast implementation.
Look here:
Fast work with Bitmaps in C#
I would create an algoritm foreach angle (0,90,180,270). Because you don't want to calculate the x, y position for each pixel. Something like below..

Tip:
try to lose the multiplies/divides.
/*This time we convert the IntPtr to a ptr*/
byte* scan0 = (byte*)bData.Scan0.ToPointer();

for (int i = 0; i < bData.Height; ++i)
{
    for (int j = 0; j < bData.Width; ++j)
    {
        byte* data = scan0 + i * bData.Stride + j * bitsPerPixel / 8;

        //data is a pointer to the first byte of the 3-byte color data
    }
}

Becomes something like:
/*This time we convert the IntPtr to a ptr*/
byte* scan0 = (byte*)bData.Scan0.ToPointer();

byte* data = scan0;

int bytesPerPixel = bitsPerPixel / 8;

for (int i = 0; i < bData.Height; ++i)
{
    byte* data2 = data;
    for (int j = 0; j < bData.Width; ++j)
    {
        //data2 is a pointer to the first byte of the 3-byte color data

        data2 += bytesPerPixel;
    }
    data += bData.Stride;
}


text:
Q: Dependency is not satisfiable error I am a new user to Ubuntu and seeking for help on installing a mod for Nautilus. I am running 12.04 on 32 bit machine. I do not know hot to compile all these files or what I am doing wrong. I downloaded the top file and got the following message when opening the file :

dependency is not satisfiable

ideas on how to proceed?

A: I tried to install it on 12.04, with the same result. The file you mention is a .deb installer file that you can (normally) install by just double clicking. You did everything right, but it turns out that the patch cannot be installed on the latest (update of) nautilus. see this bug report.
A quick search for a possible workaround gave me this: if you have synaptic package manager installed: search for nautilus, select nautilus, and choose package from the menu, in the dropdown menu  > package > force version. then choose the previous version of nautilus:

See also this link to hold packages of a certain version (especially the "Introduction to Holding Packages" - section)


text:
Q: Make specific product variations not taxable in Woocommerce I manage a Woocommerce website that sells videos. Most of them are variable products with different product variations:

*

*A hard-copy DVD by mail

*Or a stream.

The streaming videos are, obviously, virtual products, so no shipping is charged and taxes should not be charged.
Is it possible to change the tax status for some variation? Ideally, I'd like to be able to have ALL "Streaming Video" variations to be not taxable by default, but I'd settle for being able to edit them one by one.
By default, I can change the tax CLASS for a variation, but I can't change the tax STATUS.
How can I make some product variations not taxable?
Any help is greatly appreciated.

A: As taxable feature is not available for product variations, you will need to set zero taxes on those Product variations.
For that you need to go to in Woocommerce settings > Taxes (tab).
Then you will have to add a "Zero Rate" in "Additional tax classes" related field, and save:

A new "Zero Rate rates" setting tab will appear on the "Taxes" setting page:

Click on it and you will get the "Zero Rate" settings page. Insert a row this way and save:

Now on your variable products, in the variations, the Zero tax is available to be selected:

Select it for each variation and save them all. You are done.


text:
Q: Python Dataflow Template, making Runtime Parameters globally accessible So the aim of the pipeline is to be able to use Runtime Variables to be able to open a csv file and name a BigQuery table.
All I need is to be able to access these variables globally, or within a ParDo, such as parsing it into the function.
I have tried creating a dummy string, then running a FlatMap to access the Runtime Parameters and make them global, although it returns nothing.
eg.
class CustomPipelineOptions(PipelineOptions):

    @classmethod
    def _add_argparse_args(cls, parser):
        parser.add_value_provider_argument(
            '--path',
            type=str,
            help='csv storage path')
        parser.add_value_provider_argument(
            '--table_name',
            type=str,
            help='Table Id')
def run()
    def rewrite_values(element):
        """ Rewrite default env values"""
        # global project_id
        # global campaign_id
        # global organization_id
        # global language
        # global file_path
        try:
            logging.info("File Path with str(): {}".format(str(custom_options.path)))
            logging.info("----------------------------")
            logging.info("element: {}".format(element))
            project_id = str(cloud_options.project)
            file_path = custom_options.path.get()
            table_name = custom_options.table_name.get()

            logging.info("project: {}".format(project_id))
            logging.info("File path: {}".format(file_path))
            logging.info("language: {}".format(table_name))
            logging.info("----------------------------")
        except Exception as e:
            logging.info("Error format----------------------------")
            raise KeyError(e)

        return file_path

    pipeline_options = PipelineOptions()
    cloud_options = pipeline_options.view_as(GoogleCloudOptions)
    custom_options = pipeline_options.view_as(CustomPipelineOptions)
    pipeline_options.view_as(SetupOptions).save_main_session = True

    # Beginning of the pipeline
    p = beam.Pipeline(options=pipeline_options)

    init_data = (p
                 | beam.Create(["Start"])
                 | beam.FlatMap(rewrite_values))

pipeline processing, running pipeline etc.

I can access the project variable no problem, although everything else returns as blank.
If I make the custom_options variable global, or when I pass a specific customs object into a function, such as: | 'Read data' >> beam.ParDo(ReadGcsBlobs(path_file=custom_options.path)), it only returns something such as RuntimeValueProvider(option: path, type: str, default_value: None).
If I use | 'Read data' >> beam.ParDo(ReadGcsBlobs(path_file=custom_options.path.get())), the variable is and empty string.
So in essence, I just need to access these variables globally, is it possible?
Finally to clarify, I do not want to use the ReadFromText method, I can use the runtime variable there, although to incorporate the runtime options into the dict created from the csv file will be to costly as I am working with huge csv files.

A: For me it worked by declaring cloud_options and custom_options as global:
import argparse, logging

import apache_beam as beam
from apache_beam.options.pipeline_options import GoogleCloudOptions
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions

class CustomPipelineOptions(PipelineOptions):

    @classmethod
    def _add_argparse_args(cls, parser):
        parser.add_value_provider_argument(
            '--path',
            type=str,
            help='csv storage path')
        parser.add_value_provider_argument(
            '--table_name',
            type=str,
            help='Table Id')

def rewrite_values(element):
        """ Rewrite default env values"""
        # global project_id
        # global campaign_id
        # global organization_id
        # global language
        # global file_path
        try:
            logging.info("File Path with str(): {}".format(str(custom_options.path.get())))
            logging.info("----------------------------")
            logging.info("element: {}".format(element))
            project_id = str(cloud_options.project)
            file_path = custom_options.path.get()
            table_name = custom_options.table_name.get()

            logging.info("project: {}".format(project_id))
            logging.info("File path: {}".format(file_path))
            logging.info("language: {}".format(table_name))
            logging.info("----------------------------")
        except Exception as e:
            logging.info("Error format----------------------------")
            raise KeyError(e)

        return file_path

def run(argv=None):
  parser = argparse.ArgumentParser()
  known_args, pipeline_args = parser.parse_known_args(argv)

  global cloud_options
  global custom_options

  pipeline_options = PipelineOptions(pipeline_args)
  cloud_options = pipeline_options.view_as(GoogleCloudOptions)
  custom_options = pipeline_options.view_as(CustomPipelineOptions)
  pipeline_options.view_as(SetupOptions).save_main_session = True

  # Beginning of the pipeline
  p = beam.Pipeline(options=pipeline_options)

  init_data = (p
               | beam.Create(["Start"])
               | beam.FlatMap(rewrite_values))

  result = p.run()
  # result.wait_until_finish

if __name__ == '__main__':
  run()

After setting the PROJECT and BUCKET variables I staged the template with:
python script.py \
    --runner DataflowRunner \
    --project $PROJECT \
    --staging_location gs://$BUCKET/staging \
    --temp_location gs://$BUCKET/temp \
    --template_location gs://$BUCKET/templates/global_options

And execute it with providing path and table_name options:
gcloud dataflow jobs run global_options \
   --gcs-location gs://$BUCKET/templates/global_options \
   --parameters path=test_path,table_name=test_table

And the runtime parameters seem to be logged fine inside the FlatMap:


text:
Q: Tinkerpop and ArangoDB : MissingPropertyException: No such property: graph for class: Script1 I am trying to use ArangoDB as a community supported provider for Tinkerpop so that I can use Gremlin in a Python project but I get the following error:
[ERROR] DefaultGremlinScriptEngineManager - Could not create GremlinScriptEngine for gremlin-groovy
java.lang.IllegalStateException: javax.script.ScriptException: javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: graph for class: Script1

I have followed the Wiki to define the properties and yaml configuration files.
Here is my properties configuration conf/modern-arangodb.properties:
gremlin.graph = com.arangodb.tinkerpop.gremlin.structure.ArangoDBGraph
gremlin.arangodb.conf.graph.db = tinkerpop
gremlin.arangodb.conf.graph.name = modern
gremlin.arangodb.conf.graph.vertex = Place
gremlin.arangodb.conf.graph.edge = Transition
gremlin.arangodb.conf.arangodb.hosts = 127.0.0.1:8529
gremlin.arangodb.conf.arangodb.user = root
gremlin.arangodb.conf.arangodb.password = openSesame

Here is my yaml configuration conf/gremlin-server-arangodb.yaml:
host: localhost
port: 8182
scriptEvaluationTimeout: 30000
channelizer: org.apache.tinkerpop.gremlin.server.channel.WebSocketChannelizer
graphs: {
  modern: conf/modern-arangodb.properties}
scriptEngines: {
  gremlin-groovy: {
    plugins: { org.apache.tinkerpop.gremlin.server.jsr223.GremlinServerGremlinPlugin: {},
               com.arangodb.tinkerpop.gremlin.jsr223.ArangoDBGremlinPlugin: {},
               org.apache.tinkerpop.gremlin.jsr223.ImportGremlinPlugin: {classImports: [java.lang.Math], methodImports: [java.lang.Math#*]},
               org.apache.tinkerpop.gremlin.jsr223.ScriptFileGremlinPlugin: {files: [scripts/empty-sample.groovy]}}}}
serializers:
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }}             # application/vnd.gremlin-v3.0+gryo
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { serializeResultToString: true }}                                                                       # application/vnd.gremlin-v3.0+gryo-stringd
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }}         # application/json
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV2d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV2d0] }}         # application/vnd.gremlin-v2.0+json
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphBinaryMessageSerializerV1 }                                                                                # application/vnd.graphbinary-v1.0
processors:
  - { className: org.apache.tinkerpop.gremlin.server.op.session.SessionOpProcessor, config: { sessionTimeout: 28800000 }}
  - { className: org.apache.tinkerpop.gremlin.server.op.traversal.TraversalOpProcessor, config: { cacheExpirationTime: 600000, cacheMaxSize: 1000 }}
metrics: {
  consoleReporter: {enabled: true, interval: 180000},
  csvReporter: {enabled: true, interval: 180000, fileName: /tmp/gremlin-server-metrics.csv},
  jmxReporter: {enabled: true},
  slf4jReporter: {enabled: true, interval: 180000}}
strictTransactionManagement: false
idleConnectionTimeout: 0
keepAliveInterval: 0
maxInitialLineLength: 4096
maxHeaderSize: 8192
maxChunkSize: 8192
maxContentLength: 65536
maxAccumulationBufferComponents: 1024
resultIterationBatchSize: 64
writeBufferLowWaterMark: 32768
writeBufferHighWaterMark: 65536
ssl: {
  enabled: false}

I then use the ArangoDB docker image (Version 3.6.3) and run:
docker run -p 8529:8529 -e ARANGO_ROOT_PASSWORD=openSesame arangodb/arangodb:3.6.3

Then I run the Gremlin Server (Version 3.4.6) and run:
GREMLIN_YAML=conf/gremlin-server-arangodb.yaml bin/gremlin-server.sh console

After which the terminal returns the aforementioned error No such property: graph for class: Script1

A: Issue
The issue was related to the configuration.
the configuration file conf/gremlin-server-arangodb.yaml mentions a key/value pair list of graph defined by properties files:
graphs: {
  modern: conf/modern-arangodb.properties}

Then in the scriptEngines.gremlin-groovy.plugins it references:
ScriptFileGremlinPlugin: {files: [scripts/empty-sample.groovy]}

Which specifies a graph with the name g.
(In Script file scripts/empty-sample.groovy):
globals << [g : graph.traversal().withStrategies(ReferenceElementStrategy.instance())]

The global graph is not defined, which in fact is called modern in the yaml file.
Resolution
Therefore a minor change in the gremlin-server-arangodb.yaml file was made. In addition, the conf/modern-arangodb.properties graph name was changed to match.
Updated conf/modern-arangodb.properties:
gremlin.graph = com.arangodb.tinkerpop.gremlin.structure.ArangoDBGraph
gremlin.arangodb.conf.graph.db = tinkerpop
gremlin.arangodb.conf.graph.name = graph
gremlin.arangodb.conf.graph.vertex = Place
gremlin.arangodb.conf.graph.edge = Transition
gremlin.arangodb.conf.arangodb.hosts = 127.0.0.1:8529
gremlin.arangodb.conf.arangodb.user = root
gremlin.arangodb.conf.arangodb.password = openSesame

Updated conf/gremlin-server-arangodb.yaml:
host: localhost
port: 8182
scriptEvaluationTimeout: 600000
channelizer: org.apache.tinkerpop.gremlin.server.channel.WebSocketChannelizer
graphs: {
  graph: conf/modern-arangodb.properties}
scriptEngines: {
  gremlin-groovy: {
    plugins: { org.apache.tinkerpop.gremlin.server.jsr223.GremlinServerGremlinPlugin: {},
               com.arangodb.tinkerpop.gremlin.jsr223.ArangoDBGremlinPlugin: {},
               org.apache.tinkerpop.gremlin.jsr223.ImportGremlinPlugin: {classImports: [java.lang.Math], methodImports: [java.lang.Math#*]},
               org.apache.tinkerpop.gremlin.jsr223.ScriptFileGremlinPlugin: {files: [scripts/empty-sample.groovy]}}}}
serializers:
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }}             # application/vnd.gremlin-v3.0+gryo
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { serializeResultToString: true }}                                                                       # application/vnd.gremlin-v3.0+gryo-stringd
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }}         # application/json
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV2d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV2d0] }}         # application/vnd.gremlin-v2.0+json
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphBinaryMessageSerializerV1 }                                                                                # application/vnd.graphbinary-v1.0
processors:
  - { className: org.apache.tinkerpop.gremlin.server.op.session.SessionOpProcessor, config: { sessionTimeout: 28800000 }}
  - { className: org.apache.tinkerpop.gremlin.server.op.traversal.TraversalOpProcessor, config: { cacheExpirationTime: 600000, cacheMaxSize: 1000 }}
metrics: {
  consoleReporter: {enabled: true, interval: 180000},
  csvReporter: {enabled: true, interval: 180000, fileName: /tmp/gremlin-server-metrics.csv},
  jmxReporter: {enabled: true},
  slf4jReporter: {enabled: true, interval: 180000}}
strictTransactionManagement: false
idleConnectionTimeout: 0
keepAliveInterval: 0
maxInitialLineLength: 4096
maxHeaderSize: 8192
maxChunkSize: 8192
maxContentLength: 65536
maxAccumulationBufferComponents: 1024
resultIterationBatchSize: 64
writeBufferLowWaterMark: 32768
writeBufferHighWaterMark: 65536
ssl: {
  enabled: false}


text:
Q: CSS alignment issue in my header as you can see on the picture below, my menu is +/- centered in the middle of the page whereas I would like it to be much further right (i.e. 20px to the left of the social icons).
I can not reproduce this on jsfiddle so I'm posting the link of the page (also code would be too long to post here). Any thoughts on this issue and how to fix it? (note that I'm using safari latest version and that you need your screen to be at least 1600 wide to notice this)
Many thanks

An here is a mockup of how I would like it to be:

A: You can only see his issue on a much larger window size. The issue is with the div #espace-entreprises it is floated right. If you change it to be position absolute you will be fine.
#espace-entreprises {
    margin-top: 5px;
    text-align: right;
    color: red;
    font-size: 12px;
    position: absolute;
    top: 0px;
    right: 0px;
}

The issue is that when the window is wide enough #main and #escape-entreprises can actually float next to each other.  Then you notice the large 120px margin.
Also you might reduce the margin-right on #menu


text:
Q: Nearest adjacent polygon, distance and closest point to other polygons I have multiple polygons in a dataset and I would like to:

*

*Identify the nearest polygon to each polygon and what the distance between them is

*Calculate the coordinates of where the nearest parts of the two polygons are (so I can draw a line and visually check the distances)

*If the distance is 800 metres of less, join the polygons together to make multipart polygons

This code does half of my first ask and I know st_distance can do the latter. I was hoping for a solution that wouldn't need for a matrix of every distance between every polygon to be generated.
library(sf)
library(dplyr)

download.file("https://drive.google.com/uc?export=download&id=1-I4F2NYvFWkNqy7ASFNxnyrwr_wT0lGF" , destfile="ProximityAreas.zip")
unzip("ProximityAreas.zip")
Proximity_Areas <- st_read("Proximity_Areas.gpkg")

Nearest_UID <- st_nearest_feature(Proximity_Areas)

Proximity_Areas <- Proximity_Areas %>%
        select(UID) %>%
        mutate(NearUID = UID[Nearest_UID])

Is there a method of producing two outputs 1) an appended Proximity_Areas file that included the distance and XY coorindates for the nearest points for the UID and Neatest_UID and 2) a file that looks similar to the original Proximity_Areas file, just with merged polygons if the criteria is met?

A: Once you have created index of nearest neighbors you can calculate the connecting lines via a sf::st_nearest_points() call.
An interesting aspect is that if you make the call on geometries (not sf, but sfc objects) you do the calculation pairwise (i.e. not in a matrix way).
The call will return linestrings, which is very helpful since you can calculate their length and have two of your objectives (nearest points & distance) at a single call...
lines <- Proximity_Areas %>%
  st_geometry() %>% # extact geometry
  # create a line to nearest neighbour as geometry
  st_nearest_points(st_geometry(Proximity_Areas)[Nearest_UID], pairwise =T) %>%
  # make sf again (so it can hold data)
  st_as_sf() %>%
  # add some data - start, finish, lenght
  mutate(start = Proximity_Areas$UID,
         end = Proximity_Areas$UID[Nearest_UID],
         distance = st_length(.))

glimpse(lines)
# Rows: 39
# Columns: 4
# $ x        <LINESTRING [m]> LINESTRING (273421.5 170677..., LINESTRING (265535.1 166136..., LINESTRING (265363.3 1…
# $ start    <chr> "U001", "U002", "U003", "U004", "U005", "U006", "U007", "U008", "U009", "U010", "U011", "U012", "…
# $ end      <chr> "U026", "U010", "U013", "U033", "U032", "U014", "U028", "U036", "U011", "U008", "U028", "U030", "…
# $ distance [m] 317.84698 [m], 579.85131 [m], 529.67907 [m], 559.96441 [m], 0.00000 [m], 80.54011 [m], 754.94311 [m…

mapview::mapview(lines)

The part about joining close objects together is a bit tricky, since you don't know how many polygons you will end up with - you can have a polygon A that is far from C, but will end up merged since both are close to B. This does not vectorize easily and you are likely to end up running a while loop. For a possible approach consider this related answer Dissolving polygons by distance - R


text:
Q: Sci-fi serial movie: Hyper-evolved human "queen" captured by scientists Gosh, I dont know where to start... I watched some serial movie from some sci-fi television (I don't remember which one) the moment that I captured was when the humans captured the queen of the evolved humans (the happening event was in the near future and the base of this group of people was surrounded by the evolved humans that was looking like savages)
In the end of the episode that I watched was a scene where the remaining humans (they looked like scientists) were arguing about keeping the queen inside or not, some of them were thinking that she let herself be captured so she can learn about her enemy from inside the lab, she looked hairless and brown and very smart. When the arguing ended, the queen killed one of the females with something sharp. There were some familiar actors and actresses that I no longer remember (I really tried to but failed to remember). I'm 100% sure that the chick that died was in some big movie but I'm not sure which one, and I can't remember her face either. I'm not sure which program I watched this serial movie episode on. It looked kind of new and catchy.

A: I'm fairly certain you watched an episode of Wayward Pines
I cant find the exact scene you describe but see if this looks familiar;


text:
Q: Turn off audio visualization for video but keep it for audio in VLC I finally managed to have audio visualization turned on by default...

Just to find out now it's turned on by default when I open a video file too.

Any way to fix this?
Obviously I don't want to watch a visualization of my audio when watching a video :D

A: I was trying to find out the same thing. After much Googling I finally found a workaround. Let me first start by saying there is currently no way to do this built in to VLC. This is a workaround and involves a bit of work.
VLC only keeps one configuration file for all the settings per user in Windows. It is stored in a user's AppData folder:
C:\Users\UserName\AppData\Roaming\vlc\vlcrc

The problem is we need a config for audio and a config for video, TWO configs.
In the audio config we will have visualizations enabled by default, for video it will be disabled. But how do we get TWO configs? This was the tricky part.
I tried installing multiple versions of VLC. I tried installing 32-bit and 64-bit versions in an attempt to get two configs. Nothing would work. No matter how many different VLCs and whatever the .exe was named (I tried renaming vlc.exe) whenever VLC opens it always checks in your user folder for "vlcrc" and reads/writes to it to save your preferences.
BUT, it turns out there is a VLC command parameter:
--config=
Which lets you specify your config file location.
So what can we do with this? One simple method would be to launch VLC from shortcuts, one for audio and one for video, by adding the command parameter to the shortcut's target:
Shortcut for audio:
C:\Program Files\VideoLAN\VLC --config="C:\Users\UserName\AppData\Roaming\vlc\vlcrc-audio"

Shortcut for video:
C:\Program Files\VideoLAN\VLC --config="C:\Users\UserName\AppData\Roaming\vlc\vlcrc-video"

While this works, it is not very convenient as you have to click the respective shortcut for your audio or video media. Ideally, we want to click ANY audio file or ANY video file from ANY location and it will point to the correct config. But how?
Windows used to have this feature built in. It was called setting advanced file associations within the default programs settings. They removed it around Windows 8 or so. (Technically, it can still be done via registry but it is very complicated. I tried. The problem is that in Windows 10 there are multiple registry locations for each file extension and multiple levels of permissions and hierarchy for each of them. It's really confusing.)
The solution:
Ultimately, I found a third party program called "Default Programs Editor" that can do advanced file associations. I was able to change all audio extensions to point to C:...vlc.exe" --config="...vlcrc-audio" and all video extensions to C:...vlc.exe" --config="...vlcrc-video". So now I have two VLC configs in my %appdata/vlc folder: vlcrc-audio & vlcrc-video. This is a valid workaround to my issue. It even works for AutoPlay so now a music CD will correctly launch with visualizations and a DVD will not have the visualization blocking video.
The program:

*

*http://defaultprogramseditor.com/
These SuperUser pages may also be useful:

*

*Pass command line arguments to Windows "Open With"

*How do I set advanced file associations in Windows 7?
My post on the VLC forums:

*

*https://forum.videolan.org/viewtopic.php?f=14&t=146813&p=481734#p481734


text:
Q: java sql SQLException: Parameter index out of range (1 > number of parameters, which is 0) I keep getting this error when trying to connect to the database.
This is my prepared statement
String SQL = "SELECT * FROM `?` WHERE `HomeTeam` = '?'";
        PreparedStatement prepst;

        prepst =  con.prepareStatement(SQL);
        prepst.setString(1,box1.getSelectedItem().toString());
        prepst.setString(2,box1.getSelectedItem().toString());
        rs = prepst.executeQuery();

Anyone know why I get this error?

A: I think that your problem is in ' and ``` symbols. You should fix the sql as follwing:
String SQL = "SELECT * FROM ? WHERE HomeTeam = ?";
However I am not sure that parameter placeholder ? is supported after from. So, propbably you will have to put it yourself, e.g.:
String table = box1.getSelectedItem().toString();
String SQL = "SELECT * FROM " + table + " WHERE HomeTeam = ?";

A: Use
String SQL = "SELECT * FROM ? WHERE HomeTeam = ?";

Don't use ` to nest parameters, use ' to nest values you're comparing against if you're hard coding them.
You can't use ? to specify a table name.


text:
Q: My  box won't display single quotes If it has a single quote in it, any string that I try to enter into my HTML input box is truncated in the input box once it is submitted.  Its POST value comes thru unchanged, but the string shows as truncated in the input box, whether I use htmlspecialchars() or not. A noobie question, no doubt, but I've tried hard to figure it out and run out of ideas. Thanks for any help.
    <!DOCTYPE html>
    <title> Self-inserting input_box_SO.php </title>
    <?php
    //  POST form initiation.
    ECHO "<form action='input_box_SO.php' method='post'>";

    // GET POSTed value and escape it for HTML use
    $Caption_htmlspecialchars=$_POST['Caption_htmlspecialchars'];
    $Caption_htmlspecialchars=htmlspecialchars($Caption_htmlspecialchars);
    ECHO "The echo of the variable  \$Caption_htmlspecialchars  looks like this:
";
    ECHO " $Caption_htmlspecialchars
";
    ECHO "But in the input box, \$Caption_htmlspecialchars is truncated by a single quote:
";
    // ETA: Bad old line that caused the problem, now commented:
    // ECHO "<input type='text' name='Caption_htmlspecialchars' size=100 value='$Caption_htmlspecialchars' maxlength = 100 required />

";
    // ETA: Newly added line that fixes the problem:
echo '<input type="text" name="Caption_htmlspecialchars" size=100 value="'.$Caption_htmlspecialchars.'" maxlength = 100 required />

';
    // SUBMIT button.  Submits back to the same page: input_box.php
    echo "<input type='Submit' name='submit' value='Submit'/>

";
    ?>

Here is what Inspect Elements > Elements shows for the input element:
 input_box_SO.php
The echo of the variable  $Caption_htmlspecialchars  looks like this: test with special chars. & " < > and a single quote ('), which causes truncation in the input box.  But in the input box, $Caption_htmlspecialchars is truncated by a single quote:  and a single quote (" ),="" which="" causes="" truncation="" in="" the="" input="" box.="" '="" maxlength="100" required="">
With the Source looking like this:  value='test with special chars. & " < > and a single quote ('), which causes truncation in the input box. '

A: You need to change your sequence of single quotes nad double quotes to display string. change your echo <input as below
echo '<input type="text" name="Caption_htmlspecialchars" size=100 value="'.$Caption_htmlspecialchars.'" maxlength = 100 required />

';

A: Try to use the addslashes and do it like
$Caption_htmlspecialchars = addslashes($Caption_htmlspecialchars);


text:
Q: PHP changes the path url of stylesheet when loading I'm trying to autoload the stylesheets in my page but it isn't working it returns this in the console:

Resource interpreted as Stylesheet but transferred with MIME type text/html

I've found what the problem is but I'm not sure how to fix it yet. As the autoloader works on one page but not on the other.
Working page:
Request URL:http://php.dev/public/assets/css/custom.css
This is the correct url but on my other page it is:
Request URL:http://php.dev/riot/public/assets/css/custom.css
So for some reason it adds a part of the url 'riot' in the request url I'm not sure how to remove this so it could load the css style correctly.
Autoloader function:
public function loadCss(){
    $folder = glob('./public/assets/css/*.{css}', GLOB_BRACE);
    foreach ($folder as $filename) {
        echo "<link type='text/css' rel='stylesheet' href='".$filename."'>";
    }
}


text:
Q: Android app gives "JVMTI error: 103(JVMTI_ERROR_ILLEGAL_ARGUMENT) " when Profiler starts In my Android app when I try to start the Profiler it gives me this error and the app crashes shortly afterwards. This is the log:
V/StudioProfiler: Profiler initialization complete on agent.
V/StudioProfiler: Handling agent command 405 for pid: 5317.
V/StudioProfiler: Handling agent command 404 for pid: 5317.
V/StudioProfiler: Loaded classes: 15997
V/StudioProfiler: New JNI table set
I/app           : The stack is not large enough for a start_depth of 0.
E/StudioProfiler: JVMTI error: 103(JVMTI_ERROR_ILLEGAL_ARGUMENT)
V/StudioProfiler: Tracking initialization took: 507444270ns
I/app           : The stack is not large enough for a start_depth of 0.
E/StudioProfiler: JVMTI error: 103(JVMTI_ERROR_ILLEGAL_ARGUMENT)
I/app           : The stack is not large enough for a start_depth of 0.
E/StudioProfiler: JVMTI error: 103(JVMTI_ERROR_ILLEGAL_ARGUMENT)
I/app           : The stack is not large enough for a start_depth of 0.
E/StudioProfiler: JVMTI error: 103(JVMTI_ERROR_ILLEGAL_ARGUMENT)
I/app           : The stack is not large enough for a start_depth of 0.
E/StudioProfiler: JVMTI error: 103(JVMTI_ERROR_ILLEGAL_ARGUMENT)
W/app           : Verification of void com.android.tools.profiler.support.ProfilerService.<init>(boolean) took 265.237ms

I remember that the profiler was working some time ago and I made a lot of changes so I'm not sure why it's not working anymore.
Thanks in advance!


text:
Q: Android_Can't play the mp4 file generated by MediaMuxer I am trying to use MediaCodec and MediaMux to generate mp4 file. The code I am using is here.
I get some mp4 file. However, I can't play it with my player, which is just a normal software.
Does anyone has any idea? What should I do next?

A: I had a similar issue - in my case I simply wasn't calling muxer.stop() and ended up with a large unplayable file.


text:
Q: How to hide status bar and navigation bar using Theme.MaterialComponents i have some problem to hide status and navigation bar in app.
Assumptions:

*

*use lib com.google.android.material:material:1.1.0-alpha10

*use style Theme.MaterialComponents.Light.NoActionBar

Solutions like
window.apply {
      clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
       addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        } else {
            decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        }
        statusBarColor = Color.TRANSPARENT
}

Doesn't work properly

A: *

*Create new theme in styles.xml:

 <style name="AppTheme.NoActionBar" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:windowBackground">@color/white</item>
    <item name="windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="windowNoTitle">true</item>
</style>

*Apply this theme in Manifest (for desired activity)

<activity
    android:name=".SearchActivity"
    android:label="Text"
    android:theme="@style/AppTheme.NoActionBar" />


text:
Q: Sinon Spy for Non-Class Methods I have a javascript file with a bunch of util functions in a file called utils.js
export const processListOfItems = (input): [] => {
  let listOfItems = [];
  for (var index = 0; index < rawPayload.length; ++index) {
    listOfItems.push(someFunction(item));
  }
  return listOfItems;
};

someFunction is defined in utils.js as well.
For the test, I would like to stub "someFunction," but am having trouble figuring out how to do so. It looks like sinon.spy() might be the method I want, but it looks like it requires an object, of which I don't have one since it's just a utils file.
My ideal test would look something like this
describe('someFunction fails on an item', () => {
  it('returns the array with the rest of the items', () => {
    const items = ['hi', 'hello'];

    // I want to make it such that, when we go into the getListOfItems code, we return 42 whenever we call someFunction, rather than going into the logic itself.
    const someFunctionStub = sinon.stub(someFunction).returns(42);

    expect(getListOfItems(items)).toEqual([42, 42]);
  });
});

A: sinon.stub replaces a property on an object...
...and often the object is a module and the property is a function the module exports.
When the module export of a function is stubbed, any code that calls the module export of the function will then call the stub.

It isn't possible to stub someFunction in the code above since processListOfItems isn't calling the module export of someFunction, it is calling someFunction directly.
processListOfItems needs to call the module export of someFunction in order to be able to stub the call.

Here is a simple example to demonstrate using Node.js module syntax:
util.js
exports.func1 = () => {
  return 'hello ' + exports.func2();  // <= use the module
}

exports.func2 = () => 'world';

util.test.js
const sinon = require('sinon');
const util = require('./util');

describe('func1', () => {
  it('should work', () => {
    const stub = sinon.stub(util, 'func2').returns('everyone');
    expect(util.func1()).toBe('hello everyone');  // Success!
  });
});

...and here is a simple example using ES6 module syntax:
util.js
import * as util from './util';  // <= import module into itself

export const func1 = () => {
  return 'hello ' + util.func2();  // <= use the module
}

export const func2 = () => 'world';

util.test.js
import * as sinon from 'sinon';
import * as util from './util';

describe('func1', () => {
  it('should work', () => {
    const stub = sinon.stub(util, 'func2').returns('everyone');
    expect(util.func1()).toBe('hello everyone');  // Success!
  });
});

Note that ES6 modules can be imported into themselves since they "support cyclic dependencies automatically".


text: Q: Is it possible to use AWS Microsoft AD as one DC in a multi-master setup? Have an on-premise network with two AD servers already. Want to add one more AD server to the AWS cloud. Instead of setting up a Windows VM running AD, I'm wondering if I can use AWS Microsoft AD instead. It seems like it's full-fledged AD, and it would definitely do what I want in a cloud-only scenario, but I can't find explicit documentation on having it sync with other AD servers on the VPN.


text:
Q: Java maximum heap size on SGE cluster I have a pipeline written in python calling some processes in Java. The pipeline runs with two possible modes, on local mode (on a single node) or on SGE cluster.
When I set the option to cluster mode, the error message in the logs are such this
Invalid maximum heap size: -Xmx4g -jar
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

In local mode, there is no error and no problems.
My question is what can cause such an error ?
My class to run jobs either locally or on cluster is as follow
class LocalJobManager(JobManager):
    def __init__(self):
        self.cmd_strs = []

    def add_job(self, cmd, cmd_args, **kwargs):
        cmd_str = ' '.join([cmd, ] + [str(x) for x in cmd_args])

        self.cmd_strs.append(cmd_str)

    def run_job(self, cmd, cmd_args, **kwargs):
        cmd_str = ' '.join([cmd, ] + [str(x) for x in cmd_args])

        self._run_cmd(cmd_str)

    def wait(self):
        for cmd_str in self.cmd_strs:
            self._run_cmd(cmd_str)

    def _run_cmd(self, cmd_str):
        '''
        Throw exception if run command fails
        '''
        process = subprocess.Popen(cmd_str, stdin=subprocess.PIPE, shell=True)

        process.stdin.close()

        sts = os.waitpid(process.pid, 0)

        if sts[1] != 0:
            raise Exception('Failed to run {0}\n'.format(cmd_str))

class ClusterJobManager(JobManager):
    def __init__(self, log_dir=None):
        import drmaa

        self._drmaa = drmaa

        self.log_dir = log_dir

        if self.log_dir is not None:
            make_directory(self.log_dir)

        self.session = self._drmaa.Session()

        self.session.initialize()

        self.job_ids = Queue()

        self._lock = threading.Lock()

    def add_job(self, cmd, cmd_args, mem=4, max_mem=10, num_cpus=1):
        job_id = self._run_job(cmd, cmd_args, mem, max_mem, num_cpus)

        self.job_ids.put(job_id)

    def run_job(self, cmd, cmd_args, mem=4, max_mem=10, num_cpus=1):
        job_id = self._run_job(cmd, cmd_args, mem, max_mem, num_cpus)

        self._check_exit_status(job_id)

    def wait(self):
        self._lock.acquire()

        job_ids = []

        while not self.job_ids.empty():
            job_ids.append(self.job_ids.get())

        self.session.synchronize(job_ids, self._drmaa.Session.TIMEOUT_WAIT_FOREVER, False)

        self._lock.release()

        for job_id in job_ids:
            self._check_exit_status(job_id)

    def close(self):
        self.session.control(self._drmaa.Session.JOB_IDS_SESSION_ALL, self._drmaa.JobControlAction.TERMINATE)

        self.session.exit()

    def _run_job(self, cmd, cmd_args, mem, max_mem, num_cpus):
        job_template = self._init_job_template(cmd, cmd_args, mem, max_mem, num_cpus)

        job_id = self.session.runJob(job_template)

        self.session.deleteJobTemplate(job_template)

        return job_id

    def _init_job_template(self, cmd, cmd_args, mem, max_mem, num_cpus):
        job_template = self.session.createJobTemplate()

        job_template.remoteCommand = cmd

        job_template.args = [str(x) for x in cmd_args]

        job_template.workingDirectory = os.getcwd()

        if self.log_dir is not None:
            job_template.errorPath = ':' + self.log_dir

            job_template.outputPath = ':' + self.log_dir

        job_template.nativeSpecification = '-l mem_free={mem}G,mem_token={mem}G,h_vmem={max_mem}G -V -w n -pe ncpus {num_cpus}'.format(**locals())

        return job_template

    def _check_exit_status(self, job_id):
        return_value = self.session.wait(job_id, self._drmaa.Session.TIMEOUT_WAIT_FOREVER)

        if return_value.exitStatus != 0:
            raise Exception('Job {0} failed with exit status {1}.'.format(return_value.jobId,
                                                                          return_value.exitStatus))

Usually the Could not create the Java Virtual Machine (as I am reading though some forum) is caused by syntax error, even though the command called is correct and works locally, besides the class to run jobs on the cluster show above, runs for everything except Java
Thanks

A: I've run into this on SGE. You may have a default hard memory limit set around 4GB and Java seems to use a bit more than that 4GB you are setting in the -Xmx4g parameter during initialization. Can you see if you administrator has set a hard memory limit? Typically you will set or override the default limit using:
qsub -l h_vmem=16G

Try giving far more memory than needed via that parameter and see if that solves it and then ratchet down the h_vmem as far down as it goes without crashing.


text:
Q: Parse Live Query Memory Leak I'm using parse live query (in js and vue.js) to update/replace an array on each create. I noticed however that live query is causing a memory leak. As I'm running 3 live queries at at time, after day of running I get up to +2GB of memory and and error page with "out of memory".
Here an example of how I open one of my subscriptions.
 Parse.initialize(this.parse.initialize)
        Parse.serverURL = this.parse.serverURL

        const snapshots = Parse.Object.extend("snapshots");
        const query = new Parse.Query(snapshots)
        const subscriptionSnapshots = await query.subscribe()

        subscriptionSnapshots.on('open', () => {
            console.log(' -> Snapshots subscription opened');
        });

I don't know if it's related, but in my browser console I see the following alerts
[Violation] 'message' handler took <N>ms
parse.min.js:13 [Violation] 'message' handler took 164ms

Any ideas where the leak comes from and how I can stop it ?


text:
Q: Actual Difference Between Call and Apply while Passing the array as an argument While Passing Array in call Method works well as I am able to iterate it,but
in case of apply it gives an error while iterating the array. (although it only takes array-like object as argument)
var student = {
   fname:'vipul',
    lname:'jadhav',
    fullName:function(){
        return (this.fname+' '+this.lname);
    }
}

function getMarks(marks){

    console.log('USER : '+this.fullName());
    console.log('MARKS :')
    for(let i of marks){

        console.log('marks :'+i);
    }

}

var getMarksCall = getMarks.call(student,[99,78,89,90]);
var getMarksApply = getMarks.apply(student,[99,78,89,90]);

It gives an error as
Uncaught TypeError: marks is not iterable

In another case when i changes for loop to
    for(let i=0 ;i<marks.length;i++){

        console.log('marks :'+marks[i]);
    }

then i got to know that marks is only the first value of array.(see image)
debugger_screenshot
1.what is the actual difference between the call and apply..
because call also supports the array as argument then what is the need of apply?
2.why the difference between iterating the array in two methods?
3.How to iterate the array in apply?
Could anyone please help me to geeting this ?

A: Function#apply needs an array of parameters, but here you have an array of values which is not iterable for the inner for loop.
To get it working, you need to wrap the array as parameter in an array.

var student = {
    fname: 'vipul',
    lname: 'jadhav',
    fullName: function() {
        return (this.fname + ' ' + this.lname);
    }
}

function getMarks(marks) {
    console.log('USER : ' + this.fullName());
    console.log('MARKS :')
    for (let i of marks) {
        console.log('marks :' + i);
    }
}

var getMarksCall = getMarks.call(student, [99, 78, 89, 90]);
var getMarksApply = getMarks.apply(student, [[99, 78, 89, 90]]);
//                                          ^                ^
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: apply() method accepts an array of arguments. So if you are passing an array as an argument then it should be inside an array.
var getMarksApply = getMarks.apply(student, [[99, 78, 89, 90]]);

The only difference between both is call() method can accept a parameter or array of parameters but apply() method only accepts an array of parameters.
No such difference between iterating an array in both of the methods.
For more details please refer this https://www.codingame.com/playgrounds/9799/learn-solve-call-apply-and-bind-methods-in-javascript


text:
Q: Type based tag dispatching: Is it possible to differently tag containers based on the tags of their elements? Pleases disregard the row of warnings because of unused variables, the algorithms are dummy example functions.
Also, sorry for the lengthy post, I tried to shorten it as much as possible.
The following tag types and the tag structure are given:
namespace tags {

    struct ordinary_tag{};
    struct special_tag {};
    struct extra_special_tag {};

    struct ordinary_collection_tag {};
    struct special_collection_tag {};

    template<typename Type>
    struct tag
    {
        typedef void type;
    };

}

and the concrete classes used for algorithm arguments:
class concrete_one {};
class concrete_two {};

The implementation namespace stores implementations of an algorithm algorithm, based on the type of the algorithm result, which can be any type, that is tagged with a specific tag. The tag of the results determines the algorithm chosen:
namespace implementation {

template<typename Result, typename Tag>
struct algorithm {};

template<typename Result>
struct algorithm<Result, tags::ordinary_tag>
{
    static Result apply(concrete_one const & a1, concrete_two const & a2)
    {
        Result r;

        std::cout << "ordinary" << std::endl;
        // Modify r using a1, a2.

        return r;
    }

    // Commutative algorithm.
    static Result apply(concrete_two const & a1, concrete_one const & a2)
    {
        return apply(a2, a1);
    }
};

template<typename Result>
struct algorithm<Result, tags::special_tag>
{
    static Result apply(concrete_one const & a1, concrete_two const & a2)
    {
        Result r;

        std::cout << "special" << std::endl;
        // Modify r using a1, a2.

        return r;
    }
};
...

and the algorithms are also tagged for collections of tagged element types, like for example when the Result is tagged as a collection of ordinary types:
template<typename Result>
struct algorithm<Result, tags::ordinary_collection_tag>
{
    static Result apply(concrete_one const & a1, concrete_two const & a2)
    {
        Result r;

        std::cout << "ordinary collection" << std::endl;

        // Modify r using a1, a2.

        return r;
    }
};

The algorithms from the implementation namespace are dispatched by a function template that uses variadic arguments:
template<typename Result, typename ... Arguments>
Result algorithm(Arguments ... args)
{
    // Dispatch to the appropriate algorithm based on the result tag
    // and overload within the algorithm structure for the variadic arguments
    return implementation::algorithm<Result, typename tags::tag<Result>::type>::apply(args ...);
}

Some types are defined and tagged differently:
struct first_type {};

namespace tags {
    // Make first_type behave as ordinary type.
    template<>
    struct tag<first_type>
    {
        typedef ordinary_tag type;
    };
}

struct second_type {};

namespace tags {
    // Make second_type behave as a special type.
    template<>
    struct tag<second_type>
    {
        typedef special_tag type;
    };
}

and they work perfectly fine as expected:
concrete_one c1;
concrete_two c2;

first_type f1 = algorithm<first_type>(c1, c2);

second_type f2 = algorithm<second_type>(c1, c2);

but the problem is in a specialization of tag to take into account any container with an allocator, and tag it based on the tag of the container element type. This is what I have tried to do:
namespace tags
{
    // An attempt to tag all Containers with Allocator of ordinary tagged types using ordinary_collection_tag.
    template
    <
        typename OrdinaryType,
        template <typename, typename> class Container,
        template <typename> class Allocator
    >
    struct tag
    <
        typename std::enable_if
        <
            std::is_same<typename tags::tag<OrdinaryType>::type, tags::ordinary_tag>::value, // true if OrdinaryType is tagged with ordinary_tag
            Container<OrdinaryType, Allocator<OrdinaryType>> // Use this as the T argument of enable_if
        >::type // in enable_if specialized for "true" :: typename T type;
    >
    {
        typedef ordinary_collection_tag type;
    };
}

Expecting that enable_if will provide as it's T argument the Container<OrdinaryType, Allocator<OrdinaryType>> if the human-named OrdinaryType really is tagged with ordinary_tag - this is the boolean argument to enable_if that should be provided by is_same. I tried to use the STL containers that hold the first_type tagged as ordinary in the following way:
    typedef std::list<first_type> first_type_list;
    typedef std::vector<first_type> first_type_vector;

    first_type_list fl = algorithm<first_type_list>(c1, c2);
    first_type_vector fv = algorithm<first_type_vector>(c1, c2);

Instead of recognizing first_type_list/vector as ordinary_collection_tag-ed types, I get the following error:
test-other.cpp:158:12: error: template parameters not used in partial specialization:
     struct tag
test-other.cpp:158:12: error:         'OrdinaryType'
test-other.cpp:158:12: error:         'template<class, class> class Container'
test-other.cpp:158:12: error:         'template<class> class Allocator'

Now, when I don't enable the tag specialization based on the tag of the OrdinaryType, and I specialize it for any OrdinaryType like this:
// Works but doesn't see that OrdinaryType should be tagged with ordinary_tag,
// std::list<first_type> and std::vector<second_type> are both tagged ordinary_collection_tag.
//namespace tags
//{
    //template
    //<
        //typename OrdinaryType,
        //template <typename, typename> class Container,
        //template <typename> class Allocator
    //>
    //struct tag
    //<
        //Container<OrdinaryType, Allocator<OrdinaryType>>
    //>
    //{
        //typedef ordinary_collection_tag type;
    //};
//};

then types like std::vector<first_type> and std::list<second_type> get both tagged with ordinary_collection_tag even though second_type is tagged with the special_tag. This is what I have expected.
So, what did I do wrong?
I'm using gcc 4.8.2.
The complete small program can be found here.

A: Since no one answered yet and I have found a possible solution to the problem, I've decided to post it.
Instead of trying to partially specialize tag for any container like I did in the question, I assumed that having a container of elements is a general case. As a result, the tag<Type> template expexts Type to be a collection. If Type does not satisfy this condition, the template deduction chooses another specialization of Type that fits: the one for a single element. The condition is imposed by introducing a collection structure. Any container that has value_type available is now recognized as a collection of tagged elements.
Here is the solution (I just changed the names of types into fruit names, I guess to make it more easy to read):
#include <type_traits>
#include <iostream>
#include <list>
#include <vector>
#include <map>

namespace tags {

    struct apple_tag {};
    struct banana_tag {};

    struct apple_collection_tag {};
    struct banana_collection_tag {};

    template<typename Tag>
    struct collection {};

    template<>
    struct collection<apple_tag>
    {
        typedef apple_collection_tag type;
    };

    template<>
    struct collection<banana_tag>
    {
        typedef banana_collection_tag type;
    };

    template<typename Type>
    struct tag
    {
        typedef typename collection<typename tag<typename Type::value_type>::type>::type type;
    };

    // Select tags of pairs based on the second type. Used for maps (key, value) pairs.
    template
    <
        typename First,
        typename Second
    >
    struct tag<std::pair<First, Second>>
    {
        typedef typename tag<Second>::type type;
    };
}

struct apple {};

namespace tags {
    template<>
    struct tag<apple>
    {
        typedef apple_tag type;
    };
}

struct banana {};

namespace tags {
    template<>
    struct tag<banana>
    {
        typedef banana_tag type;
    };
}

template<typename Type>
struct my_container
{
    typedef Type value_type;
};

namespace implementation {

    template<typename Type, typename Tag>
    struct function {};

    template<typename Type>
    struct function<Type, tags::apple_tag>
    {
        static void apply(Type const& t)
        {
            std::cout << "apple" << std::endl;
        }
    };

    template<typename Type>
    struct function<Type, tags::banana_tag>
    {
        static void apply(Type const& t)
        {
            std::cout << "banana" << std::endl;
        }
    };

    template<typename Type>
    struct function<Type, tags::apple_collection_tag>
    {
        static void apply(Type const& t)
        {
            std::cout << "apple collection" << std::endl;
        }
    };

    template<typename Type>
    struct function<Type, tags::banana_collection_tag>
    {
        static void apply(Type const& t)
        {
            std::cout << "banana collection" << std::endl;
        }
    };
}

// Value tag Dispatcher
template<typename Type>
void function(Type const & t)
{
    implementation::function<Type, typename tags::tag<Type>::type>::apply(t);
}

int main(int argc, const char *argv[])
{
    typedef std::list<apple> apple_bag;

    apple_bag abag;

    function(abag);

    typedef std::vector<apple> apple_box;

    apple_box abox;

    function(abox);

    typedef std::map<int, apple> apple_orchard;

    apple_orchard ao;

    function (ao);

    // my_container has value_type, so it can be used as well.
    typedef my_container<banana> banana_bag;

    banana_bag bo;

    function(bo);

    return 0;
}

That's it. Here's the output:
apple collection
apple collection
apple collection
banana collection


text:
Q: Another way to prove that if n$^{th}$-degree polynomial $r(z)$ is zero at $n+1$ points in the plane, $r(z)\equiv 0$? The original problem is as follows

Let $p$ and $q$ be polynomials of degree $n$. If $p(z)=q(z)$ at $n+1$ distinct points of the plane, the $p(z)=q(z)$ for all $z\in \mathbb{C}$.

I attempted showing this is by taking the polynomial $r(z)=p(z)-q(z)$. Since both $p(z)$ and $q(z)$ are both polynomials of degree $n$, $r(z)$ can either be identically zero ($r(z)\equiv 0$), or it can be a polynomial of a degree less than $n$. However, if $p(z)=q(z)$ at $n+1$ distinct points, then $r(z)=0$ at $n+1$ points, which can only happen if $r(z)\equiv 0$ by the fundamental theorem of algebra. Hence, $p(z)=q(z)$. $\blacksquare$.
Is this the correct way to prove this? Is there another way? I'm asking this because I immediately jumped to this proof, and usually I'm wrong with these problems that are at the end of the problem set for a subsection.

A: When people say "Fundamental Theorem of Algebra", they usually mean the result that every complex polynomial has a complex root. This is far simpler than that, since it's true over any field at all, not even of characteristic zero.
For a proof, let $\rho_1,\dots,\rho_n,\rho_{n+1}$ be the roots. Then by Euclidean division, you show that $X-\rho_1$ divides your original $r(X)$, in such a way that the quotient polynomial still vanishes at the other $\rho_i$'s. Then you proceed by induction to show that $\prod_i(X-\rho_i)$ divides your original. But the product of all the $X-\rho_i$ is of degree $n+1$. So that original $r(X)$ has to have been zero to start with.