text:
Q: MongoDb Find Collections based on _id and a key in an array So if I had something like this:
{
_id:'123',
parts: ['One','Two','Three']
}

So if I wanted parts[0], is it possible to do the find for just that?
So something like:
db.stories.find({_id:'123', part:{$eq:0}})

I know the above is wrong, but I'm wondering if it's more efficient to do the find properly if possibly (criteria related to object/array key), or simply do the broad find and go from there (i.e. use the criteria without object/document.

A: You can use $project and $arrayElemAt to get the first element in the array
db.stories.aggregate([
  {
    $match: {_id: '123'}
  },{
    $project: {part: {$arrayElemAt: ['$parts',0]}}
  }
])

A: If you want to get 0 index element from the parts array you can write in this way
  db.sample.find({ _id : "123" } , { parts : { $slice : [0 , 1] } } )


text:
Q: Getting hosted IP address of WCF service I have wcf service which running with http and net.tcp protocol on IIS. Now I want to get live IP address with port that is assigned to them respectively. Furthermore,I want it in wcf service project. Please give your suggestion.

A: When you set up your WCF service using a web.config file, you specify the port as shown in the web.config below in the baseAddresses element:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="ServiceClassName">
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:12345/ServiceClassName"/>
          </baseAddresses>
        </host>
        <endpoint address=""
                  binding="netTcpBinding"
                  contract="ServiceInterfaceName" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

The IP address is a bit more tricky. Is there a reason that the IP address is not known at runtime or is there a specific reason that you cannot use the host name to connect to your service?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Given Value is not rendering in Razor input field Solved: had to remove the layout from the partial.
I have the following input:
@Html.Hidden("VendorId", (string)ViewBag.VendorId)

which doesn't render the value from the ViewBag, so, after trying everything I knew in this situation (even using the html instead of razor, still the value remains null), I figured it  would be about time to try solving this with jQuery, but things keep getting stranger. The following doesn't work:
$("#VendorId").val(id);
$("#VendorId : input").val(id);

but this works even doe jquery has at least one syntax error because of it:
$("#VendorId : input").val() = id;
$("VendorId : input").val() = id;

So, my question is, is it just me or this is really wrong? And if it is wrong, can anyone think of any reason why this is happening? I'm guessing the behaviour of razor and jquery are connected somehow but can't figure it out so I need a bit of help with this. Pretty sure it's something obvious.
I am using jQuery 1.10.2
This is where i set up the value for the ViewBag:
public async Task<PartialViewResult> SelectvendorList(string VendorId)
{
    ViewBag.VendorName = await _vendorService.GetVendorName(VendorId);
    if (VendorId == null) VendorId = "";
    ViewBag.VendorId = VendorId;

    var lists = await _vendorListService.GetAllForSelectList(User.Identity.GetUserId(), VendorId);

    IEnumerable<SelectListItem> vendorLists = lists.Select(b => new SelectListItem { Value = b.Id, Text = b.Description });
    ViewBag.vendorLists = vendorLists;

    return PartialView();
}

I also have this paragraph in my view and it renders the value corectly:

@vendorId

Here is the entire view:
@{
    ViewBag.Title = "SelectvendorList";
    Layout = "~/Views/Shared/_Purchasing.cshtml";
    var vendorId = ViewBag.VendorId;
}

New Order / Select vendor list

Vendor : @ViewBag.VendorName

@ViewBag.VendorId

@using (Html.BeginForm("AddRemoveItems", "Order", FormMethod.Get))
{
    @Html.Hidden("VendorId", (string)ViewBag.VendorId)

        @Html.Label("VendorListID", "Vendor Lists", htmlAttributes: new { @class = "control-label" })

            @Html.DropDownList("VendorListID", (IEnumerable<SelectListItem>)ViewBag.vendorLists, "", htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessage("VendorListID", "", new { @class = "text-danger" })

    <input type="submit" value="Next" />
    <input type="button" id="backButton" onclick="javascript:history.go(-1)" value="Back" />
    @Html.ActionLink("Continue with no Vendor List", "AddRemoveItems", new { VendorId = vendorId, VendorListID = "" })
}

A: Given that

@vendorId

renders the correct value, you could consider using the same variable in your hidden input, instead of the ViewBag:
@Html.Hidden("VendorId", vendorId)

A: I suggest you move away from using the ViewBag dynamic object to pass information to your views and instead create a simple ViewModel. E.g.
public class VendorViewModel
{
   public string VendorId {get; set;}
   public string VendorName {get; set;}
   public IEnumerable<SelectListItem> VendorList {get; set;}
}

In your view, at the top define the model in use
@model VendorViewModel

Then to render your hidden input:
@Html.HiddenFor(v => v.VendorId)

A: To give alue and id to input in razor, do like following
@Html.HiddenFor(m => m.VendorId, new{ @Value = ViewBag.SomeValue}, new {@id ="VendorId"})

Consider ViewBag.SomeValue has value "vendor"
This will render a html input tag like
<input type="text" value="vendor" id="VendorId" name="VendorId">

In javascript
To get the input value
$("#VendorId").val();

To assign a value to the input field
var id = "VendorId";
$("#VendorId").val(id);

hope this helps


text:
Q: Can I setenv() using a envp? I'm trying to setenv a new environement variable with setenv().
But I noticided that setenv() function set my new environement variable only if I use the environement "extern char **environ"
But I want to use the argument of the main() : "char **envp".
Here's the code I tried to do for setting in envp, but as you will see if you run that code, it won't be set in envp.
But if I use const char **environ it works.
Any ideas ?
#include <stdlib.h>
#include <stdio.h>

int     main(int ac, char **av, char **envp)
{
  int   i;

  i = 0;
  setenv("NEW_ENV_VAR", "hello_world", 0);
  while (envp[i])
    printf("%s\n", envp[i++]);
  return (0);
}

A: setenv() is documented to not be allowed to change the optional envp argument to main.
If you need to iterate through all the environment variables, use the extern char **environ variable.
See also this question.


text:
Q: Proofing de Movire without Induction and in a neat way The "usual way" gone for proving de Movire is via the road of induction. However this road get tiresome and thus wondered, if there were another way.
However I came up with a proof that relies on some "heavy hitters" and looks far from neat, intuitive, easy to pick up and else.. :
Given the ODE: $y + i y' = 0 $ with $ y(0) = 1 $, one finds $y_1 (x) = e^{ix}   $ and $y_2 (x) = \cos(x) + i \sin(x) $ to be solutions.
From Picard-Lindelöf it follows: $ y_1 = y_2 $, Euler Identity proven, and then using substitution one gets:
$ {(e^{ix})^n} = {(\cos(x) + i \sin(x))}^n = {\cos(nx) + i \sin(nx)} =  e^{inx} $, job's done.
Does someone have a good idea, how to derive de Moivre directly using as little pre-knowledge as possible? Any constructive comment, answer or recommendation is appreciated.

A: For me the simplest way is : first you define the exponential as $\exp: \mathbb{C}\to \mathbb{C}$ satisfying $\exp(z) = \sum_{n\geqslant 0} \frac{z^n}{n!}$ (it's very easy to see that this converges for all $z$). The you can show directly by expanding the series that $\exp(z+z') = \exp(z)\exp(z')$, so in particular $\exp(nz) = \exp(z)^n$.
Then you define $\cos$ and $\sin$ by $\cos(z) = \frac{\exp(iz)+\exp(-iz)}{2}$ and $\sin(z) = \frac{\exp(iz)-\exp(-iz)}{2i}$ ; in particular they are defined on $\mathbb{C}$, but if you're only interested in real variables then you can also say $\exp(it) = \cos(t) + i\sin(t)$.
Compared to defining them as solutions of ODE, this has the advantage that you don't need a theorem to show that they exist : you provide formulas (and this is quite useful because the existence of the exponential is crucial in all theorems for existence of solutions to ODE, so this avoids circular contructions).
Then the de Moivre formula is just a rewriting of $\exp(int) = \exp(it)^n$.

A: A very simple way is given in the book by James Uspensky's book titled: Theory of Equations. It is based on multiplication of the polar form representation of a complex number in the argand plane.
Let, there be two complex numbers,  $A = r(\cos\theta + i\sin\theta), B = r_1(\cos\theta_1 + i\sin\theta_1)$.Now, $(\cos\theta + i\sin\theta)(\cos\theta_1 + i\sin\theta_1) =>\cos\theta \cos\theta_1 - \sin\theta \sin\theta_1 +i(\sin\theta \cos\theta_1 + \cos\theta \sin\theta_1) \implies AB = rr_1[\cos(\theta + \theta_1) + \sin(\theta + \theta_1)]$
=> For the case of taking $n$ angles, all equal, & the modulus of all being $1$, i.e. $\theta_1= \theta_2=...=\theta_n=\theta$, and $r_1=r_2=...=r_n=1$ this formula gives the needed result, i.e. the de Moivre's formula:
$(\cos\theta + i\sin\theta)^n = \cos n\theta + i\sin n\theta$
But, I feel the generalization part (taking $n$ complex quantities) implicitly uses induction (weak case) only,


text:
Q: Is Snappy splittable or not splittable? According to this Cloudera post, Snappy IS splittable.

For MapReduce, if you need your compressed data to be splittable, BZip2, LZO, and Snappy formats are splittable, but GZip is not. Splittability is not relevant to HBase data.

But from the hadoop definitive guide, Snappy is NOT splittable.

There are also some confilitcting information on the web. Some say it's splittable, some say it's not.

A: All splittable codecs in hadoop must implement org.apache.hadoop.io.compress.SplittableCompressionCodec. Looking at the hadoop source code as of 2.7, we see org.apache.hadoop.io.compress.SnappyCodec does not implement this interface, so we know it is not splittable.

A: I have just tested with Spark 1.6.2 on HDFS, for same number of workers/processor, between a simple JSON file and compressed by snappy:

*

*JSON: 4 files of 12GB each, Spark creates 388 tasks (1 task by HDFS block) (4*12GB/128MB => 384)

*Snappy: 4 files of 3GB each, Spark creates 4 tasks

Snappy file is created like this: .saveAsTextFile("/user/qwant/benchmark_file_format/json_snappy", classOf[org.apache.hadoop.io.compress.SnappyCodec])
So Snappy is no splittable with Spark for JSON.
But, if you use parquet (or ORC) file format instead JSON, this will be splitable (even with gzip).

A: Both are correct but in different levels.
According with Cloudera blog http://blog.cloudera.com/blog/2011/09/snappy-and-hadoop/

One thing to note is that Snappy is intended to be used with a
    container format, like Sequence Files or Avro Data Files, rather than being used directly on plain text, for example, since the latter is not splittable and can't be processed in parallel using MapReduce. This is different to LZO, where is is possible to index LZO compressed files to determine split points so that LZO files can be processed efficiently in subsequent processing.

This means that if a whole text file is compressed with Snappy then the file is NOT splittable. But if each record inside the file is compressed with Snappy then the file could be splittable, for example in Sequence files with block compression.
To be more clear, is not the same:
<START-FILE>
  <START-SNAPPY-BLOCK>
     FULL CONTENT
  <END-SNAPPY-BLOCK>
<END-FILE>

than
<START-FILE>
  <START-SNAPPY-BLOCK1>
     RECORD1
  <END-SNAPPY-BLOCK1>
  <START-SNAPPY-BLOCK2>
     RECORD2
  <END-SNAPPY-BLOCK2>
  <START-SNAPPY-BLOCK3>
     RECORD3
  <END-SNAPPY-BLOCK3>
<END-FILE>

Snappy blocks are NOT splittable but files with snappy blocks are splittables.

A: Snappy is actually not splittable as bzip, but when used with file formats like parquet or Avro, instead of compressing the entire file, blocks inside the file format are compressed using snappy.
To understand what is happening when you're compressing a parquet file with snappy compression, check the structure of a parquet file [source link]

Inside a parquet file, records are split into row-groups [basically a subset of rows from the original file], and each row-groups are composed of data-pages [Column chunks in image], each column chunk is composed of many pages where actual records are stored in encoded format[columnar] with metadata. when you enable snappy compression it compresses entire pages! not the entire file. basically you are getting a splittable parquet with snappy compression.
The advantage of snappy is that it is a very light weighted compression codec.
Note: There is a default size limit to row-groups and columns chunks, 128MB and 1MB respectively [you can alter these defaults setting], you can use a different compression codec with parquet e.g. gzip


text:
Q: Show an image in a repeater grid if the bound value is evaluated to a specific value I've had a look through the questions on here, but none seem to answer my question.
I have a ASP.NET repeater grid that is set up to bound to a list that shows what the value of that item is. At the moment, it just shows the text value of the variable i.e. OFF, but what I want it to do is display the appropriate image i.e. if its off, show green image, if its on, show red image.
This is what I'm trying to do in the code, presumed you did it here instead of the aspx.cs?
<td><%# DataBinder.Eval(Container.DataItem, "Spill") == "OFF" ? %>
<asp:Image runat="server" ImageUrl="~/Images/green.JPG" />
<%:%>
<asp:Image runat="server" ImageUrl="~/Images/red.JPG" /> %>
</td>

The compiler is complaining about the '%>' after the ? and the '%>' after the : so obviously I haven't got it right, but can't think how else to do it.
Thanks for anyones help in advance

A: Markup:
<asp:Image runat="server"
   ImageUrl='<%# WhichImage(DataBinder.Eval(Container.DataItem, "Spill")) %>' />

Code-behind:
protected string WhichImage(object spill)
{
    string result = "~/Images/green.JPG";
    string spillResult= (string)spill;
    if(!spillResult.Equals("OFF"))
    {
        result = "~/Images/red.JPG";
    }
    return result;
}

A: To do it on the front side in one line, you would do something like this:
<asp:Image id="imgSpill" runat="server" ImageUrl='<%# (DataBinder.Eval(Container.DataItem, "Spill") == "OFF" ? "~/images/red.jpg" : "~/images/green.jpg") %>' />

Hope this helps! Good Luck!


text:
Q: default date range selection in React-daterangepicker I do not want to pre-select any value from date range in react-daterangepicker, by default it gives some value already selected if i choose for defined date range?

try to give its initialsetting prop a value start : "", end: "" but it gives undefined


text:
Q: How to change the background color of the section below tab bar? I want to change background color of the section which is below the tab bar but I don't know what the name of it is.

I tried with some option in tab bar but it does not work.

A: That is controlled by the breadcrumb properties found in workbench.colorCustomizations:
"workbench.colorCustomizations": {
    "breadcrumb.background": "#ff0000",
    "breadcrumb.foreground": "#00ff26"
  }


text:
Q: Protection against constant overvoltage from power supply
*

*I have a project using USB VBUS as power source.

*Fault to protect from: a bad AC-DC 5V adapter goes haywire, or a USB form factor device with non-5V output (some laptop AC-DC with USB type C?), or power surge.

The first thing comes to my mind is crowbar:

*

*F1, D3, D5, R14, C14 is the crowbar, but I don't understand the function of C14.

*D1 protects from back-flow.

*C11 is the main power supply capacitor to provide AC filtration and power stabilization, D2 and R13 forms slow-charge-quick-discharge for C11 to prevent spike when the power is first connected.

Am I using the crowbar correctly? Do I need a TVS somewhere? Any suggestion / improvement is welcome.
Thanks in advance!


text:
Q: Printing a ULARGE_INTEGER to a console I would like to print the size of the root volume set by GetDiskFreeSpaceEx(...), but the value it gives me is a ULARGE_INTEGER. What is the best way to go about printing this to a console as a decimal number? I am using plain C and Windows API functions.

A: Going by http://msdn.microsoft.com/en-us/library/windows/desktop/aa383742(v=vs.85).aspx, I'm pretty sure it'd be something like this:
printf("%llu\n", some_ularge_integer.QuadPart);


text:
Q: Using CoreBluetooth to connect to Windows10 with iOS devices Question1.
IOBluetooth can support connection  both ways via LE or classic. However it only supports macOs. CoreBluetooth supports only up to LE along with IOS.
As far as I know, in order for me to connect my bluetooth connection within IOs device, I must use CoreBluetooth frameworks. Am I correct?
Question2.
CoreBluetooth frameworks can connect Windows10 labtop with bluetooth connection?

A: Your question is a bit vague. I assume you just want to have a way to exchange some data between an iOS app and your Windows 10 desktop.

*

*Yes, you are correct. Usage of Bluetooth Classic in any of your iOS apps requires Apple MFI Membership and only makes sense if you have your own product. If you are not a member of the MFI program then you are left with CoreBluetooth (BLE). Please note, that BLE is significantly slower than Bluetooth Classic so it only makes sense for applications that require transmission of small data packets (expect around 4kB/s max).

*Yes, as long as your Windows 10 device supports BLE. If you want to use any of the SIG adopted Profiles such as HID over Gatt you should be able to connect without any additional software. Otherwise you need to implement your own profile. If you want to know more about your options, I suggest you have a look at the CoreBluetooth documentation and/or get a copy of Getting Started with Bluetooth Low Energy which is a comprehensive read on the topic.


text:
Q: Azure Function / Azure Website Custom Deploy Script Ending Prematurely I've got a custom batch deployment script for an Azure Function which is ending prematurely without erroring out. I'm hoping someone can help me understand what is going on.
The problematic portion appears to be in the "Pre-deployment" section of the script:
for /F %%f in ('git.exe diff --name-only %PREVIOUS_SCM_COMMIT_ID% %SCM_COMMIT_ID% ^| grep package.json') do (
    SET PACKAGEJSON=%%~f
    SET PKGFOLDER=!DEPLOYMENT_SOURCE!\!PACKAGEJSON:package.json=!
    echo "NPM Install: !PKGFOLDER!package.json"
    pushd "!PKGFOLDER!"
    npm install --production --progress=false --cache-min=432000
    npm install --save json-loader --progress=false --cache-min=432000
    IF !ERRORLEVEL! NEQ 0 goto error
    popd
)

If a package.json has not been modified between the last two commits, the script skips this section as expected and continues to executing the "Deployment" section.
If a package.json HAS been modified, the code works as expected at first and it runs the npm installs. Afterwards, however, it ends without an error and does not continue on to the deployment section. There is no additional output from the script after the last npm install runs.
Can anyone help me understand what is wrong? This looks correct to me.
The full script is below, and it is a portion of the following project:
https://github.com/securityvoid/.deploy
@if "%SCM_TRACE_LEVEL%" NEQ "4" @echo off
@echo Started: %date% %time%

:: ----------------------
:: KUDU Deployment Script
:: Version: 1.0.12
:: ----------------------

:: Prerequisites
:: -------------

:: Verify node.js installed
where node 2>nul >nul
IF %ERRORLEVEL% NEQ 0 (
  echo Missing node.js executable, please install node.js, if already installed make sure it can be reached from current environment.
  goto error
)

:: Setup
:: -----

setlocal enabledelayedexpansion

SET ARTIFACTS=%~dp0%..\artifacts

IF NOT DEFINED DEPLOYMENT_SOURCE (
  SET DEPLOYMENT_SOURCE=%~dp0%.
)
echo "Deployment Source: %DEPLOYMENT_SOURCE%"

IF NOT DEFINED DEPLOYMENT_DIST (
    SET DEPLOYMENT_DIST=%DEPLOYMENT_SOURCE%\dist
) ELSE (
    ECHO "Deployement Dist already set"
)
echo "Deployment Dist: %DEPLOYMENT_DIST%"

IF NOT DEFINED DEPLOYMENT_TARGET (
  SET DEPLOYMENT_TARGET=%ARTIFACTS%\wwwroot
)
echo "Deployment Target: %DEPLOYMENT_TARGET%"

IF NOT DEFINED NEXT_MANIFEST_PATH (
  SET NEXT_MANIFEST_PATH=%ARTIFACTS%\manifest

  IF NOT DEFINED PREVIOUS_MANIFEST_PATH (
    SET PREVIOUS_MANIFEST_PATH=%ARTIFACTS%\manifest
  )
)

IF NOT DEFINED KUDU_SYNC_CMD (
  :: Install kudu sync
  echo Installing Kudu Sync
  call npm install kudusync -g --silent
  IF !ERRORLEVEL! NEQ 0 goto error

  :: Locally just running "kuduSync" would also work
  SET KUDU_SYNC_CMD=%appdata%\npm\kuduSync.cmd
)

for /F "tokens=5 delims=.\" %%a in ("%PREVIOUS_MANIFEST_PATH%") do SET PREVIOUS_SCM_COMMIT_ID=%%a

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Pre-Deployment
:: ----------
@echo "Initiating Pre-Deployment: %date% %time%"
@echo "Previous Commit: %PREVIOUS_SCM_COMMIT_ID%  Current Commit: %SCM_COMMIT_ID%"
for /F %%f in ('git.exe diff --name-only %PREVIOUS_SCM_COMMIT_ID% %SCM_COMMIT_ID% ^| grep package.json') do (
    SET PACKAGEJSON=%%~f
    SET PKGFOLDER=!DEPLOYMENT_SOURCE!\!PACKAGEJSON:package.json=!
    echo "NPM Install: !PKGFOLDER!package.json"
    pushd "!PKGFOLDER!"
    npm install --production --progress=false --cache-min=432000
    npm install --save json-loader --progress=false --cache-min=432000
    IF !ERRORLEVEL! NEQ 0 goto error
    popd
)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Deployment
:: ----------

@echo "Initiating Deployment: %date% %time%"

:: 1. Build Script
node %DEPLOYMENT_SOURCE%\.deploy\deploy.js

:: 2. KuduSync
IF /I "%IN_PLACE_DEPLOYMENT%" NEQ "1" (
  call :ExecuteCmd "%KUDU_SYNC_CMD%" -v 50 -f "%DEPLOYMENT_DIST%" -t "%DEPLOYMENT_TARGET%" -n "%NEXT_MANIFEST_PATH%" -p "%PREVIOUS_MANIFEST_PATH%" -i ".git;.hg;.deployment;deploy.cmd"
  IF !ERRORLEVEL! NEQ 0 goto error
)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
goto end

:: Execute command routine that will echo out when error
:ExecuteCmd
setlocal
set _CMD_=%*
call %_CMD_%
if "%ERRORLEVEL%" NEQ "0" echo Failed exitCode=%ERRORLEVEL%, command=%_CMD_%
exit /b %ERRORLEVEL%

:error
endlocal
echo An error has occurred during web site deployment.
call :exitSetErrorLevel
call :exitFromFunction 2>nul

:exitSetErrorLevel
exit /b 1

:exitFromFunction
()

:end
endlocal
echo Finished successfully.

A: The source of the problem is that  npm is a batch file. When a batch file (your batch file) invokes another batch file, the execution flow is transferred to the called one, and once it ends its work, the execution flow does not return to the caller.
This behaviour changes if the invocation is done using the call command.
call npm ....

The execution control is transfered to the called batch file and on end the execution flow returns to the caller.
note: The exposed behaviour is a simplification of the undelaying process. Batch files are executed inside a memory "context". Without the call command, the called batch file replaces the caller "context", with the call command, a new "context" is created.
This leaves another question: if the invocation of the batch npm batch file transfer execution flow and it does not return, why the second npm command is executed?
While executing a batch file (or command lines), blocks of code (code enclosed in parenthesis) are loaded into memory and parsed as a whole. Your for command is placed in memory, and all the commands included in its do clause will continue running until the loop ends.
note: Not relevant in in this case, but once the first npm has been invoked (without call) and the caller batch "context" has been discarded (replaced by the called context), the rest of the commands in the for loop are executed (they are still in memory) in command line context and not in batch context, and as the "context" was discarded, the setlocal has been reverted and variable changes, directoy changes and delayed expansion are discarded.


text:
Q: Mosaic Aerial Photography Tiles to a Seamless Raster I've got about 6 different Aerial Photography datasets I am managing at the moment. All of them are made up of tiles covering a large area. Some of these datasets contain up to 2000 tiles. All the tiles are slightly overlapping so there re no gaps in the data. Tiles work fine for me, but other users are requesting Mosaic's of the datasets.
I've been trying over the last few days to Mosaic these tiles into a seamless raster. I've been using the ArcGIS Mosaic to New Raster Tool. It worked great on the first (smallest) dataset, but since then ArcGIS crashes after running for about 8 hours. I've tried the tool on a more power machine and with less tiles, but ArcGIS still keeps crashing.
I'm not sure what else to do here. I need to mosaic these tiles into one raster, but despite any changes to the options I keep getting the same result. I'm wondering if the Moasic to New Raster is the correct tool for this job, or should I be using something else?
I'm looking for a either a ArcGIS or python programming solution to this issue.
The options I am using for the Mosaic to New Raster Tool:

*

*Input: 500 to 2000 input tiles that are JP2

*Output: Save the new raster as a JP2

*Coordinate System: NAD83 17N to NAD83 17N

*Pixel Type: 8 Bit Unsigned to 8 Bit Unsigned

*Cellsize: 0.2 to 0.2 (varies, but the the cellsize stays the same from the input to the output)

*Band: 3 (4 in two dataets)

*Mosaic Method: I've tried pretty much every option here, the preferred is Blend.

*Colourmap: First (I haven't changed this at all yet)

A: I recommend creating a mosaic dataset within a file geodatabase.  There are many advantages of working with this type of data model.  For one, you can modify properties of the dataset once it is created to enhance rendering.  You also have much finer control of how these data are served compared to a stand-alone raster dataset created using mosaic to new raster.
Additional Resources:

*

*What is a mosaic dataset?

*Mosaic dataset properties

*Creating a mosaic dataset

*Adding raster data to a mosaic dataset


text:
Q: Python/Glue - use spark session for entire code (access variables from another class) I want to share entire SparkSession for a code I'm working on by using getOrCreate() method.
I'm stuck with an error when trying to access gc instantiated in Context:
AttributeError: type object 'Context' has no attribute 'gc'

Goal is to have SparkSession isolated into a class and used whenever I would need to rather then packing everything into one. Tried inheritance, calling Context class directly in RDSClient to no avail.
UPDATE
I came up with working solution but still wonder if there is a better way to handle it.
import sys
import re
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
import awsglue
import pyspark
import boto3
import pymssql
import pandas

class Context():
    def __init__(self):
        self.sc = SparkContext()
        self.gc = GlueContext(self.sc.getOrCreate())
        self.spark = self.gc.spark_session

    @staticmethod
    def get_parameters(*args):
        return getResolvedOptions(sys.argv, ["dynamodb_metadata_table"])

class RDSClient(Context):

    def __init__(self, ctx):
        self.gc = ctx.gc

    def rds_frame():
        tbl = self.gc.create_dynamic_frame.from_options(
                    connection_type = "sqlserver",
                    connection_options = {"url": "jdbc:sqlserver://blablabla.rds.amazonaws.com:1433/dwh",
                                            "user": "",
                                            "password": "",
                                            "dbtable": "dbo.tble_name"},
                    transformation_ctx = "glue_df")
        return tbl.printSchema()

def main():

    job = Context()

    args = job.get_parameters()
    metadata = args["dynamodb_metadata_table"]

    RDSClient.rds_frame(job)

if __name__ == "__main__":
    main()

A: Your approach looks good. However, Irrespective how you separate them into classes, its all one script at the end and every Glue job will end up having same code. Kinda boiler plate. If you have 100 scripts, all of them will have this.
If your intention is to modularize the code to make it better for unit testing, i think your code is good enough. If your intention is to have a central library with all the common classes & functions, then i would suggest to package it and add it as library to each Glue script. That way, you can set a standard process to set up the context in Glue jobs.
And, move any common properties to  job parameters, so they wont be exposed in the script. Such as JDBC Url, user name, passwords etc. or by using secret manager for passwords.
These are just my thoughts.


text:
Q: Can I make an app in my language? I've created an app, but I got rejected because of some language problems. What I did was that I've created an app in my own language.
So how can I pass the certification, as it must be possible to create an app to my marketplace in my language? It's content is dynamic so it makes no sence having an english translation. Possible steps:

*

*AssemblyInfo.cs

*
*

*set [assembly: NeutralResourcesLanguageAttribute("no")] (my is "no"/"no-NO")

*Project settings (application)

*
*

*add Your suported cultures (i have 5, Norwegian is hard :P)

*
*

*deselected English

*Select only my marketplace (1, deselect 190 :D)

*Provide Norwegian store description

*Provide English description for the testers

Should make them happy right? If I try to upload the xap now I get the following:
3010: The [NeutralResourceLanguage] attribute is invalid on the entry assembly. Update the assembly and then try again.

So how can I successfully create a app for my own langauge and pass certification, I only want my app available in my marketplace?

A: According to How do I localize for a language that isn't supported? section in following blog poost:
http://blogs.windows.com/windows_phone/b/wpdev/archive/2012/04/02/globalizing-and-localizing-a-windows-phone-app.aspx
You have to set as neutral a language which is a supported by the Store:

Set your neutral language to one of the supported display languages. For example, 'English (United States)'.

In the description section, when uploading to the DevCenter, you  have to write a note in the neutral language saying that the app is actually in an unsupported languate, the description in the language (not supported) of the app and a description in the selected neutral language (supported). I.e. you don't only have to write a description in supported language for testers, but for everyone:

On App Hub, you will be prompted to input metadata and a description for the neutral language you chose (for the above example, you'll be prompted for English). You must include the following three items in the 'Detailed description' field to pass certification:

*

*A note, such as 'The language of this application is [unsupported language name]'. This note must be written in the same language as the neutral language. For example, if you chose 'English (United States)' as your neutral language, the note must be written in English (United States). This note must be the first item in the 'Detailed description' field.

*Your app description, in the same language as the neutral language.

*Your app description, in the unsupported language.


text:
Q: How to use multiple excel files as data source for unit test in C#? I am trying to make a unit test that have data source from multiple excel files, each excel file contains a test case for the same unit test. I would like to put all the excel files in one folder and let the unit test program to iterate through all the excel files.
I have found several methods, like storing all the test cases in a XML file but this method is too tedious as I have to extract all the test cases from the excel files and put it into the same XML file. I hope to get an efficient way to do it. Any suggestions?

A: With the standard testing framework of Visual Studio (MsTest) you're able to bind to datasources using the [DataSource] attribute on your test. By default this includes support for Excel, using the OleDB driver for Excel.
However, this assumes that all your test cases live in the same excel file (since you'd use a simple connection string that opens a file and tab). If you want to grab the cases from multiple files, you'll need to implement your own Data Provider by implementing the namespaces from System.Data the technology behind this hasn't changed much since 2003.
If you're able to consolidate your excel files to a single file with your test cases each on their own row, you'd be able to use the standard DataSource attribute to feed the data into your test.
MsTest always assumes that your data is formatted in a tabular format.


text:
Q: Pass nested object in jquery ajax I want to pass following nested object in ajax using jquery:
{
   "parent_param1" : [
      {
         "sub_param1" : "sub_val1",
         "sub_param2" : "sub_val2"
      },
      {
         "sub_param1" : "sub_val1",
         "sub_param2" : "sub_val2"
      },
      {
         "sub_param1" : "sub_val1",
         "sub_param2" : "sub_val2"
      }
   ],
   "parent_param2" : "par_val2",
   "parent_param3" : "par_val3"
}

I'm trying to pass it like following example:
var url = encodedURL;
var data = 'Above Object';

$.ajax({
    type:'POST',
    url:url,
    dataType:'json',
    data:data,
        success:function(res){
              alert('success');
    },
    error:function(e){
      alert('error');
    }
});

I'm getting runtime error as response. I want to make sure that Is that correct way to pass nested object in AJAX using jQuery?

A: Right now you are just passing an object to the server, without a key. You need to pass the data as a JSON string.
console.log(typeof data); //object
console.log(typeof JSON.stringify(data)); //string

In order to read the data serverside, you need to pass the data as an object literal with a key and a value. Something like this:
data: { dto: JSON.stringify(data) },

On the serverside, you can access the object in different ways, depending on the language.
PHP:
$dto = $_POST['dto'];

ASP.NET:
var dto = HttpContext.Current.Request.Form['dto'];

A: I believe the issue you're having is that you are trying to post the object itself. You'll want to post the value as a string and then decode on the object on the server side. A similar issue here:
jQuery $.post() JSON Object
JQuery post JSON object to a server


text:
Q: How to reload Service-Worker (workbox) without reloading Webpack-Dev-Server? My question is is this possible to force webpack-dev-server to update the service-worker file without manual reloading the whole server? I'm using workbox-webpack-plugin with injectManifest option. It's looking like this:
 new InjectManifest({
  swSrc: './sw-base.js',
  swDest: 'sw.js',
}),

This is sw-base.js
importScripts(
  'https://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-sw.js',
);

workbox.setConfig({ debug: false });

self.skipWaiting();

workbox.routing.registerRoute(
  new RegExp(/\.(png|jpg)/),
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'images',
  }),
);

workbox.precaching.precacheAndRoute(self.__WB_MANIFEST);

When I'm changing the sw-base.js file (for example the cacheName) I have to reload whole webpack-dev-server to apply changes.
So is this possible to make dev-server to auto reload on sw-base.js change?
Thanks from advance :3

A: I'm answering own question but it may help others, who knows.
So most probably, that is not possible using webpack-dev-server.
However you can make a quite effective build for working with workbox and webpack.
Steps:

*

*Don't use webpack-dev-server, instead install a third party server package, "http-server" for example.

*Run your new server scoped on files in "dist/build" folder.

*Run your webpack:build command.
Side note: Don't use the --watch flag, it causes some problems with InjectManifest plugin. You have to manually rebuild your app with command on every update.

For faster development you can enable "update on reload" option in ChromeDevTools/application. It automatically unregisters and registers new service worker on reload.
Cheers


text:
Q: I'm new to Ubuntu and I can't seem to get this Curl command to work. How can I install nodejs 7.x on Ubuntu 16.04? sudo apt-get update&&sudo apt-get dist-upgrade
sudo apt-get install curl
sudo apt-get install python-software-properties
curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -

and the curl command fails when trying to enter, says "bash: -d: command error

A: Solved it, I dunno why but I had to type:
sudo apt-get install -y nodejs
sudo apt-get purge nodejs npm
curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
sudo apt-get install -y nodejs

and that seemed to actually install 4.2, remove it, then install 7.x


text:
Q: Перебор пароля localhost есть простой сайт из html и php
<?php
if(isset($_POST['auto']))
{
$log=$_POST['login'];
$pass=$_POST['password'];
$l="root";
$p="1234";
if($log==$l && $pass==$p)
{
header("location:http://ip/forma.html");
}
else
{
echo "Log non correct";
header("location:http://ip/");
}
}
?>

<!DOCTYPE html>

<meta charset="UTF-8">
<title>Страница авторизации</title>

Форма авторизации

<form action="auto.php" method="post">
Логин:
<input type="text" name="login">

Пароль:
<input type="password" name="password">

<input type="submit" value="Войти" name="auto">
</form>

Как реализовать подбор пароля через простой перебор на python?
При нажатии на кнопку войти, перекидывает на сайт ip/forma.html


text:
Q: Which file is used to retrieve data from a web server into android device I am in a running application where i need to retrieve some dynamically generated files into my android device. Currently i am using general file system which contain string.
In that string i have some images links also, so when i start AsyncTask for those images into android device.
I want to know some suggestion about other best file system that use in android programming. For my technique i got some unfortunately stopped error. SO i need some suggestion.
Thanks in advance.

A: Well, mostly JSON is used due to its super simplicity!
See a sample:
{"nodes":[{"title":"The War","hlsVideo":"http://www.streambox.fr/playlists/test_001/stream.m3u8","videoTumbnail":{"src":"http://aws-autoscale.s3.amazonaws.com/upload/styles/large/s3/war_0.jpg?itok=r73ka-ev","alt":""}},{"title":"Disney Nature","hlsVideo":"http://playertest.longtailvideo.com/adaptive/oceans_aes/oceans_aes.m3u8","videoTumbnail":{"src":"http://aws-autoscale.s3.amazonaws.com/upload/styles/large/s3/disneynature-oceans-trailer.jpg?itok=H9WzMjMh","alt":""}},{"title":"Big Buck Bunny","hlsVideo":"http://184.72.239.149/vod/smil:BigBuckBunny.smil/playlist.m3u8","videoTumbnail":{"src":"http://aws-autoscale.s3.amazonaws.com/upload/styles/large/s3/Big%20Buck%20Bunny.jpg?itok=OYj4s_Et","alt":""}},{"title":"Adventure","hlsVideo":"http://sample.vodobox.net/skate_phantom_flex_4k/skate_phantom_flex_4k.m3u8","videoTumbnail":{"src":"http://aws-autoscale.s3.amazonaws.com/upload/styles/large/s3/adventure.jpg?itok=IDS3aMpN","alt":""}},{"title":"Baby Fun","hlsVideo":"https://s3-eu-west-1.amazonaws.com/aws-autoscale/upload/Babies+Scared+of+Farts+Compilation+2014+%5BNEW+HD%5D/Babies+Scared+of+Farts+Compilation+2014+%5BNEW+HD%5D_master.m3u8","videoTumbnail":{"src":"http://aws-autoscale.s3.amazonaws.com/upload/styles/large/s3/baby_0.jpg?itok=GEnXunhX","alt":""}},{"title":"Apple Talk","hlsVideo":"http://qthttp.apple.com.edgesuite.net/1010qwoeiuryfg/sl.m3u8","videoTumbnail":{"src":"http://aws-autoscale.s3.amazonaws.com/upload/styles/large/s3/steve-jobs-talk.jpg?itok=UiFsfZlX","alt":""}},{"title":"Animals in Wild","hlsVideo":"http://playertest.longtailvideo.com/adaptive/wowzaid3/playlist.m3u8 ","videoTumbnail":{"src":"http://aws-autoscale.s3.amazonaws.com/upload/styles/large/s3/o-BEAVER-facebook.jpg?itok=WP_DOXhC","alt":""}},{"title":"Kitten","hlsVideo":"https://s3-eu-west-1.amazonaws.com/aws-autoscale/upload/CatCats.m3u8","videoTumbnail":{"src":"http://aws-autoscale.s3.amazonaws.com/upload/styles/large/s3/kitten.jpg?itok=E2SjBjFr","alt":""}}]}

In this case I have a Video Thumbnail , description and the URL, I can either use a RecyclerView or ListView to populate the items in Android.  Again it depends upon your specific requirements, using JSON you can dynamically change the items. Hope it helps!


text:
Q: Code Signing Error The company I am working for has a base app that they reskin and sell to different businesses. I have redesigned the app and am trying to upload it to their account but am getting:
[BEROR]Code Sign error: The identity 'iPhone Distribution' doesn't match any
valid certificate/private key pair in the default keychain

How do I add their developer account into my Xcode and acquire a certificate for distribution?
Thank you

A: Basically, you need to have maximum privileges in the Provisioning Portal to do the following, so if you don't, get it, and then do this:

*

*Login and download a developer certificate. If you need to create one, select How To from the menu in the Provisioning Portal under certificates.

*Download a distribution certificate. Again, if you need one, select How To.

*Open both certificates and make sure they open in your Keychain Access

*Select provisioning and download both a developer and distribution .mobileprovision provisioning profile. Create one if necessary using How To

*Make sure you have XCode open and open both .mobileprovisioning profiles. Make sure that they open in the Organizer and show in the status that they are properly linked with a certificate that is valid in the Keychain Access. If they aren't, a flag will pop up, saying something like "There is no valid certificate associated with this profile" in bright red.

*Check your code signing in both the Target and Project areas of your build. Make absolutely sure that both are trying to sign using your distribution profile.

*Make sure that you are building the distribution scheme of your app (You may have to create this).

*Finally set the build device to iOS Device, set the scheme to Distribution, and select Archive. It is imperative that when the program asks you to allow the code signing to use your private key, that you select "Allow" and not "Always Allow," as this is very buggy and often results in code signing errors.
If you need any more help, comment.
Hope this helps!


text:
Q: DoCmd.TransferSpreadsheet Export: Let user choose save destination? I successfully run TransferSpreadsheet to export an Access query to an Excel file at a specified location:
Private Sub cmdExportQuery_Click()
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "trndOTQry", _
"\\company.com\root\share\public\D2S\D2S\D2S_Scorecard\Trend OT.xls"
End Sub

Given that this is a shared file, I want a dialog to open that allows the user to select whatever save destination he chooses.  I found this link with a good solution that references this article.  When I plug this code into my window:
Private Sub cmdExportQuery_Click()
Dim strSaveAsFilter As String
Dim strSaveAsFileName As String
strFilter = ahtAddFilterItem(strSaveAsFilter, "Excel Files (*.xls)", "*.xls")
strSaveAsFileName = ahtCommonFileOpenSave( _
OpenFile:=False, _
Filter:=strSaveAsFilter, _
Flags:=ahtOFN_OVERWRITEPROMPT Or ahtOFN_READONLY)

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "trndOTQry", _
strSaveAsFileName, , "-1", True
End Sub

I get the error Compile Error: Sub or Function not defined, it highlights ahtAddFilterItem in blue, and highlights Private Sub cmdExportQuery_Click() in yellow with a yellow arrow.  I tried making a Public Sub, but nothing happened when I clicked the button.  What must I do to allow the user to choose the save destination when exporting this query to Excel?

A: There is additional code that should have also been included.  Check here:
http://access.mvps.org/access/api/api0001.htm
I also found this which may be helpful from someone else who had the same error:
"Did you also get the additional code mentioned in the NOTE
Note: This code still requires the GetOpenFileName routine provided by Ken
Getz. Make sure you copy the function from this article.
which sends you to
http://www.mvps.org/access/api/api0001.htm"


text:
Q: Problema para login password verify Tengo este codigo, se supone que está bien ya lo revise muchas veces y esta bien hecho. Pero, el password_verify no funciona, he visto que puede ser por el campo de la base de datos MySQL. Es de tipo varchar (255) y utf8mb4_unicode_ci  por si ayuda. ¿Me podrían ayudar con este problema?
$email = $_POST['email'];
$password = $_POST['password'];

try {
    $sql = "SELECT email, password from users where email= :email";
    if($inicio = $base_de_datos->prepare($sql)){
        $inicio->bindParam(':email', $email, PDO::PARAM_STR);
        $inicio->execute();
        $mData=$inicio->fetch(PDO::FETCH_ASSOC);
        $outPut = array(
            'status'=>password_verify($password,$mData['password']),
            'msg'=>'Ok'
        );
    }
    else {
        $outPut=array('status'=>false, 'msg'=>'Error prepare');
    }
}
catch (PDOException $ex) {
    $outPut=array('status'=>false, 'msg'=>$ex->getMessage());
    return $outPut;
}
catch (Exception $ex) {
    header("location: gestion.php?error");
}
var_dump($outPut);


text:
Q: Hive SQL Persist Value in Column across multiple rows until new value ISSUE
I have a table I have organised at HIT level which contains many columns built using the following code, and I wish to understand the number of rows per "task" and the time taken per "task":
Drop table if exists l_o_a.cb_base_table;
Create table l_o_a.cb_base_table as

SELECT
b_date
,cal.year_week_number as year_week_number
              ,cal.day_number as day_number
              ,cal.week_number as week_number
              ,cal.period_number as period_number
              ,cal.quarter_number as quarter_number
              ,cal.year_number as year_number
,deviceid
,sessionid
,pagename
,pagetype
,rowinsession
,basicop.feature
,basicop.component
,pagedata.pageIntent
,b_timestamp
,(case when feature = 'start' then pagetype else NULL end) as task_start
,(case when feature = 'start' then pagename else NULL end) as task_start_detail
,(case when feature = 'start' then rowinsession else NULL end) as task_start_row
,(case when feature = 'start' then b_timestamp else NULL end) as task_start_time
,(case when feature = 'complete' then pagetype else NULL end) as task_complete
,(case when feature = 'complete' then pagename else NULL end) as task_complete_detail
,(case when feature = 'complete' then rowinsession else NULL end) as task_complete_row
,(case when feature = 'complete' then b_timestamp else NULL end) as task_complete_time

FROM u_i.cs_events a

left join lookup.calendar cal on cal.calendar_date = a.b_date

WHERE b_date >= ${FROM_DAY}
and b_date <= ${TO_DAY}

GROUP BY
b_date
,cal.year_week_number
              ,cal.day_number
              ,cal.week_number
              ,cal.period_number
              ,cal.quarter_number
              ,cal.year_number
,deviceid
,sessionid
,pagename
,pagetype
,rowinsession
,basicop.feature
,basicop.component
,pagedata.pageIntent
,b_timestamp

For a user journey they can start multiple "tasks" and complete multiple "tasks" within one session, they do not need to complete all tasks but tasks must be completed sequentially not in tandem.
For all the columns made with case statements - these will populate as NULL unless the row (HIT) in question is a "Start" for those labeled "task_start%" or is a "complete" for those labeled "task_complete%"
I would like to have the below columns to repeat the value from the "start" hit until the next "start" hit to help me directly attribute the specific "start" event with the subsequent "complete" event where applicable and then be able to calculate the time taken and the rows taken to complete the task:
task_start
,task_start_detail
,task_start_row
,task_start_time
Unfortunately task_start or task_start_detail are not necessarily the same as task_complete or task_complete_detail and so i cannot connect them by name or page.
THINGS I HAVE TRIED

*

*The similar issue suggested here

https://community.cloudera.com/t5/Support-Questions/Fill-Null-With-Previous-Row-Values-in-Hive/td-p/136878
I get the following error -

Error while compiling statement: FAILED: SemanticException [Error 10017]: Line 15:56 Both left and right aliases encountered in JOIN 'task_start_row'

SELECT a.*
,c.*
FROM l_o_a.cb_base_table a

LEFT OUTER JOIN (SELECT

b1.task_start
,b1.task_start_detail
,b1.task_start_row as last_start_row
,b1.task_start_time
,min(LAG(b2.task_start_row_2,1)) OVER (Partition by sessionid order by rowinsession) as task_end_row

FROM l_o_a.cb_base_table b1 LEFT OUTER JOIN
l_o_a.cb_base_table b2 ON b1.task_start_row < b2.task_start_row
GROUP BY
b1.task_start
,b1.task_start_detail
,b1.task_start_row
,b1.task_start_time
) c ON a.task_start_row >= c.last_start_row AND (a.task_start_row <= c.task_end_row OR c.task_end_row IS NULL)

WHERE sessionid = "11da809521ad94c772e879fefbaa18830f14f5dd2e157e2606fb2c4c8718591c"

ORDER BY

a.task_start_row

Attempting to use the LAG function to take from the row previous. The number of steps between start and complete can vary so this was not viable.
Grouping by sessionID and then joining the table to a second version of the same table.
This provided some correct answers amongst many wrong ones with no sensible way to sort them.
This also left no "start" events without a "complete" event which is incorrect.
HIT LEVEL DATA EXAMPLE
Below is an image of the data of one session at HIT level so that you can see my start point.
Some data is simplified for privacy reasons
Extracted view of Hit level data for 1 specific session. This is what is exposed from the first query when limited to 1 specific session
HIT LEVEL DATA END GOAL EXAMPLE
Below is an image of what I am trying to get to at a hit level for the same session and dataset as the above image.
This is what I want to get to


text:
Q: Push Notification in Laravel 4 I am using Laravel 4 and I have a push notification system .
I had research and found a library support to :
https://github.com/davibennun/laravel-push-notification
I have configured as guide and when I run my routes as below :
Route::get('/push',function(){
$push = new \Davibennun\LaravelPushNotification\PushNotification();
$push->app('appNameAndroid')->to('My-device-token')->sent('my message'); }

It displayed an error :

Zend \ Http \ Client \ Adapter \ Exception \ RuntimeException
  Unable to enable crypto on TCP connection android.googleapis.com: make sure the "sslcafile" or "sslcapath" option are properly set for the environment.

I thought the cause is my openssl problem (I am using LAMP in Ubuntu ) and try to all way I found on internet , even I also tried to run that script on Windows (XAMPP) and it's still not works .
any ideal ?
Update:
I had to go to vendor/zendframework/zend-http/Zend/Http/Client/Adapter/Socket.php and change its config['sslverifypeer'] to "null" and it's worked ! And it's only in local server, in live server , default setting could run perfectly !


text:
Q: Duda con moment.js Tengo una duda respecto al uso de moment.js , la cuestión es, si yo hoy pongo una fecha y hora por ejemplo 14/03/2018 a la 01:00, tengo por costumbre guardar la hora UTC en base de datos para luego formatearla a la fecha/hora que corresponda dependiendo de la región del cliente (de ahí el uso de moment), hasta aquí bien, pero tengo un problema, el cual es, en lugar de ser hoy, por ejemplo lo pongo en agosto (que hay un horario distinto) pues no veo bien la hora, hasta que no tenga ese tipo de horario, cambia de +1 a +2 horas dependiendo de la época del año.
Entonces mi pregunta es, si yo quiero fijar una fecha hora, por ejemplo 14/08/2018 a la 1, quiero ver la 1, esté en marzo o en agosto, pero no entiendo muy bien como se ha de hacer esto.
Espero cualquier ayuda, gracias.

A: No se como es que haces el cambio de hora utc a local time pero esto se hace con el time zone, no se si moment.js hace esto de manera interna porque no lo he usado pero siempre puedes hacerlo tu mismo con el objeto date de javascript:
var d = new Date();
var n = d.getTimezoneOffset(); // te entrega el offset en minutos (+2 = 120)

Ahora el timezone sabe cuando es el cambio de hora, si le preguntas el offset el 13 de agosto a las 23:59 te dirá por ejemplo +1 (60) y si lo haces el 14 de agosto a las 00:00 te dirá +2 (120).
Espero esto te sirva, saludos.

A: El problema radica que al hacer hacer el formato con moment toma como default el timezone de Estados Unidos, entonces cambia el horario. Para evitar eso, es cuestión de cambiar el timezone de moment.js agregando la librería de moment-timezone.
Por ejemplo:
moment.tz("2014-06-01 12:00", "Europe/London");
// Europe/London: 2014-06-01T12:00:00-04:00
moment.tz("2014-06-01 12:00", "America/New_York");
// America/New_York: 2014-06-01T17:00:00+01:00


text: Q: why shortest distance between two lines is always perpendicular to both the lines I m new to vectors and lines. I m confused why the shortest distance between two skew lines is always perpendicular between the two lines


text:
Q: Open single popup on table row click I am stuck in a issue,
I have created one custom table, in each td of table row it has a action button,
onclick() of action it open a small menu.
But it never closes the pervious open menu, in-fact open multiple menu.
How to close previous and open only one menu.

A: Here is the code, which may help you:
import React, { useRef, useEffect, useState } from "react";

export default function App() {
  const clickOutside = useRef(null);
  const [showHideMenu, setShowHideMenu] = useState(false);

  const handleClickOutside = (event, ref) => {
    if (ref.current && !ref.current.contains(event.target)) {
      if (showHideMenu) setShowHideMenu(!showHideMenu);
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", (event) =>
      handleClickOutside(event, clickOutside)
    );
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  });
  return (

Hello CodeSandbox

      <button onClick={() => setShowHideMenu(!showHideMenu)}>Show Hide</button>
      <button onClick={() => setShowHideMenu(!showHideMenu)}>Show Hide</button>
      <button onClick={() => setShowHideMenu(!showHideMenu)}>Show Hide</button>

{showHideMenu ? "show" : "hide"}

  );
}

Actually, this code works as you want. Whenever you click outside of your button, it'll automatically close all other popups.
Here is the code sandbox:


text:
Q: Angular2 composure I'm looking into microservices and to be more exact Angular2 microservices. The main idea seems easy enough but it gets complicated as I want to make a composure of different Angular2 apps.
What I mean by this, imagine I have 2 apps which I don't have a lot of control over, app A and app B, created by different teams, each one serving a different thing (one might be a 2D viewer, the other a 3D viewer). I was thinking of building some kind of composition proxy in which I define a html file with some custom tags such as <service target = "url"> and then have the proxy make a composition and serve it to the user.
I've been researching the web for a while now and I can't seem to find anything on angular2 compositions. Here are a few of the problems I encountered :

*

*The order of the included scripts. Since each app might require different scripts to be included, not including them in the right order might crash the entire app.

*Building a totally new "core" component that is properly bootstrapped, having only the right components being bootstrapped and all that.

*Making sure css from one app doesn't overwrite css from the other

*Naming issues, since apps are different I might encounter components with the same name.
All those issues seem fixable to me by just parsing every file and modifying it accordingly. Problem is the same idea won't exactly work if the js files are both minified and unified. Also it would take a lot of processing power to do this for every request (I'd like it to be a bit hot-builded/loaded).
What are some ways I should go about building such a composition proxy and is there any examples/documentation on how to do this?

A: I am not sure I understand what you want to do but I can see from your requirement all you need is out of the box Angular2 functionality.

1) The order of the included scripts. Since each app might require
  different scripts to be included, not including them in the right
  order might crash the entire app.
2) Building a totally new "core"
  component that is properly bootstrapped, having only the right
  components being bootstrapped and all that.
3) Making sure css from one
  app doesn't overwrite css from the other Naming issues, since apps are
  different I might encounter components with the same name

I'll answer to your points:
1) You just use dynamic module loading in you "app-routing", like the following:
export function loadModuleA() {
    return System.import('./pages/module-A-view/a.module').then(mod => mod.ModuleA)
}

export function loadModuleB() {
    return System.import('./pages/module-B-view/a.module').then(mod => mod.ModuleA)
}

export const routes: Routes = [
    {
        path: 'core/sectionA',
        loadChildren: loadModuleA
    },
     {
        path: 'core/sectionB',
        loadChildren: loadModuleB
    },

If you import a library in ModuleA is not going to be available in ModuleB unless you explicitly export it each module A and module B will have their own dependencies
2) you specify your "core" as you main app.module.tsand module dependencies in their own module file, simple.
3) you only need a main stylesheet really, then every component can have their custom files. If you use angular cli, for example every time you create a new component, the cli will generate the component file, the scss file, the html file and the spec file. Otherwise you can just as easily do it yourself:
@Component({
    selector: 'whatever',
    templateUrl: './whatever.component.html',
    styleUrls: [ './whatever.component.scss' ]
})
export class WhateverComponent

If you instead wanted a StyleSheet specific to all components of (let's say) Module A, then I don't know how to do that.


text:
Q: Should TextureRegions in an atlas be power of 2? It is my understanding that images should be power of 2 for optimization with the GPU. However, if I'm packing my textures into a sheet for libGDX, can the atlas be a power of 2 and NOT the actual regions? Or should the atlas sheet be a power of 2 and each Texture Region also be a power of 2.

A: I understand that it's not. As far as I know the reason for the need of POT (power of two) textures is for optimizations things like mipmapping, anisotropic filtering, etc. So when you pack many images in one texture then you upload that entire texture to the GPU, so the GPU can perform the desired optimizations for all the texture. The atlas is like an index to lookup for certain sectors (or "pieces") of your texture (texture regions), so you can retrieve the desired regions easily. Those regions don't need to be POW, because the GPU already perform optimizations for the entire set (the entire texture). I think that you should ask these type of questions in the game dev community, so you will have a deeper response.


text:
Q: Does .NET Core 3 support TLS 1.3 I am using .NET Core 3.0 to make a proxy which support only TLS 1.3, I saw that Tls13 = 12288 is defined in SslProtocols. But during my test it only throws exception "The client and server cannot communicate, because they do not possess a common algorithm".
So my question is whether .NET Core 3.0 supports TLS 1.3 now?
I am using visual studio professional 2019 version 16.3.0 preview 3.0, my project is netcore3.0
Tls13 is defined in SslProtocols

//
// Summary:
//     Defines the possible versions of System.Security.Authentication.SslProtocols.
[Flags]
public enum SslProtocols {
    //
    // Summary:
    //     Allows the operating system to choose the best protocol to use, and to block
    //     protocols that are not secure. Unless your app has a specific reason not to,
    //     you should use this field.
    None = 0,
    //
    // Summary:
    //     Specifies the SSL 2.0 protocol. SSL 2.0 has been superseded by the TLS protocol
    //     and is provided for backward compatibility only.
    Ssl2 = 12,
    //
    // Summary:
    //     Specifies the SSL 3.0 protocol. SSL 3.0 has been superseded by the TLS protocol
    //     and is provided for backward compatibility only.
    Ssl3 = 48,
    //
    // Summary:
    //     Specifies the TLS 1.0 security protocol. The TLS protocol is defined in IETF
    //     RFC 2246.
    Tls = 192,
    //
    // Summary:
    //     Use None instead of Default. Default permits only the Secure Sockets Layer (SSL)
    //     3.0 or Transport Layer Security (TLS) 1.0 protocols to be negotiated, and those
    //     options are now considered obsolete. Consequently, Default is not allowed in
    //     many organizations. Despite the name of this field, System.Net.Security.SslStream
    //     does not use it as a default except under special circumstances.
    Default = 240,
    //
    // Summary:
    //     Specifies the TLS 1.1 security protocol. The TLS protocol is defined in IETF
    //     RFC 4346.
    Tls11 = 768,
    //
    // Summary:
    //     Specifies the TLS 1.2 security protocol. The TLS protocol is defined in IETF
    //     RFC 5246.
    Tls12 = 3072,
    //
    // Summary:
    //     Specifies the TLS 1.3 security protocol. The TLS protocol is defined in IETF
    //     RFC 8446.
    Tls13 = 12288
}

A: Google is your friend:
https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0

TLS 1.3 & OpenSSL 1.1.1 on Linux .NET Core now takes advantage of TLS
  1.3 support in OpenSSL 1.1.1, when it's available in a given environment. With TLS 1.3:
Connection times are improved with reduced round trips required
  between the client and server. Improved security because of the
  removal of various obsolete and insecure cryptographic algorithms.
  When available, .NET Core 3.0 uses OpenSSL 1.1.1, OpenSSL 1.1.0, or
  OpenSSL 1.0.2 on a Linux system. When OpenSSL 1.1.1 is available, both
  System.Net.Security.SslStream and System.Net.Http.HttpClient types
  will use TLS 1.3 (assuming both the client and server support TLS
  1.3).


text:
Q: Screen inside conda environment doesn't use python PATH I have a conda environment that is running python 3.10.5. It works on the terminal without screen. First I did
conda deactivate

And conda info at this step shows:
     active environment : base
    active env location : /home/myuser/anaconda3
            shell level : 1
       user config file : /home/myuser/.condarc
 populated config files :
          conda version : 4.13.0
    conda-build version : 3.21.8
         python version : 3.9.12.final.0
       virtual packages : __cuda=10.2=0
                          __linux=5.4.0=0
                          __glibc=2.27=0
                          __unix=0=0
                          __archspec=1=x86_64
       base environment : /home/myuser/anaconda3  (writable)
      conda av data dir : /home/myuser/anaconda3/etc/conda
  conda av metadata url : None
           channel URLs : https://repo.anaconda.com/pkgs/main/linux-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/linux-64
                          https://repo.anaconda.com/pkgs/r/noarch
          package cache : /home/myuser/anaconda3/pkgs
                          /home/myuser/.conda/pkgs
       envs directories : /home/myuser/anaconda3/envs
                          /home/myuser/.conda/envs
               platform : linux-64
             user-agent : conda/4.13.0 requests/2.27.1 CPython/3.9.12 Linux/5.4.0-109-generic ubuntu/18.04.6 glibc/2.27
                UID:GID : 1001272705:1000000513
             netrc file : None
           offline mode : False

then I did
screen -S scren_name

and the conda info at this step is
     active environment : base
    active env location : /home/myuser/anaconda3
            shell level : 1
       user config file : /home/myuser/.condarc
 populated config files :
          conda version : 4.13.0
    conda-build version : 3.21.8
         python version : 3.9.12.final.0
       virtual packages : __cuda=10.2=0
                          __linux=5.4.0=0
                          __glibc=2.27=0
                          __unix=0=0
                          __archspec=1=x86_64
       base environment : /home/myuser/anaconda3  (writable)
      conda av data dir : /home/myuser/anaconda3/etc/conda
  conda av metadata url : None
           channel URLs : https://repo.anaconda.com/pkgs/main/linux-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/linux-64
                          https://repo.anaconda.com/pkgs/r/noarch
          package cache : /home/myuser/anaconda3/pkgs
                          /home/myuser/.conda/pkgs
       envs directories : /home/myuser/anaconda3/envs
                          /home/myuser/.conda/envs
               platform : linux-64
             user-agent : conda/4.13.0 requests/2.27.1 CPython/3.9.12 Linux/5.4.0-109-generic ubuntu/18.04.6 glibc/2.27
                UID:GID : 1001272705:1000000513
             netrc file : None
           offline mode : False

then I activated the environment in screen. Now conda info says
     active environment : catvehicle
    active env location : /home/myuser/anaconda3/envs/catvehicle
            shell level : 2
       user config file : /home/myuser/.condarc
 populated config files :
          conda version : 4.13.0
    conda-build version : 3.21.8
         python version : 3.9.12.final.0
       virtual packages : __cuda=10.2=0
                          __linux=5.4.0=0
                          __glibc=2.27=0
                          __unix=0=0
                          __archspec=1=x86_64
       base environment : /home/myuser/anaconda3  (writable)
      conda av data dir : /home/myuser/anaconda3/etc/conda
  conda av metadata url : None
           channel URLs : https://repo.anaconda.com/pkgs/main/linux-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/linux-64
                          https://repo.anaconda.com/pkgs/r/noarch
          package cache : /home/myuser/anaconda3/pkgs
                          /home/myuser/.conda/pkgs
       envs directories : /home/myuser/anaconda3/envs
                          /home/myuser/.conda/envs
               platform : linux-64
             user-agent : conda/4.13.0 requests/2.27.1 CPython/3.9.12 Linux/5.4.0-109-generic ubuntu/18.04.6 glibc/2.27
                UID:GID : 1001272705:1000000513
             netrc file : None
           offline mode : False

However, when I write python in screen, the version shown is the default Ubuntu 18.04 included python which is 2.7, and not the 3.10.5 version that was part of my conda env.
how can I fix this, or make it use the proper python?

A: Edit: as mentioned by other users, setting an alias is not recommended. I was able to fix it by:

*

*Entering screen

*Writing conda deactivate until the (base) environment was no longer activated either.

*Writing conda activate my_env to activate.

Now the python path is correct.


text:
Q: Altering an embedded TrueType font so it will be usable by Windows GDI I am trying to render PDF content to a GDI device context (a 24bit bitmap to be exact). Parsing the PDF stream into PDF objects and rendering the PDF commands from the content dictionary works well, including font rendering.
Embedded fonts are decompressed from their FontFile streams and "loaded" using AddFontMemResourceEx. Now some embedded fonts remove some TrueType tables that are needed by GDI, like the 'name' table.  Because of this, I tried to modify the font by parsing the TrueType subset font into it's tables and modify those tables that have data missing / missing tables are regenerated with as correct information as possible.
I use the Microsoft Font Validator tool to see how "correct" the generated font is. I still get a few errors, like for the maxp table the max values are usually too large (it is a subset) or the xAvgCharWidth field does not equal the calculated value of the 'OS/2' table is not correct but this does not stop other embedded fonts to be useable. The fonts embedded using PDFCreator are the ones that are problematic.
Questions:

*

*How can I determine what I need to
change to the font file in order for
GDI to be able to use it?

*Are there any other font validation
tools that might give me insight
into what is still wrong with the
fontfile?

If needed: I can make an original fontfile and an altered fontfile available for download somewhere.
What modifications are made so far:

*

*Make sure there is a 'head', 'hhea', 'maxp' and 'OS/2' section.

*If we have a symbol font, clear out Panose and Unicode fields in the 'OS/2' section

*Fill in correct values for WInAscent/Desc and TypoAsc/Desc if they we're zero.

*Fill in acceptable values for super/subscript/underline positions and sizes.

*Scan all glyphs that are left en fill in X/Y min/max values in head.

*Rebuild the name section with information from the PDF file it came from.

A: Almost a year late, but I found the answer:
The font kind (symbol or not) should be the same for the 'cmap' table and the 'name' table. So if the cmap has a 3,0,4 cmap (MS, symbol, segment delta coding) and the name table contains 3,1,$0409 (MS, Unicode, enUS) entries, the font will not load.
It looks like the presence of a 'symbol cmap' determines if the font is considered a symbol font by Windows; flags in 'OS/2' don't seem to matter.
So if a font seems correct using 'Microsoft Font Validator', check if the symbol/unicode fields line up in the 'cmap' and 'name' tables.

A: With AddMemoryFont in GDI+ you can check it's Status for any errors in the memory font, like NotTrueTypeFont for example.
One option for GDI may be to try to load the embedded font into a document/form yourself with TTLoadEmbeddedFont and then check any errors returned from the error messages. The only functions that supply more information than this one are CreateFontPackage/MergeFontPackage, and their error codes, but I do fail to see how they can be used in your situation.
Barring all this, have you had a chance to review PDFCreator's source code (assuming you're using the open source one as opposed to the commercial one)?


text:
Q: validate on field blur using jquery validate plugin I need jquery validate plugin to validate all my fields on blur of the fields. Currently its validating only on submit of the form. How can I achieve this?
HTML
<input class=" required minlength " type="text" id="firstName" name="firstName" minlength="3" maxlength="40"  />

Jquery
$(document).ready(function() {
form = $('#submitForm');
if (form.length) {
  form.validate({
    ignoreTitle: false,
    onfocusout: false,
    onkeyup: false,
    onclick: false,
    submitHandler: function() {
      form[0].submit();
    },
    messages: {
        firstName:{
            required: "First Name is required.",
            minlength: "First Name entered is invalid.",
        }
    }
    });

});

A: Try this one
$('form').find('input,select,textarea').on('blur', function() {
    $(this).validate({
        ignoreTitle: false,
        onfocusout: false,
        onkeyup: false,
        onclick: false,
        messages: {
            firstName:{
                required: $(this).attr('name')+" is required.",
                minlength: $(this).attr('name')+" entered is invalid.",
            }
        }
    })
});


text:
Q: Question on Portfolio Risk & Covariance Good evening,
I was reading a stats textbook where I came across the following statement:

In order to reduce the portfolio risk of a portfolio involving two risky investments, we should choose their covariance to be negative, rather than positive

I don't really get what it means. From what I understand:

Cov = 0, the variables are not related
Cov = 0 to 1, the if the value of one variable increases, so will the other
Cov = -1 to 0, the if the value of one variable increases, the other will decrease

Am I right to then say that why having a negative covariance will reduce risk is because when one investment falls, the other will react to counter? So in such cases, the profits will be always minimal but safe.
In contrast, if the investments are positively correlated, then the portfolio will be highly risky, but highly profitable if one makes a profit.

A: $\newcommand{\E}{\mathrm{E}}$
$\newcommand{\Var}{\mathrm{Var}}$
$\newcommand{\Cov}{\mathrm{Cov}}$
 Consider a portfolio, $P_{i} = w_{i1}*X_{i} + w_{i2}*Y_{i}$. For a given expected return, $\E[P_i] = \E[X_i] + \E[Y_i]$, we want to construct the portfolio in a manner which minimizes the overall volatility (risk), which is typically measured in terms of standard deviation. Equivalently, we can use the variance as a measurement of risk, since it is just volatility squared. Then, the overall variance of our portfolio is:
$$
\Var[P_i] = w_{i1}^{2}*\Var[X_i] + w_{i2}^{2}*\Var[Y_i] + 2*\Cov[X_{i},Y_{i}]*w_{i1}*w_{i2}
$$
So, for a given expected return, we choose a combination of assets $X_{i}$ and $Y_{i}$ which minimizes $\Var[P_{i}]$, i.e. $\Cov[X_{i},Y_{i}] < 0$.


text: Q: Force app to go to initial pin screen or restart phone on Android 4.0 and above Is there a way to do that? It seems that reboot and shutdown permissions are ignored, because they are only related to system code.


text:
Q: Issue in MVC routing when GETing integer parameter I'm at a loss for why this routing issue is occurring.
Route in Global.asax.cs file:
routes.MapRoute(
    "Archives", //Route name
    "{controller}/{action}/{month}", // URL with parameters
    new { controller = "Articles", action = "Archives" },
    new { month = @"^\d+" } // Parameter.defaults
);

Controller:
public ActionResult Archives(int month)
{
    ViewData["month"] = month;
    return View(article);
}

Which keeps throwing the error:

The parameters dictionary contains a null entry for parameter 'month' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Archives(Int32)'
  in 'AppleWeb.Controllers.ArticlesController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
  Parameter name: parameters

Which is bogus because the URL is: http://localhost:64529/Articles/Archives/12
EDIT- Full routing for all to see:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    //routes.IgnoreRoute("tellerSurvey.htm/{*pathInfo}");routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Appleweb", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

    routes.MapRoute(
        "Contact", //Route name
        "{controller}/{action}/{page}", //URL with parameters
        new { controller = "Appleweb", action = "Contact", page = UrlParameter.Optional } // Paramter defaults
    );

    routes.MapRoute(
        "FormDetails", //Route name
        "{controller}/{action}/{formid}", // URL with parameters
        new { controller = "Resources", action = "FormDetails", formid = 0}
    );

    routes.MapRoute(
        "_calc",
        "{controller}/{action}/{calcid}", // URL with parameters
        new { controller = "Resources", action = "Calc", calcid = UrlParameter.Optional } // Parameter defaults
    );

    routes.MapRoute(
        "Article", //Route name
        "{controller}/{action}/{articleid}", // URL with parameters
        new { controller = "Articles", action = "Article", id = 0 } // Parameter.defaults
    );}

This is an MVC 3 project, so no routingconfig.cs.

A: Your route has not given a default value for the month and the action method has a non nullable parameter (int month).
Change your route map to:
 routes.MapRoute(
       "Archives",
       "{controller}/{action}/{month}",
       new { controller = "Articles", action = "Archives",
                       month = UrlParameter.Optional }
   );

Or action method to accept nullable int for the month parameter:
public ActionResult Archives(int? month) //nullable int
{
    ViewData["month"] = month;
    return View(article);
}

A: Here is the problem:
The URL http://localhost:64529/Articles/Archives/12 matches the other routes. It will match the Default, Contact, etc routes.
Edit
Simplest solution
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Archives",
        "{controller}/{action}/{month}",
        new { controller = "Articles", action = "Archives" },
        new { month = @"\d+"}
    );

    //short-circuit for all URLs where the month is not numeric
    //Warning: the 404 will not be handled in <customErrors>
    //Its handled in <httpErrors>
    routes.IgnoreRoute("Articles/Archives/{month}");

    //place all other routes here

Other possibilities
1) replace {controller} with the hard-coded controller name so that /Articles won't match the route. Sample:
    routes.MapRoute(
        "Contact",
        "Appleweb/{action}/{page}",
        new { controller = "Appleweb", action = "Contact", page = UrlParameter.Optional }
    );

Only match URLs that start with /Appleweb
2) use constraint
    routes.MapRoute(
        "Archives", //Route name
        "Appleweb/{action}/{page}",
        new { controller = "Appleweb", action = "Contact", page = UrlParameter.Optional },
        new { controller = "^(?!articles$).*$" } //don't match articles
    );

or
    routes.MapRoute(
        "Archives", //Route name
        "Appleweb/{action}/{page}",
        new { controller = "Appleweb", action = "Contact", page = UrlParameter.Optional },
        new { controller = "appleweb|resources" } //only allow appleweb and resources
    );

3) make the URL of archive unique like http://XXXX/Archives/12
   routes.MapRoute(
        "Archives",
        "Archives/{month}",
        new { controller = "Articles", action = "Archives" },
        new { month = @"\d+" }
   );


text:
Q: Is there a way to use distributed training with DASK using my GPU? As of now, lightGBM model supports GPU training and distributed training (using DASK).
If it is possible, how can I use distributed training with DASK using my GPU or is there any other way to do so?
Actually my task is to use the power of GPU and distributed training in lightGBM model.

It may possible I am missing a concept because I'm a beginner.

A: I'm not a LightGBM expert, so it might be better to wait for some to chime in. But from what I've been able to find, lightGBM does not really work with both Dask and GPU support.
See https://github.com/microsoft/LightGBM/issues/4761#issuecomment-956358341:

Right now the dask interface doesn't directly support distributed training using GPU, you can subscribe to #3776 if you're interested in that. Are you getting any warnings about this? I think it probably isn't using the GPU at all.

Furthermore, if your data fits in a single machine then it's probably best not using distributed training at all. The dask interface is there to help you train a model on data that doesn't fit on a single machine by having partitions of the data on different machines which communicate with each other, which adds some overhead compared to single-node training.

And https://github.com/microsoft/LightGBM/issues/3776:

The Dask interface in https://github.com/microsoft/LightGBM/blob/706f2af7badc26f6ec68729469ec6ec79a66d802/python-package/lightgbm/dask.py currently only supports CPU-based training.

Anyway, if you have only one GPU, Dask shouldn't be of much help.


text:
Q: Enabling STARTTLS for all on Postfix with Zarafa I ran into a problem which I just cannot solve with just googling it - I need some expert help.
My company runs it's own mailserver (postfix with zarafa groupware). We're an insurance company so we often receive mails with personal information which should not be read by others. So one of our partners only wants to send them encrypted, which is total reasonable. But it just doens't seem to work for external users. I really don't know how to explain that, but I'll try:
They did a check on our mailserver via:
openssl s_client -host mx01.cevo.de -port 25 -starttls smtp -debug

Which failes with this output:
CONNECTED(00000003)
read from 0xec56b0 [0xec57e0] (4096 bytes => 38 (0x26))
0000 - 32 32 30 20 6d 78 30 31-2e 63 65 76 6f 2e 64 65   220 mx01.cevo.de
0010 - 20 45 53 4d 54 50 20 53-65 72 76 69 63 65 20 72    ESMTP Service r
0020 - 65 61 64 79 0d 0a                                 eady..
write to 0xec56b0 [0xec67f0] (25 bytes => 25 (0x19))
0000 - 45 48 4c 4f 20 6f 70 65-6e 73 73 6c 2e 63 6c 69   EHLO openssl.cli
0010 - 65 6e 74 2e 6e 65 74 0d-0a                        ent.net..
read from 0xec56b0 [0xec57e0] (4096 bytes => 94 (0x5E))
0000 - 32 35 30 2d 52 65 71 75-65 73 74 65 64 20 6d 61   250-Requested ma
0010 - 69 6c 20 61 63 74 69 6f-6e 20 6f 6b 61 79 2c 20   il action okay,
0020 - 63 6f 6d 70 6c 65 74 65-64 0d 0a 32 35 30 2d 53   completed..250-S
0030 - 49 5a 45 20 32 30 34 38-30 30 30 30 0d 0a 32 35   IZE 20480000..25
0040 - 30 2d 45 54 52 4e 0d 0a-32 35 30 2d 38 42 49 54   0-ETRN..250-8BIT
0050 - 4d 49 4d 45 0d 0a 32 35-30 20 4f 4b 0d 0a         MIME..250 OK..
didn't found starttls in server response, try anyway...
write to 0xec56b0 [0x7fffd07d4ae0] (10 bytes => 10 (0xA))
0000 - 53 54 41 52 54 54 4c 53-0d 0a                     STARTTLS..
read from 0xec56b0 [0xeb79b0] (8192 bytes => 30 (0x1E))
0000 - 35 30 33 20 42 61 64 20-73 65 71 75 65 6e 63 65   503 Bad sequence
0010 - 20 6f 66 20 63 6f 6d 6d-61 6e 64 73 0d 0a          of commands..
write to 0xec56b0 [0xec5730] (317 bytes => 317 (0x13D))
0000 - 16 03 01 01 38 01 00 01-34 03 03 94 e2 69 f3 8f   ....8...4....i..
0010 - cb a4 fd 61 49 3f 15 c4-5d a2 3f ca 4e f0 a9 eb   ...aI?..].?.N...
0020 - 71 72 6b ce 65 00 b9 0c-e1 ee 9f 00 00 9e c0 30   qrk.e..........0
0030 - c0 2c c0 28 c0 24 c0 14-c0 0a c0 22 c0 21 00 a3   .,.(.$.....".!..
0040 - 00 9f 00 6b 00 6a 00 39-00 38 00 88 00 87 c0 32   ...k.j.9.8.....2
0050 - c0 2e c0 2a c0 26 c0 0f-c0 05 00 9d 00 3d 00 35   ...*.&.......=.5
0060 - 00 84 c0 12 c0 08 c0 1c-c0 1b 00 16 00 13 c0 0d   ................
0070 - c0 03 00 0a c0 2f c0 2b-c0 27 c0 23 c0 13 c0 09   ...../.+.'.#....
0080 - c0 1f c0 1e 00 a2 00 9e-00 67 00 40 00 33 00 32   .........g.@.3.2
0090 - 00 9a 00 99 00 45 00 44-c0 31 c0 2d c0 29 c0 25   .....E.D.1.-.).%
00a0 - c0 0e c0 04 00 9c 00 3c-00 2f 00 96 00 41 c0 11   .......<./...A..
00b0 - c0 07 c0 0c c0 02 00 05-00 04 00 15 00 12 00 09   ................
00c0 - 00 14 00 11 00 08 00 06-00 03 00 ff 01 00 00 6d   ...............m
00d0 - 00 0b 00 04 03 00 01 02-00 0a 00 34 00 32 00 0e   ...........4.2..
00e0 - 00 0d 00 19 00 0b 00 0c-00 18 00 09 00 0a 00 16   ................
00f0 - 00 17 00 08 00 06 00 07-00 14 00 15 00 04 00 05   ................
0100 - 00 12 00 13 00 01 00 02-00 03 00 0f 00 10 00 11   ................
0110 - 00 23 00 00 00 0d 00 20-00 1e 06 01 06 02 06 03   .#..... ........
0120 - 05 01 05 02 05 03 04 01-04 02 04 03 03 01 03 02   ................
0130 - 03 03 02 01 02 02 02 03-00 0f 00 01 01            .............
^Tread from 0xec56b0 [0xecac90] (7 bytes => 7 (0x7))
0000 - 34 32 31 20 53 4d 54                              421 SMT
139855938602656:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:787:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 169 bytes and written 352 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
---

Here's the log entry from mail.log for that request:
Jan 21 15:09:58 mx01 postfix/smtpd[1401]: connect from ec2-52-31-143-162.eu-west-1.compute.amazonaws.com[52.31.143.162]
Jan 21 15:10:10 mx01 postfix/smtpd[1401]: lost connection after EHLO from ec2-52-31-143-162.eu-west-1.compute.amazonaws.com[52.31.143.162]
Jan 21 15:10:10 mx01 postfix/smtpd[1401]: disconnect from ec2-52-31-143-162.eu-west-1.compute.amazonaws.com[52.31.143.162]

So I tried it from my laptop at work with the same command and it worked without any problem:
CONNECTED(00000003)
read from 0xbdef20 [0xbdf020] (4096 bytes => 32 (0x20))
0000 - 32 32 30 20 6d 78 30 31-2e 63 65 76 6f 2e 64 65   220 mx01.cevo.de
0010 - 20 45 53 4d 54 50 20 50-6f 73 74 66 69 78 0d 0a    ESMTP Postfix..
write to 0xbdef20 [0xbe0030] (25 bytes => 25 (0x19))
0000 - 45 48 4c 4f 20 6f 70 65-6e 73 73 6c 2e 63 6c 69   EHLO openssl.cli
0010 - 65 6e 74 2e 6e 65 74 0d-0a                        ent.net..
read from 0xbdef20 [0xbdf020] (4096 bytes => 138 (0x8A))
0000 - 32 35 30 2d 6d 78 30 31-2e 63 65 76 6f 2e 6c 6f   250-mx01.cevo.lo
0010 - 63 61 6c 0d 0a 32 35 30-2d 50 49 50 45 4c 49 4e   cal..250-PIPELIN
0020 - 49 4e 47 0d 0a 32 35 30-2d 53 49 5a 45 20 32 30   ING..250-SIZE 20
0030 - 39 37 31 35 32 30 0d 0a-32 35 30 2d 56 52 46 59   971520..250-VRFY
0040 - 0d 0a 32 35 30 2d 45 54-52 4e 0d 0a 32 35 30 2d   ..250-ETRN..250-
0050 - 53 54 41 52 54 54 4c 53-0d 0a 32 35 30 2d 45 4e   STARTTLS..250-EN
0060 - 48 41 4e 43 45 44 53 54-41 54 55 53 43 4f 44 45   HANCEDSTATUSCODE
0070 - 53 0d 0a 32 35 30 2d 38-42 49 54 4d 49 4d 45 0d   S..250-8BITMIME.
0080 - 0a 32 35 30 20 44 53 4e-0d 0a                     .250 DSN..
write to 0xbdef20 [0x7ffdc4723d90] (10 bytes => 10 (0xA))
0000 - 53 54 41 52 54 54 4c 53-0d 0a                     STARTTLS..
read from 0xbdef20 [0xad1c10] (8192 bytes => 30 (0x1E))
0000 - 32 32 30 20 32 2e 30 2e-30 20 52 65 61 64 79 20   220 2.0.0 Ready
0010 - 74 6f 20 73 74 61 72 74-20 54 4c 53 0d 0a         to start TLS..
write to 0xbdef20 [0xbdefa0] (318 bytes => 318 (0x13E))
...
subject=/OU=Domain Control Validated/OU=PositiveSSL Wildcard/CN=*.cevo.de
issuer=/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 5189 bytes and written 488 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: zlib compression
Expansion: zlib compression
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384
    Session-ID: 244534A357837835FF9B28366E16DAA71E7D71C53AA9C0C5BBA8A2CFE065AA5A
    Session-ID-ctx:
    Master-Key: 9E8041FD2EC1DD4D3F9FDCEC2D920FA35EA403356DC7498767A43CC650314B0378D73BC7E786C29881BAB7EEE123DF6B
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    TLS session ticket lifetime hint: 3600 (seconds)
    TLS session ticket:
    0000 - 12 89 a5 2e e9 2a 80 e0-29 9a e8 71 41 96 27 ef   .....*..)..qA.'.
    0010 - 58 29 f0 f7 c1 56 66 9a-9e 9e 7b 0f 47 8f 97 06   X)...Vf...{.G...
    0020 - 47 bd 53 50 75 dd 8e 41-4f ea 52 f9 21 fc 30 1a   G.SPu..AO.R.!.0.
    0030 - 68 55 29 29 3c 33 80 f7-b4 af d6 32 21 80 78 24   hU))<3.....2!.x$
    0040 - e7 37 e9 24 77 71 72 58-0e c9 fb 23 2f b8 3c 4d   .7.$wqrX...#/.<M
    0050 - 31 1b bb 8d bf ca b5 cd-ec 24 81 be e4 4f 00 d4   1........$...O..
    0060 - 14 3f e5 68 5b 58 6c 19-b4 a2 03 a7 71 9e f7 58   .?.h[Xl.....q..X
    0070 - 7a 0d b8 dc a6 0e 2c b5-24 5f 8e 33 2c 64 c2 82   z.....,.$_.3,d..
    0080 - d2 25 ed bd e0 17 90 4a-29 a6 b1 4e f7 19 be d6   .%.....J)..N....
    0090 - b0 4d 3f c3 83 29 ec c4-24 e9 5e e0 48 b2 b7 12   .M?..)..$.^.H...
    00a0 - 8a 64 02 71 fe c3 42 e0-2b d7 99 da d3 04 7e 60   .d.q..B.+.....~`

    Compression: 1 (zlib compression)
    Start Time: 1453385327
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---
250 DSN

And the log entry for the request:
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: connect from unknown[172.19.5.135]
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: setting up TLS connection from unknown[172.19.5.135]
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: unknown[172.19.5.135]: TLS cipher list "aNULL:-aNULL:ALL:+RC4:@STRENGTH"
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: SSL_accept:before/accept initialization
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: SSL_accept:SSLv3 read client hello A
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: SSL_accept:SSLv3 write server hello A
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: SSL_accept:SSLv3 write certificate A
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: SSL_accept:SSLv3 write key exchange A
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: SSL_accept:SSLv3 write server done A
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: SSL_accept:SSLv3 flush data
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: SSL_accept:SSLv3 read client key exchange A
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: SSL_accept:SSLv3 read finished A
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: SSL_accept:SSLv3 write session ticket A
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: SSL_accept:SSLv3 write change cipher spec A
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: SSL_accept:SSLv3 write finished A
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: SSL_accept:SSLv3 flush data
Jan 21 15:11:49 mx01 postfix/smtpd[1401]: Anonymous TLS connection established from unknown[172.19.5.135]: TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)

Here's the main.cfg (I removed all comments and unnecessary blank lines):
message_size_limit = 20971520
# mailbox_size_limit = 51200000
command_directory = /usr/sbin
daemon_directory = /usr/lib/postfix
myhostname = mx01.cevo.local
myorigin = mx01.cevo.local
smtp_helo_name = mx01.cevo.de
append_dot_mydomain = no
inet_interfaces = all
inet_protocols = ipv4
mydestination = $myhostname, localhost.$mydomain, localhost
mynetworks = 127.0.0.0/8 172.19.3.29 172.19.3.36 172.19.3.41 172.19.3.50 172.19.3.123 192.168.100.28 172.19.3.18
masquerade_domains = $mydomain
masquerade_exceptions = root
transport_maps = hash:/etc/postfix/transport
disable_vrfy_command = no
smtpd_banner = mx01.cevo.de ESMTP $mail_name
local_header_rewrite_clients =
virtual_alias_domains =
virtual_alias_maps = hash:/etc/postfix/virtual,
        ldap:/etc/postfix/ldap.groups,
        ldap:/etc/postfix/ldap.distlist,
        ldap:/etc/postfix/ldap.sharedfolderremote,
        ldap:/etc/postfix/ldap.sharedfolderlocal,
        ldap:/etc/postfix/ldap.virtual
virtual_mailbox_domains = ldap:/etc/postfix/ldap.virtualdomains
virtual_mailbox_maps = hash:/etc/postfix/virtual,
        ldap:/etc/postfix/ldap.groups,
        ldap:/etc/postfix/ldap.distlist,
        ldap:/etc/postfix/ldap.sharedfolderremote,
        ldap:/etc/postfix/ldap.sharedfolderlocal,
        ldap:/etc/postfix/ldap.virtual
virtual_transport = lmtp:127.0.0.1:2003
canonical_maps = hash:/etc/postfix/canonical
relocated_maps = hash:/etc/postfix/relocated
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
smtpd_recipient_restrictions = permit_mynetworks,
        permit_sasl_authenticated,
        reject_unauth_destination,
        reject_unlisted_recipient
smtpd_use_tls = yes
smtpd_tls_auth_only = yes
smtpd_starttls_timeout = 300s
smtpd_timeout = 300s
smtpd_tls_cert_file = /etc/ssl/certs/star_cevo_de.pem
smtpd_tls_key_file = /etc/ssl/private/star_cevo_de.key
smtpd_tls_CAfile = /etc/ssl/certs/star_cevo_de.cabundle
smtpd_tls_received_header = no
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain =
smtpd_sasl_security_options = noanonymous
smtp_tls_security_level = may
broken_sasl_auth_clients = yes
smtp_tls_loglevel = 2
smtpd_tls_loglevel = 2
smtpd_tls_dh1024_param_file = /etc/postfix/dh_2048.pem
smtpd_tls_dh512_param_file = /etc/postfix/dh_512.pem
tls_preempt_cipherlist = yes
smtpd_tls_eecdh_grade = strong

master.cfg:
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (50)
# ==========================================================================
25      inet  n       -       n       -       -       smtpd
465       inet  n       -       n       -       -       smtpd  -o smtpd_sasl_auth_enable=yes -o smtpd_tls_wrappermode=yes

#628      inet  n       -       n       -       -       qmqpd
pickup    fifo  n       -       n       60      1       pickup
cleanup   unix  n       -       n       -       0       cleanup
qmgr      fifo  n       -       n       300     1       qmgr
#qmgr     fifo  n       -       n       300     1       nqmgr
rewrite   unix  -       -       n       -       -       trivial-rewrite
bounce    unix  -       -       n       -       0       bounce
defer     unix  -       -       n       -       0       bounce
verify    unix  -       -       n       -       1       verify
flush     unix  n       -       n       1000?   0       flush
smtp      unix  -       -       n       -       -       smtp
showq     unix  n       -       n       -       -       showq
error     unix  -       -       n       -       -       error
local     unix  -       n       n       -       -       local
#virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       n       -       -       lmtp
#587      inet  n       -       n       -       -       smtpd -v -o smtpd_enforce_tls=yes -o smtpd_sasl_auth_enable=yes
relay    unix  -       -       n       -       -       smtp
trace    unix  -       -       n       -       0       bounce
proxymap  unix -       -       n       -       -       proxymap
anvil    unix  -       -       n       -       1       anvil
scache   unix  -       -       -       -       1       scache
discard          unix  -       -       n       -       -       discard
tlsmgr    unix  -       -       n       1000?   1       tlsmgr

So, as you can see I can use SSL from my machine (like from the 'inside') but from outside it doesn't work. I'm at the end of my knowledge, which is pretty low when it comes to postfix and mail tbh. I already googled like hell but I didn't found a solution wich fixes my problem.

A: You aren't offering TLS, at least not when seen from outside:
[me@risby ~]$ telnet mx01.cevo.de 25
Trying 195.244.228.205...
Connected to mx01.cevo.de.
Escape character is '^]'.
220 mx01.cevo.de ESMTP Service ready
ehlo me
250-Requested mail action okay, completed
250-SIZE 20480000
250-ETRN
250-8BITMIME
250 OK

My guess is that you have an adaptive firewall (like, but not limited to, the CISCO PIX) in the way, which are famous for "helpfully" fixing up the SMTP stream to remove the TLS banner.
Tell the firewall to stop messing with SMTP data, or better still throw it out the window and use iptables, and external clients should also be able to benefit from TLS.