text:
Q: WSDL to PHP with Basic Auth I need to build php classes from a WSDL that is behind basic auth.
It has tons of namespaces so it looks burdensome to do this by hand.
I have tried a few tools but looks like the auth session isn't presistent.

A: HTTP Auth works with SOAP Client, however you cannot access password protected WSDL files
See https://bugs.php.net/bug.php?id=27777

A: Using built in SOAP client, you should have something like this:
$options = array(
    'login' => $username,
    'password' => $password,
);
$client = new SoapClient($wsdl, $options);

A: I solved this by using the lib nusoap. See if it helps
$params = array(
  "param" => "value"
);

$soap_client = new nusoap_client($wsdl_url, true);
$soap_client->setCredentials(USER_SERVICE, PASS_SERVICE, 'basic');
$soap_client->soap_defencoding = 'UTF-8'; //Fix encode erro, if you need
$soap_return = $soap_client->call("method_name", $params);

A: $options = array(
     'login' => $username,
     'password' => $password,
);
$client = new SoapClient($wsdl, $options);

Yes, it works! I tried in a solution that I was building and it connects to my customer WS which is with HTTP Basic Auth.

A: How about this solution:

*

*Download the WSDL and save into a local file

*Create SoapClient with the local file

Something like this (in a simplified version) :
class MySoap {

    private $WSDL = 'https://secure-wsdl.url?wsdl';

    private $USERNAME = 'dummy';
    private $PASSWORD = 'dummy';

    private $soapclient;

    private function localWSDL()
    {
        $local_file_name = 'local.wsdl';
        $local_file_path = 'path/to/file/'.$local_file_name;

        // Cache local file for 1 day
        if (filemtime($local_file_path) < time() - 86400) {

            // Modify URL to format http://[username]:[password]@[wsdl_url]
            $WSDL_URL = preg_replace('/^https:\/\//', "https://{$this->USERNAME}:{$this->PASSWORD}@", $this->WSDL);

            $wsdl_content = file_get_contents($WSDL_URL);
            if ($wsdl_content === FALSE) {

                throw new Exception("Download error");
            }

            if (file_put_contents($local_file_path, $wsdl_content) === false) {

                throw new Exception("Write error");
            }
        }

        return $local_file_path;
    }

    private function getSoap()
    {
        if ( ! $this->soapclient )
        {
            $this->soapclient = new SoapClient($this->localWSDL(), array(
                'login'    => $this->USERNAME,
                'password' => $this->PASSWORD,
            ));
        }

        return $this->soapclient;
    }

    public function callWs() {

        $this->getSoap()->wsMethod();
    }
}

It works for me :)

A: This is Simple example to authenticate webservice using soapClient
$apiauth =array('UserName'=>'abcusername','Password'=>'xyzpassword','UserCode'=>'1991');
$wsdl = 'http://sitename.com/service.asmx?WSDL';
$header = new SoapHeader('http://tempuri.org/', 'AuthHeader', $apiauth);
$soap = new SoapClient($wsdl);
$soap->__setSoapHeaders($header);
$data = $soap->methodname($header);

This code internally parse header as follow
<soap:Header>
    <AuthHeader xmlns="http://tempuri.org/">
      <UserName>abcusername</UserName>
      <Password>xyzpassword</Password>
      <UserCode>1991</UserCode>
    </AuthHeader>
</soap:Header>

A: i've been trying to resolve this issue, but from what i understand, soap client connections to ssl+httpauth web services are more pain. I've googled and from what i understand, with my problem being solved, you can use the example below to solve your problem too(by using HttpAuth infos in both url and soapClient setup).
$username="test";
$password="test";
$url = "https://".urlencode($username).":".urlencode($password)."@example.com/service.asmx?WSDL";

$context = stream_context_create([
'ssl' => [
// set some SSL/TLS specific options
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
]]);

$client = new SoapClient($url, [
'location' => $url,
'uri' => $url,
'stream_context' => $context,
'login' => $username,
'password' => $password
]);

$params=array(
'operation'=>'arguments',
'and'=>'other bull',
'goes'=>'here'
);

$response = $client->__soapCall('OperationName', array($params));


text:
Q: MySQL query who return 0 or 1 according date I have this query:
SELECT DATE_FORMAT(DATE_SUB(`expiry_date`, INTERVAL 7 DAY), '%d %m %Y')
  FROM `my_subscriptions`
 WHERE `user_id` = '[user_id]';

which returns expiry_date minus 7 days; let's call that the "returned date".
Now I would like compare this "returned date" against the current date (the time right now), returning 0 if the current date is less than or equal to the "returned date", and 1 if it's bigger.
How can I do that?

A: You can use CASE and also use NOW() for the current date time. Try this
SELECT CASE WHEN NOW() <= DATE_FORMAT(DATE_SUB(`expiry_date`, INTERVAL 7 DAY), '%Y-%m-%d') THEN 0 ELSE 1 END AS is_expired FROM `my_subscriptions` WHERE `user_id` = '[user_id]';

redpajama_set_name: RedPajamaStackExchange


text:
Q: group consecutive values according to their distance I have a list of number:
numbers = [1,2,3,14,23,45,46,47]

I would like to create a "python-structure" (I don't know exactly what to use) containing series for which the distance is less than 5
in this case I should have:
1,2,3
45,46,47

could you help me?

A: You can loop through numbers, check the difference and append the value to the results accordingly:
results = [[numbers[0]]]           # initialize the result with the first element of numbers
for x, y in zip(numbers, numbers[1:]):         # use zip to get adjacent values
    if y - x < 5:
        results[-1].append(y)      # if difference is < 5 append result to the last sublist of result
    else:
        results.append([y])        # otherwise start a new sublist

results
# [[1, 2, 3], [14], [23], [45, 46, 47]]


text:
Q: Installing gdal to use with topo json and D3 I am working on a map tutorial (http://bost.ocks.org/mike/map/) focused on using gdal, topojson, and D3.  The tutorial I am following focuses on a mac.  I have to work with a PC.
Downloaded gdal from this site (http://trac.osgeo.org/gdal/wiki/DownloadingGdalBinaries) and followed the instructions for windows.  As far as the d3 and topojson I have those packages installed properly in my project directory.  How do I go about installing gdal on a windows so I can convert the data from it to topojson using Gitbash as my command prompt?
Thank you,
Greg

A: The easiest way to install GDAL on Windows is using the OSGEO4W Installer.
Just use the "Advanced" option and you can choose GDAL from "Commandline_Utilities"-"gdal". The installer also enables you to have multiple GDAL versions side by side, should you ever need that.


text:
Q: Cannot add an array to a div The result of document.getElementById('boxed').innerHTML = numList.join(", "); is a blank div with console error: TypeError: document.getElementById(...) is null. Heres the whole HTML:
    <!DOCTYPE html>

    <title>Super Lotto</title>
    <meta charset="utf-8">
    <link href="https://fonts.googleapis.com/css?family=Libre+Franklin" rel="stylesheet">
    <link href="lotto-styles.css" rel="stylesheet">

Lucky Numbers

Good luck!


text:
Q: Format date {yyy-mm-dd} as "mmm 'yy" I have been struggling with this for some time, with combinations of the isodate and datetime packages, without success.
I would like to create a macro that receives an input in the format {yyyy-mm-dd} and returns "mmm 'yy". For example {2014-11-04} => Nov '14
I would also like for it to work for languages other than English.
Like a say, seems to be something that isodate could handle, and yet...
Cheers.

A: \documentclass{article}

\def\shortdate#1{\ifcase#1\relax\or
    Jan\or Feb\or Mar\or Apr\or May\or Jun\or
    Jul\or Aug\or Sep\or Oct\or Nov\or Dec\fi}

\def\mydate#1{\xmydate#1\relax}

\def\xmydate#1#2#3#4-#5-#6\relax{%
\shortdate{#5} '#3#4}

\begin{document}

\mydate{2014-11-04}

\end{document}


text:
Q: Subset Dataframe given time R Given a dataframe that looks like the following:
Time    Delay   Station1
6:00:15 0:00:00 12
6:15:22 0:00:00 41
6:16:52 0:00:00 40
6:30:19 0:00:00 31
6:31:22 0:00:00 40
6:32:08 0:01:20 35
6:45:25 0:00:30 55
6:47:21 0:00:20 50
6:48:10 0:01:10 43
6:52:00 0:00:00 53
7:01:24 0:00:30 37
7:02:13 0:00:30 40
7:04:58 0:00:40 34
7:05:40 0:02:20 35
7:19:41 0:00:30 59
7:24:00 0:01:10 42
7:25:08 0:00:50 47
7:23:16 0:01:20 37

How can I subset the dataframe for times between 6:00 and 7:00? All the answers I found contain, the date as well and this is a bit confusing.
So far, amongst other things, I did the following:
df.route1 <- read.table("my.data.csv",  header = T, sep = ';',stringsAsFactors = FALSE)
subset(df.route1, format(Time, "%H:%M:%S") >= "06:00" & format(Time, "%H:%M:%S") < "07:00")

Any suggestions?

A: require(lubridate)
df$time <- strptime(x = as.character(df$time), format = "%H:%M:%S")
df[(hour(df$time) >= 6 & hour(df$time) < 7), ]

A: You can do it:
library(tibble)

data<-tribble(~Time,    ~Delay,   ~Station1,
              "6:00:15","0:00:00","12",
              "6:15:22","0:00:00","41",
              "6:16:52","0:00:00"," 40",
              "6:30:19","0:00:00"," 31",
              "6:31:22"," 0:00:00"," 40",
              "6:32:08"," 0:01:20"," 35",
              "6:45:25"," 0:00:30"," 55",
              "6:47:21"," 0:00:20"," 50",
              "6:48:10"," 0:01:10"," 43",
              "6:52:00"," 0:00:00"," 53",
              "7:01:24"," 0:00:30"," 37",
              "7:02:13"," 0:00:30"," 40",
              "7:04:58"," 0:00:40"," 34",
              "7:05:40"," 0:02:20"," 35",
              "7:19:41"," 0:00:30"," 59",
              "7:24:00"," 0:01:10"," 42",
              "7:25:08"," 0:00:50"," 47",
              "7:23:16"," 0:01:20"," 37")
library(lubridate)
library(dplyr)

datadata$Time<-hms(data$Time)
filter(data,Time>=hms("6:00:00")&Time<=hms("7:00:00"))

# A tibble: 10 x 3
           Time    Delay Station1
   <S4: Period>    <chr>    <chr>
 1    6H 0M 15S  0:00:00       12
 2   6H 15M 22S  0:00:00       41
 3   6H 16M 52S  0:00:00       40
 4   6H 30M 19S  0:00:00       31
 5   6H 31M 22S  0:00:00       40
 6    6H 32M 8S  0:01:20       35
 7   6H 45M 25S  0:00:30       55
 8   6H 47M 21S  0:00:20       50
 9   6H 48M 10S  0:01:10       43
10    6H 52M 0S  0:00:00       53


text:
Q: How to transfer several last patches from a darcs-1 repo to a darcs-2 one (converted elsewhere) I've cloned the repo listed at
https://hackage.haskell.org/package/language-c-0.4.7 as the upstream
repo, namely: http://code.haskell.org/language-c.
I've done some hacks and fixes in it, and recorded them as patches.
But then I discovered that if I want to publish them on
http://hub.darcs.net, I need a darcs-2 repo, and the initial one
which I used for cloning was unexpectedly a darcs-1 repo. (Can be checked with darcs show repo, which doesn't print darcs-2 in the case of a darcs-1 repo.) Moreover,
I've discovered also a language-c repo at
which looks like an upstream repo:
http://hub.darcs.net/visq/language-c, with a few more fresh changes
there. It is a darcs-2 repo, too, of course.
I could do the conversion to darcs-2, but I read that it is not
reproducible and one can't exchange patches between the results of
different runs of the conversion.
What is the simplest way to export my several last patches in the
darcs-1 repo and apply them in the darcs-2 repo (a clone of
http://hub.darcs.net/visq/language-c)?
(As for the question which of http://code.haskell.org/language-c and
http://hub.darcs.net/visq/language-c should be considered to be
upstream, see
https://mail.haskell.org/pipermail/haskell-cafe/2015-December/122545.html,
which I hope to get a definitive answer for soon.)

A: In practice the situation with reproducible conversion is more complicated - and not quite as bad - as the dire warning provided by darcs convert.
The main issue underlying the warning is that if two repositories have the same patches but in different orders, you might get incompatible patches.
If you rerun the conversion twice in a row on the same repository, you will get the same result. Indeed, as long as you run it on two repositories with exactly the same patches, in the same order, you will get the same result.
Moreover, the conversion is actually "prefix closed": you can have two repositories, and one starts with the the same patches as the other, in the same order, and also has some extra patches at the end. Then converting the two repositories will again result in compatible repositories.
So in your scenario, the main thing you need to do is reproduce the original conversion.
It's very likely it was done from the code.haskell.org repo and the patches there are still in the same order as they were then - it's rare for them to change order in upstream repos as it only generally happens when someone obliterates patches.
So if you do a fresh get of the code.haskell.org repo, pull your patches into that, and then do a conversion, you'll probably find that everything is ok. You can then do a get of the new hub.darcs.net repo, pull the extra converted patches into that, and check that they look ok. Run a darcs check to be on the safe side.


text:
Q: Finding The Most Relevant or Important Features for SVM using SGD (loss=hinge) I am working on a text-classification problem and have found that SVM is performing best for my text-classification problem. However, I did my experiment using sklearn's SGD classifier (loss=hinge).
LIME seems to provide a way to analyze the instance and show the analysis for each class given an instance. However, the problem with LIME is:
exp = explainer.explain_instance(test_document, c.predict_proba)

in the explainer.explain_instance function, it requires a probability distribution as the second parameter (c.predict_proba) and there is no predict_proba available for SGD (loss=hinge). I have tried using CalibratedClassifierCV but I am getting different results with it.
'=======SGD (loss=hinge)======='
Predicted:  [19, 7, 7, 13, 16, 9, 17, 6, 13, 17, 16, 17, 11, 1, 4, 14, 8, 10, 12, 10, 16, 1, 1]
True     :  [19, 3, 7, 13, 16, 9, 15, 6, 13, 10, 16, 17, 11, 1, 4, 14, 8, 5, 20, 18, 2, 12, 1]
0.6521739130434783
'====Calibrated Results======'
Predicted:  [19, 7, 7, 13, 16, 16, 12, 6, 13, 17, 16, 17, 11, 5, 4, 14, 8, 10, 15, 10, 16, 7, 1]
True     :  [19, 3, 7, 13, 16, 9, 15, 6, 13, 10, 16, 17, 11, 1, 4, 14, 8, 5, 20, 18, 2, 12, 1]
0.5652173913043478

The objective here is to find the most relevant/important features for each class in a multi-class text-classification problem. The purpose of this is to analyze the results and discuss their differences in a research paper.
Open to any suggestions or alternatives.
Also, I could possibly use sklearn's SVC instead of SGD as it has the predict_proba attribute. However, the problem is with SGD I already have a set of parameters for which I am doing the analysis and I couldn't find a way to exactly convert the SGD's configuration to SVC's configuration.

A: So I couldn't make LIME work, but I found an alternative to LIME, called ELI5 a python's library. I'll recreate an example from the tutorial website as to how this module can be used to debug a machine learning algorithm.
Assuming you already have a sklearn's clf or estimator object that is fitted on a vectorized text data:
import eli5
eli5.show_weights(clf, top=10)

The code above works, but a better way is to provide vectorizer instead and let eli5 figure out the details automatically:
#vec is the vectorizer object and
#target_names is the names of the classes to be used
eli5.show_weights(clf, vec=vec, top=10,
                  target_names=twenty_test.target_names)

To look into how the classifier assigned a particular class show_prediction shows the scores for each class with top words that contributed to that score
#second param is the test instance whose prediction you'd like to see.
#vec and target_names are same from show_weights
eli5.show_prediction(clf, twenty_test.data[0], vec=vec,
                     target_names=twenty_test.target_names)

The following is only part of the entire output produced through show_prediction method.

This is exactly what I was looking for, I wonder why I didn't find it before. Hope it helps others looking for something similar.


text:
Q: Why did Voldemort need to drink Unicorn blood?
"[...] it is a monstrous thing, to slay a unicorn. Only one who has nothing to lose, and everything to gain, would commit such a crime. The blood of a unicorn will keep you alive, even if you are an inch from death, but at a terrible price. You have slain something pure and defenceless to save yourself, and you will have but a half-life, a cursed life, from the moment the blood touches your lips."
- Firenze, Harry Potter and the Philosopher's Stone

In the first Harry Potter book/movie, we found Voldemort drinking Unicorn blood. Why did he need Unicorn blood to stay alive? Maybe, unicorn blood works on an undead soul, but wasn't he already protected by his Horcruxes in terms of being kept alive?

A: Voldemort never drank unicorn blood through his face on the back of Quirrell's head. Instead, Harry sees Quirrell leaning over the body drinking the blood himself. During the graveyard scene in Goblet of Fire, Voldemort talks about how he still had the power to possess animals, but the animals all died shortly afterwards.

I sometimes inhabited animals — snakes, of course, being my preference — but I was little better off inside them than as pure spirit, for their bodies were ill adapted to perform magic… and my pos- session of them shortened their lives; none of them lasted long….
— Goblet of Fire, chapter 33 (The Death Eaters)

It's likely that by drinking the unicorn blood, Quirrell was preserving his own life.
Keep in mind that contrary to the movie, it wasn't Harry's attacks that killed Quirrell. He died because Voldemort fled his body:

"The servant died when I left his body, and I was left as weak as ever I had been,"
— Goblet of Fire, chapter 33 (The Death Eaters)

Firenze was right, he really was only an inch from death, and it was only a combination of unicorn blood and Voldemort's power that kept him alive.
Alternatively, unicorn blood was one of the ingredients in the potion that allowed Voldemort to take his weakened baby-like form before his body was fully restored. So it's possible that by drinking the blood, Quirrell was somehow allowing Voldemort to create a physical face.

A:
See what I have become?' the face said. 'Mere shadow and vapour... I have form only when I can share another's body... but there have always been those willing to let me into their hearts and minds... Unicorn blood has strengthened me, these past weeks... you saw faithful Quirrell drinking it for me in the Forest... and once I have the Elixir of Life, I will be able to create a body of my own... (Philosopher's Stone)

He needs Unicorn blood to strengthen himself. Without it, as per Quirrel's worries, he was even weaker:

'Master, you are not strong enough!'
  'I have strength enough... for this...'

A: The Horcrux kept Voldemort alive, in a ghost-like state where he wasn't able to do very much. When Quirell found him, he was able to have a body, but he was very much in a half-life, not able to do anything of significance. Eventually, that connection started to break down. The unicorn blood allowed Voldemort to continue to possess a body, in effect keeping him alive. Indeed, without the unicorn blood, he returned to the type of life he had previously, which wasn't really living life at all, as ended up happening eventually anyways.

A: It wasn't Voldemort drinking the blood, it was Quirrel, to keep himself alive!
We see in COS that possession by Voldemort can be nearly fatal, as we find Ginny would have died if Voldemort had gained any more strength.

"So I made Ginny write her own farewell on the wall and come
  down here to wait. She struggled and cried and became very boring.
  But there isn't much life left in her. . . ."

Also, referring to Quirrel himself (GoF)

"The servant died when I left his body, and I was left as weak as
  ever I had been," Voldemort continued."

And this is stated explicitly in regards to animals:

". . . and my possession
  of them shortened their lives; none of them lasted long. . . ."

We also see in Fantastic Beasts that an Obscurus, which seems similar in many aspects to possession, destroys the host.

"There's no documented case of any Obscurial surviving past the age of ten. The one I met in Africa was eight when she – she was eight when she died."

Thus, Quirrel, being possessed by someone with the strength of Voldemort, needed to drink Unicorn blood to keep himself alive.


text:
Q: Массив указателей на структуру Добрый вечер. Подскажите как лучше на Си реализовать данную структуру(Массив указателей на структуру, что конкретно в структуре не особо важно). Не получается никак.
И как потом передавать эту структуру через указатели в функцию?
Я пробовал вот так List *str[N], но это никак не передать в функцию, чтоб там изменять

A: Эти боковые ветки - что-то вроде
struct Node
{
    int a,b;
    Node * next;
}

а по вертикали -
struct Node* str[N];

Т.е. массив указателей на списки.


text:
Q: Выделяемая память для Java Передаю в JVM command line parameters:
-Xss512k -Xms1536m -Xmx2560m -XX:MaxPermSize=1024m -XX:ReservedCodeCacheSize=256m -Dfile.encoding=UTF8
Но логи говорят, что:

*

*Всего: 444мб,

*Свободной: 302мб,

*Используется: 142мб,

эти значения получаю через
   long freeMemory = Runtime.getRuntime().freeMemory() / 1048576;
   long usedMemory = totalMemory - freeMemory;```


text:
Q: how to use a .c file to write a test class in google test instead of .cpp file? I have used googletest for my Android NDK project contain .c files. I have used a test class of the type .cpp to do the same. I want to use .c file instead. I get the following error when I try to use it :
Running main() from gtest_main.cc
[==========] Running 0 tests from 0 test cases.
[==========] 0 tests from 0 test cases ran. (1 ms total)
[  PASSED  ] 0 tests.

How can i solve this?

A: You cannot use a .c file to write a test class in googletest instead of a .cpp file.
A .c file should contain C language source code and a C/C++ compiler will assume that a .c file
is to be compiled as C.
A .cpp file should contain C++ language source code and a C/C++ compiler will assume that a .cpp file
is to be compiled as C++.
C and C++ are related but different programming languages. C is much older and simpler than C++.
There are no classes in the C language. C++ source code containing classes cannot be compiled as C.
Googletest is a unit-testing framework that is written in C++, not C, and it requires you to write
your test code in C++, using the framework classes. Your tests must coded in .cpp (and .h) files so that
the compiler will compile them as C++.
However, you can use googletest to unit-test C code. The C code will be in .c and .h files, but you
have to code your unit-tests, as usual, in .cpp and .h files. The C/C++ compiler knows that
the .c files are to be compiled as C and the .cpp files are to be compiled as C++.
There is a small complication that you must deal with when you want to #include "some_header.h"
in your C++ unit-test code, and some_header.h is one of the C-language header files:
The C++ compiler is going to process some_header.h, and it can process it correctly as long
as it knows that some_header.h is a C-language header file. To inform the C++ compiler that some_header.h
is a C header, you write this:
extern "C" {
#include "some_header.h"
}

If you don't put extern "C" { ... } around the #include for a C-language header then you will get undefined-symbol
errors at linktime.
I suggest that you experiment with a project containing the following three files:
return_one.h
// return_one.h
#ifndef RETURN_ONE_H
#define RETURN_ONE_H

// A C library :)

// A C function that always return 1.
extern int return_one(void);

#endif

return_one.c
// return_one.c
#include "return_one.h"

int return_one(void)
{
    return 1;
}

test_return_one.cpp
// test_return_one.cpp
#include "gtest/gtest.h"
extern "C" {
#include "return_one.h"
}

TEST(t_return_one, returns_1)
{
    EXPECT_EQ(1,return_one());
}

int main(int argc, char **argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

Get this project to compile, link and run with googletest.
You may find the answers to this question helpful.


text:
Q: Testing laws of side-effecting monad I'm writing a library to access web service through the API. I've defined simple class to represent API action
case class ApiAction[A](run: Credentials => Either[Error, A])

and some functions that performs web service calls
// Retrieve foo by id
def get(id: Long): ApiAction[Foo] = ???

// List all foo's
def list: ApiAction[Seq[Foo]] = ???

// Create a new foo
def create(name: String): ApiAction[Foo] = ???

// Update foo
def update(updated: Foo): ApiAction[Foo] = ???

// Delete foo
def delete(id: Long): ApiAction[Unit] = ???

I've also made ApiAction a monad
implicit val monad = new Monad[ApiAction] { ... }

So I could do something like
create("My foo").run(c)
get(42).map(changeFooSomehow).flatMap(update).run(c)
get(42).map(_.id).flatMap(delete).run(c)

Now I have troubles testing its monad laws
val x = 42
val unitX: ApiAction[Int] = Monad[ApiAction].point(x)

"ApiAction" should "satisfy identity law" in {
  Monad[ApiAction].monadLaw.rightIdentity(unitX) should be (true)
}

because monadLaw.rightIdentity uses equal
def rightIdentity[A](a: F[A])(implicit FA: Equal[F[A]]): Boolean =
  FA.equal(bind(a)(point(_: A)), a)

and there is no Equal[ApiAction].
[error] could not find implicit value for parameter FA: scalaz.Equal[ApiAction[Int]]
[error]     Monad[ApiAction].monadLaw.rightIdentity(unitX) should be (true)
[error]                                            ^

The problem is I can't even imagine how it could be possible to define Equal[ApiAction]. ApiAction is essentialy a function, and I don't know of any equality relation on functions.  Of course it is possible to compare results of running ApiAction's, but it is not the same.
I feel as I doing something terribly wrong or don't understand something essential. So my questions are:

*

*Does it makes sense for ApiAction to be a monad?

*Have I designed ApiAction right?

*How should I test its monad laws?

A: I'll start with the easy ones: Yes, it makes sense for ApiAction to be a monad. And yes, you've designed it in a reasonable way - this design looks a bit like the IO monad in Haskell.
The tricky question is how you should test it.
The only equality relation that makes sense is "produces same output given same input", but that's only really useful on paper, since it's not possible for a computer to verify, and it's only meaningful for pure functions. Indeed, Haskell's IO monad, which has some similarities to your monad, doesn't implement Eq. So you're probably on safe ground if you don't implement Equal[ApiAction].
Still, there might be an argument for implementing a special Equal[ApiAction] instance for use solely in tests, that runs the action with a hard-coded Credentials value (or a small number of hard-coded values) and compares the results. From a theoretical point of view, it's just awful, but from a pragmatic point of view it's no worse than testing it with test cases, and lets you re-use existing helper functions from Scalaz.
The other approach would be to forget about Scalaz, prove ApiAction satisfies the monad laws using pencil-and-paper, and write some test cases to verify that everything works the way you think it does (using the methods you've written, not the ones from Scalaz). Indeed, most people would skip the pencil-and-paper step.

A: It boils down to lambdas being anonymous subclasses of FunctionN, where you only have instance equality, so only the same anonymus subclass is equal with itself.
One idea of how you could do it:
Make your operations concrete subclasses of Function1 instead of instances:
abstract class ApiAction[A] extends (Credentials => Either[Error, A])
// (which is the same as)
abstract class ApiAction[A] extends Function1[Credentials, Either[Error, A]]

Which would allow you to for example create case objects for your instances
case class get(id: Long) extends ApiAction[Foo] {
  def apply(creds: Credentials): Either[Error, Foo] = ...
}

and this in turn should allow you to implement equals for each subclass of ApiAction in a way that suits you, for example on the parameters of the constructor. (You could get that for free making the operations case classes, like i did)
val a = get(1)
val b = get(1)
a == b

You could also do this without extending Function1 like I did and use a run field like you did, but this way gave the most succint example code.

A: I think you could implement it with the downside of having to use a macro or reflection to wrap your functions into a class that includes an AST. You can then compare two functions by comparing their AST.
See What's the easiest way to use reify (get an AST of) an expression in Scala?


text:
Q: how do I get directx media player to play one or more videos on a continuous loop in vb.net? When I try an error appears how do I get directx media player to play one or more videos on a continuous loop in vb.net? When I try an error appears
Error:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
Here's my code so far:
Imports Microsoft.DirectX
Imports Microsoft.DirectX.AudioVideoPlayback
Imports System.Text.RegularExpressions
Imports System.Net
Imports System.IO

Public Class Form1
    Dim PlayorPause As Integer = 0
    Dim MovieN As Integer = 0
    Dim NowPlaying As List(Of String) = New List(Of String)
    Friend WithEvents videoFile As Video
    Sub Pause()
        If PlayorPause = 0 Then
            videoFile.Play()
            PlayorPause = 1
        Else
            videoFile.Pause()
            PlayorPause = 0
        End If
    End Sub
    Sub Nextvid()
        videoFile.Dispose()
        Dim WindowSize As Size = Panel1.Size
        If MovieN > NowPlaying.Count - 1 Then
            MovieN = 0
            Nextvid()
        Else
            videoFile = New Video(NowPlaying(MovieN))
            videoFile.Owner = Panel1
            Panel1.Size = WindowSize
            videoFile.Play()
        End If
    End Sub
    Private Sub Video_End(ByVal sender As Object, ByVal e As EventArgs) Handles videoFile.Ending

        Dim WindowSize As Size = Panel1.Size
        If MovieN > NowPlaying.Count Then
            MovieN = 0
        Else
            Dim CurrenN As Integer = MovieN - 1
            MovieN = MovieN + 1
            videoFile = New Video(NowPlaying(MovieN))

        End If
        videoFile.Owner = Panel1
        Panel1.Size = WindowSize
        videoFile.Play()
    End Sub
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        NowPlaying.Add(" C:\Users\Adminx\Downloads\ShortestVid.avi")
        Dim WindowSize As Size = Panel1.Size
        videoFile = New Video(NowPlaying(0))
        videoFile.Owner = Panel1
        Panel1.Size = WindowSize
        Me.KeyPreview = True
        Me.MinimumSize = New Size(319, 444)
        Me.Size = Me.MinimumSize
        Me.DoubleBuffered = True
    End Sub
    Sub NextPress()
        MovieN = MovieN + 1
        Nextvid()
    End Sub

    Sub PrePress()
        MovieN = MovieN - 1
        Nextvid()
    End Sub

    Sub Watchbtn()
        Me.MinimumSize = New Size(660, 444)
        Panel1.Visible = True
        Panel1.Focus()
    End Sub
End Class

A: In Video_End, replace
If MovieN > NowPlaying.Count Then

with
If MovieN > NowPlaying.Count - 1 Then


text:
Q: Classify users by colors? I have a list of users. In this list, each user represented as an object that has some properties. One of this property is color. So, each user has some color. For example, the color of one user is #f5abb5 and the color of the second user is #f5abbb. Both of them are the pink colors.
I need to classify my users by colors that they choose. These colors stored as hex codes. So, I think maybe Python has some tools that help to understand colors and say that #f5abb5 and #f5abbb are pink colors? I found colour library but there is no way to understand colors like I need.
Another one way (not so good) that in a RGB color space, hex #f5abb5 is composed of 96.1% red, 67.1% green and 71% blue. That means that red is main here and I can divide users like that. But the first way to understand that both colors are pink (or other colors are sky blue, and so on) is much better.

A: Take a look at webcolors.
There's a function hex_to_name which meets your need perfectly.

>>> hex_to_name(u'#ffffff')
u'white'
>>> hex_to_name(u'#fff')
u'white'
>>> hex_to_name(u'#000080')
u'navy'
>>> hex_to_name(u'#daa520')
u'goldenrod'

Edit:
Take care of the unmatched colors.
import webcolors as wc
import numpy as np

def get_approx_color(hex_color):
    orig = wc.hex_to_rgb(hex_color)
    similarity = {}
    for hex_code, color_name in wc.css3_hex_to_names.items():
        approx = wc.hex_to_rgb(hex_code)
        similarity[color_name] = sum(np.subtract(orig, approx) ** 2)
    return min(similarity, key=similarity.get)

def get_color_name(hex_color):
    try:
        return wc.hex_to_name(hex_color)
    except ValueError:
        return get_approx_color(hex_color)

print(get_color_name(u"#F5ABB5"))
# lightpink


text:
Q: Strict mode in Javascript I am currently learning Javascript and came across the term "strict mode". I know that it is used to indicate to the compiler that the code should be examined stricter. Then I went on testing this: first I tried this:

function test() {
    "use strict";
    a = 4;
    alert(a);
}

I didn't get an alert and thought that it is quite logical as an error is thrown because "a" is not defined. Then I tried this:

{
    "use strict";
    a = 4;
    alert(a);
}

After refreshing the page an alert was shown saying "4". So my question is when is the strict mode "working" and when it isn't?

A: Quoting the MDN page on strict mode:

Strict mode applies to entire scripts or to individual functions. It doesn't apply to block statements enclosed in {} braces; attempting to apply it to such contexts does nothing.


text:
Q: De Rham Cohomology of $\mathbb{T}^2$#$\mathbb{T}^2$ If $\mathbb{T}^2=\mathbb{S}^1\times\mathbb{S}^1$, let $S_2:=\mathbb{T}^2$#$\mathbb{T}^2$, where # denotes the connected sum.
I'm trying to find an intuitive explanation for the fact that $H^1(S_2)=\mathbb{R}^4$ (de Rham cohomology)
I've read somewhere that an intuitive way of understanding $H^1(M)$ was to think of how many ways you can strangle $M$ with a wire (here, "strangle with a wire" means finding a closed loop on $M$ which cannot be continuously shrunk to a point)
For example, there is no way to strangle $\mathbb{S}^2$, so that is why $H^1(\mathbb{S}^2)=0$. A cylinder $C=\{(x,y,z)\in\mathbb{R}^3\mid x^2+y^2=1\}$ can be strangled by the loop $\{x^2+y^2=1, z=0\}$ (or similar ones), so that is why $H^1(C)=\mathbb{R}$.
For the torus, you can find $2$ kinds strangling loops (I'll call them "big radius" and "small radius"):

which is why $H^1(\mathbb{T}^2)=\mathbb{R}^2$.
Now here is my problem with $S_2$. For each of the two holes in $S_2$, I can find $2$ strangling loops (big radius, small radius) just as in $\mathbb{T}^2$, which makes $4$ strangling loops. But what about this one in the junction:

Isn't it different from the other $4$? I though it was. If we take, for example, the strangling loop with small radius of the first hole, I would not be able to make it into the red one in the junction. Same with any of the other four.
Am I missing something? Or this is an example where this intuition just fails?

A: In fact the junction loop in your picture is the sum of all of the four other loops. I don't know how to make pictures, but your last picture is good. Look at it: it consists of an outside loop, and three inside loops with two points of intersection of the loops. Ok, now imagine that these three inside loops are just one single big loop, going from left back, to the central top, to right back, to right front, to central bottom (which you have dashed), to left front. We allow ourselves to ignore the points of contact. Viewed in this way the single big central loop is the same as the outside loop.
Hope that makes sense.


text:
Q: Load N items from JSON array based on scroll and window height I want to load data from JSON to my page with jQuery (some kind of simple infinite scroll). Every time I scroll down and reach the bottom of the page 4 items will be loaded from JSON file. The problem is that if browser window height is shorter than the content I loaded (4 items), scroll bar doesn't appear. So it's not possible to load more data. What I want is to load 8 items from JSON array if scroll bar is not exist and when I scroll down I want to load 4 items and so on. (I don't want to add 8 more items after scroll)
var dataFile = 'data.json',
    container = '#items',
    limit = 4,
    start = 1;

loadData(start);

function loadData(start) {
    $.getJSON(dataFile, function(data) {
        for ( var i = start * limit - limit,j = i + limit; i < j; i++ ) {
            var item = data['items'][i];
            if (item) {
                var out = "";
                out += "

" + item['name'] + "
'
";
                $(out).appendTo($(container));
            } else {
                break;
            }
        }
        start++;
        console.log(start);
        if ( $(container).height() < $(window).height() ) {
            loadData(start);
        }
    });
}

$(window).scroll(function() {
    if ( $(window).scrollTop() + $(window).height() == $(document).height() ) {
        start++;
        loadData(start);
    }
});

My JSON file
{
  "items" : [
    {
      "name": "1 - Beggar Sandwich",
      "image" : "beggar-sandwich.png"
    },
    {
      "name": "2 - Cold Dog Sandwich",
      "image" : "cold-dog.png"
    },
    {
      "name" : "3 - Duck Sauce Sandwich",
      "image" : "duck-sauce.png"
    },
    {
      "name" : "4 - Grass Murderer Sandwich",
      "image" : "grass-murderer.png"
    },
    {
      "name" : "5 - Animal Lover Sandwich",
      "image" : "love-animals.png"
    },
    {
      "name" : "6 - Full Sandwich Menu",
      "image" : "menu.png"
    },
    {
      "name" : "7 - Murderer Sandwich",
      "image" : "murderer.png"
    },
    {
      "name" : "8 - Navy Sandwich",
      "image" : "navy.png"
    },
    {
      "name" : "9 - Grand Burger",
      "image" : "GrandBurger.png"
    },
    {
      "name" : "10 - Cherry Pie",
      "image" : "cherry-pie.png"
    },
    {
      "name": "11 - Beggar Sandwich",
      "image" : "beggar-sandwich.png"
    },
    {
      "name": "12 - Cold Dog Sandwich",
      "image" : "cold-dog.png"
    },
    {
      "name" : "13 - Duck Sauce Sandwich",
      "image" : "duck-sauce.png"
    },
    {
      "name" : "14 - Grass Murderer Sandwich",
      "image" : "grass-murderer.png"
    },
    {
      "name" : "15 - Animal Lover Sandwich",
      "image" : "love-animals.png"
    },
    {
      "name" : "16 - Full Sandwich Menu",
      "image" : "menu.png"
    },
    {
      "name" : "17 - Murderer Sandwich",
      "image" : "murderer.png"
    }
  ]
}

A: function filterArray(arr,min,max){
 var len   = arr.length
    ,up    = -1
    ,down  = len
    ,rrange= []
    ,mid   = Math.floor(len/2)
 ;
 while (up++<mid && down-->mid){
    if (arr[up]>=max || arr[down]<=min){break;}
    if (arr[up]>=min){
      rrange.push(arr[up]);
    }
    if (arr[down]<=max){
      rrange.push(arr[down]);
    }
 }
 return rrange;
}

A: Try:
(function ($) {
    $.fn.hasScrollBar = function () {
        return this.get(0).scrollHeight > this.height();
    }
})(jQuery);

var numberOfItems = 4,
        start = 1;

loadData(start);

$(window).scroll(function () {
    if ($(window).scrollTop() + $(window).height() == $(document).height()) {
        start++;
        loadData(start);
        console.log('bottom');
    }
});

function loadData(start) {
    var items = {
        "items": [
            {
                "name": "1 - Beggar Sandwich",
                "image": "beggar-sandwich.png"
            },
            {
                "name": "2 - Cold Dog Sandwich",
                "image": "cold-dog.png"
            },
            {
                "name": "3 - Duck Sauce Sandwich",
                "image": "duck-sauce.png"
            },
            {
                "name": "4 - Grass Murderer Sandwich",
                "image": "grass-murderer.png"
            },
            {
                "name": "5 - Animal Lover Sandwich",
                "image": "love-animals.png"
            },
            {
                "name": "6 - Full Sandwich Menu",
                "image": "menu.png"
            },
            {
                "name": "7 - Murderer Sandwich",
                "image": "murderer.png"
            },
            {
                "name": "8 - Navy Sandwich",
                "image": "navy.png"
            },
            {
                "name": "9 - Grand Burger",
                "image": "GrandBurger.png"
            },
            {
                "name": "10 - Cherry Pie",
                "image": "cherry-pie.png"
            },
            {
                "name": "11 - Beggar Sandwich",
                "image": "beggar-sandwich.png"
            },
            {
                "name": "12 - Cold Dog Sandwich",
                "image": "cold-dog.png"
            },
            {
                "name": "13 - Duck Sauce Sandwich",
                "image": "duck-sauce.png"
            },
            {
                "name": "14 - Grass Murderer Sandwich",
                "image": "grass-murderer.png"
            },
            {
                "name": "15 - Animal Lover Sandwich",
                "image": "love-animals.png"
            },
            {
                "name": "16 - Full Sandwich Menu",
                "image": "menu.png"
            },
            {
                "name": "17 - Murderer Sandwich",
                "image": "murderer.png"
            }
        ]
    };
    if (!$('#items').hasScrollBar()) {
        numberOfItems = 8;
    }
    for (var i = start * numberOfItems - numberOfItems, j = i + numberOfItems; i < j; i++) {
        var item = items['items'][i];
        if (item) {
            var out = "";
            out += "

" + item['name'] + "
'
";

            $(out).appendTo("#items");
        } else {
            break;
        }
    }
    start++;
}

here is fiddle: https://jsfiddle.net/p5jL1fvj/1/


text:
Q: Copy Paste all rows except header if condition met I have 2 sheets, the first one is for database all products and the second for a specific product, I want to copy the data from database to the product table based on the name of product.
I wrote this code but got an error message on product name

"Method 'Range' of object'_Worksheet' failed.

Can you please review and edit my code please? I'm really appreciate it.
Sub Amigos_Reza()
    Dim productname As String
    Dim finalrow As Long, i As Long

    'clear old data from product table
    ShBF.Rows("6:" & ShBF.Rows.Count).ClearContents

    finalrow = ShPDE.Cells(Rows.Count, 3).End(xlUp).Row
    > productname = ShPDE.Range(i, 6).Value ' I tried to change i by the number of rows for example "5" and still got the same error message

    For i = 5 To finalrow
        If productname = "Amigoz" & "Reza" Then
            ShPDE.Range(Cells(i, 3), Cells(i, 10)).Copy
            ShBF.Cells(6, 3).PasteSpecial
        End If
    Next i

    With ShBF
        .Select
        .Range("A1").Select
    End With
End Sub

What should I do to change my variable in order to my code works?

A: You get the error because in this line productname = ShPDE.Range(i, 6).Value your i is 0 but a row 0 does not exist because row counting starts with 1.
i is not defined outside your For loop.

Note that "Amigoz" & "Reza" is the same as "AmigozReza" So you probably meant something like
If productname = "Amigoz"  Or productname = "Reza" Then

Also note that you paste always into the exact same cell ShBF.Cells(6, 3).PasteSpecial so if your loop finds multiple product names then you will overwrite your destination.


text:
Q: Country and Customer Dimension I hesitate whether I should add a Country_Dimension or not since I already have a Customer_Dimension which contain some redundant fields such as:

*

*continent_name

*country_name

*postcode_#

A: Those could be two completely different things. A country name present in your Customer_Dimension will probably represent the country of an address your customer is using. Most likely the country he's living (or has lived) in. It can change over time since customers can switch addresses.
A dimension representing Countries will do exactly that, it represents countries. I think you first have to decide what the use of your dimension should be.


text:
Q: Why fputc() when putc()? getc() vs  fgetc()
putc() vs fputc()
What is the main difference between them?
I heard that both the functions do pretty much the same thing except getc() can be used as macros. What is meant by that?
If they are the same why use two functions are there to do the same things?
Any help would be seriously appreciated?

A: First of all, printf vs fprintf is different: fprintf supports a file argument, printf goes to stdout.
The reason for fputc and fgetc is that putc and getc were, on historical implementations, macro versions that evaluated the argument more than once. For example, the version on Unix V7:
#define getc(p)   (--(p)->_cnt>=0? *(p)->_ptr++&0377:_filbuf(p))
#define putc(x,p) (--(p)->_cnt>=0? ((int)(*(p)->_ptr++=(unsigned)(x))):_flsbuf((unsigned)(x),p))

Every "p" in there is replaced with the expression you put in the argument - so if it has a side effect (like you called a function to get the file, or are iterating over a list of files with the ++ operator), it will be called multiple times and possibly operate on different files.
Some modern systems (FreeBSD or OSX, for example) still do this, but generally only in an "unlocked" version since the standard getc/putc functions must be thread-safe. The unlocked versions are used for performance inside the library functions, so the lock is acquired only once at the top of the library function (so that when you call printf, it doesn't have to call fputc hundreds of times, doing the lock every time).

A: According to Kernighan's book putc is equivalent to fputc but putc could be implemented as a macro and putc may evaluate its stream argument more than once.
The difference between putc and fputc is that by using putc, you risk running the macro version which is inherently unsafe because it may have to evaluate its stream argument more than once. This causes complications that most people aren't aware of and thus do not watch out for, so fputc is better to use. fputc's macro does not have this problem.

A: At least for fprintf() it's obvious, as one could specify the FILE* where to write to. printf()  print to stdout.
The other 2X2 functions indeed are equvivalent in terms of usage.


text:
Q: Why does converting ushort port number from htons to ntohs in C# give different result? I'm sending a port number (ushort, 2 bytes) over socket, (c++ client) before that converting it to network bytes using htons.
When receiving, using C# server, I'm converting it using IPAddress.NetworkToHostOrder and the number is completely different.
htons(8085) -> 38175 ??
IPAddress.NetworkToHostOrder(38175) -> ??

What's the cause of that?

A: Unlike the BSD sockets API, where there's a separate name for each function, in .NET the NetworkToHostOrder method is overloaded, and may perform either ntohs or ntohl depending on the size of the input.
You're passing in a 32-bit integer input (int is the default type when C# sees a literal unless it doesn't fit), and therefore you get the same result as ntohl not ntohs.
If you want ntohs behavior, change the input type, e.g.
IPAddress.NetworkToHostOrder((short)38175)


text:
Q: Indexing Errors when using quarkus logging-gelf extension and ELK stack I have setup logging like described in https://quarkus.io/guides/centralized-log-management with an ELK Stack using version 7.7.
My logstash pipeline looks like the proposed example:
input {
    gelf {
        port => 12201
    }
}
output {
    stdout {}
    elasticsearch {
        hosts => ["http://elasticsearch:9200"]
    }
}

Most Messages are showing up in my Kibana using logstash.* as an Index pattern. But some Messages are dropped.
2020-05-28 15:30:36,565 INFO  [io.quarkus] (Quarkus Main Thread) Quarkus 1.4.2.Final started in 38.335s. Listening on: http://0.0.0.0:8085

The Problem seems to be, that the fields MessageParam0, MessageParam1, MessageParam2 etc. are mapped to the type that first appeared in the logs but actually contain multiple datatypes. The Elasticsearch log shows Errors like  ["org.elasticsearch.index.mapper.MapperParsingException: failed to parse field [MessageParam1].
Is there any way in the Quarkus logging-gelf extension to correctly map the values?

A: ELK can auto-create your Elasticsearch index mapping by looking at the first indexed document. This is a very convenient functionality, but it comes with some drawback.
For example, if you have a field that can contains numbers or strings, if the first document contains a number for this field, the mapping will be created with a number field so you will not be able to index a document containing a String inside this field ...
The only workaround for this is to create the mapping upfront (you can only defines the fields that causing the issue, the other fields will be created automatically).
This is an ELK issue, there is nothing we can do at Quarkus side.


text:
Q: Computing the maximum power that this opamp provides to the load Rl without occurring distortion Here's the schematic:

So first stage is a differential amplifier where vo1 =3.72V in DC (Vin= 0). In this stage i can say AmplVo1 = gainStage1 * AmplVi where distortion only happens when vo1 is bigger than Vcc (Vcc = 8V) or when T6 hits saturation.
The first case is when Vcc - VoDc = 8-3.72 =4.28 V , this is a critical point. I can imagine a sine wave with a DC component of 3.72 where its amplitude doesn't surpass 4.28 V (limit).
With T6 i dont really think it is necessary do show work because it wont affect anything, the amplitude of v01 will be bigger than the computed above.
My problem is what i should do with the next 2 stages. I remember my teacher saying to compute the DC voltage from the emissor T2 and subtract that from the DC voltage of Vo1 but i'm not sure what to do with that.


text:
Q: Multiple regression model and prediction/confidence interval for two values of a coefficient Hi i've been working on this model of house prices based on multiple independent variables. I got the out put out throught gretl.
https://www.dropbox.com/s/sq1oryrjhmplsgx/Screen%20Shot%202015-05-15%20at%206.01.02%20am.png?dl=0
Now i'm trying to interpret this additional question that got me confused... "Consider two houses that have the same size, same baths, same stories and same number of garages but one is two beds and the other is five beds. How much difference in the prices should an investor expect between the two houses according to model 1? Construct a 95% confidence interval for this difference in the prices and interpret your result."
I presume this means that the difference of 3 room equates to a difference of price equal to 3 times the coefficient of $\beta_3$ "Beds" which is
$$3\times$2388.49 =7165.47$$
I get lost at the concept of a 95% confidence interval for a multiple regression without giving the quantity x values for variables!
Now i'm going to get here that the confidence interval is "the difference $\pm$ se(Beds)*$t_{460,0.05/2}$
Where $$t_{460,0.05/2}=1.96482$$
So confidence interval is $7165.47 \mp 1184.23(1.96482)$
$$CI: 4838.6712,9492.2688 $$


text:
Q: TCP response not getting sent We seeing this behavior where all of a sudden our TCP response are not getting sent. Even when the connection is up (i.e We are able to receive request )
The TCP client is connected to server over a VPN. It work most of time but some time we don't see any information on the ngrep for response that are suppose to being sent back to server.
ngrep command
ngrep -t -d en01 port 8067

The TCP client is Twisted TCP client.
I tried netstat to check if the Send Queue size.
netstat ouptut
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 x.x.x.x.:47617           y.y.y.a:8067    ESTABLISHED
tcp        0      0 x.x.x.x.:50626           y.y.y.b:8067    ESTABLISHED

y.y.y.a - TCP server 1
y.y.y.b - TCP server 2

SEND-Q (0) Look ok to me
even the lsof output mention the QS as 0
lsof -Tqs -i TCP:8067

COMMAND   PID  USER   FD   TYPE    DEVICE SIZE/OFF NODE NAME
twistd  19561 viren    3u  IPv4 183882947      0t0  TCP x-x-x-x:47617->y.y.y.a:8067 (ESTABLISHED QR=0 QS=0)
twistd  19564 viren    3u  IPv4 183879151      0t0  TCP x-x-x-x:50626->y.y.y.b:8067 (ESTABLISHED QR=0 QS=0)

Important note the moment I restart my TCP client I see the message flow.
Not sure what is going wrong and what is happening to the packet.
Any clue??
Operating System
CentOS Linux release 7.2.1511 (Core)


text:
Q: Deriving the expansion of $\sin (\alpha - \beta)$ using $\sin x = \sqrt{1-\cos^2 x}$ I was deriving the expansion of  the expansion of $\sin (\alpha - \beta)$ given that $\cos (\alpha - \beta) = \cos \alpha \cos \beta + \sin \alpha \sin \beta$
Now, my textbook has done it in a different manner but I thought of doing it using the simple trigonometric identity $\sin^2 x + \cos^2 x = 1 \implies \sin x = \sqrt{1-\cos^2 x}$. I thought that it would be pretty easy (it probably is), until I got stuck in the final part which included the modulus function.
Here's how I did it :
$$\sin (\alpha - \beta) = \sqrt {1 - \cos^2 (\alpha - \beta)} = \sqrt{1-(\cos \alpha \cos \beta + \sin \alpha \sin \beta)^2}$$
By substituting $1$ as $\sin^2\alpha + \cos^2\alpha$ and expanding $(\cos \alpha \cos \beta + \sin \alpha \sin \beta)^2$, we get :
$$\therefore \sin (\alpha - \beta) = \sqrt{\sin^2\alpha + \cos^2\alpha - \cos^2\alpha\cos^2\beta-
\sin^2\alpha\sin^2\beta-2\sin\alpha\sin\beta\cos\alpha\cos\beta}$$
$$\therefore \sin(\alpha-\beta) = \sqrt{\sin^2\alpha (1-\sin^2\beta)+\cos^2\alpha(1-\cos^2\beta)-2\sin\alpha\sin\beta\cos\alpha\cos\beta}$$
$$\therefore \sin(\alpha - \beta) = \sqrt{\sin^2\alpha\cos^2\beta+\cos^2\alpha\sin^2\beta-2\sin\alpha\sin\beta\cos\alpha\cos\beta}$$
$$\therefore \sin(\alpha - \beta) = \sqrt{(\sin\alpha\cos\beta - \cos\alpha\sin\beta)^2} = |\sin\alpha\cos\beta-\cos\alpha\sin\beta|$$
Now, how do I get rid of the modulus sign? I do know that I must decide whether the expression inside the modulus functions in positive or negative, but I can't seem to decide how.
Thanks!

A: You start wrong, I'm afraid: you can say that
$$
\lvert\sin(\alpha-\beta)\rvert=\sqrt{1-\cos^2(\alpha-\beta)}
$$
where you cannot omit the absolute value in the left-hand side. At the end you get
$$
\lvert\sin(\alpha-\beta)\rvert=\lvert\sin\alpha\cos\beta-\cos\alpha\sin\beta\rvert
$$
(you have a sign wrong, but it's just a typo).
Now you could do a very long case analysis to show that $\sin(\alpha-\beta)$ has the same sign as $\sin\alpha\cos\beta-\cos\alpha\sin\beta$ for all $\alpha,\beta$.
Not something that I'd try myself.
I'd add that using $\pm$ doesn't help, because you would need to assign the proper sign anyway by the same case analysis.

A: What is your question?
At start when you accepted
$$\sin x =\pm \sqrt{1-\cos^2 x}, \tag1$$
at the end why don't you accept
$$\sin (\alpha - \beta) = \pm \sqrt{1-(\cos \alpha \cos \beta + \sin \alpha \sin \beta)^2}\tag2$$
in that very same sense? What is extra in (2) ?


text:
Q: Using java to send/receive different objects through UDP I am writing a program in Java where there are communications between two or more machines using UDP. My application sends objects after serializing them through the network to the other machine where it will be deserialized and dealt with it. I was successful in sending one kind of objects so far.
My problem is that I want the sender to be able to send different kind of objects, and for the receiver to be able to receive them and cast them again to their appropriate types. However, since UDP allocates a byte buffer then receive the data into the buffer, it is impossible to cast or detect the type of the received object as different objects have different sizes.
Is there is a way that I can use to send different kind of objects using UDP and then receive them at the other end? (I don't ask for code here, just some ideas)
Thanks
Edit:
I am looking for the best way to send/receive different objects types without knowing what is the type of the next expected object. Say I have three objects types and I expect receiving any of them at any givin time.
Another thing which crossed my mind after Brian's comment: How to set the buffer size for variable sized data-types like Strings, Arrays,...etc. As when receiving a UDP packet you have first to allocate a buffer with a size to receive that object. This is somehow related to my original question.

A: Why not wrap them in a known type (a Packet) that has a payload of type Object ? You can then deserialise your Packet and interrogate the resultant payload for its type.

A: What you serialize (use ObjectOutputStream), can also be deserialized (with ObjectInputStream). You retrieve an object then. It plays no role if you transport it over UDP, TCP, a pipe, a local file or whatever. Serialization writes to an OutputStream, deserialization reads from an InputStream.
You myObject.getClass() to detect what you received.

A: Basically, it's deserializing the object and then perform an instanceof check. However, since you explicitly mention the problem of the byte buffers when using UDP, i suggest to have a look at a messaging library which already performs this kind of management of byte buffers: JGroups
In pseudo code, working with jgroups looks like this:
JChannel channel = new JChannel("myapp");
Customer c = new Customer("IniTrodeInc.);
Book b = new Book("Twilight");
channel.send(new Message(c));
channel.send(new Message(b));

And on the receiving end
JChannel channel = new JChannel("myapp");
channel.addListener(new Listener(){
 public void onMessage(Message m) {
   if (m.getObject() instanceof Customer) {
     handleNewCustomer((Customer)m.getObject()));
   } else if (m.getObject() instanceof Book) {
     handleNewBook((Book)m.getObject()));
   } else {
     // Ups, we received s.t.h else
   }
 }
});

JGroups performs the abstraction of the messaging channel automatically, you do not need to know whether this is UDP, TCP or multicasting etc. JGroups will also handle peer-communication, e.g. sending messages to peer nodes which have not received the message yet etc.


text:
Q: x64 C++/CLI assemblies still reference to x86 .NET libraries My development environment is Visual Studio 2010.
I'm using managed code in my C++ project, compiling with /CLI flag and adding /FU with .NET DLLs.
When I'm compiling with 32-bit target machine everything goes right, but when compiling to 64-bit, it seems that the compiler still uses the x86 .NET DLLs.
Additionally, the relative path in Project Properties -> Common Properties -> Framework and References -> (System) Assembly reference properties -> Relative Path (uneditable) is pointing to an x86 file.
Is there a solution?

A: This is entirely normal and not a problem.  Reference assemblies are only used by the compiler to retrieve metadata, the declarations of the types in the assembly.  The equivalent of .h files in native C++.  Those declarations do not depend on the target architecture.
Architecture dependency is resolved at runtime.  For .NET Framework assemblies that contain native code (mscorlib.dll, System.Data.dll, PresentationFramework.dll), the correct assembly is retrieved from a different GAC subdirectory.  The GAC_32 subdirectory contains assemblies with 32-bit native code, GAC_64 for 64-bit, GAC_MSIL has the assemblies that contain pure IL and therefore have no architecture dependency.


text:
Q: Python Code not opening VlC player of twitch stream instances Hello so I don't stream right but wanted to make a video on peoples reactions when they are suddenly hit with a lot of people (this would be accompanied by a chat bot too and ill tell them what it was as well as ask for use permissions). So I thought it would be fun to look at view bots for twitch and found one online (code below). so I ran in installed streamlink via Pip and windows executable and it seems to run "found matching plugin twitch for URL "Stream link"" but it doesn't actually increase viewership and I can only assume this is because its not actually opening the Vlc instances, so here I am wondering what I need to do I have the latest version of python and git isnt trying to download and install anything so im assuming streamlink is all I need but im kind confused why it woudnt be opening the VLC instance any help is most appreciated.
Edit: oh and I do have the proxies and using a small amount to try and get it to work first, and will buy more later but after I get this to work!
import concurrent.futures, time, random, os

#desired channel url
channel_url = 'https://www.twitch.tv/StreamerName'
#number of viewer bots
botcount = 10
#path to proxies.txt file
proxypath = "C:\Proxy\proxy.txt"
#path to vlc
playerpath = r'"C:\Program Files\VideoLAN\VLC\vlc.exe"'

#takes proxies from proxies.txt and returns to list
def create_proxy_list(proxyfile, shared_list):
    with open(proxyfile, 'r') as file:
        proxies = [line.strip() for line in file]
    for i in proxies:
        shared_list.append((i))
    return shared_list

#takes random proxies from the proxies list and adds them to another list
def randproxy(proxylist, botcount):
    randomproxylist = list()
    for _ in range(botcount):
        proxy = random.choice(proxylist)
        randomproxylist.append(proxy)
        proxylist.remove(proxy)
    return (randomproxylist)

#launches a viewer bot after a short delay
def launchbots(proxy):
    time.sleep(random.randint(5, 10))
    os.system(f'streamlink --player={playerpath} --player-no-close --player-http  --hls-segment-timeout 30 --hls-segment-attempts 3 --retry-open 1 --retry-streams 1 --retry-max 1 --http-stream-timeout 3600 --http-proxy {proxy} {channel_url} worst')

#calls the launchbots function asynchronously
def main(randomproxylist):
    with concurrent.futures.ThreadPoolExecutor() as executer:
        executer.map(launchbots, randomproxylist)

if __name__ == "__main__":
    main(randproxy(create_proxy_list(proxypath, shared_list=list()), botcount))


text:
Q: Magento contact form customizations I'm trying to add a couple fields to the contact form so that my customers can indicate the year make and model of their vehicle when writing.
I have just upgraded my Magento installation from 1.4.3 to 1.7.0.1. My previous contact form was a hack job and this time I'm trying to get it working the right way. Reading all around, I tried adding <input type="text" size="15" value="" id="model_ext" name="bike_model_ext" class="required-entry input-text"> to the form.phtml in my template and then in the transaction email template in admin, {{var data.model_ext}}. But that doesn't work. I ensured that the template in the back end is correct by manipulating the text. I also know the form.phtml is correct, as I see elements when they change.
So then I overloaded the controller handling the contact form. I confirmed my controller is handling it (it came with a echo "it works"; die();) And in there, I'm looking for the POST data of the extra form element names, but here, too, I'm having troubles getting access to the data. Looking around the net, I tried this:
            $comment = $this->getRequest()->getPost('comment');
            $extras=Array( "year","make","model","model_ext" );
            foreach($extras as $field)
                    $comment .= "\n$field:\t".$this->getRequest()->getPost($field);
            $this->getRequest()->setParam('comment', $comment);
            parent::postAction();

But again, it is like my variables do not exist. Here, again, I know my code is being executed, because when I get anything wrong in there, the contact form crashes to an error message.
I'll be on it again in the morning, but hope that there is something easy I'm missing that someone here with more experience can help me with.
EDIT: ANSWERED I was using the ID to key in for the variables, needs to instead be the name.

A: An answer for those interested by this fix.
The $_POST and $_GET value generated by a form use name and not id.
In this situation you have to use bike_model_ext instead of model_ext.
Kind Regards,


text:
Q: How should awaiting an async task and showing a modal form in the same method be handled? I have a windows forms application in which I send an email using SmtpClient.
Other async operations in the application use async/await, and I'd ideally like to be consistent in that when sending the mail.
I display a modal dialog with a cancel button when sending the mail, and combining SendMailAsync with form.ShowDialog is where things get tricky because awaiting the send would block, and so would ShowDialog. My current approach is as below, but it seems messy, is there a better approach to this?
private async Task SendTestEmail()
{
  // Prepare message, client, and form with cancel button
  using (Message message = ...)
  {
     SmtpClient client = ...
     CancelSendForm form = ...

     // Have the form button cancel async sends and
     // the client completion close the form
     form.CancelBtn.Click += (s, a) =>
     {
        client.SendAsyncCancel();
     };
     client.SendCompleted += (o, e) =>
     {
       form.Close();
     };

     // Try to send the mail
     try
     {
        Task task = client.SendMailAsync(message);
        form.ShowDialog();
        await task; // Probably redundant

        MessageBox.Show("Test mail sent", "Success");
     }
     catch (Exception ex)
     {
        string text = string.Format(
             "Error sending test mail:\n{0}",
             ex.Message);
        MessageBox.Show(text, "Error");
     }
  }

A: I would consider handling the Form.Shown event and sending the email from there. Since it'll fire asynchronously, you don't need to worry about "working around" ShowDialog's blocking nature, and you have a slightly cleaner way to synchronize closing the form and showing the success or failure message.
form.Shown += async (s, a) =>
{
    try
    {
        await client.SendMailAsync(message);
        form.Close();
        MessageBox.Show("Test mail sent", "Success");
    }
    catch(Exception ex)
    {
        form.Close();
        string text = string.Format(
            "Error sending test mail:\n{0}",
            ex.Message);
        MessageBox.Show(text, "Error");
    }
};

form.ShowDialog();

A: One questionable thing about your existing SendTestEmail implementation is that it's in fact synchronous, despite it returns a Task. So, it only returns when the task has already completed, because ShowDialog is synchronous (naturally, because the dialog is modal).
This can be somewhat misleading. For example, the following code wouldn't work the expected way:
var sw = new Stopwatch();
sw.Start();
var task = SendTestEmail();
while (!task.IsCompleted)
{
    await WhenAny(Task.Delay(500), task);
    StatusBar.Text = "Lapse, ms: " + sw.ElapsedMilliseconds;
}
await task;

It can be easily addressed with Task.Yield, which would allow to continue asynchronously on the new (nested) modal dialog message loop:
public static class FormExt
{
    public static async Task<DialogResult> ShowDialogAsync(
        Form @this, CancellationToken token = default(CancellationToken))
    {
        await Task.Yield();
        using (token.Register(() => @this.Close(), useSynchronizationContext: true))
        {
            return @this.ShowDialog();
        }
    }
}

Then you could do something like this (untested):
private async Task SendTestEmail(CancellationToken token)
{
    // Prepare message, client, and form with cancel button
    using (Message message = ...)
    {
        SmtpClient client = ...
        CancelSendForm form = ...

        // Try to send the mail
        var ctsDialog = CancellationTokenSource.CreateLinkedTokenSource(token);
        var ctsSend = CancellationTokenSource.CreateLinkedTokenSource(token);
        var dialogTask = form.ShowDialogAsync(ctsDialog.Token);
        var emailTask = client.SendMailExAsync(message, ctsSend.Token);
        var whichTask = await Task.WhenAny(emailTask, dialogTask);
        if (whichTask == emailTask)
        {
            ctsDialog.Cancel();
        }
        else
        {
            ctsSend.Cancel();
        }
        await Task.WhenAll(emailTask, dialogTask);
    }
}

public static class SmtpClientEx
{
    public static async Task SendMailExAsync(
        SmtpClient @this, MailMessage message,
        CancellationToken token = default(CancellationToken))
    {
        using (token.Register(() =>
            @this.SendAsyncCancel(), useSynchronizationContext: false))
        {
            await @this.SendMailAsync(message);
        }
    }
}


text:
Q: nodejs azure web app giving http 431 error I had a node app hosted as an azure web app on Linux environment. The node service handles events requests as a GET method.  The application was working fine and all of a sudden since last 2 days it started throwing 431 error.
there was another similar question posted link but this is not the case here. I do not have AAD enabled
have also verified below areas

*

*no change in the node app

*no change on the client side sending the get request

*no explicit headers are sent. this was verified by making simple postman calls as well

what could have gone wrong here? any help?

A: Is it only happening for certain users? When I've seen this in the past, it was because we kept user role & state in the token (which generally does get passed in a header) and for some "test" users that had access to absolutely everything, that token was too large and we had a 431. For pretty much any other user things were fine.
Our fix was to use a key-value store (could be SQL, CosmosDB, etc.) and the user token was now an ID that mapped to the value in the data store, and the role & state info was moved there.


text:
Q: Error while accessing secured EJB (@RolesAllowed) deployed on Glassfish 4 payara server I am getting below error while accessing secured EJB (@RolesAllowed) deployed on GlassFish-A ,
I am accessing this EJB from Application deployed on Glassfish-B.

Caused by: java.lang.RuntimeException: Cannot propagate
  username/password required by target when using run as identity    at
  com.sun.enterprise.iiop.security.SecurityContextUtil.getSecurityContext(SecurityContextUtil.java:141)
    at
  com.sun.enterprise.iiop.security.SecClientRequestInterceptor.send_request(SecClientRequestInterceptor.java:271)
    at
  com.sun.corba.ee.impl.interceptors.InterceptorInvoker.invokeClientInterceptorStartingPoint(InterceptorInvoker.java:290)
    at
  com.sun.corba.ee.impl.interceptors.PIHandlerImpl.invokeClientPIStartingPoint(PIHandlerImpl.java:378)
    at
  com.sun.corba.ee.impl.protocol.ClientRequestDispatcherImpl.beginRequest(ClientRequestDispatcherImpl.java:323)
    at
  com.sun.corba.ee.impl.protocol.ClientDelegateImpl.request(ClientDelegateImpl.java:220)
    at
  com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:192)
    at
  com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(StubInvocationHandlerImpl.java:150)
    at
  com.sun.corba.ee.impl.presentation.rmi.codegen.CodegenStubBase.invoke(CodegenStubBase.java:226)
    at
  com.sun.ejb.codegen._GenericEJBHome_Generated_DynamicStub.create(com/sun/ejb/codegen/_GenericEJBHome_Generated_DynamicStub.java)
    at sun.reflect.GeneratedMethodAccessor131.invoke(Unknown Source)    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  com.sun.ejb.EJBUtils.lookupRemote30BusinessObject(EJBUtils.java:428)
    ... 107 more


text:
Q: how to disable url masking in asp.net? I have an application which points to a URL http://localhost:64162/webform1.aspx
But when run the application, it shows the URLwithout extension, http://localhost:64162/webform1 this repeats in the subsequent pages also.
I dont want the extension to be hide from the URL. I analyzed the global.aspx and web.config files for URLrewrite rules but couldn't find any.
Im using visual studio 2013 and IIS7.
How can I show the extension in my URL?

A: Finally I found the solution in the link.
I remove the friendlyURL from the installed nudgets and changed the below code in routeconfig.cs
settings.AutoRedirectMode = RedirectMode.Off;

by default it was    settings.AutoRedirectMode = RedirectMode.Permanent;  .
also cleared the cache.
It works.


text:
Q: how to select particular dataset from sql I have a sql query that has two parts
 1) Which calls a stored proc and populates the data in the temp table (using openXML function)
2) The other part of sql that joins with this table and the result set
Currently when i execute the stored proc it returns me the two result set. But it should return only me the second result set not the temp table result set.
My Visual Studio code by default selects the first result set whereas the required result set is second one.
The sql is as follow :
@SQL = 'Create table #TempTable (YearEntry int, Quarter int) insert into #TempTable exec CreateTableFromXML @YearQuarterList '  +
  ' Select * from ABCD inner join #TempTable T on T.YearEntry = A.Year '

It should return only all the columns from A table whereas it retuns
#TempTable and all the columns from A Table.

Can anybody please guide me how to get only the result set that returns all the columns from A table.
thanks

A: Instead of
' Select * from ABCD inner join #TempTable T on T.YearEntry = A.Year '

use
' Select ABCD.* from ABCD inner join #TempTable T on T.YearEntry = A.Year '

So you are specifying all of table ABCD, rather than everything from the join.

A: Is the first result set simply the (# row(s) affected) message that results from the INSERT statement? Try adding a SET NOCOUNT ON;  as the first statement of your batch and see if that helps.


text:
Q: Stylesheet not loading in Mozilla Firefox I'm stumped. Working on a site that isn't loading properly in FireFox. It loads great in Chrome and even IE, but for some reason the stylesheet isn't loading in FireFox.
The site: http://gregsonaccounting.com
I'm using html5 code and have used the basic resets and such from html5 Boiler Plate. Not sure if the problem is in my html or CSS.
Any insight is extremely helpful.
Many thanks.

A: A stylesheet should be defined in the format;
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">

You may also include media attribute, that they specify how a document is to be presented on different media: on the screen, on paper, with a speech synthesizer, with a braille device, etc.
In your page, it is;
<link rel="stylesheet" href="stylesheets/style.css" rel="stylesheet" />//Here is the problem
<link rel="stylesheet" href="nivo-slider/nivo-slider.css" type="text/css" media="screen" />
<link rel="stylesheet" href="nivo-slider/themes/default/default.css" type="text/css" media="screen" />

So that line may be modified like;
<link rel="stylesheet" href="stylesheets/style.css" type="text/css" media="screen" />

A: Your problem comes from style.css which begins by @charset "IBM437"
Replace it with @charset "UTF-8"; and it will be better !
It seams this charset IBM437 is auto added by SASS:
CSS pseudo element ▼ becomes gibberish in IE

A: Try changing:
<link rel="stylesheet" href="stylesheets/style.css" rel="stylesheet" />

to
<link rel="stylesheet" href="stylesheets/style.css" type="text/css" />

A: My CSS code worked well on Chrome, but it kept crashing on IE and Firefox. Then i found out the problem was in a badly preprocessed CSS.
Just copy paste your CSS to http://csslint.net/ and if you get any error, just fix it and you are good :)
Worth trying!

A: insert this inside your html documents. I am not writing in code just giving u the key words so you know and can put it in.
link rel="stylesheet" type="text/css" href="stylesheet.css"
it works so make sure you have this correctly or else your html document will not load with your stylesheet. best of luck to you and keep working brah.


text:
Q: Xamarin Forms splash image aspect ratio on Android I'm trying to resize a tall image for Android splash screen (iOS works OK) in Xamarin Forms app. I want to keep the aspect ratio but it gives me blank spaces on sides or the image is squashed when the view is filled.
I have tried multiple options which I found here but none of them work for me (crop, fit, center, scale, gravity, etc..).
This is my last try (mix of multiple answers):
  <?xml version="1.0" encoding="utf-8"?>
     <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
     <item>
            <bitmap
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:scaleType="fitCenter"
                android:gravity="center"
                android:src="@drawable/splash"
                android:tileMode="disabled"/>
     </item>
     </layer-list>

...and it gives me correct aspect ratio but also blank spaces.
What's the correct solution to fill the screen horizontally without losing the aspect ratio?

A: You can combine gravity attributes to combine auto fill effects.
My code for exemple is :
<?xml version="1.0" encoding="UTF-8" ?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <bitmap
        android:src="@drawable/splashscreen"
        android:gravity="clip_horizontal|fill_vertical"/>
  </item>
</layer-list>

This add possibilities and may give you one which suits your needs.
An other possibility could be something like that :
<?xml version="1.0" encoding="UTF-8" ?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item
        android:gravity="center"
        android:width="1200px"
        android:height="2200px">
    <bitmap
        android:src="@drawable/splashscreen"/>
  </item>
</layer-list>

Width and height corresponding to image size


text:
Q: If Range contains Cell with Value > 8 then MsgBox I am programming a time recording sheet. If for one weekday a value > 8 (so more than 8 hours) is filled in. I want a Messagebox to pop up.
i am struggling with the code I am currently using.
Also it would be great if the Macro would run automatically when the cells are being filled in.
Any ideas on how to approach this problem are very much appreciated.
Sub GenehmigungMehrarbeit()

   If Range("F14,F26").Value > 8 Then
        MsgBox ("Wurde der Mehraufwand der Arbeitszeit mit dem Teamlead abgesprochen?")

   If Range("G14,G26").Value > 8 Then
        MsgBox ("Wurde der Mehraufwand der Arbeitszeit abgesprochen?")

    ElseIf Range("H14,H26").Value > 8 Then
        MsgBox ("Wurde der Mehraufwand der Arbeitszeit abgesprochen?")

    ElseIf Range("I14,I26").Value > 8 Then
        MsgBox ("Wurde der Mehraufwand der Arbeitszeit  abgesprochen?")

    ElseIf Range("J14,J26").Value > 8 Then
        MsgBox ("Wurde der Mehraufwand der Arbeitszeit abgesprochen?")

  End If
Exit Sub
End Sub

A: You need to write following code at Worksheet level (right click on Sheetname, View code and paste the following code:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Application.Intersect(Target, Range("F14:J26")) Is Nothing Then
            If Target.Value > 8 Then
                MsgBox "You entered 8+ hours!!"
                Target.Value = ""
                Target.Select
            End If
    End If
End Sub

A: Overtime Worksheet Change Event
The Code
Module 1 (or any you're using)
Option Explicit

Sub GenehmigungMehrarbeit(Worksheet As Worksheet)  ' Overtime

    ' List of Check Range Addresses
    Const cRanges As String = "F14:F26,G14:G26,H14:H26,I14:I26,J14:J26"
    ' German List of Days
    Const cDays As String = "Montag,Dienstag,Mittwoch,Donnerstag,Freitag"
    ' Message 1
    Const strMsg1 = "Wurde der Mehraufwand der Arbeitszeit für den "
    ' Message 2
    Const strMsg2 = " mit dem Teamlead abgesprochen?"
    Const cHours As Long = 8  ' Hours

    Dim vntR As Variant   ' Check Range Array
    Dim vntD As Variant   ' Days Array
    Dim i As Long         ' Ranges/Days Array Elements Counter

    ' Split List of Range Addresses to Check Range Array
    vntR = Split(cRanges, ",")
    ' Split German List of Days to Days Array
    vntD = Split(cDays, ",")

    ' In This workbook's Worksheet
    With ThisWorkbook.Worksheets(Worksheet.Name)
        ' Loop through elements of Check Range Array (Days Array).
        For i = 0 To UBound(vntR)
            ' Check if sum of the current Check Range is greater than cHours.
            If WorksheetFunction.Sum(.Range(Trim(vntR(i))).Value) _
                    > cHours Then
                ' Build the (daily) message.
                MsgBox strMsg1 & Trim(vntD(i)) & strMsg2, vbInformation, vntD(i)
                Exit For ' Stop checking.
                ' Note: The message box will pop up only for the first found
                '       range with the sum greater than Hours (cHours).
                '       If you want the messages to pop up for every range
                '       with the sum greater than Hours, you should out
                '       comment the previous line.
            End If
        Next
    End With

End Sub

Sheet1 (or any you're using)
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Application.Intersect(Target, Range("F14:J26")) Is Nothing Then _
            GenehmigungMehrarbeit Me
End Sub

A: You could try:
Follow the instructions on the image:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rng1 As Range, rng2 As Range, rng3 As Range, rng4 As Range, rng5 As Range

        Set rng1 = Range("F14,F26")
        Set rng2 = Range("G14,G26")
        Set rng3 = Range("H14,H26")
        Set rng4 = Range("I14,I26")
        Set rng5 = Range("J14,J26")

        If Not Intersect(Target, rng1) Is Nothing Or Not Intersect(Target, rng2) Is Nothing _
            Or Not Intersect(Target, rng3) Is Nothing Or Not Intersect(Target, rng4) Is Nothing _
            Or Not Intersect(Target, rng5) Is Nothing Then _

            If Target.Value > 8 Then
                If Not Intersect(Target, rng1) Is Nothing Then
                    MsgBox ("Wurde der Mehraufwand der Arbeitszeit mit dem Teamlead abgesprochen?")
                Else
                    MsgBox ("Wurde der Mehraufwand der Arbeitszeit abgesprochen?")
                End If
            End If

        End If

End Sub

A: Range("F14,F26").Value returns the value only of F14, completely ignoring the F26.
This is how to build the event with a msgbox for 1 cell:
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Intersect(Target, Range("F14")) Is Nothing Then Exit Sub
    If Range("F14") > 8 Then
        MsgBox "Something in German"
    End If

End Sub

Put the above code in the corresponding worksheet, not in a module:

A: You can use Worksheet_Change event in VBA to run the code automatically when something is changed in the sheet. Copy the following code into the sheet in Visual Basic Editor.
Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Row >= 14 And Target.Row <= 26 And Target.Value > 8 Then
    If Target.Column = 6 Then
        MsgBox ("Wurde der Mehraufwand der Arbeitszeit mit dem Teamlead abgesprochen?")
    ElseIf Target.Column >= 7 And Target.Column <= 11 Then
        MsgBox ("Wurde der Mehraufwand der Arbeitszeit abgesprochen?")
    End If
End If

End Sub

This code runs whenever you change something in the sheet. Code checks if the changed cells are between 14th and 26th rows, if the value of changed cell is greater than 8, if the cells are between specified columns etc.


text:
Q: NuGet - what am I missing? I've just started trying to use NuGet to version libraries (we have MANY shared libraries that are currently referenced directly by solutions) and having numerous problems.
So I generated a NuGet package (nuget spec -> edit file -> nuget pack) and put several versions of the same .dll (packaged) in a shared folder on the network.
Last week I opened one of my solutions and deleted one of the shared .csproj files (that converts to a .dll) from a solution and then added the NuGet package to the other .csproj files that needed it and everything seemed to work fine. But I never checked in the changes and undid them. Now I'm trying to do the same thing over again and when I right-click the project and choose Manage NuGet Packages it already shows the NuGet package as installed (a green check-mark next to the name). And I've deleted all of the source and re-gotten it fresh out of TFS, so why does it show that the project already has the package? I've tried clearing my NuGet cache as well (both from the UI and nuget locals all -clear from the commandline). And yet if I try to delete that shared library (.csproj) the solution no longer compiles.
I also can't find where to set the acceptable versions like let's say that I'm ok using versions 1.0 - 2.2
Apparently I'm using NuGet 2.12.0.817 (at least that's what it says in Help->About) with Visual Studio 2013.
Does anyone have any idea what could be wrong here? I'm quickly becoming overwhelmed by all of the NuGet documentation and realizing that I may be in over my head!

A: I found the .packages file in the referenced project in a different folder from my current solution, so when I re-got my code that file wasn't overwritten and the package still appeared there. I'm still having numerous other problems, but I'll post on that separately.


text:
Q: No default constructor - inheritance ok, so I have a class "Card" with the following constructor. suit and rank are stored as fields.
Card(String s, int r ){
    suit = s;
    rank = r;
}

I want to return the rank with this method
public int getRank(){
   return rank;
}

The thing is i want to call this method from another class named Hand
if I make a reference to the card class Card c = new Card(); I have to input the parameters to the constructor. I don't want to do this.
I have tried to make Hand extend Card, but then I get the error

no default constructor

I've searched for a solution but I just can't get it to work.
My question is: How do get around this problem?
Edit: Hand class
    public class Hand extends Card {
    Deck d = new Deck();
    Hand h = new Hand();
    ArrayList<Card> hand = new ArrayList<>();

    public void giveMeCard(){
        hand.add(d.dealCard());
    }

    public ArrayList returnHand(){
        return hand;
    }

public int rank(){

    }

}

A:
I have to input the parameters to the constructor. I don't want to do this.

The solution to your problem is to start wanting to do this.
A Card without a specific suit and rank is meaningless.  You do not want to be instantiating meaningless objects.
You have not told us what your reasons are for not wanting to instantiate your card with the parameters that its constructor expects, but whatever your reasons are, they cannot possibly win over correctness.
So, you should pass the suit and rank to the constructor, you should do whatever it takes to be able to pass them, and you should not only want to do this, but actually love doing this.

A: I class has no parameterless constructor, then subclasses must call one of existing constructors of base class.
In your case you have base class
class Card {
  Card(String s, int r ){
}

so you must have
Hand extend Card {
 Hand() {
  super("s","r");
}

That's about technical side. About modeling and logic side, it makes absolutely no sense that Hand extends Card. Hand is not a Card. It contains set of cards (probably empty set=no cards in hand). Also (probably) there is upper limit of cards in hand (depends on the game you model).
Your card model is correct. It must have suit and rank (those fields should be private final in Card class). Your card should be immutable. Players should not be able to alter card in hand to some other cards, right? Actually I would model Rank and Suit as enums (they have well-known, limited set of values).
In any case (rank/suit as string or enum) you need equals/hashcode in Card and Hand classes.
You may event want to model Cards as enums, or as final static fields in Card class (one instance for actual cards).
When dealing a card, you must know what card to deal: rank and suit of that card. I guess, you are not dealing joker cards, where player can paint whatever he wants to on the card?
For me, you should also have Deck card. giveMeCard method should take (random) card from Deck, remove it from deck and add to Hand. Probably deal is better name of the method. It better reflects underlying domain (card game).


text:
Q: Discord bot issue "is a required argument missing" python I have a problem. I think this code is well written and the bot turns on and everything, but when I go to execute the commad play  I get an error.
@bot.command(name='play', aliases=['sing','p'], description="streams music")
async def play_(ctx, self, *, search: str):
    #async def play_(ctx, message, self, *, search: str):
    """Request a song and add it to the queue.
    This command attempts to join a valid voice channel if the bot is not already in one.
    Uses YTDL to automatically search and retrieve a song.
    Parameters
    ------------
    search: str [Required]
        The song to search and retrieve using YTDL. This could be a simple search, an ID or URL.
    """
    await ctx.trigger_typing()

    vc = ctx.voice_client

    if not vc:
        await ctx.invoke(self.connect_)

    player = self.get_player(ctx)

    # If download is False, source will be a dict which will be used later to regather the stream.
    # If download is True, source will be a discord.FFmpegPCMAudio with a VolumeTransformer.
    source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop, download=False)

    await player.queue.put(source)

The error is as follows:
    discord.ext.commands.errors.MissingRequiredArgument: search is a required argument that is missing.

And I don't know what to do because I have already tried to change the position but an error keeps coming out if someone knows what it is, please tell me

A: Whatever your search parameter is for, it wont work.
When the discord.py library calls a command, it calls the command as follows:
command(context, word1, word2, word3)

So if it would call your function, the named error would apper, because discord never passes a search argument to your function. E.g:
@bot.command(name='play', aliases=['sing','p'], description="streams music")
async def play_(ctx, self, *, search: str):
    [...]

-play see you again

play_(context, "see", "you", "again")

-> Error: search is a required argument that is missing

Instead, your function should look like the following:
@bot.command(name='play', aliases=['sing','p'], description="streams music")
async def play_(ctx, *search):
    [...]

A: Why do you have self as a parameter? If you're in a cog, put it before ctx. If you're not, remove that parameter. Your search term is being passed as the self parameter.


text:
Q: Error in getting block in a template I am a magento beginner and need help with creating a new custom block.
Basically, I just want the block to show "hello" if it is called.

*

*Module installation xml file, app/etc/modules/MyExtensions_HelloBlock.xml
<?xml version="1.0" encoding="UTF-8"?>
 <config>
    <modules>
      <MyExtensions_HelloBlock>
         <active>true</active>
         <codePool>local</codePool>
     </MyExtensions_HelloBlock>
   </modules>
</config>

*Module configuration xml file, app/code/local/MyExtensions/HelloBlock/etc/config.xml
<?xml version="1.0" encoding="UTF-8"?>
  <config>
    <modules>
     <MyExtensions_HelloBlock>
         <version>0.0.1</version>
     </MyExtensions_HelloBlock>
   </modules>
   <global>
     <blocks>
         <helloblock>
             <class>MyExtensions_HelloBlock_Block</class>
         </helloblock>
     </blocks>
   </global>
</config>

*Block class, app/code/local/MyExtensions/HelloBlock/Hello.php.
<?php
class MyExtensions_HelloBlock_Block_Hello extends  Mage_Core_Block_Template
{
   public function hello()
   {
   echo "hello";
   }
}

*Template file for the block, app/design/frontend/default/default/template/helloblock/hello.phtml
<?php
 $this->hello();
?>

Then I call my new block like this in the template "app/design/frontend/venedor/default/template/page/1column.phtml"
echo $this->getLayout()->createBlock('helloblock/hello')->setTemplate('helloblock/hello.phtml')->toHtml();

Result:

Fatal error: Call to a member function setTemplate() on boolean in
  /app/design/frontend/venedor/default/template/page/1column.phtml
  on line 58

I was following this tutorial.

A: You have added wrong block class, it should be  app/code/local/MyExtensions/HelloBlock/Block/Hello.php instead of  app/code/local/MyExtensions/HelloBlock/Hello.php
You are missing Block directory in the module


text:
Q: LINK : fatal error LNK1171: unable to load mspdb140.dll (error code: 127) I am trying to install pip install rasa_core and already added C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin; in my system path variable.
How can I resolve this error?
Following is my output while installing the rasa_core:
-3.5\twisted\internet\test\fake_CAs
    copying src\twisted\mail\test\rfc822.message -> build\lib.win-amd64-3.5\twis
ted\mail\test
    copying src\twisted\python\test\_deprecatetests.py.3only -> build\lib.win-am
d64-3.5\twisted\python\test
    copying src\twisted\words\im\instancemessenger.glade -> build\lib.win-amd64-
3.5\twisted\words\im
    copying src\twisted\words\xish\xpathparser.g -> build\lib.win-amd64-3.5\twis
ted\words\xish
    running build_ext
    building 'twisted.test.raiser' extension
    creating build\temp.win-amd64-3.5
    creating build\temp.win-amd64-3.5\Release
    creating build\temp.win-amd64-3.5\Release\src
    creating build\temp.win-amd64-3.5\Release\src\twisted
    creating build\temp.win-amd64-3.5\Release\src\twisted\test
    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe
/c /nologo /Ox /W3 /GL /DNDEBUG /MD -DWIN32=1 -ID:\Anaconda\envs\chatbot_p35\inc
lude -ID:\Anaconda\envs\chatbot_p35\include "-IC:\Program Files (x86)\Microsoft
Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio
 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.
14393.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um"
"-IC:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared" "-IC:\Pro
gram Files (x86)\Windows Kits\10\include\10.0.14393.0\um" "-IC:\Program Files (x
86)\Windows Kits\10\include\10.0.14393.0\winrt" /Tcsrc/twisted/test/raiser.c /Fo
build\temp.win-amd64-3.5\Release\src/twisted/test/raiser.obj
    raiser.c
    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.ex
e /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPA
TH:D:\Anaconda\envs\chatbot_p35\libs /LIBPATH:D:\Anaconda\envs\chatbot_p35\PCbui
ld\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\LIB\am
d64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\LIB
\amd64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.14393.0\ucrt\x
64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/L
IBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.14393.0\um\x64" /EXPORT:P
yInit_raiser build\temp.win-amd64-3.5\Release\src/twisted/test/raiser.obj /OUT:b
uild\lib.win-amd64-3.5\twisted\test\raiser.cp35-win_amd64.pyd /IMPLIB:build\temp
.win-amd64-3.5\Release\src/twisted/test\raiser.cp35-win_amd64.lib
    LINK : fatal error LNK1171: unable to load mspdb140.dll (error code: 127)
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\B
IN\\x86_amd64\\link.exe' failed with exit status 1171


text:
Q: Software for knotted $\mathbb{S}^2$'s in $\mathbb{S}^4$ According to the work of J. Scott Carter you can draw pictures of knotted surfaces in four-space in several different ways. I know the man is a real artist in this, but did anybody come across some software that does this for you ? See for example: http://www.jscottcarter.com/)
I guess you can figure out a parametric equation for a knotted sphere, and pay a trip to Mathematica-land, but I haven't done this.
This is probably a more specialized version of Topology software)


text:
Q: How to rspec test validations for polymorphic attributes? I'm attempting my first TDD project in Rails and Rspec. I've finally got some simple boiler plate Rspec code going for model validations. My model Employee has polymorphic associations in Email and Address.
How do I write validations for these polymorphic associations? Besides making sure validates_presence_of :first_name, :last_name, :role, I also want to make sure there is presence of emails and address.
Here's my models:
class Employee < ApplicationRecord
    has_many :employee_projects
    has_many :projects, through: :employee_projects
    has_many :phones, as: :phonable, dependent: :destroy
    has_many :emails, as: :emailable, dependent: :destroy
    has_many :addresses, as: :addressable, dependent: :destroy

     accepts_nested_attributes_for :emails, allow_destroy: true

    validates_presence_of :first_name, :last_name, :role

end

class Address < ApplicationRecord
  belongs_to :addressable, polymorphic: true
end

class Email < ApplicationRecord
    belongs_to :emailable, polymorphic: true
end

and here is my Rspec test for Employee:
require 'rails_helper'

RSpec.describe Employee, type: :model do
  context 'Validation tests' do
   subject { described_class.new(first_name: 'first_name', last_name: 'last_name', role: 'role')
  }

    it 'is valid with attributes' do
      expect(subject).to be_valid
    end

    it 'is not valid without first_name' do
      subject.first_name = nil
      expect(subject).to_not be_valid
    end

    it 'is not valid without last_name' do
      subject.last_name = nil
      expect(subject).to_not be_valid
    end

    it 'is not valid without role' do
      subject.role = nil
      expect(subject).to_not be_valid
    end

 end
end

Also hope to start using FactoryBot but want to get the basics first.