text:
Q: scala pattern matching on object type and method accepting argument of many types I want to execute method which accepts some object as an argument. There can be many different objects I can pass. There objects have different types (instances of various classes) but they all have common methods (methodA, methodB). So, I have problem with defining Types and this is what I do at the moment as an example. Anybody can help to fix it?
sealed trait Foo
final case class A(a: SomeClass1Type) extends Foo
final case class B(b: SomeClass2Type) extends Foo

object SomeObject {
  implicit val executionContext: ExecutionContext = ExecutionContext.Implicits.global

  val caseMatcher = new SomeClass1
  //  val caseMatcher = new SomeClass2

  execute(caseMatcher)

  def execute(caseMatcher: Either[SomeClass1Type, SomeClass2Type]) = {
    caseMatcher match {
      case a: A(SomeClass1) => executeCase1(new SomeClass1)
      case b: B(SomeClass2) => executeCase2(new SomeClass2)
    }
  }

  def executeCase1(param: SomeClass1Type) {
    val a = param.methodA
    val b = param.methodB
  }

  def executeCase2(caseMatcher: SomeClass2Type) {
    val a = param.methodA
    val b = param.methodB
  }
}

A: It seems you need the structural-types:
def main(args: Array[String]): Unit = {
    val c1 = SomeClass1(1)
    val c2 = SomeClass1(2)

    val result1 = process(c1) // 5
    val result2 = process(c2) // 8
  }

  def process[T <: {def multiply: Int; def sum: Int} ](t: T): Int = t.multiply + t.sum

  case class SomeClass1(int: Int) {
    def multiply: Int = int * 2
    def sum: Int = int + 2
  }

  case class SomeClass2(int: Int) {
    def multiply: Int = int * 3
    def sum: Int = int + 3
  }

But be aware it could make great performance degradation if will be used in the frequently called pieces of code.


text:
Q: Passing parameters to ansible callbacks I have recently been alerted to the existence of ansible callbacks, which appear to be a way to modify some of the defaults under given conditions.
However, I have scoured the ansible documentation as well as a few books, google and the source code, but for the life of me I cannot find the answer to this simple question:
How does one change the configuration items that affect the beahavior of ansible callbacks?
-E.g: the mail callback appears, looking at the code, to be able to be configured to send mail to a configurable email address through a configurable SMTP host. How/where/when should these be specified?
But, if the mail callback (and the base class for callbacks), are anything to go by, there actually appears to be NO standard configuration mechanism..
Mail, for instance,  gets SMTPHOST from an environment variable if it's there, and to: appears nailed to <root> (no good if the mailer insists on blah@fully.qualified.dom.ain as valid addresses).

A: Looking at the docs and some of the existing callback plugins, one method appears to be using the environment.
For example, the jabber callback simply uses 'more' env vars to allow more granular configuration.
This seems to be the case for a lot of the other callbacks, and I couldn't find any examples of using ansible variables for such purposes.
That, though, is presumably possible - checking the CallbackBase#_get_item method, it seems possible to go through the ansible vars to get at whatever config might be appropriate.
However, I do think using environment variables seems to be some form of standard - although I agree it isn't exactly a strongly defined standard if indeed it is one
As you say, the callbacks are a little obscure, and it may be this is one of those 'if you need it, you will know what to do' areas in ansible.
In the case of the mail callback, it may be your best bet is to just subclass the existing plugin to add the config variables you feel you might want.
I personally get the sense that callbacks are by and large considered an advanced feature, and that many of the available callbacks are more intended as a base (and in some cases, as a quick hack to get something) to be extended by those needing their functionality.
But that is purely a feeling.

A: I'm not shure if I get you correctly but I think youre right about the black boxes idear of the callbacks or also official modules,
I image the python modules like unix "commands" they can be very different and accept different options and the architecture makes it difficult for the ansible team to do big architectural changes since it would mean modifying/extending all the existing modules(such as the much demanded progress reports on running modules https://github.com/ansible/ansible/issues/3887 which means they have no way of checking if a module is stuck)
To have control of the configuration or change/persist them I choose another apporach than only writing callbacks.
I wrote a layer around ansible by using the dynamic inventory capability and I used Output callback plugins to format the output into json to be able to parse the output of a successfull run and save changes states / data back into my inventory management programm. That way I can change variables or even add hosts in the playbook with simple tasks call and automatically apply them back to my inventory without needing to modify or extend ansible a lot and stay relatively compatible to future versions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is javascript Reflect.construct newTarget doing When Im reading this,It tells me that "A new instance of the given target, created by calling it (or newTarget, if present) as a constructor with the given arguments." But in reality, it is not the case at all. Here is an example:
function Parent() {
  this.parent = "Parent"
  console.log("This is parent.")
}
function Child() {
  this.child = "Child"
  console.log("This is child.")
}
var result = Reflect.construct(Parent, [], Child);
console.log(result)

The output looks like this:

This is acting so weird to me because base on the doc, when we put Child as new target parameter in Reflect.construct, it should use constructor of Child to make a new instance, but the log shows "This is parent." is printed and property of Parent is saved while at the same time constructor is of Child(). How could this be possible? Can someone please explain what is happening behind the scene? This is driving me crazy, I really want to know how javascript does this. Thank you so much guys.

A: I'd say the documentation is somewhat misleadingly worded. What seems to be happening is that construct() invokes the first the first argument as the constructor (i.e. to initialize the object), but uses the last argument as the prototype (i.e. the actual "class" of the object). In your case, result instanceof Child returns true, but result instanceof Parent returns false.
So, the result of Reflect.construct(target, args, newTarget) seems to be equivalent to this:
var result = Object.create(newTarget.prototype);
target.apply(result, args);

However, there is one significant difference: in the above example, the new.target operator within either function will return undefined, since you're not using the new keyword to create the object. When you use Reflect.construct(), on the other hand, new.target will point to newTarget (hence the name, I suppose) -- probably because, in the end, the resulting object will belong to that class.
(Note: I have since requested an edit to the MDN page about Reflect.construct() to include these details)


text:
Q: Bootstrap carousel controls keep visible after click (supposed to get opacity 0) I have reworked Bootstrap carousel controls to get hidden if the carousel itself is not hovered. The problem is that if you click one of them (to go to a different slide) and move your mouse outside the .carousel container, the clicked control stays visible for some reason. Please find a live example below (just hover over the carousel, click one of the controls, and move your mouse to the code section to see what I mean):
http://codepen.io/Deka87/pen/bZLQRm
Carousel controls code:
.carousel-control {
    display: block;
    top: 50%; bottom: auto;
    width: 55px; height: 55px;
    line-height: 55px;
    text-align: center;
    background-color: fade(black,50%);
    background-image: none !important;
    opacity: 0;
    transition: all .15s;
    -webkit-transform: translateY(-50%);
            transform: translateY(-50%);

    > .glyphicon {
        position: static;
        width: auto; height: auto;
        margin: 0;
        font-size: @font-size-base;
    }
    &:hover {
        background-color: @brand-accent;
    }
}
.carousel:hover .carousel-control {
    opacity: 1;
}

Any ideas?
(also the right controls twitches a little when hovered, but that's another question).

A: You should also set the :focus pseudo class the  opacity: 0, because the default value there is opacity: .9;
This is the change:
.carousel-control {
    display: block;
    top: 50%; bottom: auto;
    width: 55px; height: 55px;
    line-height: 55px;
    text-align: center;
    background-color: fade(black,50%);
    background-image: none !important;
    opacity: 0;
    transition: all .15s;
    -webkit-transform: translateY(-50%);
            transform: translateY(-50%);

    > .glyphicon {
        position: static;
        width: auto; height: auto;
        margin: 0;
        font-size: 13px;
    }
    &:hover {
        background-color: green;
    }
    &:focus {
        opacity: 0;
    }
}

Here is the codepen demo.


text:
Q: CSS: Full-size divs show browser scrollbars I have a site which needs to be fully self-contained in the browser window, ie, the user must not have to scroll up and down to view different parts of the site. Content that is too long to fit into the content pane is handled with overflow:auto, which is working fine.
the problem is, no matter what I try I still have the following problem:
two sets of scrollbars http://www.wikiforall.net/bad_scrollbars.png
So beneaht the content which successfully fills the browser window, there seems to be a gap. This gap causes the vertical scrollbar to show itself (and there appears to be a similar gap on the right side which isn't as easy to see). I've inspected the elements using Chrome's element inspector and the <html> tag covers only up to that gap. So I have no idea where the gap is coming from.
The main page divs are setup with position: absolute, with left, right, top, and bottom all set to zero. These divs also have display: inline set, and do not have margins or padding. The html and body tags are styled the same way.
I've been looking around for a day or two but nothing I've found has worked. Does anyone know how to remove these scrollbars?

A: You can always use:
overflow: hidden;

To hide the scrollbars.


text:
Q: nRF52840 with optocoupler and mosfet I would like to make a switch which will be able to switch on/off 12-60V low current devices using nRF52840, optocoupler and mosfet.

I found this schematic and my idea was just to adjust R1 because voltage of GPIO of nRF52840 is 3.3v. I realized that source current of GPIO might not be enough to run optocoupler so I decided to look for low input current optocoupler. I found VO618A and my questions is would it be fine if I just switch PS2801 with VO618A and adjust R1? (I don't have many experience with electrical engineering experience so any guidance/help is welcomed)

A: There's a couple of problems with your circuit - the mosfet won't like much over 20V on it's gate and your circuit doesn't limit it. The 100nF cap is of little use across the led of the opto - why did you place it there?
The opto coupler is really a waste of time - it adds very little. You'd be better off to chose a mosfet that has a logic level gate.


text:
Q: WinXP logins no longer fully functional Summary:
Users with Roaming Profiles on my XP workstations appear to be unable to do various things, e.g. set a default printer, disable toolbars in IE8, or see icons on the left side of the Start menu.  Local accounts still work as expected.
Details:
I have a Mac OS X Server (10.6.4) Open Directory server that acts as a PDC for a few Windows XP workstations.  Recently, I upgraded it (10.5 --> 10.6) and another Mac server that is the BDC and OD Replica.
A few weeks later, I found out that the XP workstations were having issues with the roaming profiles.  Users would get an error at login (effectively, "I can't copy your profile from the server, so I'm using the local copy.") and then see their desktop.  They thought that they were OK, so they didn't report the problem at first.  However, it wasn't copying their profiles to the server.
In order to fix this, I moved a workstation from the domain to the workgroup "WORKGROUP", restarted, and move it back.
After that, they could login, but a new issue started.  (I mention the previous stuff in case there is a clue in there.)  Now a roaming-profile user can't do things that make lasting changes.  For example, they DO get their documents but they CAN'T print, set a default printer, or disable the Google or MSN toolbars in Internet Explorer.
I'm out of ideas.  I've tried a few things that I didn't list above, but none of them helped.
Any advise would be GREATLY appreciated.

A: Here's my best guess. My gut says that the permissions on the registry hives inside the users' roaming user profiles may be munged up. Assuming your users don't have "Administrator" rights, that's where I'd start looking first.
Logon as one of your problem users, open regedit, navigate to HKEY_CURRENT_USER, and look at the permissions (Edit / Permissions in the menu). I would expect you to see a permission for the domain account of the user you're logged-in as with "Full Control" and "Read" permission.
If you see this behavior, logon as an "Administrator", use the "Load Hive..." functionality in regedit to load the NTUSER.DAT file from the user's roaming profile folder into a subkey of HKEY_LOCAL_MACHINE, modify the permission at that subkey to include DOMAIN\User with "Full Control" permission, unload the hive, and logon as the user.
You can get these permission fouled-up by manually copying around profiles in the filesystem, rather than using the "Copy To" functionality in the "User Profiles" dialog of the "System Properties" dialog.


text:
Q: Turn off CnPack Ctrl + U feature I recently started using CnPack because I like how it displays nested code (and the colors!). However, I have found myself turning off most of the other features as I find them.
One feature that I can't seem to turn off is the Ctrl+U to see the unit list. Under the CnPack menu >> Project Enhancements >> List Units. This could be useful for some, but I much prefer MMX Ctrl+U feature as it can add units if you need it to.
I've looked under the settings (in multiple places) and haven't seen it. Anybody know how to turn this off?

A: *

*Go to menu CnPack / Options...

*Select Project Extension Wizard

*Click Settings button

*Select List units... item

*Focus ShortCut edit and press Backspace key

*Save the settings with the OK button


text:
Q: re.match with '-' not working in python I have the following code
if(keys==14):
    print (values)
    result = re.match("(^\-)", str(values))
    print "RR is", result, (values)

but the match is not working for a sample line. Here is the output which I got

-bob
RR is None bob

A: Can't reproduce:
>>> x='-bob'
>>> re.match('(^\-)', x)
<_sre.SRE_Match object; span=(0, 1), match='-'>

Your values may be different, presumably by having non-printable characters in addition at the start.  Try printing a repr of it to make sure that's not the case...!
EDIT: and indeed the repr reveals that the values start with a soft hyphen (encoded in utf-8) which may sometimes display as a dash but isn't actually a dash.  RE matching encoded byte strings can be inconvenient, so let's first decode it into text:
>>> x = '\xc2\xadbob'  # or however else `values` is obtained as such
>>> y = x.decode('utf8')
>>> re.match(ur'([\xad-])', y)
<_sre.SRE_Match object at 0x1004c0af8>

(switched to Python 2 here which is why the repr of the match object differs from the above snippet, where I was using Python 3).  On a side note, I've dropped the redundant caret in the pattern (the ^ at the start) since the match method is always anchored at the start anyway.
The core ideas of course are: (A) use Unicode to work with what is semantically actual text rather than a string of bytes; (B) use repr to check what glyphs are actually there, rather than just what they may look like in some context (since non-displaying glyphs and look-alike ones may otherwise fool you); and (C) the [\xad-] part of the (unicode) RE pattern matches either a soft hyphen ('\xad') or an actual dash -- the dash must come second, right before the ], due to RE pattern syntax (otherwise it would indicate matching a range of characters, while we want to match an actual dash if that's what is present).

A: In using re.match("(^-)", values) and assigning it to result, we are not changing the 'values'. Therefore in both print statements the 'values' will be '-bob'.
The matched object will be in the 'result'
import re
values = "-bob"
keys = 14
if(keys==14):
  print (values)
  result = re.match("(^\-)", values)
  print ("RR is", result.group(0), values)

Output
-bob
RR is - -bob


text:
Q: Session timeout in spite of setting the session time in web.config I have an ASP.net website where I am facing a session timeout issue. In web.config I have set session timeout to 480 (8 hours as session time). But even then session does not stay that long; it goes out after a number of minutes. Why is that and how I can fix it? My site is hosted on a shared hosting server.

A: By default Session time in asp.net is 20 min, and we can change it by setting Web.config file.
Now in your case you are setting it to 8 hours but went out in 1 min.
Do you know that there are few point by which session can be time out?
*) When it is wrongly configured in Web.Config file.
*) We can set this time out in server (IIS) also, so if its default setting is changed.
*) When the total memory of session is higher that the assign in shared host.
*) When there are some internal error at run time in any page, then session will be lost.
*) When some one or any process is changingadding any aspx file or web.config file at runtime.
So check all these point. I am sure it will resolve your problem...

A: Also, have you checked the app pool recycling options?

A: Your hosting provider have probably set some low value in "Recycle worker processes" in IIS for your application pool. Not sure if they can change that for you but you could try to ask them.

A: There are many reason which cause your session timeout before the actual value configure in web.config file.
one such reason is that if you hosted your applcation and forgot to reset the app pool after deployemnt.
or
once you deploy the application for first time then its corresponding app pool may get reset dusring the first run of application.
or if your app pool may get crash in between the process..
You can diagnose this problem first check your app pool (in advanced settings- if you hosted your application in IIS) now by going to the Event Viewr and check the logs in Custom Views go to server role then find the log by clicking find button at right side pane and paste your app pool name in search box.
check for the error or warning message related to app pool.
i hope this ma help you


text:
Q: angular material: md-select not working with "controller as" syntax? All I did was modify their official Async Search demo (it fits my use case) to make use of "controller as", and getting weird behaviour as a result. Codepen is here. Am I missing anything?
Here's the relevant bits of code from the above link:
JS:
angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
.controller('SelectAsyncController', function($timeout, $scope) {
  var vm = this;

  vm.user = null;
  vm.users = null;

  vm.loadUsers = function() {
    return $timeout(function() {
      vm.users =  vm.users  || [
        { id: 1, name: 'Scooby Doo' },
        { id: 2, name: 'Shaggy Rodgers' },
        { id: 3, name: 'Fred Jones' }
      ];
    }, 650);
  };
});

Markup:

    <md-select placeholder="Assign to user"
               ng-model="vm.user"
               md-on-open="vm.loadUsers()">
      <md-option ng-value="vm.user"
                 ng-repeat="user in vm.users">{{user.name}}</md-option>
    </md-select>

Assigned to: {{ vm.user ? vm.user.name : 'No one yet' }}

A: You should change ng-value to "user".
<md-option ng-value="user" ng-repeat="user in vm.users">{{user.name}}</md-option>

Here is the working Codepen.


text:
Q: Inserting records into an XML table with a unique key Maybe I'm just spoiled by SQL, but is there some cool LINQ way to insert a new record into an "XML table" and have the indexed ID update automatically (or at least semi-automatically)?
Here's what I mean by "XML table":
<myElements>
    <myElement>
        <id>1</id>
        <value>blah</value>
    </myElement>
    <myElement>
        <id>3</id>
        <value>blah</value>
    </myElement>
    <myElement>
        <id>4</id>
        <value>blah</value>
    </myElement>
    <myElement>
        <id>8</id>
        <value>blah</value>
    </myElement>
    <myElement>
        <id>9</id>
        <value>blah</value>
    </myElement>
</myElements>

In this case, the table is "myElements" and the records are the "myElement" elements (i.e., the children of myElements).
The "id" element is defined as a key in the schema, so it acts more or less as a "primary key", just like it would in SQL.
So, my question is, how do I insert a new "myElement" where the "value" element is "whatever" and the "id" element is automatically set to the next available id (in this example, it would be max(id) + 1 = 10).
I have my XML database stored in an XDocument, so I'd like a solution that uses LINQ and/or methods of XElement.
Thanks!

A: Well, since all my tables have an element called "id", I was able to write a fairly generic GetNextAvailableId element. So, here's how my insert routine would work for the "myElement" table.
public virtual int InsertMyElement(string value)
{
    int id = GetNextAvailableId("myElement");
    TableDictionary["myElement"].Add(
        new XElement(_ns + "myElement",
            new XElement(_ns + "id", id),
            new XElement(_ns + "value", value)));
    return id;
}

public virtual int GetNextAvailableId(string tableName)
{
    IEnumerable<int> ids =
        from
            r in TableDictionary[tableName].Elements()
        select
            int.Parse(r.Element(_ns + "id").Value);
    return ids.Max() + 1;
}

I don't feel too great about this solution--it will break if I ever decide to call my ID something besides "id"--but it seems like it will work for now.
Comments welcome.


text:
Q: Setup redis-cluster with Django Problem Statement
Use django-redis with redis clustering.
An error occurs when interacting with the cache.
The error points to a pickle operation on an instance of the ConnectionPool class where
one of it's attributes, a thread lock, cannot be serialized and results in the following error:
  TypeError: cannot pickle '_thread.lock' object

To Reproduce
Steps to reproduce the behavior:

*

*Run a redis cluster that REDIS_URL points to.

*Setup CACHES in Django settings file.
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": REDIS_URL,
        "OPTIONS": {
            "REDIS_CLIENT_CLASS": "redis.cluster.RedisCluster",
            "REDIS_CLIENT_KWARGS": {
                "url": REDIS_URL,
            },
        }
    }
}

*Run the Django console and try to interact with the cache e.g. cache.get("somekey")
Expected behavior
The value of the key from the Redis cluster.
Stack trace
Traceback (most recent call last):
  File "python3.9/site-packages/redis/cluster.py", line 1454, in initialize
    copy_kwargs = copy.deepcopy(kwargs)
  File "python3.9/copy.py", line 146, in deepcopy
    y = copier(x, memo)
  File "python3.9/copy.py", line 230, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "python3.9/copy.py", line 172, in deepcopy
    y = _reconstruct(x, memo, *rv)
  File "python3.9/copy.py", line 270, in _reconstruct
    state = deepcopy(state, memo)
  File "python3.9/copy.py", line 146, in deepcopy
    y = copier(x, memo)
  File "python3.9/copy.py", line 230, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "python3.9/copy.py", line 161, in deepcopy
    rv = reductor(4)
TypeError: cannot pickle '_thread.lock' object
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "python3.9/site-packages/IPython/core/interactiveshell.py", line 3552, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-6-48456cec0da8>", line 1, in <cell line: 1>
    from django.core.cache import cache; cache.get("bingo")
  File "python3.9/site-packages/django_redis/cache.py", line 91, in get
    value = self._get(key, default, version, client)
  File "python3.9/site-packages/django_redis/cache.py", line 31, in _decorator
    return method(self, *args, **kwargs)
  File "python3.9/site-packages/django_redis/cache.py", line 98, in _get
    return self.client.get(key, default=default, version=version, client=client)
  File "python3.9/site-packages/django_redis/client/default.py", line 253, in get
    client = self.get_client(write=False)
  File "python3.9/site-packages/django_redis/client/default.py", line 105, in get_client
    self._clients[index] = self.connect(index)
  File "python3.9/site-packages/django_redis/client/default.py", line 118, in connect
    return self.connection_factory.connect(self._server[index])
  File "python3.9/site-packages/django_redis/pool.py", line 72, in connect
    connection = self.get_connection(params)
  File "python3.9/site-packages/django_redis/pool.py", line 92, in get_connection
    return self.redis_client_cls(
  File "python3.9/site-packages/redis/cluster.py", line 592, in __init__
    self.nodes_manager = NodesManager(
  File "python3.9/site-packages/redis/cluster.py", line 1286, in __init__
    self.initialize()
  File "python3.9/site-packages/redis/cluster.py", line 1490, in initialize
    raise RedisClusterException(
redis.exceptions.RedisClusterException: ERROR sending "cluster slots" command to redis server 127.0.0.1:7000. error: cannot pickle '_thread.lock' object

Environment:

*

*Python version: 3.9

*Django Redis Version: 5.2.0

*Django Version: 3.2.13

*Redis Version: 7.0.0

*redis-py Version: 4.3.1

A: The problem is django_redis.pool.ConnectionFactory.get_connection
makes a pool (of class redis.connection.ConnectionPool)
  pool = self.get_or_create_connection_pool(params)
  return self.redis_client_cls(
      connection_pool=pool, **self.redis_client_cls_kwargs)

and passes it to
redis.cluster.RedisCluster.__init__( ... **kwargs ) (so kwargs now has connection_pool)
redis.cluster.NodesManager.__init__
redis.cluster.NodesManager.initialize()
    kwargs = self.connection_kwargs
    copy_kwargs = copy.deepcopy(kwargs)     *******
    *** die!  ConnectionPool has a _thread.lock, not pickle-able. ***

Because redis.connection.ConnectionPool has _thread.lock, deepcopy() fails.
Solution #1:
[6] calls RedisCluster.from_url directly from
django_redis.client.DefaultClient.connect(), bypassing
ConnectionFactory and ConnectionPool.
ConnectionPool.get_connection() makes the deadly connection_pool.
Solution #2:
Make a shim class of RedisCluster to drop "connection_pool" from
kwargs [7].
Solution #3:
Mess with RedisCluster before using it [8].
redis.cluster.RedisCluster.__ init __ scrubs kwargs before passing
it to NodesManager.
    kwargs = cleanup_kwargs(**kwargs)

It removes keys listed in redis.cluster.KWARGS_DISABLED_KEYS, which has
  KWARGS_DISABLED_KEYS = ("host", "port")

[8] adds "connection_pool" so cleanup_kwargs() removes the pesky key.
References
[6] https://github.com/jazzband/django-redis/issues/208
see cKurultayKalkan msg 2022-10-28
django-redis + redis-py 4.0 (with cluster)
add a shim class to redis.cluster.RedisCluster
class CustomRedisCluster(DefaultClient):
    def connect(self, index):
        """Override the connection retrival function."""
        return RedisCluster.from_url(self._server[index])

in settings.py,
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": REDIS_URL,
        "OPTIONS": {
            "CLIENT_CLASS": "redis_client.CustomRedisCluster",
        },
    }
}

[7] Add an adapter class in front of RedisCluster, to get rid of the
pesky 'connection_pool'.
import redis.cluster
class RedisClusterShim( redis.cluster.RedisCluster ) :
    def __init__( self,   *args, **kwargs ) :
        kwargs.pop( 'connection_pool', None )
        # redis.cluster.NodesManager.initialize() does connection_pool.deepcopy,
        # but redis.connection.ConnectionPool has a _thread.lock, not pickle-able.
        super().__init__( *args, **kwargs )

[8] mess with RedisCluster before using it, eg. add it to settings.py
def messWithRedisCluster() :
    import redis
    redis.cluster.KWARGS_DISABLED_KEYS = ("host", "port", "connection_pool" )
messWithRedisCluster()


text:
Q: Hyperjaxb: XMLGregorianCalendar to java.util.Date for Lists of Dates I implemented the solution of how replace XmlGregorianCalendar by Date? but unfortunately it does not function for Lists of dates.
In my  XSD I have
<xs:element name="Attribute1" type="xs:date" minOccurs="0">
and
<xs:element name="Attribute2" type="xs:date" minOccurs="0" maxOccurs="5">

Attribute2 is a List of dates. If I load an Entity with this attribute I get an java.lang.ClassCastException: org.hibernate.collection.internal.PersistentList incompatible with java.util.Date
I think the problem is that, Hyperjaxb only creates an Adapter
public class Adapter2 extends XmlAdapter<String, Date>
{
    public Date unmarshal(String value) {
        return (XsdDateTimeConverter.unmarshal(value));
    }

    public String marshal(Date value) {
        return (XsdDateTimeConverter.marshalDate(value));
    }

}

Maybe Hyperjaxb also needs to create an Adapter for the List<Date> like public class Adapter3 extends XmlAdapter<List<String>, List<Date>>
Does anyone have a solution for this?
Regards
Erzen
PS: I've already seen the questions Simple conversion between java.util.Date and XMLGregorianCalendar, java.util.Date to XMLGregorianCalendar and JAX-WS and Joda-Time? but those do not apply to my problem.


text:
Q: Setting up multiple document roots apache2 (server side (NOT local)) I am trying to set up two separate DocumentRoots in my httpd.conf.
I have the following:
     NameVirtualHost 89.104.220.210
#
# NOTE: NameVirtualHost cannot be used without a port specifier
# (e.g. :80) if mod_ssl is being used, due to the nature of the
# SSL protocol.
#

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for requests without a known
# server name.
#
<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host.example.com
    DocumentRoot /var/www/system.dk/html/
    ServerName  system.dk
    ErrorLog /logs/system
    CustomLog logs/dummy-host.example.com-access_log common
</VirtualHost>

<VirtualHost 89.104.220.210>
    ServerAdmin webmaster@dummy-host.example.com
    DocumentRoot /var/www/system.dk/html/system/
    ServerName  system.org
    ErrorLog /logs/system
    CustomLog logs/dummy-host.example.com-access_log common
</VirtualHost>

However when I attempt to restart, it fails to start:
    Stopping httpd:                                            [FAILED]
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 89.104.220.207 for ServerName
                                                           [FAILED]

Can anyone help me out here?
update
I have the following now:
     NameVirtualHost 89.104.220.207:80
 NameVirtualHost 89.104.220.207:1500
#
# NOTE: NameVirtualHost cannot be used without a port specifier
# (e.g. :80) if mod_ssl is being used, due to the nature of the
# SSL protocol.
#

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for requests without a known
# server name.
#
<VirtualHost 89.104.220.207:80>
     ServerAdmin webmaster@example.com
     DocumentRoot /var/www/system.dk/html
     ServerName www.system.dk
     ServerAlias system.dk
     ErrorLog /var/www/learnbypower.dk/logs/error_log

</VirtualHost>
<VirtualHost 89.104.220.207:1500>
     ServerAdmin webmaster@example.org
     DocumentRoot /var/www/system/
     ServerName system
     ServerAlias system.dk
     ErrorLog /var/www/system.dk/logs/error_log

</VirtualHost>

A: Check with below command on what error it does shows.
httpd -t

Also Apache Error logs when it fails. Default path is.
/var/log/httpd/error_log


text:
Q: What's the appropriate Java idiom/pattern for recursive call? What's the appropriate Java idiom/pattern for recursive call where I need to maintain an object across invocations? I see two options, but I don't like either of them.
Something like this:
class A {
   private ArrayList list = new ArrayList();

   public ArrayList foo (SomeType x){

      if(something) list.add(z);
      foo(y);

      return list;
   }

}

Or this?
class A {

   public ArrayList foo (SomeType x, ArrayList list){
      if (something) list.add(z);
      foo(y, list);

      return list;
   }

}

Thanks.

A: There is no idiom for recursive functions which is unique to Java. In general, the way recursive methods look like:
public <T> recursive(T t){
    if(stopConditionMet){
        return t;
    }
    // modify t and call recursively
    T nextT = modify(t);
    return recursive(nextT);
}

What you demonstrated in your question is a hybrid of recursive and iterative methods. The difference is that an iterative method does not call itself, but rather do all the work in a loop (until the stop-condition is met), which is why, in most cases, the iterative version is preferred (cheaper and safer to execute).

A: I would provide a public method that takes only the SomeType parameter.  It creates a new ArrayList and passes it to a private method that takes an ArrayList and does the actual recursion.  Also, the while loop is most likely unnecessary.  Recursion can be a replacement for using a loop.  Something like this should do:
public ArrayList foo (SomeType x) {
    return foo(x, new ArrayList());
}

private ArrayList foo(SomeType x, ArrayList list) {
    // Perform your recursion here, which probably shouldn't be in a loop.
    if (someCondition) {
        list.add(z);
        foo(y, list);
    }
    return list;
}

Once you get it working, you may want to add a generic type parameter to the ArrayList

A: You can just addrange on return from recursion:
 class A {

 public ArrayList foo (SomeType x)
 {
     List list = new ArrayList();
     while(/*some conditition*/)
     {
        if (something) list.add(z);
        list.addAll(foo(y));
     }
     return list;
  }
}

If i understand your logic correcly


text:
Q: IIS7 won't server Flash swf file that uses XML data I have an SWF file that I am attempting to serve up using SWFObjects 2.2.  It works everywhere except when served up from my server to a Chrome browser.  Specifically:

*

*local IIS 7, Chrome, IE, and FF all work

*server browsing through local file system works on Chrome, IE, and FF

*server browsing IIS 7, works in IE and FF, not Chrome

My server IIS will serve up normal SWF files to a Chrome browser, just not this specific SWF file that uses an XML data file.  My SWF file, XML data file, and referenced images are all in the same folder (wanted to eliminate that as a possible source of the error early on).
What possible IIS 7 setting would prevent a Chrome browser from rendering an SWF file that uses an XML data file?  Is there any way to troubleshoot in the Chrome browser to get some kind of idea of what the error is?
Here is the .htm file (generated by SWFObjects) that I am using:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

            <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="800" height="600" id="myFlashContent">
                <param name="movie" value="banner.swf" />
                <param name="flashvars" value="file=data.xml" />

                <object type="application/x-shockwave-flash" data="banner.swf" width="800" height="600">
                    <param name="flashvars" value="file=data.xml" />

                </object>

            </object>

Using this on my server with Chrome, all I get is a blank white page.
TIA,
Mike

A:
Using this on my server with Chrome, all I get is a blank white page.

If you right click the place where the swf is supposed to be, do you see a 'Swf not loaded' message in the context menu? If so, bring up Chrome's Developer console, launch Network tab and refresh the page. you should see a request to the server there for the swf and that might give you hints on why the load didn't succeed.
If you don't see a 'SWF' not loaded' message, and see a regular Chrome context menu, the browser didn't even attempt loading.


text:
Q: Trouble implementing simple async method call in SpringBoot I'm trying to implement a very simple asynchronous method call in my SpringBoot application but, whatever I do, I just cannot get it to work. I've looked at dozens of tutorials but they all seem unnecessarily complicated for what I'm doing. I'd appreciate any help you could provide.
Essentially, when a certain REST endpoint of my SpringBoot app is hit, it kicks off a slow task. Instead of making the client wait for the slow task to finish before getting a response, I want to asynchronously call the task method, and return a response to the client right away. For simplicity, the response that I want to return right away is generic -- I don't care about returning the result of the slow task itself.
I'm using Java 8 and SpringBoot 2.1.7

Initially, I started with just 2 classes:
1) Class 1:
@SpringBootApplication
@EnableAsync
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

2) Class 2:
@RestController
@RequestMapping("/rest")
public class Controller {

  @RequestMapping(value = "/slowTask", method = RequestMethod.GET)
  @ResponseBody
  public ResponseEntity<?> slowTask() {
    try{
            asyncSlowTask();
            // Want below response to be immediate -- instead, only occurs after above function is done.
            return new ResponseEntity<String>("Accepted request to do slow task", HttpStatus.ACCEPTED);
        }
    catch (Exception e) {
            return new ResponseEntity<String>("Exception", HttpStatus.INTERNAL_SERVER_ERROR);
        }
  }

  @Async
  public void asyncSlowTask(){
    // Sleep for 10s
    Thread.sleep(10000);
  }

}

I tested this by hitting the app locally: curl http://localhost:8080/rest/slowTask
What I expected is that the curl command would return right away -- instead, it only returned after 10 seconds (after my slow task was done).

At this point, I read that the asynchronous method shouldn't be 'self-invoked' -- I had no idea if that's what I was doing but, to be safe, I moved the async method to a new class, so that my classes now looked like this:
1) Class 1:
@SpringBootApplication
@EnableAsync
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

2) Class 2:
@RestController
@RequestMapping("/rest")
public class Controller {

  @RequestMapping(value = "/slowTask", method = RequestMethod.GET)
  @ResponseBody
  public ResponseEntity<?> slowTask() {
    try{
            AsyncClass.asyncSlowTask();
            // Want below response to be immediate -- instead, only occurs after above function is done.
            return new ResponseEntity<String>("Accepted request to do slow task", HttpStatus.ACCEPTED);
        }
    catch (Exception e) {
            return new ResponseEntity<String>("Exception", HttpStatus.INTERNAL_SERVER_ERROR);
        }
  }
}

3) Class 3:
public class AsyncClass {
  @Async
  public static void asyncSlowTask(){
    // Sleep for 10s
    Thread.sleep(10000);
  }
}

Unfortunately, this didn't make any difference -- the request is still returned only after my slow task is completed.
I've also tried a bunch of other minor variations (including putting @EnableSync and @Configuration on every class), but none of them worked.

So, here are my questions:
1) Did I need to move the async method to that 3rd class, or was my original, two-class setup good enough?
2) Which class should have the @EnableSync annotation?
I'm honestly completely lost as to where it should go -- all I know is that it should go in "one of your @Configuration classes", which means nothing to me.
3) Is there anything else I'm doing wrong??
Again, appreciate any help you can provide!

A: From the Spring Doc,
The default advice mode for processing @Async annotations is proxy which allows for interception of calls through the proxy only. Local calls within the same class cannot get intercepted that way.
Any feature(async, scheduler, transactional, etc.,) which depends on spring proxy works only on the object managed by spring container.
Your code should look like this,
@RestController
@RequestMapping("/rest")
public class Controller {

private final AsyncClass asyncClass;

public Controller(final AsyncClass asyncClass) {
    this.asyncClass = asyncClass;
}

@RequestMapping(value = "/slowTask", method = RequestMethod.GET)
public ResponseEntity<?> slowTask() {
    try {
        asyncClass.asyncSlowTask();
        return new ResponseEntity<>("Accepted request to do slow task", HttpStatus.ACCEPTED);
    } catch (final RuntimeException e) {
        return new ResponseEntity<>("Exception", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

}
@Component
public class AsyncClass {

  @Async
  @SneakyThrows
  public void asyncSlowTask() {
    Thread.sleep(10000);
  }
}

Which class should have the @EnableSync annotation?

You can have the annotation on the Application class or any @Configuration class which should be fine.

A: Try create a Async configuration
@Configuration
@EnableAsync
public class SpringAsyncConfig implements AsyncConfigurer {
    @Bean(name = "threadPoolTaskExecutor")
    public Executor threadPoolTaskExecutor() {
        return new ThreadPoolTaskExecutor();
    }

    @Override
    public Executor getAsyncExecutor() {
        return new ThreadPoolTaskExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new CustomAsyncExceptionHandler();
    }
}

and write down your methods with @Async("threadPoolTaskExecutor")
@Async("threadPoolTaskExecutor")
public void asyncSlowTask() {
    Thread.sleep(10000);
}


text:
Q: Adding multiple records to a table through a form that is required to be filled by more than one user Currently I have a Form setup where a user can fill out information (textboxes), click an add button and the record gets added into my table (it gets added to a random row in the table, not sure why).
I am trying to accomplish something different.
The form has two fields that is not supposed to be filled out by user, but by somebody else (an approver). There are usually multiple records a user will submit at a time so is it possible
to have the user fill out the form multiple times (multiple records), have them sit in a type of que until the approver inserts the final comments than proceeds to click the add button to add the record to the table?
Form code:
Option Compare Database
Private Sub Command21_Click()

On Error GoTo Err1
  DoCmd.GoToRecord , , acNewRec
  Exit Sub
Err1:
  Description.SetFocus
  btnAddRec.Enabled = False
  MsgBox (Err.Description)

End Sub

Please let me know if you need additional information.

A: Separate the forms for the users and approvers. Remove those two fields from the user form (and change them columns in the table to Required = No).


text:
Q: TextureView playing video turns black after onPause I  am using a TextureView to play a video in a ListView. The TextureView itself works perfectly, however, if I press the home button and reenter the application a few times, the TextureView turns black (though the audio continues to play). If I exit and reenter again, the TextureView turns white (or maybe transparent, as white is the colour of my background).
Here is my code:
holder.instagramTextureView
    .setSurfaceTextureListener(new SurfaceTextureListener() {

        @Override
        public void onSurfaceTextureUpdated(
                SurfaceTexture surface) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onSurfaceTextureSizeChanged(
                SurfaceTexture surface, int width, int height) {
            // TODO Auto-generated method stub

        }

        @Override
        public boolean onSurfaceTextureDestroyed(
                SurfaceTexture surface) {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public void onSurfaceTextureAvailable(
                SurfaceTexture surface, int width, int height) {
            final Surface s = new Surface(surface);

            try {
                holder.mMediaPlayer = new MediaPlayer();
                holder.mMediaPlayer.setDataSource(post
                                .getMedias().get(0)
                                .getMediaUrlVideomp4StandardRes());
                holder.mMediaPlayer.setSurface(s);
                holder.mMediaPlayer.prepare();

                holder.instagramVideoVolume = 0f;
                holder.mMediaPlayer.setVolume(
                        holder.instagramVideoVolume,
                        holder.instagramVideoVolume);
                //holder.mMediaPlayer.setOnBufferingUpdateListener(this);

                holder.mMediaPlayer
                    .setOnCompletionListener(new OnCompletionListener() {
                        @Override
                        public void onCompletion(
                                MediaPlayer mp) {

                            // To play:
                            mp.reset();
                            try {
                                mp.setDataSource(post
                                    .getMedias()
                                    .get(0)
                                    .getMediaUrlVideomp4StandardRes());
                                mp.prepare();

                            } catch (IllegalArgumentException e) {
                                // TODO Auto-generated catch
                                // block
                                e.printStackTrace();
                            } catch (SecurityException e) {
                                // TODO Auto-generated catch
                                // block
                                e.printStackTrace();
                            } catch (IllegalStateException e) {
                                // TODO Auto-generated catch
                                // block
                                e.printStackTrace();
                            } catch (IOException e) {
                                // TODO Auto-generated catch
                                // block
                                e.printStackTrace();
                            }
                            // <--- Here comes a call to
                            // "To Resize" which is shown
                            // right above this code
                            mp.start();
                        }
                });

                // holder.mMediaPlayer.setOnPreparedListener(this);
                //holder.mMediaPlayer.setOnVideoSizeChangedListener(this);

                holder.mMediaPlayer
                    .setAudioStreamType(AudioManager.STREAM_MUSIC);
                holder.mMediaPlayer.start();

                holder.instagramTextureView
                    .setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            if (holder.instagramVideoVolume == 1) {
                                holder.instagramVideoVolume = 0f;
                                holder.mMediaPlayer
                                    .setVolume(
                                        holder.instagramVideoVolume,
                                        holder.instagramVideoVolume);
                            } else {
                                holder.instagramVideoVolume = 1f;
                                holder.mMediaPlayer
                                    .setVolume(
                                        holder.instagramVideoVolume,
                                        holder.instagramVideoVolume);
                                    }
                            }
                });

            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
});

A: Problem was making a new mediaplayer each time the surface is available. Not quite sure how this worked, but this was the problem. Instead, I create the mediaplayer outside of this listener.

A: From my research, textureView.getSurfaceTexture()  returns null onResume(). What I did was reattach a listener to it in onResume().
TextureView textureView;

/*....
Usual stuff
*/

public void onPause(){
    super.onPause();

    //... destroy or disable image producer
}

public void onResume(){
    super.onResume();

    textureView.setSurfaceTextureListener(/*another listener*/);
}

Then, perform your usual things on onSurfaceTextureAvailable()

A: The black screen and audio playing happened with me when I did not release the MediaPlayer object.


text:
Q: Troubling to open macro enabled file Using MS excel URI scheme I am trying to open macro enabled excel file by MS-excel scheme using JavaScript but the file format is opening in the notepad with save option.
js code
 function OpenMasterExcel(id) {
     var File = { ID: id };
     $.get("/Home/MasterExcelOpen", File, function (result) {
          if (result.Message == "Success") {
             window.location =
                       "ms-excel:ofe|u|http://localhost:54857/Content/UploadedFolder/Book2.xlsm";
                }
                else {
                    alert("");
                }
            })
}

On button click getting popup to open excel:

After clicking on the popup button "open Office 2016" it is opening in notepad same as the image:

*

*give the full permission to the project folder

*change in the Dcomcnfg for excel application

*Enabled macro setting in excel application


text:
Q: Speed of native R function vs C++ equivalent When I compare the speed of the native Gamma function gamma in R to the C++ equivalent std::tgamma I find that the latter is about 10-15x slower. Why? I expect some differences, but this is huge, isn't it?
My implementation:
library("Rcpp")
library("microbenchmark")

cppFunction("
     double gammacpp(double x) {
         return(std::tgamma(x));
     }
")

x = max(0, rnorm(1, 50, 25))
microbenchmark(gamma(x), gammacpp(x))

Results on my machine:
Unit: nanoseconds
expr         min   lq    mean median uq  max neval cld
gamma(x)    100   101  124.91  101  102 1001   100   a
gammacpp(x) 1000 1101 1302.98 1200 1300 9401   100   b

A: Look at the code of gamma() (for example by typing gamma<Return>): it just calls a primitive.
Your Rcpp function is set up to be convenient.  All it took was a two-liner.  But it has some overhead is saving the state of the random-number generator, setting up the try/catch block for exception handling and more.  We have documented how you can skip some of these steps, but in many cases that is ill-advised.
In a nutshell, my view is that you have a poorly chosen comparison: too little happens in the functions you benchmark.  Also note the unit: nanoseconds.  You have a lot of measurement error here.
But the morale is that with a 'naive' (and convenient) C++ function as the one you wrote as a one-liner,  you will not beat somewhat optimised and tuned and already compiled code from inside R.  That is actually a good thing because if you did, you would have to now rewrite large chunks of R .
Edit: For kicks, here is a third variant 'in the middle' where we use Rcpp to call the same C API of R.
Code
#include <Rcpp.h>

// [[Rcpp::export]]
double gammaStd(double x) { return (std::tgamma(x)); }

// [[Rcpp::export]]
Rcpp::NumericVector gamma_R(Rcpp::NumericVector x) { return (Rcpp::gamma(x)); }

/*** R
set.seed(123)
x <- max(0, rnorm(1, 50, 25))
res <- microbenchmark::microbenchmark(R = gamma(x), Cpp = gammaStd(x), Sugar = gamma_R(x) )
res
*/

Output
> Rcpp::sourceCpp("~/git/stackoverflow/72383007/answer.cpp")
> set.seed(123)
> x <- max(0, rnorm(1, 50, 25))
> res <- microbenchmark::microbenchmark(R = gamma(x), Cpp = gammaStd(x), Sugar = gamma_R(x) )
>
res
Unit: nanoseconds
  expr  min     lq     mean median     uq     max neval cld
     R  102  112.0   136.95    124  134.5    1068   100   a
   Cpp 1111 1155.5 11930.02   1186 1260.0 1054813   100   a
 Sugar 1142 1201.0  6355.92   1246 1301.5  506628   100   a
>


text:
Q: mts - VARMACpp Example returns error i am very new to mts but it seams that the example of VARMACpp is not working with VARMACpp instead of VARMA
The example is:
phi=matrix(c(0.2,-0.6,0.3,1.1),2,2); theta=matrix(c(-0.5,0,0,-0.5),2,2)
sigma=diag(2)
m1=VARMAsim(300,arlags=c(1),malags=c(1),phi=phi,theta=theta,sigma=sigma)
zt=m1$series
m2=VARMA(zt,p=1,q=1,include.mean=FALSE)

works! Working with VARMACpp
m2=VARMACpp(zt,p=1,q=1,include.mean=FALSE)

returns the following error which did not manage to resolve:
Number of parameters:  8
initial estimates:  0.1814 0.3318 -0.4273 1.0542 0.3917 -0.0869 -0.073 0.5273
Par. lower-bounds:  0.0547 0.2763 -0.5518 0.9996 0.2175 -0.2218 -0.2442 0.3948
Par. upper-bounds:  0.308 0.3874 -0.3029 1.1088 0.5658 0.048 0.0981 0.6598
Error in do.call(rbind, ListResiduals) : second argument must be a list

A: Installing MTS from GitHub fixes the Problem
install.packages("devtools")
library(devtools)
install_github('MTS','d-')


text:
Q: Python ImportError associated with Python3.5 Installation and Extensions In attempting to install a Python package from GitHub for performing aerosol radiative calculations (not important). After cloning the repo and installing from source (python3 setup.py install), I tried to import the library (Python3.5.1) resulting in an import error:
ImportError: No module named 'mie._mie'

Looking at the setup.py file, I noticed that it creates this reference using the Extension syntax. What should I look for in trying to fix/debug this issue?
Why would the package install successfully but not import correctly?
NOTE: The extension essentially just wraps around some Fortran.

A: Try a straight:
import mie

If this doesn't work, consider these questions:

Is it possible you have multiple version of Python installed and are using a different one to try the import?
Are you using virtualenv by any chance?


text:
Q: String concatenation issues. The output still remains the empty string with which it was initialised I'm having a String concatenation issue. The output still remains the empty string with which it was initialised:
String ct=" ";//Encrpion part of playfair cipher
static void encryption()// The string ct is not getting printed. Only the empty string with which it was initialised is getting printed
{
    int row=98,col=7,row1=9,col1=24;//Just to initialise the variables, random numbers are assigned
    boolean bool= false, bool1=false;
    for(int i=0;i<l-1;i++)
    {
        bool=false;//So that only when both the bool values are true, it tells that it is of that iteration
        bool1=false;
        String a=Character.toString(pt.charAt(i));
        String b=Character.toString(pt.charAt(i+1));
        for(int j=0;j<5;j++)
        {
            for(int k=0;k<5;k++)
            {
                if(a==kmatrix[j][k])
                {
                    row=j;
                    col=k;
                    bool=true;
                }
                if(b==kmatrix[j][k])
                {
                    row1=j;
                    col1=k;
                    bool1=true;
                }
                while((bool==true)&&(bool1==true))
                {
                    if(col==col1)
                    {
                        if(Math.abs(row-row1)==1)//To get the difference
                        {
                            if(row<row1)
                            {
                                j=row1+1;
                                ct+=kmatrix[j][col];
                                ct+=kmatrix[row1][col];
                            }
                            else
                            {
                                j=row+1;
                                ct+=kmatrix[j][col];
                                ct+=kmatrix[row][col];
                            }

                        }
                    }
                    if(row==row1)
                    {
                        if(Math.abs(col-col1)==1)
                        {
                            if(col<col1)
                            {
                                k=col1+1;
                                ct+=kmatrix[row][col1];
                                ct+=kmatrix[row][j];
                            }
                            else
                            {
                                k=col+1;
                                ct+=kmatrix[row][col];
                                ct+=kmatrix[row1][k];
                            }

                        }
                    }
                    if((row!=row1)&(col!=col1))
                    {
                        if(row<row1)
                        {
                            ct+=kmatrix[row][col1];
                            ct+=kmatrix[row1][col];
                        }
                        else
                        {
                            ct+=kmatrix[row1][col];
                            ct+=kmatrix[row][col1];

                        }

                    }
                }
            }
        }
        i=i+1;
    }
    System.out.println(ct);
}

A: The first problem I see in the code is that you are comparing two strings with == operator, which is incorrect for the purpose of your code, and it evaluates to false. This operator does not compare the value of two strings, it only checks if two references refer to the same object.
if(a==kmatrix[j][k]) {
if(b==kmatrix[j][k]) {

Try to compare strings with equals or equalsIgnoreCase methods (the second one is case-insensitive):
if(a.equalsIgnoreCase(kmatrix[j][k])) {
if(b.equalsIgnoreCase(kmatrix[j][k])) {

A: I think there should be some problem with the matrixGeneration() method, since the values of the generated matrix have essential role in evaluating the conditions which lead to concatenation.
Would you please post the code ot matrixGeneration() method?


text:
Q: How to train SVM in Open CV for android? I am new to open CV and machine learning. I have a doubt regarding training the SVM for facial expression. I have downloaded the Cohn-Kanade facial expression database. Now do I need to extract the facial features from each image in the database and supply only the feature points as the SVM training data or do I need to supply the entire image as the training data ?

A: For an SVM, supply only the feature points, especially if you can represent them as displacements from rest state.  You want a nice, tractable vector (15-20 points?) rather than a 2D array (128x128?) of pixels.  The full image might work if you were training a CNN (convolutional neural network), but that would take a while.


text:
Q: How to make a table in a webpage scroll vertically while making everything else fixed in position I want to scroll a particular table in my webpage scroll vertically with mouse scroll event, while keeing everything else including the background image fixed in position.
This is my css script for the table
@media screen and (min-width: 480px) {
            table{
              background-color: rgba(255, 255, 0, 0.7);
              text-align: center;
              font-family: opensans;
              font-size: 20px;
              color: rgba(0, 0, 0, 255);
              width: 70vw;
              height: 100px;
              overflow-y: scroll;
              overflow-x: hidden;
            }
          }

And this is the script for background and header
body{
            background-color: rgba(0, 0, 0, 255);
            background: url("background.jpg");
            background-position: 49% 20%;
            background-repeat: no-repeat;
            background-blend-mode: luminosity;
          }

.Header{
            font-family: Neon;
            font-size: 40px;
            position: fixed;
            letter-spacing: 1px;
            top: 0;
            left: 0;
            width: 100%;
            line-height: 35px;
            text-align: center;
            color: rgb(255, 0, 0);
          }

Unfortunately the header remains fixed in its position but the background of the page is not. I tried adding the background position fixed as follows
body{
            background-color: rgba(0, 0, 0, 255);
            background: url("background.jpg");
            background-position: fixed;
            background-repeat: no-repeat;
            background-blend-mode: luminosity;
          }

But still the background goes up(vertically scrolled) while scrolling.

A: Wrap the table in a div with overflow-y: auto and set the height of the div to, for example, 100px

A: add background-attachment to be fixed.
check the below snippet
body {
    background-image: url("img_tree.gif");
    background-repeat: no-repeat;
    background-attachment: fixed;
   }

1: background-attachment property


text:
Q: ORACLE APEX Report Templates not showing up When I try to make a Classic Report with a Card Template, the Template Is not showing up in the right window. I don't have Media Lists either for example. But things like Blank with attributes are there.
Does anyone know a solution for this?
Greets

A: There are different templates. Every region has its own template - that is the "Region Template". "Blank with attributes" is one of those templates, by default it will be "Standard".
If your region is of type "Classic Report" you will get the option to select an report template for the report itself. That can be selected in the "Appearance" section of the report attributes. This is where you can find templates like "Card Template".

A: The way you described it, "solution" is to upgrade your Apex version as it seems that yours doesn't support templates you described.


text:
Q: Switch text of span element based on whether the div is expanded or collapsed I am trying to have three divs , initially all are closed.When the div is closed a span to right side is shown which is an arrow pointing towards right , when I click any div I want that the corresponding span arrow points down and again when that div is collapsed it should point right.Here is my fiddle.I think I am missing something , can anyone just help me out with this.
Also if any one could just let know better ways of doing this task (entire collapse , expansion) , it would be much appreciated.
Thanks

A: You are using slideToggle() which toggles the appearance but you are only assigning $('#sp2').html("▼");  per click which means whenever the div will be clicked, the span will get this value. You will have to place a check to see if a div is being expanded or collapsed and use appropriate code to set the span.
HTML
    ▶
jQuery
$('#one').click(function() {
        $('.sub1').slideToggle("slow");
        if ($("#sp1").hasClass("expand")) {
            $('#sp1').html("▼").removeClass("expand");
        }
        else {
            $('#sp1').html("▶").addClass("expand");
        }

        $('.sub2').slideUp("slow");
        $('.sub3').slideUp("slow");

    });

A: I've made a few amends to your code, including using classes to group elements. Your code was originally set the selected arrow, so you needed to change all the divs back their default state before completing the actions on the clicked one.
Try this:
$('.main').click(function() {
    var $el = $(this);

    if (!$el.next(".sub").is(":visible")) {
        // reset all
        $('.sub').slideUp("slow");
        $('.arrow').html("▶");

        // set current
        $el.next('.sub').slideDown("slow");
        $('.arrow', $el).html("▼");
    }
});

    ▶

Here there are many images

Here there are many images

Here there are many images

Here there are many images

Here there are many images

Here there are many images

Example fiddle

A: HERE is a DEMO
i used it in a project tested :)

but note you just have to add the images down and left URL directory on you machine
jsfiddle demo menu dropdown
i used this JQuery code
and some CSS and of course HTML
 $(document).ready(function()
    {
        //slides the element with class "menu_head" when paragraph with class "menu_head" is clicked
        $("#firstpane p.menu_head").click(function()
        {
            $(this).css({backgroundImage:"url(images/menu/down.png)"}).next("div.menu_body").slideToggle(300).siblings("div.menu_body").slideUp("slow");
            $(this).siblings().css({backgroundImage:"url(images/menu/left.png)"});
        });

    });


text:
Q: iterating over a pandas dataframe super fast I am trying to create labels for my dataset which is just a csv file with 20_000 lines of text. I 've used the following method but it takes about 15 minutes to create all the results. The desired outcome is
"This was a really crappy product", generated_label_with_confidence_score
import pandas as pd
import flair
from flair.models import TextClassifier
from flair.data import Sentence
import numba
import tqdm
import numpy as np

#@numba.jit
def predict_label(text):
  sentence = Sentence(text)
  classifier.predict(sentence)
  # print sentence with predicted labels
  return sentence.labels

for index, row in tqdm.tqdm(df_train.iterrows()):
    df_train.iloc[index, 1] = predict_label(df_train.iloc[index,0])

A: Instead of iterating over the dataframe using for loop, you can use df.apply to apply a function on each entry of a column.
Read its official documentation.
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html
I have tested time taken both by loop and df.apply here is a comparison.
In the following piece of code I applied a function(returning length of string) to text column to a dataframe having 20,000 entries.
def len_text(text):
    return len(text)

df_train = pd.DataFrame(['example sentence']*20000, columns = ['text'])

for index, row in tqdm.tqdm(df_train.iterrows()):
    df_train.iloc[index, 0] = len_text(df_train.iloc[index,0])

The above code took approximately 5 seconds to execute.
Let's see a better version by using df.apply and see how much time it will take.
df_train = pd.DataFrame(['example sentence']*20000, columns = ['text'])
st_time = time.time()

df_train['text'] = df_train['text'].apply(len_text)

en_time = time.time()
print(en_time - st_time)

The code in the cell above with df.apply took only 0.027 seconds to run on 20.000 entries.
So using df.apply instead of looping over the dataframe improved time by 4.973 seconds out of 5 seconds.


text:
Q: Proper way of closing Streams in Java Sockets I saw some posts about this but I still can't find an answer.
This is how my server interacts with the client:
public void run () {
    try {
        //Read client request
        InputStream is = server.getInputStream();
        byte[] buff = new byte[1024];
        int i;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((i = is.read(buff, 0, buff.length)) != -1) {
            bos.write(buff, 0, i);
            System.out.println(i + " bytes readed ("+bos.size()+")");
        }
        is.close();
        is = null;
        //Do something with client request

        //write response
        OutputStream os = server.getOutputStream();
        os.write("server response".getBytes());
        os.flush();
        os.close();
        os = null;

    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

And this is the client side:
public void run() {
        try {
            InetAddress serverAddr = null;
            serverAddr = InetAddress.getByName("10.0.2.2");
            socket = new Socket(serverAddr, 5000);

            //Send Request to the server
            OutputStream os = socket.getOutputStream();
            os.write(jsonRequest.toString().getBytes("UTF-8"));
            os.flush();
            os.close();
            os = null;

            //Read Server Response
            InputStream is = socket.getInputStream();
            byte[] buff = new byte[1024];
            int i;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((i = is.read(buff, 0, buff.length)) != -1) {
                bos.write(buff, 0, i);
                System.out.println(i + " bytes readed ("+bos.size()+")");
            }
            is.close();
            is = null;

            //Do something with server response

        } catch (UnknownHostException uhe) {
            sendCallbackError(uhe);
        } catch (IOException ioe) {
            sendCallbackError(ioe);
        }
    }

As you can see, the client connects and send a request. Server read that request then writes a response that the client will read.
The problem with this code is the OutputStream.close() in the client and InputStream.close() in the server. As stated in the Javadocs, closing the stream will close the Socket. The result is that when the client tries to read the server response, the Socket is already closed.
I've managed to overcome this by calling Socket.shutdownInput and Socket.shutdownOutput instead. However I am still thinking whether this is the proper way of doing it
As a note, closing the streams with close() when server writes the response or when the client reads it doesn't create problems (I would guess the closing is synchronized between client and server).
So my questions are:

*

*Is using the Socket shutdown methods a proper way?

*Can I keep closing the last streams with close() (when sending and reading
response from server)

*Could it happen that closing with shutdown would keep some data in
the buffer and wouldn't be sent?

A: You can do the following:
try{
}catch(){
}finally{
if(is!=null){
is.close();
}
if(os!=null){
os.close();
}
}

A:
The problem with this code is the OutputStream.close() in the client and InputStream.close() in the server. As stated in the Javadocs, closing the stream will close the Socket.

Correct but the InputStream in the server isn't connected directly to a Socket: it is connected to something you don't know anything about. You can close it with impunity, although again you don't need to close it at all. You can close the OutputStream in the server if you like: although, again, as it isn't connected directly to a Socket, it may or may not have any effect other than flushing.
To address your actual question, you don't need to close the output stream in the client, but you do need to send an appropriate Content-Length: header. That way the server knows how much to read from the client. If this is only a GET request the content-length may well be zero. You don't need to call shutdownOutput(), although I guess there is nothing to stop you, and calling shutdownInput() doesn't do anything to the network anyway so again there is no point to it.


text:
Q: How compatible are data science notebooks with clean architecture? Clean architecture decouples an app's core from the presentation/UI layer. The UI is just a plugin, replaceable  (eg, web-based to desktop) without impacting the core.
Many data science apps mix code, user inputs, text, graphics and other outputs in one notebook, eg, Jupyter. Everything seems coupled: the domain, UI, presentation, persistence.
Q:
How to design such an app cleanly, with the notebook maximally decoupled? Or are notebooks inherently incompatible with clean architecture?
Perhaps I could have an independent module with core functionality. The notebook would call this module, without defining any non-trivial functionality. Would this, however, allow enough decoupling or even fit with a notebook?
Why:
I'll be developing an app for a client who's only used Excel. The app will predict cost effectiveness of medical treatments and will need  MCMC simulations, regression and other stats.
I plan to implement it in Python with  Jupyter  or the nteract notebook, pushed by Netflix https://medium.com/netflix-techblog/tagged/nteract. However, this may eventually prove unsuitable for the client, as  Jupyter is mainly used by those who program it themselves. There're other potential pitfalls, eg, https://docs.google.com/presentation/d/1n2RlMdmv1p25Xy5thJUhkKGvjtV-dkAIsUXP-AL4ffI/edit#slide=id.g362da58057_0_1.
Ideally, I could easily swap between notebook types or change over to a desktop GUI.

A:
I plan to implement it in Python with  Jupyter or the nteract notebook, pushed by Netflix

Here's your use case for Clean Architecture right here. How much of your code has to KNOW which notebook you decided to use? Does this choice infect every line of your code?
Architecture called Clean, Onion, Ports and Adapters, or whatever, teaches you how to put a firewall between a detail like which notebook you used and your hard won business logic that, if you are very careful, doesn't care which notebook you used.
The notebook provides you with services you need. Look hard at what those needs are and strip them of any hint about which notebook, if any, is providing them. Don't bother with services you don't need. That creates your firewall against changing notebooks.
So long as there are places in your code that can't tell what notebook you used then they don't care when you change what you use. That's really powerful. It's just not free. It's work.
You have to decide if being able to swap notebooks is worth putting in that work.

A: Jupyter already has a fairly modular architecture. You have to distinguish:

*

*The notebook format which contains input and output cells. This is essentially just a JSON file.

*The kernel which executes code in a particular environment and language. For example you might have an R kernel, a Python kernel, and another Python kernel for code in a particular virtualenv.

*A notebook viewer or console which displays a notebook and/or allows interaction with a kernel. For example, there's the Jupyter web interface but there are also a couple of native programs. GitHub has a built-in notebook viewer.

Incidentally those three components fit a MVC architecture quite well. In particular, kernels are easy to change and do not depend on the other components!
You might want to consider whether you can already mix and match suitable components to meet your needs. However, the notebook format is the one thing you cannot easily change because the notebook is a common data model between multiple parts of a software. Similarly, all the other components (user interfaces, persistence) depend on the model in the clean architecture.


text:
Q: Convert dictionary of lists to dictionary of dictionary Current output is of format, dictionary of lists
{
    "majestic-service-1.324.02070909": [
        "/home/robotics/arm-services/FeaturesDir.yaml",
        "/home/robotics/arm-service/majestic-service.tar.gz"
    ],
}

and I'm looking to change that output format to something like below.(dictionary of dictionary)
{
    "majestic-service-1.324.02070909": {
        "yaml_file": "/home/robotics/arm-services/FeaturesDir.yaml",
        "tar_file": "/home/robotics/arm-services/majestic-service-1.324.02070909.tar.gz",
        "kind": "FeaturesDir"
    }
}

Corresponding code snippet that I've tried,
 output_dict = {}
 for file in application_files:
    match = re.match(regex_pattern, os.path.basename(file))
    if match:
         if os.path.exists(os.path.join(os.path.dirname(file), "FeaturesDir.yaml")):
              output_dict[file_without_extension(match.string)] = {os.path.join(os.path.dirname(file), "FeaturesDir.yaml")}
              output_dict[file_without_extension(match.string)].append(file)
              output_dict["Kind"] = "FeaturesDir"
         elif os.path.exists(os.path.join(os.path.dirname(file), "output_path/Deviations.yaml")):
                output_dict[file_without_extension(match.string)] = {os.path.join(os.path.dirname(file), "output_path/Deviations")}
                output_dict[file_without_extension(match.string)].append(file)
                output_dict["Kind"] = "Deviations"

# where the function file_without_extension, will return - majestic-service-1.324.02070909 from majestic-service-1.324.02070909.tar.gz

It reports the following error
AttributeError: 'set' object has no attribute 'append'

What am I doing wrong ?

A: The error occurs because in this line output_dict[file_without_extension(match.string)] = {os.path.join(os.path.dirname(file), "output_path/Deviations")} you're using {} brackets which for python are intended as the data type called set. Sets don't have append attribute, they have add attribute instead but it's a completely different data type. That's why it shows you that kind of error!


text:
Q: Distributions whose derivatives are Radon measures It is not difficult to show that if $f\in L^{loc}_1(\mathbb{R})$ and its derivative $Df$ (as an element of $\mathcal{D}'(\mathbb{R})$)is a Radon measure in $\mathbb{R}$ with finite total variation, then $f\in L_\infty(\mathbb{R})$.  The question I have is in a sense a partial converse of the statement above.

if $u\in \mathcal{D}(\mathbb{R})$ is such that $Du$ is a Radon measure with total finite variation, does $u$ have a representation in $L^{loc}_1(\mathbb{R})$? that is, is there $f\in L^{loc}_1(\mathbb{R})$ such that
$$u(\phi)=\int_\mathbb{R} \phi(t) f(t)\,dt,\qquad \phi\in\mathcal{D}(\mathbb{R})$$

This may be a very simple question. I will appreciate any reference or solution to my question.


text:
Q: Javascript and MongoDB - write to file I'm using mongoDB on an ubuntu server. However I'm using a javascript to store data and do some map/reduce. I would like to measure these operations and write the results into a file. Somehow I fail to open a file and write into it.. I tried the following:
f = new File("myfile.txt");
if(f.open("w") == true)
{
    f.write("test");
 f.Close();
}

A: Simple answer: you can not write files using Javascript.

A: It is probably better to write to the console using println and redirect the output to file, pass the javascript file as a parameter to mongo.
mongo someprocess.js > outpout

A: The file object within spidermonkey (the JS engine MongoDB uses, and coincidently the console) has been made obsolete: https://developer.mozilla.org/en-US/docs/SpiderMonkey/File_object . Not only that but it wasn't standard to spidermonkey anyway so that was a long shot.
As @gkamal states, the best way is to pipe the output of the MongoDB console like so:
mongo someprocess.js > outpout


text:
Q: Understanding Riesz's functional calculus I am studying Conway's Functional Analysis, where Riesz's functional calculus is introduced rather suddenly. Let $G \subset \mathbb C$ be open, $\mathcal A$ be a complex Banach algebra with identity $e$. The book states:

If $f: G \to \mathbb C$ is analytic and $\sigma(a) \subset G$, we will define an element $f(a) \in \mathcal A$ by $$f(a) = \frac{1}{2\pi i}\int_\Gamma f(z)(ze-a)^{-1}dz,$$

where $\Gamma$ is a suitable curve (I think further details are not necessary here, since this is common knowledge).
Question: what exactly is the object $\int_\Gamma f(z)(ze-a)^{-1}dz$? How can one understand this notation? For example, we can make sense of countable sums in a Banach space. But integration in a Banach space? I don't even have an intuition for it to be honest. Any answers, either rigorous or intuitive, are welcome.

A: There is nothing fancy going on here. You are still doing a line integral over the complex plane.
Something that is not emphasized (or even mentioned) when integration is taught, is the very asymmetric roles of the domain and the codomain. If you look at the definition of Riemann integral, what you do with the codomain is to multiply values of the function by complex numbers and add (which requires the codomain to be a vector space) and taking limits (which requires the codomain to be a topological space). So a Banach space is the perfect codomain to do Riemann integration.
Concretely, if $\Gamma$ is given by $\gamma(t)$, $t\in [0,1]$, then
\begin{align}
\int_\Gamma f(z)(ze-a)^{-1}dz&=\int_0^1f(\gamma(t))\,(\gamma(t)e-a)^{-1}\,\gamma'(t)\,dt\\[0.3cm]
&=\lim_{n\to\infty}\frac1n\,\sum_{k=1}^nf\big(\gamma(\tfrac kn)\big)\,\big(\gamma(\tfrac kn)e-a\big)^{-1}\,\gamma'\big(\tfrac kn\big).
\end{align}
The limit exists when the argument is continuous, with the same proof as for the usual real-valued Riemann integral. Here, the continuity of $f$ and $\gamma$, together with the fact that $\Gamma$ is removed from the spectrum of $a$, guarantee that the integrand is continuous.

A: Martin Argerami has given an excellent answer on what the object of the mentioned integral is. I will add a bit more words on the very book you are reading since you can find information conveniently in Conway's book itself.
This is explicitly mentioned at the beginning of Section 4 of Chapter VII "The Riesz Functional Calculus" in Conway's book you are reading (A Course in Functional Analysis, 2nd edition, page 109, emphasis mine):
Let $G$ be an open subset of $\mathbb{C}$ and let $\mathscr{X}$ be a Banach space. If $f: G \rightarrow \mathscr{X}$ is analytic and $x^{*} \in \mathscr{X}^{*}$, then $z \mapsto\left\langle f(z), x^{*}\right\rangle$ is analytic on $G$ and its derivative is $\left\langle f^{\prime}(z), x^{*}\right\rangle$. By Exercise 4 of the preceding section, if $f: G \rightarrow \mathscr{X}$ is a function such that $z \mapsto\left\langle f(z), x^{*}\right\rangle$ is analytic for each $x^{*}$ in $\mathscr{X}^{*}$, then $f: G \rightarrow \mathscr{X}$ is analytic. These facts will help in discussing and proving many of the results below.
If $\gamma$ is a rectifiable curve in $G$ and $f$ is a continuous function defined in a neighborhood of $\{\gamma\}$ with values in $\mathscr{X}$, then $\int_{\gamma} f$ can be defined as for a scalar-valued $f$ as the limit in $\mathscr{X}$ of sums of the form
$$
\sum_{j}\left[\gamma\left(t_{j}\right)-\gamma\left(t_{j-1}\right)\right] f\left(\gamma\left(t_{j}\right)\right)
$$
where $\left\{t_{0}, t_{1}, \ldots, t_{n}\right\}$ is a partition of $[0,1]$. Hence $\int_{\gamma} f=\int_{0}^{1} f(\gamma(t)) d \gamma(t) \in \mathscr{X}$. It is easy to see that for every $x^{*}$ in $\mathscr{X}^{*},\left\langle\int_{\gamma} f, x^{*}\right\rangle=\int_{\gamma}\left\langle f(\cdot), x^{*}\right\rangle$.


text:
Q: Where can I get the data_corpus_irishbudget2010 used in the examples on the Quanteda site? I have been doing all the exercises in Tutorials.Quanteda.io, but the section on constructing a DFM uses a corpus called data_corpus_irishbudget2010 doesn't run. This is the code:
toks_irish <- tokens(data_corpus_irishbudget2010, remove_punct = TRUE)
dfmat_irish <- dfm(toks_irish)
print(dfmat_irish)
I get this error:
Error in tokens(data_corpus_irishbudget2010, remove_punct = TRUE) :
  object 'data_corpus_irishbudget2010' not found
I have been able to load data_char_ukimmig2010 and data_corpus_inaugural. I just installed Quanteda this week. I also ran require(quanteda.corpora) and still can't use the data_corpus_irishbudget2010.
Any ideas?

A: That data object has been relocated to the new quanteda.textmodels package.  To access it, use:
data("data_corpus_irishbudget2010", package = "quanteda.textmodels")


text:
Q: HKObserverQuery, background updates and privacy policy I'm trying to program a heart rate monitor using the HealthKit API.
I have a Polar H7 and it is writing the data to the Health store. I achieved my goal using HKObserverQuery (no missing call to completionHandler()), HKSampleQuery and enabling background updates calling HKHealthStore.enableBackgroundDeliveryForType for the type I'm querying.
private func queryForHeartRate() {

    guard let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else {
        executeCompletionHandler(value: nil, error: nil)
        return
    }

    let observerQuery = HKObserverQuery(sampleType: sampleType, predicate: nil) { [unowned self] query, completionHandler, error in

        guard error == nil else {
            self.executeCompletionHandler(value: nil, error: error)
            return
        }

        self.queryHeartRateSample(sampleType)
        completionHandler()
    }

    healthStore.executeQuery(observerQuery)
}

private func queryHeartRateSample(sampleType: HKSampleType) {

    let timeSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
    let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: nil, limit: 1, sortDescriptors: [timeSortDescriptor], resultsHandler: { [unowned self] (sampleQuery, results, error) in

        guard error == nil else {
            self.executeCompletionHandler(value: nil, error: error)
            return
        }

        guard let samples = results as? [HKQuantitySample] where !samples.isEmpty else {
            self.executeCompletionHandler(value: nil, error: error)
            return
        }

        guard let lastSample = samples.last else {
            self.executeCompletionHandler(value: nil, error: error)
            return
        }

        let heartBeat = lastSample.quantity.doubleValueForUnit(self.heartBeatsPerMinuteUnit)
        self.executeCompletionHandler(value: heartBeat, error: nil)
    })

    healthStore.executeQuery(sampleQuery)
}

But when the app goes to background or I lock the phone (immediate passcode) the app stops to receive the updates.
Reading the docs I see:

The HealthKit data is only kept locally on the user's device. For security, the HealthKit store is encrypted when the device is locked. The HealthKit store can only be accessed by an authorized app. As a result, you may not be able to read data from the store when your app is launched in the background; however, apps can still write data to the store, even when the phone is locked. HealthKit temporarily caches the data and saves it to the encrypted store as soon as the phone is unlocked

However, when I use Runstastic, I receive sound advises when I change the heart zone; Nike+Running tracks all the heart rate the same way. How is that possible with that privacy policy?
I'm a bit lost, and the documentation is kind of confusing about what is needed to receive updates on background/locked (if possible). I read all the related answers here in SO but no one is conclusive, and the one with more information, this, speaks about background fetches, thing that is not mentioned in the docs.
Is there any resource or tutorial on how to achieve this? Is even possible? Have Runtastic or similar apps workarounds for this?
Thank you so much.

A: Your app cannot receive HealthKit data while the device is locked because the data is encrypted and inaccessible at that time. Other apps that respond to changes in heart rate while the device is locked are most likely reading data directly from the BT heart rate monitor, not HealthKit.


text:
Q: Como consumir un servicio Web por metodo POST con HttpWebRquest c#? Quiero consumir un servicio web que solicita token y en el body un elemento json , todo esto utilizando codigo c#. En postman funciona correctamente e incluso he tratado de replicar los headers tal cual pero aun no logro que funcione.
He intentado de muchas maneras pero siempre recibo el error: Error en el servidor remoto: (400) Solicitud incorrecta.
Mi codigo es el siguiente:
 private string EnviarDocumento(string jsonFirmado, string token)
    {
        string json = "";

        try
        {

            //Crear mi objeto
                    var myData = new
                    {
                        peticion = jsonFirmado
                    };

            //Transformacion a json
            string jsonBody = JsonConvert.SerializeObject(myData);
            var dataL = Encoding.UTF8.GetBytes(jsonBody);

            var url = "https://apitest.dtes.mh.gob.sv/fesv/recepciondte";
            var httpRequest = (HttpWebRequest)WebRequest.Create(url);
            httpRequest.Method = "POST";

            httpRequest.Headers["Authorization"] = token;
            httpRequest.ContentType = "application/json";
            httpRequest.ContentLength = dataL.Length;
            httpRequest.UserAgent = "SAGRISA-WS-Client";

            var data = jsonBody;

            using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
            {
                streamWriter.Write(data);
            }

            var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                json = result.ToString();
            }

        }
        catch (Exception exc)
        {
            json = "Error: " + exc.Message;
        }
        return json;
    }


text:
Q: Update Columns Where The Parameter Has Been Supplied From Code I am going to be executing an Update stored procedure from .NET. I want the following logic in T-SQL, however I can't seem to find out how this can be done.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE sp_UpdateTable

    @TableID int,
    @StartTime1 datetime,
    @EndTime1 datetime

AS
BEGIN
    SET NOCOUNT ON;

    UPDATE [Table]
       SET [StartTime1] = WAS_PASSED_FROM_CODE(@StartTime1, @StartTime1, [StartTime1])
          ,[EndTime1]   = WAS_PASSED_FROM_CODE(@EndTime1,   @EndTime1,   [EndTime1])
    WHERE TableID = @TableID
END
GO

Okay, so what I am basically looking for is a way to determine whether the parameter was specified from code, (hence WAS_PASSED_FROM_CODE) if the parameter was specified from code, then update that column to the specified value, else, leave intact (update to existing value).
Is this possible?
Note that in this case it is valid for the code to pass NULL, in that case, the column should update to NULL.

A: Make your parameters default to NULL and then use ISNULL.  If the parameter is not specified it will be NULL
Edit: Given that NULL is a valid value, add two additional parameters to marked whether or not the date parameters are specified.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE sp_UpdateTable

    @TableID int,
    @StartTime1 datetime,
    @StartTime1Specified BIT,
    @EndTime1 datetime,
    @EndTime1Specified BIT

AS
BEGIN
    SET NOCOUNT ON;

    UPDATE [Table]
       SET [StartTime1] = (CASE WHEN @StartTime1Specified = 1 THEN @StartTime1 ELSE [StartTime1] END)
          ,[EndTime1]   = (CASE WHEN @EndTime1Specified = 1 THEN @EndTime1 ELSE [EndTime1])
    WHERE TableID = @TableID
END
GO


text:
Q: Add same group of control at run time I have to add to a usercontrol (VB.NET) a variable group of similar controls.
The context:
For iceskate competition I have to create a userform with n lines (n = number of participant). On each line i have to add m combobox and m textbox (m = number of elements)
I do this in the following code, but for the combobox, when i change one , all the others keeps the same selected item. This is not the same for the textbox. I do not understand why.
Any idea?
For I = 1 To  nbrelements
                            Dim cmbelem As ComboBox
                            cmbelem = New ComboBox()
                            cmbelem.DataSource = tblelements
                            cmbelem.ValueMember = "Code"
                            cmbelem.DisplayMember = "Code"
                            cmbelem.Name = "Elem" & I & "/" & dtr.Item("idpatineur")
                            cmbelem.Height = 20
                            cmbelem.Width = 60
                            PosHor += 65
                            cmbelem.Location = new Point(PosHor,posligne)
                            Fempty.Controls.Add(cmbelem)

                            cmbelem = nothing
                            Dim txtElem As TextBox
                            txtElem = New TextBox()
                            txtElem.Name = "txt" & I & "/" & dtr.Item("idpatineur")
                            txtElem.Text = "0"
                            txtElem.Height = 20
                            txtElem.Width = 20
                            PosHor += 65
                            txtelem.Location = new Point(PosHor,posligne)
                            Fempty.Controls.Add(TxtElem)
                        Next


text:
Q: webrtc is not working on azure hsoting i am doing video conferencing in webrtc. and chat application in signalR. the video conferencing is working locally but when i host the application the conferencing on azure it is not working but signalR chat App is working properly. suggest me another hosting site for webrtc applications.

A: are you using https? Chrome only allows getUserMedia for secure origins with an exception for localhost.


text:
Q: How to change EditText field for various spinner values I want to change EditText field for each spinner selection, my EditText field should be able to take input in Feet+inch or in Cms based on the input selected by user for unit's field, i.e. if User selects Metric System then EditText should change into cm format, for FPS system the EditText should change to Feet+inch format, something like following image

I guess I have to use onClickListener on spinner and then have to change EditText, but I don't know how to do that.

A: you should use this interface with your spinner. the 'position' corresponds to the spinner array item position, it your spinner array is ["inch","cm"] then case 0 correspond "inch" and 1 is "cm".
I hope it will help.
 //set spinner listener
    mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
             switch (position) {
        case 0:
           //TODO change EditText
            break;
        case 1:
            //TODO change EditText
            break;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

A: Thank you for your time I got what I wanted , I just used a workaround,
I deploeyd three feilds Ft,In and cms; Ft for feet , In for inches and cms for centimeters, In spinner ft+in , and cms are two options, I set the visibility of non selected option as VISIBLE.GONE.


text:
Q: How do I transform this JSON data using JQ to extract each nested array element to the top level in turn? Given input of the form
[
    {"a": 1, "b": [{"c": 1}, {"c": 2}]},
    {"a": 2, "b": [{"c": 4}, {"c": 5}]}
]

I'm trying to transform to look like:
[
    {"a": 1, "b": [{"c": 1}],
    {"a": 1, "b": [{"c": 2}],
    {"a": 2, "b": [{"c": 3}],
    {"a": 2, "b": [{"c": 4}]
]

I have [map(.b) ] | flatten, however any further operation using the parent context does not seems to be possible. I'm really stuck and would appreciate any help.
Thanks

A: Here's a straightforward solution that makes no mention of any keys besides "b":
map(. + (.b[] | {b: [.]}))

A: You can try this filter:
jq 'map({a,"b":.b[]|[.]})' file

It updates the content of b with each value of c separately.


text:
Q: Why is the date being incorrectly converted? I'm trying to convert a String date into a Date object like this:
  DateFormat formatter ;
  Date date ;
  formatter = new SimpleDateFormat("dd/mm/yyyy");
  date = (Date)formatter.parse(str_date);

Source
However for some reason, the month is being converted into january always.
Example inputted date: 18/08/2012
Outputted date: Wed Jan 18 00:08:00 CET 2012
Does anyone know why this is happening please?

A: It should be "dd/MM/yyyy" (upper case M). Lower case m is for minutes.
Take a look at the table in SimpleDateFormat docs.


text:
Q: PIL Image getpixel TypeError: 'int' object is not iterable I want to use the getpixel((w,h)) method of PIL.Image but we processing image this give a
TypeError: 'int' object is not iterable
Error, it seems that method don't return a three elements tuple, have tried with both png file and jpg file same result, what happend?
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PIL import Image

def makeIndex():
    pic = Image.open('lines.jpg')
    width = pic.width
    height = pic.height
    for w in range(0, width):
        for h in range(0, height):
            r,g,b= pic.getpixel((w,h))
            print (r,g,b)

if __name__ == "__main__":
    makeIndex()

# vim:ai:et:sts=4:sw=4:

EDIT
as mentioned by the comment this time I chose another png file to do the test and do a convert('RGB') before processing
    pic = Image.open('stencil.png').convert('RGB')
    width = pic.width
    height = pic.height
    for w in range(0, width):
        for h in range(0, height):
            r,g,b= pic.getpixel((w,h))
            print (w,h), (r,g,b)

And this give a result of
(106, 988) (141, 60, 146)
(106, 989) (141, 60, 146)
(106, 990) (141, 60, 146)
(106, 991) (141, 60, 146)
(106, 992) (130, 36, 36)
(106, 993) (130, 36, 36)
(106, 994) (130, 36, 36)
(106, 995) (130, 36, 36)
(106, 996) (130, 36, 36)
(106, 997) (130, 36, 36)
(106, 998) (130, 36, 36)
(106, 999) (130, 36, 36)

And each has different r,g,b value
So what does this layer things really mean?