text:
Q: Autofac - InstancePerRequest created from DependencyResolver.Current.GetService<>() - When is it released? In an API controller project in .NET, there is a service I am using, say SomeService, requires one time only initialisation (not per request or per SomeService instance) (Although I do not think it is relevant, here the explanation for this init part: It does some setup in Azure storage for once the api is created. Doing this for every instance of SomeService is unnecessarely costly. Therefore there was the following line in Global.asax
new SomeService().Init();

Now, I am using Autofac for dependency injection. I register SomeService as ISomeService and as InstancePerRequest (because SomeService is not thread-safe). Therefore now I want to initialise SomeService in Global.asax via an instance from container. However If I try to get an instance from container as in
container.Resolve<ISomeService>().Init();

it gives this error
An exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll but was not handled in user code

Additional information: No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.

Therefore in Global.asax I get an instance as suggested in the error explanation.
DependencyResolver.Current.GetService<ISomeService>().Init();

What I want to know is that the SomeService instance I get from Current is released or not? Since there is no real request, I am not sure. At worst I can get the instance from concrete with new.

A: You are trying to merge 2 responsibilities into 1 components which breaks the Single Responsibility Principle.
In order to solve it, you can split the component with a component that will initialize the azure storage (IStorageProvider for example) and another component that will do the job. The IStorageProvider will be declared as SingleInstance (and implement IStartable if needed) and the other component will use this component.
public class AzureStorageProvider : IStorageProvider, IStartable
{
    public void Start()
    {
        // initialize storage
        this._storage = new ...
    }
}

public class SomeService : ISomeService
{
    public SomeService(IStorageProvider storageProvider)
    {
        this._storageProvider = storageProvider;
    }

    private readonly IStorageProvider _storageProvider;

    public void Do()
    {
        // do things with storage
        this._storageProvider.Storage.ExecuteX();
    }
}

and the registration :
builder.RegisterType<AzureStorageProvider>().As<IStorageProvider>().SingleInstance();
builder.RegisterType<SomeService>().As<ISomeService>().InstancePerRequest();

you can also register a IStorage and let SomeService depends directly on IStorage and use the IStorageProvider as a factory.
builder.Register(c => c.Resolve<IStorageProvider>().Storage).As<IStorage>();


text:
Q: Identity 2.0 Web Api, iOS and Android Clients Facebook app approval always rejected Here is our setup:
1) a Web Api project with ASP.NET Identity 2.0 with external login support for Facebook.
2)A native iOS App and a native Android App
We are using the appid and secret in the web api and the identity Facebook authorization options. and using web views to do the login process for Facebook.  However, we are also, after the user is authenticated, allowing them to share different pieces of the application to Facebook.  Currently, the website shows the scope of publish_actions, user_videos and user_photos.
Facebook is telling us that custom web views are not okay, and that we have to use the native SDK's on all of them.  What's the purpose of identity providing the ability to utilize getting external accounts and access tokens if you can't even use them on a mobile app?  All of our code that does the sharing process happens on the actual controllers in the web api project. We display a popup that allows the user to enter the text that gets posted, just as Facebook describes.
How can we submit a Facebook App that will explain to them that the website is the actual application that utilizes the Facebook actions we are requesting?
Is this even possible?  if not, why is the technology even available to allow external logins via an api, when you'd most likely be using it to service a native mobile client??
Thanks for the help,
Brent

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loading a 64-bit data into a 32-bit register Let's say I have a 3-element array of 64-bit data:
   src    DCQ    0x0200200AD00236DD
          DCQ    0x00003401AAC4D097
          DCQ    0X0001FC219AC931BE

assuming that I know the address of "src" (named srcAdr), I can load the lower 32-bit content of an element of src at a certain index into a register named srcLo by saying:
   LDR    srcLo, [srcAdr, index, LSL#3]

In order to get the higher 32-bit content of this element, I know I can:
   ADD    srcAdrHi, srcAdr, #4
   LDR    srcHi, [srcAdrHi, index, LSL#3]

Question is, is there a more elegant way to do this? Say, for example, in one instruction?

A: Following my comment: I do not think you can do without an extra instruction here if for whatever reason you must work with the data as with a uint64_t array, using an index.
For a 'C' function:
int foo(unsigned long long *srcT, int index) {
  unsigned int temp=0;
  temp = (unsigned int)(srcT[index]);
  temp += (unsigned int)(srcT[index] >> 32);
  return temp;
}

The compiler (ARM gcc 8.2 -O3 -mcpu=arm7tdmi) produced:
foo:
    add     r3, r0, r1, lsl #3
    ldr     r3, [r3, #4]
    ldr     r0, [r0, r1, lsl #3]
    add     r0, r0, r3
    bx      lr

As you can see it also produced an extra instruction (add) to access the 'high half'.
The exact sequence of instructions would, of course, depend on what manipulations are performed on the array. If you'd walk through it in a loop you'd most likely get ldm + add Rx,#8, etc.


text:
Q: Which is correct between Case A and Case B? Based on the following sentence, which analysis is correct, Case A or Case B?

The few minutes of attention he is giving you is sacrificial.

Case A:

*

*core noun : attention

*determiner : the few minutes of

So, Main verb is "singular is"
Case B:

*

*core noun : the few minutes

*determiner : of attention

So, Main verb is "singular is" (I think "few minutes" is considered singular noun)
I want to know this because It's a grammar test - The few minutes of attention he is giving you [are / is] sacrificial. So, two types of explanation are presented.
I want to know it more clearly with pure curiosity. (although not useful for practical English or English real life)


text:
Q: Compiling celery worker with pyinstaller I am trying to compile a script that starts a celery worker pool using Pyinstaller. The issue seems to be related to spawning new processes.
My code:
from multiprocessing import freeze_support
import app

if __name__ == "__main__":
    freeze_support()
    app.celery.worker_main(
        argv=['--broker=redis://localhost:6379', '--loglevel=DEBUG']
    )

The script compiles and launches but then I get a RuntimeError:
Traceback (most recent call last):
File "c:\users\nbrown\documents\trach_and_trace\lib\site-packages\celery\worker\__init__.py", line 206, in start
    self.blueprint.start(self)
File "c:\users\nbrown\documents\trach_and_trace\lib\site-packages\celery\bootsteps.py", line 123, in start
    step.start(parent)
File "c:\users\nbrown\documents\track_and_trace\lib\site-packages\celery\bootsteps.py", line 374, in start
    return self.obj.start()
File "c:\users\nbrown\documents\track_and_trace\lib\site-packages\celery\concurrency\base.py", line 131, in start
    self.on_start()
File "c:\users\nbrown\documents\track_and_trace\lib\site-packages\celery\concurrency\prefork.py", line 117, in on_start
    **self .options)
File "c:\users\nbrown\documents\track_and_trace\lib\site-packages\billiard\pool.py", line 968, in __init__
    self._create_worker_process(i)
File "c:\users\nbrown\documents\track_and_trace\lib\site-packages\billiard\pool.py", line 1064, in _create_worker_process
    w.start()
File "c:\users\nbrown\documents\track_and_trace\lib\site-packages\billiard\process.py", line 137, in start
    self._popen = Popen(self)
File "c:\users\nbrown\documents\track_and_trace\lib\site-packages\billiard\forking.py", line 242, in __init__
    cmd = get_command_line() + [rhandle]
File "c:\users\nbrown\documents\track_and_trace\lib\site-packages\billiard\forking.py", line 356, in get_command_line
    is not going to be frozen to produce a Windows executable.'")
RuntimeError: Attempt to start a new process before the current process has finished its bootstrapping phase. This probably means that have forgotten to use the proper idiom in the main module:
    if __name__ == __main__:
        freeze_support()
    The "freeze_support()" line can be omitted if the program is not going to be frozen to produce a Windows executable.

These errors occur in some sort of infinite loop. My best guess about how to solve this issue is to put a freeze_support call somewhere else, but after looking through all files in the traceback I see no obvious places to do this. Any suggestions about alternate ways to invoke the worker pool that might work would also be much appreciated.

A: I encountered the same problem. After several hours of research, I got the solution as following:
from billiard import freeze_support
# define your celery app here
# ...
if __name__ == "__main__":
    freeze_support()
    app.celery.worker_main(
        argv=['--broker=redis://localhost:6379', '--loglevel=DEBUG']
    )

Don't use freeze_support of multiprocessing! Because worker instances of celery is preforked by biliard module, which is a forked module from multiprocessing. My working enviroment is as following,
1) windows 10, 32 bit
2) python 3.6.5
3) celery version: 3.1.25
After above settings, I got packaged exe which can be run directly. Hope you guys good luck!


text:
Q: Send associative array using ajax The following associative array need to be send to php using:
getsz[Action]="Save";
getsz[Email]="asd@asd.sad";
getsz[Gender]="male"

but rather recieving the needed format The result at php end was:
Array(
[0] => Save
[1] => asd@asd.sad
[2] => male)

I have sent data using phpliveX library.

  getuserdata.saveuserdata(getalsz,{onUpdate:function(response,root){               }});

where getuserdata is ajaxified object of class to which saveuserdata function belongs.
I want to achieve this result
    Array(
[Action] => Save
[Email] => asd@asd.sad
[Gender] => male)

Edit: getuserdata is object
saveuserdata is function of class to which the object getuserdata
function saveuserdata($userdata)
{print_r($userdata);
}


text:
Q: Debian can't connect to internet using LAN I have a headless Raspberry Pi using Debian Wheezy.
I have a wifi dongle and if I connect my Raspberry using it, everything works fine: I can connect to the Internet, I can ping, I can update.
However, if I get down my wifi and set up the lan interface, I lost my internet connection.
I still can connect to it locally, using my laptop, but the connection doesn't exit (ie ping is not working).
Some useful info:
cat /etc/network/interfaces
auto lo
auto eth0

iface eth0 inet static
      address 192.168.0.105
      netmask 255.255.255.0
      gateway 192.168.0.1

ping www.google.com
(nothing request timed out)

ifconfig
eth0      Link encap:Ethernet  HWaddr b8:27:eb:a2:b5:20
          inet addr:192.168.0.105  Bcast:192.168.0.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1130 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1116 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:97223 (94.9 KiB)  TX bytes:146140 (142.7 KiB)

ping 192.168.0.1
PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data.
^C
--- 192.168.0.1 ping statistics ---
19 packets transmitted, 0 received, 100% packet loss, time 18007ms

cat /etc/resolv.conf
nameserver 8.8.8.8

netstat -r
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
default         192.168.0.1     0.0.0.0         UG        0 0          0 eth0
192.168.0.0     *               255.255.255.0   U         0 0          0 eth0

well, I think that's all...
Any ideas?

A: The 100% packet loss, when you ping your router, is a concern.  It indicates connectivity issues.  This can be caused by a bad cable (try a different one), MAC filtering being enabled in your router, a bad Ethernet port in either your Pi or your router, a bad iptables config, or a number of other issues.  Does anything else work using that router port and cable?


text:
Q: How do I display large numbers in a dataframe in R? I have a dataset that contains loads of tweet-IDs and user-IDs from Twitter. When loading the dataframe in R it projects the numbers e.g. like this "1.236967e+18". Since it is not a number but an ID i need the complete numbers in order to download the tweet texts from the IDs. I tried this:
daytwo <- read.table(file = 'ids_2020-03-09.csv', sep = ';', header = TRUE, as.is = !stringsAsFactors)

However I get the error that it cannot find stringsAsFactors. I assumed that that argument was the key to project the complete numbers
Error in read.table(file = "ids_2020-03-09.csv", sep = ";", header = TRUE,  :
  Object 'stringsAsFactors' not found

If I dont add the stringsAsFactors argument it imports the data with the +18 projection. How can I change that for the whole dataset at once? I already tried to make changes in Excel but R always changes it back when importing. Thanks!

A: It is probably due to the fact that your ID names are viewed as numeric values in R. Have you tried converting them to a character or factor? Something like this may help:
 daytwo$tweetID = as.factor(daytwo$tweetID)


text:
Q: Python + uwsgi - multiprocessing and shared app state We have a flask app running behind uwsgi with 4 processes. Its an API which serves data from one of our two ElasticSearch clusters.
On app bootstrap each process pulls config from external DB to check which ES cluster is active and connects to it.
Evey now and then POST request comes (from aws SNS service) which informs all the clients to switch ES cluster. That triggers the same function as on bootstrap - pull config from DB reconnect to active ES cluster.
It works well running as a single process, but when we have more then one process running only one of them will get updated (the one which picks up POST request)... where other processes are still connected to inactive cluster.
Pulling config on each request to make sure that ES cluster we use is active would be to slow. Im thinking to install redis locally and store the active_es_cluster there... any other ideas?

A: I think there are two routes you could go down.

*

*Have an endpoint "/set_es_cluster" that gets hit by your SNS POST request. This endpoint then sets the key "active_es_cluster", which is read on every ES request by your other processes. The downside of this is that on each ES request you need to do a redis lookup first.

*Have a seperate process that gets the POST request specifically (I assume the clusters are not changing often). The purpose of this process is to receive the post request and just have uWSGI gracefully restart your other flask processes.
The advantages of the second option:

*

*Don't have to hit redis on every request

*Let uWSGI handle the restarts for you (which it does well)

*You already setup the config pulling at runtime anyway so it should "just work" with your existing application


text:
Q: Exclude Directories from a Scheduled Github Action I am creating a github action to run on a schedule. The purpose of the action is to pull my pypi package pip install alphavantage_api_client then run python app.py to verify my published package is working correctly.  To make this work, I need to exclude the internal client source code with something like paths-ignore but it's not working.  How do I exclude a directory within a github action? Here is my github action config:
name: Daily End to End Tests with Alphavantage API PyPi

on:
  schedule:
    - cron: "0 */12 * * *"
  paths-ignore:
    - alphvantage_api_client

permissions:
  contents: read

env:
  ALPHAVANTAGE_API_KEY: "${{ secrets.ALPHAVANTAGE_API_KEY }}"

jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    environment:
      name: "Daily End to End Tests"
    steps:
      - uses: actions/checkout@v3
      - name: Set up Python 3.10
        uses: actions/setup-python@v3
        with:
          python-version: "3.10"
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install alphavantage_api_client
          python app.py

The error i get from the above is a syntax error with the paths-ignore, so i can see there is a problem.
I've referenced the documentation here
https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#example-excluding-paths=
but i don't see a way to exclude paths for a scheduled action. Can someone point me in the right direction?


text:
Q: Pass function to map Why aren't the two following statements equivalent:

const output1 = [..."123"].map(parseInt);
const output2 = [..."123"].map(e => parseInt(e));

console.log(output1);
console.log(output2);

What concept am I missing?

A: map will pass the index it is currently looking at as the second argument to the callback function.
parseInt takes an optional second argument which sets the radix (number base) it is parsing from.


text:
Q: abrir otra app desde app genexus Estimados desde mi app desarrollada en genexus requiero abrir otra app,

*

*si no esta instalada - abrir la direccion en playstore para instalas

*si esta instalada abrir la app desde mi app propia

He utilizado interopen
https://wiki.genexus.com/commwiki/servlet/wiki?23733,Interop.Open+method
Tengo las siguientes dudas,

*

*para el punto 1 como logro que me abra el playstore direccionada a la app para instalar

*para el punto 2, como identifico el appid de la aplicacion que quiero abrir

Se agracede los comentarios


text:
Q: What is optocoupler and how it is used? Im curious about optocoupler.
What is optocoupler,why and how it is used in electronic circuits ?

A: an optocoupler is a device used when you want to electrically isolate a circuit from another circuit that you want to send an electric signal
when you turn on the led it sends photons to the phototransistor, these phototransistor which is like a normal transistor but its "base current" is the light emitted by the led, in this way you can use it as an isolated switch between two circuits

using an optocoupler to control a 12v load with a 3v3 signal

A:
What is an optocoupler?

It's a device that couples an electronic signal from an input to an output optically.  In practice, that means it has an LED for an input, a photodiode or phototransistor for a detector, and possibly some logic or other devices conditioning the output.

How is it used in electronic circuits?

It's used when you need to communicate between two circuits while maintaining electrical isolation, either as a safety isolation or as a designer convenience.


text:
Q: upload from iPad to VPN? The setup:
I'm working on an app that has to run on a tablet. One section requires that a file (typically a picture) get uploaded to a central server. No big deal, right?
The catch:
The tablet is hooked up to a router (actually a fanless PC) that is on a VPN. The only connection to said server is via this VPN. In other words, the tablet itself has no connection to the VPN - only the router does.
The question:
Is there a 'direct' way to upload from the tablet -> server?
Displaying the pictures will be a challenge as well. For example,
<img src="http://serverip/picture.jpg">

...isn't going to work.
Suggestions? Maybe some sort of upload->scp->server? Perhaps some routing table magic?

A: FWIW: The answer is here. Use mod_proxy on the router / apache server to redirect from your VPN-less client to the VPN-only server.


text:
Q: Unable to make tree with closure-table in typeorm I'm currently working on a project where I need a tree in my database. To me, closure-table is the best bet because I will, at some point need multiple roots in the graph.
I am using typeorm 0.2.45 since nestJs doesn't support 0.3.* yet.
When adding entities to the database, without linkage, no problem:
// ./entity/Node.ts
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity, Tree, PrimaryColumn, TreeParent, TreeChildren } from "typeorm"

@Entity()
@Tree("closure-table")
export class Node extends BaseEntity {

    @PrimaryColumn()
    name: string

    @TreeParent()
    parent: Node

    @TreeChildren()
    children: Node[]

}

import { AppDataSource } from "./data-source"
import { Node } from "./entity/Node"

AppDataSource.connect().then(async (conn) => {
    const rNode = conn.getTreeRepository(Node)

    await rNode.createQueryBuilder().delete().execute()

    const [root, child] = await Promise.all(['root', 'child'].map(async (name) => {
        await rNode.insert({name})
        return rNode.findOne(name)
    }))

    console.log(await rNode.findTrees())
}).catch(error => console.log(error))

yields
[
  Node { name: 'root', children: [] },
  Node { name: 'child', children: [] }
]

But as soon as I try to add relations within the tree, all goes bad..
import { AppDataSource } from "./data-source"
import { Node } from "./entity/Node"

AppDataSource.connect().then(async (conn) => {
    const rNode = conn.getTreeRepository(Node)

    await rNode.createQueryBuilder().delete().execute()

    const [root, child] = await Promise.all(['root', 'child'].map(async (name) => {
        await rNode.insert({name})
        return rNode.findOne(name)
    }))

    child.parent = root;
    await rNode.save(child);

    console.log(await rNode.findTrees())
}).catch(error => console.log(error))

Yields
[ Node { name: 'root', children: [] } ]

And the table node_closure is completely empty (note that when filling it properly I do have the tree appearing).
What have I done wrong ?
Thanks

A: Found the answer, in fact it seems that using repository.insert does not properly updates the closure table (supposed to contain identity relation).
Since identity does not exist, it cannot be propagated when changing parent.
Corrected code is
import { AppDataSource } from "./data-source"
import { Node } from "./entity/Node"

AppDataSource.connect().then(async (conn) => {
    const rNode = conn.getTreeRepository(Node)

    await rNode.createQueryBuilder().delete().execute()

    const [root, child] = await Promise.all(['root', 'child'].map(async (name) => {
        await rNode.save({name})
        return rNode.findOne(name)
    }))

    child.parent = root;
    await rNode.save(child);

    console.log(await rNode.findTrees())
}).catch(error => console.log(error))

Be careful though, since save is an equivalent of upsert and can and will update an entity if an entity with same primary key is found.


text:
Q: EssentialSSL Intermediate CA Where can i find the EssentialSSL Intermediate CA?
I downloaded the bundle from https://support.comodo.com/index.php?/Default/Knowledgebase/Article/View/979/108/domain-validation-sha-2 , then executed this in my mac
cat comodo-rsa-domain-validation-sha-2-w-root.ca-bundle /usr/local/etc/openssl/cert.pem  > allcacerts.crt

Then I verified my EssentialSSL cert via
openssl verify -CAfile allcacerts.crt example_com.crt

But I get a
example_com.crt: OU = Domain Control Validated, OU = Hosted by Crazy Domains FZ-LLC, OU = EssentialSSL, CN = example.com
error 20 at 0 depth lookup:unable to get local issuer certificate

Additional Info:
I downloaded the Intermediate CA for EssentialSSL and tried it on the certificate that I got and I still was not able to verify it. Seems like the Intermediate CA for this EssentialSSL needs to come from the original vendor CrazyDomains.com.au which I'm still in the process of getting. But if you can direct me where I can get that, that would be great. Thanks!


text:
Q: How to execute this curl command with c# - http post with image and parameters I am trying to upload my images to deviantart
They give below curl command as example to upload stash
I got my access_token already however i don't know how can i post this with either using asp.net or C#
Help is appreciated
I need to upload image along with parameters
Here the curl command they gave as example
 curl https://www.deviantart.com/api/v1/oauth2/stash/submit \
-F "title=My great stash item&artist_comments=This is a great image&keywords=test image" \
-F access_token=Alph4num3r1ct0k3nv4lu3 \
-F "test=@path/to/image.png"

c# .net 4.5

A: You can send a POST request using WebClient like following.
using (var webcl = new WebClient())
{
    var inputdata = new System.Collections.Specialized.NameValueCollection();
    inputdata["title"] = "My great stash item";
    inputdata["artist_comments"] = "This is a great image";
    inputdata["keywords"] = "test image";
    inputdata["access_token"] = "Alph4num3r1ct0k3nv4lu3";
    inputdata["test"] = "path/to/image";

    var output = webcl.UploadValues("https://www.deviantart.com/api/v1/oauth2/stash/submit", "POST", inputdata);
}

However, when i tried this, I got 401 unauthorized error. Might be access_token got expired.
Because when i tried samething with curl,i also got following error.

{"error":"invalid_token","error_description":"Expired oAuth2 user
  token. The cli ent should request a new one with an access code or a
  refresh token.","status":" error"}


text:
Q: Implement a List similar to Android Applications Menu There is a particular functionality from Android that I would like to implement in a Xamarin.Forms/Xamarin.Android project
It is a List or Grid or some Layout that have a Scroll Index, like this:

I already create a ListView with this "FastScroll Index" via Custom Renderer, which contains an Adapter and also a scroll listener.
Is there any chance to get something like in the image?


text:
Q: Html5 video player have to press pause twice when on autoplay I am using the code in this codepen http://codepen.io/frytyler/pen/juGfk to make custom controls for my video player which works great except when I have the video set to "autoplay" like in the code below. It plays the video but I then have to press pause twice to pause it, how would I modify the code to solve this?
<video id="myVideo" autoplay controls preload="auto" poster="http://s.cdpn.io/6035/vp_poster.jpg" width="380" >

A: http://codepen.io/anon/pen/PZwxed
It's quick solution for screen, adding this snippet at last line of js inside of dom.ready().
     //doubleclick
    $('#myVideo').click(function () {
       if ($("#myVideo").get(0).paused) {
           $("#myVideo").get(0).play();
       }
    });

     $('#myVideo').dblclick(function () {

       $("#myVideo").get(0).pause();

});

there a problem, play/pause button may act weird when you click button after of click twice in screen, you need to assign play/pause button class to display properly or it would look best if you hide this button.
EDIT:
You may manipulate play/pause button in following code:
var vid = document.getElementById("myVideo");
     vid.onplaying = function() {
  //call when video is playing, it should show pause icon in button like .addClass and .removeClass
};
     vid.onpause = function() {
  //call when video is paused, it should show play icon in button like .addClass and .removeClass
};


text:
Q: CheckedTextView Custom Layout for ListView I am trying to create a layout for a ListView row which contains a CheckedTextView with a couple of TextViews. I wrapped these views in a RelativeLayout. Running the application resulted in nothing being checked.
I tried looking around for a solution and it appears that if the CheckedTextView is not the top level view of the layout, you might need to create a custom Layout that implements the Checkable interface. I tried following the instructions here but with no luck. In my case, the TextViews I am trying to set text on are always null in my ArrayAdapter so I am obviously not doing it right.
Any idea what I am doing wrong? Does anyone have an example that fits my scenario that I could follow?
custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="8dp">

<LinearLayout
    android:id="@+id/checkedTextViewLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_centerInParent="true"
    android:layout_margin="8dp">

    <CheckedTextView
        android:id="@+id/checkedTextView"
        android:layout_width="wrap_content"
        android:layout_height="?android:attr/listPreferredItemHeightSmall"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:gravity="center_vertical"
        android:checkMark="?android:attr/listChoiceIndicatorSingle"
        android:paddingStart="?android:attr/listPreferredItemPaddingStart"
        android:paddingEnd="?android:attr/listPreferredItemPaddingEnd" />

</LinearLayout>

<LinearLayout
    android:id="@+id/headingLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@id/checkedTextViewLayout"
    android:layout_alignParentStart="true"
    android:layout_margin="8dp"
    android:layout_toStartOf="@id/checkedTextViewLayout"
    android:orientation="vertical">

    <TextView
        android:id="@+id/heading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/subheading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>

CustomLayout.java
public class CustomLayout extends RelativeLayout implements Checkable {

public CustomLayout(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    initializeViews(context, attrs);
}

private void initializeViews(Context context, AttributeSet attrs) {
    LayoutInflater.from(context).inflate(R.layout.custom_layout, this);
    checkedTextView = this.findViewById(R.id.checkedTextView);
    heading = this.findViewById(R.id.heading);
    subheading = this.findViewById(R.id.subheading);
}...
}

list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<com.example.android.example.CustomLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/custom_layout_id">
</com.example.android.example.CustomLayout>

CustomArrayAdapter.java
if (convertView == null) {
        viewHolder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.list_row, parent, false);
        viewHolder.customeLayout = convertView.findViewById(R.id.custom_layout_id);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    if (data != null) {
        viewHolder.customLayout.getHeading().setText("Order # " + data.getOrderNumber());
        viewHolder.customLayout.getSubheading().setText("Subheading");
    }

A: Try this:-
custom_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?android:attr/selectableItemBackground"
android:padding="8dp">

<CheckedTextView
    android:id="@+id/checkedTextView"
    android:layout_width="wrap_content"
    android:layout_height="?android:attr/listPreferredItemHeightSmall"
    android:layout_alignParentEnd="true"
    android:layout_centerInParent="true"
    android:layout_margin="8dp"
    android:checkMark="?android:attr/listChoiceIndicatorSingle"
    android:gravity="center_vertical"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:textAppearance="?android:attr/textAppearanceListItemSmall" />

<LinearLayout
    android:id="@+id/headingLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_margin="8dp"
    android:layout_toStartOf="@id/checkedTextView"
    android:orientation="vertical">

    <TextView
        android:id="@+id/heading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/subheading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>
</RelativeLayout>

CustomLayout.java: [I got the idea from this link: Android Checkable LinearLayout states
public class CustomLayout extends RelativeLayout implements Checkable {

private CheckedTextView checkedTextView;
private TextView heading;
private TextView subheading;

public CustomLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    setClickable(true);
    initializeViews(context, attrs);
}

private void initializeViews(Context context, AttributeSet attrs) {
    LayoutInflater.from(context).inflate(R.layout.custom_layout, this);
    checkedTextView = this.findViewById(R.id.checkedTextView);
    heading = this.findViewById(R.id.heading);
    subheading = this.findViewById(R.id.subheading);
}

public TextView getHeading() {
    return heading;
}

public TextView getSubheading() {
    return subheading;
}

@Override
public void setChecked(boolean b) {
    checkedTextView.setChecked(b);
}

@Override
public boolean isChecked() {
    return checkedTextView.isChecked();
}

@Override
public void toggle() {
    checkedTextView.setChecked(!checkedTextView.isChecked());
}

@Override
public boolean performClick() {
//        Toast.makeText(getContext(),"click",Toast.LENGTH_SHORT).show();
    toggle();
    return super.performClick();
}

}

Hope that helps!


text:
Q: How to keep div inside container frames using javascript/jquery I have a simple (i think) question?
I have a conatainer 800x400 and inside is a div 10x10.
The div inside is moving by pressing the arrow keys ,but what i like to do is
keep the div inside the frames of container.

$(document).ready(function () {
  go_kw();

});

function go_kw() {
  move_me();
}

function move_me() {
  $(document).on('keydown', function (event) {

    let key = event.which;
    let qt = $('#qw');

    if(key == 37){
      qt.css('left', '-=1');
    }else if(key == 38){
      qt.css('top', '-=1');
    }else if(key == 39){
      qt.css('left', '+=1');
    }else if(key == 40){
      qt.css('top', '+=1');
    }

  });
}
#container {
    position: relative;
    border: 1px solid #000000;
    width: 800px;
    height: 400px;
    margin: 50px auto;
}
#qw {
    position: absolute;
    width: 10px;
    height: 10px;
    top: 0;
    left: 0;
    background-color: #ff0000;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

and my goal is to do this as simple it can be done.
greetz!

A: You can use Math.max (which selects the highest value of two arguments) and Math.min (which does the opposite), like so (for horizontal movement):
if(key == 37){
    qt.css('left', Math.max(qt.css('left') - 1, 0));
}
else if(key == 39){
    qt.css('left', Math.min(qt.css('left') + 1, 800));
}

A: You need to check that you are not past your div borders before moving parseInt(qt.css('left')) > 0
Snippet:

$(document).ready(function () {
  go_kw();

});

function go_kw() {
  move_me();
}

function move_me() {
  $(document).on('keydown', function (event) {

    let key = event.which;
    let qt = $('#qw');

    if(key == 37 && parseInt(qt.css('left')) > 0){
      qt.css('left', '-=1');
    }else if(key == 38 && parseInt(qt.css('top')) > 0){
      qt.css('top', '-=1');
    }else if(key == 39 && parseInt(qt.css('left')) < 790){
      qt.css('left', '+=1');
    }else if(key == 40 && parseInt(qt.css('top')) < 390){
      qt.css('top', '+=1');
    }

  });
}
#container {
    position: relative;
    border: 1px solid #000000;
    width: 800px;
    height: 400px;
    margin: 50px auto;
}
#qw {
    position: absolute;
    width: 10px;
    height: 10px;
    top: 0;
    left: 0;
    background-color: #ff0000;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

A: The easiest way should be to test if your positions are superior than 0 for left and top and lower than #container width and height for respectively right and bottom.

$(document).ready(function () {
  go_kw();

});

function go_kw() {
  move_me();
}

function move_me() {
  $(document).on('keydown', function (event) {

    let key = event.which;
    let qt = $('#qw');

    let maxHeight = $('#container').height();
    let maxWidth = $('#container').width();

    if(key == 37 && qt.position().left > 0){
      qt.css('left', '-=1');
    }else if(key == 38 && qt.position().top > 0){
      qt.css('top', '-=1');
    }else if(key == 39 && qt.position().left < maxWidth){
      qt.css('left', '+=1');
    }else if(key == 40 && qt.position().left < maxHeight){
      qt.css('top', '+=1');
    }

  });
}
#container {
    position: relative;
    border: 1px solid #000000;
    width: 800px;
    height: 400px;
    margin: 50px auto;
}
#qw {
    position: absolute;
    width: 10px;
    height: 10px;
    top: 0;
    left: 0;
    background-color: #ff0000;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

A: I would create a field with a value for left and top and check it during change like so (I've made the container smaller for easier testing, can be enlarged in css):

$(document).ready(function() {
  go_kw();

});

function go_kw() {
  move_me();
}

var qwWidth = $('#qw').width();
var qwHeight = $('#qw').height();
var maxLeft = $('#container').width() - qwWidth;
var maxTop = $('#container').height() - qwHeight;

var currentPos = {
  left: 0,
  top: 0
};

function move_me() {
  $(document).on('keydown', function(event) {
    let key = event.which;

    if (key == 37) {
      changePos('left', -1, maxLeft);
    } else if (key == 38) {
      changePos('top', -1, maxTop);
    } else if (key == 39) {
      changePos('left', 1, maxLeft);
    } else if (key == 40) {
      changePos('top', 1, maxTop);
    }

    $('#qw').css(currentPos);
  });
}

function changePos(prop, changeVal, maxVal) {
  var newVal = currentPos[prop] + changeVal;

  if (newVal < 0) {
    currentPos[prop] = 0;
  } else if (newVal > maxVal) {
    currentPos[prop] = maxVal;
  } else {
    currentPos[prop] = newVal;
  }
}
#container {
  position: relative;
  border: 1px solid #000000;
  width: 80px;
  height: 40px;
  margin: 50px auto;
}

#qw {
  position: absolute;
  width: 10px;
  height: 10px;
  top: 0;
  left: 0;
  background-color: #ff0000;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>


text:
Q: Circular image edges are jagged in Alloy appcelerator I am trying to make an circular image view in Alloy appcelerator formerly Titanium like this
XML
<ImageView id="profile_photo"  />

TSS
"#profile_photo_view_holder":{
    width: 80,
    height: 80,
    borderRadius: 40,
    borderWidth:2,
    borderColor:"black"
}

The image view is rendering properly but jaggy in its edges looks like an anti aliasing problem.
I use image factory module to scale down also but no luck.
resizedImage = ImageFactory.imageAsResized(blob, {
    width : 80,
    height : 80,
    quality : 0.9
});
$.profile_photo.image = resizedImage;

A: on Android you will need to make use of a module to achieve it.
This module is quite new and looks great:
https://github.com/m1ga/com.miga.roundview
I'm using this one in my project:
https://github.com/snowciety/sc.roundedavatar
Hope it helps


text:
Q: How to save a image on server with javascript? I'm working in a little web app that generates an base64 image, I'm using blob to put it back into a file (is a .png but I haven't renamed it yet), now I'm trying to save it on my sever Any ideas or different approaches?
This is the script:
var img = document.getElementById("MyPix");
    img.onclick = function() {

        var image_data = atob(img.src.split(',')[1]);
        var arraybuffer = new ArrayBuffer(image_data.length);
        var view = new Uint8Array(arraybuffer);
        for (var i=0; i<image_data.length; i++) {
            view[i] = image_data.charCodeAt(i) & 0xff;
        }
        try {
            var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
        } catch (e) {
            var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
            bb.append(arraybuffer);
            var blob = bb.getBlob('application/octet-stream');
        }

        var url = (window.webkitURL || window.URL).createObjectURL(blob);

        valor = (document.getElementById("link").value = url)

        location.href = valor;

    };

I'm not very good with js so if you want to have a better idea visit the project clicking here its all javascript so just see source code.

A: you can't save to your server with just client-side JavaScript. Form the data you want to save in Javascript, then POST that to your server with a call to a page that you write that can turn POST data into a file on your filesystem, so in your case a .php file with code that looks for $_POST data and then writes that to file. After making sure it's safe, because anyone will be able to post data to that page, not just people using your webpage.


text:
Q: Powershell script for checking AD replication I adapted an AD replication powershell script I found online to include the code below:
function ExitWithCode {
param
(
    $exitcode
)

$host.SetShouldExit($exitcode)
exit
}

function Write-Log {
<#
.SYNOPSIS
    Write-Log writes a message to a logfile

.DESCRIPTION
    The Write-Log function is designed to add logging capability to other scripts.
    In addition to writing output and/or verbose you can write to a log file for
    later debugging.
#>
[CmdletBinding()]
Param
(
    [Parameter(Mandatory = $true,ValueFromPipelineByPropertyName = $true)]
    [ValidateNotNullOrEmpty()]
    [Alias('LogContent')]
    [string]$Message,

    [Parameter(Mandatory = $false)]
    [ValidateSet("Error", "Info", "Status")]
    [string]$Level = "Info",

    [Parameter(Mandatory = $false)]
    [Alias('LogPath')]
    [string]$Path = 'C:\dataloop\ADHealthCheck.log'

)

BEGIN {

    [string]$FormattedDate = Get-Date -Format "dd-MM-yyyy HH:mm"

    If (-NOT (Test-Path $path)) {
        Write-Verbose "Creating $Path"
        [System.IO.FileInfo]$LogFile = New-Item $Path -Force -ItemType file
    }
}
PROCESS {
    [string]$LogLine = "$FormattedDate - $Level - $message"
    $LogLine | Out-File -FilePath $Path -Append

    Switch ($Level) {

        "Info" {Write-Verbose $LogLine}
        "Status" {Write-Output $LogLine}
        "Error" {Write-Error $LogLine}
    }
}
END {}
}

function Get-ADHealthCheck {
    [CmdletBinding()]
        param()

        BEGIN {
        Write-Log "Beginning the AD Health Check..."
        }

        PROCESS {
        $DCs = Get-ADDomainController -Filter * |sort name

        Write-Log "$($DCs.Count) Domain Controllers found" -level Info

        $results = @()

        ForEach ($DC in $DCs) {

            Write-Log "Getting replication metadata for $($DC.HostName)" -level Status
            $ReplStatuses = Get-ADReplicationPartnerMetadata -target $DC.HostName -PartnerType Both -ErrorAction SilentlyContinue

            If ($ReplStatuses) {

                 Write-Log "$($ReplStatuses.Count) replication links found for $($DC.HostName)" -level Info

                ForEach ($ReplStatus in $ReplStatuses) {

                    $Partner = $ReplStatus.Partner.Split(",")[1].Replace("CN=","")

                    $results += [pscustomobject] @{
                        'Source DC' = $DC.HostName.ToUpper()
                        'Partner DC' = (Get-ADComputer $Partner).DNSHostName.ToUpper()
                        'Direction' = $ReplStatus.PartnerType
                        'Type' = $ReplStatus.IntersiteTransportType
                        'Last Attempt' = $ReplStatus.LastReplicationAttempt
                        'Last Success' = $ReplStatus.LastReplicationSuccess
                        'Last Result' = $ReplStatus.LastReplicationResult
                    }
                }
            }

            Else {

                Write-Log "Unable to get replication status for $($DC.HostName)" -level Error
                $results += [pscustomobject] @{
                    'Source DC' = $DC.HostName.ToUpper()
                    'Partner DC' = "N/A"
                    Direction = "N/A"
                    Type = "N/A"
                    'Last Attempt' = "N/A"
                    'Last Success' = "N/A"
                    'Last Result' = "N/A"
                }
             }
        }

        ForEach ($result in $results) {

            If ("$($results.'Last Result')" -eq "0") {

                Write-Log "There were no replication issues found" -Level Info
                ExitWithCode -exitcode 0
            }

            Else {

                Write-Log "These domain controllers have replication errors. Please review them..." -Level Error
                $error = $results | where {"$($_.'Last Result')" -ne "0"} | select 'Source DC','Partner DC','Direction' | ft -AutoSize
                Write-Log $error -Level Error
                ExitWithCode -exitcode 2
            }
        }
    }
}
Get-ADHealthCheck

Basically the only issue I'm having now is the last if/else block. I need it to loop through every entry in the $results hash table and if the "Last Result" key only contains "0", then exit with code 0. If it finds any other values, it should output the source, partner, and direction value(s) fromt he hash table.
Currently, if it encounters an issue, it jumps to the else block, outputs the information requested and then runs the ExitWithCode function which eventually kills the script so anything that comes after the error is not checked.
I've been looking at this too long and have been unsuccessful so I'm throwing it out to there since it may just be something simple I'm missing.

A: Look at your for loop variables

ForEach ($result in $results) {

For each single $result in the $results. In the following if statement you should be looking at one $result but instead you are doing a comparison against all results. Your subexpression syntax here is also not required.

 If ("$($results.'Last Result')" -eq "0")

Note that this is perfectly valid code but it will not get you the results you expect. It will return all 'last result's that are 0. So if even one in the whole collection is 0 the true condition will always  fire.
So lets just make some minor changes and use the singular $result
If ($result.'Last Result' -eq "0")

That should get you the result you are looking for. I notice that you are looking for equality with the string 0. That will not be an issue here since the LHS sets the type for the comparison. Have a look at this other post to get a better understanding of what PowerShell does here.
Why is $false -eq "" true?
If your last result was the int 0 this would be true
0 -eq "0"

Your logic appears to be flawed as you have mentioned in comments on how to handle overall success and individual failures. Instead of looping through the results like you were I think we need to check the collection as a whole and loop only if errors are encountered.
# Lets check if any of the results contain failure
$failedChecks = $results | Where-object{$_.'Last Result' -ne 0}

# Evaluate $failedChecks as a boolean. If there are no failed checks Else can be assumed that everything is fine.
if($failedChecks){
    Write-Log "These domain controllers have replication errors. Please review them..." -Level Error
    $error = $failedChecks | select 'Source DC','Partner DC','Direction' | ft -AutoSize | Out-String
    Write-Log $error -Level Error
    ExitWithCode -exitcode 2
} else {
    Write-Log "There were no replication issues found" -Level Info
    ExitWithCode -exitcode 0
}


text:
Q: Path Integral in QM - Fourier Transform with respect to a Function? Consider the Fourier transform of a multivariable probability density function $Pr(\{x_n\})$, i.e. its characteristic function:
$\int Pr(\{x_n\})e^{-i2\pi\sum\limits_{n}f_nx_n}\prod\limits_{n}{dx_n}$,
which can be considered a Fourier transform with respect to a vector variable $\vec{x}$.
Now suppose instead, we consider a probability density function defined over the space of all functions of t over the region from t = 0 to t = t, $Pr[x(t)]$. We can define a path integral as follows:
$\int Pr[x(t)]e^{-i2\pi\int\limits_{0}^tL(x,\dot{x})dt}D[x(t)]$.
If $Pr[x(t)]$ is constant across all functions, then the integral is just the usual Feynman path integral. In analogy to the above, would it be possible to consider this a Fourier transform with respect to a function, i.e. the characteristic function of $Pr[x(t)]$?

A: So, the main problem here is a QM amplitude (as one derives from the path integral) is a complex number, while a Fourier transform outputs a function. But nonetheless, let's see what analogy can be drawn:
We'll assume without loss of generality that we're working with one particle. So, in classical mechanics, the Lagrangian, $L(x,\dot{x})$ may be related to the Hamiltonian via Legendre transform, i.e. $L(x,\dot{x}) = p\dot{x} - H(x,p)$, where p is the momentum and is now considered to be independent of x.
Substituting into the formula for the path integral I provided in the OP, we get:
$\int Pr[x(t)]e^{-i2\pi\int\limits_{0}^t(p\dot{x} - H)dt}D[x(t)]$,
which may be rewritten as:
$\int Pr[x(t)]e^{-i2\pi\int\limits_{0}^tpdx - Hdt}D[x(t)]$.
If p and H were considered to be totally independent variables of x(t), then yes, you could consider something like this as a characteristic function on path space. The problem is, they both vary along each path, and the end result of the integral is a complex number. So the answer to the question as written is "no".
Perhaps someone else has additional insight that I don't?


text:
Q: Javascript Injection Not working on WKWebview on Device, but is working on Simulator We need to set a cookie locally to the application that applies to our webview. We referenced this post. All we need is to inject a cookie. When running on the simulator everything works perfect, but when using a device the cookie fails to inject. This is the code we have so far.
let userContentController = WKUserContentController()
let cookieScript = WKUserScript(source: "document.cookie = 'customCookie'; domain = '.example.com'", injectionTime: .AtDocumentStart, forMainFrameOnly: false)

userContentController.addUserScript(cookieScript)
let webViewConfig = WKWebViewConfiguration()
webViewConfig.userContentController = userContentController
self.webView = WKWebView(frame: CGRectZero, configuration: webViewConfig)


text:
Q: Parse.com equivalent to sql query I want to know how can I achieve the following SQL query on parse,
e.g. assume we have 2 tables/classes in our DB: User, Profile with example values in brackets.
User
- email(tt@tt.com)
- Name(tt)

Profile
 -email(tt@tt.com)
 -age(23)

Sql query,
select User.email,User.name,Profile.age from User
JOIN Profile on User.email = Profile.email
Where User.email = 'tt@tt.com'

The resulting recordset would be "tt@tt.com,tt,23e".
Now, if I want to make the same thing with Parse, or better, how can I achieve this??
I read about these structures but I don't know if they apply to this case and how to use them. I'm developing in Android
any help would be greatly appreciated.

A: If you have pointers to _Users on your Class Profile best method would be this one :
var Profile = Parse.Object.extend("Profile");
var query = new Parse.Query(Profile);
query.equalTo("email", request.params.email);
return query.first().then(null, function(error) {
    return Parse.Promise.error('Sorry, this profile was not found.');
}).then(function(profile) {
    profile.get('_User').fetch().then(function(user) {
        console.log(
            'name : ' + user.get('name') + ' ' +
            'age : ' + profile.get('age')
        );
    });
});

Note for profile.get('_User') your pointer's name may change and not be _User

A: Try this solution.
In User class, create a Pointer to Profile. Then you can query from User class to get Profile.
ParseQuery<User> parseQuery = ParseQuery.getQuery("User");
parseQuery.whereEqualsTo("emai", "youremail@mail.com");

parseQuery.getFirstInBackground(new GetCallback<User>() {
  public void done(User user, ParseException e) {
    if (e != null) {
      Log.d("score", "The getFirst request failed.");
      return;
    }
    Profile profile = (Profile) user.get("profile");
  }
});


text:
Q: Using mod_auth_openidc to authenticate multiple google domains I am using this answer to do authentication for an apache reverse proxy to gerrit. However, I'd like to add a second domain as well -- so authenticate either against foo.com or bar.com (both of which are google apps domains so google is used for both).
I've tried several obvious things like adding multiple OIDCAuthRequestParams lines and then adding several Require statements [Require claim hd:foo.com Require claim hd:bar.com] it just accepts the first one I list and ignores the second domain. When I try to add a comma separated list, it just allows all domains in (ie OIDCAuthRequestParams=foo.com, bar.com). In fact the Require statements don't seem to anything, only the OIDCAuthRequestParams seems to work and only for one domain. Any ideas on how I can make two different domains work given the set up for gerrit as listed above?
I'm using apache2.4 Ubuntu 15.10 and libapache2-mod-auth-openidc 1.6.0 Thanks.

A: Those who are following the gerrit example, what worked for me was to not have a OIDCAuthRequestParams line at all, add the Require claim hd: lines that I needed AND remove the Require valid-user line. If I don't remove the Require valid-user it will allow any google domain including gmail.com.


text:
Q: How to rolling update deployment in kubernetes? apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: test
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app:  test
    spec:
      containers:
      - name:  test
        image: xxx:latest
        ports:
        - containerPort: 80
        imagePullPolicy: Always
      imagePullSecrets:
      - name: aaaa

I use the tag "latest". When I update the image,and the new image is still "latest". When I  "kubectl set image deployments/test test=xxx:latest",nothing happend. What should I do?

A: a RollingUpdate is always triggered when the PodTemplateSpec under template is changed.
While using the :latest tag is not suggested it can still work when using imagePullPolicy: Always and a label which is changed with every image adjustment. Sth like this:
kubectl patch deployment test -p "{\"spec\":{\"template\":{\"metadata\":{\"labels\":{\"date\":\"$(date +%s)\"}}}}}"

A: Rolling update depends on docker image tags. If you're using the latest tag in your deployment, you need to cut a new image with a new version.
The deployment resource can't determine if the images has changed if you're always using the latest tag. As far as k8s is concerned, you're already running an image with the tag latest, so it doesn't have anything to do.
It's highly recommended not to use latest for deployments for this reason. You'll have a much easier time if you version your docker images correctly.


text:
Q: Find the equation of a circle given two points and its radius - based on the coordinates of another circle There is a circle of radius 187.5m and centre $(25.23,188.6)$.
It takes the form  $(x-25.23)^2 +(y-188.6)^2=187.5^2$
There is another circle whose centre is unknown and has a radius of 1750m. This circle intersects with the y axis at $(0,2.05)$ and a point on the original circle. The point on the original circle is the point where the tangent line from point $(0,2.05)$ touches the larger circle. I want to obtain the centre of this circle.
I've created this graphically in CAD software, and the resultant centre should be close to $(87.5028,1749.861)$. I've tried doing this mathematically but i fear I haven't dealt with quadratics in a long time. Sometimes I get close to the point provided by CAD but when verifying the circle equation by plugging the point $(0,2.05)$ back in, it doesn't converge.
I've calculated the tangent point in this case to be $(16.752,1.29$) which I believe is correct.
However my problem lies when trying to get the centre point of the larger circle. If both points are on the circle then the following is true:
$(0-h)^2 + (2.05-k)^2 = 1750^2$
and
$(16.752-h)^2 + (1.29-k)^2 = 1750^2$
I solve for h in terms of k in one equation. Reinput h back into the other equation and solve for k. Once I solve for the values of k, I then solve for h. But I've used online calculators and still can't seem to reconcile the numbers.
Could someone possibly explain if my work is flawed in some way? Or possibly identify that it is possible to get similar numbers to the graphical solution? I would provide the graphic but the scales of the circles are so large it's difficult to see the area I'm concentrating on.
Thanks

A: I couldn't tell you why these calculators that you haven't identified don't give you solutions that match your CAD approximation, but keep in mind that there are two solutions to that equation, corresponding to the fact that there are two circles with the given radius that pass through the two points. When I give your equations to Mathematica to solve, one of the solutions jibes with your CAD numbers. The usual way to go about solving this system by hand is to subtract one equation from the other to get the equation of a line (in fact, the perpendicular bisector of the tangent segment), solve that for one of the variables and back-substitute to get a quadratic equation in one variable.
However, once you have the point of tangency (call it $B$), there's no need to solve any equations at all in order to find the center of the large circle. It can be done with simple vector computations and an application or two of the Pythagorean theorem. Call the known $y$-axis intersection of the large circle $A$. It's center lies somewhere on the perpendicular bisector of $AB$. This line has for a direction vector $(A_y-B_y,B_x-A_x)$. Using your values and normalizing, this gives us the unit vector $\mathbf u\approx(0.0453,0.9990)$. Half of the distance from $A$ to $B$ is $8.385$, so the distance of the large circle's center from the midpoint of $AB$ is $\sqrt{1750^2-8.385^2}\approx1749.98$. The center of the large circle is therefore at $$\frac12(A+B)\pm1749.98\mathbf u.$$ Taking the positive direction along $\mathbf u$ again produces values that are pretty close to your estimate.
Since the distance between $A$ and $B$ is so small relative to the large circle's radius and the tangent line is almost horizontal, you have to take extra care to manage roundoff error in your calculations. Also, there are two tangents to a circle through any exterior point, so as you've described the problem here, there are four solutions. No doubt you have some other critieria with which to select the correct one, but you haven't mentioned them.


text:
Q: Multilevel Column Pivot I am Learning Python using pandas, I do not know, how to pivot a data frame with columns with a multilevel index. I have the following pivot table :
df= df.pivot_table(index=["FECHA",'Planta'],
                              aggfunc = {'Menor_F0' :np.sum, 'Menor_fc' :np.sum,
                              "Total_Muestras " : "count"
                              })

it gives: PD: it is correct
                Menor_F0  Menor_fc  Total_Muestras
FECHA   Planta
01/2014 455            0         0               2
        470            1         2               5
01/2016 455            0         0               1
        470            0         1               2

But I want to visualize it, in this form, how can I do it?
FECHA         01/2014                                           01/2016
         Menor_F0  Menor_fc  Total_Muestras     Menor_F0  Menor_fc  Total_Muestras
PLANTA
455         0         0               2           0         0               1
470         1         2               5           0         1               2

A: You can try stack and unstack:
df.stack().unstack(level=(0,2))


text:
Q: Salt, passwords and security I've read through many of the questions on SO about this, but many answers contradict each other or I don't understand.
You should always store a password as a hash, never as plain text.
But should you store the salt (unique for each user) next to the hashed password+salt in the database. This doesn't seem very clever to me as couldn't someone gain access to the database, look for says the account called Admin or whatever and then work out the password from that?

A: Salt is used to increase the time that an attacker would have to spend to find a password matching the hash stored in database. Typically lookup table such as rainbow table (see http://en.wikipedia.org/wiki/Rainbow_table) is used to achieve this.
What costs time is not the lookup itself, but the time to compute the rainbow table. Adding a salt forces the attacker to recompute a new rainbow table, even if it is known by the attacker who would compromise the database

A: The salt is meant to disturb existing rainbowtables. It's no security threat to know the salt. If you know the salt, you would still need to know the password.

A: A lot of people are saying "to stop rainbow tables" without explaining what rainbow tables do or why this stops them.
Rainbow tables are a clever way of precomputing a large number of hashes and storing them in less memory than would naively be required, and you can use them to very quickly reverse a hash. Tables for bare functions such as hash = md5(password) and hash = sha1(password) are common.
However, they can be generated for ANY hash function which can be described as output = f(input). If you use a site-wide salt for all user passwords, for example hash = md5(salt+password), you could construct a function f, f(password) = md5(salt+password). Therefore you could generate rainbow tables for this function, which would take a long time, but would then let you crack every single password in the database very rapidly.
If the salt is different for each password, you can't generate a rainbow table that will crack all passwords in the database. You could generate a new one for every user but that would be pointless - naive brute-forcing would be no slower. So having a seperate salt for each user stops the rainbow tables attack.
There are several ways to do accomplish this. Popular ways include:

*

*A separate salt for each user, stored alongside their other details in the database: hash = hashfunction(salt + password)

*A global salt and some unique value per user: hash = hashfunction(salt + password + user_id) for example

*A global salt and a per-user salt: hash = hashfunction(global_salt + user_salt + password)
Having a global salt could add a little extra complexity to cracking the passwords, as it could be stored outside of the database (in the code, for example) which attackers may not gain access to in the event of a database breach. Cryptographically I don't think it adds much, but in practice it could slow them down.
Finally, to answer your actual question:
Storing the salt alongside the user data does not weaken the hash. Hash functions are one-way: Given the hash of a password, even an unsalted one, it is very difficult to find that password. The motivation behind salting is not to make an individual hash more secure, but to make the collection of multiple hashes more secure. There are several vectors of attack for a collection of unsalted hashes:

*

*Rainbow tables

*Hashing common passwords (123, password, god) and seeing if any exist in the database, and then compromise those accounts

*Look for identical hashes in the database, which means identical passwords (probably)

A: Well first of all, the primary purpose of the salt is to disable brute-forcing of the passwords, for example it prevents the usage of rainbow tables for quick compromising of a password.
Even if an attacker gains access to a database, it's not that easy to work out the real passwords from the salts (especially if you don't have the code and don't know how the password is hashed). However what I like to do for additional security is to also hash a password with a static hash that is specified in the code. This way it's not enough that you compromise the database. An example of such method (in PHP):
$hashed_password = sha1($user_password . $user_salt . $static_salt);

$user_salt is the salt in the database unique to each user, $static_salt is the salt specified in your code's settings somewhere.

A: Well well well .. so many discussions ... so much information. so many questions ...  i see that after all the questions are answers here is the summary.

*

*Why Salt?

*Why Salt is stored alongwith the hash of (password + salt).

Here is my understanding.

*

*Hackers have rainbow table for all the dictionary words which he made with great great effort. Every rainbow table making gets the hell out of the hacker. In simple words its very tough.

*As by point 1, if we make the hacker compute rainbow table for each user then he'll be getting old by the time he knows the password. And if the user frequently changes the password, then even hacker's grand children will get old by the time they know the password.

*Ok. So use different salt for each user. This makes the hacker use seperate attack to know the password of every single user.

*I see that various readers pointed out , that instead of banging head on every single user a great hacker will put all his effort towards admin account and then he is done :). So in this case, we will go a step ahead and then use some different method to compute the hash. Lets say the salt is not exactly what is stored. It may be half of the actual hash. The other half is stored somewhere else in some other way (computed in some other way). This is just an extra security measure. And we know thwt in current times, the calculation power of computers is increasing. So ethical people know that worlds fastest super computer will take 1 year to crack admin password (just an example). So they force a policy which says change admin password every 3 months. by the time hacker knows the old password , the new one is in effect. Or say the database is compromised, then good guys come to know of it by the time hacker cracks the password. And the good guys changs the things by then ( remember upgrade of alogorithms ..sha1 sha2 and now sha3 ).....

Ok..though not fully complete, but my point is bad guys take lot of time .... but good guys are a step ahead to ensure that they know the technology which bad guys will be using to crack. So just devise a better technology by time.
Take care ....

A: If you don't store the salt, how will you check if the correct password was provided?


text:
Q: Tournament graph question(s) Is a tournament graph the same thing as a directed complete graph? And, do all vertices in a tournament graph have the same number of edges?

A: Unless I'm missing something obvious then the answer to both your questions is "yes"
A tournament graph is defined as a complete graph with a direction chosen for the edges.  Hence it is a directed complete graph.
Wikipedia definition of a Tournament Graph
and since a complete graph has an edge between each vertex, then every vertex has the same number of edges, and this doesn't change when a direction is chosen for the edge.
Wikipedia definition of a Complete Graph


text:
Q: Google Spreadsheet API 500er errors The Google Drive API keeps throwing 500 errors at me and I have run out of ideas.
The returned pages for the 502 error reads:
That's an error. The server encountered a temporary error and could not complete your request.
Please try again in 30 seconds.
That's all we know.

Sometimes I also get a 500 whose error message basically says "no idea" and does not even suggest retry.
I made a toy example to reproduce the problem:
import gspread
import random
import json
from oauth2client.client import SignedJwtAssertionCredentials

def main():

    json_key = json.load(open("/home/me/.credentials/API Project-56725514b81f.json"))
    scope = ['https://spreadsheets.google.com/feeds']

    credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
    client = gspread.authorize(credentials)

    #prior to run, create a spreadsheet "Test" with the sheets "Sheet 1", "Sheet 2", "Sheet 3"
    filename =  "Test"
    spreadsheet = client.open(filename)
    while True:
        sheet='Sheet %i' %random.choice([1,2,3])
        wks = spreadsheet.worksheet(sheet)
        range= wks.range('A1:Z1')
        range[0].value = random.random()
        range[1].value = random.random()
        range[2].value = random.random()
        wks.update_cells(range)

if __name__ == '__main__':

    main()

I tested the following hypothesis:

*

*The allowed number of requests is exceeded -> I checked the Developer Console for my oauth user -> 10.000.000 requests per day are allowed, the user limit is also set high

*The error message indicated that waiting could help. I implemented exponential backoff as suggested in the Api Docs, but I get a "ResponseNotReady" exception from gspread no matter how long I wait until retry.

More information
credentials object except "private_key" and "service_account_name":
{"id_token": null, "token_uri": "https://accounts.google.com/o/oauth2/token", "token_response": null, "client_id": null, "scope": "https://spreadsheets.google.com/feeds", "token_expiry": null, "_class": "SignedJwtAssertionCredentials", "refresh_token": null, "_module": "oauth2client.client", "private_key_password": "notasecret", "access_token": null, "invalid": false, "assertion_type": null, "kwargs": {}, "client_secret": null, "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", "store": null, "user_agent": null}

A: I'm not sure which library you're using, but the line
client = gspread.login(user@gmail.com, password)
implies it's an out of date one. There is no longer any way to authenticate to Google APIs using username and password.
Depending on your programming language, you should either find a more up to date library, or program against the REST API directly.


text:
Q: sound device detected as guest but gone at normal user If I login to my account the sound device is not listed.
If I login as guest everything is there.
I searched before posting and I tried some stuff, but nothing worked yet. Also I couldn't find the same specific problem.
Yesterday everything was working fine and I don't remember messing around with anything.
I'm using 14.04
This is the output of lspci|grep -i audio:
00:14.2 Audio device: Advanced Micro Devices, Inc. [AMD/ATI] SBx00 Azalia (Intel HDA) (rev 40)
01:00.1 Audio device: NVIDIA Corporation GK104 HDMI Audio Controller (rev a1)

It is the same result as user and under guest session

A: I managed to fix my issue!

*

*I looked here:
Audio suddenly stopped, pulseaudio reinstall has not helped? (14.04)

*rm -r ~/.config/pulse

*Logout/Login
I tried this command before posting here but it was not working. I guess reinstalling pulseaudio made the folder appear.
Now everything is working fine


text:
Q: Accidentally deleted laravel.log contents I accidentally deleted the contents of laravel.log
Now, whenever I'm editing a blade, the changes doesn't reflect.
What should I do? Please help.
Thank you

A: You can run this artisan command to restore it and clear the view cache:
php artisan view:clear

and
php artisan config:cache


text:
Q: ios can't change corner radius for image in cellforrowatindexpath I am trying to round the corners of an image in cellforrowatindexpath like so:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MyCell";
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSString *identifiers = _identifiers[indexPath.row];

    if([identifier isEqualToString:@"bronze"]){
        cell.imageView.image = [UIImage imageNamed:@"bronze.png"];
        cell.imageView.layer.cornerRadius = cell.imageView.frame.size.width / 2;
        cell.imageView.clipsToBounds = YES;
    }

    return cell;
}

However, this doesn't work.  What am I doing wrong?

A: Try, right after you set your image, calling:
[cell layoutSubviews];

I don't think that this is the best way to do it, but it is a hack that will work.
This has been tested.
EDIT (for clarity):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MyCell";
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSString *identifiers = _identifiers[indexPath.row];

    if([identifier isEqualToString:@"bronze"]){
        cell.imageView.image = [UIImage imageNamed:@"bronze.png"];
        [cell layoutSubviews];
        cell.imageView.layer.cornerRadius = CGRectGetWidth(cell.imageView.frame) / 2;
        cell.imageView.clipsToBounds = YES;
    } else {
        cell.imageView.image = nil;
        cell.imageView.layer.cornerRadius = 0;
    }

    return cell;
}

A: The imageView has a frame of (0,0,0,0) at this point. So cell.imageView.frame.size.width is 0. Therefore, your code sets the cornerRadius to 0 again, which is a no-op.
you could hardcode the value for cornerRadius or you could sublass the table view cell and override -layoutSubviews


text:
Q: Link_to in Mailer I want to use "link_to" in a mailer.rb file. I have already set the default host in an initializer.
Neither of the following includes works
include Rails.application.routes.url_helpers
include ActionView::Helpers::UrlHelper

class MessageMailer < ActionMailer::Base

   ...
   "#{ link_to 'something', something_url } is the link"

end

Errors I get, when calling MessageMailer.welcome_employer(Employer.find(18)).deliver in the console:
(with neither or include ActionView::Helpers::TextHelper is present)
NoMethodError: undefined method `link_to' for #
(with only 'include ActionView::Helpers::TextHelper' or both present)
RuntimeError: In order to use #url_for, you must include routing helpers explicitly. For instance, `include Rails.application.routes.url_helpers

A: I used it in dynamic emailer using view_content as below,
@email_type.header.gsub('<Lot_No>',"#{view_context.link_to tile, root_url + product_tile_path(params)}")

A: I have done to solve this issue with 2 ways in rails 4:

*

*You can specify your mailer host in each environment. For instance:
Rails.application.routes.default_url_options[:host] = 'http://localhost:3000'

*You can use ActionController::Base.helpers.link_to
ActionController::Base.helpers.link_to("Active", disable_sub_newsletter_users_url, :class => "tiny button alert", method: :post)
or

*Use url for
Rails.application.routes.url_helpers.url_for(:controller => "users", :action => "disable_sub_newsletter"

*You have to remove 2 lines above your class
include Rails.application.routes.url_helpers
include ActionView::Helpers::UrlHelper

A: In Rails 5, the following worked for me:
class MessageMailer < ActionMailer::Base

  "#{ view_context.link_to 'something', something_url } is the link"

end

A: To make the url helpers availabe in MessageMailer you must move the includes into the class definition:
class MessageMailer < ActionMailer::Base
  include Rails.application.routes.url_helpers
  include ActionView::Helpers::UrlHelper

  "#{ link_to 'something', something_url } is the link"

end


text:
Q: Help with triple boot on Macbook Air with external SSD I own a 2015 Macbook Air running Mojave. I plan to triple boot Mac, Windows 10, and Linux (specifically Manjaro EDIT: but Ubuntu's fine) by installing them (Windows and Linux) on an external SSD and booting from there. Preferably, I don't want to use rEFind or similar, as I don't want to make any (major) changes to my Mac.
The resources I found online are mostly incomplete or outdated.
I would really appreciate it if anyone could provide a complete, comprehensive guide to do this in 2019, or at least provide of basic set of steps/links I could follow so the operating systems don't end up screwing each other over.
EDIT: I'll throw in a link to help: here
Basically, I mainly want to know about how to do this part:

Use more than one EFI partition. A drive can have more than one EFI partition. Additional EFI partitions do not have to reside at the beginning of the drive.

Thanks in advance!
EDIT 2: I think I've finally hit the jackpot here. It's perfect for what I want to do.
Basically, although it's a bit outdated, it covers all the boot file config stuff. It uses rEFInd, but installs it on the external drive so only a few are actually made to my internal SSD.
For anyone seeing this in 2022 or something, I'm happy if this helps!

A: To install Windows 10 and Linux on a empty external drive (with EFI):
With the bootable USB start your Linux distribution and start the Gparted software.
On the external drive (and make sure it's the right drive and not something else !) reformate the partition table to GPT
make a fat32 partition of 512MiB with the flag "esp"
make a Linux swap partition of the size of your RAM. (Usefull for hibernation. If you want a smaller partition make it at least 2GiB in case your RAM would be full.)
Make a ext4 partition wich leave the half of the disk empty for windows 10. This partition will be used to install Linux.
Before running the installer of Linux, install Windows 10 first to avoid boot problems.
Boot to windows 10 with a bootable USB.
When it ask for installation select "Custom: Install Windows only (advanced)"
You should see the empty part of the drive. Select it and click on "Next"
Windows 10 will be installed.
Reboot to Linux bootable USB
Then run the installer of your ditro. When it ask for installation, select the option named something like "custom partitions" or "something else". Make sure it use the fat32 esp partition for /boot/efi (GRUB 2 will be installed here), the Linux swap partition for the swap and the ext4 partition for / (Linux).
Linux will be installed.
Add a comment to this post if you have questions :)


text:
Q: C# - new CultureInfo instantiation performance I was wondering if it was a good practice to instantiate a CultureInfo object repeatdedly in a loop process (few thousand times). This object is required in many Date and String methods to force a specific culture when CurrentCulture may not be the right one.
var c = new CultureInfo("en-US", false);

What is the performance of a repeated instantiation?

A: One would think that the optimizer in the C# and/or the JIT compilers would have the smarts to recognize a loop-invariant expression and refactor outside of the loop. My inclination is to do such refactorings myself as is makes the code clearer.
Even better, use this method:
CultureInfo ci = CultureInfo.GetCultureInfo("en-US") ;

It gives you a cached, read-only instance, the instance will only be constructed once and thence retrieve from cache.
Better yet, for your stated purposes:

This [CultureInfo] object is required in many Date and String methods
  to force a specific culture when CurrentCulture may
  not be the right one.

use CultureInfo.InvariantCulture. That is what it exists for.
A third option, would be to create a static CultureInfo property holding a singleton reference to your fallback culture. Depending on your purposed, you might want to mark it as thread-local (static methods of CultureInfo are thread-safe; instance methods are not). Such a propery might look something like this:
public static string FallbackCultureId { get { return Configuration.AppSettings["FallbackConfigurationId"] ; } }

public static CultureInfo FallbackCultureInfo
{
  get { return fallBackCultureInfo ?? (fallBackCultureInfo=new CultureInfo(FallbackCultureId)) ; }
}
[ThreadStatic] private static CultureInfo fallBackCultureInfo ;

A: Why not just declare the culture outside of the loop and use the instance reference inside of the loop?
The more you put in there the longer it will take

A: In case it is for winforms/wpf app:
How to: Set the Culture and UI Culture for Windows Forms Globalization
// C#
// Put the using statements at the beginning of the code module
using System.Threading;
using System.Globalization;
// Put the following code before InitializeComponent()
// Sets the culture to French (France)
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
// Sets the UI culture to French (France)
Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR");


text:
Q: SQL Server Keep getting error message for trigger I just started with SQL a few days ago and have been trying to set up triggers to automatically populate some columns such as the ones below when data is entered for employeeTimes(clockIn, clockOut, timeIntimeOut) (similarly for those not listed here). Sorry if the column/row names are confusing - pls let me know I'll change it.
Below is my trigger, and below that is the error.
ALTER TRIGGER dailyHoursWorked
ON employeeTimes
AFTER INSERT, DELETE, UPDATE
AS
DECLARE @time INT
DECLARE @employeeID INT
DECLARE @error VARCHAR(30)
SET @time = (SELECT DATEDIFF(hh,clockIn,clockOut) FROM employeeTimes)
SET @employeeID = (SELECT employeeID FROM inserted)
SET @error = ('Please enter an employeeID')
BEGIN
UPDATE employeeTimes
SET timeIntimeOut=@time
Where employeeID=@employeeID
END

The error I get is as follows:

Subquery returned more than 1 value.  This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression.

A: Triggers in Sql server are fired based on statements, not rows.
This means that the inserted (and deleted) might contain multiple rows.
By writing SET @employeeID = (SELECT employeeID FROM inserted) you are assuming that the inserted table have only one row in it, but when updating or inserting multiple rows in a single statement that is not the case.
Also, You are assuming the same thing about the employeeTimes table -
SELECT DATEDIFF(hh,clockIn,clockOut) FROM employeeTimes

Will return a result set and not a single value if your table have more then one row.
Seems to me like the best way to go here is either use computed columns or compute whatever data you need when selecting the data from the table, rather then using a trigger for it.
If you really want to use a trigger for this, you can use an update statement with a join to the inserted table like this:
UPDATE t
SET timeIntimeOut = DATEDIFF(hh, i.clockIn, i.clockOut)
FROM employeeTimes As t
INNER JOIN inserted as i ON t.employeeID = i.employeeID


text:
Q: sparse matrix of ones (not zeroes) I'd like to change my matrix that contains lots of ones into a sparse matrix. Is there a programmatic solution to this?
I would like to avoid converting 1's to a 0 and vice-versa, because this would make things more complicated than they should be (then I would need to put in complicated conversion steps).
data <- rnorm(1e6)
zero_index <- sample(1e6)[1:9e5]
data[zero_index] <- 1

Matrix::Matrix(as.matrix(data, sparse = TRUE))

A: I don't think this is possible without coding it yourself (i.e., writing functions to convert dense matrices to and from one of the common sparse-matrix representations, e.g. compressed sparse column). Most existing sparse-matrix representations are heavily optimized to assume that the 'ignorable' elements are zero, because this is overwhelmingly the most common use case in scientific computation.
I was going to say that you could adapt the code in the Matrix package, but this conversion code is deeply buried in C code and calls CHOLMOD routines ...) One of the other sparse-matrix packages, e.g. the spam package, might be a better starting point.


text:
Q: conservative and path independent difference suppose that we have a function $F(x,y)=(\frac{-y}{x^2+y^2},\frac{x}{x^2+y^2})$ if we calculate $curlF$ we understand that $curlF=0$ ( computing $curlF$ is not my question). now the book has written that because the domain is $\mathbb{R}^2 - \{(0,0)\}$ so we can't conclude that $F$ is conservative. but F is path independent.
first question: so I concluded that if $curlF=0$ and $F$ is simply connected then $F$ is conservative but if $curlF=0$ and $F$ is not simply connected (like this example) then $F$ is path-independent. is that correct?
second question: what is the difference between conservative and path-independent?


text:
Q: Response.Redirect doesn't work I am wondering why my Response.Redirect doesn't work. So basically, I read the files in my folder, or exactly the index.html. When I find it i redirect to it .
 foreach (System.IO.FileInfo thefile in fiArr)
        {
            if (thefile.Name == "index.html")
            {
                //Response.Redirect(path + "/index.html", false);
                Response.Redirect("C://inetpub//wwwroot//Folder//" + ((LinkButton)sender).ID,     false);
            }
        }

I am just wondering why this doesn't redirect anywhere.

A: Response.Redirect only support to redirect to a URL beginning with "http://", a virtual folder located on same server or a file in same folder.
You could add your folder with files as a virtual folder in the server and redirect to the virtual location of the file.
Another approach can be to use javascript to do a client side redirect to the file instead.


text:
Q: Ruby Office Automation - cannot get event handlers to work in MSWord Ruby version 1.9.1p430 running on W7 with Office 2010.
I am trying to catch the DocumentBeforeClose event but I cannot even get close to get it to work!
I have followed some examples using Excel where the SheetSelectionChange is handled. It works without any problem.
Using the same process, I wanted to handle the above Word event.
My code fails at the WIN32OLE_EVENT.new statement. Here is what I am using:
require 'win32ole'

wd = WIN32OLE.connect('Word.Application')
wd.visible = true
doc = wd.Documents.Add

ev = WIN32OLE_EVENT.new(doc, 'ApplicationEvents4')

The error I get is:
ev = WIN32OLE_EVENT.new(doc, 'ApplicationEvents4')
RuntimeError: failed to query IConnectionPoint
    HRESULT error code:0x80040200

I have looked extensively for the correct content for the name of the sink in the WIN32OLD_EVENT statement but this is the best I have come up with and it's obviously incorrect!
I would be most grateful if someone can point me in the right direction. I would be interested to hear if anyone has managed to succesfully handle Word events from Ruby.

A: I think you should use Word object instead of doc object in WIN32OLE_EVENT call, because of 'ApplicationEvents4' relates to Word.Application.
ev = WIN32OLE_EVENT.new(wd, 'ApplicationEvents4')

PS
Don't forget about message loop
loop do
    WIN32OLE_EVENT.message_loop
end


text:
Q: Pyautogui function LocateOnScreen is giving error despite having installed required library(using python3 on ubuntu).Please help me out The function used in interpreter:
pyautogui.locateOnScreen('zoom_pic.png')

THE ERROR IS:-
Traceback (most recent call last):
 File "<pyshell#10>", line 1, in <module>
   pyautogui.locateOnScreen('zoom_pic.png')
 File "/home/aaryan/.local/lib/python3.8/site-packages/pyautogui/__init__.py", line 175, in wrapper
   return wrappedFunction(*args, **kwargs)
 File "/home/aaryan/.local/lib/python3.8/site-packages/pyautogui/__init__.py", line 213, in locateOnScreen
   return pyscreeze.locateOnScreen(*args, **kwargs)
 File "/home/aaryan/.local/lib/python3.8/site-packages/pyscreeze/__init__.py", line 371, in locateOnScreen
   screenshotIm = screenshot(region=None) # the locateAll() function must handle cropping to return accurate coordinates, so don't pass a region here.
 File "/home/aaryan/.local/lib/python3.8/site-packages/pyscreeze/__init__.py", line 498, in _screenshot_linux
   raise NotImplementedError('"scrot" must be installed to use screenshot functions in Linux. Run: sudo apt-get install scrot')
NotImplementedError: "scrot" must be installed to use screenshot functions in Linux. Run: sudo apt-get install scrot

A: The error messsage says:
"scrot" must be installed to use screenshot functions in Linux. Run: sudo apt-get install scrot

Have you tried sudo apt-get install scrot in your terminal? This should allow you to run functions like pyautogui.locateOnScreen() and pyautogui.screenshot().


text:
Q: Integral is zero; is the integrand necessarily odd? As we know, the integral of an odd (integrable) function over a symmetric interval disappears. Now, I am having difficulties about proving a somewhat converse statement of this, specifically:
Let $f$ be a continuous, $2\pi$-periodic function on $\mathbb{R}$ such that $\int_{-\pi}^{\pi} f(x)\,e^{\,ikx} \; dx \; = \; 0$ for all even $k \in \mathbb{Z}$. Prove that f is an odd function.
I am not even sure if this statement holds. Maybe there is a counterexample which I don't see right now.


text:
Q: Manipulating menu HTML My site's menu uses the built-in menu under Appearance >> Menus. I want to make a very simple change: I want to wrap each of my menu's second-level ULs in a DIV.
What's the simplest way to accomplish this?

A: Use a custom walker. Extend the functions start_lvl() and end_lvl():
class WPSE39005_Div_Walker extends Walker_Nav_Menu
{
    /**
     * @see Walker::start_lvl()
     *
     * @param string $output Passed by reference. Used to append additional content.
     * @return void
     */
    public function start_lvl( &$output, $depth )
    {
        $output .= '

';
    }

    /**
     * @see Walker::end_lvl()
     *
     * @param string $output Passed by reference. Used to append additional content.
     * @return void
     */
    public function end_lvl( &$output, $depth )
    {
        $output .= '

';
    }
}

Call it in your theme like that:
<?php
// If there is no menu assigned we show nothing.
has_nav_menu( 'top-menu' )
// Path to the file with the walker relative to theme's root.
and locate_template( 'php/class.WPSE39005_Div_Walker.php', TRUE, TRUE )
and wp_nav_menu(
    array (
    'menu'       => 'top-menu'
,   'walker'     => new WPSE39005_Div_Walker
    )
);
?>


text:
Q: Scala parser combinators and newline-delimited text I am writing a Scala parser combinator grammar that reads newline-delimited word lists, where lists are separated by one or more blank lines. Given the following string:
cat
mouse
horse

apple
orange
pear

I would like to have it return List(List(cat, mouse, horse), List(apple, orange, pear)).
I wrote this basic grammar which treats word lists as newline-delimited words. Note that I had to override the default definition of whitespace.
import util.parsing.combinator.RegexParsers

object WordList extends RegexParsers {

    private val eol = sys.props("line.separator")

    override val whiteSpace = """[ \t]+""".r

    val list: Parser[List[String]] = repsep( """\w+""".r, eol)

    val lists: Parser[List[List[String]]] = repsep(list, eol)

    def main(args: Array[String]) {
        val s =
          """cat
            |mouse
            |horse
            |
            |apple
            |orange
            |pear""".stripMargin

        println(parseAll(lists, s))
    }
}

This incorrectly treats blank lines as empty word lists, i.e. it returns
[8.1] parsed: List(List(cat, mouse, horse), List(), List(apple, orange, pear))

(Note the empty list in the middle.)
I can put an optional end of line at the end of each list.
val list: Parser[List[String]] = repsep( """\w+""".r, eol) <~ opt(eol)

This handles the case where there is a single blank line between lists, but has the same problem with multiple blank lines.
I tried changing the lists definition to allow multiple end-of-line delimiters:
val lists:Parser[List[List[String]]] = repsep(list, rep(eol))

but this hangs on the above input.
What is the correct grammar that will handle multiple blank lines as delimiters?

A: You should try setting skipWhitespace to false instead of redefining the definition of whitespace. The issue you're having with the empty list is caused by the fact that repsep doesn't consume the line break at the end of the list. Instead, you should parse the line break (or possibly end of input) after each item:
import util.parsing.combinator.RegexParsers

object WordList extends RegexParsers {

  private val eoi = """\z""".r // end of input
  private val eol = sys.props("line.separator")
  private val separator = eoi | eol
  private val word = """\w+""".r

  override val skipWhitespace = false

  val list: Parser[List[String]] = rep(word <~ separator)

  val lists: Parser[List[List[String]]] = repsep(list, rep1(eol))

  def main(args: Array[String]) {
    val s =
      """cat
        |mouse
        |horse
        |
        |apple
        |orange
        |pear""".stripMargin

    println(parseAll(lists, s))
  }

}

Then again, parser combinators are a bit overkill here. You could get practically the same thing (but with Arrays instead of Lists) with something much simpler:
s.split("\n{2,}").map(_.split("\n"))


text:
Q: Mikrotik API reference for `passthrough=no` In several parts of the Mikrotik API Manual there are references to the passthrough=no and passthrough=yes.
e.g.,:
Manual: Transparent Traffic Shaper
Manual: "/ ip firewall mangle"
But nowhere have I seen a complete description of what this attribute does! Can someone link to documentation or give a complete description of the behavior of this attribute?
(Please note that I am NOT referring to the similarly named action: action=passthrough.)

A: In my experience, when you use passthrough=yes, for example in a mangle rule, then the packet if it gets matched by that rule it's processed by the subsequent rules.
Where in case you use passthrough=no, if the packet gets matched by that rule, it will not get processed by the subsequent rules which can be useful to save some CPU as stated at the bottom of the manual page you posted.
There are certain types of configurations that passthrough=yes is needed, but in most cases I believe that it's safe to use passthrough=no unless you need otherwise.


text:
Q: "display:inline-block" displays differently than "display:inline flow-root" I have the following division container:
 Lorem.

 Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos, officia?

 Lorem ipsum dolor sit amet consectetur, adipisicing elit. Soluta, ab.

 Lorem.

As expected, the division container acts like an inline-level element.
When I alter the value of the display property to "inline flow-root", the division container no longer acts like an inline-level element and instead acts like a block-level element:
 Lorem.

 Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos, officia?

 Lorem ipsum dolor sit amet consectetur, adipisicing elit. Soluta, ab.

 Lorem.

According to the Mozilla Developer Network documentation, the "inline-block" value should be equivalent to "inline flow-root".
Why does the two values produce different display results?
Thanks in advance.

A: As per the answer given in link,
display: flow-root; Needs Chrome Canary or Firefox Nightlies.

sets it to display: table; or display: block;

May be you can use overflow: visiible to contain float-ed elements.


text:
Q: Why does loading the System assembly work in the F# Repl, but not in compiled code? let system = System.Reflection.Assembly.Load("System")
()

This works for me in the Repl, but not when compiled. Any idea why?
On compiled, I get the following exception:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System' or one of its dependencies. The system cannot find the file specified.