text:
Q: AttributeError when attempting to save a file downloaded from requests I am trying to save MP3 media files as they are packaged in a requests response to local storage. I've defined a model MP3, with its corresponding manager, MP3Manager. In the manager, we have a class method used for obtaining the data, ideally from the local database, but from an external media server if not present. This retrieval occurs in a class method called get_mp3().
Inside get_mp3(), we also have save_mp3(), which is meant to take the bytes string from response.content, save it to the filesystem, and create a database entry. However, there appears to be some kind of formatting issue, because I get the following error while executing the save_mp3() return statement:
AttributeError: '_io.BufferedWriter' object has no attribute '_committed'

How do I resolve this? Entire mp3.py file here:
import os
import requests

from django.db import models
from django.utils.translation import gettext_lazy as _

from rest_framework import status
from rest_framework.exceptions import NotFound

from api.exceptions import InternalServerError
from api.models import TimestampedModel

class MP3Manager(models.Manager):
    """
    Class defining utility methods for downloading MP3 pronunciation audio files from the Merriam-Webster media servers.
    """
    @classmethod
    def get_mp3(cls, id, url):
        """
        Obtains an MP3 file from local storage if a database entry exists, and downloads from the Merriam-Webster database on a cache miss.
        """
        mp3 = None

        try:
            # Check the local database.
            mp3 = cls.get(id=id)
        except MP3.DoesNotExist:
            # Not in store. Download and save file.
            response = requests.get(url)

            if response.status_code == status.HTTP_404_NOT_FOUND:
                raise NotFound(_('The specified ID was invalid.'))
            elif response.status_code != status.HTTP_200_OK:
                raise InternalServerError(
                    _(
                        'The file could not retrieved. Please contact support at support@example.com.'
                    ))

            filepath = f'/tmp/{id}.mp3'

            def save_mp3():
                """
                Save the downloaded file to the filesystem and local database.
                """
                with open(filepath, 'xb') as f:
                    content = response.content
                    for i in range(0, len(content), MP3.block_size):
                        upper = min(i + MP3.block_size, len(content))
                        f.write(content[i:upper])

                    return cls.create(id=id, data=f)

            try:
                mp3 = save_mp3()
            except FileExistsError:
                os.remove(filepath)
                mp3 = save_mp3()

        return mp3

class MP3(TimestampedModel):
    """
    Timestamped model for MP3 pronunciation audio files downloaded from the Merriam-Webster media servers.
    """
    # Static Variables
    objects = MP3Manager()
    relative_path = 'mp3'
    block_size = 2**16

    # Attributes
    id = models.CharField(primary_key=True, max_length=64)
    data = models.FileField(_('MP3'), upload_to=relative_path)
    _hash = models.BinaryField(
        _('MD5 hash'), editable=False, null=True, default=None, max_length=16)

Traceback here:
Traceback (most recent call last):
  File "/home/matt/Repositories/Iconopedia/back-end/api/dictionary/models/mp3.py", line 51, in get_mp3
    mp3 = MP3.objects.get(id=id)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 435, in get
    raise self.model.DoesNotExist(
api.dictionary.models.mp3.MP3.DoesNotExist: MP3 matching query does not exist.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/matt/Repositories/Iconopedia/back-end/api/dictionary/models/mp3.py", line 85, in get_mp3
    mp3 = save_mp3()
  File "/home/matt/Repositories/Iconopedia/back-end/api/dictionary/models/mp3.py", line 76, in save_mp3
    with open(filepath, 'xb') as f:
FileExistsError: [Errno 17] File exists: '/tmp/apple001.mp3'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/matt/Repositories/Iconopedia/back-end/api/dictionary/tests/test_mp3.py", line 42, in test_success_miss
    response = self.client.get(self.url_path, format='json')
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/rest_framework/test.py", line 288, in get
    response = super().get(path, data=data, **extra)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/rest_framework/test.py", line 205, in get
    return self.generic('GET', path, **r)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/rest_framework/test.py", line 233, in generic
    return super().generic(
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/test/client.py", line 473, in generic
    return self.request(**r)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/rest_framework/test.py", line 285, in request
    return super().request(**kwargs)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/rest_framework/test.py", line 237, in request
    request = super().request(**kwargs)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/test/client.py", line 719, in request
    self.check_exception(response)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/test/client.py", line 580, in check_exception
    raise exc_value
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/matt/Repositories/Iconopedia/back-end/api/dictionary/views/mp3_views.py", line 28, in get
    mp3 = MP3.objects.get_mp3(id)
  File "/home/matt/Repositories/Iconopedia/back-end/api/dictionary/models/mp3.py", line 88, in get_mp3
    mp3 = save_mp3()
  File "/home/matt/Repositories/Iconopedia/back-end/api/dictionary/models/mp3.py", line 82, in save_mp3
    return MP3.objects.create(id=id, data=f)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 453, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 726, in save
    self.save_base(using=using, force_insert=force_insert,
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 763, in save_base
    updated = self._save_table(
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 868, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 906, in _do_insert
    return manager._insert(
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 1270, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1415, in execute_sql
    for sql, params in self.as_sql():
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1358, in as_sql
    value_rows = [
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1359, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1359, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1310, in pre_save_val
    return field.pre_save(obj, add=True)
  File "/home/matt/Repositories/Iconopedia/back-end/.venv/lib/python3.9/site-packages/django/db/models/fields/files.py", line 300, in pre_save
    if file and not file._committed:
AttributeError: '_io.BufferedWriter' object has no attribute '_committed'

A: Built-in python file object can't be passed directly to Django's FileField, we need to wrap it like this:
from django.core.files import File

content = File(f)
mp3.id = id
mp3.data.save("your_file_name.mp3", content, save=False)
mp3.save()

Refer to: Django Shell image upload _io.BufferedReader no attribute size
https://docs.djangoproject.com/en/3.2/ref/files/file/#django.core.files.File


text:
Q: Condition with enum always evaluating to true Ok I am sure there has to be something stupid here. I haven't really used an enum so maybe I am just doing something incorrect. I am creating a red-black tree implementation and I am using an enum inside of class Node to for if it is a red or black node. I've stepped through the code and when I reach this statement for the given node I am trying to insert, it should not execute the loop as the parent's color is black not red! For some reason this evaluates to true and I am not sure why... Any assistance would be greatly appreciated! Thank you! :)
while(x->m_parent->m_color == (Node::Color::ST_Red)) ;

This is part of my Node class just in case.
class Node
{
public:
    Node()
    {
        m_data = 0 ;
        m_color = Node::Color::ST_Red ;
    }

    enum Color
    {
        ST_Red,
        ST_Black
    };

private:
    int m_data ;
    Color m_color ;
    Node* m_parent;

};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exception in thread "main" java.lang.NoSuchMethodError: main
Possible Duplicate:
Exception in thread "main" java.lang.NoSuchMethodError: main

public class m
{
    int a; //class variable

    void f1()
    {
       int b=10;
       System.out.println(a);
       System.out.println(b);
    }
}
class B
{
   public static void main(String args[])
   {
      m ob=new m(); //object created
      ob.f1(); //calling f1 method

   }
}

A: I'll guess.
You are trying to invoke:
java m

Since you defined you main method in class B you should call
java B

To execute it.
Here's my test:
$cat >m.java<<.
> public class m
> {
>     int a; //class variable
>     void f1()
>     {
>        int b=10;
>        System.out.println(a);
>        System.out.println(b);
>     }
> }
> class B
> {
>    public static void main(String args[])
>    {
>       m ob=new m(); //object created
>       ob.f1(); //calling f1 method
>    }
> }
> .
$javac m.java
$java m
Exception in thread "main" java.lang.NoSuchMethodError: main
$java B
0
10
$

If you see, invoking java B prints 0 10as expected.

A: Main needs to be in the top-level class whose name corresponds to the filename - so if "m" is the name of your file that's where main needs to be. Note that by convention class names start with an uppercase letter.

A: Did you invoke the Java program with java m?
The main method is defined in the class B, not m, therefore, you need the java B command to invoke it.
It may be confusing if you reasoned by "Same as filename.".
Also, putting two classes in one file may be a bad practice.


text:
Q: IP Address range for Azure Notification Hub I'm communicating from a protected server to an Azure Notification Hub service, using the endpoint provided by Azure (https://.servicebus.windows.net) -> 23.100.11.236
I need to open a firewall from my protected server to Azure. I can only do it using an IP address not a domain name.
I appreciate from other answers on Stack Overflow that it is not possible to have a static IP address assigned, and that the IP address could change over time.
I have two questions:

*

*In your experience, how often does such an IP address actually change?

*Is there an IP address RANGE which would remain valid, even if the specific IP within the range changes?

A: Answers inline..
1.In your experience, how often does such an IP address actually change?
 The IP addresses don't change often but there is no guarantee they never will.
2.Is there an IP address RANGE which would remain valid, even if the specific IP within the range changes?
 Refer to this link for the range of Azure IP Address range per datacenter:
https://www.microsoft.com/en-us/download/details.aspx?id=41653
You can whitelist all the IP Ranges for the datacenter your NotificationHub is in.
PS: You should check that link for any new additions to IP ranges.


text:
Q: Ubuntu 18.04 update problem "g_strchug: assertion 'string != NULL' failed" When I update Ubuntu from 16.04 to 18.04, there is a flood of errors:
$ sudo apt update && sudo apt upgrade
Hit:1 http://ubuntu.ntc.net.np/ubuntu bionic InRelease
(appstreamcli:30076): GLib-CRITICAL **: 20:36:32.027: g_strchug: assertion 'string != NULL' failed
(appstreamcli:30076): GLib-CRITICAL **: 20:36:32.027: g_strchomp: assertion 'string != NULL' failed
corrupted double-linked list
Aborted (core dumped)
Reading package lists... Done
E: Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/test -w /var/cache/app-info -a -e /usr/bin/appstreamcli; then appstreamcli refresh > /dev/null; fi'
E: Sub-process returned an error code

Also, when I check my Ubuntu version, it shows 18.04 in terminal, but in startup it shows 16.04. How to resolve this?


text:
Q: Azure App Service Service Endpoint configuration Can anyone advise me on how to configure two app services on a vnet (or otherwise) so that app service 'A' can offer up a restful API and service 'B' call the API on A repeatedly without experiencing SNAT port exhaustion?
Our current set up is just 2 app services (one calling the other) without a vnet. Both are accessible publicly and I'd like to keep it this way 1) for debugging, and 2) as other servers may be connecting to server 'A'. The problem is we're seeing port exhaustion...
"Private endpoint" on server A and vnet integration on B seems easy enough to configure but this causes A to become unavailable over the internet.
I've tried fiddling with the subnets and service end points options in the virtual network to no avail. I've also tried the "endpoint service policy" feature but that only seems to let me select Microsoft Storage resources...
Any tips or advice would be gratefully appreciated.
Thank you

A:
Can anyone advise me on how to configure two app services on a vnet
(or otherwise) so that app service 'A' can offer up a restful API and
service 'B' call the API on A repeatedly without experiencing SNAT
port exhaustion?

One of the workaround , you can follow
Please check if findings are correct:-
Two app services are communicated with via v-net integration and a private link. If you're only going to use the v-net integration and not the private link. Then outbound requests are possible, but inbound requests are not. This is why apps are unable to communicate with one another.
Private Endpoint with VNet Integration:- Private Endpoint assigns a unique IP address to your app for inbound traffic exclusively. It prevents your app from making outgoing calls within your network. You must utilize both Private Endpoint and Regional VNet Integration on two separate subnets if you want to have all inbound and outbound traffic in your VNet. You can secure inbound traffic with Private Endpoint, and outbound traffic with VNet Integration.
Here is the workflow that how v-net integration working with app services:

For more information please refer the below links:-

*

*SO THREAD|Azure App Service to App Service communication via Private Link & Connecting two App Services within the same VNet

*MICROSOFT DOCUMENTATION|Using Private Endpoints for Azure Web App & Use IHttpClientFactory to implement resilient HTTP requests.

A: You are hitting a limitation of Azure app Services here. A public app service (with vnet integration) is only pre-allocated 128 SNAT ports. This may not be enough in certain scenarios. As described in detail here, this can be resolved by using:

*

*Connection pools: By pooling your connections, you avoid opening new network connections for calls to the same address and port.

*Service endpoints: You don't have a SNAT port restriction to the services secured with service endpoints.

*Private endpoints: You don't have a SNAT port restriction to services secured with private endpoints.

*NAT gateway: With a NAT gateway, you have 64k outbound SNAT ports that are usable by the resources sending traffic through it.
If I would apply those recommended solutions to your specific scenario, I think the only options are solution 1 (connection pooling) and 4 (azure firewall):

*

*I would certainly recommend connection pooling. This is a minor change in the code running within your app service. If you are a senior programmer you might have already implemented this correctly.

*In your situation you want the app service to remain public, so using service endpoints is not an option.

*In your situation you want the app service to remain public, so using private endpoints is also not an option.

*If connection pooling alone is not enough, then your only option is to implement a NAT gateway or Azure firewall. Azure firewall itself provides 2,496 SNAT ports (source) per public IP address configured. Azure firewall is pretty expensive, so keep that in mind. In short, you'll have to do the following:

*

*Create a vnet with some subnets.

*The subnet used for the vnet integration should be dedicated.

*The subnet used for the azure firewall should also be dedicated.

*Create an azure firewall.

*Create route tables and an NSG if applicable.

*Enable vnet integration with the vnet "route all" option.


text:
Q: What humidity sensors allow the user to configure their I2C address? I'm building something that will need to use eight humidity sensors, and I want to use I2C to communicate with them. However, all humidity sensors I've found either have a fixed I2C address, or sometimes they have an address pin to choose between two addresses. The most I've found was the TI HDC1010, which has two address pins, so four possible I2C addresses, but that's still not enough.
Are there any humidity sensors that either have three address pins, or that have a fully configurable I2C address?

A: As far as I know there is no humidity sensor with 3 address bits available (at least I don't know any).
Yet, you could use some I2C Mux (example: PCA9548) to switch between the different sensors. Additionally , this will also give you the benefit of lower capacitance on the I2C bus, thus resulting in higher possible speed (although this is rarely required for humidity sensors).


text:
Q: Calling a function that in inside an event from another event outside I've been struggling with a javascript problem, which I can't seem to find the solution to solve it.
How can I call a function that is inside an event like this :
$('a.buttoncomments').live( 'click', function () {
    function getComments(productId,revisionId,commentId) {
        // some stuff
    }
});

from another event :
$("#container-comments").on('scroll', function() {
if($(this).scrollTop() + $(this).innerHeight()>=$(this)[0].scrollHeight && onScroll === false) {
            onScroll = true;
            nTcommentId = $(".commentId").last().val();
            // call the function here -> getComments(value,value,value);
            onScroll = false;
        }
});

When I do this way, it tells me that :

Uncaught ReferenceError: getComments is not defined

Well I think that is all the code required in order for you guys to tell me what im missing!
Thanks by advance!

A: define getComments outside of the click event. Currently it is scoped only to that function.


text:
Q: Signum function and Fourier transform I'm extracting a portion of my notes which I believe I might have copied wrongly.
Given this equation:
$$\frac{G(\omega)}{2ic\omega} [e^{ic\omega t}-e^{-icwt}]$$
I want to find the Fouerir transform of the above. I believe it involves the Fourier transform of the signum function.
The Signum function is:
$$sgn(x) = \left\{\begin{matrix}
1 ,&x>0 \\
 0,&x=0 \\
-1, &x<0
\end{matrix}\right.$$
On my notes it says the Fourier transform of sgn(x) to be
$$\frac{1}{\pi i\omega}$$ (is this the correct?)
Secondly, how do I apply the fourier transform to the above equation?
I'm pretty lost so any help would be good.

A: $$x(t) = sgn(t)$$
$$\frac{dx(t)}{dt} = 2\delta(t)$$
Now take fourier transform in both side
$$(j\omega)X(\omega) = 2$$
$$ X(\omega) = \frac{2}{j\omega}$$
$$sgn(t) \rightleftharpoons \frac{2}{j\omega}$$


text:
Q: Android Studio build finished, but cannot run at real device This is the main activity of xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    tools:context="com.example.liew.idelivery.MainActivity">

<LinearLayout
    android:orientation="vertical"
    android:layout_centerInParent="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_gravity="center"
        android:src="@drawable/logo" />

    <TextView
        android:id="@+id/txtSlogan"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:gravity="center"
        android:text="@string/slogan"
        android:textAlignment="center"
        android:textColor="@android:color/white"
        android:textSize="18sp"
        android:textStyle="italic" />
</LinearLayout>

<LinearLayout
    android:orientation="horizontal"
    android:layout_alignParentBottom="true"
    android:weightSum="2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <info.hoang8f.widget.FButton
        android:id="@+id/btnSignUp"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:layout_weight="1"
        android:text="Sign Up"
        android:textColor="@android:color/white"
        app:buttonColor="@color/btnSignUp"
        app:cornerRadius="4dp"
        app:shadowColor="@android:color/black"
        app:shadowEnabled="true"
        app:shadowHeight="5dp" />

    <info.hoang8f.widget.FButton
        android:id="@+id/btnSignIn"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:layout_weight="1"
        android:text="Sign In"
        android:textColor="@android:color/white"
        app:buttonColor="@color/btnSignUp"
        app:cornerRadius="4dp"
        app:shadowColor="@android:color/black"
        app:shadowEnabled="true"
        app:shadowHeight="5dp" />

</LinearLayout>

And this is the error that i found in my logcat.
  E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.liew.idelivery, PID: 18266
    java.lang.RuntimeException: Unable to start activity

ComponentInfo{com.example.liew.idelivery/com.example.liew.idelivery.MainActivit
  y}: android.view.InflateException: Binary XML file line #43: Error inflating
      class info.hoang8f.widget.FButton
        at
     android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2462)
        at
     android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2534)
        at android.app.ActivityThread.access$900(ActivityThread.java:164)

A: I think the error occurred as there is no closing tag for RelativeLayout. If the problem still persists try to attach the MainActivity file as well, I'll check it.
One last suggestion: Try to use ConstraintLayout instead of LinearLayout and RelativeLayout :)

A: android.view.InflateException: Binary XML file line #43: Error inflating class
Exception arise only there are something wrong in xml file first of all your xml files need to close with the tag
</RelativeLayout>

Other possibility is that custom views which are you using,  make sure the views are on the correct path (package name exist with the path)
info.hoang8f.widget.FButton


text:
Q: Can I change the location of the view scripts in Zend Framework? Right now the view scripts for my Zend Framework application are located in the application/views/scripts directory. Is it possible to change this location to something that is configurable?
I am assuming this goes somewhere in the index.php file or my application.ini file.

A: I found the solution using partial guesswork with the application.ini file.  Here are the two Entries you can change in Zend Framework 1.11.12.
resources.layout.layoutPath = "/path/to/layouts/"
resources.view.scriptPath = "/path/to/scripts/"

A: For convenience ZF automatically sets the view script path to be module/views/scripts/controller/action.phtml
You can add a script path via $view->addScriptPath('/path/to/view/scripts') which adds this new path to the stack of available view script paths. It checks the last one set first, then checks on the one before until it finds a file.
Or you can reset the script path via $view->setScriptPath('/path/to/view/scripts')
If you need to do this for a controller place this in your _init() method. If you need it for your entire application I'd recommend sticking it in your Bootstrap.
I believe it's also possible to place this in application.ini via: resources.view.basePath = "/path/to/views/"
See http://framework.zend.com/manual/en/zend.view.controllers.html


text:
Q: $\lim_ {x\to 0} \frac{a^x\sin(bx)-b^x\sin(ax)}{\tan(bx)-\tan(ax)}$ Determine
$$\lim_ {x\to 0} \frac{a^x\sin(bx)-b^x\sin(ax)}{\tan(bx)-\tan(ax)}.$$
Considering $a$ not equal to $b$, I tried to do this by dividing $\tan(bx)$ and $\tan(ax)$ by $bx$ and $ax$ respectively but I think its not right. Am I allowed to this as this was on further simplifying (doing the same with sine in numerator) giving the correct answer which was $1$.

A: $$\lim_{x\to0}\frac{a^{x}sin(bx)-b^{x}sin(ax)}{tan(bx)-tan(ax)}$$
Since it's of the form $\frac{0}{0}$ in the direct substitution. L'hopital rule can be used.
$$\lim_{x\to0}\frac{a^{x}bcos(bx)-b^{x}acos(ax)+a^{x}\ln(a)sin(bx)-b^{x}\ln(b)sin(ax)}{bsec^{2}(bx)-asec^{2}(ax)}$$
Now directly put $x=0$ which gives us
$$\lim_{x\to 0}\frac{b-a}{b-a}$$ which is $1$

A: Use L'Hospital's rule to say
\begin{align*}
L &= \lim\limits_{x\to 0}\frac{a^x\sin(bx) - b^x\sin(ax)}{\tan(bx) - \tan(ax)}\\
&= \lim\limits_{x\to 0}\frac{\frac{d}{dx}(a^x\sin(bx) - b^x\sin(ax))}{\frac{d}{dx}(\tan(bx) - \tan(ax))}\\
&= \lim\limits_{x\to 0}\frac{a^x\ln(a)\sin(bx) + ba^x\cos{bx} - b^x\ln(b)\sin(ax) - ab^x\cos(ax)}{b\sec^2(bx) -a\sec^2(ax)}\\
&= \frac{1\times\ln(a)\times 0+b\times 1\times 1-1\times\ln(b)\times 0-a\times 1\times 1}{b-a}\\
&=1
\end{align*}
hence completing the answer.

A: The given limit to be evaluated is $L = \lim\limits_{x\to 0}\frac{a^x\sin(bx) - b^x\sin(ax)}{\tan(bx) - \tan(ax)}$, which becomes $\frac{0}0$ on direct substitution.
Therefore, by L'Hospital's rule (not sure of the spelling) :
$$L = \lim\limits_{x\to 0}\frac{a^x\sin(bx) - b^x\sin(ax)}{\tan(bx) - \tan(ax)} = \lim\limits_{x\to 0}\frac{\frac{d}{dx}(a^x\sin(bx) - b^x\sin(ax))}{\frac{d}{dx}(\tan(bx) - \tan(ax))} =  \lim\limits_{x\to 0}\frac{a^x\ln(a)\sin(bx) + ba^x\cos{bx} - b^x\ln(b)\sin(ax) - ab^x\cos(ax)}{b\sec^2(bx) -a\sec^2(ax)}$$
Now on substituting $x = 0$, $$L = \frac{0 +b\times 1 \times \cos(0) - 0 - a \times 1 \times \cos(0)}{b - a} = 1$$
NB: the end result is a definite value if $a \neq b$

A: $$\lim_ {x\to 0} \frac{a^x\sin(bx)-b^x\sin(ax)}{\tan(bx)-\tan(ax)}$$
$$\lim_ {x\to 0} \frac{a^x\frac{\sin(bx)}{x}-b^x\frac{\sin(ax)}{x}}{\frac{\tan(bx)}{x}-\frac{\tan(ax)}{x}}$$

*

*$$\color{blue}{\lim_{x\to0}\frac{\sin(kx)}{x}=\lim_{x\to0}\frac{\tan(kx)}{x}=k}$$

*$$\implies \frac{a^0b-b^0a}{b-a}=1$$

*You can divide with $x$ as $x\to 0 \neq0$


text:
Q: The origin of Japanese translation of sheaf, 層 A sheaf (French faisceau) is called 層 in Japanese. Literal meaning of 層 would be a layer, a stratum, or a story (as in a building,) so the terminology is a bit different from what sheaf or faisceau might suggest. Korean and Chinese translations are the same, but Japaneses are likely the first to use the translation, per the early contribution of Japanese mathematicians like Oka Kiyoshi.
Who was the first to introduce the translation 層, and why?

A: Akizuki Yasuo seems to be the one who first used the term. According to his book 輓近代数学の展望 (quoted from here):

層という訳語の由来は仏語 Faisceau のあとの方の 'ソー' をとったというが一つの根拠である。Faisceau の元来の意味は束 (タバ) である。'群の束' (X 上に配置された) の意である。ところで、これを横に見ると地層のような層になる。そこで、垂直を水平におきかえて層と訳してみたのである。この訳がよいか、悪いか、わが国で定着しているかどうか知らないが、この訳語の発案者として、その由来を記しておく。
--秋月康夫「輓近代数学の展望」p.176 (1970年)。ダイヤモンド社。東京

So he chose to use 層 because:

*

*it sounds like the last syllable of faisceau, (which complies with Zhen Lin's answer,)

*the word 束("bundle") had been already taken,

*and if you change your perspective, layers are a horizontal bundle.

It's worth noting that English-speaking mathematicians also tried to introduce the term stack for faisceau for similar reasons, as seen in Hodge & Atiyah (1955):

The French word "faisceau" has been translated into English as "sheaf" or "stack". In this paper we use the word "stack", since "sheaf" has been used before in mathematics.

A: According to Masaki Kashiwara:

It has been said that, when they translated this term into Japanese, they decided to translate it as "sō (sheaf)" because the pronunciation is similar to the sound of "faisceau." However, I haven't been able to confirm if this is true or not.

There is a similar hypothesis for 函数 (= function) in Mandarin Chinese: the first character, hán, is pronounced like the first syllable of "function". (There are other hypotheses.)


text:
Q: More clarification about the usage of split in Perl I have this following input file:
test.csv
done_cfg,,,,
port<0>,clk_in,subcktA,instA,
port<1>,,,,

I want to store the elements of each CSV column into an array, but I always get error when I try to fetch those "null" elements in the csv when I run the script. Here's my code:
# ... assuming file was correctly opened and stored into
# ... a variable named $map_in

my $counter = 0;

while($map_in){
    chomp;
    @hold_csv = split(',',$_);

    $entry1[$counter] = $hold_csv[0];
    $entry2[$counter] = $hold_csv[1];
    $entry3[$counter] = $hold_csv[2];
    $entry4[$counter] = $hold_csv[3];

    $counter++;
}
print "$entry1[0]\n$entry2[0]\n$entry3[0]\n$entry3[0]"; #test printing

I always got use of uninitialized value error whenever i fetch empty CSV cells
Can you help me locate the error in my code ('cause I know I have somewhat missed something on my code)?
Thanks.

A: This looks like CSV. So the tool for the job is really Text::CSV.
I will also suggest - having 4 different arrays with numbered names says to me that you're probably wanting a multi-dimensional data structure in the first place.
So I'd be doing something like:
#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use Text::CSV;

my $csv = Text::CSV->new( { binary => 1 } );

open( my $input, "<", "input.csv" ) or die $!;
my @results;

while ( my $row = $csv->getline($input) ) {
   push ( @results, \@$row );
}

print join ( ",", @{$results[0]} ),"\n";
print Dumper \@results;
close($input);

If you really want separate arrays, I'd suggest naming them something different, but you could do it like this:
 push ( @array1, $$row[0] );   #note - double $, because we dereference

I will note - there's an error in your code - I doubt:
while($map_in){

is doing what you think it is.

A: When you're assigning $entryN, define a default value:
$entry1[$counter] = $hold_csv[0] || '';

same for other @entry
I think there is a typo in while($map_in) { it should be while (@map_in) {.


text:
Q: Delivering programmed content with timer on a Flutter/Firebase app I've been developing a Flutter mobile App, and I'm using the Firebase Cloud Firestore to deliver "cards" on the app. But I need to create a "rule" to change for another card each 24 hours, or if possible, to change every midnight in the user's time.
I don't know how I can do this... if I create a code for this in the app, will not this restart the timer always the user restart the app?
Please, if the solution is in Flutter/Firebase docs, invite me the link, I didn't find nothing about this.
Thank you.


text:
Q: DeskTop: How to Fix MC1000 unknown Build error - could not find type 'System.Management.Instrumentation.InstrumentedAttribute I am migrating a .net framework 4.6.1 Desktop app to Core 6. I have resolved all errors except this one: MC1000 Unknown build error, 'Could not find type 'System.Management.Instrumentation.InstrumentedAttribute' in assembly 'C:\Users\M70151.nuget\packages\system.management\7.0.0\lib\net6.0\System.Management.dll'.'    ABC C:\ProgramFiles\dotnet\sdk\7.0.100\Sdks\Microsoft.NET.Sdk.WindowsDesktop\targets\Microsoft.WinFX.targets.
I cannot see System.Management being used anywhere in the App. I do not see WinFX.Targets referenced in the framework version of the App. I guess this was added because of the migration? Any ideas on resolving this issue?
I tried replacing system.Management, verifying the path, no success. I checked the System.Management.Instrumentation for the InstrumentedMethod. It does not appear to exist.How can I tell what is trying to use the method?


text:
Q: Bootstrap Multi select search clear button click event not working I am using bootstrap multi-selector with search enabled option.

I am trying to unselect all selected items on click of X button. But i am not able to handle click event for this button.
Please help or suggest a better way to do this.
Here is sample code:
<select id="multiselect-users" name="users[]" multiple="multiple">
    <option value="1">User1</option>
    <option value="2">User2</option>
</select>

<script type="text/javascript">
 $('#multiselect-users').multiselect({
    enableFiltering: true
 });
  // .multiselect-clear-filter is X button class. This button is part of bootstrape-multiselect if you enable filter
 $(document).on('click', '.multiselect-clear-filter', function(){

    // not working :(
    alert('test');
 });
</script>

I want to unselect all selected items on click of this X button.

A: What you a really expecting is that when you click on a select option an alert is displayed.
But the name of this event is not called 'click' is called 'changed':

     $(document).on('change', '#multiselect-users', function(){

     // woking :)
     alert('test');
     });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="multiselect-users" name="users[]" multiple="multiple">
      <option value="1">User1</option>
      <option value="2">User2</option>
    </select>

Also, you should add this event to the select tag not to .multiselect-clear-filter.
I have to say something about the:
 $('#multiselect-users').multiselect({
    enableFiltering: true
 });

part. And is that change event doesn't work when this is enabled. But I think maybe this function is from another library.
Hope this helps!

A: Hi You can try this option also
 $('#multiselect-users').multiselect({
        includeFilterClearBtn:true
 });

A: Try following code:
$('.multiselect-clear-filter').click(function () {
    $('#myDropDown option:selected').each(function () {
        $(this).prop('selected', false);
    })
    $('#myDropDown').multiselect('refresh');
});

NOTE: Do not include this inside $(document).Ready()


text:
Q: No access to other table data SQL I have two tables, in relationship (as you can see in the screenshot):

Now I select from table zerts and want to get all zerts in a list. And now I want to get the username, by the userid. How to access this data which is connected?
$sql = "SELECT * FROM zerts ORDER BY created";
    $result = mysqli_query($conn, $sql);
    while($row = mysqli_fetch_assoc($result)) {
      echo "
" . $row["id"] . "	" . $row["userid"] . "	" . $row["username"] . "
";
    }

Why is this not possible to get the username by the userid? I get a blank output at the username field.

A: You need to create join for this to access username of different table.
$sql = "SELECT zerts.userid,users.username,users.id FROM zerts JOIN users ON users.id = zerts.userid ORDER BY created";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
  echo "
" . $row["id"] . "	" . $row["userid"] . "	" .
  $row["username"] . "
";
}

A: Please update your query rest of the code will same.
$sql = "SELECT zerts.*,users.username FROM zerts
LEFT JOIN users ON (zerts.userid = users.id)  ORDER BY zerts.created";

Hope this help.


text:
Q: What is creating ./var/lib in my yocto image? tl;dr Yocto creates an empty directory var/lib in my image, even after it has been explicitly deleted by ROOTFS_POSTPROCESS_COMMAND. Why, and how can I get rid of it?

I am trying to create an yocto image with an exact predefined set of files and directories, without the usual rootfs files. To start with, I'm trying to create a completely empty image.
For testing purposes I'm using a clean yocto jethro clone with MACHINE ??= "qemux86" in conf/local.conf. Let's start with this recipe
meta-selftest/recipes-test/images/test-empty-image.bb

which comes with the yocto clone. It is very simple:
SUMMARY = "An empty image."
IMAGE_INSTALL = ""
IMAGE_LINGUAS = ""
PACKAGE_INSTALL = ""

inherit image

Building bitbake test-empty-image gives me the following files in the image:
$ tar tf tmp/deploy/images/qemux86/test-empty-image-qemux86.tar.bz2
./
./etc/
./etc/version
./etc/default/
./etc/default/postinst
./etc/ld.so.cache
./etc/rpm/
./etc/rpm/platform
./etc/rpm/sysinfo/
./etc/rpm/sysinfo/Dirnames
./etc/timestamp
./var/
./var/lib/

Let's try to delete the remaining files and folders by appending this to the recipe:
remove_dirs () {
        rm -rf ${IMAGE_ROOTFS}/etc
        rm -rf ${IMAGE_ROOTFS}/var
}
ROOTFS_POSTPROCESS_COMMAND += "remove_dirs ; "

This works for etc, but not for var:
$ tar tf tmp/deploy/images/qemux86/test-empty-image-qemux86.tar.bz2
./
./var/
./var/lib/

For some more debugging, I add logging statements to the cleanup function:
remove_dirs () {
        echo "################# Listing before rm -rf:" >> ${IMAGE_ROOTFS}/listing.txt
        ls ${IMAGE_ROOTFS} >> ${IMAGE_ROOTFS}/listing.txt
        rm -rf ${IMAGE_ROOTFS}/etc
        rm -rf ${IMAGE_ROOTFS}/var
        echo "################# Listing after rm -rf:" >> ${IMAGE_ROOTFS}/listing.txt
        ls ${IMAGE_ROOTFS} >> ${IMAGE_ROOTFS}/listing.txt
}

which results in the file listing.txt:
################# Listing before rm -rf:
etc
listing.txt
oe_install
var
################# Listing after rm -rf:
listing.txt
oe_install

So the directory var/lib is definitely deleted by the ROOTFS_POSTPROCESS_COMMAND, but than apparently recreated later. How can I get rid of this directory?

A: This is quite annoying and in the past I had the same problem. Do the following in your image recipe:
IMAGE_PREPROCESS_COMMAND += "remove_dirs"
This should run after the ROOTFS part.
See Yocto manual entry for IMAGE_PREPROCESS_COMMAND


text:
Q: Use array.reduce() for array of characters I have an array of characters (arr) and a string (J), I wanted to use the array.reduce() method to count the number of characters of the array (arr) present in the string J.
Below is the code which shows how I am using array.reduce() method,
let val = arr.reduce((count , ch) => {
    return J.includes(ch) ? count + 1 : count
});

But when I tried with sample value as,
arr = [ 'a', 'A', 'A', 'S', 'S' ];

J = 'aA';

I get the anser as
val = 'a11'

A: You need to add initialValue in second parameter of .reduce() as mentioned in docs
arr.reduce(callback[, initialValue])

var arr = [ 'a', 'A', 'A', 'S', 'S' ];
var J = 'aA';
let val = arr.reduce((count , ch) => {
    return J.includes(ch) ? count + 1 : count
}, 0);
console.log(val);


text:
Q: FSharpChart: two scales on same graphic I'm using FSharpChart to print on the same graphic the moving average and the volume of a stock. The problem is that one graphic goes from 20 to 50 more or less, the other from 0 to 80 mln, so when I combine the two, one is split to the bottom and this is useless. Can I have two different scales on the Y-axis so that the two graphic "merge" correctly?

A: You can do this if you set the AxisType of one of the series to AxisType.Secondary.  Of course it's then up to you to make sure axis labels, legend, etc make it clear which data maps to which scale.
open FSharp.Charting
open System.Windows.Forms.DataVisualization.Charting

let squaresChart = [ 1 .. 100 ] |> List.map (fun n -> (n, n*n)) |> Chart.Line
let cubesChart   = [ 1 .. 100 ] |> List.map (fun n -> (n, n*n*n)) |> Chart.Line

let bad =
    [ squaresChart
      cubesChart ]
    |> Chart.Combine

let good =
    [ squaresChart
      cubesChart |> Chart.WithSeries.AxisType(YAxisType = AxisType.Secondary) ]
    |> Chart.Combine

Bad:

Good:

This works, but in the quick testing I've done to write this answer, it appears that FSharp.Charting has some bugs whereby certain customizations are "infectious."  After creating the "good" chart, the secondary axis now appears even when I don't want it:
// secondary axis sticks around
bad |> Chart.WithTitle(Text = "Why secondary axis?")

// now the title and the secondary axis *both* stick around!
Chart.Rows [bad; good]

A: As far as I know you cannot Chart.Combine charts with independent scales. However, you may stack them on each other with a different combinator, for example with Chart.Rows like in snippet below
#I @"C:\code\packages\FSharp.Charting.0.90.12"
#load "FSharp.Charting.fsx"

open FSharp.Charting
open System

let parabola = [ for x in 1.0 .. 1.0 .. 10.0 -> (x, (x ** 2.0) * 1000.0 ) ]
let curve = [ for i in 0.0 .. 0.02 .. 2.0 * Math.PI -> (sin i, cos i * sin i) ]

Chart.Rows([Chart.Line(parabola); Chart.Line(curve)])

producing the combined chart with constituents having quite different scale:


text:
Q: Javascript to find a given variable value's position in one array in another array I have two arrays (array1 and array2), that match indices and sizes, but have different corresponding values. I want to use a single-valued variable (x) whose value exists in array1 to find the index position from array1 and then return the value in the same position from array2.
The values in the arrays are not always single-valued as well.
An example of array1 may have in one value:
array1 = [10, 15, 20, 27]
array2 = [up, down, left, right]
I want to use if x = down, return 15.

var x = PriPosition;
var array1 = Amts;
var array2 = Positions;
var y;

for(I=0;I<array2;i++)
{
   if(array2[I] == x)
   {
      y = array1[I];
      break;
   }
}
y;

This function has the variables built from a report except for "y". I used the variables to shorten the real names.
When this javascript is ran, the results are blank with or without the "y;". I have also tried the indexOf() function.
Thank you for any insight.

A: I got indexOf to work. Please comment if code isn't what you need.
x = "Foo"
var array1 = ["Foo", "Bar", 0, true];
var array2 = [false, "Foo", 2, "Bar"];
var y = array2[array1.indexOf(x)]


text:
Q: Does getElementById work on elements created by javascript? I've created two functions to load expanded views of a month in the archive section of my blog when it's link is clicked:
// Load open view of a month in the Archive section
function loadMonth(date) {
  // Remove other open month
     removeMonth();

  // Hide opening month's link
  // Define variable to hold month anchor tag
     var monthLink = document.getElementById(date);
     monthLink.style.display = "none"; // Hide month anchor

  // Define new open month node and its attributes
     var openMonth = document.createElement("div");
     openMonth.setAttribute("id", "openMonth");
     openMonth.innerHTML = "Testing one, two, three.";

  // Insert open month
  // Define a variable to hold the archive Div node
     var archive = document.getElementById("archive");
  // Insert the open month in the archive node before it's link
     archive.insertBefore(openMonth,monthLink);

     return;
  }

// Close full view of a month and replace with respective link
function removeMonth() {

  // Define global function vars
     var archive = document.getElementById("archive"); // Define a var to hold the archive Div node
     var openMonth = document.getElementById("openMonth"); // Define var to hold the open month Div node

  // Get date of full view month for replacement anchor tag where ID = date
     var month = openMonth.getElementsByTagName("span")[0].innerHTML; // Define var to hold the name of the open month
     var date = (new Date(month + " 15, 2008").getMonth() + 1); // Define var to hold the numerical equivalent of the month
     var year = archive.getElementsByTagName("h3")[0].innerHTML.split(" "); // Define var to hold the year being displayed in the archive
     date = year[1] + "" + date; // Change date var to string and insert year

  // Remove the open month
     archive.removeChild(openMonth);

  // Show Link for that month
     document.getElementById(date).className = "big"; // Fixes display error when anchor has class firstLink
     document.getElementById(date).style.display = "inline"; // Returns link from display "none" state
     return;
}

The functions work when run on the original static content, but when a second link is clicked in the archive, they do nothing. I am wondering if maybe because the elements that were created by my functions cannot be called by document.getElementById. Perhaps a different method of accessing those nodes should be used, or maybe replacing "document" with something that works on javascript created elements too?
Any advice would be greatly appreciated. Thanks.

A: You should be fine with:
openMonth.id = "openMonth";

getElementById() can only work if the element is part of the DOM, but since you already use insertBefore() this is merely a side note.
There is a common source of confusion involved here: An attribute named "id" is not necessarily the one that is defined as the element ID in the underlying DTD. In declarative HTML, they are linked automatically. When you use setAttribute(), you are not more than creating an attribute named "id". The element ID itself is accessible via the .id property.
Edit
The following works for me:
function test()
{
  // create element, set ID
  var p = document.createElement("P");
  p.innerHTML = "Look ma, this is a new paragraph!";
  p.id = "newParagraph";

  // make element part of the DOM
  document.getElementsByTagName("BODY")[0].appendChild(p);

  // get element by ID
  var test = document.getElementById("newParagraph");
  alert(test.innerHTML);
}

A: To answer your main question: document.getElementById does work with dynamically added elements.
In your sample code you are creating the openMonth div and setting its innerHTML. Then in the remove tag you are doing this:
var month = openMonth.getElementsByTagName("span")[0].innerHTML;

openMonth.getElementsByTagName("span") will not exist and will get an error because there are no span elements. I don't know if this is a mistake in the code or if it is just a incomplete sample in the post.

A: Another idea - you're reusing the 'openMonth' id for different elements, maybe that's a problem even if you remove the previous element first.
You could try to use a class instead of id, or you could holding a global variable with the 'current month element'.

A: It works only if you specify an id for the element when creating it. I remember when I was creatin elements on the fly I would set a counter for the id or if the data was retrieved from a database I would use the row id instead.
I would create the element using the innerHTML field of an element and inserting the element as text, then the rendering engine would take it from there . It is not the best way to do this but it is very fast I you are in some some of hurry...
Hope that helped


text:
Q: Save webpage data to file locally: How can get data from a webpage into JSON file and be able to save that to local machine I am working on a completely locally run web app which is to be run without any network connection. The idea is to distribute a pack to users (~40) who will use the app to basically fill in bunch of form fields and charts. As changes are made to the page an object with data in JSON format is filled in. I have the page working well now and I have a function to load an existing JSON file and populate any fields that are present in the file. The idea behind this is that someone can be "halfway" through filling out the fields in the app or someone can load up previous work.
My question here is; what is the best system available to get data from a webpage into JSON file and be able to save that to local machine so that it can be distributed (emailed, saved to SP, network drive, access db etc etc) at a later date? The scenario under which the app will be used is a strictly no network access area so this is why I need to be able save and access a file locally. I have a half-solution where I can open a separate tab which has the contents of the file but I really would prefer to have the downloading/saving prompting done for me as most users won't go further than seeing a page with gibberish on it.
the code I have to accomplish this much is:
//Download file
function SaveToDisk() {
    var data = JSON.stringify(currentSession);
    var fileURL = 'data:text/json;charset=utf8,' + encodeURIComponent(data);
    var fileName = $('file-save').val();
    console.log(fileURL);

    // for non-IE
    if (!window.ActiveXObject) {
        var save = document.createElement('a');
        save.href = fileURL;
        save.target = '_blank';
        save.download = fileName || 'unknown';

        var event = document.createEvent('Event');
        event.initEvent('click', true, true);
        save.dispatchEvent(event);
        (window.URL || window.webkitURL).revokeObjectURL(save.href);
    }

    // for IE
    else if ( !! window.ActiveXObject && document.execCommand)     {
        var _window = window.open(fileURL, '_blank');
        _window.document.close();
        _window.document.execCommand('SaveAs', true, fileName || fileURL)
        _window.close();
    }
}

currentSession object looks like:
//Global JSON variables
var currentSession = {
    "sections":{
        "header":{
            "tool":"",
            "subsystem":"",
            "engineer":"",
            "date":"",
            "so":""

        },
        "whys":{
            "why1":{
                "error":"",
                object:"",
                norm:"",
            },
            why2:{
                error:"",
                object:"",
                norm:"",
            },
            why3:{
                error:"",
                object:"",
                norm:"",
            },
            why4:{
                error:"",
                object:"",
                norm:"",
            },
            why5:{
                error:"",
                object:"",
                norm:"",
            }
        },
        probDescription:{
            "F":{
                "is":"",
                "isnot":""
            },
            "O":{
                "is":"",
                "isnot":""
            },
            "T":{
                "is":"",
                "isnot":""
            },
            "L":{
                "is":"",
                "isnot":""
            },
            "P":"",
            "W":"",
            "Pos":"",
            "S":""
        },
        possibleCauses :{
            "data":""
        },
        notes: ""
    }
};

UPDATE: Attempting this on windows machine (up to now been testing on mac) on IE9 gives the following error:
SCRIPT5007: Unable to get value of the property 'document': object is null or undefined

at the following line of the above code:
        _window.document.close();

Checking up on the line before:
    // for IE
    else if ( !! window.ActiveXObject && document.execCommand)     {

shows me that the if statement checks if activeXObject is present (only in IE???) and something else (div editable???) is true then it goes with the IE solution.
Then it creates a new window with the data url, (not sure what '_blank' is here) and attempts to save the file. So why is it erroring on the _window.document line? It does open a new window with the URL as:
data:application/octet-stream;{data}

Any help here also greatly appreciated(and needed)
All help and suggestions gladly welcomed as I am rather new to all this and still learning.
Thx in advance

A: To force the download/saving prompt you can change the MIME type to application/octet-stream. The MIME type won't be saved to disk, so you don't have to worry about that later on. The second line in the function should therefore read:
var fileURL = 'data:application/octetstream;charset=utf8,' +  encodeURIComponent(data);

Of course there are good reasons that this local saving procedure can not be completely automated. Otherwise viruses could be easily distributed.
If you want to access the file later to distribute it via email, the local storage solutions in html5 do not really help.

A: Since I work mostly on IE9 and can guarantee that the users will use this I found this answer solved my issue:
https://stackoverflow.com/a/6106417/1770604
I have it implemented like so:
//Make file for attaching to mail
function makefile () {

    var fso = new ActiveXObject("Scripting.FileSystemObject"),
        FName = $('#file-save').val() + ".json",
        data = JSON.stringify(currentSession),
        thefile=fso.CreateTextFile("C:\\temp\\" + FName,true);

    thefile.Write(data);
    thefile.Close();
    alert("File created and saved to C:/temp/directory");
}

I have searched as much as possible and to my limited knowledge there are only two solutions to this without using a separate server:

*

*ActiveXObject in IE9 which allows the user to interact with the file system and write to a file in a specified dir - from what i've read this is not a very secure solution however this is my only real option.

*Some form of local/portable web server which can be distributed and started without user needing to do anything - I haven't been able to find the answer to this question yet so will keep looking but consider the question answered for now as long as you use IE9.


text:
Q: django, group model by days I have models.py with:
class Game(models.Model):
    date = models.DateTimeField()

I want to have a function that returns all games grouped by days. Result should be a dict with keys: 'day' and 'games' (list of games for the day). I do it in such way:
from itertools import groupby

def get_games_grouped_by_days():
    def get_day(obj):
        return obj.date.day
    games = Game.objects.all()
    grouped_games = []
    for day, games_in_day in groupby(games, key=get_day):
        grouped_games.append({
            'day': day,
            'games': list(games_in_day)
        })
    return grouped_games

This function works fine, but I would like to know if there is a more query-way to do such group thing.

A: what about this:
query = Game.objects.all().query
query.group_by = ['date']
results = QuerySet(query=query, model=Game)

Then you can iterate on results, and get the day and game from each item.


text:
Q: Can I start a text with "While"? I know it's OK to start sentences with While, but is it OK to start a text with it? For example:

While electron-electron correlations and interactions are crucial in the descriptions of atoms and molecules, studies of ionization in the strong-field régime have in general ignored their effects.

I've had a look in the corpora but I can't quite see how to ask the question there.

A: While beginning a text with the word while is perfectly acceptable, your primary concern, it seems to me, should be its effect on your audience, and whether or not the sentence is sufficiently strong to draw them into what you have to say.
"While electron-electron correlations and interactions . . ." has an informal and slightly chatty feel to it.  The sentence sounds as if it would be more appropriate in the middle of a paragraph, and not at the beginning.  Here's a hypothetical and illustrative paragraph, which for simplicity's sake contains blanks:

The phenomenon of __ has been well attested in the literature.  Scientists and theorists in the field, from John __ in the 1990s to Carol __ early in the new century, have described the phenomenon in elegant detail.  While we should be grateful for their efforts to date, we still have a great deal to learn, specifically in the phenomenon's __ .  It is my purpose in this book, therefore, to use the discoveries of the past as a springboard for __ , in the hopes of stimulating further explorations into __ .  With a little luck and a lot of hard work, perhaps we could be instrumental in ushering in a veritable paradigm shift in this exciting stage of discovery.  We are arguably on the cusp of doing just that!

In a perhaps overly simplified explanation of the above, you have the following:  a solid and foundational statement, followed by a few prominent examples to buttress your first statement.  Then there comes a transitional statement that accomplishes two things.  First, it praises the findings of past researchers (assuming their contributions to the field are considered unassailable by your peers), and second, it points to what needs to be done if your community of scientists is to push the envelope of discovery to the next level.  That's where your studies in the field, which you plan to explain and develop in your text, become relevant to your readers.  Make sense?

A: Yes, we can! Yes, we can!

"You mean an SMS text? Yes. Any ordinary sentence? Also yes." – Robusto

You can try.

"You can try. Only the publisher, editor, and peer reviewers get to tell you whether your attempt will succeed." – Bill Franke

(And a little bit irony here)

"Sure, start your whole 1000-page textbook with While." – GEdgar


text:
Q: Kotlin collections throw ClassNotFoundException on Android Using any of the lines below throws a ClassNotFoundException when app is run on Android.
val list = listOf("a", "b")
val arrayList = arrayListOf("a", "b")
val map = mapOf("key" to "value")

The exception:
04-28 15:12:00.770 27326-27326/com.example.kotlin E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kotlin, PID: 27326
java.lang.NoClassDefFoundError: Failed resolution of: Lkotlin/collections/CollectionsKt;
    at com.example.kotlin.MainActivity.onCreate(MainActivity.kt:17)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "kotlin.collections.CollectionsKt" on path: DexPathList[[zip file "/data/app/com.example.kotlin-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.kotlin-1/lib/x86, /vendor/lib, /system/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    at com.example.kotlin.MainActivity.onCreate(MainActivity.kt:17)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Suppressed: java.lang.ClassNotFoundException: kotlin.collections.CollectionsKt
    at java.lang.Class.classForName(Native Method)
    at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
    at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
            ... 14 more
 Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

The following is my app module gradle file:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 23
    buildToolsVersion "24.0.0 rc3"

    defaultConfig {
        applicationId "com.example.kotlin"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled = true
    }
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:gridlayout-v7:23.3.0'
    compile 'com.android.support:cardview-v7:23.3.0'

    kapt 'com.android.databinding:compiler:2.1.0-beta3'
}

buildscript {
    ext.kotlin_version = '1.0.1-2'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
repositories {
    mavenCentral()
}

kapt {
    generateStubs = true
}

Is there any other dependency I need to add to gradle in order to use any of the Kotlin collection classes?

A: You need to depend on the Kotlin standard library which contains these classes:
dependencies {
   /* ... */
   compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}


text:
Q: regular expression - comment out all lines containing the word "logging" I am trying to mass comment out all the lines referring to logging in a code.
I am using notepad ++ and ideally this would be achievable by replacing all the lines being like
< some text > logging

by
# < some text > logging

Sorry in advance to ask this kind of question on SO, but I'm kind of stuck , and I'm sure this can be useful to other people.

A: Find with (?=.*logging)^ and replace with #
Eplanation:
(?=.*logging) will lookahead for word logging and if present search for beginning of string with ^

Regex101 Demo

A: In notepad++,
Search "^(.*) logging"
Replace "#\1 logging"
Make sure search mode is "Regular expression"

A: Find what : ^.*logging$
Replace with: # $0
Search mode: Regular expression
$0 is a variable for the match.
And the regex matches a line that ends with "logging".
So replacing it with # $0 puts a # at the start of a line that ends with logging.

^  : start of a line
  .* : zero or more characters
  $  : end of a line

And to a avoid commenting lines that are already are commented?
Adding a negative lookahead helps with that:
Find what: ^(?!\s*#).*logging$


text:
Q: How to get list of options / data from an input-based select2 3.5 control Were using 3.5.3, and have had no luck finding a way to do this.
After I select2-enable an input box with an array of values (using data: in the consructor options), is there a way to get that list back again, from the drop-down in question? We have utility code that needs to retrieve that list and disable an option, and that utility code doesn't have access to the same context that rendered the select2 to begin with (i.e. we don't have the array we used to build it, as this might affect many select2 controls on the page).
I would have expected something like $(control).select2('query', '') or .select2('search',''), but no luck. I'd even be happy just retrieving the initial constructor options, and getting the "data" item from that.
We can't use a select because we need the ability to dynamically add new user-typed options.
Upgrading to select2 4.0 isn't feasible, due to the degree of coupling our code has with 3.5 (I tried for weeks, and after hundreds of LOC changed, there was no end in sight).
I've searched for hours online, in stackoverflow and select2 documentation and elsewhere. If this answer already exists, I'm unable to find it.


text:
Q: Converting webcam program to process one image I am currently trying to modify a program that takes in a webcam stream as input. The problem is, when I try to alter the program to use a single image, it doesn't display the output that I am expecting e.g. with video stream (code below)
#include "opencv2/opencv.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>

#include "BackgroundRemover.h"
#include "SkinDetector.h"
#include "FaceDetector.h"
#include "FingerCount.h"

using namespace cv;
using namespace std;

int main(int, char**) {
    VideoCapture videoCapture(0);
    videoCapture.set(CV_CAP_PROP_SETTINGS, 1);

    if (!videoCapture.isOpened()) {
        cout << "Can't find camera!" << endl;
        return -1;
    }

    Mat frame, frameOut, handMask, foreground, fingerCountDebug;

    BackgroundRemover backgroundRemover;
    SkinDetector skinDetector;
    FaceDetector faceDetector;
    FingerCount fingerCount;

    for (int i = 0; i < 2; i++)
    {
        videoCapture >> frame;
        frameOut = frame.clone();

        skinDetector.drawSkinColorSampler(frameOut);

        foreground = backgroundRemover.getForeground(frame);

        faceDetector.removeFaces(frame, foreground);
        handMask = skinDetector.getSkinMask(foreground);
        fingerCountDebug = fingerCount.findFingersCount(handMask, frameOut);

        imshow("output", frameOut);
        imshow("foreground", foreground);
        imshow("handMask", handMask);
        imshow("handDetection", fingerCountDebug);

        if (i == 0)
        {
            backgroundRemover.calibrate(frame);
            skinDetector.calibrate(frame);
        }
    }
    waitKey(0);
}

The output shows a detection. Whereas, if I modify the code so that frame doesn't read from the video stream, the output shows nothing at all. Can anybody help to fix this? EDIT: Due to confusion from some members of the community, the modified code is below that reads in a single image:
#include "opencv2/opencv.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>

#include "BackgroundRemover.h"
#include "SkinDetector.h"
#include "FaceDetector.h"
#include "FingerCount.h"

using namespace cv;
using namespace std;

int main(int, char**) {

    string imageName("C:/Users/whoever/Desktop/hand_test.jpg"); // by default
    Mat image;
    image = imread(imageName.c_str(), IMREAD_COLOR); // Read the file

    Mat frame, frameOut, handMask, foreground, fingerCountDebug;

    BackgroundRemover backgroundRemover;
    SkinDetector skinDetector;
    FaceDetector faceDetector;
    FingerCount fingerCount;

    for (int i = 0; i < 2; i++)
    {
        frame = image;
        frameOut = frame.clone();

        skinDetector.drawSkinColorSampler(frameOut);

        foreground = backgroundRemover.getForeground(frame);

        faceDetector.removeFaces(frame, foreground);
        handMask = skinDetector.getSkinMask(foreground);
        fingerCountDebug = fingerCount.findFingersCount(handMask, frameOut);

        imshow("output", frameOut);
        imshow("foreground", foreground);
        imshow("handMask", handMask);
        imshow("handDetection", fingerCountDebug);

        if (i == 0)
        {
            cout << "Calibrating...";
            backgroundRemover.calibrate(frame);
            skinDetector.calibrate(frame);
        }
    }
    waitKey(0);
}

A: The original code processes different images captured from the camera each time it goes round the loop and outputs the differences. Since you are now using the same image every time round there are never any differences hence the output is completely blank. (Note that it will still be playing the output as a video, just a constantly blank one)
The first line in the for loop is where it grabs a new image from the camera:
   videoCapture >> frame;

As you can see in your updated code you are removing this and just using the same image again:
    frame = image;

Try saving 2 different images instead and have the program load in a different one each time round the loop.
Here is a fairly brute force way to do it which you could improve to load a different file each time it loops, use arrays and so on:
string imageName1("C:/Users/whoever/Desktop/hand_test_1.jpg"); // by default
string imageName2("C:/Users/whoever/Desktop/hand_test_2.jpg"); // by default
Mat image1;
Mat image2;
image1 = imread(imageName1.c_str(), IMREAD_COLOR); // Read the file
image2 = imread(imageName2.c_str(), IMREAD_COLOR); // Read the file

Mat frame, frameOut, handMask, foreground, fingerCountDebug;

BackgroundRemover backgroundRemover;
SkinDetector skinDetector;
FaceDetector faceDetector;
FingerCount fingerCount;

for (int i = 0; i < 2; i++)
{
    if (i = 0) { frame = image1 } else { frame = image2 };
...


text:
Q: Toggle animate links I want to toggle the width of links in the following code. Its working but I want the width to revert when I click the another link thereby remaining with one extended link, I hope I make sense.
<!DOCTYPE>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

many other links here

A: I wouldn't use toggle for this, because it's good for one thing - toggle on/off of a singly selected item/group.  What you're trying to do is reset other items while switching on one.  Try something like this instead:
$(".nav_links li a.link").click(function(){
    // Reset all links.
    $(".nav_links li a.link").animate({width:72},200);

    // Set currently clicked on as necessary.
    $(this).animate({width:237},200);
});


text:
Q: Double click instead of single click is required with custom button in IE Please see the following link:
http://jsfiddle.net/HAaFb/55/
Not sure why this requires a double click and how can it be modified to work with a single click.
The problem happens only in IE it works with Mozilla.
HTML:
 <div class="custom-input-file">
        <input type="hidden" value="10000000" name="MAX_FILE_SIZE" />
        <input class="input-file" type="file" size="1" onchange="readURL(this);" multiple="multiple" name="files[]" />
        Choose files
 </div>

CSS
 .custom-input-file .input-file {
    margin: 0;
    padding: 0;
    outline: 0;
    font-size: 10000px;
    border: 10000px solid transparent;
    opacity: 0;
    filter: alpha(opacity=0);
    position: absolute;
    right: -1000px;
    top: -1000px;
    cursor: pointer;
}

 .custom-input-file {
    overflow: hidden;
    position: relative;
    cursor: pointer;
}

 .custom-input-file {
  background-color:yellow;
    width: 229px;
    height: 29px;
    font-family: "Tw Cen MT";
    font-weight: bold;
    font-size: 18px;
    text-align: center;
    padding-top: 7px;
    margin: 0 auto;
    color:black;
}

A: I won't go into the code in the fiddle, as I assume is not exactly what you have on your html (open divs for instance).
Try removing border: 10000px solid transparent;


text:
Q: node-webkit in app purchase flow I am porting a webapp to be used on OSX using node-webkit. Our app also has a premium plan (subscription).
How would I trigger the a in app purchase flow from within js code?


text:
Q: numpy function which converts an array of '+'/'-' chars to an array of +/-1 int values I have an array like this:
sign_char_array = np.array(['+', '-', '+', '+'])
# dtype='<U1'

I'd like to convert this into an array of +1 and -1 values (so that it is easy to multiply this array of signs with an array of corresponding integer or float values). I'd like the final output to be:
converted_sign_array = np.array([1, -1, 1, 1])

I know that I can write the following line of code to do this manually:
2 * (sign_char_array == '+').astype('int') - 1
# array([ 1, -1,  1,  1])

However, I am curious: is there a built-in numpy or astropy function which does this conversion?
For context: I'm an astronomer and I work often with published scientific tables that provide sexagesimal coordinates. Sometimes the sign of the latitude/declination coordinate is provided as its own data column of strings, rather than being included as a sign in front of the next column.

A: np.where is the first thing that comes to mind, though I'm sure there are many ways of accomplishing the same thing.
converted_sign_array = np.where(sign_char_array == '+', 1, -1)

A: You have a number of options:

*

*The best is likely np.where, covered in the accepted answer.

*For two options, you can use direct indexing:
 np.array([+1, -1])[(sign_char_array == '+').view(np.int8)]

*np.select is a generalization that allows you to potentially add more options to the input:
 result = np.select([sign_char_array == '+',  sign_char_array == '-'], [1, -1])

you can simplify the computation of the first argument using broadcasting. This also allows you to expand the options:
 result = np.select(sign_char_array == [['+'],  ['-'], ['t']], [1, -1, 2])

*np.choose is an index-based function similar to np.select:
 _, i = np.unique(sign_char_array, return_inverse=True)
 result = np.choose(i, [1, -1])

You can generalize this to many options using a mapping and the fact that the output of np.unique is sorted:
 map_in = np.array(['+', '-', 't'])
 map_out = np.array([1, -1, 2])

 _, i = np.unique(sign_char_array, return_inverse=True)
 result = np.choose(i, map_out[map_in.argsort()])

You can turn this into a one-liner by replacing i with np.unique(sign_char_array, return_inverse=True)[1]. This method looks more complex than using np.select, but it is actually more efficient.


text:
Q: C++ Using base function in overridden function I want to define a Interface which already implements some of the basic functions, which may have to be modified a little bite when they're overridden.
Is it possible to call the base function inside of the overriding function in C++?
Example:
class A
{
  public:
  void function1 (int a)
  {
    do_something_with(a);
  }
};

class B : public A
{
  public:
  void function1 (int a)
  {
    // call of base function
    function1 (a);

    // further processing
    do_something_more_with(a);
  }
};

Would this work or would it lead to an infinite recursion? Is there any way to do something like that?

A: Since function1(int a) in class A is public, you can call it in class B using
A::function1(a);


text:
Q: Kubernetes ingress with 2 services does not always find the correct service I have a Kubernetes cluster with a backend service and a security service.
The ingress is defined as follows:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: solidary-life
  annotations:
    kubernetes.io/ingress.global-static-ip-name: sl-ip
    certmanager.k8s.io/acme-http01-edit-in-place: "true"
    ingress.kubernetes.io/force-ssl-redirect: "true"
    ingress.kubernetes.io/ssl-redirect: "true"
  labels:
    app: sl
spec:
  rules:
    - host: app-solidair-vlaanderen.com
      http:
        paths:
        - path: /v0.0.1/*
          backend:
            serviceName: backend-backend
            servicePort: 8080
        - path: /auth/*
          backend:
            serviceName: security-backend
            servicePort: 8080
  tls:
  - secretName: solidary-life-tls
    hosts:
    - app-solidair-vlaanderen.com

The backend service is configured like:
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: backend
  labels:
    app: sl
spec:
  template:
    metadata:
      labels:
        app: sl
        tier: web
    spec:
      containers:
      - name: backend-app
        image: gcr.io/solidary-life-218713/sv-backend:0.0.6
        ports:
          - name: http
            containerPort: 8080
        readinessProbe:
          httpGet:
            path: /v0.0.1/api/online
            port: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: backend-backend
  labels:
    app: sl
spec:
  type: NodePort
  selector:
    app: sl
    tier: web
  ports:
  - port: 8080
    targetPort: 8080

and the auth server service:
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: security
  labels:
    app: sl-security
spec:
  template:
    metadata:
      labels:
        app: sl
        tier: web
    spec:
      containers:
      - name: security-app
        image: gcr.io/solidary-life-218713/sv-security:0.0.1
        ports:
          - name: http
            containerPort: 8080
          - name: management
            containerPort: 9090
          - name: jgroups-tcp
            containerPort: 7600
          - name: jgroups-tcp-fd
            containerPort: 57600
          - name: jgroups-udp
            containerPort: 55200
            protocol: UDP
          - name: jgroups-udp-mc
            containerPort: 45688
            protocol: UDP
          - name: jgroups-udp-fd
            containerPort: 54200
            protocol: UDP
          - name: modcluster
            containerPort: 23364
          - name: modcluster-udp
            containerPort: 23365
            protocol: UDP
          - name: txn-recovery-ev
            containerPort: 4712
          - name: txn-status-mgr
            containerPort: 4713
        readinessProbe:
          httpGet:
            path: /auth/
            port: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: security-backend
  labels:
    app: sl
spec:
  type: NodePort
  selector:
    app: sl
    tier: web
  ports:
  - port: 8080
    targetPort: 8080

Now I can go to the url's:

*

*https://app-solidair-vlaanderen.com/v0.0.1/api/online

*https://app-solidair-vlaanderen.com/auth/
Sometimes this works, sometimes I get 404's. This is quite annoying and I am quite new to Kubernetes. I don't find the error.
Can it have something to do with the "sl" label that's on both the backend and security service definition?

A: Yes. At least that must be the start of the issue, assuming all your services are on the same Kubernetes namespace. Can you use a different label for each?
So, in essence, you have 2 services that are randomly selecting pods belonging to the security Deployment and the backend deployment. One way to determine where your service is really sending requests is by looking at its endpoints and running:
kubectl -n <your-namespace> <get or describe> ep


text:
Q: Android GCM Push notification not giving any notifications Hello all I am trying to implement Push Notification Using GCM. I am using This Link . I am using API 15
<uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

static final String SERVER_URL = "http://10.0.2.2/gcm_server_php/register.php";

    // Google project id
    static final String SENDER_ID = "2*********12"; //12 digit ID

I have give this permission to Manifest.xml
<permission
        android:name="com.example.googlecoludmessaging.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.example.googlecoludmessaging.permission.C2D_MESSAGE" />

    <!-- This app has permission to register and receive data message. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <!-- Network State Permissions to detect Internet status -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

But this not giving me any Display or any notifications. I have tried in emulator as well as in device
Thanks in advance.

A: i think this tutorial uses old api.
visit https://developer.android.com/google/gcm/index.html
GCM not Working  (its my Qustion, there is no error in Program)

A: Try to follow the official guide step by step: https://developer.android.com/google/gcm/gs.html
What you need to do is to implement a server (to send notifications which you can do anywhere -- in the link you referred to, it's done on a PHP server but it can be any server/machine that can send JSON format HTTP POST) and a client side implementation to react to these notifications. You need to implement the correct sets of services and intents in your client to react to them. To implement your client, read this: https://developer.android.com/google/gcm/client.html. To implement your server: https://developer.android.com/google/gcm/server.html
If you're sending notifications from your server, check that you don't receive any exceptions when you connect to GCM (i.e. you keys are all in order, your request is of the correct format and the HTTP POST is successful) and then attempt to put breakpoints in your GCM service/broadcast intent to see if you receive anything. If you follow the official guide, you should be able to get this working easily.


text:
Q: Can I block an insert inside a trigger on Oracle 11g? So, what I want to do is to block an insert if the condition is met. In this case, I'm developing a simple library database system and I don't want to allow someone to be able to borrow a book if that certain person has already borrowed 2 books and still hasn't returned any of them.
I need to do this via trigger, is it possible? Also, I'd like to know if I can supply a query into the WHEN clause like I did.
CREATE OR REPLACE TRIGGER trigger_borrowing_limit
BEFORE INSERT ON Borrowing
REFERENCING NEW ROW AS NROW
FOR EACH ROW
WHEN SELECT COUNT(*) FROM Borrowing WHERE RETURN_DATE IS NULL AND NROW.ID = Borrowing.ID > 2
BEGIN
?
END

A: You can't supply a query for the WHEN clause. From the Oracle 11 docs (search for "WHEN (condition)" once you get to the page):

Restrictions on WHEN (condition)

*

*If you specify this clause, then you must also specify FOR EACH ROW.

*The condition cannot include a subquery or a PL/SQL expression (for example, an invocation of a user-defined function).

As for preventing the row insert, the comment from Mihai is the way to go. Your front end can catch the exception, and if it's error number -20101 (per Mihai's example) you'll know that the person already has two books out. Note that some drivers will report the absolute value of the exception number, so the error number that reaches you may be 20101.

Addendum: a followup question asked how to apply the "two books out" logic since it's not valid for the WHEN clause.
The answer is to drop the WHEN clause and put the logic into the trigger body. Note that I normally stick with the standard NEW for referencing the new row, so my answer doesn't have the REFERENCING NEW AS NROW:
CREATE OR REPLACE TRIGGER trigger_borrowing_limit
  BEFORE INSERT ON Borrowing
DECLARE
  booksOut NUMBER;
BEGIN
  SELECT COUNT(*) INTO booksOut
    FROM Borrowing
    WHERE RETURN_DATE IS NULL AND NEW.ID = Borrowing.ID;
  IF booksOut > 2 THEN
    -- Next line courtesy of Mihai's comment under the question
    raise_application_error(-20101, 'You already borrowed 2 books');
  END IF;
END;


text:
Q: basic input validation with java.io I'm a beginner programmer, I have been writing code for about three weeks now. I want to make a simple program that asks for user input temperature and tells whether or not the user has fever (temperature higher than 39). I also want to validate the user input, meaning that if the user types "poop" or "!@·R%·%" (symbol gibberish), the program will output the phrase "invalid input". I'm trying to use the try/catch statements, this is my code:
package feverPack;

import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException{

        try{
        InputStreamReader inStream = new InputStreamReader(System.in);
        BufferedReader stdIn = new BufferedReader(inStream);

        System.out.println("please input patient temperature in numbers");
        String numone =stdIn.readLine();}

        catch (IOException e) {
            System.out.println("invalid input");
        }
        catch (NumberFormatException e){
            System.out.println("invalid input");
        }
        int temp = Integer.parseInt(numone) ;

        System.out.println("Your temperature is " + temp + "ºC");

        if (temp > 39) {
            System.out.println("You have fever! Go see a doctor!");
        }
        else{
            System.out.println("Don't worry, your temperature is normal");
        }
    }
}

There is an error in line 22 (when i transform numone into a temp) saying "numone cannot be resolved to a variable", as I am a beginner I don't really know what to do, please help.

A: Move the declaration of numone outside the try block. Basically, numone was declared within the scope of the try block and was not available outside the scope of the try block, so moving it out would give it a wider visibility.
String numone = null;
int temp = 0;
try
{
...
numone = stdIn.readLine();
temp = Integer.parseInt(numone) ;
System.out.println("Your temperature is " + temp + "ºC");
if (temp > 39) {
      System.out.println("You have fever! Go see a doctor!");
 }
else{
    System.out.println("Don't worry, your temperature is normal");
}
}
catch(..)
{
...
}


text:
Q: Problem involving the 4 forces that maintain an airplane in level flight The 4 forces affecting an airplane in level flight are gravity, lift, thrust, and drag. By
altering one, the others are affected. My question is could a wing (retractable) be installed on top of a vehicle with a computer controlling the configuration of the wing to
maintain a constant lift of 50% when speed allows. Reduction in weight results in reduction in thrust. How does the increase in drag on the wing compare with the pros of lift regarding fuel burn.

A: A nice idea, but it actually sorts itself out in flight.
As fuel is burned and weight is reduced the aircraft trim is changed to reduce both the lift and the drag of the main wing. The drag reduction reduces the fuel burn.

A: What you propose is an adaptable aircraft which continuously reconfigures itself according to the actual mass and, therefore, lift requirement. Something like this actually exists as a glider: The Akaflieg Stuttgart fs29 (picture source).

fs29 multiple exposure with wing span changing between 13.3 and 19 m.
This makes sense, because by reducing wing area with increasing speed, the airfoil will stay at a similar operating point over a range of speeds.
But if you are not bound to a particular flight altitude, there is a much simpler way to keep the airfoil at the same operating point regardless of lift required. By flying higher and thus in less dense air, airliners do exactly this (mostly over the open sea; over land only as far as air traffic control allows). A long range airliner carries fuel weighing as much as 40% of its take-off mass and adapts to the loss of mass over time by steadily (or stepwise) climbing higher.


text:
Q: Thread.sleep() optimization for small sleep intervals I am writing a library that involves a caller-defined temporal resolution. In the implementation, this value ends up being an interval some background thread will sleep before doing some housekeeping and going back to sleep again. I am allowing this resolution to be as small as 1 millisecond, which translates to Thread.sleep(1). My hunch is that that may be more wasteful and less precise than busy-waiting for 1 ms. If that's the case;

*

*Should I fall back to busy-waiting for small enough (how small) time intervals?

*Does anyone know if the JVM is already doing this optimization anyway and I don't need to do anything at all?

A: That's easy to test:
public class Test {

    static int i = 0;
    static long[] measurements = new long[0x100];

    static void report(long value) {
        measurements[i++ & 0xff] = value;
        if (i > 10_000) {
            for (long m : measurements) {
                System.out.println(m);
            }
            System.exit(0);
        }
    }

    static void sleepyWait() throws Exception {
        while (true) {
            long before = System.nanoTime();
            Thread.sleep(1);
            long now = System.nanoTime();
            report(now - before);
        }
    }

    static void busyWait() {
        while (true) {
            long before = System.nanoTime();
            long now;
            do {
                now = System.nanoTime();
            } while (before + 1_000_000 >= now);
            report(now - before);
        }
    }

    public static void main(String[] args) throws Exception {
        busyWait();
    }
}

Run on my windows system, this shows that busyWait has microsecond accuracy, but fully uses one CPU core.
In contrast, sleepyWait causes no measurable CPU load, but only achieves millisecond accuracy (often taking as much as 2 ms to fire, rather than the 1 ms requested).
At least on windows, this is therefore a straightforward tradeoff between accuracy and CPU use.
It's also worth noting that there are often alternatives to running a CPU at full speed obsessively checking the time. In many cases, there is some other signal you could be waiting for, and offering an API that focuses on time-based resolution may steer the users of your API in a bad direction.


text:
Q: simple timestamp for SMS on iPhone I am thinking this is an easy question, because I know how to do it in iChat for the computer.
But for an iPhone, SMS messages are shown as a speech bubble in a conversation with someone. Aside from the timestamp banner that appears before a message that is a long time after previous messages in an SMS conversation, how can I get a timestamp (or the time sent) of an SMS message?

A: if your iPhone is jailbroken you can download this tweak (xMessages
) for free from the cydia store


text:
Q: How to use PolymorphicJsonAdapterFactory with an interface in Moshi? I have an interface with two concrete types as part of my model that I'd like to serialize/deserialize with Moshi. My issue is that I don't fully understand if PolymorphicJsonAdapterFactory is actually meant for my use case. I've looked at the samples and a few blog posts and (if I'm understanding them correctly) all of them seem to point to the fact that your interface is supposed to have a field in the interface that allows you to determine the type. I'm working in an existing codebase and so I can't easily add a field that would allow me to figure out what type it is by some string literal.
This is where I'm at with my Moshi code and I'm seeking validation on whether or not I'm using PolymorphicJsonAdapterFactory correctly. Note: I'm using java for the moshi portion of the code and for my model. My interface and it's concrete types are in kotlin
String json = ...;

Moshi moshi = new Moshi.Builder()
.add(PolymorphicJsonAdapterFactory.of(PersonInterface.java, "")
            .withSubtype(BusinessPerson.java, "occupation")
            .withSubtype(PolicePerson.java, "rank")
)
.build();
JsonAdapter<MyModel> jsonAdapter = moshi.adapter(MyModel.class);

MyModel myModel = jsonAdapter.fromJson(json);

Note: I'm using java for the moshi portion of the code and for my model. My interface and it's concrete types are in kotlin
MyModel is defined as the following
class MyModel {
    String month;
    PersonInterface person;
}

My interface and concrete classes in kotlin:
Interface PersonInterface {
    val personsName: String?
}

data class BusinessPerson(
        override val personsName: String,
        val occupation: String?
) : PersonInterface

data class PolicePerson(
    override val personsName: String,
    val rank: String?
) : PersonInterface

The goal is to hopefully have Moshi be able to create a
class MyModel {
    String month;
    BusinessPerson person;
}

or a
class MyModel {
    String month;
    PolicePerson person;
}

depending on whether or not the person field contains an occupation (which means it's of type BusinessPerson) or if it contains the field rank (which means it's of type PolicePerson).

A: PolymorphicJsonAdapterFactory.of(PersonInterface.java, "")
    .withSubtype(BusinessPerson.java, "occupation")
    .withSubtype(PolicePerson.java, "rank")

means that JSON for every person is supposed to contain a key "" and "occupation" or "rank" is the value for this key, not a key name itself as you want. So e.g. it would encode a
BusinessPerson("John", "CEO")

as
{"": "occupation", "personsName": "John", "occupation": "CEO"}

I think you'll have to write your own adapter factory for this use-case if you want to avoid a discriminator field.


text:
Q: Dynamic Event Names in StencilJS based on Prop value I am trying to create a general slider component using StencilJS. The idea I had was to pass a slider ID as a prop, then use the prop as the event name when the slider changes.
The problem is the listeners are not catching the dynamic events emitted with the prop names. I think it might have to do with the component lifecycle but I am not sure. Any Ideas?
export class ParentComponent{

    @Listen('slider_A')
    onSliderValueChangeA(){
        console.log('event A') //not logging on slider change
    }

    @Listen('slider_B')
    onSliderValueChangeB(){
        console.log('event B') //not logging on slider change
    }

    @Listen('slider_C')
    onSliderValueChangeC(){
        console.log('event C')//not logging on slider change
    }

    render(){
        return (

                <slider-input slider_id={'slider_A'} slider_title={'S1'} ></slider-input>
                <slider-input slider_id={'slider_B'} slider_title={'S2'} ></slider-input>
                <slider-input slider_id={'slider_C'} slider_title={'S3'} ></slider-input>

        );
    }
}

Here is the slider component...

@Component({
    tag: 'slider-input',
    styleUrl: 'slider-input.scss',
    shadow: true
})

export class Slider{
    @Prop() slider_id: string;

    @Event({
        eventName: this.slider_id,
    }) on_slider_value_change: EventEmitter<null>;

    onValueChange(change){
        this.slider_value = change.value;
        this.on_slider_value_change.emit()
    }
.
.
.

A: I think a better approach would be to emit the slider's ID as event data/detail instead, but anyway...
The listeners should work afaik, but the @Event decorator might not. You can try to create the events manually instead, using dispatchEvent and CustomEvent.
export class MySlider {
  @Element() host: HTMLMySliderElement;

  onValueChange(change) {
    this.slider_value = change.value;

    this.host.dispatchEvent(new CustomEvent(this.slider_id));
  }

  // ...
}

A: As far as I know dynamic event names are not possible in Stencil, possibly because the event name is interpreted before the component is loaded.
Instead you can attach the listeners directly to the elements:
export class Slider {
    @Prop() slider_id: string;

    @Event() valueChange: EventEmitter<null>;

    onValueChange(change){
        this.slider_value = change.value;
        this.valueChange.emit()
    }
]

export class ParentComponent{

    onSliderValueChange(id: string){
        console.log('event', id)
    }

    render(){
        return (

                <slider-input slider_id={'slider_A'} onValueChange={() => this.onSliderValueChange('A')} slider_title={'S1'} ></slider-input>
                <slider-input slider_id={'slider_B'} onValueChange={() => this.onSliderValueChange('B')} slider_title={'S2'} ></slider-input>
                <slider-input slider_id={'slider_C'} onValueChange={() => this.onSliderValueChange('C')} slider_title={'S3'} ></slider-input>

        );
    }
}

Or you could add the listener manually:
@Element() el: HTMLElement;

this.el.querySelector('slider-input').addEventListener('valueChange', e => {
  switch(e.currentTarget.slider_id) {
    case 'slider_A':
      console.log('event A');
      break;
    case 'slider_B':
      console.log('event B');
      break;
  }
});

// or

this.el.querySelector('slider-input[slider_id=slider_A]')
  .addEventListener('valueChange', () => console.log('event A');