text:
Q: Using Python to Determine time from Sunset minus 2 hours to 10 pm I have a project I'm trying to put into Python, but am not very strong with coding.
I have an array for sunset in local solar time, and want to use that to calculate an hourly load. I am given that the load runs from 2 hours before sunset until 10pm.
I'd like to set up an if statement that says if((sunset - 2) < hour < 22): then x calculation occurs. But it doesn't want to let me do that since sunset is an array.
days = np.arange (1, 366) #days to 365
    day_no = np.repeat(days, 24)
    declination = pv.declination(day_no)
        sunrise, sunset = pv.sun_rise_set(latitude, declination, 0)

        print('Local Solar Time of Sunrise and Sunset (24h): ', sunrise, sunset)
        for idx,  PV_Ah in enumerate(PV_Array_Ah):
                day_number = np.floor(idx/24)
                hour = (idx - day_number*24)
            if ((sunset-2) < hour < 22):
                load = (4*3 + 20)*.93
                answer.append(load)
            else:
                load = 0

I'll also end up using my 'load' value in a plot, load on the y-axis vs every hour of the year on the x-axis.
How would I go about setting up the if statement for this calculation? And then recording the load in an array to plot?


text:
Q: Creating a layer 2 virtual interface, linked via virtual bridge to eth0 Good evening,
I have a sticky problem, in that I need to create a virtual interface for use with a VM, but it has to be layer-2 only: The VM will communicate with a pre-set MAC address (either one can be set for the adapter, which will be used by the VM - or the VM will masquerade another pre-set MAC address.)
Most of the solutions I've already found relate to using layer 3 (i.e. IP addresses), and unfortunately those solutions won't work for me: The layer 3 configuration must be done inside the VM, and the virtual NIC and virtual switch must be configured for L2 traffic only.
For security and operational reasons, I require no IP address configuration at all (i.e. link-local only for IPv4 and IPv6, or layer 3 completely disabled.)
Put simply, I need a topology like this:
My VM <-> vnic0 <-> vbr0 <-> eth0 <-> external network

I need to create a virtual adapter, called vnic0, connected (along with real adapter eth0) to a virtual bridge, called vbr0. Preferably, I'm after configuration files for RHEL 7.4 / CentOS 7.4 that will allow the configuration to work automatically, without interaction from a system administrator, after a reboot. I may also need to create vnic1, vnic2, vnic3, et cetera, all connected to vbr0, in the future.
Use of VLANs isn't strictly necessary (it can be assumed that everything is on a non-VLAN / native VLAN), but if some genius out there can show me how to configure, say, tagged dot1q traffic, with native VLAN 50 on vnic0, native VLAN 51 on vnic1, et cetera, with eth0 functioning as a trunk (with all or a subset of VLANs allowed to travel along it), serious brownie points would be due to you. :)
I have already tried the following:
modprobe dummy
ip link set name vnic0 dev dummy0
ip link add vbr0 type bridge
ip link eth0 down
ip link set dev eth0 master vbr0
ip link set dev vnic0 master vbr0
ip link set vbr0 up
ip link set vnic0 up
ip link set eth0 up

The biggest problem is that my vnic0 network broadcasts packets, but never receives them. My network isn't super-chatty, but I would expect to see at least some broadcast packets received by vnic0 via vbr0. However, that isn't happening. Attempts to run DHCP within the VM connected to vnic0 results in a timeout, though there is a perfectly functioning DHCP server connected to eth0.

A: Don't use dummy devices
This comes up regularly, I don't know why people insist to use them. Dummy devices are only useful to allow long-living applications to bind to a specific IP address, so the dummy devices can be moved around and bridged to other, more short-lived devices if necessary.
What you want is a macvlan or several which replace your vnic*. In spite of the name, macvlan's have nothing to do with VLAN tagging. The macvlan will operate on layer 2, will already be sort-of bridged to the master interface (eth0), and you can select one of several modes that possibly restrict the interaction of the bridged devices, if you need that.

A: Virtual ethernet interfaces are virtual interfaces, created in pairs, that act like a patch cable:
ip link add name nic0 type veth peer name vnic0 address 00:11:22:33:44:55
ip link set dev eth-VM master vbr0
ip link set nic0 up
ip link set vnic0 up

You should end up with a loose vnic0 with a 00:11:22:33:44:55 MAC address you can assign to your VM. They are discussed at the macvlan page mentionned above. I don't know that much about macvlan, but this should work as well and you wouldn't use the bridge vbr0.
ip link add link eth0 name vnic0 address 00:11:22:33:44:55 type macvlan mode bridge
ip link set vnic0 up

redpajama_set_name: RedPajamaStackExchange


text:
Q: List of recursively concatenated lists in R Is there a concise way to create a list of recursively concatenated lists in R?
Here's a concrete illustration of the type of problem I'd like to solve: Given two lists, such as
u <- list("A", list("B", list("C", "D")), "E")
v <- c("x", "y")

I would like to (recursively) produce the following list of character vectors
w <- list(c("A", "x"), c("A", "y"),
          c("B", "C", "x"), c("B", "C", "y"),
          c("B", "D", "x"), c("B", "D", "y"),
          c("E", "x"), c("E", "y"))

By "concise" I mean in an R-idiomatic manner with a minimal number of explicit for-loops.
What I've tried: I first tried solving the more basic problem of pairwise concatenation, that is, the problem of forming a list like
r <- list(c("A", "x"), c("A", "y"), c("B", "x"), c("B", "y"),
          c("C", "x"), c("C", "y"))

from two lists like
p <- list("A", "B", "C")
q <- list("x", "y")

However, performing the seemingly sensible operation
outer(p, q, FUN = "c")

threw the exception
dims [product 6] do not match the length of object [12]

What gives?

A: One option might be
 w1 <- do.call(c,lapply(u, function(x) {
        x1 <- if(!is.list(x)) outer(x,v, FUN=paste)
        else t(outer(do.call(paste, x), v, FUN= paste))
        strsplit(x1, " ")}))
identical(w, w1)
#[1] TRUE


text:
Q: Outputting a string variable into a text file in HEX format I'm stuck with a problem that I cannot solve.
So what i need is following: I need to make a program that receives one string input and converts it to hex and after that it saves it into a file.
If the file isn't created, it should, but if there is one already it should continue writing to the same (i guess "a+" parameter is what i need here right? )
So an example. I execute the program. Asks me to input some words.
I type "stack" and it returns me this "73 74 61 63 6B" which is correct.
I've done that with this algorithm
#include <cstdio>
#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;
int main(){
 string a;
 cin >> a;
 for( int i = 0; i < a.size(); i++ )
  printf( "%hX ", a[i] );
 cout << endl;
 system( "pause" );
 return 0;
}

That is all fine but I need that outputed in a text file.
I used this:
for( int i = 0; i < a.size(); i++ )
     {
      fprintf(pFile, "%hX ", a[i]);
     }

But it doesn't work. Can i get help with this one, thank you!
The full code, sorry I'm having problems with code samples I hope you don't mind pastebin link
http://pastebin.com/3u1mfg8n

A: You are learning C++ so why not use file streams?
#include <fstream>
#include <iomanip>

using namespace std;

int main () {
  // Read your string as before
  fstream fs;
  fs.open ("hex.txt", fstream::out | fstream::app); // app = append to file
  for(int i=0; i<a.size(); ++i)
  {
    fs << hex << static_cast<int>(a[i]) << " ";
  }
  fs.close();
  return 0;
}

A: I have tested your code and it is working correctly. It creates a file called Personal Shop Codes.txt in the directory it is run from. I expect the problem is that your program is not being run from the directory you expect it to be run from, so your output file is merely misplaced. This can often be the case when executing your program inside an IDE.

A: You need to use fopen() and assign that to your FILE pointer first:
FILE *pFile;
pFile = fopen("output.txt","w");

And then close the file when your program has finished writing to it:
fclose(pFile);

A: This will convert each byte in the string (each character that is) into its 2-character hex encoding:
for(int i = 0; i < a.size(); i++)
{
    printf("%2.2X ", a[i]);
}

If you want to store it:
std::string b = "";
for (int i = 0; i < a.size(); ++i)
{
    char tmp[3] = {0};
    sprintf(tmp, "%2.2X", a[i]);
    b += tmp;
}

Then you can write the entire b string out to the file easily.


text:
Q: Expectation related with convergence let x be arandom variable and let
$A_n$ ={${ \omega  : n \leq |x(w)|<n+1 }$} n=0,1,2,...
prove that
$\sum_{n=1}^{\infty}p(|x|> n)$=$\sum_{n=1}^{\infty}np(A_n)$ $\leq$ E(|x|)
$\leq$ $\sum_{n=1}^{\infty}(n+1)p(A_n)$=1+$\sum_{n=1}^{\infty}p(|x|>n)$
deduce
1) E(x) is finite iff $\sum_{n=1}^{\infty}p(|x|> n)$ is convergent
2)if E(x) is finite then np(|x|> n) $\to$ 0 as n $\to$ $\infty$
I try to solve it , I begin with
let $A_n =({n \leq |x|<n+1} ) = ({|x|<n+1})-({|x|<n})$
then
$p(A_n)=p({|x|<n+1})-p({|x|<n})$
what i I can do now , any help please its important problem for me !

A: I'll address the first half of the expression you need to prove and let you finish the second half. First, $\sum_{n=1}^\infty P(|X| \geq n) = \sum_{n=1}^\infty n P(A_n)$ is just a matter of rearranging the terms of the series. To wit,
$$\begin{align}\sum_{n=1}^\infty P(|X| \geq n) &= \sum_{n=1}^\infty \Big[ P(n \leq |X| < n+1) + P(n+1 \leq |X| < n+2) + ...\Big]
\end{align}$$
In this sum, the term $P(1 \leq |X| < 2)$ occurs $1$ time, the term $P(2 \leq |X| < 3)$ occurs $2$ times, and, in general, the term $P(n \leq |X| < n+1)$ occurs $n$ times, hence
$$\sum_{n=1}^\infty P(|X| \geq n) = \sum_{n=1}^\infty n P(A_n).$$
To justify this rearrangement completely rigorously, you can appeal to something like the Tonelli-Fubini theorem. I leave the details to you. You may want to have a look at this post, which raises a question that is similar to yours and receives a very nice answer from Did.
Now, if $x$ is a non-negative real number, let $\lfloor x \rfloor$ be the greatest integer that is less than or equal to $x$ (e.g. $\lfloor \pi \rfloor = 3$). Note that by definition $\lfloor x \rfloor \leq x$. Also note that if $X$ is a real-valued random variable, then $\lfloor |X| \rfloor$ is an integer-valued (and therefore discrete) random variable. Thus, by the definition of expected value,
$$\sum_{n=1}^\infty n P(A_n) = \sum_{n=1}^\infty n P(\lfloor |X| \rfloor = n) = E(\lfloor |X| \rfloor) \leq E|X|.$$


text:
Q: Is it anti-pattern to run asynchronous callbacks in catch blocks? Is it an anti-pattern to run asynchronous callbacks in error catching like this?
await something()
   .catch(async (err) => {
      console.error(err);
      await otherStuff();
   });

A: If your intent is to have that whole expression there never reject - that is, to avoid the need for
try {
  await something()
   .catch(async (err) => {
      // ...
} catch(e) {
  // handle
}

Then what you're doing right now isn't safe if there's any chance of the otherStuff call rejecting. If otherStuff might reject, then you should make sure to catch possible errors it throws, eg
await something()
   .catch(async (err) => {
      console.error(err);
      await otherStuff();
   })
   .catch(handleOtherStuffErrors)

Though having an async function with only a single await isn't that useful - consider instead just returning the Promise:
await something()
   .catch((err) => {
      console.error(err);
      return otherStuff();
   })
   .catch(handleOtherStuffErrors)

Chaining catches like that is pretty odd, but it's not impossible that that's what one's logic requires, so don't make a blanket statement about whether it's inherently bad.

A: The way you do it is. In a promise you should return the promise instead of making the callback async and awaiting it.
I don't think it is since you can call .then behind the catch. Sometimes an throw just goes into a diffrent branch of operations but at the end its preference.
await something()
   .catch((err) => {
      console.error(err);
      return otherStuff();
   }).then(res => {
  // work with data
});


text:
Q: How can i unset the for and foreach loop value in php My html code is:

        Product Code Detailes

        Title
    @foreach($x as $k_x => $v_x)
        {{ $v_x }}
    @endforeach

    @foreach ($y as $k_y => $v_y)
        {{ $v_y }}
    <?php $pro_code_count=count($pro_code);
    //print_r($pro_code);
    ?>
    @for($r = 1; $r <=sizeof($x); $r++)

        <?php $i=1; ?>
        @foreach($pro_code as $key=>$val)
        @if($i % 2 != 0)
          <input type="text" name="pro_code[]" value="{{ $val }}">
        @else
          <input type="text" name="pro_code[]" value="{{ $val }}">
        @endif
        @endforeach
        <?php
        $i++;
        ?>

        @endfor

    @endforeach

In that i can loop data inside table, the X and Y axis looped correctly, but inside an  datas are looped more then one time,
nw how can i stop the looping process
my o\p is looking like below

i want data like an below like that

A:

Product Code Detailes

Title
@foreach($x as $k_x => $v_x)
{{ $v_x }}
@endforeach

@foreach($y as $k_y_t=> $v_y_t)
{{ $v_y_t }}

@foreach($y as $k_y=> $v_y)
    @foreach($x as $k_x => $v_x)
    @if($k_y_t==$k_y)

    @foreach($pro_code as $k_pro_code=> $v_pro_code)
    <?php
    if($k_x.'-'.$k_y==$k_pro_code){
        echo '<input type="text" name="value" value="'.$v_pro_code.'">';
    }
    ?>
    @endforeach

    @endif
    @endforeach
@endforeach

@endforeach

$x: {"3":"bule","4":"green"}
$y: {"5":"cotten","6":"polyester"}
$pro_code_in_edit: {"3-5":"12","4-5":"23","3-6":"56","4-6":"89"}


text:
Q: Can std::threads be created / destroyed from global variables in a Windows DLL? I'm creating a logging object which performs the real file writing work on a separate std::thread, and offers an interface to a log command buffer, syncing the caller threads and the one worker thread.  Access to the buffer is protected by a mutex, there's an atomic bool for the worker thread exit condition, and I'm using Windows native Events as a signal to wake up the worker thread when new commands arrive.  The object's constructor spawns the worker thread so it is immediately available.  The worker thread is simply a while loop checking the exit condition, with in the loop a blocking wait for the signal.  The object's destructor finally just sets the exit condition, signals the thread to wake up and joins it to ensure it's down before the object is fully destroyed.
Seems simple enough, and when using such an object somewhere in a function it works nicely.  However, when declaring such an object as a global variable to have it usable for everyone it stops working.  I'm on Windows, using Visual Studio 2017 with the 2015 tool chain.  My project is a DLL plugin for another application.
The things I tried so far:

*

*Start the thread in the constructor of the global object.  This however makes the main thread hang immediately when my DLL is loaded.  Pausing the app in the debugger reveals we're in the std lib, at a point where the main thread should have launched the worker thread and is now stuck waiting for a condition variable, presumably one that is signaled by the worker thread once it is launched?

*Delay-construct the thread on demand when we first use the global object from somewhere else.  This way constructing it goes nicely without a hang.  However, when signalling the worker thread to exit from the destructor, the signal is sent, but the join on the worker thread now hangs.  Pausing the app in the debugger reveals our main thread is the only one still alive, and the worker thread is already gone?  A breakpoint placed in the worker thread function right before the close brace reveals it is never hit; the thread must be getting killed?

*I also tried to start the thread via a std::future, starting it up async, and that one launches perfectly fine from the constructor in global objects.  However, when the future tries to join the thread in the destructor, it hangs as well; here again no worker thread to be detected anymore while no breakpoint gets hit in it.

What could be going on?  I can't imagine it's because the thread construction and destruction takes place outside main() so to speak; these std primitives should really be available at such moments, right?  Or is this Windows specific and is the code running in the context of DllMain's DLL_PROCESS_ATTACH / DLL_THREAD_ATTACH events, where starting up threads might wreak havoc due to thread local storage not yet being up and running or such? (would it?)
EDIT -- added code sample
The following is an abbreviation/simplification of my code; it probably doesn't even compile but it gets the point across I hope :)
class LogWriter {
public:
    LogWriter() :
        m_mayLive(true) {
        m_writerThread = std::thread(&C_LogWriter::HandleLogWrites, this); // or in initializer list above, same result
    };
    ~LogWriter() {
        m_mayLive = false;
        m_doSomething.signal();
        if (m_writerThread.joinable()) {
            m_writerThread.join();
        }
    };
    void AddToLog(const std::string& line) { // multithreaded client facing interface
        {
            Locker locker; // Locker = own RAII locker class
            Lock(locker); // using a mutex here behind the scenes
            m_outstandingLines.push_back(line);
        }
        m_doSomething.signal();
    }

private:
    std::list<std::string> m_outstandingLines; // buffer between worker thread and the rest of the world
    std::atomic<bool> m_mayLive; // worker thread exit signal
    juce::WaitableEvent m_doSomething; // signal to wake up worker thread; no std -- we're using other libs as well
    std::thread m_writerThread;

    int HandleLogWrites() {
        do {
            m_doSomething.wait(); // wait for input; no busy loop please

            C_Locker locker; // access our line buffer; auto-released at end of loop iteration
            Lock(locker);

            while (!m_outstandingLines.empty()) {
                WriteLineToLog(m_outstandingLines.front());
                m_outstandingLines.pop_front();
                if (!m_outstandingLines.empty()) {
                    locker.Unlock(); // don't hog; give caller threads some room to add lines to the buffer in between
                    std::this_thread::sleep_for(std::chrono::milliseconds(10));
                    Lock(locker);
                }
            };
        } while (m_mayLive); // atmoic bool; no need to mutex it

        WriteLineToLog("LogWriter shut down"); // doesn't show in the logs; breakpoints here also aren't being hit
        return 0;
    }

    void WriteLineToLog(const std::string& line) {
        ... fopen, fprintf the line, flush, close ...
    }

    void Lock(C_Locker& locker) {
        static LocalLock lock; // LocalLock is similar to std::mutex, though we're using other libs here
        locker.Lock(&lock);
    }
};

class Logger {
public:
    Logger();
    ~Logger();
    void operator() (const char* text, ...) { // behave like printf
        std::string newLine;
        ... vsnprintf -> std::string ...
        m_writer.AddToLog(newLine);
    }

private:
    LogWriter m_writer;
};

extern Logger g_logger; // so everyone can use g_logger("x = %d\n", x);
// no need to make it a Meyer Singleton; we have no other global objects interfering

A: Since you're writing a DLL in C++, you have to understand how "globals" in DLL's work. The compiler sticks their initialization in DllMain, before anything else that you would do there. But there are some strict rules what you can do in DllMain, as it runs under loader lock. The short summary is that you can't call anything in another DLL because that DLL cannot be loaded while your DllMain is running. Calling CreateThread is definitely not allowed, not even if wrapped inside a std::thread::thread constructor.
The problem with the destructor is quite possibly because your DLL has exited (can't tell without code). The DLL unloads before the EXE, and their respective globals are also cleaned up in that order. Any attempt to log from a destructor in an EXE will fail for obvious reasons.
There is no simple solution here. Andrei Alexandrescu's "Modern C++ Design" has a reasonable solution for logging in the non-DLL case, but you'll need to harden that for use in a DLL. An alternative is to check in your logging functions if your logger still exists. You can use a named mutex for that. If your log function fails in OpenMutex, then either the logger does not exist yet or it no longer exists.

A: Think I've encountered that destruction issue with DLLs to use with Unity.
The only solution I found back then was to essentially give up true global variables that would need cleanup.
Instead I put them in a separate class which is instantiated only a single time into a global pointer by some custom launch function. Then my DLL got a "quit()" function also called by the user of the DLL. The quit function correctly destroys the instance carrying the global variables.
Probably not the smoothest solution and you have a pointer-indirection on every access to the global variables, but it turned out to be comfortable for serializing the state of the global variables as well.


text:
Q: Match .h, .m, .mm files but NOT .html I want to do some processing on just the source files of type .h, .m, .mm. I do NOT want to include the .html files.
The following misses the .mm files as I'm only matching .h or .m and not trying to catch longer extensions.
find ./ -type f -name "*.[hm]"

This only catches the .mm files, as the ? operator always matches a character. I'd like it to be an optional zero or one match like in regex.
find ./ -type f -name "*.[hm]?"

But if I use * instead, it matches 0 or multiple characters. This returns everything, but also has the .html files that I don't want.
find ./ -type f -name "*.[hm]*"

Any ideas on how to do this?

A: You can combine conditions:
find -type f -and \( -name '*.h' -or -name '*.m' -or -name '*.mm' \)

Or:
find ./ -type f -and -name '*.[hm]*' -and -not  -name '*.html'

A: You were running OS X. There is -E switch that you can use to tell find that the regular expression is an extended expression.

Interpret regular expressions followed by -regex and -iregex primaries as extended (modern) regular expressions rather than basic regular expressions (BRE's).  The re_format(7) manual page fully describes both formats.

Your command should now work:
find -E . -type f -regex ".*\.([hm]|mm)"


text:
Q: PHP Code to get STRING from site and SAVE to .js file / site instead of VB.NET i am programming a little bit in VB.net and ich have a code to search into a website for a string and give me the next 4 characters after the string i need... so far so good... in vb.net no Problem:
    Dim value As String = New System.Net.WebClient().DownloadString(TextBox1.Text)
Dim wordArr As Integer = value.IndexOf("plid=")
Dim substring As String = value.Substring(wordArr + 5, 4)
substring = "var plid2 = '" & substring & "';"

.... and then save it to a plid.js File on my local machine
Now I want to place a cron job on to my server. I have to do this now in a PHP file......Now Question...... does anyone knows a simple PHP Way for my problem????
:-)

A: Hi thanks to rickdenhaan..... if someone searching for such code.... here is the way which works for me:
    <?php
$meinString = file_get_contents('URL');
$findMich   = 'toni=';
$pos = strpos($meinString, $findMich);
$plid = "var plid2 = '" . substr($meinString, $pos + 5, 4) . "';";
$myfile = fopen("plid.js", "w") or die("Unable to open file!");
fwrite($myfile, $plid);
fclose($myfile);
?>


text:
Q: Tidy-html5 on Mac OS: how to install Please help
I need to install HTML tidy on Mac OS
http://w3c.github.com/tidy-html5/
I call the commands in the Terminal and get nothing:
$ make -C build/gmake/
make: *** build/gmake/: No such file or directory.  Stop.

$ sh build/gnuauto/setup.sh && ./configure && make
sh: build/gnuauto/setup.sh: No such file or directory

What's the problem? What else should I install?

A: It didn't work for me, but here is what did:
Tap dupes repository:
brew tap homebrew/dupes

Homebrew dupes repository contains

formulae [that] duplicate software provided by OS X, though may provide more recent or bugfix versions.

Then install from the dupes repository:
brew install tidy --HEAD

A: The following worked for me:
brew update
brew install tidy-html5

Shell output:
➜  ~  brew install tidy-html5
==> Downloading https://homebrew.bintray.com/bottles/tidy-html5-4.9.26.yosemite.
######################################################################## 100.0%
==> Pouring tidy-html5-4.9.26.yosemite.bottle.tar.gz
  /usr/local/Cellar/tidy-html5/4.9.26: 8 files, 1.2M

A: To install tidy5 which is the most up-to-date version of Tidy for OS X:
Ensure you have homebrew installed.
Then tap the dupes repository which provides brew recipes for new versions / bug fixes of software which is provided by the OS X system.
$ brew tap homebrew/dupes

Install Tidy (tidy-html5)
$ brew install --HEAD tidy

Untap the dupes repository
$ brew untap homebrew/dupes

To invoke
$ tidy5 -v
> HTML Tidy for Mac OS X version 5.4.0

A: tidy-html5 has been promoted to stable, so you should simply need to run in an up-to-date installation of Homebrew the command:
$ brew install tidy-html5

A: I've just installed the Tidy in Mac OS X 10.9.1:
brew install tidy

It will automatically install its dependencies: automake and libtool
And you may notice, I have a default tidy under /usr/bin/tidy, which has a version:
HTML Tidy for Mac OS X released on 31 October 2006 - Apple Inc. build 15.12
After installation of Homebrew, the version appears as
HTML Tidy for Mac OS X released on 25 March 2009
, under the path: /usr/local/Cellar/20090325/bin/tidy

A: The problem is that the documentation doesn't mention that you have to be in the bundle directory to run the first commands. The commands given are relative to the bundle directory.
Steps I just did successfully yesterday:
cd ~/Library/Application Support/Avian/Pristine Copy/Bundles
git clone https://github.com/w3c/tidy-html5
cd tidy-html5/
sudo make -C build/gmake/
sudo make install -C build/gmake/
Not sure about the shared library part because I did not go through those steps.


text:
Q: Getting office365 task properties I am working on Office 365 tasks using ews api in c#. I have successfully accessed most properties of a task but fed up with accessing two properties and their values 1-Repetition, 2-Unit of measure for actualwork and totalwork (can access ActualWork and Total work but not their unit of measures eg. if actualwork is set in hours or minutes? how to get this?). Can anyone help me how to get these properties?
enter image description here
enter image description here

A: The unit of measurement is always minutes as documented in https://msdn.microsoft.com/en-us/library/ee219615(v=exchg.80).aspx . Those UI elements are calculated based on the value in minutes. Eg you can easily test this in the UI try setting it to 480 minutes and you should see the UI change to 1 day once you save it and reopen it. But you need to take into account it working hours (where 480 minutes equal one day and 2400 minutes equal one week (8 hours in a work day and 5 work days in a work week)).


text:
Q: Create custom standard output stream I am using LispWorks's Multiprocessing tools (see here). I start a number of subprocesses (using process-run-function), where each subprocess is associated with a particular mailbox. What I want to achieve is that messages to standard output (using format) in the subprocess end up in the mailbox, after which I can read them in the main process.
I would go about this by replacing the *standard-output* stream of the subprocess with a custom stream that calls mailbox-send on the formatted string. However, I have no idea on how to create a custom stream like this. What are my options here?

A: Something like this:

(defclass mailbox-input-stream (stream:fundamental-character-input-stream)
  ((mailbox :initarg :mailbox
            :accessor mailbox-stream-mailbox
            :initform nil)))

(defmethod stream-element-type ((stream mailbox-input-stream))
  'character)

(defmethod stream:stream-read-char ((stream mailbox-input-stream))
  (let ((char (mp:mailbox-read (mailbox-stream-mailbox stream))))
    (if (eql char #\Line-Separator)
        #\Newline
        char)))

(defclass mailbox-output-stream (stream:fundamental-character-output-stream)
  ((mailbox :initarg :mailbox
            :accessor mailbox-stream-mailbox
            :initform nil)))

(defmethod stream-element-type ((stream mailbox-output-stream))
  'character)

(defmethod stream:stream-write-char ((stream mailbox-output-stream) char)
  (mp:mailbox-send (mailbox-stream-mailbox stream)
                   (if (eql char #\Newline)
                       #\Line-Separator
                       char)))

(defmethod stream:stream-line-column ((stream mailbox-output-stream))
  nil)

(defmethod stream:stream-start-line-p ((stream mailbox-output-stream))
  nil)

Then you can use READ-LINE, WRITE-LINE, READ-CHAR, WRITE-CHAR on streams created like this:
(make-instance 'mailbox-input-stream :mailbox (mp:process-mailbox process))

(make-instance 'mailbox-output-stream :mailbox other-mailbox)


text:
Q: Node.js - Array can't be pushed with Cheerio each at Netlify Functions I'm creating a project that TimelineJS with scraped Wikipedia JP's data on Netlify Functions.
TimelineJS requires JSON with it determined schema, I scraped multiple elements from Wikiepdia JP for the JSON data.
I need to set these elements to the array, and return body as a text when HTTP requested.
The code I wrote is here.
const axios = require('axios')
const cheerio = require('cheerio')
const moment = require('moment')
const ogs = require('open-graph-scraper')

const url = 'https://ja.wikipedia.org/wiki/'

moment.locale('ja')

const getOGPImagePath = async (options) => {
  return await ogs(options)
    .then((response) => {
      // console.log(response)
      const ogImagePath = response.data.ogImage.url
      return ogImagePath
    })
    .catch((error) => {
      console.log(error)
    })
}

exports.handler = async (event, context) => {
  const date = event.queryStringParameters.date
  const endpoint = url + date
  const momentDate = moment(date, 'M月D日')
  const day = momentDate.format('D')
  const month = momentDate.format('M')
  const html = await axios.get(encodeURI(endpoint),{ headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100'}})
  const $ = await cheerio.load(html.data, { decodeEntities: false })
  let data = []

  $('.mw-parser-output > ul').first().find('li').not('.mw-empty-elt').each(async (i,elem) => {
    const year = String($(elem).text().match(/\d{1,4}年/)).replace(/年/, '')
    const content = String($(elem).text().match(/\-\s(.*)/))

    const contentHtml = $(elem).html().replace(/((^<a(.*)>\d{1,4}年<\/a>(.*)\s\-\s)|(^\d{1,4}年(.*)\s\-\s))/,'')

    const $c = await cheerio.load(contentHtml, { decodeEntities: false })

    const mainUrl = await 'https://ja.wikipedia.org' + $c('a').first().attr('href')

    const options = {
      url: mainUrl
    }

    // console.log(mainUrl) <- works fine

    const ogImagePath = await getOGPImagePath(options)

    // console.log(ogImagePath) <- works fine

    data.push({
      media: {
        url: ogImagePath,
      },
      start_date: {
        year: year,
        month: month,
        day: day
      },
      text: {
        text: contentHtml
      },
      background: ogImagePath
    })

    // console.log(data) <- works fine
  })

  console.log(data) // <- Does not works fine. The result is '[]' empty array.

  return {
    statusCode: 200,
    body: JSON.stringify({ events: data }),
    headers: {
      'Content-Type': 'application/json; charset=utf8',
      'Access-Control-Allow-Origin': "*"
    }
  };
}

Does anyone have a solution for this situation?


text:
Q: Running docker on a jenkins docker container I am running a jenkins docker container and with in that I have installed docker. But when I try to run docker commands I get an error that the daemon is not turned on so I try the sudo systemctl start docker command and get the following error.
'System has not been booted with systemd as init system (PID 1). Can't operate.
Failed to connect to bus: Host is down' error
Then I try the sudo service docker start command followed by sudo service docker status which then returns the following error.
'Docker is not running ... failed!'.
So I am not quite sure what to do going forward? Any ideas?


text:
Q: Does MonoDevelop support custom targets in project (csproj) files? For example adding this to a csproj
<Target Name="BeforeBuild">
      <Exec Command="foo.exe arg1 arg2"  />
</Target>

For me it seems to be ignoring them

A: You can turn it on in the options screen

A: MD supports MSBuild projects by mapping them into its old internal build engine, which can't support arbitrary MSBuild constructs like this.
There is experimental support to use MSBuild/xbuild as the build engine, and you can enable this in MD Preferences.


text:
Q: Tell me whats wrong with this python code? I'm relatively new to coding so please help me out here. The code will only run until the 5th line. This code may be a total babel, but please humor me.
EDIT: There is no exception, nothing happens. After asking me to choose between 1 and 2, the code just stops.
print('This program will tell you the area some shapes')
print('You can choose between...')
print('1. rectangle')
print('or')
print('2. triangle')

def shape():
    shape = int(input('What shape do you choose?'))

    if shape == 1: rectangle
    elif shape == 2: triangle
    else: print('ERROR: select either rectangle or triangle')

def rectangle():
    l = int(input('What is the length?'))
    w = int(input('What is the width?'))
    areaR=l*w
    print('The are is...')
    print(areaR)

def triangle():
    b = int(input('What is the base?'))
    h = int(input('What is the height?'))
    first=b*h
    areaT=.5*first
    print('The area is...')
    print(areaT)

A: Your problem is that you have put your code into functions, but never call them.
When you define a function:
def shape():
    ...

To run that code, you then need to call the function:
shape()

Note that Python runs code in order - so you need to define the function before you call it.
Also note that to call a function you always need the brackets, even if you are not passing any arguments, so:
if shape == 1: rectangle

Will do nothing. You want rectangle().

A: A better coding style will be putting everything inside functions:
def display():
    print('This program will tell you the area some shapes')
    print('You can choose between...')
    print('1. rectangle')
    print('or')
    print('2. triangle')

def shape():
    shap = int(input('What shape do you choose?'))
    if shap == 1: rectangle()
    elif shap == 2: triangle()
    else:
        print('ERROR: select either rectangle or triangle')
        shape()

def rectangle():
    l = int(input('What is the length?'))
    w = int(input('What is the width?'))
    areaR=l*w
    print('The are is...')
    print(areaR)

def triangle():
    b = int(input('What is the base?'))
    h = int(input('What is the height?'))
    first=b*h
    areaT=.5*first
    print('The area is...')
    print(areaT)

if __name__=="__main__":
    display() #cal display to execute it
    shape() #cal shape to execute it


text:
Q: Starting point for survival analysis (overall survival and Porgression-free survival ) I have retrospective data of cancer patients who treated with chemo + radiation therapy and we want to measure the effect of treatment approach on survival so to  determine the start and end point for the interval of the survival (overall survival and Progression-free survival) should we choose which date ?
(the date of diagnosis - date of start treatment - date of end treatment)
and the second question is on Progression-free survival , how we should deal with death it should be as endpoint like the progression or censored ?
and if you have any reference to how determine the end and the start point please let me know
Thanks

A: For a retrospective study, I'd recommend that you start with the choices made for TCGA clinical data in Cell 173:400-416, 2018.

we chose the date of diagnosis as time zero for time-to-event calculations ...

The authors provide several reasons for that choice. It's typically the best-defined of the dates in retrospective data, and the date that probably matters most from a patient's perspective. That choice also allows you to evaluate the interval between diagnosis and start of treatment as a predictor in your model.
There might be some ambiguity in the start date of treatment if some patients receive chemoradiation adjuvant to primary surgery. You'd have to decide whether that is the date of surgery or of the start of adjuvant therapy. I'd worry about using the end date of treatment, as not all patients can tolerate a full chemoradiation series.
You could make any choice you want for time zero, however, provided that it is clear and consistent.
With respect to progression-free survival, it depends on patient tumor status at death. Quoting again from the TCGA clinical data paper, where they call this the "progression-free interval" (PFI):

PFI is the period from the date of diagnosis until the date of the first occurrence of a new tumor event (NTE), which includes progression of the disease, locoregional recurrence, distant metastasis, new primary tumor, or death with tumor. Patients who were alive without these event types, or died without tumor were censored ... The event time is the shortest period from the date of initial diagnosis to the date of an event. The censored time is from the date of initial diagnosis to the date of last contact or the date of death without disease.

You should recognize, however, that this definition of PFI can lead to bias. In practice, progression might be discovered at one of a series of clinical follow-up visits, so you only know that the progression occurred during the time interval between the immediately prior clinical visit and the visit that found progression.
Placing the date of progression at the former or the latter date will tend to bias the PFI toward shorter or longer times. It is preferable to treat the PFI in such cases as interval-censored, for which you need to record both the date of the last progression-free visit and that of the visit at which progression was detected.


text:
Q: models relationship question i have a model Post and a model User where a post belongs to a User and a User has many posts . I would like to have me returned my friends posts .
After "grabbing" my friends with @friends = current_user.friends , i have to browse through all my @friends ( who of course are also User-s ) and have them return a array in a variable that contains the most recent 20 of my friends posts and i don't know how.

A: In order to sort you can do:
array_posts = {}
@friends.each do |friend|
  array_posts[friend.name] = friend.posts.sort_by(&:created_at)
end

array_post will have for each of your friends their lists of posts sorted by their created_at attribute.


text:
Q: How can I get the customer ID in a cached block when full page cache is enabled? When the full page cache is enabled Magento disabled the PHP sessions, this way I am unable to load the customer session and get the user ID.

A: I have found this. It could be useful to you guys.
use Magento\Customer\Model\Context as CustomerContext;
use Magento\Customer\Model\Context;
use Magento\Framework\App\Http\Context as HttpContext;

/**
 * @param HttpContext $httpContext
 */
public function __construct(HttpContext $httpContext)
{
    $this->httpContext = $httpContext;
}

/**
 * @return bool
 */
private function isLoggedIn()
{
    return (bool)$this->httpContext->getValue(Context::CONTEXT_AUTH);
}

If you want to force the start of the php session you could inject the class Magento\Framework\Session\SessionManager in the constructor
and use $this->session->start()
    if (null === $customerId) {
        if ($this->httpContext->getValue(CustomerContext::CONTEXT_AUTH)) {
            if (!$this->session->isSessionExists()) {
                $this->session->start();
            }

            $visitorData = $this->session->getData('visitor_data');
            if (isset($visitorData['customer_id'])) {
                $customerId = $visitorData['customer_id'];
            }
        }
    }


text:
Q: Operation could destabilize the runtime when emiting a nullable setter I am currently overriding the setter of a given class with Reflection.Emit.
Everything works fine except when I use it with a nullable property....
Here is the code I use :
ilSetterGen.Emit(OpCodes.Ldarg_0);
ilSetterGen.Emit(OpCodes.Call, baseGetter);
ilSetterGen.Emit(OpCodes.Ldarg_1);
ilSetterGen.Emit(OpCodes.Ceq);
Label retLabel = ilSetterGen.DefineLabel();
ilSetterGen.Emit(OpCodes.Brtrue_S, retLabel);

ilSetterGen.MarkLabel(retLabel);
ilSetterGen.Emit(OpCodes.Ret);

Do you have any clue ?
EDIT : as pointed out in the answer the problem is in the equality test... I so removed the irrelevants part...

A: As always, the first thing to do is to look at what similar code in c# generates as IL, for example via reflector.
I'm not at a PC but that "ceq" looks suspect; that only works for some primitives and references; a "lifted" equals would check HasValue of each, get the values of each, and use the appropriate equality test - possibly by "ceq", but possibly via static-call to the equality operator (op_*).


text:
Q: Unable decrypt data in NodeJS which is encrypted using Swift CryptoKit - AES-256-GCM I am trying to create an application in NodeJS (Electron) as a cross platform Desktop App. This will pair with the mobile app developed using SWIFT on iOS. As part of sharing data, it is encrypted using AES-256-GCM algorithm. I have the following encrypt and decrypt methods in SWIFT:
//listItems is an array of the following structure:
// - id: Int, title: String, data: String, ldate: String
func encrypt(listItems: [ListItem], pass: String) -> String{
    let encoder = JSONEncoder()
    do{
        let data = try encoder.encode(listItems)
        let key = SymmetricKey(data: SHA256.hash(data: pass.data(using: .utf8)!))
        let iv = AES.GCM.Nonce()
        let sealedBox = try AES.GCM.seal(data, using: key, nonce: iv)
        return sealedBox.combined?.base64EncodedData()
    }catch{
        fatalError("Couldn't encrypt data\(error)")
    }
}

func decrypt(data: Data, pass: String) -> [ListItem]{
    do{
        let key = SymmetricKey(data: SHA256.hash(data: pass.data(using: .utf8)!))
        let mySealedBox = try AES.GCM.SealedBox(combined: Data(base64Encoded: data)!)
        let content = try AES.GCM.open(mySealedBox, using: key)
        return load(content)
    }catch{
        fatalError("Couldn't encrypt data\(error)")
    }
}

func load<T: Decodable>(_ data: Data) -> T{
    do{
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    }catch{
        fatalError("Could not parse the data")
    }
}

For NodeJS, I have the below functions:
const crypto = require('crypto')
module.exports = {
    encryptData(data,password){
        let password_hash = crypto.createHash('sha256').update(password, 'utf-8').digest('hex').slice(0,32).toLowerCase();
        let iv = crypto.pseudoRandomBytes(12);
        iv = Buffer.from('mBj0tzBUxDFmix1T', 'base64');

        let cipher = crypto.createCipheriv('aes-256-gcm', password_hash, iv);
        let encryptedData = Buffer.from(cipher.update(data, 'utf8', 'hex') + cipher.final('hex'), 'hex');
        console.log(' --------------- ENC BEGIN ---------------');
        console.log(`IV Length: ${iv.length}`);
        //console.log(`IV Base64 Length: ${iv.toString('base64').length}`);
        console.log(iv.toString('base64'));
        //console.log(`AuthTag Length: ${cipher.getAuthTag().length}`);
        //console.log(`AuthTag Base64 Length: ${cipher.getAuthTag().toString('base64').length}`);
        console.log(cipher.getAuthTag().toString('base64'));
        //console.log(`Encrypted Data Length: ${encryptedData.length}`)
        //console.log(`Encrypted Data Base64 Length: ${encryptedData.toString('base64').length}`)
        console.log(encryptedData.toString('base64'));
        console.log(' --------------- ENC END ---------------');
        console.log(Buffer.concat([cipher.getAuthTag(), encryptedData]).toString('base64'));
        console.log(Buffer.concat([encryptedData, cipher.getAuthTag()]).toString('base64'));
        //let encryptedBuffer = Buffer.concat([iv, cipher.getAuthTag(), encryptedData]);
        return iv.toString('base64') + cipher.getAuthTag().toString('base64') + encryptedData.toString('base64');
    },

    decryptData(data,password){
        let password_hash = crypto.createHash('sha256').update(password, 'utf-8').digest('hex').slice(0,32).toLowerCase();
        //let combinerBuffer = Buffer.from(data, 'base64');
        //let iv = combinerBuffer.slice(0,16);
        let iv = Buffer.from(data.slice(0,16), 'base64');
        console.log(' --------------- DEC BEGIN ---------------');
        console.log(iv.toString('base64'));
        let at = Buffer.from(data.slice(16,32), 'base64');
        console.log(at.toString('base64'));
        let enc_buffer = Buffer.from(data.slice(32), 'base64');
        console.log(enc_buffer.toString('base64'));
        console.log(' --------------- DEC END ---------------');
        let deciper = crypto.createDecipheriv('aes-256-gcm', password_hash, iv);
        deciper.setAuthTag(at)
        let dec_buf = deciper.update(enc_buffer, 'utf8') + deciper.final('utf8');
        return dec_buf.toString('utf8');
    }
}

The encrypted by SWIFT cannot be decrypted by NodeJS. While decrypting the data, i get the error:
Unsupported state or unable to authenticate data
I have a similar code in Java also which works well with the SWIFT generated encrypted data but the NodeJS one does not work at all. The main question is how do I get the AAD and AuthTag from the combined encrypted text generated by SWIFT. In Java, I just need to extract the first 16 bytes of IV and the rest as Cipher Text which includes Auth Tag as well. However, in NodeJS i need to manually extract the pass on the AuthTag. I tried breaking up the combined data from SWIFT as:

*

*IV (16 bytes) + CipherText + Tag (16 bytes)
and also as:

*IV (16 bytes) + Tag (16 bytes) + CipherText

Both of these do not work and generate the same error as above.
Below is the Java Code:
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;

class CryptoTest{
    public static void main(String[] args){
        try{
            String enc = Crypto.encrypt("This is data", "password");
            String dec = Crypto.decrypt(enc,"password");
            System.out.println(enc);
            System.out.println(dec);

        }catch(Exception ex){
            System.out.println("ERROR");
        }
    }

    private static class Crypto {
        private static final int GCM_TAG_LENGTH = 16;
        private static final int GCM_IV_LENGTH = 12;
        private static final String ALGORITHM = "AES_256/GCM/NoPadding";
        private static final String ALGORITHM_SHORT_NAME = "AES";
        private static final String HASH_ALGORITHM = "SHA-256";

        public static String encrypt(String plaintext, String password) throws Exception
        {
            //Generate the key from password
            MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM);
            byte[] key = md.digest(password.getBytes(StandardCharsets.UTF_8));

            SecureRandom sr = new SecureRandom(password.getBytes(StandardCharsets.UTF_8));
            byte[] iv = new byte[GCM_IV_LENGTH];
            // sr.nextBytes(iv);
            iv = Base64.getDecoder().decode("mBj0tzBUxDFmix1T");

            // Get Cipher Instance
            Cipher cipher = Cipher.getInstance(ALGORITHM);

            // Create SecretKeySpec
            SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM_SHORT_NAME);

            // Create GCMParameterSpec
            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);

            // Initialize Cipher for ENCRYPT_MODE
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);

            // Perform Encryption
            byte[] cipherText = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));

            //Return the IV and CipherText as Base64 encoded and appended strings
            System.out.println(Base64.getEncoder().encodeToString(iv));
            System.out.println(Base64.getEncoder().encodeToString(cipherText));

            return Base64.getEncoder().encodeToString(iv)+Base64.getEncoder().encodeToString(cipherText);
        }

        public static String decrypt(String sourceText, String password) throws Exception
        {
            //Get the IV from cipherText
            byte[] iv = Base64.getDecoder().decode(sourceText.substring(0,16));

            //Get the reminder of cipherText after the iv
            byte[] cipherText = Base64.getDecoder().decode(sourceText.substring(16));

            //Generate the key from password
            MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM);
            byte[] key = md.digest(password.getBytes(StandardCharsets.UTF_8));

            // Get Cipher Instance
            Cipher cipher = Cipher.getInstance(ALGORITHM);

            // Create SecretKeySpec
            SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM_SHORT_NAME);

            // Create GCMParameterSpec
            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);

            // Initialize Cipher for DECRYPT_MODE
            cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);

            // Perform Decryption
            byte[] decryptedText = cipher.doFinal(cipherText);

            return new String(decryptedText);
        }
    }
}

Data: This is data

Key: password

IV: mBj0tzBUxDFmix1T

Java code generates the following:

Encrypted Text: UgNY3VAwNU07iEqU1Jq3m3Q+p6bDCZg6UI0h8w==

NodeJS code generates the following:

AuthTag: BXQ0vZH4HBBpGb7Y7R9iJw==

Encrypted Text: O+wuVJB06JO6rPrc

From what I have read, Java will generate the encrypted text with the AuthTag included in it. I tried concatenating the AuthTag to Encrypted Text but the output never equals the one generated by Java.
The Java encrypted text however can be decrypted by the SWIFT CryptoKit code without any issues.

A: In addition to the fact that Java crypto puts the GCM authtag at the end of the ciphertext (as identified in comments) your Java code is using the SHA256 of the password as the key, while your nodejs is using the ASCII characters of the hex representation of half the SHA256; this is a completely different value, and the whole point of symmetric (traditional) cryptography is that you must use (exactly) the same key at both ends. In addition your method of converting to base64 and then concatenating with string-plus, and conversely slicing the base64 before decoding, only works right if the data and IV are both multiples of 3: the GCM IV/nonce is 12, which is okay, and so is your example value 'This is data', but most real data won't be.
The following modified js matches your Java. I don't do SWIFT, but if as you say it matches your Java it should also match this js.
const crypto = require('crypto')
function encryptData(data,password){
        //--let password_hash = crypto.createHash('sha256').update(password, 'utf-8').digest('hex').slice(0,32).toLowerCase();
        let password_hash = crypto.createHash('sha256').update(password, 'utf-8').digest();
        let iv = Buffer.from('mBj0tzBUxDFmix1T', 'base64'); // TEST ONLY SHOULD BE UNIQUE (such as random)
        let cipher = crypto.createCipheriv('aes-256-gcm', password_hash, iv);
        //--let encryptedData = Buffer.from(cipher.update(data, 'utf8', 'hex') + cipher.final('hex'), 'hex');
        let encryptedData = Buffer.concat([cipher.update(data, 'utf8'), cipher.final()]);
        //--return iv.toString('base64') + cipher.getAuthTag().toString('base64') + encryptedData.toString('base64');
        return Buffer.concat([iv,encryptedData,cipher.getAuthTag()]).toString('base64');
        // or just concat([iv,cipher.update(data,'utf8'),cipher.final(),cipher.getAuthTag()]).toString('base64')
    }

function decryptData(data,password){
        let password_hash = crypto.createHash('sha256').update(password, 'utf-8').digest(); //**
        let combinerBuffer = Buffer.from(data, 'base64'); //**
        let iv = combinerBuffer.slice(0,12); //**
        let deciper = crypto.createDecipheriv('aes-256-gcm', password_hash, iv);
        let temp = combinerBuffer.length-16;
        deciper.setAuthTag(combinerBuffer.slice(temp));
        return deciper.update(combinerBuffer.slice(12,temp), 'utf8') + deciper.final('utf8');
    }

let p = 'password', i = 'This is data';
let c = encryptData(i,p); console.log(c);
let d = decryptData(c,p); console.log(d);

Finally, using a single fast and unsalted hash of a password for a key has very little security and will likely be broken. But that's a design issue, and offtopic for SO. If you have the power to change this design and care about actual security, see security.SX, where you will find many recommendations to at least use something like PBKDF2 (an iterated, salted HMAC) or even better one of the newer, memory-hard password hashes like scrypt or argon2.
Also, as I commented, the IV/nonce for GCM is only required to be unique; using a secure random generator is one common way of obtaining unique values, but not the only one. (This contrasts to CBC mode where the IV must be unique and unpredictable, which in practice requires either random or SIV.)


text:
Q: How to SSH a server getting dynamic IPs from DHCP I have a ubuntu server at remote site to whom I access via SSH user@ip-address.
IP is assigned from a DHCP server of remote site (for which I don't have access). After few reboots, the server's IP gets released and it gets new IP address. I then have to call someone at remote site to go and check the server's new IP so I can SSH.
Is there a way that I can SSH the machine via hostname (or any other configuration) without completely relying on the IP?


text:
Q: What will happen to the remaining tasks when ContinueWhenAny is invoked? What will happen to the remaining tasks when  TaskFactory.ContinueWhenAny(Task[], Action(Task)) is invoked? DO the remaining tasks get cancelled or will be running in the background after a particular task is completed first? How do we cancel them if they are running in the background?

A: The remaining tasks run as normal. This continuation triggers when the first Task completes.
Cancel the remaining tasks like this:
var tknSource = new CancellationTokenSource();
List<Task> tasks = new List<Task>();

for(int i = 0; i < 50; i++)
{
    tasks.Add(Task.Run(DoWork(tknSource.Token))); //pass the token to the tasks
}

TaskFactory.ContinueWhenAny(tasks.ToArray(), p => tknSource.Cancel()); //requests a cenllation on tasks that are still running

Note that you can only request cancellation. DoWork has to observe and act upon the token as it changes state.
Check out the MSDN article on Task Cancellation for more details


text:
Q: Sending bytes commands to a Star Micronics SM-S220I printer I'm trying to get my head around how this works. I want to change the font size of a specific word in the ticket.
On the manual, it says that the character size is changed with the following commands:
ASCI: GS ! n
HEX: 1D 21 n

Where n represents both height and width expansions. Bit 0 to 2 sets the character width. Bit 4 to 6 sets the character height.
So I tried these different code variations:
[commands appendBytes:"\x1d\x21\x00"
               length:sizeof("\x1d\x21\x00") - 1];
[commands appendData:[@"ABCD1\n" dataUsingEncoding:NSASCIIStringEncoding]];

[commands appendBytes:"\x1d\x21\x02"
               length:sizeof("\x1d\x21\x02") - 1];
[commands appendData:[@"ABCD2\n" dataUsingEncoding:NSASCIIStringEncoding]];

[commands appendBytes:"\x1d\x21\x04"
               length:sizeof("\x1d\x21\x04") - 1];
[commands appendData:[@"ABCD3\n" dataUsingEncoding:NSASCIIStringEncoding]];

[commands appendBytes:"\x1d\x21\x06"
               length:sizeof("\x1d\x21\x06") - 1];
[commands appendData:[@"ABCD4\n" dataUsingEncoding:NSASCIIStringEncoding]];

[commands appendBytes:"\x1d\x21\x08"
               length:sizeof("\x1d\x21\x08") - 1];
[commands appendData:[@"ABCD5\n" dataUsingEncoding:NSASCIIStringEncoding]];

[commands appendBytes:"\x1d\x21\x10"
               length:sizeof("\x1d\x21\x10") - 1];
[commands appendData:[@"ABCD6\n" dataUsingEncoding:NSASCIIStringEncoding]];

[commands appendBytes:"\x1d\x21\x12"
               length:sizeof("\x1d\x21\x12") - 1];
[commands appendData:[@"ABCD7\n" dataUsingEncoding:NSASCIIStringEncoding]];

[commands appendBytes:"\x1d\x21\x14"
               length:sizeof("\x1d\x21\x14") - 1];
[commands appendData:[@"ABCD8\n" dataUsingEncoding:NSASCIIStringEncoding]];

[commands appendBytes:"\x1d\x21\x16"
               length:sizeof("\x1d\x21\x16") - 1];
[commands appendData:[@"ABCD9\n" dataUsingEncoding:NSASCIIStringEncoding]];

[commands appendBytes:"\x1d\x21\x18"
               length:sizeof("\x1d\x21\x18") - 1];
[commands appendData:[@"ABCD10\n" dataUsingEncoding:NSASCIIStringEncoding]];

[commands appendBytes:"\x1d\x21\x19"
               length:sizeof("\x1d\x21\x19") - 1];
[commands appendData:[@"ABCD11\n" dataUsingEncoding:NSASCIIStringEncoding]];

Which give me this result:

Which is totally unexpected, at least for me. Can anyone help me understand how this works?
The final output I would like is to get the height of ABCD9 but with a proportional width.
Thank you

A: I do not know that printer, but from your example output it seems that bits 0-2 define
the height, and bits 4-6 the width of the character (just the other way around from what
you described). So the bits of n are
0www0hhh

The string "ABCD9" is printed with n = \x16 = 00010110, which corresponds
to height = 6 (binary 110) and width = 1 (binary 001).
To get the string printed with width = height = 6 you would need
n = 01100110 = 0x66

therefore
[commands appendBytes:"\x1d\x21\x66" length:3];


text:
Q: Run time for a recursive statement Take the following pseudocode:
def dividethree (n) :
if ( n == 1) :
   return True  #O(1)
if (( n % 3) == 0) :
   return ( dividethree ( n / 3) )
else :
   return False #O(1)

Would the big O runtime for this be O(log3(n)) given that if we start with n we would divide by 3 going further and further down the binary tree? The if statement of n mod 3 is throwing me off.
Thanks!

A: Your analysis seems correct although I wouldn't refer to this particular call chain as a binary tree since only one child can be spawned recursively. Disregard n % 3 from a complexity standpoint because if you call it with an exponent of 3 such as 9, 27, 81... you have the worst case scenario.


text:
Q: Deploy pre-written SpringMVC + Hibernate to AWS Basically, I've already written a webapp, it has hibernate with SpringMVC + Spring-security.
I have an EC2 account, my question is, when deploying it to the cloud rather than on a server locally like I do now (with RDS rather than having MySQL on localhost like I do now), should I just copy the war over onto the Tomcat installation of EC2, or do everything through Eclipse?
Is it relatively straight forward to set the new Hibernate.cfg.xml to point at a RDS rather than localhost?
At the moment I just copy the war onto the server and use iptables to map 80 to 8080, but I think I'm taking a very long route for deployment...I've not setup the db layer yet remotely...
Thanks,

A: I am used to deploying WAR files to EC2 instances (though using WebLogic instead of Tomcat), and I think it is much more straightforward just to FTP the files over to the EC2 instance rather than trying to deploy them through Eclipse.
For your other question, it is completely straightforward pointing Hibernate.cfg.xml to RDS. You will probably have no issues doing so, as long as you remember to give the correct permissions on RDS. Hope it helps.


text:
Q: sql smallest value with left join I have two tables, Article and Image with one-to-many where Article is the parent and the Image has foreign key column article_id. Each Image also has the column position that is integer.
Now what I need is to I get all of the articles, regardless if there are any images for all of them, but for those that have one ore more images it needs to return a single image which has the lowest position stored in position column.
In other words along the pseudo lines:
SELECT FROM ALL ARTICLES LEFT JOIN IMAGES (WHERE IMAGE FOR THIS ARTICLE HAS SMALLEST POSITION)

What SQL query to get the above?

A: One cannot give a precise answer without knowing your schema, but in essence you want to get the groupwise minimum:
SELECT *
FROM   Article LEFT JOIN (
         Images NATURAL JOIN (
           SELECT   article_id, MIN(position) AS position
           FROM     Images
           GROUP BY article_id
         ) AS t
       ) USING (article_id)

A: SELECT * FROM ARTICLES AS art
LEFT JOIN
 (SELECT article_id, image_id,
                 MIN(Position) AS Position
   FROM Images
   GROUP BY article_id, image_id) AS MinPos
 LEFT JOIN Images AS img ON
MinPos.article_id = img.article_id AND
MinPos.image_id = img.image_id


text:
Q: Remaining space when using auto layout space constraint I'm trying to use auto layout for automatically resize my scroll view. Although I created space constraints as 0, there are 16 pixels space from both left and right sides of the screen in run time.
Design time picture:

A: uncheck Constrain to margins option


text:
Q: How to keep NULL values in STRING_SPLIT Please excuse formatting, this is my first post.
I have a table like the one below:

id
code
Fig

1
AAA
MB010@2-1-2-5A@2-2-3

2
AAB
MB010@2-3-4-2@2-2A-2-4

3
AABA
NULL

4
AAC
MB020@2-5-3A

My code is as follows:
  SELECT
     source.id
    ,source.code
    ,codePub = LEFT(source.Fig,5)
    ,f.value AS [FigRef]
  FROM [dbo].[sourceData] AS source
  OUTER APPLY STRING_SPLIT(source.[Fig], '@') as f
  WHERE f.value NOT LIKE 'MB%'

Which gives me the following table:

id
code
codePub
FigRef

1
AAA
MB010
2-1-2-5A

1
AAA
MB010
2-2-3

2
AAB
MB010
2-3-4-2

2
AAB
MB010
2-2A-2-4

4
AAC
MB020
2-5-3A

But I want the codes with NULL values as well, like below:

id
code
codePub
FigRef

1
AAA
MB010
2-1-2-5A

1
AAA
MB010
2-2-3

2
AAB
MB010
2-3-4-2

2
AAB
MB010
2-2A-2-4

3
AABA
NULL
NULL

4
AAC
MB020
2-5-3A

How can I keep the codes with NULL Fig values?

A: Your WHERE clause filters NULLs out.
NULL LIKE 'MB%' is "unknown", which is not "true" in the context of the WHERE clause, so these rows are filtered out.
NULL NOT LIKE 'MB%' is still "unknown", which is still not "true" in the context of the WHERE clause, so these rows are also filtered out.
NULL = NULL is "unknown", NULL IS NULL is "true".
Comparison Operators

Comparison operators test whether two expressions are the same.
The result of a comparison operator has the Boolean data type. This
has three values: TRUE, FALSE, and UNKNOWN. Expressions that return a
Boolean data type are known as Boolean expressions.
When SET ANSI_NULLS is ON, an operator that has one or two NULL expressions returns UNKNOWN.

You need to explicitly compare with NULL using IS operator. For example, like this:
  SELECT
     source.id
    ,source.code
    ,codePub = LEFT(source.Fig,5)
    ,f.value AS [FigRef]
  FROM
      [dbo].[sourceData] AS source
      OUTER APPLY STRING_SPLIT(source.[Fig], '@') as f
  WHERE
      f.value NOT LIKE 'MB%' OR f.value IS NULL

A: it should be an easy as just putting isnull around the splitting values:
 SELECT
     source.id
    ,source.code
    ,codePub = LEFT(source.Fig,5)
    ,f.value AS [FigRef]
  FROM [dbo].[sourceData] AS source
  OUTER APPLY STRING_SPLIT(isnull(source.[Fig],'NULL'), '@') as f
  WHERE f.value NOT LIKE 'MB%'

A: You might be able to use a union here:
SELECT
    source.id,
    source.code,
    codePub = LEFT(source.Fig, 5),
    f.value AS [FigRef]
FROM [dbo].[sourceData] AS source
OUTER APPLY STRING_SPLIT(source.[Fig], '@') AS f
WHERE f.value NOT LIKE 'MB%'

UNION ALL

SELECT id, code, Fig, NULL
FROM [dbo].[sourceData]
WHERE Fig IS NULL
ORDER BY id;


text:
Q: Call JavaScript function(with parameters) by onclick event I cant use PHP variables to use as parameters for my function.
The function is:
<script type="text/javascript">
function myFunction(id,name) {
    alert(id);
    alert(name);
}
</script>

And this is PHP part:
echo "<button onclick='myFunction($intvar,$strvar)' type='button'>ClickMe</button>";

the call works when I use numbers like this: myFunction(0,1)
but I need to use variables to call myFunction.
Please Help, thanks.

A: You try this
function myFunction(ide,name) { change insted of id => ide
    echo "<button onclick='myFunction(".'"'.$intvar.'","'.$strvar.'"'.")' type='button'>ClickMe</button>";

A: Good practice is to echo json encoded version of variables, this way you ensure that strings are properly quoted:
echo "<button onclick='myFunction(" . json_encode($intvar) . "," . json_encode($strvar, JSON_HEX_APOS) . ")' type='button'>ClickMe</button>";


text:
Q: Unit Testing callback converted to promise with Sinon So i want to test the function below by stubbing channel.sendToQueue, however I am not sure how to handle the callback that gets converted to a promise.
const queMessage = async function(channel, queue, msg, opts={persistent: true})
{
    //Does not return promise from Amqplib so creating our own.
    return new Promise(function (resolve, reject) {
        logger.debug('Queuing message on %s queue. %o, %o', queue, msg, opts)
        channel.sendToQueue(queue, Buffer.from(msg), opts, (err, ok)=>
        {
            if(err)
            {
                logger.error('Error pushing message to %s queue. %o',queue, err)
                reject(err)
            }
            else
            {
                logger.verbose('Pushed message to %s queue successfully.', queue)
                resolve()
            }
        })
    })
}

A: Here is the unit test solution:
index.ts:
const logger = {
  debug: console.log,
  error: console.error,
  verbose: console.log,
};

const queMessage = async function(channel, queue, msg, opts = { persistent: true }) {
  return new Promise(function(resolve, reject) {
    logger.debug('Queuing message on %s queue. %o, %o', queue, msg, opts);
    channel.sendToQueue(queue, Buffer.from(msg), opts, (err, ok) => {
      if (err) {
        logger.error('Error pushing message to %s queue. %o', queue, err);
        reject(err);
      } else {
        logger.verbose('Pushed message to %s queue successfully.', queue);
        resolve();
      }
    });
  });
};

export { queMessage, logger };

index.test.ts:
import { queMessage, logger } from './';
import sinon from 'sinon';
import { expect } from 'chai';

describe('60531301', () => {
  it('should send to queue successfully', async () => {
    const channelStub = {
      sendToQueue: sinon.stub().callsFake((queue, buffer, opts, callback) => {
        callback(null, 'ok');
      }),
    };
    const verboseLogSpy = sinon.spy(logger, 'verbose');
    await queMessage(channelStub, 'queue', 'some message');
    sinon.assert.calledWithExactly(verboseLogSpy, 'Pushed message to %s queue successfully.', 'queue');
  });

  it('should handle error if send to queue failure', async () => {
    const mError = new Error('network');
    const channelStub = {
      sendToQueue: sinon.stub().callsFake((queue, buffer, opts, callback) => {
        callback(mError, null);
      }),
    };
    const errorLogSpy = sinon.spy(logger, 'error');
    try {
      await queMessage(channelStub, 'queue', 'some message');
    } catch (error) {
      expect(error).to.be.eql(mError);
    }
    sinon.assert.calledWithExactly(errorLogSpy, 'Error pushing message to %s queue. %o', 'queue', mError);
  });
});

Unit test results with 100% coverage:
  60531301
Queuing message on queue queue. 'some message', { persistent: true }
Pushed message to queue queue successfully.
    ✓ should send to queue successfully
Queuing message on queue queue. 'some message', { persistent: true }
Error pushing message to queue queue. { Error: network
    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/60531301/index.test.ts:18:20
    at Generator.next (<anonymous>)
    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/60531301/index.test.ts:8:71
    at new Promise (<anonymous>)
    at __awaiter (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/60531301/index.test.ts:4:12)
    at Context.it (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/60531301/index.test.ts:17:65)
    at callFn (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runnable.js:387:21)
    at Test.Runnable.run (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runnable.js:379:7)
    at Runner.runTest (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:535:10)
    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:653:12
    at next (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:447:14)
    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:457:7
    at next (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:362:14)
    at Immediate._onImmediate (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:425:5)
    at runCallback (timers.js:705:18)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)
  [stack]:
   'Error: network\n    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/60531301/index.test.ts:18:20\n    at Generator.next (<anonymous>)\n    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/60531301/index.test.ts:8:71\n    at new Promise (<anonymous>)\n    at __awaiter (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/60531301/index.test.ts:4:12)\n    at Context.it (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/60531301/index.test.ts:17:65)\n    at callFn (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runnable.js:387:21)\n    at Test.Runnable.run (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runnable.js:379:7)\n    at Runner.runTest (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:535:10)\n    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:653:12\n    at next (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:447:14)\n    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:457:7\n    at next (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:362:14)\n    at Immediate._onImmediate (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:425:5)\n    at runCallback (timers.js:705:18)\n    at tryOnImmediate (timers.js:676:5)\n    at processImmediate (timers.js:658:5)',
  [message]: 'network' }
    ✓ should handle error if send to queue failure

  2 passing (70ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 index.ts |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------


text:
Q: How to set the background color of a file input in IE10+? Internet Explorer makes the background color of a file upload input gray by default:

See: http://jsfiddle.net/L0t48vnf/
How do I make the background color white?
Applying background: white CSS works in IE8 and 9, but not IE10 or 11.  See: http://fiddle.jshell.net/L0t48vnf/1/show/


text:
Q: how to get exact 3 months ago date and time from today's date and current time using C# I want to get data from database which is saved from past 3 months for that i have current date and time but how to calculate 3 months ego date and time, SO that i can pass these 2 dates in the query and get the data which was saved between these dates

A: Try this:
DateTime.Now.AddMonths(-3)

A: Use the AddMonths method:
DateTime ago = DateTime.Now.AddMonths(-3);

A: You can try this DateTime.Now.AddMonths(-3)

A: Use -3 as parameter in AddMonths method
DateTime dtPreviousDate = DateTime.Now.AddMonths(-3);

DateTime.AddMonths Method

A number of months. The months parameter can be negative or positive.

A: AddMonths can be negative.
DataTable tblResult = new DataTable();
string sql = "SELECT * FROM dbo.TableName WHERE Date BETWEEN @startDate AND @endData";
using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, con))
using (var da = new SqlDataAdapter(cmd))
{
    // asuming that your startdate is three months ago and your enddate is now
    cmd.Parameters.AddWithValue("@startDate", DateTime.Now.AddMonths(-3));
    cmd.Parameters.AddWithValue("@endDate", DateTime.Now);
    da.Fill(tblResult);
}

A: DateTime now = DateTime.Now;
DateTime olddate = new DateTime(now.Year, now.Month - 3, now.Day);


text:
Q: How to submit django ModelForm from template I am trying to create instances of
class Message(models.Model):
    text        = models.TextField()
    created     = models.DateTimeField(auto_now_add=True)
    sender      = models.ForeignKey(User, related_name='messages_sent')
    receiver    = models.ForeignKey(User, related_name='messages_received')

when users try to message other users. I have a form
<form action="{% url 'chat:submit_message' viewed_user.username %}" method="post">
{% csrf_token %}
    <input type="text" name="message" id="message" value="" />
    Enter your message here

<input type="submit" value="Send" />
</form>

and the "sender" is stored in the 'request.user', and "receiver" is carried as 'username' in
url(r'^message/(?P<username>\w+)/$',        views.message

I tried
def send_message(request, username):
    """Add a new comment."""
    # p = request.POST
    print request
    message = Message()
    m = request.POST
    mf = MessageForm(m, instance=message)
    text    = request.POST['message']
    sender  = User.objects.get(username=username)
    receiver= request.user
    mf.fields["text"] = text
    mf.fields["sender"] = sender
    mf.fields["receiver"] = receiver
    mf.save()

and got complaints of
`AttributeError at /chat/message/[username]/submit/
'unicode' object has no attribute 'widget'`

How do I create messages when form is submitted?

A: Here is the code which will work:
from django import forms
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect

class MessageForm(forms.ModelForm):
    class Meta:
        model = Message
        fields = ['text']

@login_required
def send_message(request, username):
    if request.method == 'POST':
        message = Message(sender=request.user,
                          receiver=get_object_or_404(User, username=username))
        form = MessageForm(request.POST, instance=message)
        if form.is_valid():
            form.save()
        else:
            # handle the invalid form here if you want
    return redirect('some-view')

Note that the field name is the text but not the message so you need to update the html form with valid field name.


text:
Q: Change the order of the columns based on a specific pattern I have a data frame similar to the structure below:

I would like just to reshuffle the columns to get the following order (No computation is necessarey):

The order should be Amount, Buy, Sell for the both two sequences. I know that Amount fields are always numeric and the Buy fields contains only Buy, and Sell fields only Sell. There could be also further Amount03, Buy03 and Sell03 in the table, where you do not need to do any change (e.g. Right order)!
To replicate the issue, I attached the sample data frame below:
main = {'ID': [1,2,3],
        'Name1': ['Julius', 'Peter', 'Marcus'],
'Postcode': [58921, 69751, 60314],
'Buy01': ['Buy', 'Buy', ''],
'Sell01': ['', '', 'Sell'],
'Amount01': [1500, 1200, 3000],
'ELO': [15, 18, 15],
'Buy02': ['Buy', ' ', ''],
'Sell02': ['', 'Sell', 'Sell'],
'Amount02': [1600, 1100, 3620],
'Height': [178, 165, 174],
'Weight': [96, 85, 73],
        }
df = pd.DataFrame(main, columns = ['ID', 'Name1', 'Postcode', 'Buy01', 'Sell01', 'Amount01', 'ELO',  'Buy02', 'Sell02', 'Amount02', 'Height', 'Weight'])

I am looking for a generic solution. Any help/suggestion would be highly appreciated!

A: This is not the full solution to your question but might be useful to spark some ideas.
In pandas you can get the columns of the dataframe with the following notation:
df[['col1', 'col2']]

Based on that idea, you can change the order the columns are displayed too. For example in your case:
>>> df[['Amount01', 'Sell01', 'Buy01']]
   Amount01 Sell01 Buy01
0      1500          Buy
1      1200          Buy
2      3000   Sell

You could potentially do something like this to reorder the columns:
>>> columns = list(df.columns)
>>> df[sorted(columns)]
   Amount01  Amount02 Buy01 Buy02  ELO  Height  ID   Name1  Postcode Sell01 Sell02  Weight
0      1500      1600   Buy   Buy   15     178   1  Julius     58921                    96
1      1200      1100   Buy         18     165   2   Peter     69751          Sell      85
2      3000      3620               15     174   3  Marcus     60314   Sell   Sell      73

More ad hoc "ordering" can be done using a custom algorithm for sorting. There you can add the logic you described to sort the columns array and then get the columns sorted.


text:
Q: Nesting of static blocks are not allowed in Java? OCJA 1.8 I am preparing for OCJA exam where I came across the concept of static blocks. I was trying the different combination where I have noted that nesting of instance blocks are allowed but nesting of static blocks are not allowed. Why nesting of static blocks are not allowed? Unfortunately I am not able to find the online resource where this reason can be explained.
Below is nesting of instance block which compiles fine.
  class Test {
   {
        {
            System.out.print("Instance Block One");
            {
                System.out.print("Nested Instance Block");
            }
        }
    }

      public static void main(String[] args){
        System.out.print("Main Method");
     }
}

Below is nesting of static block which fails at compile time.
  class Test {
    static{
            static{
                System.out.print("Static Block One");
                    static{
                        System.out.print("Nested static Block");
                    }
                }
        }

   public static void main(String[] args){
      System.out.print("Main Method");
   }
}


text:
Q: Setting up ASP.NET Identity multi factor I'm setting up a REST API project using ASP.NET Core Identity for user management only (so this will be my identity provider). What I would like to also add is multi factor authentication (I would prefer Microsoft's authenticator). I don't know how to do that exactly and I could not find anything on the web which I could use.
Did anyone had to implement this and if so willing to share a repo , code sample or something ?
My app consists from an asp.net core backend and a react app.


text:
Q: Calling dispose within list.removeAll I'm pretty new to C# programming, and the concept of the GC, and its realtions to IDisposable is still a bit vague. What does calling Dispose mean in terms of the garbage collection?
Specifically i wonder if the following code may fail occationally, depending on when the garbage collection kicks in. (I have not been able to make it crash during my tests).
//List<TestClass2> tc2List;
//TestClass2 invokes a thread. It implements IDisposable.
//Its Dispose() sets a stop-condition for the thread,
//and joins the thread, awaiting it to stop. (may take 100 msek)

tc2List.RemoveAll(t =>
{
  if (String.Compare(t.Name, "Orange") == 0)
  {
    t.Dispose(); //May take up to 100 msek
    return true;
  }
  return false;
});

A: Your code works, but it's bad style. Predicates should not have side effects. So you should first dispose the elements, and then remove them.
Predicate<T> filter = t => t.Name == "Orange";
foreach(var t in tc2List.Where(filter))
  t.Dispose();
tc2List.RemoveAll(filter);

A:
i wonder if the following code may fail occationally, depending on when the garbage collection kicks in

No, it won't fail
//Its Dispose() sets a stop-condition for the thread,
//and joins the thread, awaiting it to stop. (may take 100 msek)

That is a slightly a-typical use of Dispose() but not wrong. A more efficient approach would use a different Stop() so that you can stop all threads at once. Or call Dispose() from Parallel.ForEach(). But whatever method you choose, it is not hindering, nor is it being hindered by, the GC.

A: Do you have finalize method in you TestClass2?
Dispose main properties

*

*This has to be implemented in classes implementing IDispose interface.

*Its the right place for freeing-up unmanaged resources like file, handles, and connections etc.

*Dispose() method is called explicitely in the code itself.

*Dispose() method is automatically called (for objects which implement IDispose), when used in a "using"

Refer to link.

A: What does calling Dispose mean in terms of the garbage collection?
Calling dispose, means you are forcibly cleaning up things (literally the memory) using your implementation of the Dispose method. Note : (Some of the framework classes do call your implementation of Dispose for you. System.Windows.Forms.Form for example)
Garbage collection on the contrast is a feature of the .NET runtime that will clean up things for you automatically. Automatically i mean, because its up to the memory pressure and other factors that is taken care by the runtime.
A simple strategy i would recommend. Do Dispose() if you think that the memory would stay longer than needed and would impact the application. Else leave it to the runtime, it will automatically cleans up (i.e finalizes) the objects when they go out of scope. The GC has its own algorithm on how to do cleanup, but you can to a greater extent rely on it.
The next question
Specifically i wonder if the following code may fail occasionally, depending on when the garbage collection kicks in
I guess no. Failure of the code due to GC kicking in, depends on how you write the finalizer of TestClass2. Definitely your call t.Dispose() wont clash with the GC.


text:
Q: SharePoint provider hosted add in throwing 401 error on execute query We have a provider hosted app used by many customers in SharePoint Online, but there is this one new customer who is getting this error whenever he tries to launch the app after installation.
AppOnlyPolicy is true
User is tenant admin and site collection admin.
From exception stack trace, I suspect below piece of code is culprit:
Host context for Event receiver is fetched via:
TokenHelper.CreateAppEventClientContext

host context for page request is fetched via:
TokenHelper.GetClientContextWithAccessToken

;
this.SP.site = this.SP.hostContext.Site;
                this.SP.hostContext.Load(this.SP.site, s => s.ServerRelativeUrl, s => s.Id, s => s.Url);

                this.SP.rootWeb = this.SP.site.RootWeb;
                this.SP.hostContext.Load(this.SP.rootWeb, w => w.Id, w => w.Title, w => w.Url, w => w.ServerRelativeUrl, w => w.WebTemplate);

                this.SP.hostWeb = this.SP.hostContext.Web;
                this.SP.hostContext.Load(this.SP.hostWeb, w => w.Id, w => w.Title, w => w.Url, w => w.ServerRelativeUrl, w => w.WebTemplate);

                this.SP.hostContext.Load(this.SP.hostWeb.CurrentUser, user => user.Title, user => user.LoginName, user => user.Id, user => user.Email, user => user.IsSiteAdmin);
                this.SP.hostContext.Load(this.SP.hostWeb.RegionalSettings, r => r.LocaleId, r => r.Time24, r => r.TimeZone, r => r.DateFormat);

                this.SP.hostContext.ExecuteQuery();

Exception:
System.Net.WebException: The remote server returned an error: (401) Unauthorized.
   at System.Net.HttpWebRequest.GetResponse()
   at Microsoft.SharePoint.Client.SPWebRequestExecutor.Execute()
   at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)
   at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()

What all scenarios can be possible which can lead to this error, based on above info?

*

*I have tried removing all instances of app doing fresh
installation(including all recycle bins)

*tried deleting and re-adding app principals (site collection + tenant
level full control)

*Installed the app via sharepoint store also tried via .app file in
app catalog

As per logs I got this error at two point:

*

*while app is getting installed (in app event receiver)

*Whenever user tries to open any app pages

Both time same code is getting called


text:
Q: Change date time on Ubuntu 16.04 LTS manually? I need to change date time manually on the server Ubuntu 16.04, I disabled the ntp and disable the auto update the ntp from timedatectl using command:
timedatectl set-ntp 0

And following result is the timedatectl command :
Local time: Wed 2017-02-22 13:31:46 +0530
  Universal time: Wed 2017-02-22 08:01:46 UTC
        RTC time: Wed 2017-02-22 14:33:39
       Time zone: Asia/Colombo (+0530, +0530)
 Network time on: no
NTP synchronized: no
 RTC in local TZ: no

But when I change the time manually using sudo date -s "22 FEB 2017 07:30:00" its not updated.
Note: My server is hosted on Azure.
I confirmed this happened after system update.


text:
Q: Removing repetition I have a sentence: "As she reaches an inch from your face, something burning inside you (love) caused you to raise your arms and envelop her slim figure."
"inside you caused you" sounds repetitive.
I tried just using "As she reaches an inch from your face, something burning inside caused you to raise your arms and envelop her slim figure."
But then the reader may mistake that for something literally burning inside the house. Or is that implication okay?
How to improve the wording to remove this repetition?

A: Since the context is clearly defined, the readers should automatically assume there is nothing burning inside the house. Your original wording is fine.
You can also say:

your burning desire caused you...


text:
Q: Error too many rows 50001 in a custom Rest API I have a custom rest API that when is called from a third party system (this third party system calls me providing a country code like UK, DE, US... and some other parameters) I filter account object using this parameters and send them a custom JSON formated with the information they need, this works perfect for all countries except for US, I have so much accounts created with this country code (more than 100.000) so as long as I call this API with providing US parameter I'm getting too many rows 50001 Error in the line that I query in my APEX code for these accounts. Since I can't filter more these queries, how would you face this problem guys?
EDIT:
First of all, thank you @nbrown @Phil W @cropredyy
let me explain it a bit better, I don't need to return more than 50000K results, when this process works for other countries, we are retrieving 20 or 30 results for maybe 40K accounts finded in the first query. The problem is that my very first query over account is returning, for the US country, more than 50000K results so there we have the problem, I can't filter more this query. Can i do something like this:
1.- 3rd party system call me
2.- Run a batch process or something and get all the list of accounts
3.- Send this list to an apex method, do all the filterings
4.- Create the Json with all the records that pass the filter and send this Json to the 3rd party system.


text:
Q: text entered in EditText does not change into password immediately the password when entered by user does not change into * immedietly and plain text is displayed for 5 secs or so.I don't want this as my making a custom lock screen otherwise others can see the password entered.
I'm using

android:password="true"

kindly help

A: As far as I know this is how it is on all mobile platforms, and it's the "normal" way, because of the small, virtual keyboard you may introduce the wrong character. Nevertheless if you really want to modify that you'll have to create you own EditText, which will extend android's EditText.


text:
Q: instantiating a class using an interface and an implementation Trying to get clarifications on when you create a new variable, based on an interface or abstract class, and new it when a specific implementation.
Example:
IBlah blah = new BlahImpl();

How would you read that out?
Is it:
A reference variable blah of type IBlah is instantiated with the class BlahImpl?
And so the reference variable will be bound to IBlah, and hence only have the methods/instance and static variables of IBlah but use BlahImpl classes implementaiton of those properties/vars?
Just trying to get my terminology corrected.

A: Interfaces and abstract classes can never be instantiated. What you can do as you have in your example is to instantiate a concrete class but assign the resulting object to an interface.
Consider the following class hierarchy:
    IBlah
      ^
      |
AbstractBlah
      ^
      |
   BlahImpl

If IBlah is an interface and AbstractBlah is an abstract class and BlahImpl is a concrete class, the following lines of code are all invalid:
IBlah blah1 = new IBlah();
IBlah blah2 = new AbstractBlah();
AbstractBlah blah3 = new AbstractBlah();

The following lines of code are both valid:
IBlah blah1 = new BlahImpl();
AbstractBlah blah3 = new BlahImpl();

So you can only instantiate concrete a class but the variable you assign that to can be any super-type (a parent class or interface implemented by the class) of the concrete class.
You can refer to and use the concrete class through the interface or abstract class variable. In fact this is actually encouraged as programming to an abstract class (or interface) makes your code more flexible.
It is possible to create a concrete class from an interface or abstract class in in-place. So if we have an interface like this:
interface IBlah {
    void doBlah();
}

That interface could be implemented and instantiated in one fell swoop like so:
IBlah blah = new IBlah() {
    public void doBlah() {
        System.out.println("Doing Blah");
    }
};

A: "A BlahImpl object is instantiated, and assigned to variable blah as an implementation of interface IBlah."  We could also call it a cast, since there is an implicit cast by assigning it like that.
Edit: your first answer sounds reasonable too, the second one does not.

A: Maybe this is clearer:
Create new instance of BlahImpl and up cast it to IBlah and assign it to blah.


text:
Q: How can I append records that don't already exist in a table from a cartesian product query? My current query returns every possible outcome from 2 tables and inserts them into a junction table.
My current query looks like this:
INSERT INTO tblJunction_Courses_Software ( CourseID, SoftwareID )
SELECT tblCourses.CourseID, tblSoftware.SoftwareID
FROM tblSoftware, tblCourses
WHERE (((tblSoftware.Exclude)=No));

How can I add an additional clause to make sure that duplicate data is not appended every time the query is run?

A: I think you can do what yo want with a not exists clause:
INSERT INTO tblJunction_Courses_Software ( CourseID, SoftwareID )
     SELECT c.CourseID, s.SoftwareID
     FROM tblSoftware as s CROSS JOIN tblCourses as c
     WHERE s.Exclude = No AND
           NOT EXISTS (SELECT 1
                       FROM tblJunction_Courses_Software as cs
                       WHERE cs.CourseId = c.CourseId AND
                             cs.SoftwareId = s.SOftwareId
                      );


text:
Q: How convert blob data type into R data type (character or logical) I am reading data from database using odbc driver. I try to use dplyr syntax:
df <- tbl(con, tbl_name) %>%
    select(...) %>%
    filter(...) %>%
    collect()

But most of fields from tbl_name marked as blob type. I know some of them is character (starts with zeros and marked as blob[16 B], some logical (marked as blob[1 B]). Can I convert them to the R data type for manipulate?
Also one field have datetime type. I want to use it in filter  - what date type I must to use in expression?  I use '2020-01-01 00:00:00', as.POSIxt() - not work.


text:
Q: How to set rate limit on my outgoing requests on my own local system? Is it possible to set a rate limit in all requests which are outgoing from my own local system? I want my server not to be banned or blocked by other servers.
I searched for a forward proxy with NGINX but didn't find an official way to do that.
Maybe there is a way with ufw or iptables or anything?

A: Yes, you can limit it on NGINX server. You can configure NGINX as a proxy for all your outbound requests to external services and use module ngx_http_limit_req_module. Example of configuration and main idea, described in this article: https://www.monterail.com/blog/2011/outbound-api-rate-limits-the-nginx-way.
link to NGINX module: http://nginx.org/en/docs/http/ngx_http_limit_req_module.html


text:
Q: Numpy: averaging many datapoints at each time step This question is probably answered somewhere, but I cannot find where, so I will ask here:
I have a set of data consisting of several samples per timestep. So, I basically have two arrays, "times", which looks something like: (0,0,0,1,1,1,1,1,2,2,3,4,4,4,4,...) and my data which is the value for each time. Each timestep has a random number of samples. I would like to get the average value of the data at each timestep in an efficient manner.
I have prepared the following sample code to show what my data looks like. Basically, I am wondering if there is a more efficient way to write the "average_values" function.
import numpy as np
import matplotlib.pyplot as plt

def average_values(x,y):
    unique_x = np.unique(x)
    averaged_y = [np.mean(y[x==ux]) for ux in unique_x]
    return unique_x, averaged_y

#generate our data
times   = []
samples = []

#we have some timesteps:
for time in np.linspace(0,10,101):

    #and a random number of samples at each timestep:
    num_samples = np.random.random_integers(1,10)

    for i in range(0,num_samples):
        times.append(time)
        samples.append(np.sin(time)+np.random.random()*0.5)

times   = np.array(times)
samples = np.array(samples)

plt.plot(times,samples,'bo',ms=3,mec=None,alpha=0.5)
plt.plot(*average_values(times,samples),color='r')
plt.show()

Here is what it looks like:

A: A generic code to do this would do something as follows:
def average_values_bis(x, y):
    unq_x, idx = np.unique(x, return_inverse=True)
    count_x = np.bincount(idx)
    sum_y = np.bincount(idx, weights=y)

    return unq_x, sum_y / count_x

Adding the function above and following line for the plotting to your script
plt.plot(*average_values_bis(times, samples),color='g')

produces this output, with the red line hidden behind the green one:

But timing both approaches reveals the benefits of using bincount, a 30x speed-up:
%timeit average_values(times, samples)
100 loops, best of 3: 2.83 ms per loop

%timeit average_values_bis(times, samples)
10000 loops, best of 3: 85.9 us per loop

A: May I propose a pandas solution. It is highly recommended if you are going to be working with time series.
Create test data
import pandas as pd
import numpy as np

times = np.random.randint(0,10,size=50)
values = np.sin(times) + np.random.random_sample((len(times),))
s = pd.Series(values, index=times)
s.plot(linestyle='.', marker='o')

Calculate averages
avs = s.groupby(level=0).mean()
avs.plot()


text:
Q: Access Django from outside Django shell in real Python I run Django through a Python 3.4 virtualenv and I want to make some cronjob scripts that will access models and save.
I can do this through the Django shell python manage.py shell will initiate the Django shell. From there I can do from polls.models import Poll, Choice and make a new Poll and save it into the DB.
How can I do this through the regular Python shell?

A: Your best bet is probably to create a management command. You can run it from the command line by calling (python manage.py ) and from within the script you can access any django functions or models.
For further instructions on how see here https://docs.djangoproject.com/en/dev/howto/custom-management-commands/


text:
Q: access dictionary of list index after if control flow Say I have a list and a dictionary:
d = {'a':[0,1,2,3,4,5],'b':[0,1,2,3,4,5],'label':['love','apple','heart','hi','hello','world']}
l = ['hi','hello','world']

The dictionary of lists have the same number of items in the list, I'm looping through the list first and then an inner loop through the key,value pairs of the dictionary. My goal is to access the index of the list d['a'] and d['b'] whenever l is equal to d['label'].
My try is the following:
for i in l:
    for k,v in d.items():
        if k == 'label':
            for x in v:
                if x == i:
                    # access d['a'][3] and d['b'][3] but here i'm only printing
                    print(x)

So basically whenever l == d['label'] I want the position(index) of d['a'] and d['b'] where this event has occurred.

A: There's no need for all those loops. Use index() to get the index of a string in d['label'], then you can use that to access the corresponding elements of d['a'] and d['b'].
for word in l:
    try:
        index = d['label'].index(word)
        print(word, d['a'][index], d['b'][index])
    except ValueError:
        print(word, "not found")

A: If the order of the items in l doesn't matter, then use zip():
for a, b, label in zip(d['a'], d['b'], d['label']):
    if label in l:
        print(a, b)

If you need to iterate over the elements in the order they are in l, then I would still use zip and then sort the result by the label's location in l.