text:
Q: Suave App Hosted on IIS with HttpPlatformHandler Closes Connection I'm trying to get a basic Suave application running in IIS (IIS 10.0) using HttpPlatformHandler (version 1.2).
When I have it return a single WebPart such as
(OK "Hello World")

The application runs in IIS fine and I can make requests to it by name at http://localhost/testapp (testapp is the name of the application under the Default Web Site).
However, if I use something more complex for the WebPart such as
let app =
    choose
        [ GET >=> choose
            [ path "/hello" >=> OK "Hello GET"
              path "/goodbye" >=> OK "Good bye GET" ]
          POST >=> choose
            [ path "/hello" >=> OK "Hello POST"
              path "/goodbye" >=> OK "Good bye POST" ] ]

The website starts up but I cannot reach it by application name. I am still able to reach it by port however.
When I hit the application by name I receive an HTTP 503.2 (bad gateway) response.
The application is started from a FAKE script executed by the HttpPlatformHandler.
For context, this is the FAKE script which starts the application:
#r "./tools/FakeLib.dll"
#r "Suave.dll"

open System
open Suave
open Suave.Successful
open Fake
open System.Net
open Suave.Filters
open Suave.Sockets
open Suave.Operators
open System.IO

Environment.CurrentDirectory <- __SOURCE_DIRECTORY__

let port = Sockets.Port.Parse <| getBuildParamOrDefault "port" "8083"

let serverConfig =
    { defaultConfig with
       logger = Logging.Loggers.saneDefaultsFor Logging.LogLevel.Verbose
       bindings = [ HttpBinding.mk HTTP IPAddress.Loopback port ]
    }

let app =
  choose
    [ GET >=> choose
        [ path "/hello" >=> OK "Hello GET"
          path "/goodbye" >=> OK "Good bye GET" ]
      POST >=> choose
        [ path "/hello" >=> OK "Hello POST"
          path "/goodbye" >=> OK "Good bye POST" ] ]

startWebServer serverConfig (OK "Hello")
//startWebServer serverConfig app

The above script works as expected. However if I use the app WebPart instead of (OK "Hello") I encounter the issue described above.
For completeness here is the web.config set up for the HttpPlatformHandler:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <remove name="httpplatformhandler" />
      <add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
    </handlers>
    <httpPlatform
              stdoutLogEnabled="true" startupTimeLimit="20"
              processPath=".\tools\FAKE.exe"
              arguments=".\test.fsx port=%HTTP_PLATFORM_PORT%" >
      <environmentVariables>
      </environmentVariables>
    </httpPlatform>
  </system.webServer>
</configuration>

I've reviewed the logs, but unfortunately I can't see anything that indicates an error.
I've checked the Event Viewer, and the only clue that something might be wrong is this information event in the application log:
The description for Event ID 1001 from source HttpPlatformHandler cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.

Here is a portion of the log from the case where the app does run as expected (without choose):
[V] 2016-01-19T02:43:40.6932823Z: initialising BufferManager with 827392 bytes [Suave.Socket.BufferManager]
[I] 2016-01-19T02:43:40.7114149Z: listener started in 20.885 ms with binding 127.0.0.1:18450 [Suave.Tcp.tcpIpServer]
[V] 2016-01-19T02:43:40.8146603Z: 127.0.0.1 connected, total: 1 clients [Suave.Tcp.job]
[V] 2016-01-19T02:43:40.8166665Z: reserving buffer: 811008, free count: 99 [Suave.Tcp.job] [Suave.Socket.BufferManager]
[V] 2016-01-19T02:43:40.8217965Z: -> processor [Suave.Web.httpLoop.loop]
[V] 2016-01-19T02:43:40.8228181Z: reading first line of request [Suave.Web.processRequest]
[V] 2016-01-19T02:43:40.8378128Z: reserving buffer: 802816, free count: 98 [Suave.Web.readMoreData] [Suave.Socket.BufferManager]
[V] 2016-01-19T02:43:40.8498033Z: reading headers [Suave.Web.processRequest]
[V] 2016-01-19T02:43:40.8776578Z: freeing buffer: 802816, free count: 99 [Suave.Web.split] [Suave.Socket.BufferManager]
[V] 2016-01-19T02:43:40.8866594Z: parsing post data [Suave.Web.processRequest]
[V] 2016-01-19T02:43:40.8886553Z: <- processor [Suave.Web.httpLoop.loop]
[V] 2016-01-19T02:43:40.9057610Z: 'Connection: keep-alive' recurse [Suave.Web.httpLoop.loop]
[V] 2016-01-19T02:43:40.9057610Z: -> processor [Suave.Web.httpLoop.loop]
[V] 2016-01-19T02:43:40.9057610Z: reading first line of request [Suave.Web.processRequest]
[V] 2016-01-19T02:43:40.9057610Z: reserving buffer: 802816, free count: 98 [Suave.Web.readMoreData] [Suave.Socket.BufferManager]
[V] 2016-01-19T02:43:45.2531307Z: reading headers [Suave.Web.processRequest]
[V] 2016-01-19T02:43:45.2541141Z: freeing buffer: 802816, free count: 99 [Suave.Web.split] [Suave.Socket.BufferManager]
[V] 2016-01-19T02:43:45.2541141Z: parsing post data [Suave.Web.processRequest]
[V] 2016-01-19T02:43:45.2541141Z: <- processor [Suave.Web.httpLoop.loop]
[V] 2016-01-19T02:43:45.2551164Z: 'Connection: keep-alive' recurse [Suave.Web.httpLoop.loop]

And here is a portion of the log where the app does not work as expected (with routing via choose):
[V] 2016-01-19T02:44:59.6356127Z: initialising BufferManager with 827392 bytes [Suave.Socket.BufferManager]
[I] 2016-01-19T02:44:59.6537478Z: listener started in 20.987 ms with binding 127.0.0.1:18708 [Suave.Tcp.tcpIpServer]
[V] 2016-01-19T02:44:59.8848907Z: 127.0.0.1 connected, total: 1 clients [Suave.Tcp.job]
[V] 2016-01-19T02:44:59.8879891Z: reserving buffer: 811008, free count: 99 [Suave.Tcp.job] [Suave.Socket.BufferManager]
[V] 2016-01-19T02:44:59.8929862Z: -> processor [Suave.Web.httpLoop.loop]
[V] 2016-01-19T02:44:59.8939749Z: reading first line of request [Suave.Web.processRequest]
[V] 2016-01-19T02:44:59.9068548Z: reserving buffer: 802816, free count: 98 [Suave.Web.readMoreData] [Suave.Socket.BufferManager]
[V] 2016-01-19T02:44:59.9209857Z: reading headers [Suave.Web.processRequest]
[V] 2016-01-19T02:44:59.9259688Z: freeing buffer: 802816, free count: 99 [Suave.Web.split] [Suave.Socket.BufferManager]
[V] 2016-01-19T02:44:59.9338521Z: parsing post data [Suave.Web.processRequest]
[V] 2016-01-19T02:44:59.9378580Z: <- processor [Suave.Web.httpLoop.loop]
[V] 2016-01-19T02:44:59.9518518Z: freeing buffer: 811008, free count: 100 [Suave.Tcp.job] [Suave.Socket.BufferManager]
[V] 2016-01-19T02:44:59.9518518Z: Shutting down transport. [Suave.Tcp.job]
[V] 2016-01-19T02:44:59.9528516Z: 127.0.0.1 disconnected, total: 0 clients [Suave.Tcp.job]

When the app executes the connection opens and then closes immediately. When I hit the app by port a new connection opens and then closes immediately (again).
Am I doing something wrong with the host configuration for the app, or am I missing something in how I'm using the choose function? Any help would be appreciated. Thank you!

A: I think the routes should look like :
path "/app/hello"


text:
Q: Best way to add a space when joining values What would be the best way to implement spaces in my variable so that I can display it like value | value and not value|value
Code:
$pageTitle         = $pageName . '|' . $siteName;

A: This is your solution:
$pageTitle         = $pageName . ' | ' . $siteName;

Anyway you can use this to:
$pageTitle         = $pageName . ' | ' . $siteName;

In this last, you can give 1,2,3 or more spaces, example:
$pageTitle         = $pageName . '   |   ' . $siteName;
$pageTitle         = $pageName . '   |   ' . $siteName;

Reference: http://www.w3schools.com/html/html_entities.asp

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to unarchive data in swift 3? I have an app where I save an array of CNContact to UserDefaults as such:
var contactsArray = [CNContact]()
let defaults = UserDefaults()
func (contact: CNContact){
    contactsArray.append(contact)
    let contactArrayArchive = NSKeyedArchiver.archivedData(withRootObject: contactArray) //archive the data
    defaults.set(contactArrayArchive, forKey: "contactArray")
    defaults.synchronize()
}

This archives the data to allow it to be saved to defaults. My issue is with how I can convert this data back to an array of CNContact in the viewDidLoad. I have seen many answers online which suggest to use NSKeyedArchiver.unarchiveObjectwithData but typing this into Xcode, with swift 3, says that the .unarchiveObjectwithData is not a member of NSKeyedArchiver. I keep looking for stuff about how to do this in swift 3 but have been unsuccessful. How can I unarchive the value?

A: You can use
 NSKeyedUnarchiver.unarchiveObject(with: Data)

You have Used NSKeyedArchiver . You cannot use this to unarchive an Object.

A: If you press ⇧⌘0 to open the documentation and type nsk (3 characters are sufficient) you will see

To unarchive something you need the NSKeyedUnarchiver


text:
Q: Render react-bootstrap modal onclick I need to open ReactBootstrap.Modal window on click + to pass some properties to the modal.
I have my component with modal window content:
React.createClass({
  render: function () {
    return (
        <ReactBootstrap.Modal show={this.state.show} bsSize="large" aria-labelledby="contained-modal-title-lg">
            <ReactBootstrap.Modal.Header onClick={this.hideHandler} closeButton>
                <ReactBootstrap.Modal.Title id="contained-modal-title-lg">Babe Info:</ReactBootstrap.Modal.Title>
            </ReactBootstrap.Modal.Header>
            <ReactBootstrap.Modal.Body>
        some body
            </ReactBootstrap.Modal.Body>
            <ReactBootstrap.Modal.Footer>
                <ReactBootstrap.Button onClick={this.hideHandler}>Close</ReactBootstrap.Button>
            </ReactBootstrap.Modal.Footer>
        </ReactBootstrap.Modal>
    );
  }
});

What I need is to create and mount this component upon user click + pass to the component some properties that depends on where exactly one clicked.
I did something like this in my click handler, but it doesn't work:
    var modal = React.createElement(MyModal, this.props.data);
    ReactDOM.render(
        modal,
        document.getElementById('modal_container')
    );

Any advices?


text:
Q: How to add title on line numbers?
So I am using the function \linenumbers which by default puts a number for each line at the left for the written text. But I somehow need a unit/title on the number but I can't find anything about this?
Example:

title
1       Something something
2       Something something
3       Something something
4       Something something
5       Something something

I hope someone can lead me in a direction to this!

A: You can write a title and shift it to the left by removing paragraph indent with \noindent and shifting it further into the margin by a negative \hskip (horizontal skip).
However, line numbers are not really suitable to be used for numbered lists. Firstly, the numbers are in the margin, so they are not really part of the text visually. Secondly, the numbers are for lines, so if you have an item that is more than one line then it is not numbered correctly. Thirdly, the numbers are small, which may not look good if your list items are in a larger font.
The normal environment for numbered list is enumerate. You can customize such lists using the enumitem package, which allows you to set the indentation, label width, distance between lines, etc.
An example of both the linenumbers approach and the enumerate approach:
\documentclass{article}
\usepackage{lineno}
\usepackage{enumitem}
\begin{document}
\noindent \hskip-15pt Title

\linenumbers
Something something

Something something

Something something

Something something

Something something

\nolinenumbers

\vspace{5mm}

\noindent Title
\begin{enumerate}[itemsep=-1mm,labelsep=6mm]
\item Something something
\item Something something
\item Something something
\item Something something
\item Something something
\end{enumerate}
\end{document}


text:
Q: Extending django catridge product causes Grapelli KeyError in admin I'm currently working on a django / mezzanine / cartridge store.
All of my products will have a CAD file and a PDF file, in an effort to stay DRY I have created a BaseProduct model which is defined as follows:
models.py
class BaseProduct(Product):
     cadfile = fields.FileField(upload_to="product", extensions=(".dwg",), blank=True, null=True)
     pdffile = fields.FileField(upload_to="product", blank=True, null=True)

     objects = SearchableManager()
     search_fields = ("title", "description")

     class Meta:
         abstract = True

Additionally, I have other product types that subclass this base product type as follows.
class CorniceProduct(BaseProduct):
     cornice_picture =  fields.FileField(upload_to="product", null=True, blank=True)
     ceiling_projection = models.IntegerField(null=True, blank=True)
     wall_height = models.IntegerField(null=True, blank=True)

class CeilingRoseProduct(BaseProduct):
     width = models.IntegerField(null=True, blank=True)
     height = models.IntegerField(null=True, blank=True)

This works as far as models goes, the issue comes with the mezzanine admin area, this is mostly derived from the cartridge/shop/admin.py file.
admin.py
option_fields = [f.name for f in ProductVariation.option_fields()]

product_fieldsets = deepcopy(DisplayableAdmin.fieldsets)
product_fieldsets[0][1]["fields"].insert(2, "available")
product_fieldsets[0][1]["fields"].extend(["content", "categories", "pdffile", "cadfile"])
product_fieldsets = list(product_fieldsets)

other_product_fields = []
if settings.SHOP_USE_RELATED_PRODUCTS:
    other_product_fields.append("related_products")
if settings.SHOP_USE_UPSELL_PRODUCTS:
    other_product_fields.append("upsell_products")
if len(other_product_fields) > 0:
    product_fieldsets.append((_("Other products"), {
    "classes": ("collapse-closed",),
    "fields": tuple(other_product_fields)}))

product_list_display = ["admin_thumb", "title", "status", "available",
                    "admin_link"]
product_list_editable = ["status", "available"]

# If variations are used, set up the product option fields for managing
# variations. If not, expose the denormalised price fields for a product
# in the change list view.
if settings.SHOP_USE_VARIATIONS:
    product_fieldsets.insert(1, (_("Create new variations"),
        {"classes": ("create-variations",), "fields": option_fields}))
else:
    extra_list_fields = ["sku", "unit_price", "sale_price", "num_in_stock"]
    product_list_display[4:4] = extra_list_fields
    product_list_editable.extend(extra_list_fields)

class CorniceProductAdmin(ProductAdmin):
    cornice_additional_fieldsets = ("cornice_picture", "ceiling_projection", "wall_height" )
    fieldsets = product_fieldsets
    fieldsets.append((_("Cornice specific"), {
        "fields": tuple(cornice_additional_fieldsets)
   }))

admin.site.register(CorniceProduct, CorniceProductAdmin)

class CeilingRoseProductAdmin(ProductAdmin):
    rose_additional_fieldsets = ("width", "height")
    fieldsets = product_fieldsets
    #del fieldsets[4]
    fieldsets.append((_("Ceiling Rose specific"), {
        "fields": tuple(rose_additional_fieldsets)
    }))
    exclude = ('cornice_picture', 'ceiling_projection', 'wall_height',)

admin.site.register(CeilingRoseProduct, CeilingRoseProductAdmin)

When I go into the admin area to edit a ceilingroseproduct I get the following error:
Error & Traceback
Template error:
In template /home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/grappelli_safe/templates/admin/change_form.html, error at line 14
   Key 'cornice_picture' not found in 'CeilingRoseProductForm'. Choices are: _meta_title, available, cadfile, categories, content, description, expiry_date, gen_description, height, in_sitemap, keywords, option1, option2, pdffile, publish_date, related_products, slug, status, title, upsell_products, width.   4 : {% load i18n admin_urls admin_static admin_modify %}
   5 :
   6 : <!-- JAVASCRIPTS -->
   7 : {% block javascripts %}
   8 :     {{ block.super }}
   9 :     {% url "admin:jsi18n" as jsi18nurl %}
   10 :     <script src="{{ jsi18nurl|default:"../../../jsi18n/" }}"></script>
   11 :     {{ media }}
   12 :     {% if inline_admin_formsets %}
   13 :     <script src="{% static "grappelli/js/admin/Inline.js" %}"></script>
   14 :     <script  src="{% static "grappel li/js/admin/CollapsedInlineFieldsets.js" %}"></script>
   15 :     {% endif %}
   16 : {% endblock %}
   17 :
   18 : <!-- COLTYPE/BODYCLASS -->
   19 : {% block coltype %}colM{% endblock %}
   20 : {% block bodyclass %}{{ opts.app_label }}-{{ opts.object_name.lower }} change-form{% endblock %}
   21 :
   22 : <!-- BREADCRUMBS -->
   23 : {% block breadcrumbs %}{% if not is_popup %}
   24 : <div class="breadcrumbs">

Traceback:

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/forms/forms.py" in __getitem__
  144.             field = self.fields[name]

During handling of the above exception ('cornice_picture'), another exception occurred:

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response
  217.                 response = self.process_exception_by_middleware(e, request)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response
  215.                 response = response.render()

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/response.py" in render
  109.             self.content = self.rendered_content

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/response.py" in rendered_content
  86.         content = template.render(context, self._request)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/backends/django.py" in render
  66.             return self.template.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render
  208.                     return self._render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in _render
  199.         return self.nodelist.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render
  994.                 bit = node.render_annotated(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render_annotated
  961.             return self.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/loader_tags.py" in render
  174.         return compiled_parent._render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in _render
  199.         return self.nodelist.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render
  994.                 bit = node.render_annotated(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render_annotated
  961.             return self.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/loader_tags.py" in render
  174.         return compiled_parent._render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in _render
  199.         return self.nodelist.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render
  994.                 bit = node.render_annotated(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render_annotated
  961.             return self.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/loader_tags.py" in render
  70.                 result = block.nodelist.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render
  994.                 bit = node.render_annotated(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render_annotated
  961.             return self.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/loader_tags.py" in render
  70.                 result = block.nodelist.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render
  994.                 bit = node.render_annotated(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render_annotated
  961.             return self.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/defaulttags.py" in render
  209.                     nodelist.append(node.render_annotated(context))

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render_annotated
  961.             return self.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/loader_tags.py" in render
  210.                 return template.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render
  210.                 return self._render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in _render
  199.         return self.nodelist.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render
  994.                 bit = node.render_annotated(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render_annotated
  961.             return self.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/defaulttags.py" in render
  209.                     nodelist.append(node.render_annotated(context))

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/base.py" in render_annotated
  961.             return self.render(context)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/template/defaulttags.py" in render
  165.                 values = list(values)

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/contrib/admin/helpers.py" in __iter__
  115.                 yield AdminField(self.form, field, is_first=(i == 0))

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/contrib/admin/helpers.py" in __init__
  127.         self.field = form[field]  # A django.forms.BoundField instance

File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/forms/forms.py" in __getitem__
  150.                     ', '.join(sorted(f for f in self.fields)),

Exception Type: KeyError at /admin/my_shop/ceilingroseproduct/add/
Exception Value: "Key 'cornice_picture' not found in 'CeilingRoseProductForm'. Choices are: _meta_title, available, cadfile, categories, content, description, expiry_date, gen_description, height, in_sitemap, keywords, option1, option2, pdffile, publish_date, related_products, slug, status, title, upsell_products, width."

I can fix it by umcommenting the del fieldsets[4] line, however this seems very hacky and would require this level of override for each product type which I don't really want to do.

A: Have a look at this PR in Cartridge which will become the official way to do what you're trying to do:
https://github.com/stephenmcd/cartridge/pull/293


text:
Q: Adding two calculated times together in PHP I need some help, I have already previously calculated my times for a weekly timesheet in PHP, not my question; is it possible to add these all together?
I tried to use the following function but i'm not sure this works. The aim is for each week to calculate how much time is spent in total in this format.
$time = "18 hours 13 minutes";
$time2 = "47 minutes";
$time3 = "1 hour";
$time4 = "1 hour";
$time5 = "1 hour";
$time6 = "";
$time7 = "";

$max_date=abs(strtotime($time) + strtotime($time2) + strtotime($time3) + strtotime($time4) + strtotime($time5) + strtotime($time6) + strtotime($time7));

So in all it should show 22 hours as the total.
Thats if this is possible?

A: You can do this using DateTime objects. We create two identical objects using the current time, then we use the modify method to add each of the time variables to one of them. We can then take the difference between the two objects (creating a DateInterval object) and output the value of that in the same format as the inputs:
$start = new DateTime();
$end = clone($start);

if (!empty($time)) $end->modify("+$time");
if (!empty($time2)) $end->modify("+$time2");
if (!empty($time3)) $end->modify("+$time3");
if (!empty($time4)) $end->modify("+$time4");
if (!empty($time5)) $end->modify("+$time5");
if (!empty($time6)) $end->modify("+$time6");
if (!empty($time7)) $end->modify("+$time7");

$total = $end->diff($start);
echo $total->format('%h hours %i minutes');

Output:
22 hours 0 minutes

Demo on 3v4l.org


text:
Q: Infinite $digest Loop - ng-repeat I'm getting an error Infinite $digest Loop while trying to loop through the following ng-repeat.
<select ng-options="item.QuoteId as item.Quote for item in smallGroup.getQuotesByRating(control.vlcSI['recSet']) track by $index">
    <option value="">Select Quote</option>
</select>

I have the following JS function :
          function getQuotesByRating(quotes){
                var quoteList = [];
                if(typeof quotes != 'undefined' && quotes.length > 0){
                    quotes.map(function(item){
                        if(item.RatingType == 'Member & Composite'){
                            item.Quote =  item.Quote + ' : Member Rated'
                            quoteList.push(item);
                            item.Quote =  item.Quote + ' : Composite Rated'
                            quoteList.push(item);
                        }
                        else{
                            item.Quote =  item.Quote + ' : ' + item.RatingType
                            quoteList.push(item);
                        }
                    });
                    return quoteList;
                }
                return quotes;
          }

What would be the possible solution for this situation?


text:
Q: loading multiple libraries by using loadlibrary function I want to load the following libraries.
librariesmozcrt19.dll
nspr4.dll
plc4.dll
plds4.dll
mozsqlite3.dll
nssutil3.dll
softokn3.dll
nss3.dll

I know the single library can be loaded as
HMODULE hDLL=LoadLibrary(pDLLName);

But I'm not getting how load multiple libraries.

A: Call LoadLibrary for each library in turn. There is no "bulk load" API.


text:
Q: Convolution in Hardy spaces Question Are there non-trivial restrictions on the coefficients of functions in Hardy spaces ($H_p(\mathbb{D})$, $p<1$) that make a subspace that is closed under convolution?
Definition The Hardy space $H_p$ is the set of power series $f(z)=\sum_{n=0}^{\infty}a_nz^n$ which have finite norm
\begin{equation*}
\| f\|_{H_p}= \lim_{\rho\rightarrow 1^{-}}\| g\|_{L_p},
\end{equation*}
where $g(\theta) = f(\rho e^{i\theta})$.
Definition The convolution of two functions $f(z)=\sum_{n=0}^{\infty}a_nz^n$, $g(z)=\sum_{n=0}^{\infty}b_nz^n$ is defined as
\begin{equation}
f*g(z) =\sum_{n=0}^{\infty}a_nb_n z^n
\end{equation}
Question If $f,g\in H_p$ and $\{a_n\},\{b_n\}\in \ell_{\infty}$, then $\{a_nb_n\}\in \ell_{\infty}$. Is $f*g\in H_p$?


text:
Q: How does GeoTIFF file store elevation data? I'm trying to understand how elevation data is stored in GeoTIFF files, when used for Digital Elevation/Surface Models. My very basic understanding is that in a GeoTIFF file (or at least those produced by Fusion's dtm2tif function), each pixel has a value associated with it for each band, and that these values are 0 if no data is present, and between 1 and 255 for data.
Is there a piece of metadata in the GeoTIFF that indicates how to scale between 1-255 to the elevation data in the elevation model?
Is there an easy way of accessing this scaling in python?


text:
Q: transform ec2 tags with jq and node.js I need to transform this ec2 tags (array)
[
    { Key: 'Name', Value: 'xxx' },
    { Key: 'role', Value: 'yyy' }
]

to
{
 name : 'xxx',
 role : 'yyy'
}

using jq and node.js. Could you help please
regards

A: You could use Object.fromEntries like this:

const tags = [
    { Key: 'Name', Value: 'xxx' },
    { Key: 'role', Value: 'yyy' }
];

const obj = Object.fromEntries(tags.map(({ Key, Value }) => [Key, Value]));

console.log(obj);


text:
Q: How to update a table with composite key using hibernate? I am newbie to hibernate. If there is a table which has a composite key, how to update the table using hibernate.

A: You should be able to use a composite-id for that.
Example copied from the link:
<composite-id
    name="propertyName"
    class="ClassName"
    mapped="true|false"
    access="field|property|ClassName">
    node="element-name|."

    <key-property name="propertyName" type="typename" column="column_name"/>
    <key-many-to-one name="propertyName" class="ClassName" column="column_name"/>
    ......
</composite-id>

You can then retrieve the record using load instead of get
Book bk1 = new Book();
bk1.setBookId(1);
bk1.setBookName("Hibernate Examples");
bk1.setAuthor("ISHTEK");
Book bk2 = (Book) session.load(Book.class, bk1);

which you can then update after changing your values
session.update(bk1);


text:
Q: Errors in sbt Scala project Created a sample Scala project structure (on my OS X Mavericks based computer) as follows:
Inside sample_project dir:
src
    main
      java
      scala
        Hello.scala
      resources
    test
      java
      scala
      resources
 build.sbt

Hello.scala:
object Hello {
    def main(args: Array[String]) = println("Hello!")
}

build.sbt:
name := "hello"

version := "1.0"

scalaVersion := "2.11.1"

Placed the build.properties under sample_project/project:
sbt.version=0.13.5

When I try to run it using the "sbt" command inside the root folder:
/sample_project $ sbt
Getting org.scala-tools.sbt sbt_2.8.1 0.13.5 ...

:: problems summary ::
:::: WARNINGS
        module not found: org.scala-tools.sbt#sbt_2.8.1;0.13.5

    ==== local: tried

      .ivy2/local/org.scala-tools.sbt/sbt_2.8.1/0.13.5/ivys/ivy.xml

      -- artifact org.scala-tools.sbt#sbt_2.8.1;0.13.5!sbt_2.8.1.jar:

      .ivy2/local/org.scala-tools.sbt/sbt_2.8.1/0.13.5/jars/sbt_2.8.1.jar

    ==== Maven2 Local: tried

      file://.m2/repository/org/scala-tools/sbt/sbt_2.8.1/0.13.5/sbt_2.8.1-0.13.5.pom

      -- artifact org.scala-tools.sbt#sbt_2.8.1;0.13.5!sbt_2.8.1.jar:

      file://.m2/repository/org/scala-tools/sbt/sbt_2.8.1/0.13.5/sbt_2.8.1-0.13.5.jar

    ==== typesafe-ivy-releases: tried

      http://repo.typesafe.com/typesafe/ivy-releases/org.scala-tools.sbt/sbt_2.8.1/0.13.5/ivys/ivy.xml

      -- artifact org.scala-tools.sbt#sbt_2.8.1;0.13.5!sbt_2.8.1.jar:

      http://repo.typesafe.com/typesafe/ivy-releases/org.scala-tools.sbt/sbt_2.8.1/0.13.5/jars/sbt_2.8.1.jar

    ==== Maven Central: tried

      http://repo1.maven.org/maven2/org/scala-tools/sbt/sbt_2.8.1/0.13.5/sbt_2.8.1-0.13.5.pom

      -- artifact org.scala-tools.sbt#sbt_2.8.1;0.13.5!sbt_2.8.1.jar:

      http://repo1.maven.org/maven2/org/scala-tools/sbt/sbt_2.8.1/0.13.5/sbt_2.8.1-0.13.5.jar

    ==== Scala-Tools Maven2 Repository: tried

      http://scala-tools.org/repo-releases/org/scala-tools/sbt/sbt_2.8.1/0.13.5/sbt_2.8.1-0.13.5.pom

      -- artifact org.scala-tools.sbt#sbt_2.8.1;0.13.5!sbt_2.8.1.jar:

      http://scala-tools.org/repo-releases/org/scala-tools/sbt/sbt_2.8.1/0.13.5/sbt_2.8.1-0.13.5.jar

    ==== Scala-Tools Maven2 Snapshots Repository: tried

      http://scala-tools.org/repo-snapshots/org/scala-tools/sbt/sbt_2.8.1/0.13.5/sbt_2.8.1-0.13.5.pom

      -- artifact org.scala-tools.sbt#sbt_2.8.1;0.13.5!sbt_2.8.1.jar:

      http://scala-tools.org/repo-snapshots/org/scala-tools/sbt/sbt_2.8.1/0.13.5/sbt_2.8.1-0.13.5.jar

        ::::::::::::::::::::::::::::::::::::::::::::::

        ::          UNRESOLVED DEPENDENCIES         ::

        ::::::::::::::::::::::::::::::::::::::::::::::

        :: org.scala-tools.sbt#sbt_2.8.1;0.13.5: not found

        ::::::::::::::::::::::::::::::::::::::::::::::

:: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS
unresolved dependency: org.scala-tools.sbt#sbt_2.8.1;0.13.5: not found
Error during sbt execution: Error retrieving required libraries
  (see sample_project/project/boot/update.log for complete log)
Error: Could not retrieve sbt 0.13.5

A: This looks like an sbt version mismatch. Create a project directory under sample_project and inside it create a file called build.properties with the following contents:
sbt.version=0.13.5

A: It seems you have an old launcher version of sbt, perhaps even too old to cope with the new 0.13.5.
Try to update your launcher to the latest version. On MacOS, the easiest way is to use the Homebrew package manager. If not already done, install it with:
$ ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

then, install sbt:
$ brew install sbt


text:
Q: QPython Android PySpeedTest I installed this module PySpeedTest on the QPython on Androidenter code here and tried running the below code
import pyspeedtest
st = pyspeedtest.SpeedTest()
ping = st.ping()
download = st.download()
upload = st.upload()

print('ping: ' + str(ping))
print('download: ' + str(download))
print('upload: ' + str(upload))

which returns

ping: 20.457208156585693
download: 79367128.02705236
upload: 8458681.882858781

The above code dosent seem to work . I got from this link
https://pypi.org/project/pyspeedtest/
can somebody please help me.


text:
Q: unexpected outcome of data.table fintersect all = TRUE Set operations for data tables
The amazing data.table package contains Set operations for data tables. The examples given in the documentation contain datatables with only one column. In order to understand their behaviour and difference with base R set operations I extended the tables with another column. This resulted in an unexpected outcome, which might be due to my understanding, it might also be a bug which I will raise if the stackoverflow community agrees.
Example 1, with expected outcome
The following example shows the expected behaviour when we use the default setting for parameter all set to FALSE
library(data.table)

(DT <-
    data.table(
      x = c(1, 2, 2, 2),
      y = LETTERS[c(1, 2, 2, 3)]
    )
)

   x y
1: 1 A
2: 2 B
3: 2 B
4: 2 C

data.table::fintersect(DT, DT, all = FALSE)

   x y
1: 1 A
2: 2 B
3: 2 C

Example 2, with unexpected outcome
The following example shows the unexpected behaviour when we don't use the default setting for parameter all but set it to TRUE
library(data.table)

(DT <-
    data.table(
      x = c(1, 2, 2, 2),
      y = LETTERS[c(1, 2, 2, 3)]
    )
)

   x y
1: 1 A
2: 2 B
3: 2 B
4: 2 C

data.table::fintersect(DT, DT, all = TRUE)

   x y
1: 1 A
2: 2 B
3: 2 B

Expected Outcome

   x y
1: 1 A
2: 2 B
3: 2 B
4: 2 C

Analysis
The implementation of data.table::fintersect can be found on Git as found by a commit of jangorecki committed on 6 Mar 2016

Reproducing this function in R-code gives the expected outcome
DT1 <-  copy(DT)[, ".seqn" := rowidv(DT)]
DT2 <-  copy(DT)[, ".seqn" := rowidv(DT)]
DT1[DT2, .SD, .SDcols=setdiff(names(DT1),".seqn"), nomatch=0L, on=names(DT1)]

   x y
1: 1 A
2: 2 B
3: 2 B
4: 2 C

Question
As this function exists for many years I would be surprised if this is a bug, probabaly my understanding is wrong. It might be due to my R-version or other dependencies (see sessionInfo() below)
What should be the behaviour?
SessionInfo
R version 4.0.5 (2021-03-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19043)

Matrix products: default

locale:
[1] LC_COLLATE=Dutch_Netherlands.1252  LC_CTYPE=Dutch_Netherlands.1252    LC_MONETARY=Dutch_Netherlands.1252
[4] LC_NUMERIC=C                       LC_TIME=Dutch_Netherlands.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] data.table_1.14.2

loaded via a namespace (and not attached):
 [1] compiler_4.0.5  fastmap_1.1.0   htmltools_0.5.2 tools_4.0.5     yaml_2.2.1      rmarkdown_2.10  knitr_1.33      xfun_0.25
 [9] digest_0.6.27   rlang_0.4.11    evaluate_0.14

A: Example 3, with expected outcome and ALL = TRUE
The answer of Cole is indeed the root cause, many thanks. I will raise a bug.
Below the working example based on the comments
library(data.table)

(DT <-
    data.table(
      x1 = c(1, 2, 2, 2),
      y1 = LETTERS[c(1, 2, 2, 3)]
    )
)

   x1 y1
1:  1  A
2:  2  B
3:  2  B
4:  2  C

data.table::fintersect(DT, DT, all = TRUE)

   x1 y1
1:  1  A
2:  2  B
3:  2  B
4:  2  C


text:
Q: Cursor is always crosshair in D3 due to slider I'd like to change my cursor, which is always "crosshair" when hovering over my D3 visualization. I don't have any JS, D3 og CSS code that should change the cursor to "crosshair". I've tried d3.select("body").style("cursor", "default"); and
html, body {cursor: "default";}, but nothing seems to work. Is this a common problem?
EDIT: I've found that it's likely due to my use of a slider/brush. See http://jsfiddle.net/0ukesgaw/.
Updated jsfiddle. Still not working.

A: No, it's not a common problem AFAIK. It would be easier to help if you provided a code sample. It's generally a better approach to apply the CSS for the cursor on the d3 visualization itself, not "globally" on the html or body elements.
CSS example:
svg {
  cursor: default;
}

Update 1:
I inspected the elements using Chrome's dev tools (right-click > Inspect element) and found this:
<rect class="background" x="0" width="200" height="210"
  style="visibility: hidden; cursor: crosshair;"></rect>

Which means that the cursor: crosshair is somehow applied to this element. I can't see it anywhere in your source code, so I suppose it's something that d3 adds – so you were right in your original question.
A quickfix for this, would be to add:
svg rect.background {
  cursor: default !important;
}

However, it's probably worth taking the time to find the source code that generates it, if this is going to be in production.
Update 2:
Looking closer at this, it seems to come from d3's Brush component: https://github.com/mbostock/d3/wiki/SVG-Controls#brush
This is from https://github.com/mbostock/d3/blob/master/src/svg/brush.js:
  background.enter().append("rect")
    .attr("class", "background")
    .style("visibility", "hidden")
    .style("cursor", "crosshair");

Looks like you need to go with something like cursor: default !important :-/


text:
Q: Chart.js chart.update() method is not doing anything I am working with Chart.js. I have a chart that can display the data. I also have different datasets that I would like to interchange on a button press.
All the datasets are in an array and should just be interchanged with my method. Once I changed all the values, I call the update() method. Nothing happens!
I have checked the content of char.data.datasets.data and it does in fact contain the current data. The only thing is, that Chart.js does not seem to want to update.
What am I missing here?
The function that updates the chart:
let getValues = function(dataset, label)
{
  return firebase.database().ref("/data/" + dataset).once("value").then(function(snapshot)
  {
    var amazon = snapshot.val().Amazon;
    var google = snapshot.val().Google;
    var facebook = snapshot.val().Facebook;
    var twitter = snapshot.val().Twitter;

    chart.data.datasets.data = [];
    chart.data.labels = [];
    chart.data.datasets.label = null;

    chart.data.datasets.data = [amazon, google, facebook, twitter];
    chart.data.labels = names;
    chart.data.datasets.label = label;
    chart.update();
    console.log(chart.data.datasets.data);
  });
}

If you need any more information please let me know.

A: chart.data.datasets is an array of datasets, not a single dataset. datasets does not have its own data and label attributes. Rather, each individual dataset in the array has its own data and label attributes. You therefore cannot do datasets.data or dataset.label.
If you want to update the data or label variable of a specific dataset, you need to select that object from the array. To select the first dataset, simply use datasets[0]:
chart.data.datasets[0].data = [amazon, google, facebook, twitter];
chart.data.datasets[0].label = label;

If you want to update all datasets, use a forEach loop to iterate through the array:
chart.data.datasets.forEach((dataset) => {
    dataset.data = [amazon, google, facebook, twitter];
    dataset.label = label;
});

Two more points:
One other possible problem is that the names variable is not initialized anywhere, though it could be that you just didn't include that part of the code in your question.
Also, why do you have the following three lines of code, if you just reassign all the values in the next three lines of code?
chart.data.datasets.data = [];
chart.data.labels = [];
chart.data.datasets.label = null;


text:
Q: Symmetry factors in two interacting fields
Red and blue colored lines represent the two different fields.
At 1st order, by the exchange of the blue legs and red legs we get $\frac{1}{4}$ factor and in one of the 2nd order term drawn above, from the exchange of vertices, the blue legs and red legs we get $\frac{1}{2^4 \cdot 2}$.
However it seems like I'm missing a factor of 2 in the numerator for the number of topologically different feynman diagrams.
Could anyone point out what I'm missing here?

A: If we are using the standard convention, where each term$^1$ in the Lagrangian is divided by its symmetry factor, then the numerical coefficient in front of a Feynman diagram is the reciprocal of its symmetry factor $S$.
For a proof, see e.g. Ref. 1.
OP's first diagram has $S=4$ while OP's second diagram has $S=16$.
References:

*

*P. Etingof, Geometry & QFT, MIT 2002 online lecture notes; Chapter 3.

--
$^1$ In particular, this means that OP's interaction term in the Lagrangian should be normalized as $-\frac{\lambda}{4}\color{red}{\phi}^2\color{blue}{\phi}^2$.

A: Assuming we have the interaction $$\mathcal{L}_{\text{int}}=\frac{\lambda}{2\times2}\phi^2\Phi^2$$
The first bubble diagram comes from the $1$st-order expansion of the expression
$$\langle \Omega|Te^{-i\int d^4x\mathcal{L}_{\text{int}}}|\Omega\rangle$$
which is
$$\frac{-i\lambda}{4}\int d^4x\langle \Omega|T\phi(x)^2\Phi(x)^2|\Omega\rangle$$
There's only one way to contract this expression, namely $\phi$ with $\phi$ and $\Phi$ with $\Phi$, and so we just have the $1/4$.
The next two-loop bubble diagram comes from the $2$nd-order expansion
$$\frac{1}{2!}\left(\frac{-i\lambda}{4}\right)^2\int d^3x ~d^3y \langle \Omega|T\phi(x)^2\Phi(x)^2\phi(y)^2\Phi(y)^2|\Omega\rangle$$
There's a bunch of terms in this expression, the one we want is generated by contracting the 2 $\Phi(x)$s and $\Phi(y)$s together. There are two ways for the 4 $\Phi$s to contract with each other and only one way for the remaining $\phi$s to contract at the same points. And so the overall numerical factor in front of our integral here is
$$2\times\frac{1}{2!}\times\frac{1}{4^2}=\frac{1}{16}$$


text:
Q: OpenGL ES 2.0 - Multiple post processing effects Hello
I want to apply multiple image processing effects to an input texture using OpenGL ES.
I successfully managned to apply one post processing effect using a Framebuffer Object but I do not quite understand how, without repeating every single step of my step of my process, I can apply numerous post processing effect without having to redo every step each time.
The steps I am going through right now are the following:

*

*Loading my shader(s) and getting the desired location to transfer my data

*Initializating my FBO

*Creating a texture using my input data

*Binding FBO

*Activating TEXTURE0 and binding the previously generated texture

*Sending data using the acquired location

*Drawing a full screen quad and making it use my shader program

*Reading the FBO texture (using glReadPixels) and saving the result to an image

*Unbinding everything to clean up.

From what I understand I do need to repeat the step 5,6,7 with my other post processing shader and using the texture I finally got in step 8 but I do not think this is the right way to go as it wil force me to read data from FBO into a texture to then retransfert them which is really costy.
Am I missing something ?

A: If your 2 post-processing effects can be done in a single shader then you should do that, it's much more efficient that way because the memory bandwidth costs of reading and writing entire framebuffers often dwarfs the cost of a few extra shader calculations.
However, many post-processing effects need to operate on the finished result of previous post-processing pass. The typical solution is to setup two FBOs and 'ping-pong' between them. So, if you had 3 post-processing effects that need to be chained, you'd have 3 passes:

*

*Pass 1. Texture=Input Data, Shader=Effect1, Render Target=FBO A.

*Pass 2. Texture=FBO A, Shader=Effect2, Render Target=FBO B.

*Pass 3. Texture=FBO B, Shader=Effect1, Render Target=FBO A.

I think the bit you're missing is that you can use the texture from a framebuffer directly without having to create a brand new texture populated with data from glReadPixels. This tutorial might help.


text:
Q: How do I add a link to my HTML page with out affecting the other functionality in the page? I added one new link in a webpage. it works fine, but when I hit a link, one blank is coming with that page. I know the reason: it's because of  in the bottom. I am adding the code below.
My question is "how to add without affecting other links" or changing functionality in other web page?
In the first web page, I added this link:
<%-- Access the A.O.E.One-Stop-Shop in the Resource Center for further information and instructions.--%>

This link is affected by an  in the same page.

The  is calling in another webpage. Due to this I am getting a blank page.


text:
Q: How to show an error on enter key press if textarea empty? I have this chat which I am trying to make. Everything works ok so far but I want to show an error when I press enter if the textarea is empty. Can anyone tell me how I can do it? I've been trying many methods but nothing worked. Thank You.
$("#message").keypress(function(e) {
    var test = $("#Uname").val()
    var valmsg = $('#message').val();

    if (e.which == 13 && valmsg.trim()) {
        $("#chat").append("
" + test+ ':' + valmsg + "
");
        $('#message').val('');
    }
});

Here is my code https://jsfiddle.net/azfwuzad/2/

A: You can achieve this by checking that the value of the textarea is not empty when the return key is pressed. Try this:
$("#message").keypress(function(e) {
    var test = $("#Uname").val()
    var valmsg = $('#message').val();

    if (e.which == 13 && valmsg.trim() == "") {
        e.preventDefault();
        alert('Please type a message to send');
    } else if (e.which == 13) {
        $("#chat").append("
" + test + ':' + valmsg + "
");
        $('#message').val('');
    }
});

Updated fiddle
The call to preventDefault() will stop the enter key press from adding a new line in an empty textarea.


text:
Q: NodeJS - Parse JSON (only strings or numbers) I have got a little dilema what to do (What should I do). I've got in my app several places where I am using AJAX to transfer a JSON data. So for example receiving a data from the registration form:
try {
   var data = JSON.parse(json);
}
catch(e) {
   // ...
}

var fields = {
   firstName: data.firstName || "",
   lastName: data.lastName || "",
   ...
};

Then I need to do something with these fields. Let's say:
if (fields.firstName) {
   // OK save it to the DB
}

if(fields.lastName.xxx()) { // xxx() is a method that belongs to JS String Object
   // Do something...
}

The problem is what if fields.firstName or fields.lastName is {} / []? That may happen if somebody sent a modified JSON with a wrong data types, the whole app will then crash since the method xxx is missing.
Do I have to check the type of every field whether it is really a string, a number, an array... or is there some another maybe nicer way how to do this?

A: Unfortunately that's a problem you'll have to face anytime using a dynamic language like JavaScript.
One possible solution is not using String methods, but creating a function that will check it's arguments first:
// original, with string methods
if (text instanceof String && text.trim().length === 0) { ... }

// alternative, define function first
var isEmptyString = function(text) {
  if (!(text instanceof String)) throw new Error("Argument must be a String");
  return text.trim().length === 0;
}

// use it in your code
if (isEmptyString(text)) { ... }

That can lead to cleaner code.
Just be sure not to define those functions in a global scope, when you have to use them in a Browser. Within the node.js modules that should not be a problem.

A: You'll have to make a little validator. Like that:
var format = {
  foo: "string",
  bar: "string"
};
var data = {
  foo: "bar",
  bar: []
}
var validate = function (data, format) {
  for(var d in data) {
    if(typeof data[d] !== format[d])
      return false;
  }
  return true;
}
console.log(validate(data, format));

You can also remove invalid data like this:
var format = {
  foo: "string",
  bar: "string"
};
var data = {
  foo: "bar",
  bar: []
}
var validate = function (data, format) {
  for(var d in data) {
    if(typeof data[d] !== format[d])
      delete data[d];
  }
  return data;
}
console.log(validate(data, format));

A: In addition to what Tharabas suggests, you could take advantage of the 2nd argument of JSON.parse for doing your sanity check:
JSON.parse(data, function(key, value) {
  return key === 'firstName' ? cleanup(value) : '';
});

See this page for further information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse


text:
Q: how to pass another argument to url django? dans my views.py of page1.html :
def spwords(request, spray_id)
  if request.method == 'POST':
    value= request.POST["rangeVal"]  #### the other argument that i want to pass it to views.py of the second page html ...
    form = forms.SpwordsForm(request.POST)

    return HttpResponseRedirect(reverse('sp_url', args=[sp_id]))  # if POST we go to page2.html on this url

in my url.py :
 url(r'^queries/(.*)$', qviews.sp_queries, name='sp_url')

in my views.py of the Page2.html :
 def sp_queries(request, sp_id):
      #### here i want to recupere arguments : sp_id and value

i want to pass  value= request.POST["rangeVal"]  of the views.py of the first page html to the second page html, i.e , i want to pass value in arguments of "HttpResponseRedirect(reverse('sp_url', args=[sp_id]))".
but i want to keep the format of urls.py : i.e just   queries/sp_id

A: You can use url querystring. For example:
url = "{}?rangeVal={}".format(reverse('sp_url', args=[sp_id]),value)
return HttpResponseRedirect(url)

Here I am adding the value of rangeVal as url querystring and passing to HttpResponse. Now to get the value in sp_queries, you can use the following code:
def sp_queries(request, sp_id):
    value = request.GET.get('rangeVal', None)

Alternative solution:
Use request.session. For example:
if request.method == 'POST':
    value= request.POST["rangeVal"]
    form = forms.SprayKeywordsForm(request.POST)
    request.session['rangeVal'] = value
    return HttpResponseRedirect(reverse('sp_url', args=[sp_id]))

def sp_queries(request, sp_id):
    value = request.session.pop('rangeVal', None)

For more information, please check the documentation.


text:
Q: onProviderDisabled - need gps in battery saving mode onProviderDisabled is telling me the gps is disabled. I want to be able to get the lat and lon in the wifi gps mode as well as the full gps mode.
I am using this code to start up
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
        3000,
        1, this);

It all works with the full GPS on but I need to be able to get the lat and lon in either mode.

A: You can request updates from more than one provider. Add the following line:
locationManager.requestLocationUpdates(LocationManager. NETWORK_PROVIDER, 3000, 1, this);

The same callback methods, i.e. onLocationChanged(), onProviderDisabled(), etc.,  will be used to pass the updates from both providers. If you need to know which provider is passing the update, you can use the Location.getProvider() method in onLocationChanged(), and the String provider parameter passed in the others.


text:
Q: Calculated column in mySQL based on another column after a calculation Found a few similar links but can't apply it to my own work.
I'm working on a mySQL game rental database and I'm trying to get the column of late fees to calculate - I tried to create a function but couldn't get it quite right.
I have a game table (Game) which includes the overdue per day charge. I have a rental table (Rental) which has the due return date and the actual return date.
I want to create a function (or a view- whichever is more suitable) to calculate the overdue fee based off these dates.
For example
Game
Over_due_charge_per_day 3.00
Rental
Due_return_date 01-12-16
Actual_return_date Null
over_due_charge ?
When actual return date is > due_return_date I need to calculate the over_due_charge_per_day.
Any tips?
Thanks

A: Try to join both tables and then use this logic:
Update Game
set latefees=(Case when return_date > due_return_date then (return_date-due_return_date)*3 else 0 end)


text:
Q: C++ static variable produces a fatal error LNK1120: 1 unresolved externals in Visual Studio I am new to C++ and I am trying to learn the different uses of static keyword, I read that one of them is to define a static variable inside a class and call it using the scope operator. I tried to used that but Visual Studio 2012 produce an linking error. My code is:
class Vehicle
{
public:
    Vehicle(){};
    ~Vehicle(){};
    static int temp;
};

int _tmain(int argc, _TCHAR* argv[])
{

    Vehicle::temp=100;

    std::cout << Vehicle::temp << std::endl;

    system("Pause");
    return 0;
}

And the error is:
1>LearningC++.obj : error LNK2001: unresolved external symbol "public: static int        Vehicle::temp" (?temp@Vehicle@@2HA)
1>c:\users\avraam\documents\visual studio 2012\Projects\LearningC++\Debug\LearningC++.exe : fatal error LNK1120: 1 unresolved externals
What may cause this problem?
Edit1 (to make it more clear):
My question is how can I access a static variable declared inside a class? Is this possible without using a member function?

A: You need to define temp, add this after class Vechicle:
class Vehicle
{
// Left out class code for brevity
   void useTemp() { temp = 200 ; } // Adding method inside class the uses temp
};

int Vehicle::temp = 0 ;

Note, you do not need static keyword when you define temp. Since it is static you do not need an instance of the class to access the variable, so the code you had in main is correct:
Vehicle::temp=100;

std::cout << Vehicle::temp << std::endl;

Vehicle v1 ;
v1.useTemp() ;

std::cout << Vehicle::temp << std::endl;

A: You need to define the static member outside the class:
#include <iostream>

class Vehicle
{
  public:
     Vehicle(){};
    ~Vehicle(){};
    static int temp;
};

int Vehicle::temp = 0;

int _tmain(int argc, TCHAR* argv[])
{
    Vehicle::temp = 100;  //^^access the variable with classname plus ::
    std::cout << Vehicle::temp << std::endl;
    std::cin.get();
    return 0;
}

then access it in main with classname followed by :: and variable name.


text:
Q: Extra folder name being added to images / links when retrieving content from Joomla Article table I am creating an external application which retrieves certain article content from Joomla 2.5 tables.
My external application is in a folder named appln. I have a file named article.php. In this file I have retrieved certain articles from Joomla 2.5. I can successfully retrieve the article content and display in my file.
But this issue is the article containing any PDF and Images links, on click of this links the page is displayed as a 404 page not found...
NOTE: The PDF and images files do exits.
The reason is because the path to the images is as follow:

http://www.websitename.com/appln/image1.jpg

The page should be:

http://www.websitename.com/image1.jpg

I am unable to figure out why it is adding /appln/ before the name of the image or pdf file.

A: Look in the plugin code for something like:
$document->setBase(...)

A: Because the images are inserted relative like this:
<img src="image1.jpg">

You could probably fix it by adding this to the <head> area:
<base href="http://www.yoursite.com/" />


text:
Q: Javascript picture quiz Images failing to load resource 404 error I am building a simple javascript picture quiz for a project. I have only written the function for show question and possible answers but for some reason when i call the quiz the images aren't loading and i am getting an error re failing to load the resource. The img files work perfectly fine otherwise and i have tried both .png & .jpg and both display the same error.
I have a few elements to add in to the JS like checkAnswer and Display score but i need the images to work as they are the answer buttons.
Corresponding HTML

Question

Javascript two sample questions and answers & function;
let spQuiz = [
    {
        question: "What planet is closest to the Sun?",
        answers: [
            "../img/venus.png",
            "../img/mercury.png",
            "../img/mars.png",
            "../img/earth.png"
        ],
        correctAnswer: '1'
    },
    {
        question: "Which planet has the highest mountain in our solar system, a volcano named Olympus Mons?",
        answers: [
            "../img/mars.png",
            "../img/jupiter.png",
            "../img/neptune.png",
            "../img/earth.png"
        ],
        correctAnswer: '0'
    },
];

let newQuestion = 0;
function displayQuestion () {
    let question = spQuiz[newQuestion];
    document.getElementById("question-text").innerHTML = question.question;
    let answers = question.answers;
    for (let i = 0; i < answers.length; i++) {
        let answer = answers[i];
        let img = document.createElement("img");
        img.src = answers;
        img.onclick = function() {
            checkAnswer(i);
        };
        document.getElementById("answer-btns").appendChild(img);
    }
}

displayQuestion();


text:
Q: How to create sound notes in Delphi? Is there a command that we can make our Delphi application to emule sound where we can choose the numeric tone and duration just like in basic?

A: To produce a pure sine tone, you can use
Windows.Beep(400, 1000)

which will sound a 400 Hz pure sine tone for a duration of 1000 milliseconds.
If you want to play a real instrument (piano, guitar, or any of the 125 (?) other options), you can use MIDI. Simply use the MMSystem unit and do
var
  mo: HMIDIOUT;

const
  MIDI_NOTE_ON = $90;
  MIDI_NOTE_OFF = $80;
  MIDI_CHANGE_INSTRUMENT = $C0;

function MIDIEncodeMessage(Msg, Param1, Param2: byte): integer;
begin
  result := Msg + (Param1 shl 8) + (Param2 shl 16);
end;

procedure NoteOn(NewNote, NewIntensity: byte);
begin
  midiOutShortMsg(mo, MIDIEncodeMessage(MIDI_NOTE_ON, NewNote, NewIntensity));
end;

procedure NoteOff(NewNote, NewIntensity: byte);
begin
  midiOutShortMsg(mo, MIDIEncodeMessage(MIDI_NOTE_OFF, NewNote, NewIntensity));
end;

procedure SetInstrument(NewInstrument: byte);
begin
  midiOutShortMsg(mo, MIDIEncodeMessage(MIDI_CHANGE_INSTRUMENT, NewInstrument, 0));
end;

procedure InitMIDI;
begin
  midiOutOpen(@mo, 0, 0, 0, CALLBACK_NULL);
  midiOutShortMsg(mo, MIDIEncodeMessage(MIDI_CHANGE_INSTRUMENT, 0, 0));
end;

After you have initialised the MIDI system, you can try
NoteOn(50, 127);
Sleep(500);
SetInstrument(60);
NoteOn(60, 127);
Sleep(500);
NoteOff(60, 127);
SetInstrument(80);
NoteOn(70, 127);
Sleep(500);
NoteOff(70, 127);
SetInstrument(90);
NoteOn(80, 127);
Sleep(500);
NoteOff(80, 127);
SetInstrument(100);
NoteOn(90, 127);
Sleep(500);
NoteOff(90, 127);
SetInstrument(12);
NoteOn(40, 127);
Sleep(1000);
NoteOff(40, 127);

MIDI programming is so underrated!
Compiled demo EXE


text:
Q: Is it correct that part of business logic stays in the controller? having a simplified class like this that regulate a quiz game:
class Game():
def __init__(self,username):
    ...
    self.username=username
    self.question_list=db.getQuestions()
    self.game_over=False

def get_question(self):
    ...
    if self.question_list.is_not_empty():
        return question

def check_answer(answer)
    ...
    if answer.is_correct():
        self.game_over=False
    else:
        self.game_over=True

and having a web controller that receive input parameters like username, questions and answers..is it correct to use Game class directly from controller?
I ask this question because looking at controller code, i feel guilty to have coded inside some logic too; for example controller instantiates Game just when username is received and then calls get_question and check_answer in order.
Do you think is more correct to have another "layer" that receives input parameters from controller and talk directly to Game class?

A: I think you're good.
The thing is you can't have a perfect architecture with complete isolation of layers and data formats only visible on one side of the boundary. It's inevitable some layer will have to talk to the other.
It's okay to call get_question and check_answer if you're doing a very basic logic to decide in controller how to proceed next. If it's a matter of a few checks that will lead to a few possible controller decisions, then do it.
But if you wanted, say, to collect data from the user, convert it to some specific format, validate it, then maybe call business methods that could yield dozens of possible outcomes, and all that directly in the controller, it would have been too much clearly.

A: I would definitely keep as much as possible out of the controller. Otherwise your controller bloat will be ridiculous.


text:
Q: How to remote trigger parameterized jenkins jobs with R code? How can I remotely trigger a Jenkins job with the help of an R code?
When I post this URL in my browser it works-
https://JENKINSURL/job/PROJECT/buildWithParameters?token=TOKEN&day=20171001

Not sure how to replicate this with my R code. I used the POST function in HTTR call but I always get an HTTP 403 error.
res <- POST("https://JENKINSURL/job/PROJECT/buildWithParameters?token=TOKEN&day=20171001",verbose())

Authentication required

Permission you need to have (but didn't): hudson.model.Hudson.Read
 ... which is implied by: hudson.security.Permission.GenericRead
...
Any thoughts on what I may be doing wrong?

A: You aren't specifying a user ID in your request, so it is going to be using the anonymous user. Your anonymous user has to have read access to the job (or job->read in global perms) you are trying to trigger, or it won't be authorized to access the job/PROJECT uri to trigger the build.
So you have to either specify a user ID with the proper read access in the url, give the anonymous user read access, use project-based matrix auth, or you can use the Build Token Root plugin to provide a different URL that doesn't require read access to the job. Then you only need the token.


text:
Q: Indexing Ops in TF Is there a way to index an operation in tensorflow? In particular, I'm interested in indexing by the iterator variable of tf.while_loop.
More concretely, let's say I have my_ops = [op1, op2]. I would like to have:
my_ops = [...]
i = tf.constant(0)
c = lambda i: tf.less(i, 10)
b = lambda i: my_ops[i](...)
r = tf.while_loop(c, b, [i])

which unfortunately will not work, since a python array supports only integer indexing.

A: I believe this is not possible. However, you could instead use tf.stack to stack the operations' output tensors, and then use tf.gather to obtain the desired output.
Here you have an example:
import tensorflow as tf

def condition(i, x):
    return tf.less(i, 10)

def body_1(my_ops):
    def b(i, x):
        stacked_results = tf.stack([op(x) for op in my_ops])
        gather_idx = tf.mod(i, 2)
        return [i + 1, tf.gather(stacked_results, gather_idx)]

    return b

def body_2(my_ops):
    def b(i, x):
        nb_ops = len(my_ops)
        pred_fn_pairs = [(tf.equal(tf.mod(i, nb_ops), 0), lambda: my_ops[0](x)),
                         (tf.equal(tf.mod(i, nb_ops), 1), lambda: my_ops[1](x))]
        result = tf.case(pred_fn_pairs)
        return [i + 1, result]

    return b

my_ops = [lambda x: tf.Print(x + 1, [x, 1]),
          lambda x: tf.Print(x + 2, [x, 2])]
i = tf.constant(0)
x = tf.constant(0)
r = tf.while_loop(condition, body_2(my_ops), [i, x])  # See the difference with body_1

with tf.Session() as sess:
    i, x = sess.run(r)
    print(x)  # Prints 15 = 5*2 + 5*1


text:
Q: Volume of Hemisphere Puzzle Here we have 3 hemispheres.
The volumes of which are;
$$V_0 = y$$
$$V_1 = 15x$$
$$V_2 = 10x$$
Find $y$ and come up with a formula for finding $y$ with any values of $V_1$ and $V_2$.

This is my attempt at working it out but what I have at the very end looks very complicated and I wasn't expecting something like that.
$$V_0 = \left(\frac{2π}{3}\right)(r_0)^3 ∴ r_0 = \sqrt[3]{\frac{3V_0}{2\pi}}$$
$$V_1 = \left(\frac{2π}{3}\right)(r_1)^3 ∴ r_1 = \sqrt[3]{\frac{3V_1}{2\pi}}$$
$$V_2 = \left(\frac{2π}{3}\right)(r_2)^3 ∴ r_2 = \sqrt[3]{\frac{3V_2}{2\pi}}$$
Using Pythagoras' theorem we get;
       $$ (2r_0)^2 = (r_1+r_2)^2 + (r_1-r_2)^2$$
$$⇒       4(r_0)^2 = 2(r_1)^2 + 2(r_2)^2$$
$$⇒ 4\left(\sqrt[3]{\frac{3V_0}{2\pi}}\right)^2 = 2\left(\sqrt[3]{\frac{3V_1}{2\pi}}\right)^2 + 2\left(\sqrt[3]{\frac{3V_2}{2\pi}}\right)^2$$
$$⇒      \sqrt[3]{\frac{3V_0}{2\pi}} = \left({\frac{\left({\frac{3V_1}{2\pi}}\right)^{\frac{2}{3}} + \left({\frac{3V_2}{2\pi}}\right)^{\frac{2}{3}}}{2}}\right)^{\frac{1}{2}}$$
$$⇒      V_0 = \left({\frac{2\pi}{3}}\right)\left({\frac{\left({\frac{3V_1}{2\pi}}\right)^{\frac{2}{3}} + \left({\frac{3V_2}{2\pi}}\right)^{\frac{2}{3}}}{2}}\right)^{\frac{3}{2}}$$

A: You can use the given relations on $V_1$ and $V_2$ to get their respective radii. Having found the radii in terms of $x$, you need to find the length of the direct common chord between them. Draw the radii from the the centres $C_1$ and $C_2$ to the tangent $T$, note that they are perpendicular. Let them meet the tangent at $T_1$ and $T_2$ respectively. Drop a perpendicular from $C_2$ to $C_1T_1$, let them meet at $X$. Then $C_1C_2X$ is a right angled triangle, $C_2XT_1T_2$ is a rectangle. Now use pythagorus' theorem to find the length of the tangent, which is the same as the diameter of the topmost hemisphere and equate with the area.

A: $$V_0 = \left(\frac{2π}{3}\right)(r_0)^3 ∴ r_0 = \sqrt[3]{\frac{3V_0}{2\pi}}$$
$$V_1 = \left(\frac{2π}{3}\right)(r_1)^3 ∴ r_1 = \sqrt[3]{\frac{3V_1}{2\pi}}$$
$$V_2 = \left(\frac{2π}{3}\right)(r_2)^3 ∴ r_2 = \sqrt[3]{\frac{3V_2}{2\pi}}$$
Using Pythagoras' theorem we get;
$$(r_1+r_2)^2 = (2r_0)^2 + (r_1-r_2)^2$$
$$⇒(r_0)^2 = r_1r_2$$
$$⇒\left({\frac{3V_0}{2\pi}}\right)^{\frac{2}{3}} = {\frac{3V_1}{2\pi}}^{\frac{1}{3}}{\frac{3V_2}{2\pi}}^{\frac{1}{3}}$$
$$⇒\left({\frac{3V_0}{2\pi}}\right)^2 = {\frac{9V_1V_2}{4\pi^2}}$$
$$⇒V_0^2 = V_1V_2$$
Now just sub in $V_1$ and $V_2$ respectively.


text:
Q: Handle DONE buttons and video finish playing events in UIWebview I have a UIWebview which will play a YOUtube video playlist, and I need to handle the events when user click DONE button and close the webview.
So far, the working solution i found is to handle UIMoviePlayerControllerDidExitFullscreenNotification, but when UIWebview finish playing a video in the list it will exit the fullscreen mode and enter back to fullscreen mode to play the next one. My app handles the event of exiting fullscreen as pressing DONE button and only the first song of the list get played.
My question is that is there anyway to handle DONE button click events without handling UIMoviePlayerControllerDidExitFullscreenNotification, or to handle those two events separately?


text:
Q: dropping columns in multiple excel spreedsheets Is there a way in python i can drop columns in multiple excel files? i.e. i have a folder with several xlsx files. each file has about 5 columns (date, value, latitude, longitude, region). I want to drop all columns except date and value in each excel file.

A: Let's say you have a folder with multiple excel files:
from pathlib import Path

folder = Path('excel_files')

xlsx_only_files = list(folder.rglob('*.xlsx'))

def process_files(xls_file):

    #stem is a method in pathlib
    #that gets just the filename without the parent or the suffix
    filename = xls_file.stem

    #sheet = None ensure the data is read in as a dictionary
    #this sets the sheetname as the key
    #usecols allows you to read in only the relevant columns
    df = pd.read_excel(xls_file, usecols = ['date','value'] ,sheet_name = None)

    df_cleaned = [data.assign(sheetname=sheetname,
                              filename = filename)
                  for sheetname, data in df.items()
                 ]

    return df_cleaned

combo = [process_files(xlsx) for xlsx in xlsx_only_files]

final = pd.concat(combo, ignore_index = True)

Let me know how it goes
stem

A: I suggest you should define columns you want to keep as a list and then select as a new dataframe.
# after open excel file as

df = pd.read_excel(...)

keep_cols = ['date', 'value']
df = df[keep_cols] # keep only selected columns it will return df as dataframe

df.to_excel(...)


text:
Q: How can I use jQuery in html to display the drop down menu correctly hi I am new to jQuery and I am trying to implement it to an HTML code but it doesn't work
it works here https://jsfiddle.net/6trb0whz/
but it doesn't work here
can someone help me solve this, please
    <!DOCTYPE html>

   <input type="radio" name="test" value="Orange" /> Burger Garage
   <input type="radio" name="test" value="Burger" /> Hardee's
    <input type="radio" name="test" checked="checked" value="Apple" /> Burger Factory & More

    <select ID="DropDownList2" Height="18px" Width="187px">
        <option Value="Apple_Style_1">Turbo Chicken</option>
        <option Value="Apple_Style_2">Twin Turbo Chicken</option>
        <option Value="Apple_Style_3">Garage Burger</option>
        <option Value="Burger_Style_1">Chicken Fille</option>
        <option Value="Burger_Style_2">Grilled Chicken Fillet</option>
        <option Value="Burger_Style_3">Jalapeno Chicken</option>
        <option Value="Orange_Style_1">Original Burger</option>
        <option Value="Orange_Style_2">Twin Turbo Chicken</option>
        <option Value="Orange_Style_3">Shuwa Burger</option>
    </select>

UPDATE
It works now for one time then disappears after clicking on the third radio button
you can try it in here https://jsfiddle.net/ujvr082w/
This is the code
<!DOCTYPE html>

   <input type="radio" name="test" value="Orange" /> Burger Garage
   <input type="radio" name="test" value="Burger" /> Hardee's
    <input type="radio" name="test" checked="checked" value="Apple" /> Burger Factory & More

    <select ID="DropDownList2" Height="18px" Width="187px">
        <option Value="Apple_Style_1">Turbo Chicken</option>
        <option Value="Apple_Style_2">Twin Turbo Chicken</option>
        <option Value="Apple_Style_3">Garage Burger</option>
        <option Value="Burger_Style_1">Chicken Fille</option>
        <option Value="Burger_Style_2">Grilled Chicken Fillet</option>
        <option Value="Burger_Style_3">Jalapeno Chicken</option>
        <option Value="Orange_Style_1">Original Burger</option>
        <option Value="Orange_Style_2">Twin Turbo Chicken</option>
        <option Value="Orange_Style_3">Shuwa Burger</option>
    </select>

A:

<!DOCTYPE html>

  <input type="radio" name="test" value="Orange" /> Burger Garage
   <input type="radio" name="test" value="Burger" /> Hardee's
   <input type="radio" name="test" checked="checked" value="Apple" /> Burger Factory & More

    <select ID="DropDownList2" Height="18px" Width="187px">
        <option Value="Apple_Style_1">Turbo Chicken</option>
        <option Value="Apple_Style_2">Twin Turbo Chicken</option>
        <option Value="Apple_Style_3">Garage Burger</option>
        <option Value="Burger_Style_1">Chicken Fille</option>
        <option Value="Burger_Style_2">Grilled Chicken Fillet</option>
        <option Value="Burger_Style_3">Jalapeno Chicken</option>
        <option Value="Orange_Style_1">Original Burger</option>
        <option Value="Orange_Style_2">Twin Turbo Chicken</option>
        <option Value="Orange_Style_3">Shuwa Burger</option>
    </select>

You can put your script after creationg your html.
If you put before html in dropdown menu It take all value in dropdown menu.


text:
Q: Running multiple Python scripts in parallel using bash I want to run a simple python script 100 times in parallel using bash. If I run the python scrips serial everthing is fine, but if I run them in parallel I get the error
stdin is not a tty
Presumably because the same python file gets opened multiple times?
Here's the bash file
#!/bin/bash

for i in {1..5}; do
        winpty python test.py &
done

If I remove the & sign everything works fine (serial) but not if I run it in parallel. The Python file is litterally just  1+1
PS: I run python with  winpty python and not the usual python because I run it from the git-bash console and that thing has issues... But again, I don't think this is where the issue comes from, because running everything in serial works fine...

A: I don't have winpty to test following script, but try :
#!/bin/bash

for i in {1..5}; do
        winpty python test.py < /dev/tty > /dev/tty 2>&1 &
done


text:
Q: Django restframework serializer with joining tables I'm creating a django API for a discord bot for sounds recorded management.
Here are my models (simplified) :
class Member(models.Model):
    name = models.CharField("Discord Name", max_length=100, unique=True)
    discord_id = models.BigIntegerField("Discord ID", unique=True, blank=True, null=True)

class Sound(models.Model):
    id = models.AutoField("Sound ID", primary_key=True)
    file = models.FileField("Sound", upload_to='sounds/')
    added_by = models.ForeignKey(Member, verbose_name="Author", on_delete=models.SET_NULL, blank=True, null=True)

    tags = TaggableManager("Tags", blank=True)

class MemberinSound(models.Model):
    sound = models.ForeignKey(Sound, on_delete=models.CASCADE, related_name="membersinsound")
    personality = models.ForeignKey(Member, related_name='membersinsound', on_delete=models.CASCADE)

Explanations : a sound is uploaded by any member (added_by), with multiples optional tags, and personality that appears in this sound (MemberinSound).
You can imagine this 3 tables like (player, match, and playersinmatch).
My view to get a specific sound is :
class SpecificSound(APIView):

    def get(self, request, id: int, formate=None, **kwargs):
        sound = Sound.objects.select_related().get(id=id)
        membersinsound = sound.membersinsound.all()
        serializer = SoundSerializer(sound, many=False)
        return Response(serializer.data)

And serializers.py :
class MemberInSoundSerializer(serializers.ModelSerializer):
    class Meta:
        model = MemberinSound
        fields = [
            'personality'
        ]

class SoundSerializer(serializers.ModelSerializer):

    personality = MemberInSoundSerializer(many=True, read_only=True)
    class Meta:

            model = Sound
            fields = [
                'id',
                'title',
                'volume',
                'file',
                'stream_friendly',
                'is_active',
                'personality',

            ]

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation['path'] = instance.file.path
        return representation

First problem I got is in my view where I send to my serializer only Sound model (without MemberinSound), I don't find how to get this in a one shot query. Maybe using annotate options ? Thought it could be possible with something like backward relationships shown in the documentation.
First time I use the restframework, maybe I made others mistakes.
For infos, I'm using Django 4.0.3 ; djangorestframework 3.13.1 and Python 3.8 with SQLITE3.


text:
Q: Jquery Conflict issue for slider tab not working for second tab I am using Jquery carousel tab slider for my project. But i am getting some issue, that is when I click on the Featured products the slider goes down and stops working.
Please see link for your reference
Also see the js fiddle for the html jsfiddle
See the JScode:-
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>

 <script type="text/javascript">
    addOnload(function () {
        BIGB.utils.runOnload();
    });
    addWindowOnload(function () {
        BIGB.utils.runWindowOnload();
    });
    require_module.init({ "carousel": { "url": "slider/carousel-e1e730d.js" } });
</script>
<script type="text/javascript">

    require_module.js("carousel", function () {
        $(".require-nav-carousel").each(function () {
            var $this = $(this);
            var params = {
                content: $('.ccarousel', $this),
                buttonOverlap: true,
                sliderOverlap: true
            };
            var parsed_params = $this.data();
            $.extend(params, parsed_params);
            var navCarousel = new BIGB.ui.Carousel(params);
            navCarousel.init();
            $this.removeClass("require-nav-carousel");
        });
    });
    BIGB.linkTracking.setContext("hp");
    $('.bannerHolder').each(function () {
        $(this).mouseenter(function () {
            $(this).addClass('hoverIn').removeClass('hoverOut').removeClass('noTransition');
        }).mouseleave(function () {
            $(this).addClass('hoverOut').removeClass('hoverIn').addClass('noTransition');
        });
    });
    (function () {
        var $window = $(window);
        $window.bind('scroll', _.throttle(enableChristmasSaleUnit, 200));
        $window.bind('resize', _.throttle(enableChristmasSaleUnit, 200));
        var $saleUnit = $('.sticky-unit');
        function enableChristmasSaleUnit() {
            requestAnimFrame(function () {
                var st = $window.scrollTop();
                if (st > 200) {
                    !$saleUnit.hasClass("sticky-unit-active") && $saleUnit.addClass("sticky-unit-active");
                } else {
                    $saleUnit.hasClass("sticky-unit-active") && $saleUnit.removeClass("sticky-unit-active");
                }
            });
        }
    })();

</script>

See below the Image for error

A: If you want to use multiple version of jQuery ,try the following solution mate.. :)
<!-- load jQuery 2.2.1 -->
<script type="text/javascript" src="jquery-2.2.1.js"></script>
<script type="text/javascript">
var jQuery221 = $.noConflict(true);
</script>

<!-- load jQuery 1.10 -->
<script type="text/javascript" src="jquery-1.10.js"></script>
<script type="text/javascript">
var jQuery110 = $.noConflict(true);
</script>

Then use the desired plugin with the desired jQuery version..


text:
Q: How to identify spamming script I know this is an age-old question but I've not found a satisfactory answer on how to identify a spamming script on postfix.
I know I've to look at the mail logs for postfix, get the message ID and examine the header content which I've done. I don't seem to see "X-PHP-Originating-Script" line to locate the exact script. Instead I have the line X-mailer: Mailer v1.0. Is there any other way I can locate a script that's sending out emails from my local machine?
Below is the message ID
*** MESSAGE CONTENTS deferred/1/17A30ED943C ***
Received: from somedomain.com (localhost [127.0.0.1])
    by mymail-server.com (Postfix) with ESMTP id 17A30ED943C
    for <someuser@aol.com>; Mon, 18 Jul 2016 12:45:54 +0300 (EAT)
Date: Mon, 18 Jul 2016 09:45:54 +0000 (UTC)
From: jms <info@somedomain.com>
To: someuser@aol.com
Message-ID: <1698090211.3510965.1468835154806@somedomain.com>
Subject: FW:  Hi nolaspud
MIME-Version: 1.0
Content-Type: multipart/alternative;
    boundary="----=_Part_3510964_1152532126.1468835154806"
X-mailer: Mailer v1.0

A: would be faster enable the X-PHP-Originating-Script header by allowing it in php.ini file by option mail.add_x_header = On.
Then just check new email in mailq.

A: If you have a machine that is compromised, the first step is to disconnect it from network. Then you can replace with a new secured one.
I know this is not answer you expect, but it could be very complicate to cleanup a compromised machine. The way you ask this question shows your lack of experience in dealing with security issues and the best answer is to replace the machine with a clean and secure one.
If you want to see which process was sending the email, check for running processes, check crontab and at. Check loaded modules, check if the machine has the network cards in promiscuous mode. Use netstat -anp | grep :25 to see which processes are connecting to SMTP. You can use Rootkit Hunter to search for the attack traces.


text:
Q: RasberriPi 4, trying to stream Camera throuth UDP Socket - OSError: [Errno 99] Cannot assign requested address (Python, Kivy + Socket) So basicly I just need stream from server (RasberiPi4) to my client (Android phone). My friend can run this code and its working on his Pi (Server) - Linux (Client). I have been struggling to fix this error.
So this is USB DEBUG -
https://paste.pythondiscord.com/sijojirobo
This is code for Server
https://paste.pythondiscord.com/izohamodos
This is Client
https://paste.pythondiscord.com/maquqesojo
So when I launch Kivy app this errors shows up, so something is not right but I tried many things.
I am using RaspAP which creates hotspot on which I connect with client and cant connect on UDP Server. Can someone please help me?


text:
Q: Mac OS X ignoring hosts file Mac seems to be ignoring new changes to my hosts file. Older changes work without a problem. I've spent the past 4 hours trying to figure this one out. Help!
I have folders for each site that I develop in my /Sites folder. For example, several folders are named:
wp.dev
daf.dev
test.dev

I run MAMP, set the Apache Port to 80 and the MySQL Port to 3306 (so that I don't have to add the port to the address bar in a browser).
I have edited my /private/etc/hosts file as follows:
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1   localhost
255.255.255.255 broadcasthost
::1             localhost

127.0.0.1   wp.dev
127.0.0.1   daf.dev
127.0.0.1   test.dev
fe80::1%lo0 localhost

Here's the kicker: wp.dev and daf.dev have been around for over a month. They resolve without a problem in my browser. I added test.dev this morning. When I type it into a browser it simply searches "test.dev" as opposed to resolving a domain.
I can ping any of the above domains and they go to 127.0.0.1, including test.dev.
For what it's worth, I've tried virtualhostsx with the same problem. I also run dscacheutil --flushcache and restart MAMP when making changes.
I need to kick off development on a new site, and this is driving me crazy.

A: Try putting all your entries at the top of the file.
Not really logical, but worth a try.


text:
Q: Непонятки с преобразованием типов - пример из книги Лафоре C++ В книги Лафоре С++, приводится странный пример преобразования типов.
Насколько я знаю.. если мы кастуем int к float, то выделяется память для float и 7 преобразуется в 7.0.
В книги почему-то 7 преобразуется к 7.5. Это ошибка? Или старые версии компиляторов так делали?
Кто знает ответ - помогите пожалуйста разобраться.

A: В оригинале книги иллюстрация выглядит так:

Дело в том, что при переводе на русский бывает по-разному. Бывает, что пару сотен ошибок добавлено, если книга горит, и дали кому-то бегом, чтоб поскорее выпустить (например, первое издание "Программирование. Принципы и практика с использованием С++" Страуструпа)... Бывает и наоборот - пара сотен ошибок в русском издании исправлено (например, "Компиляторы" Ахо, Лам, Сети и Ульмана).
Все очень сильно зависит от того, кто книгу делал. Так что как совет - смотреть не только (а часто и не столько) на автора переводной книги, сколько на то, кто именно книгу делал...


text:
Q: Master not found after building nopcommerce plugin I have builded this payment plugin for Nopcommerce 3.70
https://github.com/ePay/nopcommerce
to make it available for Nopcommerce v. 3.70. Building and installation was successful but when I try to configure the module inside nopcommerce I get this error:

The view 'Nop.Plugin.Payments.ePay.Views.PaymentePay.Configure' or its
  master was not found or no view engine supports the searched
  locations. The following locations were searched:
~/Themes/PowerHub/Views/PaymentePay/Nop.Plugin.Payments.ePay.Views.PaymentePay.Configure.cshtml
  ~/Themes/PowerHub/Views/Shared/Nop.Plugin.Payments.ePay.Views.PaymentePay.Configure.cshtml
  ~/Views/PaymentePay/Nop.Plugin.Payments.ePay.Views.PaymentePay.Configure.cshtml
  ~/Views/Shared/Nop.Plugin.Payments.ePay.Views.PaymentePay.Configure.cshtml
  ~/Administration/Views/PaymentePay/Nop.Plugin.Payments.ePay.Views.PaymentePay.Configure.cshtml
  ~/Administration/Views/Shared/Nop.Plugin.Payments.ePay.Views.PaymentePay.Configure.cshtml

The only thing I have changed in the source is in the "Description.txt"

SupportedVersions: 3.60 -> SupportedVersions: 3.70

Build Action is set to Embeded Resource

A: For versions 2.00-3.30 the views (.cshtml files) should be marked as an embedded resource. And starting version 3.40, ensure that the "Build Action" property of the view file is set to "Content", and the "Copy to Output Directory" property is set to "Copy if newer".


text:
Q: How to find the version of Jetty used in Restlet framework version 2.1? Need to know the version of Jetty that an application based on Restlet framework uses. All I know is that the version of Restlet framework used is 2.1 from the pom.xml file in the project.

A: use the "--version" flag:

java -jar start.jar --version

A: If you add -X to the build command line it should show the way maven resolves dependencies, giving you a full dependency chain including what version of jetty would be getting pulled in.
Some of the tooling for various IDE's will give you this information as well, if you open the pom.xml in Eclipse with the m2eclipse tooling you should see a pretty graph with this info.


text:
Q: Is there a way to supply a boolean statement in the isActive parameter within NavigationLink in SwiftUI? I'm trying to get a NavigationLink to trigger when a string is no longer nil. Is there anyway to do this or something similar?
NavigationLink(destination: MainView(), isActive: $settings.isLoggedS !=nil)

Any help is greatly appreciated!

A: You can program the link.
          @State var activeString : String = ""
          var body: some View {
            NavigationView{
                NavigationLink(destination: Text(""), isActive: Binding<Bool>(get: {self.activeString != ""}, set: { _ in
                }) ){
                    TextField("input", text: $activeString)}}}


text:
Q: How to prevent profile pages from revealing when I was last online on steam? I always start my steam with "Automatically sign into Friends when I start Steam" disabled.
It seems to work — people can't see if I'm online. But when I check the profiles of my steam buddies, there I can find myself and the time when I was "Online last time".
There the last time is always set to the time when I logged into my account. I don't like it — how to disable this?

A: Make your Profile Private so that they can't access to your Profile. If you do so, they won't be able to see when you were online, but on the downside, they can't see anything.

A: To get around this, I created another Steam account, and added it as a "family" account so I could share the game library of my regular account.
When I want to be anonymous, I log into the new account. If I want to be available for my friends etc, I log into the original account.

A: This is not possible to change.

A: If you press firends, and then on the arrow next to yourself you can press offline. Then you will appear to be offline for all players. But if you want to make sure no one can find out anything, press Steam in the left upper corner and then go offline!


text:
Q: TypeError: Cannot read property '_id' of undefined angular7 I have a component employee
I am trying to create a form, for which I have created "employee component", "employee service" and "employee model"
In employee.component.html I have below form
 <form #employeeform="ngForm" (ngSubmit)="onSubmit(employeeform)">
          <input type="hidden" name="_id"  [(ngModel)]="employeeservice.selectedEmployee._id" #_id="ngModel"/>
        </form>

In employee.component.ts I have below code
 import { Component, OnInit } from '@angular/core';
 import { EmployeeService } from '../shared/employee.service';

 @Component({
    selector: 'app-employee',
    templateUrl: './employee.component.html',
    styleUrls: ['./employee.component.css'],
    providers : [EmployeeService]
 });

 export class EmployeeComponent implements OnInit {
    constructor(private employeeservice : EmployeeService) { }
      ngOnInit() {
      }
   }

This is my employee.service.ts file which I have imported in employee component
 import { Injectable } from '@angular/core';
 import { HttpClient } from '@angular/common/http';
 import { Observable } from 'rxjs';
 import { Employee } from './employee.model';

 @Injectable({
   providedIn: 'root'
 })
 export class EmployeeService {
   selectedEmployee : Employee;
   employees: Employee[];

   constructor() { }
 }

Here is my employee.model.ts which I have imported in employee service
 export class Employee {
     _id: string;
     name: string;
     position : string;
     office : string;
     salary : number;
 }

I am getting the below error in my browser console when I run the command "ng serve"
 EmployeeComponent.html:9 ERROR TypeError: Cannot read property '_id' of undefined
at Object.eval [as updateDirectives] (EmployeeComponent.html:9)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:23911)
at checkAndUpdateView (core.js:23307)
at callViewAction (core.js:23548)
at execComponentViewsAction (core.js:23490)
at checkAndUpdateView (core.js:23313)
at callViewAction (core.js:23548)
at execComponentViewsAction (core.js:23490)
at checkAndUpdateView (core.js:23313)

Am I missing any imports that a form needs or what could be the error. I am a beginner and trying to learn angular. I have googled for the solution, but I couldn't find any relevant solution. Please help me out

A: I would recommend you to create an instance of the employee inside of the EmployeeComponent , and every time when you open the component - retrieve it from the service and target it at the html code. Something like:
export class EmployeeComponent implements OnInit {
    employee: Employee;

    constructor(private employeeservice : EmployeeService) {
      this.employee = employeeservice.getSelectedEmployee();
    }
      ngOnInit() {
      }
   }

and later at the html:
 <form #employeeform="ngForm" (ngSubmit)="onSubmit(employeeform)">
          <input type="hidden" name="_id"  [(ngModel)]="employee._id" #_id="ngModel"/>
        </form>

Or pass it again with Injection.
At the moment, the problem is that your EmployeeComponent can't target like you want (passing from html to the service variable), so you are getting - Undefined error.

A: Initially, when the component is loaded, the employee.service has no value set for selectedEmployee. The html is rendered and the [(ngModel)]="employeeservice.selectedEmployee._id" expects a value of employeeservice.selectedEmployee._id. But employeeservice.selectedEmployee is not initialized yet, hence the error.
I would suggest you to use a default _id in case you haven't set the employeeservice.selectedEmployee._id.
For that use [(ngModel)]="employeeservice.selectedEmployee ?  employeeservice.selectedEmployee._id : 0"

A: It is as the error says: you want to access the _id but the selectedEmployee is never actually defined.
You can either only display the element when it has been defined using *ngIf on your html element or give it a default value like so selectedEmployee : Employee = {} (setting any variable needed from the class accordingly)

A: Your employee.service.ts file should be like this.
 import { Injectable } from '@angular/core';
 import { HttpClient } from '@angular/common/http';
 import { Observable } from 'rxjs';
 import { Employee } from './employee.model';

 @Injectable({
   providedIn: 'root'
 })
 export class EmployeeService {
     selectedEmployee: Employee = {
    _id: '',
    name: '',
    position: '',
    office: '',
    salary: null
  };
   employees: Employee[];

   constructor() { }
 }


text:
Q: How to make a image clickable in Advanced PDF/HTLM Templates I want to add an image and make that image clickable and redirect to a link.
So my customer can pay me online.
But when I add the image and add the link. The image is not clickable.
I try to use the code source, making it a button but didn't work.
Can you help me?
Here is the code I'm using:

Thank you!

A: Try this:
HTML


text:
Q: 404 error after putting WordPress on my vps server but homepage does work So my WordPress site worked perfectly on my localhost, until I transferred it to my Windows Server machine. Now, only the index still works; the other pages give me a 404 error.
I have already tried changing permalink options and other fixes, but nothing has worked.
How I can get my other pages online?

A: Its too easy

*

*go to wp-admin in your WordPress.

*in dashboard go to settings.

*in settings go to Permalink Settings.

*in Permalink Settings if your Common Settings set on Day and name or anything else change it to Plain.

*save the setting and go to your web pages.

*if every things work correctly back to Permalink Settings and change Common Settings on Day and name or anything you want.


text:
Q: Xcode change global variable for each target I have a series of targets, and each one looks at a global variable I am currently storing in a constants file for the name of the directory in which that app's resources live. However, this means that I have to change this value each time i change the target, which is a terrible process.
What is the best way to change that value in each target?  Or should i specify this value somewhere in my target plist ? If so how do i retrieve that value?
Thanks!

A: With your project open in Xcode, look in the Groups & Files panel for your Target. Right click to bring up your popup menu. Select Get Info. Select the build tab. Scroll down to the "Preprocessor Macros" and add something like "MY_OPTION_1". Do something similar for your other targets. Say "MY_OPTION_2", "MY_OPTION_3", etc.
Now, in your code you can do a define test. Like
#ifdef MY_OPTION_1
   // define values here
#endif

#ifdef MY_OPTION_2
   // define values here
#endif

#ifdef MY_OPTION_3
   // define values here
#endif

Then, depending on what target you use, the values within the corresponding defines are used.

A: Go to your target properties by double clicking the target and find Preprocessor Macros. Add a constant, such as FILE_PATH="/some/place/green/" and then when you want to use it, just
fopen(FILE_PATH... or whatever function/method you want to perform on FILE_PATH
do the definition part for each target.


text:
Q: Enable direction in Google Maps SDK in iOS When I click on GMSMarker, I want to enable direction and map like below image. Its working fine in android.

A: Have you checked this Maps SDK for iOS documentation? You can use the Google Directions API to request directions, and then use the encoded path returned from the service to draw a GMSPolyline using GMSPath's pathFromEncodedPath: method.
Here's a related SO thread: Google Maps iOS SDK, Getting Directions between 2 locations. This blog tutorial might also help.


text:
Q: how to do a condition in map operator es6 I need to check a condition in map function, to prepend zeros for single digit values which means 00.00 to 09.30 remaining values be same.
currently it is prepending for all the values.
code:
export class SelectOverviewExample implements OnInit {
  days=[];
  times =[];

ngOnInit(){
  [...this.days] = weekdays;
  // [...this.times]=IntervalTime;
  this.OnCall();
}

OnCall(){
var toInt  = time => ((h,m) => h*2 + m/30)(...time.split(':').map(parseFloat)),
    toTime = int => [Math.floor(int/2), int%2 ? '30' : '00'].join(':'),
    range  = (from, to) => Array(to-from+1).fill().map((_,i) => from + i),
    eachHalfHour = (t1, t2) => range(...[t1, t2].map(toInt)).map(toTime);
let x=[];

[...x]= eachHalfHour('0:00','15:30');

[...this.times]=x.map(i=>'0'+i);
;}

}

demo:enter link description here

A: [...this.times]=x.map(i=>{
    if ( condition ) {
        i = '0'+i;
    }

    return i;
});

Thanks Alexander Staroselsky, I made a typo.