text:
Q: How to do remote ssh non-interactively I am trying to connect to a remote host from my local host through the below command.But there was a setting in the remote host that soon after we login it will prompt to enter a badge ID,password and reason for logging in, because it was coded like that in profile file on remote-host How can I overcome those steps and login directly non-interactively, without disturbing the code in profile.
jsmith@local-host$ ssh -t -t generic_userID@remote-host
Enter your badgeID, < exit > to abort:
Enter your password for <badgeID> :
Enter a one line justification for your interactive login to generic_userID

A: Small amendment: to overcome remote server expect approach is required, but in case local script connects to bunch of remote servers, which configuration may be broken, just use SSH options:
ssh -f -q -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null USER@TARGETSYSTEM

This will omit ask for password in case there is no ssh_key setup, exit silently and continue with script/other hosts.
Puts ssh to background with -f, which is required when calling ssh command from sh (batch) file  to remove local console redirect to remote input (implies -n).

A: Look into setting up a wrapper script around expect. This should do exactly what you're looking for.
Here are a few examples you can work from.

A: I have upvoted Marvin Pinto's answer because there is every reason to script this, in case there are other features in the profile that you need, such as Message of the Day motd.
However, there is a quick and dirty alternative if you don't want to make a script and you don't want other features from the profile. Depending on your preferred shell on the remote host, you can insist that the shell bypasses the profile files.  For example, if bash is available on the remote host, you can invoke it with:
ssh -t -t generic_userID@remote-host bash --noprofile

I tested the above on the macOS 10.13 version of OpenSSH. Normally the command at the end of the ssh invocation is run non-interactively, but the -t flag allows bash to start an interactive shell.
Details are in the Start-up files section of the Bash Reference Manual.


text:
Q: ridge, lasso regression error in cv.glmnet and error in randomForest I am trying to run a ridge, lasso regression as well as randomForest model on the total replacement cost from a csv file.
This is what I did as follows:
data$TOTAL_REPLACEMENT_VALUE=log(data$TOTAL_REPLACEMENT_VALUE)
n_total=nrow(data)
n_train=round(n_total*0.7)
training_data=data[1:n_train,]
test_data=data[n_train+1:n_total,]
X_train_cost_model=model.matrix(TOTAL_REPLACEMENT_VALUE~TYPE,data=training_data)
X_test_cost_model=model.matrix(TOTAL_REPLACEMENT_VALUE~TYPE,data=test_data)
Y_train_cost=training_data[,"TOTAL_REPLACEMENT_VALUE"]
Y_test_cost=test_data[,"TOTAL_REPLACEMENT_VALUE"]

I proceed on to run a ridge and lasso regression via this:
install.packages("glmnet",dependencies = TRUE)
library(glmnet)
ridge_replacement_cost_model=cv.glmnet(X_train_cost_model,Y_train_cost,alpha=0,type.measure = "mse")
ridge_pred_replacement_cost=predict(ridge_replacement_cost_model,newx = X_test_cost_model,exact=TRUE,s="lambda.min")
lasso_replacement_cost_model=cv.glmnet(X_train_cost_model,Y_train_cost,alpha=1,type.measure = "mse")
lasso_pred_replacement_cost=predict(lasso_replacement_cost_model,newx = X_test_cost_model,exact=TRUE,s="lambda.min")

install.packages("randomForest")
library(randomForest)
rf_total_replacement_cost_model=randomForest(TOTAL_REPLACEMENT_VALUE~TYPE,                                                data=training_data,importance=TRUE)
rf_pred_replacement_cost=predict(rf_total_replacement_cost_model,test_data,type="class")

However, I encountered these errors
Error in glmnet(x, y, weights = weights, offset = offset, lambda = lambda,  :    number of observations in y (590) not equal to the number of rows of x (589)

Error in na.fail.default(list(TOTAL_REPLACEMENT_VALUE = c(18.126980599175,  :
  missing values in object

The first error occurred after running the ridge and lasso regression while the second error occurred after running the randomForest model. I understand there is a thread on similar issues but I do not understand where went wrong. Any help is really appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: vue router.push Uncaught (in promise) undefined I try to redirect to another route if user is logged in, but got this error.
Please help me!
Uncaught (in promise) undefined

I used JWT for authentication.
jwtLogin
loginJWT({commit}, payload) {
    return new Promise((resolve, reject) => {
        jwt.login(payload.userDetails.email, payload.userDetails.password)
            .then((response) => {
                if (response.data.user_data) {
                    router.push(router.currentRoute.query.to || '/')
                    localStorage.setItem('accessToken', response.data.access_token)

                    commit('updateUserInfo', response.data.user_data, {root: true})

                    commit('setBearer', response.data.access_token)

                    resolve(response)
                } else {
                    reject({message: 'Wrong Email or Password'})
                }

            })
            .catch(error => {
                reject(error)
            })
    })
},

After clicking the login button and reloading the page, then click the login button again, there are no errors.
An error occurs if the page is not refreshed after clicking the login button.

A: You get this error, cause you didn't handle the promise error.
Promises, if not handled well, can cause unpredictable errors (especially when mixed with unnecessary callback functions, which is not the case here).
I see two bigger mistakes in your code:

*

*the starting promise error/success is not handled (unhandled/uncaught promise error)

*you navigate away before/during the user login data is saved (router.push())
Both of them can throw you an error, even if you think you are already logged in.
Also, the if/then condition is not necessary inside promise chain, it can handle itself if done right.
Hopefully this pseudo code will help you better understand:
login(formdata)
  .then((response) => {
    // login response success,
    // save the userdata and token
    resolve(response) // or return(respone)
  })
  .then((response) => {
    // user data succesfully saved,
    // and you can do extra check on it
    // safe to navigate away
    resolve(reponse) // or return(respone)
  })
  .catch((error) => {
    // anything goes bad,
    // you land here with error message
    // handle the error
  })
  .finally(() => {
    // if finally() is supported by your login method
    // you can decide whats next,
    // the promise is fulfilled/rejected
  })

// other potential (and often made mistake) to do logic here:
// we are 'after' the login method, but not out of the woods yet
// the promise might be still be unresolved/unrejected = undefined

There are other ways to handle promises: async/await, try/catch
But I prefer to chain it, when the method is 'thenable'.
More elegant IMHO
Happy promises!


text:
Q: How to solve $\int \sqrt{1+\sin x}\, dx$? It's easy to get this:
$$\int \sqrt{1+\sin x}\, dx \\= \int \sqrt{ \sin^2{\frac{x}{2}} + \cos^2{\frac{x}{2}} + 2\sin{\frac{x}{2}}\cos{\frac{x}{2}}}\,\, dx  \\ = \int \left | \sin{\frac{x}{2}} + \cos{\frac{x}{2}} \right |\, dx \\= \sqrt{2} \int \left | \sin{\left ( \frac{x}{2} + \frac{\pi}{4} \right )} \right |\, dx$$
So, in fact, my question is how to solve the integrate $\int \left | \sin x \right| dx $.
Or how to deal with the integrate when have absolute in it?

A: As zkutch has given how to calculate with absolute value here is another approach
To avoid confusion its better to do this we have $$\int \frac{\cos x}{\cos x}\sqrt{1+\sin x}dx=\int \frac{\cos x dx}{\sqrt{1-\sin x}}=-2\sqrt{1-\sin x}+C$$
Here in above integral i had put $1-\sin x=t$ which gave answer easily

A: Hint: $|\sin x|=(-1)^n \sin x$ for $\pi n \leqslant x < \pi (n+1)$, where $n=0, \pm 1,\pm2, \cdots$.
To keep antiderivative continuous in $x=\pi (n+1)$ you need to solve
$$\left((-1)^{n+1}\cos x +C_n\right) \Big|_{x=\pi (n+1)}=\left((-1)^{n+2}\cos x +C_{n+1}\right)\Big|_{x=\pi (n+1)}$$
taking some $C=C_0$.


text: Q: How to read real time ECG data in Samsung Galaxy Watch 4 - Wear OS? I'm trying to access Samsung Galaxy Watch 4 real time ECG (eletrocardiogram) values using SensorManager and SensorEventListener in Android Studio. I tried to access it by sensor constant number (type_number) which references com.samsung.sensor.ecg and nothing was returned by this sensor. How can i access this ECG data via Android Studio?


text:
Q: Exclude using friendly_id? I want to run a controller query and exclude the current (self) record.  I can use this:
Model.where.not(slug: params[:id])

That works fine until you manage to pass the record id.
Is there a cleaner more direct way to do this?
UPDATE
I clarified my example.  I want to search where the id OR slug columns are not equal to the params[:id].  This also would have to chain after any normal scope or where query I run.

A: You can write this query
Model.where('slug <> :param_id or id <> :param_id', {param_id: params[:id]})

A: You can use or:
Model.where.not(slug: params[:id]).or(Model.where.not(id: params[:id]))

Or you can rewrite your query:
Model.where('slug <> :param_id or id <> :param_id', {param_id: params[:id]})


text:
Q: Python requests module url encode I'm trying to send json as a parameter thru a get method for an api, I found that the url to which it is hitting is little bit different from the original url. Some ":%20" text is inserted in between the url. Not sure why this difference is coming, Can someone help
Original URL: http://258.198.39.215:8280/areas/0.1/get/raj/name?jsonRequest=%7B%22rajNames%22%3A%5B%22WAR%22%5D%7D

My URL : http://258.198.39.215:8280/areas/0.1/get/raj/name?jsonRequest=&%7B%22rajNames%22:%20%22WAR%22%7D

Python code:
headers = {'Accept': 'application/json','Authorization': 'Bearer '+access_token}
json = {'rajNames':'WAR'}
url = 'http://258.198.39.215:8280/areas/0.1/get/raj/name?jsonRequest='
r = requests.get(url, params=json.dumps(json),headers=headers)
print _r.url

A: The spaces are not the problem; your method of generating the query string is, as is your actual JSON payload.
Note that your original URL has a different JSON structure:
>>> from urllib import unquote
>>> unquote('%7B%22rajNames%22%3A%5B%22WAR%22%5D%7D')
'{"rajNames":["WAR"]}'

The rajNames parameter is a list, not a single string.
Next, requests sees all data in params as a new parameter, so it used & to delimit from the previous parameter. Use a dictionary and leave the ?jsonRequest= part to requests to generate:
headers = {'Accept': 'application/json', 'Authorization': 'Bearer '+access_token}
json_data = {'rajNames': ['WAR']}
params = {'jsonRequest': json.dumps(json_data)}
url = 'http://258.198.39.215:8280/areas/0.1/get/raj/name'
r = requests.get(url, params=params, headers=headers)
print _r.url

Demo:
>>> import requests
>>> import json
>>> headers = {'Accept': 'application/json', 'Authorization': 'Bearer <access_token>'}
>>> json_data = {'rajNames': ['WAR']}
>>> params = {'jsonRequest': json.dumps(json_data)}
>>> url = 'http://258.198.39.215:8280/areas/0.1/get/raj/name'
>>> requests.Request('GET', url, params=params, headers=headers).prepare().url
'http://258.198.39.215:8280/areas/0.1/get/raj/name?jsonRequest=%7B%22rajNames%22%3A+%5B%22WAR%22%5D%7D'

You can still eliminate the spaces used in the JSON output from json.dumps() by setting the separators argument to (',', ':'):
>>> json.dumps(json_data)
'{"rajNames": ["WAR"]}'
>>> json.dumps(json_data, separators=(',', ':'))
'{"rajNames":["WAR"]}'

but I doubt that is really needed.


text:
Q: use csv values as a column in query in mysql I have some values/ids coming from external sources like logs that needs to be sanitized/type casted before use. So e.g. if I have values like this:
800, 776, 7803, 827, 91, 976, 908

I want to be able to perform some operation on each value in mysql. I was hoping to be able to do something like this:
Select myCol*10
FROM (SELECT (800, 776, 7803, 827, 91, 976, 908) as myCol from dual);

but it fails with an error

ERROR 1241 (21000): Operand should contain 1 column(s).

The closest query I could find that allowed selecting multiple rows was this. But that would require prefixing each value with UNION ALL SELECT e.g.
SELECT 1, 2, 3
UNION ALL SELECT 4, 5, 6
UNION ALL SELECT 7, 8, 9

Another option that could work is in memory table or even something like this. But those seems like overkill for something seemingly so simple.

A:
version: 5.7.30, max values are like 1000. – M-WaJeEh

Possible solution.

*

*Create service table which stores integers from 1 to 1000. You may create it in your database, in some service database, or even in mysql database.

*Use the next code (a pattern from the question used):
SELECT myCol*10
FROM ( SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(@arg, ',', numbers.num), ',', -1) as myCol
       FROM mysql.numbers
       WHERE numbers.num <= LENGTH(@arg) - LENGTH(REPLACE(@arg, ',', '')) + 1 ) source;

where @arg is placeholder for CSV string ('800, 776, 7803, 827, 91, 976, 908').
Of course, you may provide the amount of values in CSV into WHERE expression instead of commas counting.
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=0042c8c9e5ffe46eee7a57e628ef75f8


text:
Q: Problem with method in a class when called from another class I'm writing a simple scene graph to hold some objects so I can control the rendering and drawing of these objects in OpenGL. I have two classes, one called GameObject which defines the objects with certain parameters such as position and velocity as well as how to draw the object. It has a method called update() which is used to calculate any change in position and then calls the draw() to draw itself onto the screen.
Another class is called sceneNode. This class controls the data structure which I use to store the objects. This an instance of this class contains a pointer to a GameObject instance to allow me to access the data and a sceneNode has children of type sceneNode stored in a vector.
Each class works perfectly well on their own. I can add children to the scene graph etc and I can create a GameObject and tell it to draw itself and everything works as expected.
I then added a new method to sceneNode which is called render(), this method gets the pointer to gameObject and calls it's update function before calling render() on any children of the node.
The problem is: the update() method is called and the GameObject is drawn but it is always drawn in the same place and doesn't move despite having a velocity and change in position. Calling the update() function by using an instance of GameObject DOES draw the object and move the object around the screen. I've been staring at this code for hours and can't see what I'm missing. I'm still fairly new to the idea of pointers and calling methods from another class so I may have missed something obvious.
Here are the relevant methods:
GameObject.cpp:
The variables position, velocity etc are listed as protected.
void GameObject::update(){

for (int i = 0; i<3;i++){
    this->velocity[i] +=this->acceleration[i];
}
this->position[0] += this->velocity[0];
this->position[1] += this->velocity[1];
this->position[2] += this->velocity[2];

this->draw();
}

void GameObject::draw() {
glTranslatef(this->position[0], this->position[1], this->position[2]);

glBegin(GL_TRIANGLES);
for (int i = 0; i < this->num_tris; i++) {
    for (int j = 0; j <3 ; j++) {
        glVertex3fv(vertices[triangles[i].INDEXES[j]]);
    }
}
glEnd();
}

sceneNode.cpp:
void sceneNode::render(){
GameObject *go = new GameObject();
go = this->data;
//data is the name of the variable storing a pointer to a GameObject
go->update();
//update() is a method that redraws the object and calc's new position etc

if (hasChildren()) {    //if this node has children, render all of them aswell...
    for (int i = 0; i< this->node_tree.size(); i++) {
        this->node_tree.at(i).render();
    }
}

sceneNode.h:
This is how the GameObject pointer is set up in the sceneNode
Protected:
GameObject* data;

I'm lost as to why the position is not changing for the render() method but is for the update() method as they are both calling the same thing?
Thanks for any help

A: There are some big problems here.
GameObject *go = new GameObject();
go = this->data;

You're creating a new object and then you are forgetting the pointer to that object. This happens every time you call render, so you have tons of memory that you aren't using that grows with time. You can just say:
GameObject *go = NULL;

to create a pointer without allocating data to it.
You can also omit the this->foo everywhere. It's implied within all classes.
So although I can't see the error in this code, chances are it is elsewhere, since you're making mistakes with pointers like above. You probably have pointers pointing to things you're not drawing. If you look at the memory addresses of the things that are updating and the memory addresses of the things being updated in render(), they may actually be different. If they are then you know that you're not calling update on the same things you are drawing. To get a memory address look at the value of 'this' within a function call. Write them down and make sure they are the same as the objects you are drawing. The error is not in this code.

A: In SceneNode, when you assign this-> data to go, you are effectively setting go to null! take out that assignment or do this->data = new GameObject() instead of using go.


text:
Q: XLS0413 The property 'ItemsSource' was not found in type 'TreeView' I have the following MainPage.xaml  pasted in from the docs
<Page
    x:Class="jtUFlow.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:jtUFlow"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:controls="using:Windows.UI.Xaml.Controls"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Page.Resources>

    </Page.Resources>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Padding="100">
        <SplitView IsPaneOpen="True"
               DisplayMode="Inline"
               OpenPaneLength="296">
            <SplitView.Pane>
                <TreeView ItemsSource="{x:Bind DataSource}">
                    <TreeView.ItemTemplate>
                        <DataTemplate x:DataType="local:Item">
                            <TreeViewItem ItemsSource="{x:Bind Children}"
                                          Content="{x:Bind Name}"/>
                        </DataTemplate>
                    </TreeView.ItemTemplate>
                </TreeView>
            </SplitView.Pane>

            <StackPanel Grid.Column="1" Margin="12,0">

                <TextBlock Text="Your flavor selections:" Style="{StaticResource CaptionTextBlockStyle}"/>
                <TextBlock x:Name="FlavorList" Margin="0,0,0,12"/>
                <TextBlock Text="Your topping selections:" Style="{StaticResource CaptionTextBlockStyle}"/>
                <TextBlock x:Name="ToppingList"/>
            </StackPanel>
        </SplitView>
    </Grid>
</Page>

I get build errors
Unknown member 'ItemsSource' on element 'TreeView'
XLS0413 The property 'ItemsSource' was not found in type 'TreeView'.
XDG0012 The member "ItemsSource" is not recognized or is not accessible.
XDG0012 The member "ItemTemplate" is not recognized or is not accessible.
XLS0415 The attachable property 'ItemTemplate' was not found in type
XLS0413 The property 'ItemsSource' was not found in type 'TreeViewItem'.

intellisense also warns
the member itemsource is not recognised or accessible.

The datasource is given by
using System.Collections.ObjectModel;
using Windows.UI.Xaml.Controls;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace jtUFlow
{

    public sealed partial class MainPage : Page
    {
        private ObservableCollection<Item> DataSource = new ObservableCollection<Item>();

        public MainPage()
        {
            this.InitializeComponent();
            DataSource = GetDessertData();
        }

        private ObservableCollection<Item> GetDessertData()
        {
            var list = new ObservableCollection<Item>();
            Item flavorsCategory = new Item()
            {
                Name = "Flavors",
                Children =
            {
                new Item() { Name = "Vanilla" },
                new Item() { Name = "Strawberry" },
                new Item() { Name = "Chocolate" }
            }
            };
            Item toppingsCategory = new Item()
            {
                Name = "Toppings",
                Children =
            {
                new Item()
                {
                    Name = "Candy",
                    Children =
                    {
                        new Item() { Name = "Chocolate" },
                        new Item() { Name = "Mint" },
                        new Item() { Name = "Sprinkles" }
                    }
                },
                new Item()
                {
                    Name = "Fruits",
                    Children =
                    {
                        new Item() { Name = "Mango" },
                        new Item() { Name = "Peach" },
                        new Item() { Name = "Kiwi" }
                    }
                },
                new Item()
                {
                    Name = "Berries",
                    Children =
                    {
                        new Item() { Name = "Strawberry" },
                        new Item() { Name = "Blueberry" },
                        new Item() { Name = "Blackberry" }
                    }
                }
            }
            };

            list.Add(flavorsCategory);
            list.Add(toppingsCategory);
            return list;
        }

        // Button event handlers...
    }

    public class Item
    {
        public string Name { get; set; }
        public ObservableCollection<Item> Children { get; set; } = new ObservableCollection<Item>();

        public override string ToString()
        {
            return Name;
        }
    }

}

The only Nuget package I have installed is
Microsoft.NETCore.UniversalWindowsPlatform v6.1.9

My configuration is Debug x86 with build and deploy checked
Min and Target version is 17134
My operating system is Windows 10 version 1803 17134.376
[Update]
I see the docs do mention that Windows.UI.XamlControls namespace has the ItemsSource property.  The namespace is in Windows.UI.Xaml.Controls.dll, Windows.dll
However when I look at the metadata for TreeView I see the assembly is Windows.Foundation.UniversalApiContract

Intellisense thinks that I am using Windows.UI.Xaml.Controls.Treeview yet the using appears not needed

[Update]
The SDK is showing the wrong version

Editing the version in the project file causes errors
I am re-upgrading
[Update]
Attempting a new project. It asks to install tools.

Then it reinstalls SDK 17134 that I just removed !
[Update]
I have installed Microsoft.UI.Xaml and changed the XAML to reference
xmlns:Custom="using:Microsoft.UI.Xaml.Controls"

I am able to build without errors now but the app crashes.
    {Windows.UI.Xaml.UnhandledExceptionEventArgs}
    Exception: {Windows.UI.Xaml.Markup.XamlParseException: The text associated with this error code could not be found.

Cannot find a Resource with the Name/Key TreeViewItemMinHeight [Line: 1569 Position: 38]}
    Handled: false
    Message: "Cannot find a Resource with the Name/Key TreeViewItemMinHeight [Line: 1569 Position: 38]"
    Native View: To inspect the native object, enable native code debugging.

I expect this is because DataTemplate is in the Windows.UI.Xaml namespace instead of the Microsoft.UI.Xaml namespace
[Update]
OK, I am pretty sure I am in version hell now.
I just updated to the latest pre-releases

Now I get
Microsoft.UI.Xaml nuget package requires TargetPlatformVersion >= 10.0.17763.0 (current project is 17134)

Fixed that.
Now I have
The "CompileXaml" task could not be initialized with its input parameters.  jtUFlow C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\XamlCompiler\Microsoft.Windows.UI.Xaml.Common.targets

and
The "EnableTypeInfoReflection" parameter is not supported by the "CompileXaml" task. Verify the parameter exists on the task, and it is a settable public instance property.    jtUFlow C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\XamlCompiler\Microsoft.Windows.UI.Xaml.Common.targets   335

and
Severity    Code    Description Project File    Line    Suppression State
Warning NU1603  Microsoft.NETCore.UniversalWindowsPlatform 6.2.0-preview1-26926-04 depends on Microsoft.Net.Native.Compiler (>= 2.2.0-rel-26924-00) but Microsoft.Net.Native.Compiler 2.2.0-rel-26924-00 was not found. An approximate best match of Microsoft.Net.Native.Compiler 2.2.0-rel-26924-01 was resolved. jtUFlow D:\dev\jtUflow\jtUFlow\jtUFlow\jtUFlow.csproj   1

[Update]
I rewound to latest stable Nuget packages and noticed that I forgot to put the following inside App.xaml
<Application.Resources>
    <XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls"/>
</Application.Resources>

Now MainPage.xaml states
Visual Studio requires a newer version of WIndows to display this content.
Please update to Windows 10, version 1809 ( 10.0.17763.0) or later

A: Back to your original question. The ItemsSource is listed in the doc as preview feature, see the following:

*

*TreeView:(Preview) Data binding to the ItemsSource property on TreeView and TreeViewItem

*TreeView.ItemsSource Property:Device family Windows 10, version 1809 (introduced v10.0.17763.0)
So yes your problem is pending on SDK. For this question, actually binding to the ItemsSource in Treeview should support on 17763. You need to upgrade your OS to 1809 and also install 17763 SDK.
And I have tested this in a 1809 machine which has 17763 installed, it works without problem.


text:
Q: How get rid from redirect while using NGINX I've always used Apache as my web server, but i now have to use NGINX for other reasons. This is now running on a AWS Linux AMI.
This is my first time playing around I have managed to get a blank config working but when i add in my rules i converted from .htaccess i keep getting the site going into a redirect. Not sure if its my config or not. Also, im not sure if you need a seperate one for 443?
server {
  listen 80;
  server_name sitename.co.uk www.sitename.co.uk;
  root /var/www/html/Project;

  location / {
    try_files $uri $uri/ /index.php?$args;

    if (!-e $request_filename){
      rewrite ^/([^\.]+)$ /$1.php break;
    }
    if ($http_host ~* "^sitename\.co.uk"){
      rewrite ^(.*)$ https://sitename.co.uk/$1 redirect;
    }
    if (!-e $request_filename){
      rewrite ^(.*)$ /index.php break;
    }
    if (!-e $request_filename){
      rewrite ^(.*)$ /index.php break;
    }
  }

access_log /var/log/nginx/sitename.access.log;
error_log /var/log/nginx/sitename.co.uk.error.log;
}

Any help would be great.

A: This is probably due to this part causing an infinite loop:
if ($http_host ~* "^sitename\.co.uk"){
  rewrite ^(.*)$ https://sitename.co.uk/$1 redirect;
}

This seems like it could have been for redirecting http to https. The correct way to achieve this in nginx is to use two separate server blocks. One listening on 443(https) and configured with ssl, and the other listening on 80(http) with contents that looks like this:
server {
 listen 80;
 server_name sitename.co.uk www.sitename.co.uk;
 return 301 https://sitename.co.uk$request_uri;
}

There are many tutorials elsewhere on the web for nginx config, so I won't go into further detail. Hopefully this helps solve your immediate issues. :)


text:
Q: Add different values to array in loop. Javascript I am trying to add new dates to an array with a while loop, for some reason the first time it loops through it correctly adds it. But the second time it deletes the previous time and adds 2 of the new value.
var currentDate = new Date();
var testDate = new Date(2021, 8, 27, 0, 0, 0, 0);
var displayDate = new Date(2021, 5, 27, 0, 0, 0, 0);
var dateArray = [];

while (d.getTime() + 13 < currentDate.getTime()) {
    d.setDate(d.getDate() + 14);
    displayDate.setDate(displayDate.getDate() + 14);
    console.log(displayDate);
    dateArray.push(displayDate);
    console.log(dateArray);
}
console.log(dateArray);


text:
Q: spring Kafka Ambiguous methods for payload type I'm trying to consume two different type of payloads from Kafka topic using spring-kafka-2.2.0 and spring-boot-2.1.0 but unfortunately no luck so far blowing out with exception.
So I have two models in my project com.kafka.model.Professor and com.kafka.model.Student and i configured them in type mapping also. But I'm not sure which part I'm missing on this deserialization.
Config
@Configuration
public class KafkaConsumerConfig {

@Value("${kafka.consumer.bootstrap-server}")
private String bootstrapServer;

@Bean("consumerConfigs")
public Map<String, Object> consumerConfigs() {
    Map<String, Object> props = new HashMap<>();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer);
    props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-4");
    props.put(JsonDeserializer.TYPE_MAPPINGS,
            "professor:com.kafka.model.Professor, student:com.kafka.model.Student");
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);
    props.put(ConsumerConfig.CLIENT_ID_CONFIG, "test-4");
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
    props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
    return props;
}

@Bean("consumerFactory")
public ConsumerFactory<String, Object> consumerFactory() {
    JsonDeserializer<Object> jsonDeserializer = new JsonDeserializer<>(Object.class);
    jsonDeserializer.addTrustedPackages("*");

    return new DefaultKafkaConsumerFactory<>(consumerConfigs(), new StringDeserializer(), jsonDeserializer);
}

@Bean("kafkaListenerContainerFactory")
@ConditionalOnMissingBean(name = "KafkaAutoConfiguration")
public ConcurrentKafkaListenerContainerFactory<String, Object> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(consumerFactory());
    factory.setBatchListener(true);
    factory.getContainerProperties().setAckMode(AckMode.BATCH);
    return factory;
    }

}

Listener class
@Service
@KafkaListener(topics = "test-events",id = "kafkaListenerContainerFactory-11")
public class KafkaConsumerService {

@KafkaHandler
public void student(List<Student> stu) {
    System.out.println(stu);
}

@KafkaHandler
public void professor(List<Professor> pro) {
    System.out.println(pro);
   }

}

Error
2019-02-15 13:04:33.060 ERROR 14863 --- [actory-11-0-C-1] o.s.k.listener.BatchLoggingErrorHandler  : Error while processing:
ConsumerRecord(topic = stores-pricing-easytest-manual-events, partition = 4, offset = 1189400, CreateTime = 1550096019845, serialized key size = 7, serialized value size = 49, headers = RecordHeaders(headers = [], isReadOnly = false), key = student, value = {studentName=thomas, rollNum=109, age=35})

 org.springframework.kafka.KafkaException: Ambiguous methods for payload type: class java.util.ArrayList: student and professor

A: The @KafkaHandler approach doesn't work with BATCH mode. At least in the way you have it now: there is just no method to handle a distinguished batch by the generic arument.
Consider to turn off a batch mode or just handle everything in a single @KafkaListener method which already accepts a List as an argument for payload with any generic information.
NOTE: Apache Kafka doesn't distribute deserialized record between different batches. They all are going to be produced for the listener in the same ConsumerRecords. So, your logic with attempt to distribute by the generic type in the list is never going to happen, even if we would figure out a generic type of the method argument... So, the plain RECORD more is your saver.


text:
Q: What's the difference between working at a software company and a company whose focus is in another field? Recently, I was approached by a local ad agency with a job opportunity. They are bringing all web/interactive development in-house and adding to their development team.
I'm growing sick of my cushy, yet boring corporate job, and am intrigued by the position.
Having only worked for software shops where the primary business was making software, I worry that they may not put emphasis on quality software practices, since development is not the focus of their business.
Could anyone with experience at both compare/contrast working at a software company with working at a company that just happens to have an in-house software development team or department?

A: The difference largely depends on the company itself; I've worked at good non-software companies and terrible software companies.  On average, though, here's what I've found:
Non-Software Company
Emphasis is on getting things done quick, with little or no thought given to quality or long-term maintainability.  Developers are usually technically ignorant beyond what they've done in the past or during their time with the company, and often trying to introduce new concepts (ORMs, SOLID principles, TDD, etc.) will be met with confusion or immediate dismissal.  People tend to focus more on "towing the company line".
Software Company
Emphasis on getting things done without sacrificing quality.  Co-workers are more likely to keep up to date with technology (whether or not they can utilize it at work) and often look how they can integrate new ideas or frameworks into the daily routine to make the software better.  If they aren't already familiar with and are using concepts like TDD, ORMs, SOLID, etc. they have probably heard of it and are more willing to evaluate them.
Again this is in the end company dependent.  I worked at a non-software company with an extremely Agile team that embraced TDD and ORMs and taught me a lot about proper software engineering, and I worked at a small software company that wrote VBScript spaghetti code of the worst kind and have 50+ developers that each had to work on different pages to avoid things breaking, and tons of red tape for even a minor change.  However, the less the company outwardly relies on software, the more likely the environment will be very poor for software development.

A: I have worked in the IT department of large companies developing software for in-house use; I have worked in companies developing software for the market; and I have worked in agencies doing web development for clients.
And I would not say there was any difference whatsoever between those different companies in terms of the importance of productivity boosting things.
Keeping programmers productive is vital regardless of what sort of development those programmers are doing. And I would say that keeping programmers happy and keeping them working for you is even more important when they are maintenance programmers in the IT department of a non-software company.

A: One difference for certain will be less emphasis on the overhead and redtape that you have to go through at a corporate software shop.  You will find that you will be able to have much more granular control over all aspects of your projects.
One pro is that this can be refreshing...
It turned out horribly for me personally though but that just may be because I chose poorly.  One HUGE con is that you are no longer tied to the bread-and-butter of the business and instead you are an administrative overhead.  Budget controllers treated me like I was personally taking money from their own wallets and proceeded to "beat me like a rented mule" so to speak.  For me it was an infuriating and exhausting ordeal so you should carefully look for signs of this kind of attitude when you interview.

A: I've worked as the only software developer on a floor of non-software people, and I think independence is even more important in that case.  When you don't have dozens of people using the same tools, you have to make a lot more decisions—what language you will use, what compiler, what servers, etc.  Lone developers need more freedom to install, evaluate, and administer software that's taken for granted in a group setting.

A: There's already some great answers here, but I'd just like to reference a link to the transcript of the 2nd part of a talk that Joel Spolsky gave at Yale University:
Joel Spolsky - Talk At Yale Part 2 of 3
There he talks about the difference between "in-house" programmers and programmers that work in software/technology companies.
His three main points are:

*

*When you're an in-house programmer, you never get to do things the
right way. You always have to do things the expedient way.

*As an in-house programmer, once some software is "good enough," you
stop working on it.  When you develop software "products," you get to
make them beautiful.

*When you're a programmer at a software company, the work you're doing
is directly related to the way the company makes money.  That means,
for one thing, that management cares about you.
Personally, I've worked at both software companies and non-software companies throughout my career, and although there are always exceptions to every rule, I do agree with Joel's points as the vast majority of companies seem to be in accordance with them.

A: It will depend on the company. But usually, if it isn't their main focus, the software will be of lesser quality. The process, if they have any, will be less stringent. The testing non-existant. And the work overall less technically challenging.
They'll want it to work, and work now, and that'll be good enough.
But some places are hip about software development, even if they're mom & pop shops doing something else entirely. It depends on the business leadership being open to good ideas, the tech leadership knowing enough to do it right, and having people that can explain a good idea. Which might be you.
Interview the company. Ask them if the know of/adhere to the Joel test. Most of them are good points. See if they understand technical debt and the mythical man-month. Who is your project manager, what process does he use, and how geeky is he?

A: There's a HUGE difference.  In the former, you're part of a profit center.  In the latter, you're part of a cost center.  Guess which one gets better treatment?
I work for a software company now and am SO much happier than I was at my last job, where it was all layoffs & outsourcing all the time, and developers were just seen as easily replaceable widgets (instead of the heart of the company).

A: One major difference is that working at a software shop you are probably helping to generate jobs within the company. Working in the programming dept. at a different type of company is, in general, going to mean that you are writing software to replace people. It's a depressing reality to deal with. That being said, an ad agency may very well be a different beast entirely. More like a web dev shop within another company, would be my guess.

A: Well per my observations there are at least two cases when sticking with software company borders to matters of professional survival.
First case is if one is totally into coding - give me 80... 90... 100% time to code or I die. At software shops, this is almost a granted, as if everybody knows how to get there because, well, because everybody is doing just that. But outside, there is a really high risk to fail getting there. One may get as low as 50, 40, 30% (my personal coding load once dropped to 20% - no kidding, I measured in JIRA!) It's not because "they" don't want you to code - no they want but, but... they may just don't know how.
Second "deadly risk" is if someone has serious problems in communication. This may be troublesome even in software shops, right, but at least there are good chances to survive and live a nice productive life without disturbing interactions. :) At non-software companies though, such chances are much lower - quite an opposite, it's almost inevitable that one will eventually have to spend much effort to educate some outsider in IT basics just because otherwise it will be impossible to do the job.
Well except for two cases mentioned above I know no other strong reason to strictly lock self to software companies. Now, which side to prefer? as far as I can tell, this is more a matter of taste, of what kind of fun clicks more on you.

Both sides offer their own, distinct forms of getting fun. It's not easy to describe.
I'd say software companies are more fun to those aiming at "high marks" while outside ones give a thrill to those striving for "big difference". I think of it about like this (note numbers below are invented only to simplify making a point)...

*

*At software firm, one has a chance to deliver 100 features a year - a highest mark nobody yet achieved. It's gonna be hard, it's gonna be tough, it's gonna be top - making a cool 50% improvement over average 70 features a year. Great challenge, really.

*At the same time, in outside firm one has a chance to deliver 50 features a year - a highest boost nobody ever achieved. It's gonna be hard, it's gonna be tough, it's gonna be big - making a whopping 500% boost over average 10 features a year. Great challenge, trust me.

Note btw that chances to get 500% boost at software company are negligibly small in comparison - and respectively, chances to achieve 100 features are negligibly small outside.
Top marks at one side expand our understanding of professional limits, improving our knowledge of how to do things better. Big difference at other side makes a deep impact on the company culture, improving outsiders knowledge on how to to it right.
Now, if you have a clear preference for one or another, you know what side to take. Or, if you're indecisive, just feel free to swing between them as you wish. :)

A: Kudos to the cost vs profit center response.
I've been in both and would much much prefer a software company.  Since your correlation to profits is more obvious, your more likely to have some proper performance based compensation and an overall corp culture that embraces a software developers personality.  Often that translates into less office politics, Dockers not required, obvious career paths, and less BS.  But if your more into a steady 9-5, perhaps less challenging, not cutting edge type gig than sometimes corp IT is a better deal - not being cynical here, I understand some people like a more typical work/life balance at the expense of other things.  In my experience the overall quality of a developer is much, much better at a software company; opposed to the mediocrity that often permeates corp IT.  I know that there are exceptions, but this is based on my experience of the avg software corp vs avg corp IT dept.

A: I recently worked at a large American non-software company where a colleague heard the CEO say "I don't give a f*** about software I run an **". In my experience this is par for the course. There will almost inevitably be issues that seem obvious to the software team but the non dev management will refuse to even think about.

A: Programmers are still programmers.  Just because the primary product of the company isn't software doesn't mean that a programmer doesn't need the same amenities.

A: I.T is part of the Support group in non Software Companies..Software Programmers developed applications that  will help the company for much better productivity,faster transactions,technical support etch...
Some Non software companies(Manufacturing/Industrial etch) offers trainings and other things to their programmers but many are not, so they used to outsource Programmers in Other companies.

A:
Could anyone with experience at both compare/contrast working at a
  software company with working at a company that just happens to have
  an in-house software development team or department?

I'd rather contrast working within an IS department to working in the product development arm of a company that sells software.  Just to clarify each side and give some of each, with some formatting corrections:
IS department
The company may make hardware, software, cars, or whatever but the key here is that there is an internal department that is responsible for the systems that the company uses day-in and day-out.  In here there can be frameworks like ITIL that can try to bring some maturity to the processes that the department runs as part of this department is the infrastructure guys that keep the lights on and the other part is the development and analysis guys that put in improvements, enhancements and new systems.  Here projects can vary in length though in some cases in can take years to get a system fully implemented due to phases in the roll out if some big system is being replaced like a CMS, CRM or ERP.
At times I have had the feeling of being a cog in a machine and at others it is rather neat to be part of the backbone of the company for the lows and highs of such a position.  I don't get to brag to people outside the company too much because most of my work is on internal systems that isn't intended to be publicly accessible or viewed.  Here there can be support tickets where one may have to deal with vendors of software as someone has an issue that isn't necessarily something where it is easy to know what caused the error and so the IS department has to follow-up with someone else to help resolve the issue.  In other cases it may be that some customization has to be altered due to changing requirements or business rules.
Software company
Here this is working on what the company sells directly and thus there are some big rule differences.  First, the customer here can't be boxed as much as the IS department case.  In the IS department there may be just a few users of a system so that governance can take care of many odd cases where if someone intentionally chooses to misuse a tool, that can't always be prevented.  In the software company there isn't that safety net.  If someone downloads your software and they manage to find a way to do something rather destructive with it, the company may get a big black eye for it.  In this case there can be some showing off of what I did as there may be some cool feature to show a friend or relative if they want to know a bit more about what I do.
Something to note here is that there can be companies that are brought in as system integrators to put in big customizable enterprise software that work with people in IS departments on the million dollar implementation of stuff as well as those that work directly for the company making the big software itself.  There can also be application service providers that I'd put under here as they are selling a service that is built mostly of software usually.  For example, Google may have an IS department as well as a number of software developers even though one wouldn't go to a store to buy a DVD of Google's software, at least I don't think I've seen that though I do know of many Google products on-line that can be used rather easily.  This can allow for some specialization as it isn't likely to be as diverse as the IS department where a general application developer could support dozens of different applications.


text:
Q: Tmux window name changes when creating a new pane I have several problems with windows names and panes.
First if I have a window named "myWin" and I create a new pane, the name is changed into "bash" whereas I want it to remain "myWin".
Second, if I have a two windows, "foo" and "bar", and I do join-pane -s bar, my window is renamed "bash" too.
To finish, I'd like that after my join-pane -s bar, when I do a break-pane, my window previously named "bar" is re-created with the same name.

A: For all of you struggling with the same question — for me the issue happens when I set default-terminal in .tmux.conf to anything except:
set -g default-terminal "xterm-256color"

Which is really weird because tmux FAQ definitely specifies that is should be tmux or tmux-256color or something similar.
I've tried different options and sometimes window name won't be changed but then something else stops working (i.e. normal behavior of the up button ↑).
Also I use macOS Terminal and in Preferences > Profiles > Advanced I have setting Declare terminal as xterm-256color which is certainly related.


text:
Q: How to update angular data without refreshing the page? I have some data in a database table that I used angular to show it. And I use the following script which is in the footer to do that:

And my load_data() function in my controller like:
 public function load_data(){
    $data["groups"] = $this->Groups->fetch_groups();
    return $this->output
    ->set_status_header(200)
    ->set_content_type('application/json', 'utf-8')
    ->set_output(json_encode($data["groups"], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}

And my view is some inputs with submit button. What I need is when I click on the button to add a new record the table is automatically updated without refreshing the page each time. So I make another script to do so

HTML code like:

                    <form class="floating-labels m-t-40" method="post" id="add" action="addgroup">

                            <input type="text" name="group_title" class="form-control input-lg" id="input8" required>
                            Group Name

                            <input type="text" name="group_link" class="form-control input-lg" id="input7" required>
                            Link

                            <select name="group_icon_code" class="custom-select form-control" id="location1" required >
                                <option value="">Icon</option>
                                <?php
                                if(isset($icons))
                                    foreach($icons as $icon)
                                        echo '<option value="'.$icon->icon_value.'">'.$icon->icon_name.'</option>';
                                ?>
                            </select>

                            <input type="hidden" id="uri" name="uri" value="Groups_/addgroup" />
                            <button type="submit" ng-click="loadData()" name="add" value="1" class="btn btn-success">  save</button>
                            <button type="reset" class="btn btn-inverse">  cancel</button>

                    </form>

                                    title
                                    link
                                    order
                                    icon
                                    control

                                    {{ d.group_title }}
                                    {{ d.group_link }}
                                    {{ d.group_order }}

I have tried to put angular script in the on click function but it doesn't work.
What I need is to reload the same location again after adding.
Any ideas.

A: AngularJS is mostly used for two way data binding, which seems to be what you are looking for. There should be no need for using JQuery for updating your data if you are using Angular. All variables declared inside your $scope refresh automatically when being changed

So you are already posting data when loading the angular controller.
I would include that inside a function attached to the scope, so when clicking the button, you post your object and insert it afterwards in the table.

var app = angular.module('enterprise', []);

app.controller('entercontroller', function($scope, $http){
  $scope.tableData = [{ text: "First row" }, { text: "second row" }];

  $scope.loadData = function () {
    // here you do your http post
    var newRow = { text: "New Row" };
    $scope.tableData.push(newRow); // do this inside your http callback function
  }
});

        {{row.text}}

  <button ng-click="loadData()">
    Load data
  </button>

A: If you just want to refresh the list of your data in your table after your transaction, you can use this script. You don't need to add refresh function on your add button. Use this on your load data.

angular.module('app', [])
.controller('ctrl', function($scope, $timeout) {

  $scope.IntervalTime = 2000;
  $scope.updatedData = 0;

  timeoutFn();

  function timeoutFn() {
    $timeout(function() {

      //Add your select data query here

      $scope.updatedData++;

      timeoutFn();

    }, $scope.IntervalTime);
  }
})

          Data

          {{updatedData}}

Note: Your table will refresh on every 2sec and load the updated select data as I set this to $scope.Interval you can change the interval based on what you want.


text:
Q: Apply Left Join in Laravel eloquent. I have the following sql query-
SELECT
   viewtasksactivitiesprojects.task_name,
   users.firstname,
   users.lastname
FROM
   viewtasksactivitiesprojects
LEFT JOIN users
   ON (viewtasksactivitiesprojects.activitytask_owner_id=users.id)
WHERE
   activitytasks_active=1
   AND activity_status=5
   AND activitytask_id IN
   (
      SELECT
         activitytask_id
      FROM
         Activitytasks
      WHERE
         activity_id=26 AND active=1
         AND task_status=8
   )

I m using Laravel framework in which I want to transform this query to laravel eloquent format.
However I have achieved the same at some extent but I am not able to implement the 'Join' Part of the query.
Can Anyone please suggest me how to implement the Left join in laravel eloquent.
And one more thing is there any method in laravel by which we can pass the queries in sql format directly.

A: I got the answer-
DB::table('viewtasksactivitiesprojects')->leftJoin('Users',function($join){
           $join->on('viewtasksactivitiesprojects.activitytask_owner_id','=','users.id');
       })->whereIn('activitytask_id',function($query) use($id) {
                    $query->select('activitytask_id')
                            ->from(with(new Activitytask)->getTable())
                            ->where('activity_id', '=', $id)->where('active','=',1)->where('task_status','=',8);
                })->where('activitytasks_active','=',1)->where('activity_status','=',5)->get(array('viewtasksactivitiesprojects.task_name','users.firstname', 'users.lastname','users.id'));


text:
Q: R Cronbach's alpha -- rbindlist error I'm new to R. I'm trying to calculate Cronbach's alpha (from psych package) for a data set. The data set looks like this:
R> belong_data
      belong.q1 belong.q2 belong.q3 belong.q4 belong.q5
   1:        NA        NA        NA        NA        NA
   2:         5         5         5         5         5
   3:        NA        NA        NA        NA        NA
   4:         5         5         4         5         5
   5:         4         5         4         3         3

I'm getting the following error:
R> alpha(belong_data)
Error in rbindlist(l, use.names, fill) :
  Item 2 of list input is not a data.frame, data.table or list

I don't understand where the rbindlist call is coming from or how to feed in the correct data structure. The data set itself ("belong_data") is a data.frame. Not sure what the problem is.

A: Update: This issue happened because psych::alpha creates a matrix and binds tries to bind that matrix to the input data.table. However rbind (which calls rbindlist internally) for data.table only handled list / data.frame / data.table inputs so far.
rbind for data.tables now coerces non-data.table list elements to data.tables first and then calls rbindlist internally. This commit fixes the issue and should be available from v1.9.8 on. From NEWS:

*rbind for data.tables now coerces non-list inputs to data.tables first before calling rbindlist so that binding list of data.tables and matrices work as expected to be consistent with base's rbind, #1626. Thanks @ems for reporting here on SO.

This looks like a reproducible data.table bug. I've filed it here. Thanks for posting it!
require(psych)
require(data.table)
> DT = data.table(a=1:5,b=6:10)
> alpha(DT)
Error in rbindlist(l, use.names, fill, idcol) :
  Item 2 of list input is not a data.frame, data.table or list
> setDF(DT)
> alpha(DT)  # works

> sessionInfo()
R version 3.2.2 (2015-08-14)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 15.10

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8    LC_PAPER=en_US.UTF-8
 [8] LC_NAME=C                  LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] data.table_1.9.7 psych_1.5.8

loaded via a namespace (and not attached):
[1] parallel_3.2.2 mnormt_1.5-4
>


text:
Q: Pass parameter of procedure as variable to trigger I have a table named artist_log & it has following structure
[action_type     char(6)]
[artist_id       int]
[mod_date        datetime    default current_timestamp]

Created a procedure as mentioned below:
create procedure update_artists
    @m_artist_id int,
    @m_place_of_birth varchar(60)
as
begin
    update artists
    set place_of_birth = @m_place_of_birth
    where artist_id = @m_artist_id ;
end ;

and executing it with following statement
execute update_artists 2019, 'Delhi' ;

I want to create a trigger UPDT_LOG which will add a record to table artist_log with values as UPDATED and value of artist_id column should be same as parameter viz. @m_artist_id which was passed to execute above mentioned procedure. Any help?

A: You don't have to 'pass' parameters to a trigger. Whatever rows you update, you can access using the DELETED and INSERTED tables in the body of the trigger.
create trigger updt_log on artists for update as
insert into artist_log (action_type, artist_id)
select 'UPDATE', artist_id
from inserted

This is the simplest form of a trigger. If artist_id can be updated by design, then you'll have to handle that case as well.


text:
Q: How to tell if CATransaction complete block called when animation complete or removed I am building a timer and I want to get notified when my animation is complete, such that I can proceed with the logic.
I am trying to use CATransaction's complete block. But it gets called when either the animation completes or it is removed. Is there a way to tell the difference?
I am basically asking the same question as this one: CATransaction complete block success or failure
In the answer it says use CATransation's setValue. But I have no idea how.


text:
Q: Generating HTML list from hierarchy MySQL Table I have a hierarchy table like so
id| name         | parent_id | header
1 | Assets       | 0         | Y
2 | Fixed Assets | 1         | Y
3 | Asset One    | 2         | N
4 | Income       | 1         | N

I pull this data via axios and trying to render in the below way
I am trying to generate a UL LI list like so

        Assets

                Fixed Assets

Asset One

Income Receiveables

It would multiple parent-child relationship meaning it could go till 10 levels. I am confused on how to achieve this.
Can someone guide me to achieve this?
Dummy Payload
[{id: 1, name: assets, parent_id: 0, header:Y}, {id: 2, name: Fixed Assets, parent_id: 1, header:Y} ....]

A: I only would like to give you an alternative.
It would be much easier if you can change the way you represent the data. It may depend to have control over the service which you pull the data.
Example:
var data = {
  "id": 1,
  "name": "Assets",
  "header": true,
  "children": [
    {
      "id": 2,
      "name": "Fixed Assets",
      "header": true,
      "children": [
        {
          "id": 3,
          "name": "Asset One",
          "header": false
        }
      ]
    },
    {
      "id": 1,
      "name": "Income",
      "header": false
    }
  ]
}

After that, this example would lead you a solution: https://v2.vuejs.org/v2/examples/tree-view.html

A: I would recommend you to use the data struct as @The_Cute_Hedgehod offer nested parent-child relation.
I can add an example how to convert your current ds to it.
after you got the given payload, you can always render it using custom vue component
you can find full working example here:
https://codepen.io/omer-shacham/pen/xxbrxdO
example data
var data = [{
  "id": 1,
  "name": "Assets",
  "children": [
    {
      "id": 2,
      "name": "Fixed Assets",
      "children": [
        {
          "id": 3,
          "name": "Asset One",
        }
      ]
    },
    {
      "id": 1,
      "name": "Income",
    }
  ]
}

example template
<template>

    {{ name }}

 0">
            <TreeNode v-for="child in children" :node="child"/>

</template>

and your root app

   <TreeNode v-for="child in root" :child="child"/>


text:
Q: replace '.' with ';' in a string except 3rd and 6th I want to replace . with ; in "qwe.qwee.qwer.qwer.qwer.qwww.qwww" except 3rd and 4th '.' with the help of for loops and if statements.
Can anyone update this with an if statement?
var str = "qww.qwer.qwer.qwer.qwww.qwww.qwww";
for (var i = 0; i <= str.length; i++) {
  str = str.replace(".", ";");
}
console.log(str);

A:

var a = 'qwe.qwee.qwer.qwer.qwer.qwww.qwww';
var out = a.split('.').map(function(s, i) {
    return s + (i >= 2 && i <= 3 ? '' : ';')
}).join('');
console.log( out );


text:
Q: Removing a String from a String REGEX I have an automatically generated string which looks as follows:
["January","February",null,"April"]

I need to remove any match of ",null" from the string, ie:
["January","February",null,"April"] --> ["January","February","April"]

How can I find everything except for ",null"?
I have tried variations of "^(?!,null).*" without success.

A: To answer your question as stated, you don't need regex:
str = str.replace(",null", "");

However, to handle the edge cases too:
["January","February",null,"April"] --> ["January","February","April"]
["January",null,null,"April"] --> ["January","April"]
[null,"January","February","April"] --> ["January","February","April"]
["January","February","April",null] --> ["January","February","April"]
[null] --> []

you would be better served with regex:
str = str.replaceAll("(?<=\\[)null,?|,null", "");

The replacement regex caters for null the first (and potentially only) position, and any other case.

A: Please review this one, we can use filter function

var arr = [null, "January","February",null,"April", null];

var arr2 = arr.filter(function(x){return x !== null})

console.log(arr,arr2);


text:
Q: [Shiny]: Add link to another tabPanel in another tabPanel I'm trying to put a link on my "home" tabPanel to all others tabPanels of my app.
The idea is as follows:
ui = navbarPage("",
         tabPanel("home",
                  fluidPage(
                    fluidRow(box("this 1st box should lead me to tab1a")),
                    fluidRow(box("this 2nd box should lead me to tab1b")),
                    fluidRow(box("this 2nd box should lead me to tab2")))
            ),
         navbarMenu("tab1",
                    tabPanel("tab1a"),
                    tabPanel("tab1b")),
                    tabPanel("tab2")
         )

shinyApp(ui, server=function(input, output) {})

I've seen the answer in Add link panel tabs in Shiny with various top level navigation bars, but I couldn't implement it on my code, since it deals with html (which i've never worked before, so I'm not familiar with the functions etc) and the code considers tabPanels within the same tab (not sure if that's why it didn't work here, if maybe it didn't work because the tabs I'm trying to link are on a navbarPage or something).
Can anyone help me or tell me where i could learn how to implement this on my example?

A: This answer is purely JavaScripted, but very minimal, I guess. Since Shiny creates tabs with random number Ids, and does not give access to the Ids it used, this has do be done client-sided. But there is no knowledge of JavaScript needed to implement this to other scenarios. The JavaScript part is just for Copy/Paste and the trigger command is easy to understand.
What did I do? I installed a function, that finds the Navbar link corresponding to the desired tab, and just clicks it. This utility can be added to any element with the "onclick" attribute. There are no special tags (e.g. no "a" tag) required.
The code below should make it easy to customize this solution to fit your needs.
Note: I used the original Code with the box, although it does not have any visual effect.
Code:
library(shiny)
library(shinydashboard)

ui = shinyUI(

  navbarPage("Header",
    tabPanel("home",
      tags$head(tags$script(HTML('
        var fakeClick = function(tabName) {
          var dropdownList = document.getElementsByTagName("a");
          for (var i = 0; i < dropdownList.length; i++) {
            var link = dropdownList[i];
            if(link.getAttribute("data-value") == tabName) {
              link.click();
            };
          }
        };
      '))),
      fluidPage(
        fluidRow(box("this 1st box should lead me to tab1a", onclick = "fakeClick('tab1a')")),
        fluidRow(box("this 2nd box should lead me to tab1b", onclick = "fakeClick('tab1b')")),
        fluidRow(box("this 2nd box should lead me to tab2", onclick = "fakeClick('tab2')"))
      )
    ),
    navbarMenu("tab1",
      tabPanel("tab1a", "Some Text inside Tab 1a."),
      tabPanel("tab1b", "Some Text inside Tab 1b.")
    ),

    tabPanel("tab2", "Some Text inside Tab 2.")
  )
)

server = function(input, output, session){}

runApp(shinyApp(ui, server), launch.browser = TRUE)

Have fun!


text:
Q: puedo gestionar una base de datos de phpmyadmin con workbench? tengo un dominio que tiene host junto phpmyadmin, aqui cree una base datos pero quiero saber si puedo gestionarla con workbench y que programas necesito para poder hacer la conexion. Gracias

A: La verdad es que depende de tu proveedor de hosting. Si no permite conexiones externas, sólo podrás utilizar phpMyAdmin. En caso contrario, podrás conectarte a tu base de datos desde cualquier cliente de MySQL: Workbench, dBForge, Heidi, ...


text:
Q: How to log an error into a Table from SQLPLus I am very new to Oracle so please base with me if this is covered else where.
I have a MS SQL box running Jobs calling batch files running scripts in SQLPLUS to ETL to an Oracle 10G database.
I have an intermittent issue with a script that is causing the ETL to fail which at the minute without error logging is something of an unknown. The current solution highlights the load failure based on rowcounts for before and after the script has finsihed.
I'd like to be able to insert any errors encoutered whilst running the offending script into an error log table on the same database receiving the data loads.
There's nothing too technical about the script, at a high level is performs the following steps all via SQL code and no procedural calls.

*

*Updates a table with Date and current row counts

*Pulls data from a remote source into a staging table

*Merges the Staging table into an intermediate staging table

*Performs some transformational actions

*Merges the intermediate staging table into the final Fact table

*Updates a table with new row counts

Please advise whether it is possible to pass error messages, codes, line number etc etc via SQLPLUS into a Database table? and if so the easiest method to achieve this.
A first few lines of the script are shown below to give a flavour
/*set echo off*/
set heading off
set feedback off
set sqlblanklines on

/* ID 1 BATCH START TIME */
INSERT INTO CITSDMI.CITSD_TIMETABLE_ORDERLINE TGT
(TGT.BATCH_START_TIME)
(SELECT SYSDATE FROM DUAL);
COMMIT;

insert into CITSDMI.CITSD_TIMETABLE_ALL_LOADS
(LOAD_NAME, LOAD_CRITICALITY,LOAD_TYPE,BATCH_START_TIME)
values
('ORDERLINE','HIGH','SMART',(SELECT SYSDATE FROM DUAL));
commit;

/* Clear the Staging Tables */

TRUNCATE TABLE STAGE_SMART_ORDERLINE;
Commit;

TRUNCATE TABLE TRANSF_FACT_ORDERLINE;
Commit;

and so it goes on with the rest of the steps.
Any assistant will be greatly appreciated.

A: Whilst not fully understanding your requirement, a couple of pointers.

*

*The WHENEVER command will help you control what sqlplus should do when an error occurs, e.g.

WHENEVER SQLERROR EXIT FAILURE ROLLBACK
WHENEVER OSERROR EXIT FAILURE ROLLBACK
INSERT ...
INSERT ...
This will cause sqlplus to exit with error status 1 if any of the following statements fail.
You can also have WHENEVER SQLERROR CONTINUE ...
Since the WHENEVER ... EXIT FAILURE/SUCCESS controls the exit status, the calling script/program will know if it worked failed.

*

*Logging

use SPOOL to spool the out to a file.

*

*Logging to table.

Best way is to wrap your statements into PLSQL anonymous blocks and use exception hanlders to log errors.
So, putting the above together, using a UNIX shell as the invoker:
sqlplus -S /nolog <<EOF
WHENEVER SQLERROR EXIT FAILURE ROLLBACK
CONNECT ${USRPWD}
SPOOL ${SPLFILE}

BEGIN
   INSERT INTO the_table ( c1, c1 ) VALUES ( '${V1}', '${V2}' );
EXCEPTION
   WHEN OTHERS THEN
      INSERT INTO the_error_tab ( name, errno, errm ) VALUES ( 'the_script', SQLCODE, SQLERRM );
      COMMIT;
END;
/

SPOOL OFF
QUIT
EOF

   if [ ${?} -eq 0 ]
   then
      echo "Success!"
   else
      echo "Oh dear!! See ${SPLFILE}"
   fi


text:
Q: What use is having multiple URL's in a Slack Outgoing Webhook Integration? Since multiple URL's are possible in the configuration what use or behavior of it would be? Are there any benefits to having multiple URL's instead of only the one?
Currently I only have a single URL in the configuration.


text:
Q: PHP Class constructor not running when called from static function in another class I am currently stamped and i can't see where I have done it wrong. I have a static function request() below:
private static function request(){

   if($_SERVER['REQUEST_METHOD']=='GET'){

       $data = RunData::get('cmd');

   }

which calls a static function get() which in turn calls a private function clean() which uses variables set in the class constructor loading an Injected class Sanitize
class RunData {

    public static $sanitize;

    public function __construct( Sanitize $sanitize ){

        self::$sanitize = $sanitize;

    }

   private static function clean($variable_array){

        if(is_array($variable_array)){

            $filters = array('string' => 'sanitize_string');

            return self::$sanitize->filter($variable_array, $filters);

        }
    }

    public static function get($variable){

        if(self::clean($_GET)){

            return $_GET[$variable];

        }

    }

}

but when I run I get this error.

Fatal error: Call to a member function filter() on a non-object

This filter function is loaded from the Sanitize Class which is injected into the constructor.
What possibly have I missed??? The constructor doesn't seem to be running
Thanks

A: You're correct, __construct() is not called when the class is invoked statically. You'll need to set up the object manually by injecting that Sanitize class via some sort of setup method before calling the method.
For example:
public static function setSanitizeClass(Sanitize $sanitise)
{
    self::$sanitize = $sanitize;
}

Then:
RunData::setSanitizeClass(new Sanitize());
$data = RunData::get('cmd');


text:
Q: Match two identical images with different filenames if a single image has been saved twice with two different filenames, is there a way to compare them to see if they're the same..?
I'm hoping a basic hash or CRC type check could work..?
File size might not, as there are millions of images in the pool and different images could have the same size..
Hoping there's an easy way to do it in C#..

A: If the file contents are identical, then a cryptographic hash would at least give a very good indication of equality. The SHA256 class would be a good candidate here, although it's possibly a little over the top. For example:
static byte[] Sha256HashFile(string file)
{
    using (SHA256 sha256 = SHA256.Create())
    {
        using (Stream input = File.OpenRead(file))
        {
            return sha256.ComputeHash(input);
        }
    }
}

The simplest way to compare the two returned byte arrays is probably to convert them both to strings using Convert.ToBase64 and then compare the strings. Ugly but easy :) You could also use Enumerable.SequenceEqual:
byte[] hash1 = Sha256HashFile("file1.png");
byte[] hash2 = Sha256HashFile("file2.png");
bool same = hash1.SequenceEqual(hash2);

If you want to store the hashes as a set or dictionary, you could implement your own IEqualityComparer<byte[]> but frankly it would be easiest to use a base64 string. For example, this will print out the duplicate files:
var hashToNameMap = new Dictionary<string, string>();
foreach (string file in files)
{
    byte[] hash = Sha256HashFile(file);
    string base64 = Convert.ToBase64(hash);
    string existingName;
    if (hashToNameMap.TryGetValue(base64, out existingName))
    {
        Console.WriteLine("{0} is a duplicate of {1}", file, existingName);
    }
    else
    {
        hashToNameMap[base64] = file;
    }
}

A few notes:

*

*This isn't guaranteed to be accurate, but the chances of getting a collision are very small, particularly if the files also have to be valid images.

*This involves reading all of every file - even if there are no other files with the same size (and therefore no possible duplicates). This may or may not be an issue for you.

*Even if there are multiple files of the same size, you only need to read all of them to find duplicates... you could potentially read the files and compute the hashes as you go, stopping as soon as you find that files are different.

How you approach this depends on whether your goal is absolute speed, simplicity of code, etc. It may also depend on whether the pool will grow over time - for example, you may want to hash files as soon as you get two or more files of the same size, so that when you add another file of the same size you can hash that and add it without ever rereading the existing data.

A: First, check the length anyway. Only when they match you have to look deeper.
For all images with the same size, compute a Hash. When the hashes match you can be fairly sure the images are identical. The library offers many cryptographically secure hashes but you may want to look for optimizations:

*

*Sample. If your images are large (> 100 kB) you can save on I/O by computing the hash over a few segments only. A few kB at the start, middle and end is probably enough to get a good fingerprint. Do use multiples of 512 for the sizes and offsets of those blocks.  Jpeg compression works a little like a Hash: a few pixels difference usually lead to big differences in the bitstream.

*use a faster hash. A simple xor algorithm might suffice in this case.

*If you really want to compare 2 images at a time then use a Hash implementation that let's you check intermediate results. As soon as there's a difference you can stop.

*But when you have a lot of same-size files, compute the Hash once per file and find the (Size, Hash) duplicates.

A: in
System.Security.Cryptography;

use SHA1
using(SHA1 sha = SHA1.Create()) { //added using based on Jon Skeet comment
    byte[] newData = sha.ComputeHash(data);
}

data is the byte[] data of the file
newData is the hash
This is only appropriate if you want to know if the two images files are literally the same bytes, not if they just encode the same pixels (which could be different files if meta-data is different)

A: You could read the binary from each file and then compare the binary contained. The same image should have the exact same binary in each array.
Just a thought.

A: You can also do something like this
public string ImageToBase64(Image image,
                            System.Drawing.Imaging.ImageFormat format)
{
    using (MemoryStream ms = new MemoryStream())
    {
         // Convert Image to byte[]
         image.Save(ms, format);
         byte[] imageBytes = ms.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);
        return base64String;
    }
}

then you can just do a String.Compare(). This is probably slow for larger pictures because it generates a pretty large string but I have posted it just for the sake of completnes:)


text:
Q: SOAP client, wsdl, python I have SOAP service with WSDL and php-client for it.
Php-client:
<?php
$client = new SoapClient('https://xx.xx.xx.xx/service/?wsdl');
$headers = array();
$headers[] = new SoapHeader('http://mfisoft.ru/auth','Login','admin');
$headers[] = new SoapHeader('http://mfisoft.ru/auth','Password','admin');
$client->__setSoapHeaders($headers);
$table_hi = $client->getTableByTitle('Blocked numbers');
$row_data = array(
    array(
                      array(
                              'name' => 'prfx',
                              'value' => '55555555'
                       ),
                      array(
                              'name' => 'blocking_time',
                              'value' => '20140306185014'
                       )

)
);

$rowset=$client->insertRowset($table_hi, $row_data);
?>

But I need to rewrite the python.
I tried to do using suds and pysimplesoap.
from suds.client import Client
url = 'http://localhost/service/?wsdl'
client = Client(url)

I don't understand how make similar program in particular these strings
$headers[] = new SoapHeader('http://mfisoft.ru/auth','Login','admin');
$headers[] = new SoapHeader('http://mfisoft.ru/auth','Password','admin');
$client->__setSoapHeaders($headers);

I have not found in suds doc.
I need your help.
Thanks in advance.
p.s.
Sorry for my bad English
P.S.S.
I need to rewrite the php client in the python client.

A: Forgive the formatting in advance.. the proper way to setup and connect using the suds client is as follows. In the case that you want the server part, I can't tell 100% from your question.. I might be able to help but it's not something I've ever done before in python.
client = suds.client.Client.(self,url=wsdl_url,
                             doctor=schema_doctor,
                             username=username)
try:
    # This will throw an Exception if the wsdl_url is bad
    # and will return False if the authentication fails
    if not client.service.Connection_Authenticate(username,
                                                  password):
        raise Exception("Failed to authenticate.")


text:
Q: How to send message back from client to the server via WebSocket in Laravel with Laravel WebSockets? WebSocket allows two-way communication: the server can send messages to the browser and the browser - the client - can respond back via the same connection.
I am implementing Chat Application in Laravel 6 using:

*

*Laravel Echo JavaScript Package (not laravel-echo-server),

*Laravel WebSockets

*pusher-js.

I already get it worked that the server triggers events and the client listens to those events as following.

*

*Install Laravel WebSockets package.

composer require beyondcode/laravel-websockets

*Configure config/broadcasting.php.

        'pusher' => [
            'driver' => 'pusher',
            'key' => xxx,
            'secret' => xxx,
            'app_id' => xxx,
            'options' => [
                'cluster' => xxx,
                'encrypted' => true,
                'useTLS' => true,
                'host' => '127.0.0.1',
                'port' => 6001,
                'scheme' => 'https',
            ],
        ],
    ]

*Configure config/websockets.php
'apps' => [
        [
            'id' => xxx,
            'name' => xxx,
            'key' => xxx,
            'secret' => xxx,
            'enable_client_messages' => true,
            'enable_statistics' => true,
        ],
    ],

*Install Pusher server.

composer require pusher/pusher-php-server "~3.0"

*Set broadcasting driver to use pusher in .env file.

BROADCAST_DRIVER=pusher

*Use laravel-echo and pusher-js on my client side.

import Echo from "laravel-echo"

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-key',
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true,
});

*Start WebSockets server.

php artisan websockets:serve

*On the server-side, trigger events with an event class that implements ShouldBroadcastNow class.

event(new MyEventClass((object)$message));
Everything works fine. In step 8, I trigger events from the server-side.
Note that I am not using the official Pusher server, I just utilize the Pusher API implementations and pusher-js but point the Laravel Echo JavaScript package to the local Laravel WebSockets server, configured in step 6.
Please do not confus Laravel Echo JavaScript package with laravel-echo-server of Socket.IO Server. I am not using Socket.IO Server.
Now instead of triggering events on the server-side as shown in step 8, I want to tigger events from the client-side since WebSocket allows two-way communication. How can I do that in Laravel with Laravel Echo JavaScript Package, Laravel WebSockets PHP package?

A: Refer to this documentation: https://pusher.com/docs/channels/using_channels/events#triggering-client-events
According to pusher documentation, Initialize your front end using this
 this.echo = new Pusher('mykey', {
    wsHost: 'localhost',
    wsPort: 6001,
    forceTLS: false,
    disableStats: true,
    enabledTransports: ['ws', 'wss']
  });

use this to trigger your event
var channel = this.echo.subscribe("private-channel");
channel.bind("pusher:subscription_succeeded", () => {
var triggered = channel.trigger("client-someEventName", {
   your: "data",
 });
});

A: After having initialized Echo, you need to listen on a certain channel within your frontend.  I will show some Vue code, but modify accordingly:
Vue File
export default {
    methods: {
        sendCommand(command) {
            axios.post('/api/command', { 'command': command })
            .then((res) => {
                //
            })
        }
    },
    mounted() {
        Echo.channel('xxx')
        .listen('.weight-change', (e) => {
            this.weight = e.weight
        })
    }
}

In here, you can see that all the incoming messages are captured on the listen portion of the code and sending a new message is done with an api route on the backend that sends them to the Echo channel.
Please let me know if you need any clarification.

A: For everyone that may face this issue.
You no need echo and should instantiate from the Pusher directly
const my_pusher = new Pusher("APP_KEY", {
        cluster: 'mt1',
        wsHost: window.location.hostname,
        wsPort: 6001,
        forceTLS: false,
        disableStats: true,
    });

And to send message to the server:
my_pusher.send_event('EVENT_NAME',{'ANYTHING':'YOU_WANT'})

A: I might be incorrect, but I don't believe you can push to Pusher with their pusher-js package. That's what the pusher-php-server composer package is for.
There may be a node package for this, but why are you trying to reinvent the wheel? Just use axios or a Vuex action to post to one of your routes to fire your event and then let Echo pick up the response.
You don't even need to create a controller, just use a route closure and fire your event. Axios or Vuex will both return a Promise so you can manage wait for a response in your component or your Vuex action.
I could understand if you were trying to implement a different type of driver to Broadcast with like RabbitMQ or Rachet or something, but it's designed to be a circular loop of sorts, hit your endpoint from js, fire the event from PHP, let Pusher/or websockets do it's thing, receive your broadcast back in js.


text:
Q: How this code works to replace the values in previous lines in Python I am learning Pandas, and I encountered a problem in my textbook which is hard for me to understand, my code is below:
amzn=pd.read_csv('data/amzn_stock.csv',index_col='Date',parse_dates=['Date'])
amzn_close=amzn['Close']
amzn_daily_return=amzn_close.pct_change()
amzn_daily_return=amzn_daily_return.dropna()
mean=amzn_daily_return.mean()
std=amzn_daily_return.std()
abs_z_score=amzn_daily_return.sub(mean).abs().div(std)

pcts=[abs_z_score.lt(i).mean() for i in range (1,4)] #lt=less
print('{:.3f} fall within 1 standard deviation.'
     '{:.3f} within 2 and {:.3f} within 3'.format(*pcts))

I am ok for all of the statement except the last line:
print('{:.3f} fall within 1 standard deviation.'
         '{:.3f} within 2 and {:.3f} within 3'.format(*pcts))

I know it tries to use the values in pcts to replace {:.3f}, but I don't really know how this works. From my experience, I know for example in the following code:
print('%s. capital of %s?\n'%(1, 'New York'))

%s will be replaced by 1, and second %s will be replaced by New York.
So how does my previous example work? Is there any reference I can read online?
Thanks


text:
Q: Question about Duhamel's principle. I know how to apply Duhamel's principle to solve a problem, but I don't quite understand a fine detail regarding it.
$ \begin{cases}
u_t = ku_{xx} + f(x,t) , & x \in \mathbb{R}, t > 0\\
u(x,0) = 0, & x \in \mathbb{R}
\end{cases}$
In order to solve this with Duhamel's principle we consider,
$ \begin{cases}
w_t(x,t,\tau) = kw_{xx}(x,t,\tau) , & x \in \mathbb{R}, t > 0\\
w(x,0,\tau) = f(x,\tau), & x \in \mathbb{R}
\end{cases}$
and solve this homogenous PDE, and the solution is given by
$$w(x,t,\tau) = \int_{\mathbb{R}}\Phi(x-y,t)f(y,\tau)~dy. $$
How do we know that adding the variable  $\tau$ does not effect the validity of the standard solution of the heat equation? How do we know the proof still works out for the heat equation? By proof, I mean the proof that the bottom statement is true.
I know that the solution works if this were the case,
$ \begin{cases}
w_t(x,t) = kw_{xx}(x,t) , & x \in \mathbb{R}, t > 0\\
w(x,0) = f(x), & x \in \mathbb{R}
\end{cases}$
and it would be given by,
$$w(x,t) = \int_{\mathbb{R}}\Phi(x-y,t)f(y)~dy. $$

A: The reason is that $\tau$ is just a parameter in the equation, which only involves derivatives with respect to $t$ and $x$. If you fix $\tau$, you are in the standard situation. A similar situation is: the general solution of the PDE for $u(x,y)$
$$
u_x=0
$$
is just the solution of the ODE $y'=0$, $y=C$, the only difference being that since $y$ plays the role of a parameter, it would be $u(x,y)=C(y)$.


text:
Q: Inserting a JSON value into a mysql but 0 is being inserted I am creating a python API that will take values from a user in the form of a JSON object and insert these values into a database. Instead of inserting the data, a 0 is being inserted while the id increments as expected. Would anyone be able to advise me as to how to solve this problem?
cursor = cnx.cursor()

sql = "INSERT INTO `player`(`player_id`,`Name`, `Age`, `Overall`, `Position`) " \
      "VALUES ('', `Name`=%s,`Age`=%s,`Overall`=%s,`Position`=%s);"

cursor.execute(sql, (request.json['Name'], request.json['Age'],
                     request.json['Overall'], request.json['Position']))

cnx.commit()

The code above is what I am currently using. All help is appreciated

A: Use NULL for auto incrementing fields, and don't specify the name of the field in the VALUES below:
cursor = cnx.cursor()

sql = "INSERT INTO `player`(`player_id`,`Name`, `Age`, `Overall`, `Position`) " \
      "VALUES (NULL, %s, %s, %s, %s);"

cursor.execute(sql, (request.json['Name'], request.json['Age'],
                     request.json['Overall'], request.json['Position']))

cnx.commit()


text:
Q: Вывод нежелательного символа \ в .json документ Мой код выводит в json документ символ \. Подскажите, как можно это исправить
import json
import socket
from ping3 import ping

ports = [20, 21, 22, 23, 25, 43, 53, 80,
         115, 123, 143, 161, 179, 443, 445,
         514, 515, 993, 995, 1080, 1194,
         1433, 1723, 3128, 3268, 3306, 3389,
         5432, 5060, 5900, 8080, 10000]

services = [
    "FTP-DATA", "FTP", "SSH", "Telnet", "SMTP", "WHOIS", "DNS", "http", "SFTP", "NTP", "IMAP", "SNMP", "BGP", "HTTPS",
    "MICROSOFT-DS", "SYSLOG", "PRINTER", "IMAPS", "POP3S", "SOCKS", "OpenVPN", "SQL Server", "PPTP", "HTTP", "LDAP",
    "MySQL", "RDP", "PostgreSQL", "VNC", "Tomcat", "Webmin"]

with open('list_of_hosts.txt') as f:
    num_lines = len(f.readlines())

hosts_website = []
hosts_web = []

def scan_and_write(host_name):
    host_ping = ping(host_name)

    if host_ping is not False:
        ip = socket.gethostbyname(host_name)
        json_data = [{"hostname": f"{host_name}", "ports": [{}]}]

        for a in range(len(ports)):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            socket.setdefaulttimeout(0.01)
            result = s.connect_ex((ip, ports[a]))
            if result == 0:
                json_data[0]["ports"][0][ports[a]] = services[a]
                return json.dumps(json_data)

    else:
        json_data = [{"hostname": f"{host_name}"}]
        return json.dumps(json_data)

with open('../pythonProject/list_of_hosts.txt') as f:
    i = 0
    for i in range(num_lines):
        line = f.readline()
        if 'website' in line:
            hosts_website.append(line.rstrip('\n'))

with open('../pythonProject/list_of_hosts.txt') as f:
    i = 0
    for i in range(num_lines):
        line = f.readline()
        if 'web' in line:
            hosts_web.append(line.rstrip('\n'))

    data_website = []
    data_web = []

with open('hosts.json', "w") as f:

    json_website_and_web = {"website.ru": data_website, "web.com": data_web}

    for i in range(len(hosts_website)):
        data_website.append(scan_and_write(host_name=hosts_website[i]))

    for i in range(len(hosts_lmru)):
        data_web.append(scan_and_write(host_name=hosts_web[i]))

    d.write(json.dumps(json_website_and_web))

получается примерно следующее
{"website.ru": ["[{\"hostname\": \"test.website.ru\", \"ports\": [{\"80\": \"http\"}]}]"}, "web.com": ["[{\"hostname\": \"test.web.com\"}]"]}

A:
у вас scan_and_write возвращает строку. поэтому эта строка при последующей >сериализации словаря json_website_and_web экранируется. возвращайте из >scan_and_write не строку, а json_data – Nofate

Nofate, спасибо вам. Это помогло
if host_ping is not False:
        ip = socket.gethostbyname(host_name)
        json_data = [{"hostname": f"{host_name}", "ports": [{}]}]

        for a in range(len(ports)):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            socket.setdefaulttimeout(0.01)
            result = s.connect_ex((ip, ports[a]))
            if result == 0:
                json_data[0]["ports"][0][ports[a]] = services[a]
                return json_data # UPD

    else:
        json_data = [{"hostname": f"{host_name}"}]
        return json_data # UPD


text:
Q: Check the execution time of a query accurate to the microsecond I have a query in SQL Server 2019 that does a SELECT on the primary key fields of a table.  This table has about 6 million rows of data in it.  I want to know exactly how fast my query is down to the microsecond (or at least the 100 microsecond).  My query is faster than a millisecond, but all I can find in SQL server is query measurements accurate to the millisecond.
What I've tried so far:

*

*SET STATISTICS TIME ON
This only shows milliseconds

*Wrapping my query like so:
SELECT @Start=SYSDATETIME()
SELECT TOP 1 b.COL_NAME FROM BLAH b WHERE b.key = 0x1234
SELECT @End=SYSDATETIME();
SELECT DATEDIFF(MICROSECOND,@Start,@End)

This shows that no time has elapsed at all.  But this isn't accurate because if I add WAITFOR DELAY '00:00:00.001', which should add a measurable millisecond of delay, it still shows 0 for the datediff.  Only if I wat for 2 milliseconds do I see it show up in the datediff

*Looking up the execution plan and getting the total_worker_time from the sys.dm_exec_query_stats table.
Here I see 600 microseconds, however the microsoft docs seem to indicate that this number cannot be trusted:

total_worker_time ...  Total amount of CPU time, reported in microseconds (but only accurate to milliseconds)

I've run out of ideas and could use some help.  Does anyone know how I can accurately measure my query in microseconds?  Would extended events help here?  Is there another performance monitoring tool I could use?  Thank you.

A: This is too long for a comment.
In general, you don't look for performance measurements measured in microseconds.  There is just too much variation, based on what else is happening in the database, on the server, and in the network.
Instead, you set up a loop and run the query thousands -- or even millions -- of times and then average over the executions.  There are further nuances, such as clearing caches if you want to be sure that the query is using cold caches.


text:
Q: duvida if campos Estou com um form onde o utilizador pode pesquisar por um intervalo de datas, ou por id, nome,nif
tenho o seguinte codigo:
$("#pesquisa").on("submit", function (event) {
    event.preventDefault();

    var key = document.getElementById("key").value;
    alert(key);
    var start = new Date(document.getElementById("datainicio").value);
    var end = new Date(document.getElementById("datafim").value);

    if (key !== "") {
        mostrarinfo();

    }

    var timeDiff = Math.abs(end.getTime() - start.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

    alert(diffDays);

    if (((diffDays < 180) {
        $("#estado").hide();

        mostrarinfo();
    } else {
        $("#estado").show();
    }

});

Só me esta a funcionar para a data,  para o campo key não queria pesquisa mesmo sem inserir a data.
Código HTML
<form id="pesquisa" class="navbar-form navbar-left" role="search" method="POST"  >

        KEY:
        <input type="search" class="form-control" placeholder="key"  hidden="hidden" name="key"  id="key" value=""/>

        De:
        <input class="form-control"   placeholder="Data inicio"  id="datainicio" hidden="hidden"  name="datainicio" type="date" value="<?php echo $_SESSION['datainicio']; ?>"/>
        a:
        <input class="form-control" placeholder="Data Final" id="datafim" name="datafim"  hidden="hidden" type="date"  value="<?php echo $_SESSION['datafim']; ?>"/>
        Estado:

    <button id ="submit" type="submit" class="btn btn-primary">Pesquisar</button>

    Intervalo de datas superior a 180 dias</input>
</form>


text:
Q: Displaying content in uiwebview I want to display information from web page in UIWebView. But the problem is website has headers, ads on the side etc. I want to display only the main content. Is this possible by any means?
Thanks!

A: Are you talking about a website? You could create a css specially for iPhone browser
<link type="text/css" rel="stylesheet" media="only screen and (max-device-width: 480px)" href="iPhone.css">

This stylesheet would be called only by an iPhone device.


text:
Q: Showing more than one slide at a time in bootstrap carousel I have a carousel that autoplays through a list of reviews. I need adjust it so that when it first loads, you also see half of the next review. When a review is in the middle, you should be able to see the second half of the previous review, and the first half of the following review. I need it to also smoothly slide, not just click to the next slide, if possible.
HTML

I can't wait to test this out.

 This is a testimonial window. Feedback of user can be displayed here.

Tester McTesty
  www.domain.com

I can't wait to test this out.

 This is a testimonial window. Feedback of user can be displayed here.

Testella McShanty
  www.domain2.com

I can't wait to test this out.

 This is a testimonial window. Feedback of user can be displayed here.

John Doe
  www.domain3.com

CSS
.carousel-indicators .active {
    background: #31708f;
}
.content {
    margin-top:20px;
}
.adjust1 {
    float:left;
    width:100%;
    margin-bottom:0;
}
.adjust2 {
    margin:0;
}
.carousel-indicators li {
    border :1px solid #ccc;
}
.carousel-control {
    color:#31708f;
    width:5%;
}
.carousel-control:hover, .carousel-control:focus {
    color:#31708f;
}
.carousel-control.left, .carousel-control.right {
    background-image: none;
}
.media-object {
    margin:auto;
    margin-top:15%;
}

Current Fiddle: LINK