text:
Q: How can I apply converting within my stored procedure I have seen this resolved on here different time however I'm unsure how to apply this conversion in this case. Please see error messages and code below:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value
Conversion failed when converting date and/or time from character string.

Code:
ALTER PROCEDURE SP_Loans_to_Date
    @ReportDate DATETIME
AS
BEGIN
    DECLARE @DayofWeek VARCHAR(100),
            @BeginofWeek DATE,
            @BeginofMonth DATE,
            @BeginofYear DATE

    SET @DayofWeek = DATENAME(DW, @ReportDate)
    SET @BeginofWeek = (SELECT
                            CASE
                               WHEN @DayofWeek = 'Sunday'
                                  THEN DATEADD(DD, 0, @ReportDate)
                               WHEN @DayofWeek = 'Monday'
                                  THEN DATEADD(DD, -1, @ReportDate)
                               WHEN @DayofWeek = 'Tuesday'
                                  THEN DATEADD(DD, -2, @ReportDate)
                               WHEN @DayofWeek = 'Wednesday'
                                  THEN DATEADD(DD, -3, @ReportDate)
                               WHEN @DayofWeek = 'Thursday'
                                  THEN DATEADD(DD, -4, @ReportDate)
                               WHEN @DayofWeek = 'Friday'
                                  THEN DATEADD(DD, -5, @ReportDate)
                               WHEN @DayofWeek = 'Saturday'
                                  THEN DATEADD(DD, -6, @ReportDate)
                            END BeginofWeek)
    SET @BeginofMonth = (SELECT
CONVERT(DATETIME, CONVERT(VARCHAR(100), DATEPART(MM, @ReportDate)) + '1'+
CONVERT(VARCHAR(100), DATEPART(YY, @ReportDate))))
    SET @BeginofYear =  (SELECT ('1/1' +
                                CONVERT(VARCHAR(100), DATEPART(YY, @ReportDate))))

    SELECT
        SSN, LoanDate,
        CASE
           WHEN LoanDate >= @BeginofWeek AND LoanDate <= @ReportDate
              THEN 'WeektoDate'
           WHEN LoanDate >= @BeginofWeek AND LoanDate <= @ReportDate
              THEN 'MonthtoDate'
           WHEN LoanDate >= @BeginofWeek AND LoanDate <= @ReportDate
              THEN 'YeartoDate'
           ELSE NULL
        END ToDate,
        CASE
           WHEN LoanDate >= @BeginofWeek AND  LoanDate <= @ReportDate
              THEN 1
           WHEN LoanDate >= @BeginofWeek AND  LoanDate <= @ReportDate
              THEN 2
           WHEN LoanDate >= @BeginofWeek AND  LoanDate <= @ReportDate
              THEN 3
           ELSE NULL
        END ToDateOrder
    FROM
        [dbo].[Dim_Loan];

END

A: My recommendation is to avoid unnecessary date->string->date conversions, you can get those values in this simpler way
DECLARE @DayofWeek INT,
        @BeginofWeek DATE,
        @BeginofMonth DATE,
        @BeginofYear DATE

SET @DayofWeek = DATEPART(DW, @ReportDate)
SET @BeginofWeek = DATEADD(DAY, 1 - @DayofWeek, @ReportDate)
SET @BeginofMonth = DATEFROMPARTS(YEAR(@ReportDate), MONTH(@ReportDate), 1)
SET @BeginofYear = DATEFROMPARTS(YEAR(@ReportDate), 1, 1)


text:
Q: Erro php para obter dados de uma determinada area de um site Boa noite tenho um código em php para obter os dados de uma determinada pagina, uso o modelo inicial e funciona estou tentando usar-lo em outro site como esta ai no modelo mas da um erro:

E_NOTICE : type 8 -- Undefined offset: 3 -- at line 68
E_NOTICE : type 8 -- Undefined offset: 2 -- at line 68
E_NOTICE : type 8 -- Undefined offset: 1 -- at line 68
E_NOTICE : type 8 -- Undefined offset: 0 -- at line 68

Segue abaixo o código não tenho ideia como resolver, obrigado.
<?php class cotacoes { public function pegaValores() {

    if(!$fp=fopen("http://www.valor.com.br/valor-data/moedas" ,"r" )) {
        echo "Erro ao abrir a página de cotação" ;
        return(0);
    }

    //variáveis de classe
    $arrayValores = array();

    //inicio do processamento - ler página
    $uolHTML = "";
    while(!feof($fp)) { // leia o conteúdo da página, uma linha por vez, armazene na variável uolHTML
        $uolHTML .= fgets($fp);
    }
    fclose($fp);

    //array contendo as expressoes regulares que indicam cada moeda
    $patterns = array(
        "dolarComercial" => "/table-data valor_tabela.*Dólar Comercial/",
        "dolarTurismo"   => "/table-data valor_tabela.*Dólar Turismo/"

    );

    $uolHTML = preg_replace("/id=.block-valor_data_blocks-dolar-euro-full./", "", $uolHTML);
    $uolHTML = preg_replace("/<tr>/", "\n<tr>", $uolHTML); //acrescentar quebra de linha
    $uolHTML = preg_replace("/<td>/", "\n<td>", $uolHTML); //acrescentar quebra de linha

    //loop para cada moeda
    while( list($moeda, $pattern) = each($patterns) ) {

        $arrayHTML = explode("\n", $uolHTML);

        //loop por cada linha da pagina HTML
        while ( list($indice, $linha) = each($arrayHTML) ) {

            //se bloco HTML casa com a pattern da moeda do looping atual...
            if (preg_match($pattern, $linha)) {

                //print "Encontrei '$pattern' em: $linha\n\n";

                //ler proxima linha
                $linha = $arrayHTML[++$indice];

                //pegar cotacao compra
                preg_match("/<td>(.*)<\/td>/", $linha, $valor);
                $compra = substr($valor[1],0,4);

                //ler proxima linha
                $linha = $arrayHTML[++$indice];

                //pegar cotacao venda
                preg_match("/<td>(.*)<\/td>/", $linha, $valor);
                $venda = substr($valor[1],0,4);

                //atribuindo valores ao array de retorno
                array_push($arrayValores, $compra, $venda);
            }

        } // fim while

    } // fim while

    return($arrayValores);

} } $uol = new cotacoes(); list($dolarComercialCompra, $dolarComercialVenda, $dolarTurismoCompra, $dolarTurismoVenda) = $uol->pegaValores(); print ($dolarComercialCompra); ?>

A linha com o erro em questao seria a

list($dolarComercialCompra, $dolarComercialVenda, $dolarTurismoCompra, $dolarTurismoVenda) = $uol->pegaValores();

Se alguem souber algo

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular URL mapping with routes for initial load I have an angular project which has multiple routes say /category/fruit/apple so the full url is http://myserver/category/fruit/apple through router link everything is fine but if I open this link directly in typing in URL then it is 404 my backend is  nodejs with express. And the 404 make sense as there is no route configured like this.
My Question, In this kind of situation how should I handle?
I thought I had, redirect to root http://myserver?path=category-fruit-apple and from the root component do the dynamic routing. Is it the correct way ?
Please suggest the best way.

A: Because it´s just javascript, the server didn´t know the route.
You have to add these lines in .htaccess
RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

So, if the server didn´t find this route, you redirect to your angular-root and angular can handle this route. Therefore you can also replace "index.html" with the route, where your angular-root is.

A: There is a frontend-only solution (so, zero configuration server-side), too, namely hash routing. Add a line
useHash: true

in the root router module's configuration (then, the urls will look something like http://myserver/#/category/fruit/apple).

A: Of course you need to config your server to route to the right content.
Two examples are apache http server or nginx.
Here are some minimal config examples for both.
Angular apache example (.htaccess):
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . index.html [L]
</IfModule>

Nginx example (nginx.conf):
server {
    listen 80;

    server_name your.app;

    location / {
        proxy_pass       http://localhost:4200;
        proxy_set_header Upgrade    $http_upgrade;
        proxy_set_header Connection $http_connection;
        proxy_set_header Host       $host;
    }
}

A: You can apply simple redirects to the index.html for everything that isn't a resource. I've got a public repo you might find useful, it's an incredibly simple express server I use to test the hosting of various Angular apps:
https://github.com/hevans90/node-ng-server/blob/master/server.js
tl;dr: make a list of resource file types & their directory, to serve your assets, but otherwise redirect ALL requests to index.html & let the Angular router do its work.

A: As other people wrote, it's just a matter of redirect to index.html instead of throwing 404 on the server side.
There's a whole section that talks exactly about this on Angular's webpage.

A: Its because your server does not know the route. The server understands only one route
i.e. index.html
When the index page is loaded, client side rendering comes into picture. Angular determines the component to be loaded at client side and loads appropriate component.
When you navigate using links in the page, track your network calls, you will see that no request goes to backend. When you reload the route, then this entire route goes to server and it throws 404.
You can use HashLocationStrategy. This would append # in your route #/category/fruit/apple
All servers will ignore the route after # loading the main page, which would allow client side rendering again.
If you wish the do server side rendering, have a look at https://angular.io/guide/universal

A: in nodejs return with index.html
 // Redirect all the other requests
    this.app.get('*', (req: Request, res: Response) => {
        if (allowedExt.filter((ext) => req.url.indexOf(ext) > 0).length > 0) {
            res.sendFile(path.resolve(`dist/assets/${req.url.split('?')[0]}`));
        } else {
            res.sendFile(path.resolve('dist/app/index.html'));
        }
    });


text:
Q: How to run a Node.js like a cron job? I had a php file which made a REST API call to a url which returned a json object.
I converted the code to Node.js as show below which works like a charm. However, i ran a cron job for my php script to run every 5 minute.
I am not sure how a node js would work in this case ? Can i make node javascript file to run every 5 minutes without a cron ? The idea is to save the JSON object into a MySQL db from node.js
Can someone help me with the architecture here ? I am trying to understand how do i run a node.js file every 5 minutes ? Any tutorial or example would be great! Thanks in advance
I just started using node so i am very new to it
var http = require("http");
    url1 = "http://xyz.net/v2/plan/"

var request = http.get(url1, function (response) {
    var buffer = "",
        data,
        route;

    response.on("data", function (chunk) {
        buffer += chunk;
    });

    response.on("end", function (err) {
        console.log(buffer);
        console.log("\n");
        data = JSON.parse(buffer);
        // MYSQL code here to insert the object into Database every 5 minutes
    });
});


text:
Q: How to access directory file outside django project? I have my Django project running on RHEL 7 OS. The project is in path /root/project. And project is hosted on httpd server. Now iam trying to access a file out side the directory like /root/data/info/test.txt
How should I access this path in views.py so that I can read and write file which is outside the project directory ? I tried to add the path in sys.path but it didn't work. Read and write permission are also give to the file.

A: Add the following lines to your settings.py
import os
..
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FILES_DIR = os.path.abspath(os.path.join(BASE_DIR, '../data/info'))

Then you can use in your view
from django.conf import settings
import os
..
file_path = os.path.join(settings.FILES_DIR, 'test.txt')


text:
Q: How can I detect the file format with Jquery? How can I detect the file format with Jquery?
I have a div that will receive a file. This file can be .pdf or .doc
If user upload a file .pdf, the ico in side, need to be 'pdf.ico'...
Can I discover this with Jquery?
My code:

Manual

If the file is = .pdf / produtosDownIco need to change.

A: would
if ($(yourFileHandle).attr("href").indexOf(".pdf") >-1)
{
   //apply the icon accordingly
}

not suffice? In this situation, you are doing a string search in the href attribute of the URL. I offer this solution as its as best I can discern from your question what you are trying to accomplish.
To provide a more thorough answer - here's a URL to the jquery documentation that discusses how to access element attributes https://api.jquery.com/attr/
One More Edit: Please be clear that we are not actually interrogating the file itself. Rather we are looking at a URL. If the file at the end of "../somedir/somefile.pdf" is not actually a PDF but has a PDF extension in the URL - it will resolve "true" as a pdf because of the string ".pdf" being found in the string object representing the href attribute in this case.
So this solution will work as long as you have control (at some level, be it yourself or a business user that maintains the file(s) ) over how the file is saved, and referenced.
If you need to actually handle the file and look at what type it is, you will need a serverside solution which is apt at this task.
But if all you're interested in is assigning a graphic depending on filetype extension, this will perform as intended
-b


text:
Q: How to make Google reCAPTCHA a required field? How can I make Google's No CAPTCHA reCAPTCHA a required field?
I mean, I want to check it with HTML or JavaScript.

A: What you have to do is prevent the form submission until you can validate the user response by using the Google reCaptcha verify callback, then, if it passes, allow the form to submit. See this answer: Google ReCAPTCHA how to make required? and also check the documentation: https://developers.google.com/recaptcha/docs/display#example


text:
Q: Confidence Interval for Predictions Made by Sklearn LassoCV Regression Model I have a data set "X" with "n" samples, which was used for training a lasso regression model.
There were "p" predictors in the dataset from which the LassoCV selected "k" of them in the final trained model. I will use this model to make predictions.
I want to know the Confidence Interval for my predictions done by this model.
Assuming "y" are the true lables for my data, and "y^" are the predicted values by my model, and 90% of confidence to be of interest, the following formula was used:
conf_int = 1.645 * (np.sqrt(sum((y - y^)**2)/(n - k - 2)))

I was wondering if this formula is correct. If not, I appreciate it if you could provide me with some link or tutorial for that.
Thanks in advance for your opinions and comments


text:
Q: Quick way to simplify $\frac{\frac{x^2-y^2}{x^2+y^2}-\frac{x^2+y^2}{x^2-y^2}}{\frac{x-y}{x+y}-\frac{x+y}{x-y}}$? What's a quick way to simplify $\displaystyle\frac{\displaystyle\frac{x^2-y^2}{x^2+y^2}-\displaystyle\frac{x^2+y^2}{x^2-y^2}}{\displaystyle\frac{x-y}{x+y}-\frac{x+y}{x-y}}$?
I tried to find another way to simplify it, but the one that has only worked so far involves multiplying terms out and subtracting them. There has to be a quicker way. It simplifies to $\displaystyle\frac{xy}{x^2+y^2}$.

A: As $\dfrac{\dfrac ab}{\dfrac  cd}=\dfrac{ad}{bc},$
$\displaystyle\frac{\displaystyle\frac{x^2-y^2}{x^2+y^2}-\displaystyle\frac{x^2+y^2}{x^2-y^2}}{\displaystyle\frac{x-y}{x+y}-\frac{x+y}{x-y}}$
$=\displaystyle\frac{(x^2-y^2)^2-(x^2+y^2)^2}{(x^2+y^2)(x^2-y^2)}\cdot\frac{(x^2-y^2)}{(x-y)^2-(x+y)^2}$
Now use $(a+b)^2-(a-b)^2=4ab$

A: Knowing that $(a+b)^2-(a-b)^2=4ab$, I'd note right away that the denominator is
$$\frac{(x-y)^2-(x+y)^2}{x^2-y^2}=\frac{-4xy}{x^2-y^2}\;,$$
so we have
$$-\frac{(x^2-y^2)^2}{4xy(x^2+y^2)}+\frac{x^2+y^2}{4xy}=\frac{(x^2+y^2)^2-(x^2-y^2)^2}{4xy(x^2+y^2)}=\frac{4x^2y^2}{4xy(x^2+y^2)}=\frac{xy}{x^2+y^2}\;.$$


text:
Q: Check if a character is in data frame I'm looking for a simple way to check if values in an R data frame have comma (or any character for that matter).
Let's suppose I have the following data frame:
df <- data.frame(A = c("apple","orange", "banana","strawberries"),
                 B = c(23,12,10,15),
                 C = c("2,53", "1.35","0,25","1,44"))

If I know the column with commas in it I use this:
which(grepl(",",df$C))
length(which(grepl(",",df$C)))

However, I want an output as the one above but not specifying the column of my dataframe.
Any suggestions?

A: You need to simply go through all three columns; sapply works here:
sapply(df, grep, pattern = ",")

##output:

# $A
# integer(0)
#
# $B
# integer(0)
#
# $C
# [1] 1 3 4

To get the length you can do this:
sapply(sapply(df, grep, pattern = ","), length)

# A B C D
# 0 0 3 0

A: Somewhat simpler to grasp solution; first, convert your data frame to vector.
df2vector <- as.vector(t(df))

df2vector
# [1] "apple"        "23"           "2,53"         "orange"       "12"
# [6] "1.35"         "banana"       "10"           "0,25"         "strawberries"
# [11] "15"           "1,44"

Then use your approach.
length(which(grepl(",",df2vector)))
# [1] 3


text:
Q: What about a material makes it diamagnetic For a material to be magnetic, all the magnetic atoms (atoms with half filled electron shells) need to be aligned, but what about a material gives it the property of diamagnetism?

A: There are several mechanisms causing diamagnetism. And all atoms are diamagnetic to a certain degree, this property may only be hidden by paramagnetism.
The fundamental mechanism driving diamagetism is (very roughly) Lenz's law, that an induced current lowers the inbound field.
The atom's diamagnetism is driven by the $\propto \vec A^2$-term in the Hamiltonian of an electron coupled to the electromagnetic field (this can be found in any introductory book on QM).
Superconductors are perfect diamagnets up to a critical field strength.
Conductors are AC diamagnets (as can be seen in the typical introductory course experiment of an aluminium ring repelled by a solenoid which is driven by AC).


text:
Q: How can I find a path for process with *32 in it's name using a batch file? I am using a batch file to try and find a process named "you.exe". But in task manager the name is "you.exe *32". How can I find it's path?
I tried the script:
for %%I in (PROCESS-NAME.exe *32) do set "ExPath=%%~$PATH:I"
echo %ExPath%

But for some reason it doesn't work on processes that has *32 in their name.
it only works on processes with normal names like "you.exe"
How can I find the path for those processes?
I am using windows 7
Also what do I do in case I have more than 1 process with the same name ?
.
.
I will give you an example:
As suggested by one of the users in the answers, I am using this batch file to search:
@echo off

setlocal
set "process=issch.exe"

for /f "usebackq delims=" %%p in (`wmic process where "name='%process%'"
                               get executablepath /value 2^>nul ^| findstr
^=`) do (
  set %%p
)

if defined executablePath (
   echo %executablePath%
 )^
else (
  echo Unable to find process: %process%
)

PAUSE

when I try to search for process: issch.exe thats marked in the picture it gives me nothing. Not even the not found message
But when I try to search for a different name: ipoint.exe it works fine.
Or if I try to search for issch.exe *32  i get a not found message.
So my guess is that it finds the process issch.exe but for some reason it can't process its' values.
 I get the same "error" for every process that has *32 in it's name.
How can I search for processes with *32 in their names, and get their path?

A: You could use the wmic command to retrieve the executable path of a process. The following script looks for all the processes with the name PROCESS-NAME.exe and sets the variable executablePath to the path of the processes that were found.
The problem with this approach is that for every single match, the variable executablePath will be overwritten. The executablePath variable will be set to the last match found.
@echo off

setlocal
set "process=PROCESS-NAME.exe"

for /f "usebackq delims=" %%p in (`wmic process where "name='%process%'"
                                   get executablepath /value 2^>nul ^| findstr ^=`) do (
  set %%p
)

if defined executablePath (
  echo %executablePath%
)^
else (
  echo Unable to find process: %process%
)

Another approach is to check if the variable exePath is already defined before setting its value. This way the exePath variable will be set to the first match found.
@echo off

setlocal
set "process=PROCESS-NAME.exe"

for /f "usebackq skip=1 delims=" %%p in (`wmic process where "name='%process%'"
                                          get executablepath 2^>nul`) do (
  if not defined exePath (
    set "exePath=%%p"
  )
)

if not "%exePath%" == "" (
  echo %exePath%
)^
else (
  echo Unable to find process: %process%
)

In order to save the executable paths of every single process, the retrieved values will have to be stored in separate variables. Keep in mind that if the process that you are looking for is executed multiple times from the same location, all the retrieved values are the same as well and you will need another way to differentiate one process from another. Depending on your situation, there might be a way to do this by comparing some of the other properties from the Win32_Process class.
@echo off

setlocal enabledelayedexpansion
set "processName=PROCESS-NAME.exe"

for /f "usebackq delims=" %%p in (`wmic process where "name='%processName%'"
                                   get executablepath /value 2^>nul ^| findstr ^=`) do (
  set /a count+=1
  set process[!count!].%%p
)

if not defined process[%count%].executablePath (
  echo Unable to find process: %processName%
  exit /b
)

for /l %%c in (1, 1, %count%) do (
  echo !process[%%c].executablePath!
)


text:
Q: C# ASP.NET Master Page and ChildPage - Assign strings from Child Page into Master Page Here is the section of my child page file and my master page file respectively. I am going  to pass strName,   from Child page to master page .I would like to access this Master Page variable in child page and assign child page variable to master page on or before the Page Load. I often get the last  selected value but not the current value
For instance , Given the record shows Mary, John , Peter,
if I click Mary , then show none
if I click Peter, show Mary
if I lick John,  show Peter
Would you please suggest and show how to resolve this issue ?
the following is my code
   protected void grdNameSelection_ItemCommand(object sender, GridCommandEventArgs e)
    {
        RadGrid CurrentGrid = (RadGrid)sender;
        GridData GridSource = PageSource.GrdSrcNameSelection;
        String a = GridSource.state.ToString();

        if (e.CommandName == "SelectCurrent")
        {
            foreach (GridDataItem item in CurrentGrid.SelectedItems)
            {

                RowData row = (RowData)GridSource.Current[item.DataSetIndex];
                string Name = row.Name;
            }
        }
    }
 protected void grdCompanySelection_PreRender(object sender, EventArgs e)
    {
        UserSession.Instance.CurrentName= Name ;

        RadGrid CurrentGrid = (RadGrid)sender;
        GridData GridSource = PageSource.GrdSrcCompanySelection;
        CommandButtonDisplay(GridSource, CurrentGrid);

    }

Master Page
 protected void Page_init(object sender, EventArgs e)
    {

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        lblHeader.Text = UserSession.Instance.CurrentName;

        if (!Page.IsPostBack)
        {  ,,,,

A: Unfortunately MS hasn't provided a very good way of doing this. You basically have two options.

*

*Access the control from the child page and then set whatever value you need (child page is this in the example):
Label label1 = this.Master.FindControl("Label1") as Label;
label1.Text = "Hello";

*Preferred provide some kind of setter on the master page. This is "safer" because the child page doesn't directly manipulate the master's controls.
 MyType master = this.Master as MyType;
 if(master == null)
    return;

 master.MyProperty = "something";

 // In master page
 public string MyProperty
 {
    get { return label.Text; }
    set { label.Text = value; }
 }


text:
Q: Securing access to a website on IIS I've got a website running on IIS7.5. I want to ask for credentials (fixed user/password) on access to the website. I don't need to do anything with those credentials - just to make sure the user knows them.
I'd like to make it transparent to the website (it shouldn't "concern" the website).
Is there some elegant way of doing this?
Thanks

A: Well the easiest way is to create some local user accounts on your server and then enable Windows Authentication on your site in IIS. When users visit the site they will be asked for credentials, which will be validated against the Windows user database.


text:
Q: Calculate exponential moving average with values in different columns I have a data structure like
data = {
    "Home Team": ["A", "C", "D", "B", "A"],
    "Away Team": ["B", "A", "A", "A", "D"],
    "Home Feat": [1, 2, 0, 10, 7],
    "Away Feat": [2, 3, 0, 5, 1],
    "Primary Key": [1, 2, 3, 4, 5],
}
df = pd.DataFrame(data=data)

I am trying to compute the exponential moving average per team in new features Home Exp Mov Avg {feature} Last {offset} Games and Away Exp Mov Avg {feature} Last {offset} Games. I have this super slow and long function, which takes aprox 4 min for 8000 rows:
>>> import numpy as np
>>> import pandas as pd
>>> def extract_feature_per_team(df, feature, team, against):
...     """
...     Extracts feature for per team from columns, that comes in pairs of two.
...     """
...     result = df.copy(deep=True)
...     result.columns = result.columns.str.split(expand=True)
...     if not against:
...         result = result.stack(0).loc[lambda x: x["Team"] == team, feature].tolist()
...     else:
...         result = result.stack(0).loc[lambda x: x["Team"] != team, feature].tolist()
...     return pd.DataFrame(data={team: result})
...
>>> def add_Exp_Mov_Avg_FEAT_Last_OFFSET_Games(df, feature, offset):
...     """
...     Adds features "Home Exp Mov Avg {feature} Last {offset} Games" and "Away
...     Exp Mov Avg {feature} Last {offset} Games" based on "Season", "Home Team",
...     "Away Team", "Home {feature}" and "Away {feature}" for a given dataframe
...     and offset. Values of new features are float (rounded to 2 decimals). This
...     function prevents overlaps between saisons. IMPORTANT: Reindex df before
...     usage!
...     """
...     col_home = f"Home Exp Mov Avg {feature} Last {offset} Games"
...     col_away = f"Away Exp Mov Avg {feature} Last {offset} Games"
...     df[col_home] = -1.0
...     df[col_away] = -1.0
...     for index, row in df.iterrows():
...         season = row["Season"]
...         # home
...         tmp = df.iloc[: index + 1]
...         team = row["Home Team"]
...         tmp = tmp.loc[
...             ((tmp["Home Team"] == team) | (tmp["Away Team"] == team))
...             & (tmp["Season"] == season)
...         ]
...         tmp = tmp[["Home Team", "Away Team", f"Home {feature}", f"Away {feature}"]]
...         result = (
...             extract_feature_per_team(tmp, feature, team, False)
...             .ewm(span=offset)
...             .mean()
...             .shift(1)
...             .round(2)[team]
...             .iloc[-1]
...         )
...         if np.isnan(result):
...             result = 0.0
...         df.at[index, col_home] = result
...         # away
...         tmp = df.iloc[: index + 1]
...         team = row["Away Team"]
...         tmp = tmp.loc[
...             ((tmp["Home Team"] == team) | (tmp["Away Team"] == team))
...             & (tmp["Season"] == season)
...         ]
...         tmp = tmp[["Home Team", "Away Team", f"Home {feature}", f"Away {feature}"]]
...         result = (
...             extract_feature_per_team(tmp, feature, team, False)
...             .ewm(span=offset)
...             .mean()
...             .shift(1)
...             .round(2)[team]
...             .iloc[-1]
...         )
...         if np.isnan(result):
...             result = 0.0
...         df.at[index, col_away] = result
...     return df
...
>>> data = {
...     "Season": ["2021-2022", "2021-2022", "2021-2022", "2021-2022", "2021-2022"],
...     "Home Team": ["A", "C", "D", "B", "A"],
...     "Away Team": ["B", "A", "A", "A", "D"],
...     "Home Feat": [1, 2, 0, 10, 7],
...     "Away Feat": [2, 3, 0, 5, 1],
... }
>>>
>>> df = pd.DataFrame(data=data)
>>> add_Exp_Mov_Avg_FEAT_Last_OFFSET_Games(df, "Feat", 3)
test = {"Season": [1, 3, 0, 5, 7]}
pd.DataFrame(data=test).ewm(span=3).mean().shift(1)
      Season Home Team Away Team  ...  Away Feat  Home Exp Mov Avg Feat Last 3 Games  Away Exp Mov Avg Feat Last 3 Games
0  2021-2022         A         B  ...          2                                0.00                                0.00
1  2021-2022         C         A  ...          3                                0.00                                1.00
2  2021-2022         D         A  ...          0                                0.00                                2.33
3  2021-2022         B         A  ...          5                                2.00                                1.00
4  2021-2022         A         D  ...          1                                3.13                                0.00

[5 rows x 7 columns]
>>> # doublecheck
>>>
>>> test = {"Test": [1, 3, 0, 5, 7]}
>>> pd.DataFrame(data=test).ewm(span=3).mean().shift(1)
     Season
0       NaN
1  1.000000
2  2.333333
3  1.000000
4  3.133333

Is there a more Pythonic way to solve/rewrite this?


text:
Q: Xamarin white screen in local machine enter image description here
Hello,
I have a problem with Xamarin, when i run program i see only white screen, just like on picture.
MainPage.xaml.cs have this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
namespace Hello
{
public class App : Application
{
    public App()
        { // The root page of your application
            MainPage = new ContentPage
            {
                Content = new StackLayout
                {
                    VerticalOptions = LayoutOptions.Center,
                    Children = {
                        new Label {
                            HorizontalTextAlignment = TextAlignment.Center,
                            Text = "Welcome to Xamarin Forms!"
                        }
                    }
                }
            };
        }
        protected override void OnStart()
        {
            // Handle when your app starts
        }
        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }
        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}

I take this code from "Creating Mobile Apps with Xamarin Forms", somebody know what is wrong with this program?

A: Write your code in Shared project's App.xaml.cs class which is partial class. The code above you are showing is not partial class. Probably, as your screenshot showing you have written App class code in Main.axml.cs file
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace App
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();

            //MainPage = new MainPage();
            MainPage = new ContentPage
            {
                Content = new StackLayout
                {
                    VerticalOptions = LayoutOptions.Center,
                    Children =
                    {
                        new Label
                        {
                            HorizontalTextAlignment=TextAlignment.Center,
                            Text="Welcome to xamarin forms"
                        }
                    }
                }
            };
        }
    }
}


text:
Q: CONCAT(column) OVER(PARTITION BY...)? Group-concatentating rows without grouping the result itself I need a way to make a concatenation of all rows (per group) in a kind of window function like how you can do COUNT(*) OVER(PARTITION BY...) and the aggregate count of all rows per group will repeat across each particular group. I need something similar but a string concatenation of all values per group repeated across each group.
Here is some example data and my desired result to better illustrate my problem:
grp  |  val
------------
1    |  a
1    |  b
1    |  c
1    |  d
2    |  x
2    |  y
2    |  z

And here is what I need (the desired result):
grp  |   val  |  groupcnct
---------------------------------
1    |   a    |  abcd
1    |   b    |  abcd
1    |   c    |  abcd
1    |   d    |  abcd
2    |   x    |  xyz
2    |   y    |  xyz
2    |   z    |  xyz

Here is the really tricky part of this problem:
My particular situation prevents me from being able to reference the same table twice (I'm actually doing this within a recursive CTE, so I can't do a self-join of the CTE or it will throw an error).
I'm fully aware that one can do something like:
SELECT      a.*, b.groupcnct
FROM        tbl a
CROSS APPLY (
            SELECT STUFF((
                        SELECT '' + aa.val
                        FROM   tbl aa
                        WHERE  aa.grp = a.grp
                        FOR XML PATH('')
                   ), 1, 0, '') AS groupcnct
            ) b

But as you can see, that is referencing tbl two times in the query.
I can only reference tbl once, hence why I'm wondering if windowing the group-concatenation is possible (I'm a bit new to TSQL since I come from a MySQL background, so not sure if something like that can be done).

Create Table:
CREATE TABLE tbl
    (grp int, val varchar(1));

INSERT INTO tbl
    (grp, val)
VALUES
    (1, 'a'),
    (1, 'b'),
    (1, 'c'),
    (1, 'd'),
    (2, 'x'),
    (2, 'y'),
    (2, 'z');

A: In sql 2017 you can use STRING_AGG function:
SELECT STRING_AGG(T.val, ',') AS val
    , T.grp
FROM @tbl AS T
GROUP BY T.grp

A: I tried using pure CTE approach: Which is the best way to form the string value using column from a Table with rows having same ID? Thinking it is faster
But the benchmark tells otherwise, it's better to use subquery(or CROSS APPLY) results from XML PATH as they are faster: Which is the best way to form the string value using column from a Table with rows having same ID?

A: DECLARE @tbl TABLE
(
    grp INT
    ,val VARCHAR(1)
);

BEGIN
 INSERT INTO @tbl(grp, val)
VALUES
    (1, 'a'),
    (1, 'b'),
    (1, 'c'),
    (1, 'd'),
    (2, 'x'),
    (2, 'y'),
    (2, 'z');
END;
----------- Your Required Query
SELECT  ST2.grp,
SUBSTRING(
            (
                SELECT ','+ST1.val  AS [text()]
                FROM @tbl ST1
                WHERE ST1.grp = ST2.grp
                ORDER BY ST1.grp
                For XML PATH ('')
            ), 2, 1000
       ) groupcnct
FROM @tbl ST2

A: Is it possible for you to just put your stuff in the select instead or do you run into the same issue? (i replaced 'tbl' with 'TEMP.TEMP123')
Select
A.*
, [GROUPCNT] = STUFF((
                        SELECT '' + aa.val
                        FROM  TEMP.TEMP123 AA
                        WHERE  aa.grp = a.grp
                        FOR XML PATH('')
                   ), 1, 0, '')

 from TEMP.TEMP123 A

This worked for me -- wanted to see if this worked for you too.

A: I know this post is old, but just in case, someone is still wondering, you can create scalar function that concatenates row values.
IF OBJECT_ID('dbo.fnConcatRowsPerGroup','FN') IS NOT NULL
DROP FUNCTION dbo.fnConcatRowsPerGroup
GO
CREATE FUNCTION dbo.fnConcatRowsPerGroup
    (@grp as int) RETURNS VARCHAR(MAX)
AS
BEGIN
    DECLARE @val AS VARCHAR(MAX)

    SELECT @val = COALESCE(@val,'')+val
    FROM tbl
    WHERE grp = @grp

    RETURN @val;
END
GO

select *, dbo.fnConcatRowsPerGroup(grp)
from tbl

Here is the result set I got from querying a sample table:
grp  |   val  |  (No column name)
---------------------------------
1    |   a    |  abcd
1    |   b    |  abcd
1    |   c    |  abcd
1    |   d    |  abcd
2    |   x    |  xyz
2    |   y    |  xyz
2    |   z    |  xyz


text:
Q: Java do-while loop inside a method in its own class I'm pretty new to java and we didn't really go over the methods but its required for the project. I am trying to place the whole two do-while loops into a method that I can call off within the public void run(). Could someone please guide me out how I can accomplish it? I am trying to place this nested loop with inner and outer do-while loops inside its own method possibly within its own class also
Here is the full code:
The section where the do loop starts I'm trying to place it in its own method and how do I go by accomplishing that?
App.java
import acm.program.*;

public class App extends ConsoleProgram
{
    public void init()
    {
        setSize(300,600);
    }
    public void run()
    {
        //  Counter variables
        int n = 0;
        int counter = 0;
        int score = 0;

        n = readInt("How many times did you take this quiz: ");

        /*
         * Printing questions
         */

        //  First Question
        Questions questionOne = new Questions();
        println(" ");
        questionOne.SetQuestion("Question 1: ");
        questionOne.SetChoice1("Answer a: ");
        questionOne.SetChoice2("Answer b: ");
        questionOne.SetChoice3("Answer c: ");
        questionOne.SetChoice4("Answer d: ");
        questionOne.SetCorrectAnswer("b");

        //  Second Question
        Questions questionTwo = new Questions();
        println(" ");
        questionTwo.SetQuestion("Question 2: ");
        questionTwo.SetChoice1("Answer a: ");
        questionTwo.SetChoice2("Answer b: ");
        questionTwo.SetChoice3("Answer c: ");
        questionTwo.SetChoice4("Answer d: ");
        questionTwo.SetCorrectAnswer("d");

        //  Third Question (Hard Question)
        Questions questionThree = new Questions();
        println(" ");
        questionThree.SetQuestion("Question 3:  ");
        questionThree.SetChoice1("Answer a: ");
        questionThree.SetChoice2("Answer b: ");
        questionThree.SetChoice3("Answer c: ");
        questionThree.SetChoice4("Answer d: ");
        questionThree.SetCorrectAnswer("a");

        // CREATE A METHOD FOR THIS DO-WHILE LOOP.
        do
        {
            if ( n <= 3 )
            {
                println("You may now take the quiz!");
                println(" ");
            }
            else
            {
                println("You're out of quiz attempts. You have already taken it 3 times.");
                break;
            }

            do
            {
            score = 0;

            if (counter==5)
            {
            println("You scored less than 100%");
            println("Take a break! You may retake the quiz on a later date. ");
            break;
            }

            // print question 1
            println(questionOne.PrintQuestion());

            // input answer for question number 1
            String yourAnswer = readLine("Your answer: ");
            println(" ");

            // check if the question 1 is correct, if it is, add 1 to the score++
            if (questionOne.IsAnswerCorrect(yourAnswer))
            {
                score++;
                println("You got it right!");
            }
            else    // if its not correct, print you got it wrong
            {
                println("You got it wrong!");
                println(" ");
                println(" ");
            }

            // print question 2
            println(questionTwo.PrintQuestion());

            // input answer for question number 2
            String yourAnswer2 = readLine("Your answer: ");
            println(" ");

            // check if the question 2 is correct, if it is, add 1 to the score++
            if (questionTwo.IsAnswerCorrect(yourAnswer2))
            {
                score++;
                println("You got it right!");
            }
            else    // if its not correct, print you got it wrong
            {
                println("You got it wrong!");
                println(" ");
                println(" ");
            }

            // print question 3
            println(questionThree.PrintQuestion());

            // input answer for question number 3
            String yourAnswer3 = readLine("Your answer: ");
            println(" ");

            // checking for hard question. To make it easier, we're using boolean to check for the hard question
            boolean hardQuestion = false;

            // check if the question 3 is correct, if it is, add 1 to the score++ // hard question becomes true
            if (questionThree.IsAnswerCorrect(yourAnswer3))
             {
                score++;
                println("You got it right!");
                println(" ");
                hardQuestion = true;
             }
             else
             {
                println("You got it wrong!");
                println(" ");
                println(" ");
             }
             if (score == 0)
             {
                 println("You need more practice!");
                 println(" ");
             }

             // if you got at least the hard one right, your score is of 1 and that is what gets printed out
             else if (score == 1)
             {
                 if (hardQuestion)
                 {
                     println("Well, at least you got the hard one correct! ");
                     println(" ");
                 }
                 else
                 {
                     // if the other ones are correct, print out this message if hard is wrong
                     println("You need to warm up!");
                     println(" ");
                 }
             }

             // if you got at least two correct
             else if (score == 2)
             {
                 if (hardQuestion)
                 {
                     // user got one correct and hard one correct
                     println("You are amazing!");
                     println(" ");
                 }
                 else
                 {
                     // if hard one was wrong
                     println("You're on your way!");
                     println(" ");
                 }
             }
             else
             {
                 // all answers are correct including the hard ones
                 println("You are a scholar!");
                 println(" ");
                 println("Congradulations you passed! You got 100% on the quiz!");
                 break;
             }
                // count number of tries the quiz has been looped
                counter++;
                if (counter < 5)
                {
                    println("You scored less than 100%");
                    println(" ");
                    println(" ");
                    println("Try again!");
                    println(" ");
                }
            } while (true); // end program loop

            break;

        } while (true); // end while loop
    } // closing public run
} // closing public class

Private String questions code:
Questions.java
public class Questions {
    private String _question;
    private String _correctAnswer;
    private String _correctAnswer2;
    private String _correctAnswer3;
    private String _choice1, _choice2, _choice3, _choice4;

    public void SetQuestion(String q)
    {
        _question = q;
    }
    public String GetQuestion()
    {
        return _question;
    }

    public void SetCorrectAnswer(String c)
    {
        _correctAnswer = c;
    }

    public String GetCorrectAnswer()
    {
        return _correctAnswer;
    }

    public void SetCorrectAnswer2(String b)
    {
        _correctAnswer2 = b;
    }

    public String GetCorrectAnswer2()
    {
        return _correctAnswer2;
    }

    public void SetCorrectAnswer3(String a)
    {
        _correctAnswer3 = a;
    }

    public String GetCorrectAnswer3()
    {
        return _correctAnswer3;
    }

    public void SetChoice1(String a)
    {
        _choice1 = a;
    }

    public void SetChoice2(String b)
    {
        _choice2 = b;
    }

    public void SetChoice3(String c)
    {
        _choice3 = c;
    }
    public void SetChoice4(String d)
    {
        _choice4 = d;
    }
    public String PrintQuestion()
    {
        String result = " ";

        result = _question + "\n" + _choice1 + "\n" + _choice2 + "\n" + _choice3 + "\n" + _choice4 + "\n";
        return result;
    }

    public boolean IsAnswerCorrect(String a)
    {
        return _correctAnswer.equals(a);
    }

    /*public boolean IsAnswerCorrect2(String b)
    {
        return _correctAnswer2.equals(b);
    }*/

    }

A: You can use this code or make necessary modifications as per your need, simply it has a method which takes an array of Questions and then performs operations by taking out questions from array
import acm.program.*;

public class App extends ConsoleProgram
{

        int n = 0;
        int counter = 0;
        int score = 0;

    public void init()
    {
        setSize(300,600);
    }
    public void run()
    {
        //  reset counter variables
        n = 0;
        counter = 0;
        score = 0;

        n = readInt("How many times did you take this quiz: ");

        /*
         * Printing questions
         */

        //  First Question
        Questions questionOne = new Questions();
        println(" ");
        questionOne.SetQuestion("Question 1: ");
        questionOne.SetChoice1("Answer a: ");
        questionOne.SetChoice2("Answer b: ");
        questionOne.SetChoice3("Answer c: ");
        questionOne.SetChoice4("Answer d: ");
        questionOne.SetCorrectAnswer("b");

        //  Second Question
        Questions questionTwo = new Questions();
        println(" ");
        questionTwo.SetQuestion("Question 2: ");
        questionTwo.SetChoice1("Answer a: ");
        questionTwo.SetChoice2("Answer b: ");
        questionTwo.SetChoice3("Answer c: ");
        questionTwo.SetChoice4("Answer d: ");
        questionTwo.SetCorrectAnswer("d");

        //  Third Question (Hard Question)
        Questions questionThree = new Questions();
        println(" ");
        questionThree.SetQuestion("Question 3:  ");
        questionThree.SetChoice1("Answer a: ");
        questionThree.SetChoice2("Answer b: ");
        questionThree.SetChoice3("Answer c: ");
        questionThree.SetChoice4("Answer d: ");
        questionThree.SetCorrectAnswer("a");

        evaluate(new Questions[]{questionOne,questionTwo,questionThree});

    } // closing public run

private void evaluate(Questions[] q){
 //  METHOD FOR DO-WHILE LOOP.
        do
        {
            if ( n <= 3 )
            {
                println("You may now take the quiz!");
                println(" ");
            }
            else
            {
                println("You're out of quiz attempts. You have already taken it 3 times.");
                break;
            }

            do
            {
            score = 0;

            if (counter==5)
            {
            println("You scored less than 100%");
            println("Take a break! You may retake the quiz on a later date. ");
            break;
            }

            // print question 1
            println(q[0].PrintQuestion());

            // input answer for question number 1
            String yourAnswer = readLine("Your answer: ");
            println(" ");

            // check if the question 1 is correct, if it is, add 1 to the score++
            if (q[0].IsAnswerCorrect(yourAnswer))
            {
                score++;
                println("You got it right!");
            }
            else    // if its not correct, print you got it wrong
            {
                println("You got it wrong!");
                println(" ");
                println(" ");
            }

            // print question 2
            println(q[1].PrintQuestion());

            // input answer for question number 2
            String yourAnswer2 = readLine("Your answer: ");
            println(" ");

            // check if the question 2 is correct, if it is, add 1 to the score++
            if (q[1].IsAnswerCorrect(yourAnswer2))
            {
                score++;
                println("You got it right!");
            }
            else    // if its not correct, print you got it wrong
            {
                println("You got it wrong!");
                println(" ");
                println(" ");
            }

            // print question 3
            println(q[2].PrintQuestion());

            // input answer for question number 3
            String yourAnswer3 = readLine("Your answer: ");
            println(" ");

            // checking for hard question. To make it easier, we're using boolean to check for the hard question
            boolean hardQuestion = false;

            // check if the question 3 is correct, if it is, add 1 to the score++ // hard question becomes true
            if (q[2].IsAnswerCorrect(yourAnswer3))
             {
                score++;
                println("You got it right!");
                println(" ");
                hardQuestion = true;
             }
             else
             {
                println("You got it wrong!");
                println(" ");
                println(" ");
             }
             if (score == 0)
             {
                 println("You need more practice!");
                 println(" ");
             }

             // if you got at least the hard one right, your score is of 1 and that is what gets printed out
             else if (score == 1)
             {
                 if (hardQuestion)
                 {
                     println("Well, at least you got the hard one correct! ");
                     println(" ");
                 }
                 else
                 {
                     // if the other ones are correct, print out this message if hard is wrong
                     println("You need to warm up!");
                     println(" ");
                 }
             }

             // if you got at least two correct
             else if (score == 2)
             {
                 if (hardQuestion)
                 {
                     // user got one correct and hard one correct
                     println("You are amazing!");
                     println(" ");
                 }
                 else
                 {
                     // if hard one was wrong
                     println("You're on your way!");
                     println(" ");
                 }
             }
             else
             {
                 // all answers are correct including the hard ones
                 println("You are a scholar!");
                 println(" ");
                 println("Congradulations you passed! You got 100% on the quiz!");
                 break;
             }
                // count number of tries the quiz has been looped
                counter++;
                if (counter < 5)
                {
                    println("You scored less than 100%");
                    println(" ");
                    println(" ");
                    println("Try again!");
                    println(" ");
                }
            } while (true); // end program loop

            break;

        } while (true); // end while loop
}

} // closing public class


text:
Q: How do I remove this ugly border created inset shadow? How do I remove this ugly border created by a background totally overlapped by a inset shadow? Well, that was the idea anyway.

circle {
  display:block;
  text-decoration:none;
  border-radius:50%;
  width:100px;
  height: 100px;
  background: black;
  text-align:center;
  transition: all 0.8s ease-out;
  box-shadow:inset 0px 0px 0px 50px #ffd300;
  font-size: 0;
  z-index: -1;
  border: 10px solid #ffd300;
}

.circle:hover {
  box-shadow:inset 0px 0px 0px 0px #ffd300;
  transition: all 0.2s ease-out;
}

Code snippet over at Codepen

A: There is no solution to the actual rendering. (See below the solution for the explanation).
On the contrary, I've played and found a fix for you, which might do the exact thing, by placing an :after pseudo element to mimic the animation exactly as you want it to be.
Click on the "Run code snippet" button below to see if this is exactly what you want.

.circle {
  display:block;
  text-decoration:none;
  border-radius:50%;
  width:120px;
  height: 120px;
  background: #ffd300;
  text-align:center;
  transition: all 0.8s ease-out;
  font-size: 0;
  z-index: -1;
}

.circle:before {
  display:block;
  content:'';
  position:absolute;
  background:black;
  width:0px;
  height:0px;
  border-radius:50%;
  top:68px;
  left:68px;
  transition: all 0.2s ease-out;
  overflow:hidden;
  z-index: 0;
}

.circle:hover:before {
  width:100px;
  height:100px;
  top:18px;
  left:18px;
  font-size: 48px;
}

.circle:after {
  display:block;
  position:absolute;
  font-size: 48px;
  line-height: 90px;
  color: black;
  transition:  color 0.2s ease-out;
  content: "J";
  z-index: 1;
  top:18px;
  left:58px;
}

.circle:hover:after {
    color: white;
    transition:  color 0.1s ease-out;
}
Click

Explanation to the problem
 I've pasted two images of how they are rendered in Webkit (Chrome) and Gecko (Firefox). The shadow is getting pixelated along the edges if it is curved. The same phenomena also happens while drawing a curve.

Image 1, ChromeIt is a 500px x 500px of the same code that you used, just to magnify the effect that we are talking about. You can see those weird ugly border in a better view. Now, try reducing border-radius:50%; to a 20%, 10% or 0%, you will slowly see those ugly marks disappearing. As pixels are square themselves, it renders perfectly in case of a rectangular shape / with straight line edges.

Image 2, FirefoxIn the second image, you can see how Firefox renders the same object (500px x 500px), and adds a secondary unknown border along the outside edge of the circle, which is actually the background:black, going out of the 10px border as well (proof: Change the background to #ffd300 and it will disappear).

To conclude, this aliasing phenomenon is a rendering issue currently for both the major browser engines, though its minimized in actual rendering of the circular object itself, but its more prominent in case of shadows or other things which blurs / blends with other colors. It is not a problem with your code though.

A: The shape has a background color of black, a 10px outside border of yellow, and a 50px inside border of yellow. This seems to be so that when you hover, it will change the inside of the circle to red.
To get rid of the little sliver completely, you could just change .circle's background to #ffd300 (or whatever).
This breaks the animation, however, so you might want to add background:black to .circle:hover.

A: You can change your CSS to this:
.circle {
  display:block;
  text-decoration:none;
  border-radius:50%;
  width:100px;
  height: 100px;
  background: #ffd300;
  text-align:center;
  transition: all 0.8s ease-out;
  box-shadow:inset 0px 0px 0px 50px #ffd300;
  font-size: 0;
  z-index: -1;
  border: 10px solid #ffd300;
}

.circle:hover {
  box-shadow:none;
  background: black;
  transition: all 0.2s ease-out;
}

Basically, move the back background to hover state and get rid of the box-shadow. Of course you'll have the border on hover, because it goes with your approach, but at least you won't have the border on default state.
Remember that you can use multiple box-shadows by simply separating them with a comma, but either way, no matter how many you add, you will have this border because the border-radius:50% will add it. For reference, try taking the border-radius definition out and you'll see that border disappear.
In short: the only way to get rid of that border at all times, is to use 2 elements: an outer div with background color #ffd300 and an inner div with background color #000 and the J, otherwise you'll have that border, it's just how CSS works

A: if you add to the CSS a border-width: 0px;. See http://www.w3schools.com/cssref/pr_border-width.asp


text:
Q: Getting an object with a variable. -javascript- var i = "test";
var test1 = {
    test: 3,
    b: 3
};
console.log(test1.i);

Sorry if it's a simple answer, I am still learning.
var i is looping to something different every few seconds and var i will always be something on test1.

A: Do it this way:
var test1 = {
    test : 3
};
console.log(test1[i])

A: If you are trying to retrieve a property of an object you can use the . notation, or the [] notation
var test1 = {
    test: 3,
    b: 3
};

Using . notation
test1.test;       // -> returns 3

Using [] notation
var propertyName = 'test'
test1[propertyName];       // -> returns 3


text:
Q: Custom (group-)sorting of column in Datatables I'm trying to understand the custom sorting mechanism in Datatables. What I'm trying to do is sorting a column according to its value and the value of other columns (conatining a group) to get groupwise sorting.
To do this I came accross the sorting plugin: https://datatables.net/plug-ins/sorting/
Just as an example (could be another) I had a look at the "anti-the" plugin. To actvate it I added:
targets = "_all", type = "anti-the"

to the columnDefs
and used
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
    "anti-the-pre": function ( a ) {
        console.log("pre");
        return a.replace(/^the /i, "");
    },

    "anti-the-asc": function ( a, b ) {
        console.log("asc");
        return ((a  b) ? 1 : 0));
    },

    "anti-the-desc": function ( a, b ) {
        console.log("desc");
        return ((a  b) ? -1 : 0));
    }
} );

The plan is to adapt these three functions to get the desired grouped sorting.

*

*Interestingly "pre" is printed to the console everytime when the table header is clicked (and the table is resorted). I expected "asc" and "desc" to be printed as well (in alterning order) but nothing is printed, why?

*Is this the right approach to get the desired result of grouped sorting or do I need to define my own "orderDataType" to reach this?
Edit:
Just to make things a bit clearer:
Let's assume I have a table containing the information/columns about "department" and "floor" When sorting "floor" I'd like it to be sorted for floor for every department
before sorting:
|department|floor|
|IT|2|
|IT|1|
|Sales|1|
|Sales|2|
after click on header ("floor" -> asc)
|IT|1|
|IT|2|
|Sales|1|
|Sales|2|
click again (desc)
|IT|2|
|IT|1|
|Sales|2|
|Sales|1|
in the data I have there ist no mix between groups (here: departments) -> rows for the same department will be next to each other

A: As you are trying to do a groupwise sorting of your data i would recommend you use datatables "orthagonal data" in combination with HTML5 data-* attributes
As you can read here (Datatables Website - Orthagonal Data  - HTML5) using the custom attribute data-order should be your weapon of choice.
For example:
You want to group department and floor but only show department to the user. This example should show you the desired output
(The floornumber in the surname cell is a helper to visualise the right ordering and can be removed)

            Department	Surname

            IT	 Daniel (1)

            sales	 Sue (2)

            IT	 John (1)

            IT	 Mr. Miyagi (2)

            sales	 Mel (2)

            sales	 Marc (1)

Edit:
The sorting in the first example would be wrong for floors 10 and above. It would be 1, 10, 2, 3, 4 and so on because datatables would strictly sort the string.
To address this issue there is a sorting plugin called natural sorting on the datatables website. Including this code and adding { columnDefs: [ { type: 'natural' , targets: 0 } ] } to the tabledefinition will fix the sorting to a more human way.


text:
Q: how to pass data from one function to another in component.ts , angular2 hi am passing some values on button click "data.someid" i want to get this "data.someid" in another button click
html
---
<button (click)="click1(data.someid)"></button>
<button (click)="click2()"></button>

component.ts
click1(data){
   this.value = data
}
click2(){
  console.log(this.value)
}

Now am storing retrieved data into this.value on "click1" , and i want to access it in the another button click , but console.log(this.value) showing undefined
please someone tell me how to access it.

A: You should add type="button" to your button elements,
<button type="button (click)="click1(data.someid)"></button>

otherwise the buttons inside the forms will be by default type=submit like you were submitting a form. That is why this refers to something else inside your click scope.

A: Have you declared the variable as local variable inside class? And make sure that you clicked first button before second one.
export class SomeClass {
  value: any;

  click1(data){
    this.value = data
  }
  click2(){
    console.log(this.value)
  }
}


text:
Q: PowerShell Bulk update Active Directory Managers field I'm trying to update our managers field in our active directory and have a script
the input file looks like this
Firstname.LastnameEmployee;firstname.lastnameManager

Here is the script I'm using...
This is the error I'm getting

You cannot call a method on a null-valued expression.
  At line:26 char:5
  +     $ObjSearchemployee.Filter = "(&(objectCategory=person)(objectClass=user)(sAM ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
      + FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
  At line:31 char:9
  +         $ObjSearchmanager.Filter = "(&(objectCategory=person)(objectClass=user)( ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
      + FullyQualifiedErrorId : InvokeMethodOnNull

###############################################################
# Update_Manager_v1.0.ps1
# input : n/a
# output : none (logs)
# Version 1.
# Changelog : n/a
# MALEK Ahmed - 02 / 06 / 2013
###################

##################
#--------Config
##################
$adPath="LDAP://DC=local,DC=com"

##################
#--------Main
##################
#LDAP connection
$objDomain=New-Object System.DirectoryServices.DirectoryEntry($adPath)
#Doing an LDAP search
$ObjSearchemployee=New-Object System.DirectoryServices.DirectorySearcher($ObjDomain)
$ObjSearchmanager=New-Object System.DirectoryServices.DirectorySearcher($ObjDomain)
#Operations on user accounts
Import-Csv .\input.csv -Delimiter ';' | Foreach-Object {
    $ObjSearchemployee.Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName="+ $_.employee.trim() +"))"
    $allSearchResultemployee = $ObjSearchemployee.FindAll()
    foreach ($objSearchResultemployee in $allSearchResultemployee)
    {
        $objUseremployee=New-Object System.DirectoryServices.DirectoryEntry($objSearchResultemployee.Path)

        $ObjSearchmanager.Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName="+ $_.manager.trim() +"))"
        $allSearchResultmanager = $ObjSearchmanager.FindAll()
        foreach ($objSearchResultmanager in $allSearchResultmanager)
        {
            $objUsermanager=New-Object System.DirectoryServices.DirectoryEntry($objSearchResultmanager.Path)
            $objUseremployee.manager = $objUsermanager.distinguishedname
        }
        $objUseremployee.CommitChanges()
        "" + $objUsermanager.displayName + " is now the manager of " + $objUseremployee.displayName + ""
    }
}

A: $.Employee.trim() is the problem since you do not have a column header of "Employee" as per your source example. See You cannot call a method on a null-valued expression.
Assuming your first column is for the samaccountname then you should change that to $_.Firstname.LastnameEmployee.trim() else you need to redefine how your search is being done or update your source file to contain the relevant information and get your code to match.
As the error suggests you will have the same problem with $_.Manager.trim()


text:
Q: Vertex AI forecasting AutoML giving different answers for same input data I trained Vertex AI forecasting AutoML model one with target column as String and other numeric input features as String then I trained another AutoML model with target column as float and other input features as Integer.
The predictions are different for both the models. The data is same only the datatypes/schema changed.
Google documentation says:

When you train a model with a feature with a numeric transformation,
Vertex AI applies the following data transformations to the feature,
and uses any that provide signal for training:

*

*The value converted to float32.

So both the data should be same even after transformation.
Why would results be different? Is it possible?

A: I have follow the steps to have a forecasting model as show on Build an AutoML Forecasting Model with Vertex AI and reach the conclusion that vertex AI compress a lot of the steps of the prediction model generation so it can be easily operate by users.
I think the most reasonable answer for your observation among strings and numeric values resides in the way data processing is performed to generate our prediction models. I think you will not find inside vertex AI documentation as it would mean to disclose how vertex AI code works and handles its Feature Engineering and train steps to generate the models, which is protected.
Regardless, Lets speculate a bit, I think the difference among datatypes conversion might occur when datatype is converted and passed to the algorithm for processing. Lets said a linear regression sample, you will find that the slightest variation on data conversion can affect the outcome of your prediction model which could also be what is happening here.


text:
Q: WP All Import - Using Xpath to set a select value I'm working on setting up an import using WP All Import, the idea is to update/add/remove posts within a custom post type which contain ACF fields.
The CSV we are importing contains a column called "Feed ID" which holds data like Apple12343, Banana98799, Carrot2198379, Onion1287361 and so on.
What I want to achieve is to populate an ACF select box value that has options like 'Fruit' and 'Vegetable', depending on the Feed ID value, using XPath. So essentially I need some sort of function that will take the first part of the feed ID (letters only), then assign the select box value based on that. Is this doable?

A: Looks like you can use the Variable Repeater Mode (CSV) to import your data:

If your repeating data is stored in a single column in your CSV file, and is separated by a separator character, use this option.

Then create a custom PHP function that would break up each value into the title and ID (Apple => 12343, etc.) and call your function from the text box:
[custom_function({feed_id[1]})]

As for the last part of actually creating a select box from titles and IDs - I don't know how to do that. Hopefully someone can build on this answer. Also please share if you figured it out.


text:
Q: Start video playback NOT enter full screen When I watch videos in Safari sometimes I want to stop the video and go to another tab, then I come back to the video and click on it to start the playback. But instead of the video starting I go to full screen. How do I stop this behavior?

A: I have discovered that I can go to full screen with a double click. If the double click speed is too fast it won't do it so there has to be a couple seconds between clicks, so I think that what is happening is that I am clicking the tap where the video is and then clicking in the screen and the time between the two clicks is the right amount to put me in full screen. Now that I know this I can do another double click to exit full screen. I would still like to be able to disable tis if anyone knows how to do it.


text:
Q: Matlab : Copy Excel Sheet and Save Workbook I would like to copy multiple sheets from an existing workbook to a new one.
Here is my code, I can copy the sheets but I am not able to save the workbook properly.
In my following code, I copy the first three sheets and save the workbook but when I open it, it is empty. I think my workbook handle is wrong.
Excel = actxserver('Excel.Application');
Excel.Visible = true;

WB = invoke(Excel.Workbooks,'open','C:\Example.xlsx');
SHS = WB.Sheets; %sheets of template Workbook
SH = WB.Worksheets.Item(3);
invoke(SH,'Copy');
SH = Excel.ActiveSheet;
SH1 = WB.Worksheets.Item(2);
SH2 = WB.Worksheets.Item(1);
invoke(SH2,'Copy',SH);
invoke(SH1,'Copy',SH);
SH = Excel.ActiveSheet;
nWB = Excel.ActiveWorkbook;
nWB.SaveAs('C:\TEST.xlsx',1)
Excel.Quit()

A: For horizontal concatenation of sheets
Step 1: Make one cell array containing repetitions of your filename (same number as number of sheets you want to combine), and one cell array with numbers of the sheets. Then use cellfun to read all sheets.
Step 2: Define from which column you would like to write data. The first sheet you read should be written from column 'A' I suppose. You probably want to start on the first line, so range is 'A1' first time (i.e. k = 1) you write data to your new file. For k > 1 it's a bit more tricky. You need to keep to track on the number of columns of all sheets you read, in order to know where the new range will be when you write sheet 2, 3, ... , n in your new file. Convert your count to Excel column names. This can be done with the char command. Make sure to take care of the wrapping (After Z comes AA).
Solution:
% STEP 1
n = 3; %number of sheets you want to combine
filename = strcat(cell(1,n), 'C:\Example.xlsx');
sheets = num2cell(1:n);
combinedSheets = cellfun(@xlsread,filename, sheets,'un',0);

% STEP 2
range = {'A1'};
cols = 0;
for k = 1:n
    xlswrite('C:\TEST.xlsx',combinedSheets{k},1, cell2mat(range))
    cols = cols + size(combinedSheets{k},2);
    q = floor(cols/26);
    d = mod(cols,26);
    range = strcat(cell(1,q+1), 'A');
    range{end} = [char(d+'A'),'1'];
end

For vertical concatenation of sheets
This is a bit simpler as we do not need to handle column names and wrapping etc.
Solution:
n = 3; %number of sheets you want to combine
filename = strcat(cell(1,n), 'C:\Example.xlsx');
sheets = num2cell(1:n);
combinedSheets = cellfun(@xlsread,filename, sheets,'un',0);

range = 'A1';
rows = 1;
for k = 1:n
    xlswrite('C:\TEST.xlsx',combinedSheets{k},1, range)
    rows = rows + size(combinedSheets{k},1);
    range = sprintf('A%s', num2str(rows));
end


text:
Q: HttpRequest.GetBufferlessInputStream not supported Running an MVC5 application I get this error when attempting to POST back to my controller.
I is happening during the EnsureFiles() method, but I'm not trying to load any files at all.
Here is the entire stack traces
[HttpException (0x80004005): This method or property is not supported after HttpRequest.GetBufferlessInputStream has been invoked.]
System.Web.HttpRequest.EnsureFiles() +3274885
System.Web.HttpRequest.get_Files() +12
System.Web.HttpRequestWrapper.get_Files() +28
System.Web.Mvc.HttpFileCollectionValueProvider.GetHttpPostedFileDictionary(ControllerContext controllerContext) +120
System.Web.Mvc.HttpFileCollectionValueProvider..ctor(ControllerContext controllerContext) +51
System.Web.Mvc.HttpFileCollectionValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +117
System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +160
System.Web.Mvc.ControllerBase.get_ValueProvider() +85
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +154
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +199
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +1680
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +59
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +94
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +559
System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +82
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +105
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +588
System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +47
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +65
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +139
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +484
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +98
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +106
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +446
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

My form is embarrassingly simple
@using (Html.BeginForm())
{

    In order to continue you must change your password.

    @Html.LabelFor(x=> Model.OldPassword)
    @Html.TextBoxFor(x=> Model.OldPassword)

    @Html.LabelFor(x => Model.NewPassword)
    @Html.TextBoxFor(x => Model.NewPassword)

    @Html.LabelFor(x => Model.NewPasswordConfirm)
    @Html.TextBoxFor(x => Model.NewPasswordConfirm)

    <input type="submit" class="btn btn-primary" value="Submit" />
    <input type="reset" class="btn btn-danger" value="Cancel" />

}

Has anyone encountered this problem before.  I got a couple of hits on the internet, but nothing that worked.

A: answer to this was turning off HttpLogging in Thinktecture IdSrv.
LoggingOptions = new LoggingOptions
{
  **EnableHttpLogging = false**,
  EnableWebApiDiagnostics = true,
  IncludeSensitiveDataInLogs = true,
  WebApiDiagnosticsIsVerbose = true,
},

A: I also got this error when adding Azure Active Directory authentication to an MVC web app that previously had no authentication.
When I moved the code below in Startup.cs from after the MVC and Web API configuration code to before it, the exception stopped occurring.
    // Microsoft Azure Active Directory
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
    app.UseCookieAuthentication(new CookieAuthenticationOptions());
    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            ClientId = appSettings.IdaClientId,
            Authority = appSettings.IdaAuthority,
            PostLogoutRedirectUri = appSettings.IdaPostLogoutRedirectUri
        });


text:
Q: Factoring ideal into prime ideals in $\mathbb{Z}[\sqrt{-5}]$ I would like to write the ideal $(9)$ as a product of prime ideals in $\mathbb{Z}[\sqrt{-5}]$, which is a Dedekind domain. We have
$$9=3 \cdot 3=(2+\sqrt{-5})\cdot (2-\sqrt{-5}) $$
and I have shown that $3,2+\sqrt{-5},2-\sqrt{-5}$ are irreducible and not prime.
I can see that $(3)$ is not a prime ideal because $(2+\sqrt{-5}) (2-\sqrt{-5})=9 \in (3)$, but $2+\sqrt{-5},2-\sqrt{-5}\notin (3)$.
I am not sure what to do next.

A: This is exactly the situation that the Dedekind-Kummer theorem treats. This is given in the following two theorems from Keith Conrad's Factoring after Dedekind.
Theorem 1 (Dedekind). Let $K$ be a number field and $\alpha \in O_K$ such  that $K= \mathbb{Q}(\alpha)$. Let $f(T)$ be the minimal polynomial of $\alpha$ in $\mathbb{Z}[T]$. For any prime $p$ not dividing $[O_K:\mathbb{Z}[\alpha]]$, write
$$
f(T) \equiv \pi_1(T)^{e_1}\cdots \pi_g(T)^{e_g} \pmod{p}
$$
where the $\pi_i(T)$ are distinct monic irreducibles in $\mathbb{F}_p[T]$. Then $ (p) = p O_K$ factors into prime ideals as
$$
\newcommand{\p}{\mathfrak{p}}
(p) = \p_1^{e_1} \cdots \p_g^{e_g}
$$
where there is a bijection between the $\p_i$ and $\pi_i(T)$ such that $N(\p_i) = p^{\deg(\pi_i)}$. In particular, this applies for all $p$ if $O_K=\mathbb{Z}[\alpha]$.
He further describes how to obtain generators for the $\p_i$ in Theorem 8.
Theorem 8. In the notation of Theorem 1, when $\p_i$ is the prime ideal corresponding to $\pi_i(T)$ we have the formula $\p_i = (p,\Pi_i(\alpha))$ where $\Pi_i(T)$ is any polynomial in $\mathbb{Z}[T]$ that reduces mod $p$ to $\pi_i(T)$ mod $p$.
Returning to your problem, the minimal polynomial of $\sqrt{-5}$ is $T^2 + 5$. How does this factor mod $3$? What does this tell you about the primes ideals in the factorization of $(3)$ and their generators?


text:
Q: Converting date and/or time from character string causes error I have an update statement below that is auto generated when executing a proc:
BEGIN TRAN
UPDATE Core.Config
SET    Value = 'Insert',
       ModifiedBy = 'HARROGATE\Name',
       DeletedDate = '0'
WHERE  ConfigID = '1'
       AND Value = 'Update'
       AND ModifiedBy = 'HARROGATE\Name'
       AND DeletedDate = '0'
IF @@ROWCOUNT <> 1
  BEGIN;
      THROW 99999, 'Error - Single Row not updated, rollback terminated', 1;
  END;
COMMIT TRAN

-- now update the [Core].[TaskChangeLog] to confirm rollback....

UPDATE Tcl
SET    [Hasbeenrolledback] = 1,
       [Rollbackdate] = 'Jan  5 2016  9:21AM',
       tcl.Comments = Tcl.comments + ' Rollback by HARROGATE\Name'
FROM   [Core].[TaskChangeLog] Tcl
       INNER JOIN Core.TaskLog Tl
               ON Tcl.TaskLogID = Tl.TaskLogID
WHERE  Tl.TaskID = 'ABC123_New'
       AND Tcl.TaskChangeLogID = Isnull(58, Taskchangelogid)

However I receive the following error when I try to execute the update stating:

Conversion failed when converting date and/or time from character
  string.

I think it is the 'DeletedDate' that is causing the issue but I am not too sure. Where and why in my code is causing this error?
Code:
MERGE Core.Config AS Tgt
USING (SELECT @ConfigKey,
              @Value,
              @Deleted) AS Src (ConfigKey, Value, Deleted)
ON (Tgt.ConfigKey = Src.ConfigKey)
WHEN MATCHED THEN
  UPDATE SET Value = Src.Value,
             DeletedDate = Iif (@Deleted = 1, GETUTCDATE(), NULL),
             ModifiedBy = SUSER_SNAME(),
             ModifiedDate = GETUTCDATE()
WHEN NOT MATCHED THEN
  INSERT (ConfigKey,
          Value,
          AddedBy,
          ModifiedBy)
  VALUES (@ConfigKey,
          @Value,
          SUSER_SNAME(),
          SUSER_SNAME())
OUTPUT 'Core.Config',
       'ConfigID',
       inserted.ConfigID,
       Iif($action = 'Update', Core.Updxmlfragment('Value', inserted.Value, deleted.Value) + Core.Updxmlfragment('ModifiedBy', inserted.ModifiedBy, deleted.ModifiedBy) + Core.Updxmlfragment('DeletedDate', inserted.DeletedDate, deleted.DeletedDate ), Core.Insxmlfragment('ConfigID') + Core.Addnlxmlfragment ('ModifiedBy', inserted.ModifiedBy))

UPDATE - as asked by a user, pasted the updXMLfragment below:
IF (@InsertedValue = '')
  BEGIN
      SET @InsertedValue = ' '
  END

IF(@DeletedValue = '')
  BEGIN
      SET @DeletedValue = ' '
  END

IF(@FieldName IS NULL)
  --if(@InsertedValue IS NULL and @DeletedValue IS NULL or @FieldName IS NULL) -- pre v2.1 logic
  BEGIN
      -- This "errors" the function and ensures the script doesn't get any further than the update
      RETURN CONVERT(INT, 'NULL Params passed for XML Fragment Generation')

  END

-- Validate the date has the correct "time" element associated - i.e HH:MM:SS:MSS
IF (@FieldName LIKE '%date%')
  BEGIN

    IF((TRY_PARSE(@InsertedValue as datetime) IS NOT NULL) OR (TRY_PARSE(@DeletedValue AS datetime) IS NOT NULL))
        BEGIN
            IF((LEN(REPLACE(@DeletedValue, ':', '')) +3 <> LEN(@deletedvalue)) OR (LEN(REPLACE(@InsertedValue, ':', '')) +3 <> LEN(@InsertedValue)))
                BEGIN
                    -- This "errors" the function and ensures the script doesn't get any further than the update
                    RETURN CONVERT(DATETIME, 'Invalid Date Params passed for XML Fragment Generation')
                END
        END
  END

A: I assume that DeletedDate is DATETIME type, than update DeletedDate='0' will fail on conversion.
If you intend on updating to NULL use DeletedDate = NULL.
Also in condition you should not use DeletedDate='0'. If searching for null value use DeletedDate IS NULL.


text:
Q: Why are the "Use" declaration lines of code disappearing?! Magento2 I am adding a new PHP file to an existing Controllers folder. I am trying to insert the same "use" declarations into my new file as in the other existing controller files within this same folder.
When I try to copy over the use declarations into my file and then press save the "use" declaration code disappears!
Here's the use statements I am trying to insert that disappears when I hit save:
use \Mobileplans\Api\Data\VirtualnumbersInterface;
use \Mobileplans\Api\VirtualnumbersRepositoryInterface as VirtualnumbersRepository;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;

The only use declaration code block that saves to this new file without disappearing is:
use Magento\Backend\App\Action\Context;

A: The cause for the use statements disappearing was that my IDE was cleaning out any use statements that were not being used in my file.
Once I added code that utilized the class I was trying to use, the use statement stopped disappearing.

A: Everything outside of a pair of opening and closing tags is ignored by the PHP parser which allows PHP files to have mixed content. This allows PHP to be embedded in HTML documents.
blog


text:
Q: 2 way binding is not working properly in vuejs I have defined a vuejs component this way:
<template>
    <form @submit.prevent="submit">
        <textarea id="content" cols="30" rows="10" v-model="content">{{ content }}</textarea>

        <button class="btn btn-lg btn-success" type="submit" @click="send()">
            Send content
        </button>
    </form>
</template>

<script>
    export default {
        data() {
            return {
                content: '// Initial content'
            }
        },
        methods: {
            send() {
                console.log('Content', this.content);
            },
            submit() {
                return false;
            }
        },
        mounted() {
            console.log('Template init ', this.content);
        }
    }
</script>

When I click on send, the send method outputs the content of the textarea as expected. But when I change the content of the textarea with jquery:
$('#content').val(content);
and hit send, it doesn't update content in the template. "Send" outputs the old value.
can somebody please explain to me what's wrong here?

A: v-model is listening for an input event to trigger changing the value of its bound variable.
From the vue.js documentation:

v-model internally uses different properties and emits different
events for different input elements:

*

*text and textarea elements use value property and input event;

*checkboxes and radiobuttons use checked property and change event;

*select fields use value as a prop and change as an event.

Using the JQuery val() method to select the element and change the value does not trigger an event that v-model is listening for, so the value of your bound variable does not change/update.
If you absolutely have to use JQuery to change the content, you could manually trigger an event that might also trigger the v-model binding to update:
$('#content').val(content).trigger('input');


text:
Q: Confidence interval for the mean of a bounded non stationary random variableb given N samples I have a random variable bounded on [0,1].
The mean can be modeled as a random process. Assume the change of the mean |mu_i - mu_{i+1}| is bounded with a known bound.
Given N (N is not large) samples (X_1,..., X_N) I want to estimate the upper confidence bound on the mean.
I was unable to find anything in the literature and was hoping someone might have some pointers to relevant research :)

A: You have to look for the distribution of the difference between two consecutive samples pdf(|X_i - X_{i+1}). This distribution can be compared to analytically (if the probability density functions pdf are nice) or Monte-Carlo-generated distributions (if pdf is not so nice) with given bound called the expected distribution. You can use standard methods like a fitting routine to get the best matching bound and the corresponding confidence intervals. Here the low number of samples will challenge you. Here it is important to use the correct pdfs in advance for the construction of expected distributions, otherwise the calculation might give misleading results.
I call the former described approach the first order estimate, as you only use information of directly consecutive samples. However I assume more information is hidden in higher orders, e.g. the next-to-next sample and so on. The way is equivalent, but at the and you can fit multiple distributions simultaneous, which should lead to more accuracy.
I'm sorry that I cannot give you any pointers to research


text:
Q: Why when starting the game the script is turned off ? I need to turn it on after the game is running I have a prefab name bullet.
I dragged the prefab and put it under a weapon.
The script is turned on but when starting the game the script is turned off and I need to turn it on again.
In the screenshot the bullet prefab is in the middle. On the left in the hierarchy the bullet is under SciFiRifle(Clone) on the right in the Inspector on the bottom there is a script attached name Shooting.
The script is turn on.
But then when I'm running the game the script for some reason is turned off :
First for some reason I also need to collapse the SciFiRifle(Clone) to see the bullet again in the hierarchy :

And the script is turned off :

I can't figure out why it's hiding the bullet in the hierarchy and turning the script off when running the game.
The script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Shooting : MonoBehaviour
{
    public GameObject projectile;
    public Animator anim;

    private void Start()
    {
        anim.SetBool("Shooting", true);
    }

    private void Update()
    {
        if (anim.GetBool("Shooting") == true)
        {
            GameObject bullet = Instantiate(projectile, transform.position, Quaternion.identity) as GameObject;
            bullet.GetComponent<Rigidbody>().AddForce(transform.forward * 10, ForceMode.VelocityChange);
        }
    }
}

UPDATE :
I found what is making the problem. Not yet how to solve it.
The second child in the Hierarchy of Object is Sci-Fi_Soldier.
And to Sci-Fi_Soldier attached some scripts one of them is Player Controller it's not my script.
Some properties of this script in the Inspector get Right Gun what i assigned in to the Right Fun is the SciFiRifle(Clone) and the Bullet is child of SciFiRifle(Clone).
You can see it marked in yellow :

If I'm removing this script at all the Player Controller then the script Shooting on the Bullet will stay turned on and it will stay collapsed.
I can't figure out what making the problem in the Player Controller script :
using UnityEngine;
using System.Collections;

[RequireComponent (typeof (Animator))]
public class PlayerController : MonoBehaviour {

    public Transform rightGunBone;
    public Transform leftGunBone;
    public Arsenal[] arsenal;

    private Animator animator;

    void Awake() {
        animator = GetComponent<Animator> ();
        if (arsenal.Length > 0)
            SetArsenal (arsenal[0].name);
        }

    public void SetArsenal(string name) {
        foreach (Arsenal hand in arsenal) {
            if (hand.name == name) {
                if (rightGunBone.childCount > 0)
                    Destroy(rightGunBone.GetChild(0).gameObject);
                if (leftGunBone.childCount > 0)
                    Destroy(leftGunBone.GetChild(0).gameObject);
                if (hand.rightGun != null) {
                    GameObject newRightGun = (GameObject) Instantiate(hand.rightGun);
                    newRightGun.transform.parent = rightGunBone;
                    newRightGun.transform.localPosition = Vector3.zero;
                    newRightGun.transform.localRotation = Quaternion.Euler(90, 0, 0);
                    }
                if (hand.leftGun != null) {
                    GameObject newLeftGun = (GameObject) Instantiate(hand.leftGun);
                    newLeftGun.transform.parent = leftGunBone;
                    newLeftGun.transform.localPosition = Vector3.zero;
                    newLeftGun.transform.localRotation = Quaternion.Euler(90, 0, 0);
                }
                animator.runtimeAnimatorController = hand.controller;
                return;
                }
        }
    }

    [System.Serializable]
    public struct Arsenal {
        public string name;
        public GameObject rightGun;
        public GameObject leftGun;
        public RuntimeAnimatorController controller;
    }
}

It's hiding the Bullet in the Hierarchy and also turning off the script Shooting. But the script Shooting is not used anywhere else in the Hierarchy or in any other scripts. But by trying removing scripts I found that this script is the one that make the problem with the Bullet.
This is the Inspector screenshot of SciFiRifle(Clone) :

A: The PlayerController script actually destroys your Sci-fi Rifle (the one you put in the prefab) and then instantiates a new one with the one provided in the Right Gun field of the PlayerController script (that is why you need to collapse it again, because what you see is a new instance of the rifle prefab).
The lines in the PlayerControllerthat describe this behaviour are:
                if (rightGunBone.childCount > 0)
                    Destroy(rightGunBone.GetChild(0).gameObject);

Which destroys the rifle you put in the prefab. And:
                if (hand.rightGun != null) {
                    GameObject newRightGun = (GameObject) Instantiate(hand.rightGun);
                    newRightGun.transform.parent = rightGunBone;

Which spawns a new instance of the prefab you provided in the Right Gun field, replacing the rifle you put in the prefab.
You could try: either removing the prefab from the PlayerController field or remove the Sci-fi Rifle from the prefab.


text:
Q: INSERT INTO + COMMIT in packages what is the best solution to write a oracle package for record persistence?
I've always written something like this:
    create or replace
    PACKAGE BODY           "USP_PRICELIST" AS

      PROCEDURE  usp_TABLE1Save
        (
        pErrorCode              OUT NUMBER,
        pMessage                OUT VARCHAR2,
        pPARAM1                 IN CHAR,
        pPARAM2             IN CHAR
        )

        IS

    BEGIN

        pErrorCode := 0;

        INSERT INTO TABLE1
          (PARAM1, PARAM2)
        VALUES
          (pPARAM1, pPARAM2);
        EXCEPTION
                 WHEN OTHERS THEN pErrorCode := SQLCODE; pMessage := SQLERRM;

    END usp_TABLE1Save;

END USP_PRICELIST;

and I was wondering if I have to COMMIT after the INSERT INTO.
Alberto

A: I would not put a commit in the procedure, and leave that to the code that calls the procedure.  This allows the procedure to be used as part of a larger transaction.  The insert is not implicitly committed.

A: It really depends on whether you want your operation to take part in a transaction or to be atomic.

A: Be careful, if you place the commit in the package it will commit the entire transaction
create table testcommit (colA varchar2(50)) ;

DECLARE
  PROCEDURE SELFCOMMIT(VAL IN TESTCOMMIT.COLA%TYPE) AS
                BEGIN
                     INSERT INTO TESTCOMMIT(COLA) VALUES(VAL);
                     COMMIT ;
                END SELFCOMMIT ;
  PROCEDURE NOCOMMIT(VAL IN TESTCOMMIT.COLA%TYPE) AS
                BEGIN
                     INSERT INTO TESTCOMMIT(COLA) VALUES(VAL);
                END NOCOMMIT ;

BEGIN
  INSERT INTO TESTCOMMIT(COLA) VALUES('INITIAL');
  SELFCOMMIT('FIRST SELF COMMIT');
  ROLLBACK ; --KILL TRANSACTION

  INSERT INTO TESTCOMMIT(COLA) VALUES('SECOND MAIN INSERT');
  NOCOMMIT('NO AUTO COMMIT');
  ROLLBACK;

END ;
/
SELECT * FROM TESTCOMMIT;

-->
COLA
--------------------------------------------------
INITIAL
FIRST SELF COMMIT
-->NOTE THE SELFCOMMIT AFFECTS THE ENTIRE TRANSACTION, THUS RENDERING THE ROLLBACK MOOT

--drop table testcommit;

A: You should also look at the concept of autonomous transactions

A: By default Oracle has no auto-commit, so you have to.