text:
Q: remove virtual environment created with venv in python3 How can I delete a virtual environement created with
python3 -m venv <name>

Can I just remove the directory?
This seems like a question googling should easily answer, but I only found answers for deleting environments created with virtualenv or pyvenv.

A: If your environment is active, you should deactivate it first. Not sure if not deactivating will cause any problems, but that's the right way to do it. Once you deactivate, you can simply delete the virtual environment directory.
To deactivate an active environment, simply execute the 'deactivate' bash command.

A: In your venv project folder created using python3 -m venv . or whatever, run this to remove the venv files:
rm -r bin include lib lib64 pyvenv.cfg share

If you're still in the venv by using source bin/activate, run deactivate first.
However, according to this page, one should always use python3 -m venv .venv so the venv files are neatly contained in a single .venv folder in your project root. That way the Visual Studio Code Python extension can find/use it as well.

A: Yes, delete the directory. it's where executables for the venv and modules and libraries and entire other stuff for venvs is kept.

A: To delete a environment in WINDOWS. Make sure you are in activated environment:
$ deactivate

This will deactivate your current environment.
Now you can go to the directory where your  folder or  folder is present. Delete it manually. DONE!
To create a new environment , Simply from bash:
$ python3 -m venv venv

To activate it:
$ source venv/bin/activate

A: There is no built-in way to remove a virtualenv created with python3 -m venv <name>. If you created a python3.6 virtualenv in, for instance, /usr/local then you can remove it with an Ansible playbook like:
---
- name: Remove virtualenv
  hosts: all

  vars:
    venv: /usr/local

    virtualenv_files:
      - pyvenv.cfg
      - bin/activate
      - bin/activate.csh
      - bin/activate.fish
      - bin/easy_install
      - bin/easy_install-3.6
      - bin/pip
      - bin/pip3
      - bin/pip3.6
      - bin/python
      - bin/python3
      - bin/python3.6
      - bin/wheel
      - lib/python3.6/site-packages

  tasks:

  - name: Freeze virtualenv
    shell: |
      set -e
      source "{{ venv }}/bin/activate"
      pip3 freeze > /tmp/frozen
    args:
      creates: /tmp/frozen
    register: frozen
    failed_when: false

  - name: Remove site-packages from virtualenv
    when: frozen.rc == '0'
    become: true
    shell: |
      set -e
      source {{ venv }}/bin/activate
      pip3 uninstall -y -r /tmp/frozen

  - name: Remove virtualenv_files
    become: true
    file:
      path: "{{ venv }}/{{ item }}"
      state: absent
    loop: "{{ virtualenv_files }}"


text:
Q: How to poll an AMQP queue using Spring Integration I have the use case that I need to wait 2 hours before consuming messages from an AMQP (we use Rabbit) queue.
EDIT:  To clarify my use case... I need each individual message to wait 2 hours before being read.  E.g.  Message 1 arrives at 10am and Message 2 arrives at 10:15.  I need Message 1 to be read at 12p and Message 2 to be read at 12:15p.
We are using Spring Integration 3.x.
The int-amqp:inbound-channel-adapter is message driven and doesn't have a polling option from what I can find.
A couple things I've thought of:

*

*Set auto-startup to false and manually start the inbound channel adapter using a quartz job.

*Create my own custom SimpleMessageListenerContainer that is based on polling (not sure how easy this would be)

*Configure a "delay queue" in rabbitmq using this method: How to create a delayed queue in RabbitMQ?

*EDIT: add 4th option:  Use delayer to delay each message for 2 hours: http://docs.spring.io/spring-integration/docs/3.0.2.RELEASE/reference/html/messaging-endpoints-chapter.html#delayer
Any suggestions?

A: We don't currently have a polling inbound adapter. #1 is easy. For #2, the simplest would be to use a RabbitTemplate and invoke receive() from an inbound-channel-adapter in a POJO.
I would go with #1; you don't need quartz, you can use a simple Spring scheduled task and a control bus to start the adapter.

A: Another trick is about to use PollableAmqpChannel:
<int-amqp:channel id="myQueueName" message-driven="false"/>

and provide the <poller> for the subscriber to that channel.
There is no reason to send messages to that channel (because you will poll messages from Rabbit Queue) and, right, it looks like anti-pattern, but it is a hook how to avoid any workarounds with direct RabbitTemplate usage via SpEL.
UPDATE
<delayer> can help you, but it depends of your requirements. If you don't want to poll messages from RabbitMQ, you should use the workaround above. But if you just don't want to process message until some time is elapsed, you can just 'delay' it for that time.
Don't forget to add persistent message-store to avoid losing messages during that period and unexpected application failure.

A: FYI, how I solved the issue.  (Used solution #3).
<rabbit:queue name="delayQueue" durable="true">
  <rabbit:queue-arguments>
    <entry key="x-message-ttl">
       <value type="java.lang.Long">7200000</
     </entry>
     <entry key="x-dead-letter-exchange" value="finalDestinationTopic"/>
     <entry key="x-dead-letter-routing-key" value="finalDestinationQueue"/>
  </rabbit:queue-arguments>
</rabbit:queue>

<rabbit:topic-exchange name="finalDestinationTopic">
  <rabbit:bindings>
    <rabbit:binding queue="finalDestinationQueue" pattern="finalDestinationQueue"/>
  </rabbit:bindings>
</rabbit:topic-exchange>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I visualize permissions to my users on our intranet? There have been quite a few people in my organization who have expressed confusion about who has access to what.
This is also making them reluctant to use SharePoint. Because this isn't clear to them.
Preferably, they would like a nice picture, maybe on every page, showing who has access and what their rights are.
Has this been done before? Is there a way to import the permissions of a site/list into a nice Visio diagram or something of the sort? And have it visible to all?

A: You could try something like http://permissionsmanager.codeplex.com/

A: Trying the demo version right now, but this looks like what your asking about: http://www.docusnap.com/en/docusnap/permission-analysis


text:
Q: Is it possible to create an extension method that is called when the object is created? I cannot modify the object I am working with and I need a method but I really want it to be called when the object is created. So I was thinking that a extension method would be good here, however I don't know if it is possible but, if it is, then how?
EDITED:
My static class has this main object which I am supposed to create:
EcuVersion Ecu;

I will call this method from my class:
Ecu = ConvertAutodetect.Convert(rawData, Ecu, response);

and the platform will be looking for the Ecu object.
My method will return an EcuVersion object. This object contains a collection besides a lot of other things and I am working only with the respective collection which is:
ICollection<AutodetectStep> AutodetectSteps { get; set; }

AutodetectStep class has 4 childs and on one of it's childs I needed this extension method to be called when the child is created.
I have to create many childs and add them to the collection, also, I will never be instantiated my object because everything is static in there.
So is it suitable to use the factory pattern ?

A: Create a class which inherit from your type
public class YourObject
{
    public YourObject()
    {
        // some code
    }

    public void SomeMethod() {}
}

public class YourObjectWithExtraLogic : YourObject
{
    public YourObjectWithExtraLogic() : base()
    {
        // here add some extra logic
    }
}

Then you can use your class with extra logic anywhere where base class used.
public void Execute(YourObject obj)
{
    obj.SomeMethod();
}

var newObject = new YourObjectWithExtraLogic();
Execute(newObject);

With this approach you need to be careful not to violate "Liskov Substitution Principle".
For example your extra logic can not break expected behavior of base class.

A: No, this is not possible. If it was it would be very unreliable because it would depend on whether you included relevant extension with using or not. That's actually general problem of extension methods but here it's even worse as it would never cause compile time error.
The best way how to implement this is probably using the factory pattern to indirectly construct the object and inject that factory in the code. This still doesn't solve the problem of existing code though.


text:
Q: Why does the first method to be called in Java have to be static but in android it doesn't? In Java, the first method to be run is
public static void main(String[] args)
In android, the first method to be run is
protected void onCreate(Bundle savedInstanceState)
I was always wondering why does the first method in Java have to be static but in android doesn't? Would anyone please help me to get this thing clear in my mind?

A: These are two different scenarios. We have a general java language run by a java virtual machine. This jvm is designed to call a specific entry point for all applications. Thus this have to be as generic as possible.
Android runtime and many other like WARs, Applets, Servlets are "higher" apis. Thus they have all their specific entry points. Since these apis are already running within general jvm with an own main() method, they are able to implement more complex and domain specific entry points. Thus in this case the android runtime creates an object of a given class and invokes the methods designed by the api.
See also:

*

*Java Web Application specify entry point

*Entry point for Java applications: main(), init(), or run()?
And many other resource.

A: Because Android studio is based on a framework.
If you take a look at the callstack when breaking on 'onCreate', you can see that a static main() method is called & creates an instance of your MainActivity class.
http://picpaste.com/stack-FOnB69o6.png


text:
Q: How to use Dojo in my Django application? How do I use Dojo in my Django application? Please show me comprehensive examples on how to do this.
Any links to sample code for this combination will be appreciated
NB: I also don't mind examples using Dojango.

A: You may have seen this blog post:
http://blog.uxebu.com/2008/07/26/ajax-with-dojango/
You can also try the various examples, blog articles and docs here.
http://code.google.com/p/dojango/

A: *

*copy dojango over to you project root

*include the following lin in your settings.py > MIDDLEWARE_CLASSES: 'dojango.middleware.DojoCollector',

*include the following lin in your settings.py > TEMPLATE_DIRS: '/<project_location>/dojango/templates/dojango', (so you can see some nice demos)

*include the following lin in your settings.py > INSTALLED_APPS: 'dojango',

*change from django.forms import * to from dojango.forms import * in your forms.py


text:
Q: Losing keys in pandas dataframe when after using groupby I'm pretty new to Python and I just encountered a problem.
mini_agg is my original pandas.dataframe and I'm trying to group
it by 2 columns.
trial = mini_agg.groupby(['date','product','product_type_1','product_type_2','product_type_3','product_type_4']).sum()

print mini_agg.shape
print trial.shape

output:

(2965909, 10)
   (499281, 4)

Furthermore I cannot access the keys by which I grouped by.
In R I do obtain my column back when using aggregate.
Can you please help me? Thank you in advance

A: How to GroupBy a Dataframe in Pandas and keep Columns
Just found the answer I didn't find with my previous queries:
trial = mini_agg.groupby(['date','product','product_type_1','product_type_2','product_type_3','product_type_4']).sum().reset_index()

It is sufficient to add .reset_index()

A: I expected mini_agg values to be provided however I suppose it's a combination of two one-dimensional labeled data structures. So as you mentioned mini_agg is a  pandas.dataframe and as you must know DataFrame Like Series has a possibility to accept another DataFrame as input:
Therefore, If mini_agg to be like:
import pandas as pd
FRAME= {'one' : pd.Series([1., 2., 3.], index=['product_type_1', 'product_type_2', 'product_type_3']),
'two' : pd.Series([1., 2., 3., 4.], index=['product_type_1', 'product_type_2', 'product_type_3', 'product_type_4'])}
mini_agg = pd.DataFrame(FRAME)

So,
trial = pd.DataFrame(mini_agg, index=['date','product','product_type_1','product_type_2','product_type_3','product_type_4'], columns=['A', 'B', 'C', 'D', 'E', 'F'])


text:
Q: TypeScript inference of string literals My question is pretty simple. Given this code:
const array = [1, 2, 3, 4, 5];
const map01 = array.map((v) => v % 2 ? "" : "");
//    ^? string[]
const map02 = array.map((v) => v % 2 ? "odd" : "even");
//    ^? ("odd" | "even")[]
const map03 = array.map((v) => v % 2 ? "!" : "");
//    ^? ("" | "!")[]

Why such odd inference by TypeScript? Shouldn't map01 be inferred as ""[]?
Playground

A: The details for how and when literal type widening happens are laid out in microsoft/TypeScript#10676.  In particular, it says:

*

*In a function with no return type annotation, if the inferred return type is a literal type (but not a literal union type) and the function does not have a contextual type with a return type that includes literal types, the return type is widened to its widened literal type.

So this implies that in the case of "odd" | "even", you have a literal union type, which is not widened, while in the case of "", you have a non-union literal type, which is widened.
As for why this rule is used as opposed to a simpler "never widen" rule, it's a heuristic that was chosen to minimize surprise in "normal" circumstances.  Literal types are generally more useful in unions than standing alone, so the compiler assumes that function foo() {return "abc"} is more likely intended to return string, while function bar() {return Math.random<0.5 ? "abc" : "def"} is more likely intended to return a union of literals.  As a heuristic it's not perfect, but it has apparently caused less surprise than alternatives would.
There are various issues in GitHub where the current behavior is deemed to be working as intended; for example, see microsoft/TypeScript#51551 with this comment:

The widening rules are in place to heuristically attempt to infer "better" types and different code is allowed to behave differently under these heuristics


text:
Q: segmentation fault and memory not mapped when loading the rtracklayer package from Bioconductor into R in a conda environment I have create a conda environment with r and bioconductor-rtracklayer in it:
conda create --name bioconductor-rtracklayer --channel conda-forge --channel bioconda --channel r --yes r=3.5.1 bioconductor-rtracklayer=1.42.1
and activated it:
conda activate bioconductor-rtracklayer
I am working on macOS High Sierra 10.13.3
I then open R in the terminal and type:
library(rtracklayer)
and get the following error:
Loading required package: GenomicRanges
Loading required package: stats4
Loading required package: BiocGenerics
Loading required package: parallel

Attaching package: 'BiocGenerics'

The following objects are masked from 'package:parallel':

    clusterApply, clusterApplyLB, clusterCall, clusterEvalQ,
    clusterExport, clusterMap, parApply, parCapply, parLapply,
    parLapplyLB, parRapply, parSapply, parSapplyLB

The following objects are masked from 'package:stats':

    IQR, mad, sd, var, xtabs

The following objects are masked from 'package:base':

    anyDuplicated, append, as.data.frame, basename, cbind, colMeans,
    colnames, colSums, dirname, do.call, duplicated, eval, evalq,
    Filter, Find, get, grep, grepl, intersect, is.unsorted, lapply,
    lengths, Map, mapply, match, mget, order, paste, pmax, pmax.int,
    pmin, pmin.int, Position, rank, rbind, Reduce, rowMeans, rownames,
    rowSums, sapply, setdiff, sort, table, tapply, union, unique,
    unsplit, which, which.max, which.min

Loading required package: S4Vectors

 *** caught segfault ***
address 0x18, cause 'memory not mapped'

Traceback:
 1: dyn.load(file, DLLpath = DLLpath, ...)
 2: library.dynam(lib, package, package.lib)
 3: loadNamespace(package, lib.loc)
 4: doTryCatch(return(expr), name, parentenv, handler)
 5: tryCatchOne(expr, names, parentenv, handlers[[1L]])
 6: tryCatchList(expr, classes, parentenv, handlers)
 7: tryCatch({    attr(package, "LibPath") <- which.lib.loc    ns <- loadNamespace(package, lib.loc)    env <- attachNamespace(ns, pos = pos, deps)}, error = function(e) {    P <- if (!is.null(cc <- conditionCall(e)))         paste(" in", deparse(cc)[1L])    else ""    msg <- gettextf("package or namespace load failed for %s%s:\n %s",         sQuote(package), P, conditionMessage(e))    if (logical.return)         message(paste("Error:", msg), domain = NA)    else stop(msg, call. = FALSE, domain = NA)})
 8: library(pkg, character.only = TRUE, logical.return = TRUE, lib.loc = lib.loc,     quietly = quietly)
 9: .getRequiredPackages2(pkgInfo, quietly = quietly)
10: library(pkg, character.only = TRUE, logical.return = TRUE, lib.loc = lib.loc,     quietly = quietly)
11: .getRequiredPackages2(pkgInfo, quietly = quietly)
12: library(rtracklayer)

Possible actions:
1: abort (with core dump, if enabled)
2: normal R exit
3: exit R without saving workspace
4: exit R saving workspace
Selection:

I don't understand what the problem is. Can please someone help me?
Note that I can run library(rtracklayer) from within RStudio without any problems and I can use the functions in the package successfully. Why is there this discrepancy between the command line and RStudio?
Following Johannes Koester's comment, I have created a conda environment and installed bioconductor-rtracklayer without specifying the r channel:
conda create --name bioconductor-rtracklayer --channel conda-forge --channel bioconda --yes r=3.5.1 bioconductor-rtracklayer=1.42.1

activate the environment, opened R in the terminal and typed library(rtracklayer) but I still got the following error:
Loading required package: GenomicRanges
Loading required package: stats4
Loading required package: BiocGenerics
Loading required package: parallel

Attaching package: 'BiocGenerics'

The following objects are masked from 'package:parallel':

    clusterApply, clusterApplyLB, clusterCall, clusterEvalQ,
    clusterExport, clusterMap, parApply, parCapply, parLapply,
    parLapplyLB, parRapply, parSapply, parSapplyLB

The following objects are masked from 'package:stats':

    IQR, mad, sd, var, xtabs

The following objects are masked from 'package:base':

    anyDuplicated, append, as.data.frame, basename, cbind, colMeans,
    colnames, colSums, dirname, do.call, duplicated, eval, evalq,
    Filter, Find, get, grep, grepl, intersect, is.unsorted, lapply,
    lengths, Map, mapply, match, mget, order, paste, pmax, pmax.int,
    pmin, pmin.int, Position, rank, rbind, Reduce, rowMeans, rownames,
    rowSums, sapply, setdiff, sort, table, tapply, union, unique,
    unsplit, which, which.max, which.min

Loading required package: S4Vectors

 *** caught segfault ***
address 0x18, cause 'memory not mapped'

Traceback:
 1: dyn.load(file, DLLpath = DLLpath, ...)
 2: library.dynam(lib, package, package.lib)
 3: loadNamespace(package, lib.loc)
 4: doTryCatch(return(expr), name, parentenv, handler)
 5: tryCatchOne(expr, names, parentenv, handlers[[1L]])
 6: tryCatchList(expr, classes, parentenv, handlers)
 7: tryCatch({    attr(package, "LibPath") <- which.lib.loc    ns <- loadNamespace(package, lib.loc)    env <- attachNamespace(ns, pos = pos, deps)}, error = function(e) {    P <- if (!is.null(cc <- conditionCall(e)))         paste(" in", deparse(cc)[1L])    else ""    msg <- gettextf("package or namespace load failed for %s%s:\n %s",         sQuote(package), P, conditionMessage(e))    if (logical.return)         message(paste("Error:", msg), domain = NA)    else stop(msg, call. = FALSE, domain = NA)})
 8: library(pkg, character.only = TRUE, logical.return = TRUE, lib.loc = lib.loc,     quietly = quietly)
 9: .getRequiredPackages2(pkgInfo, quietly = quietly)
10: library(pkg, character.only = TRUE, logical.return = TRUE, lib.loc = lib.loc,     quietly = quietly)
11: .getRequiredPackages2(pkgInfo, quietly = quietly)
12: library(rtracklayer)

Possible actions:
1: abort (with core dump, if enabled)
2: normal R exit
3: exit R without saving workspace
4: exit R saving workspace
Selection: 1
R is aborting now ...
[1]    44550 segmentation fault  R

Note that my .libPaths() contains:
.libPaths()
[1] "/Users/user/Library/R/3.5/library"
[2] "/Users/user/anaconda/envs/bioconductor-rtracklayer/lib/R/library"

should I remove the first line that is inside .libPaths() for R to fetch the R package in the conda environment?
However, library(rtracklayer, lib.loc = '/Users/user/anaconda/envs/bioconductor-rtracklayer/lib/R/library') gives me the same error.

A: There is no need to mix the r channel with conda forge and bioconda. They are even binary incompatible. All packages from the r channel are in conda-forge now. Please see http://bioconda.github.io for the right channel order and combination. Hope that this might solve the error already.

A: Went into .bash_profile and deleted the R_LIBS_USER variable. It's now working. Suggested by Johannes Koester.


text:
Q: TCP receives packets, but it ignores them I have a really strange networking problem. The actual network configuration is quite complex, because I am using Openstack and Docker to build a virtual network. However, the problem is not there, because I am capturing on my host's interface and I see all the packet in the right way.... But for some reasons I do not know, it seems that TCP is ignoring them, though they have been received: it doesn't send ACK for them and it doesn't send the data to the application.
In my trials, I sent HTTP GET request for an html page to a server jetty (IP 192.168.4.3) from an host (192.168.4.100).
What I see capturing on 192.168.4.100 with Wireshark is:
192.168.4.100 -> SYN -> 192.168.4.3
192.168.4.3 -> SYN, ACK -> 192.168.4.100
192.168.4.100 -> ACK -> 192.168.4.3

192.168.4.100 -> GET / HTTP/1.1 -> 192.168.4.3
192.168.4.3 -> ACK -> 192.168.4.100
192.168.4.3 -> Fragment 1 of HTTP 200 OK response -> 192.168.4.100
192.168.4.3 -> Fragment 2 of HTTP 200 OK response -> 192.168.4.100
192.168.4.3 -> Fragment 3 of HTTP 200 OK response (PSH) -> 192.168.4.100

192.168.4.3 -> Retransmission of Fragment 3 of HTTP 200 OK response (PSH) -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 1 of HTTP 200 OK response -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 1 of HTTP 200 OK response -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 1 of HTTP 200 OK response -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 1 of HTTP 200 OK response -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 1 of HTTP 200 OK response -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 1 of HTTP 200 OK response -> 192.168.4.100

192.168.4.100 -> ACK of Fragment 1 -> 192.168.4.3

192.168.4.3 -> Retransmission of Fragment 2 of HTTP 200 OK response -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 3 of HTTP 200 OK response (PSH) -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 2 of HTTP 200 OK response -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 2 of HTTP 200 OK response -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 2 of HTTP 200 OK response -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 2 of HTTP 200 OK response -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 2 of HTTP 200 OK response -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 2 of HTTP 200 OK response -> 192.168.4.100

192.168.4.100 -> ACK of Fragment 2 -> 192.168.4.3

192.168.4.3 -> Retransmission of Fragment 3 of HTTP 200 OK response (PSH) -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 3 of HTTP 200 OK response (PSH) -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 3 of HTTP 200 OK response (PSH) -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 3 of HTTP 200 OK response (PSH) -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 3 of HTTP 200 OK response (PSH) -> 192.168.4.100
192.168.4.3 -> Retransmission of Fragment 3 of HTTP 200 OK response (PSH) -> 192.168.4.100

192.168.4.100 -> ACK of Fragment 3 -> 192.168.4.3

This is actually a big problem, because there are about 40 seconds between the GET request and the last ACK which coincides with the moment the application (telnet in this case) gets the data.
I have checked all the checksum and they are correct...
So I actually don't know why this happens and what to do! I have tried with different OS as hosts (a Windows 8 mobile phone, a MAC OSX, a Ubuntu 14.04, ...), but nothing changes.
If I send the same request from another docker of the virtual network, everything works fine.
Any idea about what the problem could be?
Thanks!
PS here you can see a screenshot of the capture:

Update
One thing I think can be interesting is that I have made an analogous capture, but when a HTTP request is sent from 192.168.4.3 to 192.168.4.100. The capture is taken again on the 192.168.4.100 interface and it seems again that 192.168.4.100 ignores the packets it receives (look at the three way handshake for example). And I found no reason for this again.

A: I managed to solve my problem. I post here the solution which can be useful if someone has my same problem.
The problem was that I disabled the TSO (tcp-segmentation-offload) on the virtual bridge to which my Dockers are attached with the command:
ethtool -K IFACE_NAME tso off

It turns off only TSO, whereas the checksumming offload remains on. Evidently, this creates some problem and though Wireshark showed me that TCP checksum was OK, actually it wasn't. So the host ignored the packet due to the bad TCP checksum.
To turn off TSO and checksumming too, I just used the command:
ethtool --offload IFACE_NAME rx off tx off

And now everything works.


text:
Q: Event Viewer for Websphere MQ failures, errors on Unix On Windows Server, the event viewer can provide several errors like 2035 or insufficient size of logs for transactions,...
I  don't see where i can find exactly the same events logs on unix ( Solaris & Redhat). Nothing on syslog, messages and audit.
Any idea ?

A: Because the 2035 is an error returned to the application, it is not something that is logged in the QMGR error logs by default. You can however enable reporting on the 2035 so that you can troubleshoot it further yourself.  Use  MQSAUTHERRORS to generate a FFDC detail or use MQS_REPORT_NOAUTH  to better diagnose return code 2035

A: Look into queue manager specific error log files, AMQERR01.LOG, AMQERR02.LOG and AMQERR03.LOG under qmgrs/<-your qmgr name->/errors directory.


text:
Q: MySQL PHP Matching User ID's when creating a "USER" I am coding a "social media site" for a class project, and I am having trouble in one section.
When first registering an account, the user must enter a username and password, and click a submit button. PHP code checks the inputs to make sure they're all valid and that there will not be any duplicates, and if everything passes, it adds in the username and password into a SQL table called "users". Users has 3 columns: username, password, and userID. userID is the primary key.
Once that process is completed, we redirect to a separate page, where the user can enter more personal information, such as first and last name, city, country, etc. This table, called "userInfo" has the columns: firstName, lastName, emailAddress, address, city, country, and userID. userID, once again, is the primary key.
What I'm trying to figure out is how to match the two user ID's in an insert statement. I have a form that gathers all the required information, but I am not sure how to set up the SQL query to make sure that users.userID matches userInfo.userID.
Here's my PHP for users (initial registration)
<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";

if(isset($_POST['submit'])){
    // Get inputs
    $username = $_POST['user'];
    $password = $_POST['password'];

    // Clean inputs and encrypt password
    $username = mysqli_real_escape_string($conn, $username);
    $password = mysqli_real_escape_string($conn, $password);
    $password = md5($password);

    // Check username not empty
    if (empty($username)) {
        $error = "true";
        $errorMessage = "Please enter a value for your username";
    }

    // Check username does not already exist
    $checkUserQuery = "SELECT username FROM users WHERE username = '$username'";
    $checkResult = $conn->query($checkUserQuery);
    if($checkResult->num_rows > 0) {
        $error = "true";
        $errorMessage = "This username already exists";
    }

    // Username does not exist, add to database
    else {
        $insertUserQuery = "INSERT INTO users (username, password) VALUES('$username', '$password')";
        $insertResult = $conn->query($insertUserQuery);
        $_SESSION['username'] = $username;
        header("Location: userInfo.php");
    }
  }
?>

Here's my PHP code so far for userInfo:
<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";

$username = $_SESSION['username'];

if(isset($_POST['submit'])){
    // Get inputs
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $emailAddress = "fakeEmailAddress@fakeyfakefake.com";
    $address = $_POST['address'];
    $city = $_POST['city'];
    $country = $_POST['country'];

    // Clean inputs
    $firstName = mysqli_real_escape_string($conn, $firstName);
    $lastName = mysqli_real_escape_string($conn, $lastName);
    $address = mysqli_real_escape_string($conn, $address);
    $city = mysqli_real_escape_string($conn, $city);
    $country = mysqli_real_escape_string($conn, $country);

    // Validate Inputs (Only validating first and last name, location entries are not required)

    if(empty($firstName) || empty($lastName)) {
        $error = "true";
        $errorMessage = "Please enter your first AND last name";
    }

    else {

    }
  }
?>

Apologies if this is super messy. Databases are NOT my strong suit lol.
Many thanks to anyone who can help!

A: You'll want to get the mysqli_insert_id for your insert into the users table and pass that along (potentially via your $_SESSION) for creation in userInfo.


text:
Q: get rsync to dereference symlinked dirs presented on cmdline like find -H I'd love rsync to copy symlinks to dirs specified on the cmdline as dirs but leave all symlinks in the copied tree as is - like find -H, but the only way is a nasty hack of
rsync -aR --rsync-path='cd /sender/parent/dir/of/tree; rsync' symlinkeddir/ target

the issue there is that this becomes an exception in my rsync backup scripts just for this one set of paths so I can't use the same command (or more so, just ONE rsync) to do what I want. find -H -like behaviour would do it very nicely. :/

A: If somelink is a symbolic link to a directory somedir, then
rsync -a somelink/. target/

copies the content of somedir into target.
If you only have relative symlinks that stay inside the source, then you can use
rsync -a --copy-unsafe-links somelink target/

If you want to preserve the symlink path inside the target, I don't think what you want to do can be done with rsync alone. You can do it with rsync plus a bit of shell code: loop over the sources, and specify the target subdirectory explicitly.
mkdir -p target/somelink
rsync -a somelink/. target/somelink


text:
Q: why use Modules and clases in typescript with AMD compiling? I am creating a module(not sure if it should be module/class/or none) for my project.
I mostly perfer this way.
///<reference path="..\typings\knockout\knockout.d.ts" />
///<reference path="..\typings\requirejs\require.d.ts"/>
///<reference path="hubs.d.ts" />

//export module SignalRService {
    export var deployHub = $.connection.deployHub;
    export var status = ko.observable();
    export function intialize() {
        $.connection.start()
        .done(() => { this.status("Connection Succesfull") } )
        .fail(() => { this.status("Connection Failed")});

    }

//}

this results in me being able to do as this:
var ko: KnockoutStatic = require('ko');
var hostNodes = ko.observableArray([]);
import signalr = module('SignalRService');

export class AppViewModel {

    ///Properties
    hostNodes = hostNodes;
    error = ko.observable();
    signalr = signalr;
    ///Constructor
    constructor() {

        signalr.intialize();
    }
}

i have directly access to the defined stuff in my "module" from the import. Alternative, if i create it as a typescript module. i have to add:
signalr = signalr.SignalRService;
to get access to my module from the import. Anyone who can enlighten me a little about if i missed out something when i do not declare it as a module in my typescript file?

A: From my point of view - you are using two different approaches to define modules in TypeScript (JavaScript).
Modules help you to make sure that you will not have collisions with external libraries. For example, if you will define Common class in your script and in the same time one of your external library will have class with the same name, and both of them will be in Global Context - you will have a problem, one of the implementation will override another.
When you do export module SignalRService and you don't use AMD compilation option for JS - you move all your implementation our of Global Context. When you don't do export module, but do AMD compilation - the problem with Global Context also got fixed. So, we can say - that if you application is based on AMD - you probably don't need to have export module.


text:
Q: \hbar new letter I would want to know in which package the symbol \hbar is defined. In fact I ask this because I need to create a letter like \hbar but with 'k' instead of 'h'.

A: \hbar is defined in the LaTeX kernel:
\newcommand{\hbar}{\mathchar'26\mkern-9mu h}

So
\newcommand{\kbar}{\mathchar'26\mkern-9mu k}

should do what you want (although it might need some customization if other fonts are used).


text:
Q: Exception in thread "main" java.lang.NoSuchMethodError Netbeans I have 3 files in my project, 2 class files and the main file. I get this error when I use netbeans and run the code.
Exception in thread "main" java.lang.NoSuchMethodError
This is the code in my main file:
package ejercicio1;

import java.util.Scanner;

public class Principal {
    private static Scanner teclado;
    //private static Persona persona;
    private static Alumno alumno;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    // Inicializamos el objeto para reservar espacio en memoria RAM
    //persona = new Persona();
    alumno = new Alumno();
    teclado = new Scanner(System.in);

    // Vamos solicitando al usuario cada dato y guardandolo en el objeto
// creado
    System.out.print("Introduce el nombre: ");
    **alumno.setNombre(teclado.nextLine());**

    System.out.print("Introduce los apellidos: ");
    alumno.setApellidos(teclado.nextLine());

    System.out.print("Introduce la edad: ");
    alumno.setEdad(teclado.nextInt());

    System.out.print("Introduce el curso: ");
    alumno.setCurso(teclado.nextLine());

    System.out.println();

    // Mostramos por pantalla los datos guardados en el objeto

    System.out.println(alumno.getNombre() + " " + alumno.getApellidos() + " tiene " + alumno.getEdad() + " años y cursa " + alumno.getCurso());
}

}

The error shows at this line: alumno.setNombre(teclado.nextLine());
This is my alumno.java file:
package ejercicio1;

public class Alumno extends Persona {
   // Definimos la variable propia de esta clase
    private String curso;

    // Creamos el constructor
public Alumno() {

}

    // Definimos el getter y setter de la variable
    public void setCurso(String curso){
        this.curso = curso;
    }

    public String getCurso(){
        return curso;
    }
}

And this is my Persona.java file
package ejercicio1;
public class Persona {
    String nombre, apellidos;
int edad;

    public Persona() {
    // No le pasamos parámetros ya que no es necesario
}

    public void setNombre(String nombre){
        this.nombre = nombre;
    }

    public void setApellidos(String apellidos){
        this.apellidos = apellidos;
    }

    public void setEdad(int edad){
        this.edad = edad;
    }

    public String getNombre(){
        return nombre;
    }

    public String getApellidos(){
        return apellidos;
    }

    public int getEdad(){
        return edad;
    }
}


text:
Q: SUM() function gives incorrect output I have a single table named trust_fund:
trust_fund table
My Query is:
$sql = "SELECT SUM(available_balance) AS total_fund FROM trust_funds WHERE type = 'Admin'";
at first, it displays 100000000 which is correct, but when I update the table (transfered 500 from Admin to Agent), Admin available_balance become 99,999,504 and Agent becomes 500.
There is an extra 4 in Admin Balance. I tried transfering the 500 back to Admin Account and Admin Account becomes 100000008.
The Output of the Query
I am confused because the tables shows correct values, 100000000 and 0, but running the query will give 100000004.
Please help
Table Definition

Column
Type

id
INT(AI)

uid
Text

available_balance
Float

wallet_address
Text

type
Text

A: Your problem arises from your use of the FLOAT data type for currency.
FLOAT is a poor choice for a currency column because it attracts errors from representation and rounding (See Is floating point math broken?)
Use INT (or BIGINT) if you're working with integer values. Alternatively, use DECIMAL to store and work with exact decimal values.


text:
Q: AWS lambda does not send return to SNS I try to send a message to an SNS topic after the lambda function is done.
For that I return from the lambda handler function the message (python).
Lambda executes without error and returns the message correctly. IAM is set to allow the lambda to publish to the specific SNS topic.
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "None",
            "Effect": "Allow",
            "Action": [
                "sns:Publish",
                "sns:Subscribe",
                "sns:ConfirmSubscription"
            ],
            "Resource": "arn:aws:sns:eu-central-1:123456789012:TOPIC"
        }
    ]
}

simplified code of lambda is:
#import packages

def handler(event, context) -> dict:
    """
    lambda handler function for invoking session

    param event: json/dict like key:val mapping for regular lambda invocations with custom topics (e.g. different data pipeline stage, different customers etc.)
    param context: AWS logging

    return: dict like key:val mapping to deliver custom topics to AWS Service invocations
    """

    #-----# key:val mapping #-----#
    '''
    '''
    Message = event["Records"][0]["Sns"]["Message"]
    Message = Message.replace("'", "\"")
    Message = json.loads(Message)

    #does lot's of stuff here
    #eg. getting data from S3, posting data to S3
    #send topic to SNS is NOT used, since it should be configured by the general lambda settings as endpoint destination.

    # -----# update key:val mapping #-----#
    event = {
        "timestamp": timestamp
    }

    return event

is there anything else one has to do? Because after inspecting cloudwatch logs, no messages arrive at the SNS.

A: Solution:
Used Test for testing, but it invokes the lambda function not async. Therefore the fault was in the kind of invokation.


text:
Q: A little C++ help please(repeated output) SO i have this code:
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{

    int x;
    x=rand();
    int guess;
    do{
        cout<<"Enter your guess:";
        cin>>guess;
        if(guess==x)cout<<"You got it ! ;)\n";
        else {
            cout<<"Wrong(";
            if (guess<x) cout<<"too small)\n";
            else cout<<"too big)\n";
        }

    } while (guess != x);

    return 0;
}

question: After compiling and running this program, i enter "999999999999" and it keeps repeating the "too big". why is this so?
additional info: when i set the value of x to constant 10, and i entered 11, i notice it only repeats "too big" once. is there something i am not aware of? or is the code flawed?
many thanks :)

A: If you look at data types, you will see that an int can only hold up to 2,147,483,6471. When you try and input a larger number than what your data type can hold than std::cout fails and it then tries and process it again in the next loop and that also fails and it sends you in an infinite loop.
You can fix your issue by using a bigger data type.

1 - The size of int depends on your machine, please check http://en.cppreference.com/w/cpp/language/types for the list of ranges that an int can hold

A: You are expecting this code to always be successful:
cin>>guess;

Types derived from std::ios_base like std::cin may go into an error state.
You can begin to handle this completely by using the stream in a bool context.
}while (cin && guess != x);

A: If you're curious about exactly what's going on, check out this cplusplus.com thread, where someone's having very similar problems reading too-large numbers from std::cin.  The second poster, "int main" sums it up very nicely (reformatted a bit for SO):

cin.fail() detects whether the value entered fits the value defined
  in the variable. But if cin.fail() is true, it means that:

*

*the entered value does not fit the variable

*the variable will not be affected

*the instream is still broken

*the entered value is still in the buffer and will be used for the next cin >> variable statement.

  Hence you have to do the following:

*

*repair the instream via cin.clear()

*clear the buffer with cin.ignore(std::numeric_limits<int>::max(), '\n')

I still find this behaviour bizarre and counterintuitive, but at least we know what's happening now.
Note: The statement "the variable will not be affected" isn't true, at least for my system (g++ 4.6).  The variable is in fact set to the maximum possible value.  Which makes leaving the entered value on the stream even less explicable...


text:
Q: Issue with Java classes not being resolved I'm working with JSP and Java, I'm getting an error stating DbSettings cannot be resolved.
I have created the class DbSettings and it's in my build folder and DbSettings.java is in my source folder.
Here is the stacktrace:
An error occurred at line: 53 in the jsp file: /currency_form.jsp
DbSettings cannot be resolved
50:         ResultSet rs = null;
51:         String message = null;
52:         try {
53:             rs = DbSettings
54:                     .getResultSet("SELECT BLMBG_CURR_CODE,BLMBG_CURR_NAME FROM AON_CURRENCY_SDO ORDER BY BLMBG_CURR_NAME");
55:             fEmptyRecordset = rs.first();
56:         } catch (Exception ex) {

Stacktrace:
    org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
    org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:366)
    org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:476)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:378)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:657)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Java Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DbSettings {
    private static Connection getConnection() throws Exception {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection conn = null;
        conn = DriverManager.getConnection(
                "jdbc:oracle:thin:@uschduxcls004sg08:xxxx:xxxxx",
            "xxxxx", "xxxx");
        return conn;

    }

    public static final ResultSet getResultSet(String command) throws Exception {
        Connection conn = getConnection();
        Statement stmt = null;
        stmt = conn.createStatement();
        System.out.println("Statement was Succesful");
        ResultSet rs = null;
        rs = stmt.executeQuery(command);
        System.out.println("Query was Succesful");
        return rs;

    }
}

JSP Code:
// Declare variables
boolean fEmptyRecordset, fFirstPass, fNeedRecordset;
        int i; // as Integer
        fEmptyRecordset = false;
        fFirstPass = true;
        fNeedRecordset = true;
        ResultSet rs = null;
        String message = null;
        try {
            rs = DbSettings
                    .getResultSet("SELECT BLMBG_CURR_CODE,BLMBG_CURR_NAME FROM AON_CURRENCY_SDO ORDER BY BLMBG_CURR_NAME");
            fEmptyRecordset = rs.first();
        } catch (Exception ex) {
            fEmptyRecordset = true;
            message = ex.getMessage();
        }
        String aMonth = "";
        int aDate, aYear;
        if ("results".compareToIgnoreCase(request.getParameter("action")) == 0) {
            aMonth = request.getParameter("selMonth");
            aDate = Integer.parseInt(request.getParameter("selDate"));
            aYear = Integer.parseInt(request.getParameter("selYear"));
        } else {
            switch (Calendar.getInstance().get(Calendar.MONTH)) {
            case Calendar.JANUARY:
                aMonth = "JAN";
            case Calendar.FEBRUARY:
                aMonth = "FEB";
            case Calendar.MARCH:
                aMonth = "MAR";
            case Calendar.APRIL:
                aMonth = "APR";
            case Calendar.MAY:
                aMonth = "MAY";
            case Calendar.JUNE:
                aMonth = "JUN";
            case Calendar.JULY:
                aMonth = "JUL";
            case Calendar.AUGUST:
                aMonth = "AUG";
            case Calendar.SEPTEMBER:
                aMonth = "SEP";
            case Calendar.NOVEMBER:
                aMonth = "NOV";
            case Calendar.DECEMBER:
                aMonth = "DEC";
            }
            aDate = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
            aYear = Calendar.getInstance().get(Calendar.YEAR);
        }
        if (message != null || fEmptyRecordset) {
            out.println("
");
            out.println(message);
            out.println("
");
    %>

A: Check that you have correctly imported DBSetting class in your JSP.
It is possible to use import statements in JSPs, but the syntax is a little different from normal Java.
This one is a page directive.  The page directive can contain the list of all imported packages.  To import more than one item, separate the package names by commas, e.g.
General Syntax :
<%@ page import="package1.myClass1,package2.myClass2,....,packageN.myClassN" %>

A: You have to either use fully qualified class name or add import for the DBSettings class
for eg. to import List class
<%@ page import="java.util.List" %>


text:
Q: In an onchange event, can you pass parameters that are not the current control? If I have a function:
function passSomeParams(p0, p1) {
    window.Location.href = "/something/anotherthing.aspx?firstParam=" +
        p0 + "&secondParam=" + p1;
}

Can I pass inputs other than the current control? I wanted to do something like this below, but wasn't able to get it to work or find resources online mentioning if it was possible or not.
<asp:CheckBox runat="server" ID="chkCheckboxA" />
<asp:CheckBox runat="server" ID="chkCheckboxB"
    onchange="passSomeParams(this.value, chkCheckboxA.value)"/>

Thanks. I appreciate the help.

A: If it has to be done the way you did, using inline event handler, then you can do it the following ways. But there are better ways!
function passSomeParams1(v1, v2) {
    //Option 1
    var param1 = v1;
    var param2 = v2;
    // --;
}
function passSomeParams2(v1, v2) {
    //Option 2
    var param1 = document.getElementById(v1).value;
    var param2 = document.getElementById(v2).value;
    // --;
}

Without inline event handler:
document.getElementById('second').addEventListener("change", function() {
    //Option 3
    var param1 = document.getElementById('first').value;
    var param2 = document.getElementById('second').value;
    // --;
});

jQuery:
$('#second').on("change", function() {
    //Option 4
    var param1 = $(this).val();
    var param2 = $("#first").val();
    // --;
});

HTML (sample)
<input type="checkbox" id="first" value="1" />
<input type="checkbox" id="second" value="2" onchange="passSomeParams1(this.value, document.getElementById('first').value)"/>

<input type="checkbox" id="first" value="1" />
<input type="checkbox" id="second" value="2" onchange="passSomeParams2(this.id, 'first')"/>


text:
Q: (Advanced Rest Client ,Postman) Vs chrome browser http request I am trying to make a Http post request from my angularjs application using $http provider. $http provider is nothing just an angular wrapper for xmlHttprequest object. For a POST request , I am getting response by using Advanced Rest Client /Postman, But the same call is not finishing with angularjs http call.
Advanced Rest Client/Postman sending content-type:application/json.
So my question is , What difference it makes for calls going from  Advanced Rest Client/Postman Or a browser?


text:
Q: Random variables - proof of convergence in probability I've got this exercise from lecture notes, but I couldn't find an answer.
For each positive integer $n$, let $X_{n}$ be a non-negative random variable with $\mathbb{E}[X_{n}] < \infty$.
Prove that if $\lim_{n\to\infty}\mathbb{E}[X_{n}] = 0$, then $X_{n} \xrightarrow{\mathbb{P}} 0$, i.e., for every $\epsilon > 0$, $\lim_{n\to\infty}\mathbb{P}[|X_{n}| \geq \epsilon] = 0$.
I tried using Chebyshev inequality, but it goes nowhere and not noticing my mistakes is driving me mad. I'd be glad if someone can give me a hint, please.

A: According to Markov Inequality, we have $P(X\geq a)\leq \frac{E[X]}{a}$, where $a$ is positive and $X$ is a non-negative random variable. If we apply the same here:
$$P(X_n\geq \epsilon)\leq \frac{E[X_n]}{\epsilon} \rightarrow \lim_{n\rightarrow\infty}P(X_n\geq \epsilon)\leq \lim_{n\rightarrow\infty}\frac{E[X_n]}{\epsilon}=0$$
So, we have $\lim_{n\rightarrow\infty}P(X_n\geq \epsilon)\leq 0$, which means it is equal to $0$, since a probability value is non-negative. Also, since the variable is non-negative, we have $X_n=|X_n|$, which finally yields $\lim_{n\rightarrow\infty}P(|X_n|\geq\epsilon)=0$, i.e. $X_n\xrightarrow{\mathbb{P}} 0$.


text:
Q: How do I execute an async/await function without using any external dependencies? I am attempting to create simplest possible example that can get async fn hello() to eventually print out Hello World!. This should happen without any external dependency like tokio, just plain Rust and std. Bonus points if we can get it done without ever using unsafe.
#![feature(async_await)]

async fn hello() {
    println!("Hello, World!");
}

fn main() {
    let task = hello();

    // Something beautiful happens here, and `Hello, World!` is printed on screen.
}

*

*I know async/await is still a nightly feature, and it is subject to change in the foreseeable future.

*I know there is a whole lot of Future implementations, I am aware of the existence of tokio.

*I am just trying to educate myself on the inner workings of standard library futures.

My helpless, clumsy endeavours
My vague understanding is that, first off, I need to Pin task down. So I went ahead and
let pinned_task = Pin::new(&mut task);

but
the trait `std::marker::Unpin` is not implemented for `std::future::GenFuture<[static generator@src/main.rs:7:18: 9:2 {}]>`

so I thought, of course, I probably need to Box it, so I'm sure it won't move around in memory. Somewhat surprisingly, I get the same error.
What I could get so far is
let pinned_task = unsafe {
    Pin::new_unchecked(&mut task)
};

which is obviously not something I should do. Even so, let's say I got my hands on the Pinned Future. Now I need to poll() it somehow. For that, I need a Waker.
So I tried to look around on how to get my hands on a Waker. On the doc it kinda looks like the only way to get a Waker is with another new_unchecked that accepts a RawWaker. From there I got here and from there here, where I just curled up on the floor and started crying.

A: This part of the futures stack is not intended to be implemented by many people. The rough estimate that I have seen in that maybe there will be 10 or so actual implementations.
That said, you can fill in the basic aspects of an executor that is extremely limited by following the function signatures needed:
async fn hello() {
    println!("Hello, World!");
}

fn main() {
    drive_to_completion(hello());
}

use std::{
    future::Future,
    ptr,
    task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
};

fn drive_to_completion<F>(f: F) -> F::Output
where
    F: Future,
{
    let waker = my_waker();
    let mut context = Context::from_waker(&waker);

    let mut t = Box::pin(f);
    let t = t.as_mut();

    loop {
        match t.poll(&mut context) {
            Poll::Ready(v) => return v,
            Poll::Pending => panic!("This executor does not support futures that are not ready"),
        }
    }
}

type WakerData = *const ();

unsafe fn clone(_: WakerData) -> RawWaker {
    my_raw_waker()
}
unsafe fn wake(_: WakerData) {}
unsafe fn wake_by_ref(_: WakerData) {}
unsafe fn drop(_: WakerData) {}

static MY_VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake_by_ref, drop);

fn my_raw_waker() -> RawWaker {
    RawWaker::new(ptr::null(), &MY_VTABLE)
}

fn my_waker() -> Waker {
    unsafe { Waker::from_raw(my_raw_waker()) }
}

Starting at Future::poll, we see we need a Pinned future and a Context. Context is created from a Waker which needs a RawWaker. A RawWaker needs a RawWakerVTable. We create all of those pieces in the simplest possible ways:

*

*Since we aren't trying to support NotReady cases, we never need to actually do anything for that case and can instead panic. This also means that the implementations of wake can be no-ops.

*Since we aren't trying to be efficient, we don't need to store any data for our waker, so clone and drop can basically be no-ops as well.

*The easiest way to pin the future is to Box it, but this isn't the most efficient possibility.

If you wanted to support NotReady, the simplest extension is to have a busy loop, polling forever. A slightly more efficient solution is to have a global variable that indicates that someone has called wake and block on that becoming true.


text:
Q: VB.NET, MySQL & Crystal Report comparative statement between two tables My two MySQL tables have different information but one field is common. I am showing you the structure of two tables.

I need to show it in a single report filtering by cust_id.
i.e. Customer Id wise billing and payment report.
I tried...
SELECT * FROM billing_info as a,payment_info as b WHERE a.cust_id='1' AND b.cust_id='1' AND a.cust_id=b.cust_id
but rows are repeating.
Hope I explained this properly. Now what should I do ?
Is it possible in Crystal Report to show two tables data ?

A: I guess ur table structure may resulting duplicate entries.
in table payment_info instead of using the cust_id (reference of cust table),  u should use id of table billing_info so that we will get more precised output for ur query.
U also get payment details agains which bill has been made.


text:
Q: Android Studio using the UserVoice Java SDK I just created a new project in Android Studio and want to add the UserVoice Java SDK as a dependency.
I'm adding the line compile 'com.uservoice:uservoice-java:0.0.2' to the app build.gradle file in the dependencies block.
When I try to build it will fail the build with
Output:
    UNEXPECTED TOP-LEVEL EXCEPTION:
    com.android.dex.DexException: Multiple dex files define Lorg/apache/commons/collections/Buffer;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:594)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:552)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:533)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:170)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:188)
        at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439)
        at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287)
        at com.android.dx.command.dexer.Main.run(Main.java:230)
        at com.android.dx.command.dexer.Main.main(Main.java:199)
        at com.android.dx.command.Main.main(Main.java:103)

At this point I have not modified the project in any way.
Is there any way to exclude the offending dependencies and getting the UserVoice SDK to work?
Thanks!

A: The above didn't work for me, what was needed was to exclude the commons-collection dependency from uservoice.
compile('com.uservoice:uservoice-java:0.0.2'){
    exclude group: 'commons-collections'
}

This along with the following allowed it to play nice with gradle:
packagingOptions {
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
}

A: I managed to get this working finally.
What I did was add
dexOptions {
   preDexLibraries = false
}

to the build.gradle android block. This was suggested here
I had to also add
packagingOptions {
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
}

to the same block.


text:
Q: Simultaneously bluetooth remote (android) and run program I'm a student on a hogeschool in the Netherlands. We're working with the LEGO Mindstorms NXT for a project.
However, I'm using my phone (minddroid and other applications) to drive the NXT, but I don't know how to simultaneously run a program.
For example, I drive it over a black line with the remote, and because the program is running, the sensor sees in the program that if it drives over a black line, it has to stop.

A: Is your question how to get the NXT to both communicate on bluetooth and monitor the line at the same time? If so:
Then there are two general solutions:
Main Loop
In your main loop, first check for communications from the bluetooth system, and then check the sensor to see if the black line is detected. Then repeat.
Interrupt
In this solution, the main process would handle communications with the Android phone. The line sensor would be setup to cause a program interrupt when it detects the black line.
The interrupt service routine (ISR) would either set a flag to indicate that the robot should stop or would directly stop the robot.
Choosing which of the above solutions you choose is often dependent on the features of your operating system.
PS It could also be that I'm not understanding your question correctly. In that case, never mind...

A: No I meant that I wanted to run a program simultaneously with the bluetooth remote.
But I solved it, I connected the nxt with a mobile app, so I could only send direct commands. I solved it by connecting with the program, not the nxt robot.
Thanks anyway!


text:
Q: Custom JWT Auth with Spring Webflux I'm trying to setup authentication with JWT with Spring Security inside a Spring WebFlux application. I'm using a custom authorization scheme based on custom JWT claims. The problem I'm having is that when I try to invoke a secured endpoint authentication fails with Authentication failed: An Authentication object was not found in the SecurityContext.
Here is the SecurityWebFilterChain I'm using:
@Configuration
@EnableWebFluxSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class WebSecurityConfiguration {
    @Bean
    fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {

        return http {

            authorizeExchange {
                authorize(anyExchange, authenticated)
            }

            oauth2ResourceServer {
                jwt {
                    jwtAuthenticationConverter = grantedAuthoritiesExtractor()
                }
            }
        }
    }

    fun grantedAuthoritiesExtractor(): Converter<Jwt, Mono<AbstractAuthenticationToken>> {
        val jwtAuthenticationConverter = JwtAuthenticationConverter()
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(MappingJwtAuthoritiesConverter())
        //               custom JWT -> Collection<GrantedAuthority>  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        return ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter)
    }

    @Bean
    fun jwtDecoder(): ReactiveJwtDecoder {
        val secretKey: SecretKey = SecretKeySpec("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".toByteArray(), "HMACSHA256")

        return NimbusReactiveJwtDecoder.withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS256).build()
    }

    @Bean
    fun jwtValidator(): OAuth2TokenValidator<Jwt> {
        return OAuth2TokenValidator<Jwt> { OAuth2TokenValidatorResult.success() }
    }

    fun jwtAuthenticationManager(jwtDecoder: ReactiveJwtDecoder): JwtReactiveAuthenticationManager {
        return JwtReactiveAuthenticationManager(jwtDecoder).apply {
            this.setJwtAuthenticationConverter(grantedAuthoritiesExtractor())
        }
    }
}

Here is MappingJwtAuthoritiesConverter:
class MappingJwtAuthoritiesConverter : Converter<Jwt, Collection<GrantedAuthority>> {
    companion object {
        private val WELL_KNOWN_CLAIMS: Set<String> = setOf("myCustomClaim")
    }

    override fun convert(jwt: Jwt): Collection<GrantedAuthority> {
        val authorities = jwt.claims.entries
            .filter { (key, _) -> key in WELL_KNOWN_CLAIMS }
            .map { (key, value) ->
                return@map SimpleGrantedAuthority("$key:$value")
            }

        return authorities
    }
}

I searched online but many JWT/Spring Webflux implementation hand-roll JWT validation and handling, and I'd rather use what's already offered by Spring under OAuth integration. Right now the only custom piece I'm using is the converter from JWT to GrantedAuthority, but I still can't get authentication to work.
With the following JWT:
header:
{
  "typ": "JWT",
  "alg": "HS256"
}

payload:
{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1658474926,
  "exp": 1668478526,
  "myCustomClaim": "READ"
}

Encoded:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNjU4NDc0OTI2LCJleHAiOjE2Njg0Nzg1MjYsIm15Q3VzdG9tQ2xhaW0iOiJSRUFEIn0.lh66pHMd_xvXAF2itblHeHbZReJQA5xkGLKqXZV6MjI
The endpoint I'm trying to secure is defined as:
@RestController
class FooController {
    @PreAuthorize("hasAuthority('myCustomClaim:READ')")
    @RequestMapping(
            method = [RequestMethod.GET],
            value = ["/foo"],
    )
    override suspend fun getFoo(): ResponseEntity<String> {
        return ResponseEntity.ok("Got foo")
    }
}

Spring logs:
2022-07-22 09:43:35.138 DEBUG 508191 --- [ctor-http-nio-2] o.s.w.s.adapter.HttpWebHandlerAdapter    : [b7fe0c9e-1] HTTP GET "/foo"
2022-07-22 09:43:35.313 DEBUG 508191 --- [     parallel-2] o.s.w.s.s.DefaultWebSessionManager       : Created new WebSession.
2022-07-22 09:43:35.319 DEBUG 508191 --- [     parallel-2] o.s.s.w.s.u.m.OrServerWebExchangeMatcher : Trying to match using org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers$1@3602a026
2022-07-22 09:43:35.319 DEBUG 508191 --- [     parallel-2] o.s.s.w.s.u.m.OrServerWebExchangeMatcher : matched
2022-07-22 09:43:35.319 DEBUG 508191 --- [     parallel-2] a.DelegatingReactiveAuthorizationManager : Checking authorization on '/foo' using org.springframework.security.authorization.AuthenticatedReactiveAuthorizationManager@2668fdab
2022-07-22 09:43:35.320 DEBUG 508191 --- [     parallel-2] o.s.s.w.s.a.AuthorizationWebFilter       : Authorization successful
2022-07-22 09:43:35.325 DEBUG 508191 --- [     parallel-2] s.w.r.r.m.a.RequestMappingHandlerMapping : [b7fe0c9e-1] Mapped to it.project.backend.controllers.FooController#getFoo(Continuation)
2022-07-22 09:43:35.665 DEBUG 508191 --- [     parallel-2] o.s.s.w.s.a.AuthenticationWebFilter      : Authentication failed: An Authentication object was not found in the SecurityContext
2022-07-22 09:43:35.694 DEBUG 508191 --- [     parallel-2] o.s.w.s.adapter.HttpWebHandlerAdapter    : [b7fe0c9e-1] Completed 401 UNAUTHORIZED

Any ideas?

A: The problem was using @EnableGlobalMethodSecurity instead of @EnableReactiveMethodSecurity in the configuration bean. After fixing that everything started to work.

A: Looks like the secret key you constructed your jwtDecoder with does not correspond to the signature of the token you posted and thus the token validation fails.
You can use https://jwt.io/ to check that.


text:
Q: Adding multiple Images to LinearLayout programmatically I am trying to add multiple ImageViews to a LinearLayout. The LinearLayout is defined in the xml but I am trying to create the ImageViews with code. So far my code just makes one image in the middle even though I am trying to add the the view multiple times.
Here is my main method:
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LinearLayout lay = (LinearLayout)findViewById(R.id.layout);
    ImageView[] views = new ImageView[10];
    for (int i=0;i<10;i++){
        views[i] = new ImageView(this);
        views[i].setImageResource(R.drawable.redeight);
        lay.addView(views[i]);
    }
}
}

Here is the xml:
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/layout"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent">

 </LinearLayout>

A: Try this in you for loop
ImageView iv = new ImageView(this);
ViewGroup.LayoutParams params = iv.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT; // Or a custom size
params.width = ViewGroup.LayoutParams.WRAP_CONTENT; // Or a custom size
iv.setLayoutParams(params);
iv.setImageResource(R.drawable.redeight);

views[i] = iv;
lay.addView(iv);


text:
Q: How to get referenced pipeline run via rest api? Using Azure Pipelines, I have a yaml pipeline with a pipeline resource specified:
https://learn.microsoft.com/en-us/azure/devops/pipelines/process/resources?view=azure-devops&tabs=schema#define-a-pipelines-resource
resources:
  pipelines:
  - pipeline: Workload
    source: Build Azure Function App

In the Run dialog you are then able to pick a run of this referenced pipeline as an input to the pipeline you are planning to run.
I would like to query previous pipeline runs through rest api in order to retrieve the particular run the pipeline has run against.
I tried the following rest api:
az rest -m get -u https://dev.azure.com/myorg/myproject/_apis/pipelines/20/runs/713?api-version=6.0-preview.1 --resource 499b84ac-1321-427f-aa17-267ca6975798 -o json
But this does not seem to yield the referenced pipeline run.
Any clues?

A: From the GET Run REST API, the response body does not contain the source pipeline: https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/runs/get?view=azure-devops-rest-6.0#pipelinereference
The Pipeline Reference part carries the below information:

Checking the sample response body:

Source is defined in the Pipeline resource, but the GET Run API does not recall .


text:
Q: If statements to check every permutation Hi I am trying to evaluate a list of 3 data records coming back from database.
I need to check if these values are null & replace with a "-" symbol.
The problem I end up is having a very long list of if statements, is there an easy way to do this?
if (row count == 1)
{
    if (only firstNull)
    {
        //Replace first.label with "-"
    }
    else if (only secondNull)
    {
        //Replace second.label with "-"
    }
    else if (only thirdNull)
    {
        //Replace third.label with "-"
    }
    else if (only (firstNull && secondNull))
    {
        //Replace first.label = "-" & second.label = ""
    }
    else if (only (secondNull && thirdNull))
    {
        //Replace second & third label = "-"
    }
    else if (only (thirdNull && firstNull))
    {
        //Replace third && first label = "-"
    }
}
else
{
    // Replace all labels with "-"
}

A: When you access the specified fields you can use the nullable operator:
field ?? "-". This will yield the field name or "-" if field==null.
for example
Object field = null;
System.Console.WriteLine(field ?? "field is null");

will output:

field is null

without throwing an exception.

A: I don't understand why you have so many clauses...  If a field is null, you want to replace it with "-"... You have 3 fields, you should at most have 3 clauses...  (Note, this is pseudocode, to match your question)
if (row count == 1)
{
    if (firstNull)
    {
        //Replace first.label with "-"
    }
    if (secondNull)
    {
        //Replace second.label with "-"
    }
    if (thirdNull)
    {
        //Replace third.label with "-"
    }
}
else
{
    // Replace all labels with "-"
}

You don't need to handle every combination of the 3 fields as separate ifs...
Ideally your fields would be stored in some kind of collection (which you've omitted), that way you would be able to do something like:
if(row count == 1)
{
    foreach(field in Fields)
    {
        if(fieldIsNull)
        {
            // Set corresponding label to "-"
        }
    }
}

As an aside, if you always want to do a translation when reading from the database, so that if it is NULL, you want '-', then it may make sense to handle this as part of your select clause.  So, with Oracle you could have:
SELECT
    NVL(FIELD1, '-'),
    NVL(FIELD2, '-'),
    NVL(FIELD3, '-')
FROM
    SOME_TABLE

I think for SQLServer, the equivalent would be:
SELECT
    ISNULL(FIELD1, '-'),
    ISNULL(FIELD2, '-'),
    ISNULL(FIELD3, '-')
FROM
    SOME_TABLE

Both of these would mean that the database returned '-' instead of NULL if the column was empty.  This does of course assume that the column you're returning is a string type.  If not, you would have to perform the appropriate conversion on the field to turn it into one.

A: Use a loop to go through each record and check whether they are null. If the record you are looking at is null, replace it with "-".


text:
Q: How to calculate size of a GIF image? I want to convert my video 9 seconds to GIF. I choose the following parameters:
FPS: 7 , Scale: original (720x1152).
In the result I get a gif with size 4.67MB.
Can anybody show me how to guess size of gif depending on input parameters?

A: If the gif has a BitDepth of 8 bit (256 color) then
(x * y * fps * length) / 8 = size in bytes

But gif uses compression so this is not always true.


text:
Q: How can i use jQuery selector inside (tornado) template tag? I hope i am asking the right question. Basically, i have python/tornado app and i have an issue populating two combo boxes in my html page. I am trying to populate the second combo box  depending on the selected value in the first one. In my python settings file i have json data with following structure:
data = {'A':{
            '1': {},
            '2': {},
            '3': {}
            },
        'B': {
             '3': {},
             '4': {}
             }
       }

The first combo box contains values A and B, and if A is selected then the second combo box should contain 1, 2 and 3... I try to load it like this:
{% block filter1 %}
<select id="filter1">
{% for key in settings.data %}
    <option value="{{ key }}">{{key}}</option>
{% end %}
</select>
{% end %}

{% block filter2 %}
<select id="filter2">
{% for key in settings.data[$("#filter1").val()] %}
    <option value="{{ key }}">{{key}}</option>
{% end %}
</select>
{% end %}

The problem is obviously settings.data[$("#filter1").val()], it's both serverside and clientside code, and i cannot use it like that. Is there an 'easy' way to get that kind of behavior? Am i maybe missing something obvious, or should i use some different approach?

A: You are correct that this is the issue

{% for key in settings.data[$("#filter1").val()] %}

There is no getting around having this work up front though. Since this is going to be dependent on client interaction, the code to handle that interaction must be client side.
What this means is that you will need to do this with javascript and not simply server side code (unless there is a helper for generating this type of javascript). Essentially it will be along the lines of a script tag or reference, an onchange event, and some sort of population logic which draws on elements on the page or perhaps some sort of json storage.


text:
Q: How can I run a soundcloud file on the onload procedure in a html file I want to replace an existing miniplayer on a website which starts playing after opening the page though an onload JavaScript.

A: The soundcloud custom player widget has an autoplay option which looks like it would suit your needs.
http://developers.soundcloud.com/docs/custom-player


text:
Q: Finding an angle in a triangle, when the length of one side is unknown and the distances from each vertex to an arbitrary point is known Given the triangle $\triangle ABN$ I would like to find the angle $\angle ANB$. The lengths of $AN$ and $BN$ are known, but the length $AB$ is unknown.
There exists another point $S$ that forms two more triangles $\triangle ANS$ and $\triangle BNS$. The lengths of $NS, AS$ and $BS$ are known. The location of $S$ is arbitrary, it may be inside or outside $\triangle ABN$.
Using these triangles $\angle ANS$ and $\angle BNS$ can be calculated. These can then be used to find $\angle ANB$. However, There are multiple ways to calculate ANB depending on the position of $S$, as shown by these two figures:

I've also come up with other equations that are required when $S$ is in different positions.
Is there a better way to find $\angle ANB$?
If there is not, is there a way to determine which of the equations to use to calculate $\angle ANB$ from $\angle ANS$ and $\angle BNS$?
The coordinates of the four points $A$, $B$, $N$ and $S$ are all unknown.

A: You can use Cayley–Menger determinants. Writing $ab$ for the distance between $a$ and $b$, you get
$$\begin{vmatrix}
0 & SA^2 & SB^2 & SN^2 & 1 \\
SA^2 & 0 & AB^2 & AN^2 & 1 \\
SB^2 & AB^2 & 0 & BN^2 & 1 \\
SN^2 & AN^2 & BN^2 & 0 & 1 \\
1 & 1 & 1 & 1 & 0
\end{vmatrix}=0$$
This will lead to a quadratic equation in $AB^2$, which will give you two possible solutions. For each possible value of $AB^2$ you of course take the positive square root as $AB$. But that still leaves you with two solutions, and unless you have additional information, both of them are valid.
Here is one way to think about the two solutions. Since you know $AN, SA, SN$ you can construct $\triangle ANS$ uniquely up to a congruence transformation. The same holds for $\triangle BNS$ taken by itself. But if you combine them along the edge $NS$, you have to make a choice: are $A$ and $B$ on the same side of $NS$, or on different sides? Or in other words, do the triangles have the same or opposite orientation. Either solution would be valid, either would satisfy all your length requirements, but they would lead to different distances $AB$ and different angles $\gamma$. The following picture illustrates this:

Once you have $AB$, you can compute $\gamma$ from that using the cosine law:
$$\gamma=\arccos\frac{AN^2+BN^2-AB^2}{2\cdot AN\cdot BN}$$
The result will be in the range $[0°,180°]$, i.e. unsigned and no reflex angles. Which is what's to be expected if all you have are lengths.

A:
As stated, the problem does not necessarily have a single solution. Example:
AN = 1.0, BN = 0.65, NS = 0.92, AS = 0.81, BS = 0.35
B's coordinates can be either {0.45509,0.354363} or
{0.733145,0.592696}, and the values of angle ANB is different for
these two sets of coordinates.
Note that I am using approximate numbers here, but the roundoff errors
are small enough to be ignored.
I hope to expand on my answer by providing a closed formula for the
two possible values of ANB (when they exist).
EDIT: General answer:
Create a Cartesian grid such that $N$ is at the origin, $A$ lies on
the positive x axis and $S$ lies in the upper half plane. You can
always do this using translation, rotation, and reflecting without
affecting any lengths:

(note that $A$ and $N$ above are flipped from my counterexample
earlier, as it turns out the calculations are easier with $N$ at the
origin; I've also replaced the side lengths with lowercase letters
since I'm using Mathematica to help solve this problem)
Although I've draw B and S in quadrant I, B can be in any quadrant,
and S can be in quadrants I or II (since we explicitly chose our axis
system so that sy > 0).
We can now find sx and sy by solving the simultaneous equations:
$\text{sx}^2+\text{sy}^2=d^2$
$(\text{sx}-c)^2+\text{sy}^2=e^2$
The are two solutions, but only one with sy > 0:
$
   \left\{\text{sx}\to \frac{c^2+d^2-e^2}{2 c},\text{sy}\to
    \sqrt{d^2-\frac{\left(c^2+d^2-e^2\right)^2}{4 c^2}}\right\}
$
We can now solve for bx and by using:
$(\text{bx}-\text{sx})^2+(\text{by}-\text{sy})^2=f^2$
$\text{bx}^2+\text{by}^2=g^2$
and plugging in the values of sx and sy we found earlier, yielding two
solutions, both valid:
$
   \left\{\text{bx}\to \frac{\left(c^2+d^2-e^2\right)
    \left(d^2-f^2+g^2\right)+\sqrt{(c-d-e) (c+d-e) (c-d+e) (c+d+e) (d-f-g)
    (d+f-g) (d-f+g) (d+f+g)}}{4 c d^2},\text{by}\to -\frac{c^4
    \left(d^2-f^2+g^2\right)+c^2 \left(\sqrt{(c-d-e) (c+d-e) (c-d+e) (c+d+e)
    (d-f-g) (d+f-g) (d-f+g) (d+f+g)}-2 \left(d^2+e^2\right)
    \left(d^2-f^2+g^2\right)\right)+(d-e) (d+e) \left(\sqrt{(c-d-e) (c+d-e)
    (c-d+e) (c+d+e) (d-f-g) (d+f-g) (d-f+g) (d+f+g)}+(d-e) (d+e)
    \left(d^2-f^2+g^2\right)\right)}{4 c d^2 \sqrt{-(c-d-e) (c+d-e) (c-d+e)
    (c+d+e)}}\right\}
$
$
   \left\{\text{bx}\to \frac{\left(c^2+d^2-e^2\right)
    \left(d^2-f^2+g^2\right)-\sqrt{(c-d-e) (c+d-e) (c-d+e) (c+d+e) (d-f-g)
    (d+f-g) (d-f+g) (d+f+g)}}{4 c d^2},\text{by}\to \frac{c^4
    \left(-\left(d^2-f^2+g^2\right)\right)+c^2 \left(\sqrt{(c-d-e) (c+d-e)
    (c-d+e) (c+d+e) (d-f-g) (d+f-g) (d-f+g) (d+f+g)}+2 \left(d^2+e^2\right)
    \left(d^2-f^2+g^2\right)\right)+(d-e) (d+e) \left(\sqrt{(c-d-e) (c+d-e)
    (c-d+e) (c+d+e) (d-f-g) (d+f-g) (d-f+g) (d+f+g)}-(d-e) (d+e)
    \left(d^2-f^2+g^2\right)\right)}{4 c d^2 \sqrt{-(c-d-e) (c+d-e) (c-d+e)
    (c+d+e)}}\right\}
$
To find ABN, we simply take the arctangent of
$\frac{\text{by}}{\text{bx}}$. Since the angle will always be between
0 and 180 degrees (if it's larger than 180 degrees, we measure the
angle clockwise), we can use the single argument form of arctangent
(I'd stated incorrectly earlier than we needed the two argument
form. This yields:
$
   -\tan ^{-1}\left(\frac{c^4 \left(d^2-f^2+g^2\right)+c^2 \left(\sqrt{(c-d-e)
    (c+d-e) (c-d+e) (c+d+e) (d-f-g) (d+f-g) (d-f+g) (d+f+g)}-2
    \left(d^2+e^2\right) \left(d^2-f^2+g^2\right)\right)+(d-e) (d+e)
    \left(\sqrt{(c-d-e) (c+d-e) (c-d+e) (c+d+e) (d-f-g) (d+f-g) (d-f+g)
   (d+f+g)}+(d-e) (d+e) \left(d^2-f^2+g^2\right)\right)}{\sqrt{-(c-d-e) (c+d-e)
    (c-d+e) (c+d+e)} \left(\left(c^2+d^2-e^2\right)
    \left(d^2-f^2+g^2\right)+\sqrt{(c-d-e) (c+d-e) (c-d+e) (c+d+e) (d-f-g)
    (d+f-g) (d-f+g) (d+f+g)}\right)}\right)
$
$
   \tan ^{-1}\left(\frac{c^4 \left(-\left(d^2-f^2+g^2\right)\right)+c^2
    \left(\sqrt{(c-d-e) (c+d-e) (c-d+e) (c+d+e) (d-f-g) (d+f-g) (d-f+g)
    (d+f+g)}+2 \left(d^2+e^2\right) \left(d^2-f^2+g^2\right)\right)+(d-e) (d+e)
    \left(\sqrt{(c-d-e) (c+d-e) (c-d+e) (c+d+e) (d-f-g) (d+f-g) (d-f+g)
   (d+f+g)}-(d-e) (d+e) \left(d^2-f^2+g^2\right)\right)}{\sqrt{-(c-d-e) (c+d-e)
    (c-d+e) (c+d+e)} \left(\left(c^2+d^2-e^2\right)
    \left(d^2-f^2+g^2\right)-\sqrt{(c-d-e) (c+d-e) (c-d+e) (c+d+e) (d-f-g)
    (d+f-g) (d-f+g) (d+f+g)}\right)}\right)
$
Mathematica can't find a simpler form for the answer, and I'm not sure
how useful the above is, but there you have it.
Note that I assume the triangle inequality throughout. When the
triangle inequality doesn't hold, some of the square roots above are
of negative values, and thus have no real number solutions.


text:
Q: kotlin: retrofit2 getting 404 url not found error Getting Response{protocol=http/1.1, code=404, message=Not Found, url=https://test.test.com/service/one}
The url is correct as postman works fine.
I have tried looking into this error but most things come back with URL was in correct. and the error itself is vague.
code that starts it. the builder is a json string that is valid. I have tested it in postman.
    CoroutineScope(Dispatchers.Default).launch {

        val call = submitService.submitCarton(builder.toString())
        Log.d("submit", "begining")
        withContext(Dispatchers.Main) {
            if (call.isSuccessful) {
                Log.d("submit",call.body() as String)

            } else {
                Log.d("submit", "else....")

            }
        }
    }

service factory:
    fun makeSubmitService() : SubmitService{
    val url =  "https://test.test.com/service/"
    return Retrofit.Builder().baseUrl(url)
        .client(okHttpClient).addConverterFactory(GsonConverterFactory.create())
        .build().create(SubmitService::class.java)
}

interface:
interface SubmitService {
@POST("one")
suspend fun submitCarton(@Body json: String): Response<myModel>
}

Expected results are a json response however I am not getting that far.
edit: I created a okhttpclient and did a request manual and I get a message 200 ok.
code for my test
    val JSON = MediaType.parse("application/json; charset=utf-8")
    val client = OkHttpClient()
    val body = "some json"
    val requestBody = RequestBody.create(JSON, body)
    val request = Request.Builder()
            .url("https://test.test.com/service/one")
            .post(requestBody)
            .build()

    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(request: Request, e: IOException) {

            Log.e("test", e.toString())
        }

        @Throws(IOException::class)
        override fun onResponse(response: Response) {

            Log.d("test", response.toString())
        }

    })

A: Solved it myself.
Issue was dumb, retrofit2 was giving 404 even though the web service was returning a error message.
added
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'

private val interceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)

private val okHttpClient = OkHttpClient().newBuilder()
    .connectTimeout(1, TimeUnit.MINUTES)
    .readTimeout(30, TimeUnit.SECONDS)
    .writeTimeout(20, TimeUnit.SECONDS)
    .addInterceptor(interceptor)
    .build()

found out retrofit was sending a very unformatted string
"{ \"all my json filled with \" }"

instead of
{ json }

fixed it by adding
.addConverterFactory(ScalarsConverterFactory.create())

to my service factory
for anyone wondering why I am basically creating the json as a string instead of using a JSON object is because the service I talk to really really wants it to be in a very specific order which JSON just don't care about it however it wants it to look like JSON as well...


text:
Q: Azure PowerShell vs Azure CLI; creating an ACI OWASP ZAP container issue I am trying to set up an automated DAST scan via Azure Powershell and hosted in the Azure cloud. I want to use Azure powershell as it gives me a bit more control and integration possibilities.
The Azure CLI I have working :
rem Create the container
call az container create -g %ACI_RESOURCE_GROUP% -n %ACI_INSTANCE_NAME% --image owasp/zap2docker-stable --ip-address public --ports 8080 --azure-file-volume-account-name %ACI_STORAGE_ACCOUNT_NAME% --azure-file-volume-account-key %STORAGE_KEY% --azure-file-volume-share-name %ACI_SHARE_NAME% --azure-file-volume-mount-path /zap/wrk/
--command-line "zap.sh -daemon -host 0.0.0.0 -port 8080 -config api.key=abcd -config api.addrs.addr.name=.* -config api.addrs.addr.regex=true"

However doing it in Azure Powershell, a bit more commands are required, but I :
$volume = New-AzContainerGroupVolumeObject -Name "owasp-dast-volume" -AzureFileShareName $storageAccountShareName -AzureFileStorageAccountName $storageAccountName -AzureFileStorageAccountKey (ConvertTo-SecureString $key -AsPlainText -Force)
$mount = New-AzContainerInstanceVolumeMountObject -MountPath "/zap/wrk/ " -Name "owasp-dast-volume"
$container = New-AzContainerInstanceObject -Name $AzureContainerInstanceName  -Image owasp/zap2docker-stable
-Command 'zap.sh -daemon -host 0.0.0.0 -port 8080 -config api.key=abcd -config api.addrs.addr.name=.* -config api.addrs.addr.regex=true'
#

New-AzContainerGroup -ResourceGroupName $ResourceGroupName -Name 'owasp-zap-cg' -Container $container -Volume $volume -location $location  -IPAddressType 'Public' -OSType 'Linux'

It appears as to be failing because of the command argument in Azure Powershell, which is the exact same as it is in the Azure Cli, but in PowerShell
z.ContainerInstance.internal\New-AzContainerGroup : CodePackageActivation:owasp-zap-scfobt2:EntryPoint:133186770245706206'. 'There was an error during CodePackage activation.GrpcStatusCode=UNKNOWN,
ErrorMessage=failed to create containerd task: failed to create shim task: failed to create container fadcb85315c2a29c90a44973cc69e550fa8752257b408d399fcdbb759740b956: guest RPC failure: failed to create
container: failed to run runc create/exec call for container fadcb85315c2a29c90a44973cc69e550fa8752257b408d399fcdbb759740b956 with exit status 1: container_linux.go:380: starting container process
caused: exec: "zap.sh -daemon -host 0.0.0.0 -port 8080 -config api.key=abcd -config api.addrs.addr.name=.* -config api.addrs.addr.regex=true": executable file not found in $PATH: unknown'
;The container group provisioning has failed. Refer to 'DeploymentFailedReason' event for more details.
At C:\Program Files\WindowsPowerShell\Modules\Az.ContainerInstance\3.1.0\custom\New-AzContainerGroup.ps1:315 char:7
+       Az.ContainerInstance.internal\New-AzContainerGroup @PSBoundPara ...
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: ({ SubscriptionI...    ]
  }
} }:<>f__AnonymousType9`4) [New-AzContainerGroup_CreateExpanded], UndeclaredResponseException
    + FullyQualifiedErrorId : OK,Microsoft.Azure.PowerShell.Cmdlets.ContainerInstance.Cmdlets.NewAzContainerGroup_CreateExpanded

I really have no idea what I am doing wrong, as it appears that Powershell complains over  the zap.sh file missing on the container, but I am using the same image (and version) that I really dont see the issue. If someone could enlighten me where I am going wrong that would be amazing

A: I think you have missed a step.
You create the volumemountobject, but then you don't use it in the containerinstance object, so it doesn't know where to reference
Yours
$container = New-AzContainerInstanceObject -Name $AzureContainerInstanceName  -Image owasp/zap2docker-stable
-Command 'zap.sh -daemon -host 0.0.0.0 -port 8080 -config api.key=abcd -config api.addrs.addr.name=.* -config api.addrs.addr.regex=true'

Microsoft Docs
Powershell docs for az continer commands - reference the mountpoint created with the -VolumeMount parameter
$container = New-AzContainerInstanceObject -Name test-container -Image alpine -VolumeMount $mount

The docs then create the container group
$containerGroup = New-AzContainerGroup -ResourceGroupName test-rg -Name test-cg -Location eastus -Container $container -Volume $volume


text:
Q: how to read values from xlsx file to store value through getter and setter to object and finally to array list I have tried to read values from excel file to store each and every row and cells from XSSFWorkbook in an object and add it to arraylist.But its adding only last element in arraylist. Including my code below.

 try
           {
               ArrayList<OrderInfo> orderList = new ArrayList<OrderInfo>();
               XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("C:/mytemp/Order Details.xlsx"));

               for (Sheet sheet : wb ) {
                   OrderInfo order_Info = new OrderInfo();
                      for (Row row : sheet) {
                          int rowId = row.getRowNum();
                          if(rowId != 0){
                               Cell del_zone = row.getCell(0);
                               order_Info.setDel_zone(del_zone.getStringCellValue());
                               Cell cust_id = row.getCell(1);
                               order_Info.setCustomer_id(cust_id.getStringCellValue());
                          }
                      }
                      orderList.add(order_Info);
                  }

                  for(int i = 0;i<orderList.size();i++){
                   logger.info("*******Print List Object******"+orderList.get(i).getDel_zone()+"****Cust_Id****"+orderList.get(i).getCustomer_id());
                  }

               }
           catch (Exception e)
           {
                   System.err.println("Exception :" + e.getMessage());
           }

A: orderList.add(order_Info) should be inside the for (Row row : sheet) loop, you have it outside
Also it needs to be created inside the loop: OrderInfo order_Info = new OrderInfo(); should be later
           for (Sheet sheet : wb ) {
                  for (Row row : sheet) {
                      int rowId = row.getRowNum();
                      if(rowId != 0){
                           Cell del_zone = row.getCell(0);
                           OrderInfo order_Info = new OrderInfo();
                           order_Info.setDel_zone(del_zone.getStringCellValue());
                           Cell cust_id = row.getCell(1);
                           order_Info.setCustomer_id(cust_id.getStringCellValue());
                           orderList.add(order_Info);
                      }
                  }
              }


text:
Q: Problemas al actualizar BD con axios y vue en la vista buen día, estoy desarrollando un proyecto en Laravel usando VUE, sin embargo presento el siguiente problema, tengo dos tablas una llamada Empleados Internos y otra llamada Clientes, quiero asignar de forma dinámica una empresa a los Empleados Internos para esto utilizo el v-if para mostrar texto y v-else para mostrar un select donde muestro los Clientes que tengo en la base de datos, me funciona correcto al momento de guardar en la Base de datos con Axios, hace la funcion sin problemas el problema es que en el view una vez que doy guardar me sigue mostrando la empresa o información anterior y no la actual, anexo el código del padre/hijo
SERVICIOS
<template>

Empleados Registrados:

                        Nombre
                        Telefono
                        Empresa
                        Acción

                <empleadocomponente-component
                    v-for="(EmpleadosInterno, index) in EmpleadosInternos"
                    :key="EmpleadosInterno.id"
                    :EmpleadosInterno="EmpleadosInterno"
                    @update="updateEmpleadosInterno(index, ...arguments)"
                    @delete="deleteEmpleadosInterno(index)">
                </empleadocomponente-component>

</template>

COMPONENTE
<template>

{{EmpleadosInterno.completo}}

{{EmpleadosInterno.telefono}}

{{EmpleadosInterno.empresa}}

                <select v-else class="form-control" id="Cliente" v-model="ClienteSeleccionado">
                    <option v-for="Cliente in Clientes"
                            :key="Cliente.id"
                            :value="Cliente">{{Cliente.nombreempresa}}</option>
                </select>

                    Asignar Empresa

                <button v-else type="button" class="btn btn-success" v-on:click="onClickUpdate()">
                    Guardar Cambio
                </button>

                <button class="btn btn-danger" v-on:click="deleteEmpleadosInterno(EmpleadosInterno.id)">
                    Eliminar Empleado
                </button>

</template>

A: Puedes obligar a que tu componente se refresque una vez termines la llamada de la API:
Agrega una key al componente que deseas actualilzar:
:key="componentKey"

Inicia un contador en tu data():
componentKey = 0

Una vez finalice la llamada de la Api actualiza la key del componente, esto hará que el componente se redibuje con los datos nuevos:
this.componentKey += 1;

Eso debería ser suficiente.
Por favor modifica tu pregunta, el código debe ir como texto.


text:
Q: Output of function not showing First up: Yes I'm a beginner with Mathematica although I have plenty of experience with other languages.
Currently I'm trying to define a function, that when run animates a pendulum. When I try to run it, nothing happens. No error message is generated but no result is given. It's probably just a simple misset semicolon. I tried for hours to debug it already by restructuring the code, adding and removing semicolons, running it in a new kernel, inserting sanity checks and simplifying the code -  to no avail. Every time I try to run the animation nothing seems to work anymore.
The Code begins with a function to plot static instances (which in itself works, I just included it to be complete) and then adds a function, that solves a movement equation and tries to apply it to the pendulum.
++++++Trigger Warning:+++++++
My Code is pretty messed up from the debugging and looks really spaghettiesque, which I will change once I have found the flaw in the code.
You have been warned!
++++++++++++++++++++++++++

ClearAll[plotPendulum];
plotPendulum[theta_, t_, subs_List ] :=
    Module[{p1, p2, le, ps, ra, lines, dots, ceil,
            text, text2, all, pendulum},
        p1 = {0, h[t]} /. subs;
        p2 = {l*Sin[theta], h[t] + l*Cos[theta]} /. subs;
        le = (l + a) /. subs;
        ra = le*{{-1.05, 1.05}, {-1.55, 1.55}};
        ceil  = {Brown, Thickness[0.05], Line[{{-l,0}/.subs, {l,0}/.subs}]};
        lines = {Black, Thickness[0.01], Line[{{0, 0}, p1}], Thickness[0.005], Line[{p1, p2}]};
        dots  = {Black, PointSize[0.04], Point[{{0, 0}, p1}], Red, PointSize[0.1], Point[{p2}]};
        text = {Black, Background -> None,
        Text[m, p2 + {1.5, 0}, {-1.5, 0}],
        Text[l, p1 + (p2 - p1)/2 - {0.05*le, 0}, {1,0}],
        Text[" t = " <> ToString[t] <> " s ",{-l*0.5,1.1*Ceiling[a]}/.subs]};

        all = Join[ceil, lines, dots, text];

        pendulum = Show[Graphics[all, Background->White], PlotRange -> ra];
        Return[pendulum]
  ]

(*plotPendulum[2.001,Pi/4//N,{l->10,a->1.5,omega->2*Pi}]  *)

(*Problematic part ahead:*)

f[ln_,an_,wn_,thetan_,dthetan_]:=Module[{g= 9.81},
moveq = (-g+an*wn^2*Sin[t*w])*Sin[theta[t]]+ ln* D[D[theta[t],t],t]==0    ;

thetaoft= NDSolve[{moveq, theta[0]== thn, theta`== dthn},theta,{t,0,60}];

image= plotPendulum[thetaoft, Pi/4//N,{l->ln,a->an,omega->wn}];

test = Animate[image, {t, 0,  Pi/4//N}];(*I tried removing and adding the semicolons on image, test and return*)

Return[test]

]

f[10,0.5,2*Pi,3,1]

Thanks to all people making it this far - any help or input is appreciated!


text:
Q: Shiny textOutput line break I have a list of objects, one of which is a prediction from a random forest model.
The data looks like :
 print(a$predict)
 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
 B  A  B  A  A  E  D  B  A  A  B  C  B  A  E  E  A  B  B  B

I'm trying to get this printed to a shiny app.
In my server.R file I have :
output$prediction <- renderPrint({
    input$process

    withProgress(message = 'Making prediction. Please wait', value = 0.1, {

      isolate(
        print(modelset()$predict))
    })})

In my UI.R file I have :
tabPanel('Prediction', textOutput('prediction'))

The issue is that the shiny app outputs the object as 1 long string of text :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 B A B A A E D B A A B C B A E E A B B B Levels: A B C D E
How can I get the output printed in the same way as we see in R studio?
Thanks in advance.

A: It's okay, I figured it out.  I need to replace
textOutput

With
 verbatimTextOutput


text:
Q: gulp postcss cssnano does not combine the same selector when it is not next to it Gulp in postcss with cssnano combine the same selector when the selector next to it but unfortunately it does not combine the selector when it is not next to it.
It works very well when selectors are next to it
.box {
    color: blue;
}
.box {
    font-weight: 700;
}

to
.box {
    color: blue;
    font-weight: 700;
}

unfortunately it doesn't do the job when it is not next it
.box {
    color: blue;
}
.love{
  color: red;
}
.box {
    font-weight: 700;
}