text:
Q: LEFT JOIN expression not supported I need to do a query with a left outer join just like below, however Access is showing a warning dialog "JOIN expression not supported".I understand that Access doesn't support INNER JOIN nested inside a LEFT JOIN but as I am a beginner in SQL I don't see any other way to get the same result.
The goal of the query is to get everything that is in the select even when InvoiceItems.Amount is null.
SELECT MainOrder.OrderNumber, OrderComponent.ArticleNumber, SupplierOrderMain.*, InvoiceItems.Amount
FROM InvoiceItems LEFT JOIN
     ((MainOrder INNER JOIN
       OrderComponent
       ON MainOrder.OrderNumber = OrderComponent.OrderNumber
      ) INNER JOIN
      SupplierOrderMain
      ON OrderComponent.ID = SupplierOrderMain.OrderComponentID
     )
     ON InvoiceItems.OrderComponent = OrderComponent.ID;

A: I'm not sure why you would want outer joins in this situation at all (you don't explain why).  But just start with the table where you want to keep everything and work from there:
SELECT MainOrder.OrderNumber, OrderComponent.ArticleNumber, SupplierOrderMain.*, InvoiceItems.Amount
FROM ((InvoiceItems LEFT JOIN
       OrderComponent
       ON InvoiceItems.OrderComponent = OrderComponent.ID
      ) LEFT JOIN
      MainOrder
      ON MainOrder.OrderNumber = OrderComponent.OrderNumber
     ) LEFT JOIN
     SupplierOrderMain
     ON OrderComponent.ID = SupplierOrderMain.OrderComponentID


text:
Q: Access-Control-Allow-Origin while accessing I am facing a problem of Access-Control-Allow-Origin while accessing from Angular JS, How should I fix this error with POST Request.
Please Provide me a solution to access or Insert data with POST request in Angular JS, Now I m fine with GET request to access cross domain but not with POST Request
Backend is developed in python Django

A: Ask your backend(python django) developer to configure django-cors-headers

A Django App that adds CORS (Cross-Origin Resource Sharing) headers to responses.

It's the best solution I have got so far. It'll allow cross origin requests.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to combine 3 separate SQL statements into 1 set of results I have a SQL query that I am running 3 times (3 changing only the date range) and want to combine the result into one table, instead of running 3 different queries and trying to join outside of SQL. I am trying to find amount of times something has occurred per day/month/year. I'm running this in SQL Server.
I have 2 tables; one has the date of the transaction, and the other has the information I need (first 3 characters of the InventoryNumber table) so I am having to join these tables. I then want to group by the first 3 characters of the inventory number, and add the count in the column.
The end goal is to have something that looks like this:
InvNum | DayCount | MonthCount | YearCount
abc    | 2        | 10         | 40
def    | 0        | 2          | 6
xyz    | 0        | 0          | 2

Here is my query for the single day one. This works exactly like I want it to.  But now, I want to add on there the counts for the Month, and then the counts for the year also. The only thing that would change between this query and the other 2 is the count column name, and then the date.:
SELECT
    LEFT(LINEITEM.InventoryNumber, 3) AS InvNum,
    COUNT(*) AS DailyCount
FROM
    INVOICE
INNER JOIN
    LINEITEM ON INVOICE.InvoiceID = LINEITEM.InvoiceID
WHERE
    InventoryNumber IS NOT Null
    AND InventoryNumber != 'Misc'
    AND DateCreated > '5-20-2022'
GROUP BY
    LEFT(LINEITEM.InventoryNumber, 3)
ORDER BY
    InvNum ASC;

I have looked through some of the other questions similar to this, but their queries were much simpler and I was not able to replicate the same thing with my queries.
Any help is appreciated.

A: Without knowing enough here, you should consider a conditional aggregation
Declare @D Date='2022-05-20';

SELECT InvNum     = LEFT(LINEITEM.InventoryNumber, 3)
      ,DayCount   = sum( case when DateCreated = @D then 1 else 0 end )
      ,MonthCount = sum( case when month(DateCreated) = month(@D) then 1 else 0 end )
      ,YearCount  = sum( case when year(DateCreated) = year(@D) then 1 else 0 end )
 FROM  INVOICE
INNER JOIN  LINEITEM ON INVOICE.InvoiceID = LINEITEM.InvoiceID
WHERE InventoryNumber IS NOT Null
  AND InventoryNumber <> 'Misc'
  AND DateCreated >= format(@D,'yyyy-01-01')
GROUP BY LEFT(LINEITEM.InventoryNumber, 3)
ORDER BY InvNum ASC;

A: Looks like you need conditional aggregation with three different start dates.
DECLARE @D date = '2022-05-20';
DECLARE @M date = '2022-04-21';
DECLARE @Y date = '2021-05-21';

SELECT InvNum     = LEFT(li.InventoryNumber, 3)
      ,DayCount   = COUNT(CASE WHEN i.DateCreated >= @D THEN 1 END)
      ,MonthCount = COUNT(CASE WHEN i.DateCreated >= @M THEN 1 END)
      ,YearCount  = COUNT(*)
 FROM INVOICE i
INNER JOIN LINEITEM li ON i.InvoiceID = li.InvoiceID
WHERE li.InventoryNumber <> 'Misc'
  AND i.DateCreated >= @Y
GROUP BY
  LEFT(li.InventoryNumber, 3)
ORDER BY
  InvNum;

Note that <> 'Misc' also excludes nulls, and that ASC is the default.

You can also calculate those start dates dynamically
DECLARE @D date = DATEADD(day, -1, CAST(GETDATE() AS date));
DECLARE @M date = DATEADD(month, -1, CAST(GETDATE() AS date));
DECLARE @Y date = DATEADD(year, -1, CAST(GETDATE() AS date));

A: This maybe will do the work for you:
SELECT ISNULL(DailyQuery.InvNum, ISNULL(MonthlyQuery.InvNum, YearlyQuery.InvNum)) as InvNum,
       ISNULL(DailyCount,0) as DailyCount,
       ISNULL(MonthlyCount,0) as MonthlyCount,
       ISNULL(YearlyCount,0) as YearlyCount
FROM
(SELECT
    LEFT(LINEITEM.InventoryNumber, 3) AS InvNum,
    COUNT(*) AS DailyCount
FROM
    INVOICE
INNER JOIN
    LINEITEM ON INVOICE.InvoiceID = LINEITEM.InvoiceID
WHERE InventoryNumber != 'Misc'
    AND DateCreated > DATEADD(day, DATEDIFF(day, 0,  GETDATE()-1), 0) --first hour day before
GROUP BY
    LEFT(LINEITEM.InventoryNumber, 3)
) DailyQuery
FULL JOIN
(SELECT
    LEFT(LINEITEM.InventoryNumber, 3) AS InvNum,
    COUNT(*) AS MonthlyCount
FROM
    INVOICE
INNER JOIN
    LINEITEM ON INVOICE.InvoiceID = LINEITEM.InvoiceID
WHERE InventoryNumber != 'Misc'
    AND DateCreated > DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0) --first day of current month
GROUP BY
    LEFT(LINEITEM.InventoryNumber, 3) ) MonthlyQuery ON DailyQuery.InvNum = MonthlyQuery.InvNum
FULL JOIN
(SELECT
    LEFT(LINEITEM.InventoryNumber, 3) AS InvNum,
    COUNT(*) AS YearlyCount
FROM
    INVOICE
INNER JOIN
    LINEITEM ON INVOICE.InvoiceID = LINEITEM.InvoiceID
WHERE InventoryNumber != 'Misc'
    AND DateCreated > DATEADD(year, DATEDIFF(year, 0, GETDATE()), 0) --first day of current month
GROUP BY
    LEFT(LINEITEM.InventoryNumber, 3) ) YearlyQuery ON MonthlyQuery.InvNum = YearlyQuery.InvNum

A: you need to write three queries each query results in these tables based on the column and date in the where clause
just change the column and date value in the where clause for each table
first query result
InvNum | DayCount
abc    | 2
def    | 0
xyz    | 0

second query result:
InvNum  | MonthCount
abc     | 10
def     | 2
xyz     | 0

third query result:
InvNum | YearCount
abc    | 40
def    | 6
xyz    | 2

and then join these three tables on InvNum column


text:
Q: ruby - can't write to logs in daemons Normally I can write logs with Logger:
//abc.rb
require 'logger'
logger = Logger.new('foo.log')

$./abc.rb

But in a Daemons I got a permission error:
//xyz.rb
require 'logger'
require 'daemons'

Daemons.run_proc('xyz') do
  logger = Logger.new('foo.log')
end

$./xyz.rb
/home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:599:in `initialize': Permission denied - foo.log (Errno::EACCES)
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:599:in `open'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:599:in `create_logfile'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:594:in `open_logfile'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:549:in `initialize'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:314:in `new'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:314:in `initialize'

I ran abc.rb and xyz.rb in the same directory and with the same identity. Why can't one log as the other can?

A: Here's the reason. From the Daemons documentation.
I have put in bold the relevant part for you:

What does daemons internally do with my daemons?
From a technical aspect of view, daemons does the following when creating a daemon:

*

*Forks a child (and exits the parent process, if needed)

*Becomes a session leader (which detaches the program from the controlling terminal).

*Forks another child process and exits first child. This prevents the potential of acquiring a controlling terminal.

*Changes the current working directory to "/".

*Clears the file creation mask (sets umask to 0000).

*Closes file descriptors (reopens STDOUT and STDERR to point to a logfile if possible).

So after you start the daemon you should either change your current working directory (Dir.chdir) to the directory you want to use for logging, or use absolute paths for your logfiles.


text:
Q: Accessing AngularJS model objects via an array? I've got an interesting problem (to me at least).
I'm on a project where we are getting data from an API and its nesting a set of objects in an array.  We want to be able to display/edit them individually.  The tricky part is getting to them from the view.  Here's the setup using a similar but made up scenario.
User navigates to /profile/exploit/1
Ideally we grab that parameter and use it to filter the array.  Here's the sample JS (without the param, I'm hardcoding the value for simplicity)
var app = angular.module('app',[]);

app.controller('AppCtrl', ['$scope',
  function($scope) {
    // The data is coming in from the API in a similar format.
    // There is an array with objects in it, and we need
    // display and/or edit those individual records
    // This is a way simplified version of it
    // (and nothing like the real data, haha)
    $scope.profile = {
      name: "Alexander",
      location: "Earth",
      exploits: [
        {name: "Conquer Achaemenid empire", year: "334 BC", duration: 3},
        {name: "Conquer the Balkans", year: "335 BC", duration: 4},
        {name: "Conquer the Persian Empire", year: "334 BC", duration: 6}
      ],
    }
    // I planned to set this with a parameter /profile/exploits/1
    e = 1;
  }]);

And, here's the HTML

    <link rel="stylesheet" href="style.css" />

      Name: {{ profile.exploits[0].name }}

      Year: {{ profile.exploits[0].year }}

      Duration: {{ profile.exploits[0].duration }} months

What I'd like to do is something like:
    {{ profile.exploits[e].name }}
Where e sets the record in the array.  But I can't for the life of me figure out how to make that happen.  Seriously hoping it's something ridiculously simple.
I've got a mock of it here http://embed.plnkr.co/XhIlJt8BGCAkw70tRTgn/preview

A: You can pull info from the url with $location.  So try something like this:
var app = angular.module('app',[]);

app.controller('AppCtrl', ['$scope', '$location', function($scope, $location) {

  $scope.profile = {
    name: "Alexander",
    location: "Earth",
    exploits: [
      {name: "Conquer Achaemenid empire", year: "334 BC", duration: 3},
      {name: "Conquer the Balkans", year: "335 BC", duration: 4},
      {name: "Conquer the Persian Empire", year: "334 BC", duration: 6}
    ],
  }

  $scope.activeProfile = function() {
    var i = $location.path();  //Should be your desired value
    return $scope.profile.exploits[i];
  }

}]);

Hope this helps,
Jordan


text:
Q: How do I get the profile URL of a user? I want to create a custom view for profile pages, So I Want to get the profile URLs. Something like $node_url that get the profile URL.

A: Are you using pathauto or Profile 2?
If not the URL looks like
www.example.com/username
www.example.com/user/UID.

Check the documentation about Drupal paths and URL aliases.


text:
Q: My player is switching between animations when it is not programed to When my player is moving, the animation switches between idle and walk when I am holding down D. I played the animation and it looks fine but when I play the transition it starts idle and switches to walk. I have tried creating a new project and doing it again but it does the same thing. Does anyone know how to fix this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    [SerializeField]
    float moveForce = 10f;

    [SerializeField]
    float jumpForce = 11f;

    float movementX;

    Rigidbody2D myBody;

    Animator Anim;

    private SpriteRenderer sr;

    string WALK_ANIMATION = "Walk";

    private void Update()
    {
        playerMoveKeyboard();
        animatePlayer();
    }

    private void Awake()
    {
        myBody = GetComponent<Rigidbody2D>();
        Anim = myBody.GetComponent<Animator>();
        sr = GetComponent<SpriteRenderer>();

    }
    void playerMoveKeyboard()
    {
        movementX = Input.GetAxisRaw("Horizontal");
        transform.position += new Vector3(movementX, 0f, 0f) * moveForce * Time.deltaTime;
    }
    void animatePlayer()
    {
        if(movementX > 0)
        {
            Anim.SetBool(WALK_ANIMATION, true);
            sr.flipX = false;
        }
        else if (movementX < 0)
        {
            Anim.SetBool(WALK_ANIMATION, true);
            sr.flipX = true;
        }
        else
        {
            Anim.SetBool(WALK_ANIMATION, false);
        }

    }
}

A: Not sure if I am seeing the problem correctly from the gif, but can't you just turn off "Has exit time" and change the transition duration to 0?

A: Not sure but using a float instead of a bool to decide when to play the animation might solve this. That is how I've been doing it and never had any problems.
Do this by creating a new parameter in the animator called "Speed". Change the condition from idle to walk to Speed greater 0.01 and walk to idle to Speed less 0.01 or some other small number.
In the code you can change "Speed" to the player speed by adding:
anim.setFloat("Speed", Mathf.Abs(movementX))

to the update function inside the player movement script.
You should also remove the Anim.SetBool() from  the funciton animatePlayer().


text:
Q: Firebase JS SDK warning while using firebase database in reactjs I am trying to use firebase database for my project but I am unable to properly import and use the module. I have followed what the official documentation recommends.
This is the code where I am using it.
import React from "react";
import firebase from "firebase";
import ProjectItemCards from "./components/project-item-cards";

const ProjectContext = React.createContext();

class ProjectProvider extends React.Component {
  constructor() {
    super();
    this.state = {
      social: {},
      projects: [],
      featuredProjects: [],
      loading: true,
    };
  }

  componentDidMount() {
    var ref = firebase.database().ref("projects");

    ref.on("value", (snapshot) => {
      const projects = snapshot.val();

      console.log(projects);

      const featuredProjects = projects
        .map((project) => (project.featured === true ? project : null))
        .slice(0, 4);

      this.setState({
        projects,
        featuredProjects,
        loading: false,
      });
    });
  }

  getProjectElements(projects) {
    const projectElementList = projects.map((project, index) => {
      return (
        <ProjectItemCards key={index} project={project}></ProjectItemCards>
      );
    });
    return projectElementList;
  }

  render() {
    return (
      <ProjectContext.Provider
        value={{ ...this.state, getProjectElements: this.getProjectElements }}
      >
        {this.props.children}
      </ProjectContext.Provider>
    );
  }
}

export { ProjectProvider, ProjectContext };

I have initialized firebase as follows
import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

import "bootstrap";
import "./sass/main.scss";

import * as firebase from "firebase/app";
import "firebase/analytics";

var firebaseConfig = {
  apiKey: process.env.REACT_APP_API_KEY,
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "1:841600272388:web:12314d1260dded0601cd51",
  measurementId: "G-55E4QT6C4F",
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();

ReactDOM.render(<App />, document.getElementById("root"));

I have removed all sensitive information from above code
Also note that I am getting my data as required and everything is working fine. I just want to get rid of this warning

A: initialization code should be used in a utility file and look like the following:
import * as firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/storage'

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID
}

firebase.initializeApp(firebaseConfig)

export const db = firebase.firestore()
export const storage = firebase.storage()
export default firebase

you want to export the individual firebase features you are utilizing.  In your case I would assume firebase.firestore
then your import should look like so:
import {db} from '../utils/firebase'


text:
Q: Counting how many numbers in an array are between 1.5 - 35 C# I am trying to work out how to count how many numbers in an array fall between the values of, 1.5 - 35. I am struggling to work out which method I should use to achieve this. I was thinking maybe a for-each embedded loop but then the more I think about it the more I question that method. Any help would be appreciated on how I may achieve this, I will post my current code below as I have already worked out how to calculate the average and minimum price for the equation.
class Program
{
    static void Main(string[] args)
    {
        read_stock_price();
    }
    static void read_stock_price()
    {
        Console.Write("Enter how many stocks to enter price for: ");
        int numStocks = Convert.ToInt32(Console.ReadLine());

        double[] arrayinput = new double[numStocks];

        for (int i = 0; i < numStocks; ++i)
        {
            Console.Write("Enter price for stock number: ");
            arrayinput[i] = Convert.ToDouble(Console.ReadLine());
        }

        double sum = arrayinput.Sum();
        double average = sum / numStocks;

        Console.WriteLine("Average price: {0} out of {1} stocks", average, numStocks);
        Console.WriteLine("Minimum price: {0}", arrayinput.Min());

    }
}

A: You can use LINQ instead of a for-each.  First filter the array then count the elements.
var count = arrayinput
   .Where(x => 1.5 <= x && x <= 35.0)
   .Count();

A: Shortest way is Enumerable.Count
var count = arrayinput.Count(x => 1.5 < x && x < 35.0);

A: if we assumed arrayinput is your filled array you can use this:
     double[] arrayinput = new double[numStocks];

     double[] filteredArray = arrayinput.Where(p => p > 1.5 && p < 3.5).ToArray();

     int count = filteredArray.Count();

this code filter your array with value between 1.5 & 3.5.


text:
Q: On Azure Portal, is it possible to disable Informational toast notifications only? On Azure Portal, we started receiving some toast information notifications advertising the slot deployment feature on Azure WebApp.
Thoses notifications could be great when you don't know this feature. It's less great when you are already aware of this feature and can't disable this kind of notification.
It also seems that this notification is triggered each time a deployment is done on WebApps that does not use the slot deployment feature. You get spammed when you have a lot of WebApps, rendering those notifications useless :(
Each time you open the portal, you receive this spam :

The only way I found was to disable completely the toast notifications in the Azure portal settings :

That's not a good solution, we still want to get errors and warnings notifications.
Is there a way to disable only the App Service Advisor Informational notifications ?


text:
Q: glReadPixels is not working with GL_FLOAT I'm using OpenGL shader and trying to print the color values.
So, I used glReadPixels function. It is working with GL_UNSIGNED_BYTE but not with GL_FLOAT.
Is there anything else should I do?
This is my code.
void settingFrameBuffers()
{
    glGenFramebuffers(NUM_FBO, fbo);
    glGenTextures(NUM_FBO, tex);

    for (int i = 0; i < NUM_FBO; i++)
    {
        glBindFramebuffer(GL_FRAMEBUFFER, fbo[i]);
        glBindTexture(GL_TEXTURE_2D, tex[i]);

        if (i == 0) glActiveTexture(GL_TEXTURE0);
        else if (i == 1) glActiveTexture(GL_TEXTURE1);
        else if (i == 2) glActiveTexture(GL_TEXTURE2);
        else if (i == 3) glActiveTexture(GL_TEXTURE3);
        else if (i == 4) glActiveTexture(GL_TEXTURE4);
        else if (i == 5) glActiveTexture(GL_TEXTURE5);

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, NULL);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex[i], 0);

        GLuint dbo;
        glGenRenderbuffers(1, &dbo);
        glBindRenderbuffer(GL_RENDERBUFFER, dbo);
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height);

        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, dbo);

        glDrawBuffer(GL_COLOR_ATTACHMENT0);
    }
}

void printWholeMassToConsole()
{
    GLfloat* data =new GLfloat[4 * width*height];

    glBindFramebuffer(GL_FRAMEBUFFER, fbo[otFb]);
    //glReadPixels(0, 0, width, height, GL_RGBA, GL_FLOAT, data);
    glReadnPixels(0, 0, width, height, GL_RGBA, GL_FLOAT, sizeof(data), data);

    float sumR = 0;
    float sumG = 0;
    float sumB = 0;

    for (int i = 0; i < 4 * width*height; i += 4)
    {
        if (i > 0) break;
        sumR += data[i];
        sumG += data[i + 1];
        sumB += data[i + 2];
    }

    float sum = sumR + sumG + sumB;

    float possibleDiff = 3.0*width*height*0.5;
    //if (abs(wholeMass - sum) <= possibleDiff) cout << "O - ";
    //else cout << "X - ";
    printf("mass : %d\t %d\t %d\t %d\n", sum, sumR, sumG, sumB);

    free(data);
}

This is the first shader.
// vertex shader
#version 450

in vec4 position;
in vec2 texCoord;

out vec2 fragTexCoord;

void main()
{
    gl_Position = position;
    fragTexCoord = texCoord;
}

// fragment shader
#version 450

in vec2 fragTexCoord;

out vec4 FragColor;

void main()
{
    FragColor = vec4(0.5, 0.0, 0.0, 1.0);
}

This is the second shader.
// vertex shader
#version 450

in vec4 position;
in vec2 texCoord;

out vec2 fragTexCoord;

void main()
{
    gl_Position = position;
    fragTexCoord = texCoord;
}

// fragment shader
#version 450

in vec2 fragTexCoord;

uniform sampler2D tex;

out vec4 FragColor;

void main()
{
    FragColor = texture(tex, fragTexCoord);
}

It draws something on otFb framebuffer through the first shader and then otFb texture is mapped on the main framebuffer.
When I use glReadPixels with GL_FLOAT, the program is terminated by itself, when glReadnPixels with GL_FLOAT, the program print garbage values.
I used so many times to search, but I could not find the solutions.
Or is there any different way that I can try?

A: Try changing the first parameter of the framebuffer binding function call(the second line of code in your printWholeMassToConsole function) i.e.:
glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo[otFb]);

Hope it works.


text:
Q: PHP: Object properties can be assigned functions, but then those can't be invoked? Reproduced with this code
<?php
$justReturn1 = function() { return 1;};

class A {
        public $f;
        public function __construct($func) {
                $this->f = $func;
        }
}

$instance = new A($justReturn1); // Create instance

$f = $instance->f; // Assign the function within $instance->f to a variable external to object

echo $f(); // Returns: 1
echo $instance->f(); // Returns: Fatal error: Call to undefined method A::f()

The same function can be invoked if I assign it to a variable, but can't be invoked if I assign it to an object property.
This is really annoying, since I was counting on this consistency (common sense).
I'm writing a class that receives a big configuration array with some validation functions inside it. I then store those validation functions on an object just fine, but I need an indirection step (creating a variable and assigning this function to it) before I can invoke them!
Is there a flaw in my test? Is this actually PHP unimplementedness?


text:
Q: Quantile functions in Python I'm having trouble finding quantile functions for well-known probability distributions in Python, do they exist?  In particular, is there an inverse normal distribution function?  I couldn't find anything in either Numpy or Scipy.

A: Check the .ppf() method of any distribution class in scipy.stats.
This is the equivalent of a quantile function (otherwise named as percent point function or inverse CDF)
An example with the exponential distribution from scipy.stats:
# analysis libs
import scipy
import numpy as np
# plotting libs
import matplotlib as mpl
import matplotlib.pyplot as plt

# Example with the exponential distribution
c = 0
lamb = 2

# Create a frozen exponential distribution instance with specified parameters
exp_obj = scipy.stats.expon(c,1/float(lamb))

x_in = np.linspace(0,1,200) # 200 numbers in [0,1], input for ppf()
y_out = exp_obj.ppf(x_in)
plt.plot(x_in,y_out) # graphically check the results of the inverse CDF

A: It seems new but I've found this about numpy and quantile. Maybe you can have a look (not tested)


text:
Q: DataFrame.to_csv throws error '[Errno 2] No such file or directory' I am trying to write a DataFrame to a .csv file:
now = datetime.datetime.now()
date = now.strftime("%Y-%m-%d")

enrichedDataDir = "/export/market_data/temp"
enrichedDataFile = enrichedDataDir + "/marketData_optam_" + date + ".csv"

dbutils.fs.ls(enrichedDataDir)
df.to_csv(enrichedDataFile, sep='; ')

This throws me  the following error

IOError: [Errno 2] No such file or directory:
  '/export/market_data/temp/marketData_optam_2018-10-12.csv'

But when i do
dbutils.fs.ls(enrichedDataDir)

Out[72]: []

There is no error! When i go on the directory levels (one level higher):
enrichedDataDir = "/export/market_data"
dbutils.fs.ls(enrichedDataDir)

Out[74]:
[FileInfo(path=u'dbfs:/export/market_data/temp/', name=u'temp/', size=0L)
 FileInfo(path=u'dbfs:/export/market_data/update/', name=u'update/', size=0L)]

This works, too. This mean for me that i have really all the folders which i want to access. But i dont know thy the .to_csv option throws the error. I also have checked the permissions, which are fine!

A: The main problem was, that i am using Micrsoft Azure Datalake Store for storing those .csv files. And for whatever reason, it is not possible through df.to_csv to write to Azure Datalake Store.
Due to the fact that i was trying to use df.to_csv i was using a Pandas DataFrame instead of a Spark DataFrame.
I changed to
from pyspark.sql import *

df = spark.createDataFrame(result,['CustomerId', 'SalesAmount'])

and then write to csv via the following lines
from pyspark.sql import *

df.coalesce(2).write.format("csv").option("header", True).mode("overwrite").save(enrichedDataFile)

And it works.

A: Here is a more general answer.
If you want to load file from DBFS to Pandas dataframe, you can do this trick.

*

*Move the file from dbfs to file
%fs cp dbfs:/FileStore/tables/data.csv file:/FileStore/tables/data.csv

*Read data from file dir
data = pd.read_csv('file:/FileStore/tables/data.csv')
Thanks

A: have you tried opening the file first ? (replace last row of your first example with below code)
from os import makedirs
makedirs(enrichedDataDir)

with open(enrichedDataFile, 'w') as output_file:
    df.to_csv(output_file, sep='; ')

A: check the permissions on the sas token you used for the container when you mounted this path.. if it starts with "sp=racwdlmeopi" then you have a sas token with immutable storage.. your token should start with "sp=racwdlmeop"


text:
Q: Redirect Match. Remove Numbers from Url Just in need of some assistance with some redirects.
I have the following url I need to remove the ending number from:
http://www.testsite.com/category/subactegory/this-product-name-12966.html
So it becomes:
http://www.testsite.com/category/subactegory/this-product-name.html
I have tried the following but cant quite crack it.
RedirectMatch 301 ^-([0-9]+).html http://www.testsite.com/$1.html
Any help would be greatly appreciated
Brendan

A: Actually your regex is little incorrect. Try this:
RedirectMatch 301 ^/(.+?)-([0-9]+)\.html$ /$1.html


text:
Q: How is "composite" as a verb pronounced in British English? I always pronounce "composite" as COM-posite when it is used as an adjective or a noun. But in some technical contexts as "alpha compositing" it is also used as a verb, and in this case I discovered myself reading out as com-POZ-ite. As a non-native speaker of English, I got unsure about the pronunciation, so I looked up in several dictionaries.

*

*Merriam-Websters list (käm-ˈpä-zət) as the main pronunciation, and (ˈkäm-pə-zit) as "especially British".

*dictionary.com, which uses Random House Unabridged dictionary as its main, lists (kuhm-poz-it) as the only pronunciation, so it seems stressing the second syllable is the norm in American English.

*dictionary.com also has a British English dictionary when you scroll down, which is Collins English Dictionary. For the adjective and the noun, the given pronuncation is (ˈkɒmpəzɪt), and for the verb, they suggest (ˈkɒmpəˌzaɪt). I also checked the website of Collins dictionary, and when you scroll down, they do list (ˈkɒmpəˌzaɪt) as a pronunciation for the verb with a voice recording.

*The online version of Oxford and Cambridge English dictionary doesn't have an entry of "composite" as a verb.

*Wiktionary says (ˈkɒmpəzɪt) is the Canadian or "received" pronunciation and (kəmˈpɑzɪt) is the American pronunciation.

Gathering all these it seems it's okay to stick to (ˈkɒmpəzɪt) regardless of the type (verb, noun, etc.) of the word, but this way, isn't it a bit uncomfortable to pronounce with a suffix, like "compositing" as COM-positing?
I'm wondering how actual British English speakers pronounce this word as a verb. Collins dictionary is making things more confusing as they list (ˈkɒmpəˌzaɪt) as the pronunciation for the verb. It the word actually pronounced this way?

A: Judging by the rather rare examples that can be found online, your tendency of stressing the second syllable is consistent with how native British English speakers pronounce "composite" as a verb in technical contexts: /kəmˈpɒzɪt/.

*

*Here's the phrase "chroma key compositing" in British English on Forvo.

*British graphics expert Simon Ubsdell has a series of tutorials on compositing theory where you can hear him using it as a verb, with second-syllable stress.

*UK-based game designer Grant Abbitt has a tutorial video on how to use a compositor where he uses the same stress pattern.

The only example I've encountered so far that doesn't use second-syllable stress for the verb is the Collins Dictionary recording you cited in the question. So even though there are other British pronunciations out there for the word in isolation, it's safe to say that some (not necessarily all) British English speakers use the pronunciation with second-syllable stress in the context you're asking about.

A: The OED gives:
composite, v.
Pronunciation: /kɒmpəˈzʌɪt/
Politics. transitive. To amalgamate (resolutions put before a party conference or Trades Union Congress) into one composite resolution.


text:
Q: Moving from one enum state to the next and cycling through I simply have enumerator with 3 modes ledOn, ledBlink, ledOFF and I have a variable mode that keeps track of modes for particular object. So for example I have one LED starting in mode ledOn i would like to for example after 5 seconds move to the next element which would be ledBlink then to ledOFF and then cycle through to ledON is there an easy way to achieve something like this?
import time
from threading import Thread
from enum import Enum

class ledController(Thread):
    ledModes = Enum('ledModes', 'ledON ledBlink ledOFF')
    def __init__(self, GPIOID, state=False, blinkDuration=2, mode=ledModes.ledON):
        self.GPIOID = GPIOID
        self.state = state
        self.blinkDuration = blinkDuration
        self.mode = mode
        self.blinked = False
        Thread.__init__(self)
    def run(self):
        if(self.mode == self.ledModes.ledON):
            self.ledON()
        if(self.mode == self.ledModes.ledBlink):
            self.ledBlink()
        if(self.mode == self.ledModes.ledOFF):
            self.ledOFF()
        time.sleep(self.blinkDuration)
        self.mode.next()
    def ledSwitch(self):
        self.state = not self.state
        print(self.ledDetails())
    def ledON(self):
        self.state = True
        print(self.ledDetails())
    def ledOFF(self):
        self.state = False
        print(self.ledDetails())
    def ledBlink(self, duration):
        self.ledON()
        print(self.ledDetails())
        time.sleep(self.Blinkduration)
        self.ledOFF()
        print(self.ledDetails())
        time.sleep(self.Blinkduration)
    def ledDetails(self):
        return "Thread: "+self.getName()+", LED: "+str(self.GPIOID)+", State: "+str(self.state)+", Mode: "+str(self.mode.name)+", Blink duration: "+str(self.blinkDuration)

redLED = ledController(17, blinkDuration = 3)
blueLED = ledController(18, mode = ledController.ledModes.ledOFF)

redLED.setName('1')
blueLED.setName('2')

redLED.start()
blueLED.start()

redLED.join()
blueLED.join()

A: I would just use itertools.cycle instead of your enum:
>>> from itertools import cycle
>>> ledModes = cycle(['ledON', 'ledBlink', 'LedOFF'])
>>> first = next(ledModes)
>>> second = next(ledModes)
>>> third = next(ledModes)
>>> fourth = next(ledModes)
>>>
>>> first
'ledON'
>>> second
'ledBlink'
>>> third
'LedOFF'
>>> fourth
'ledON'
>>>

FYI, you can either do next(ledModes) or ledModes.next(), both are doing the same.
EDIT: You could use something like this, as method of your class:
from itertools import cycle

def initialize_cycle(start_mode):
    states = ['ledON', 'ledBlink', 'ledOFF']

    if start_mode not in states:
        raise ValueError('start_mode invalid')

    iterable = cycle(states)
    for _ in states[:states.index(start_mode)]:
        iterable.next()

    return iterable

test1 = initialize_cycle('ledON')
test2 = initialize_cycle('ledOFF')
test3 = initialize_cycle('ledBlink')

# validation
for test in test1, test2, test3:
    for _ in range(5):
        print test.next()
    print '-' * 20

Output:
$ python cycle.py
ledON
ledBlink
ledOFF
ledON
ledBlink
--------------------
ledOFF
ledON
ledBlink
ledOFF
ledON
--------------------
ledBlink
ledOFF
ledON
ledBlink
ledOFF
--------------------

A: The easiest fix for your current code is to:

*

*change your run method, and

*add a next_mode method:

like so:
def run(self):
    while True:
        set_mode = getattr(self, self.mode)
        set_mode()
        time.sleep(self.blinkDuration)
        self.next_mode()

def next_mode(self):
    self.mode = {
            self.ledModes.ledON: self.ledModes.ledBlink,
            self.ledModes.ledBlink: self.ledModes.ledOFF,
            self.ledModes.ledOff: self.ledModes.ledOn,
            }[self.mode]

A: Probably an overkill:
import itertools

class EnumCycler(object):
    def __init__(self, enum, start_at=None):
        self.enum = enum
        self.members = list(enum.__members__.values())
        self.start_at = self.members[0] if start_at is None else start_at
        self.cycles = 0

    def __iter__(self):
        cycle = itertools.cycle(self.members)
        sanity_check = len(self.members)
        for value in cycle:
            if sanity_check:
                if value != self.start_at:
                    sanity_check -= 1
                    continue
                sanity_check = 0
            self.cycles += 1
            yield value

Then:
>>> mode = Enum('ledModes', 'ledON ledBlink ledOFF')
>>> led_mode_cycler = EnumCycler(mode, start_at=mode.ledOFF)
>>> for value in led_mode_cycler:
...     print(led_mode_cycler.cycles, value)
...     if led_mode_cycler.cycles >= 10: break  # infinite loop if we never break off
1 ledModes.ledOFF
2 ledModes.ledON
3 ledModes.ledBlink
4 ledModes.ledOFF
5 ledModes.ledON
6 ledModes.ledBlink
7 ledModes.ledOFF
8 ledModes.ledON
9 ledModes.ledBlink
10 ledModes.ledOFF


text:
Q: When use Google Bigquery in Google Dataflow After a few days testing and developing some Google Dataflow templates with python, I'm questioning myself  about if using BigQuery is appropriate for our project.

Why this thoughts?

*

*BigQuery focuses on Online Analytical Processing (OLAP) so treat
BigQuery like an Online Transaction Processing (OLTP) it might not be
the best option.
Even knowing that, I decided to use BQ, because it has better compatibility with Google Dataflow.

*

*After develop a first version of a python dataflow's template and try with a few data this works well. Using streaming or batch execution of this pipeline I don't have any special issues.
The problems begin when I try to use BQ like OLTP. Here is where I found some issues due to my use case: In some case, I can not use bulk updates and I have to use single row mutations, so I have to use DML sentences to perform this task. The result is that the execution time begin to increase considerable with hundred of single row mutations.

*

*Even If I assume this increase of time, I found that in BQ you can only use 1,000 updates per table per day. (More quotes)

Alternatives
Here is where I'm not sure about which other services should I use instead of BigQuery:

*

*Cloud SQL is the OLTP database of Google. This could be the appropriate for my use case, but: is Cloud SQL work as fast as BQ if I try to analyze the data? I will have many tables with million of rows and, for example, working with Microsfot Sql Server is not sufficient for me due to the high processing times.

*How Cloud SQL work with apache beam and pipelines?

*Works with Cloud SQL and migrate data to BigQuery each day to avoid make single row mutations in BQ?

*Which service could be the best to use in this case?

A: How Cloud SQL work with apache beam and pipelines?
The o/p of final transform will be a collection not a string, Writing collection to cloudsql might get overloads, high latency. You could write using MySqlDb.connect in #pardo function where you process single element[TableRow] [Not a good practice].
Works with Cloud SQL and migrate data to BigQuery each day to avoid make single row mutations in BQ?
You can write a python script which exports data from cloudsql table to either GCS or LocalStorage[where your script is scheduled to run] and then upload back to BQ.
But you've to make sure about NULL Values. When you export data as a file, Null values in table will be replaced with ['N] leads to inappropriate row-value count while uploading to BQ.
This all can be done with single python script.
Which service could be the best to use in this case?

A: I would avoid using BigQuery for transactional workloads, as it tends to be very inefficient for update operations. Similarly, Cloud SQL will be good for transactional workloads but slow for analytical ones.
If you need a database that can both handle updates and an analytical workload, I'd suggest looking into BigTable. You can read about how to pick a storage option for GCP here.
Another option, as you said, would be doing all your transactional work in Cloud SQL and once a day or so syncing it to BigQuery and doing the analytical work there, for instance WePay uses a workflow like that.
To address your other question, yes, Dataflow can work with Cloud SQL without any issue just connecting normally, just make sure to use connection pooling to avoid running out of connections.


text:
Q: How to import or use js file configuration into any vue page in your nuxt app I have a Nuxt project of listing booking.
I have done all my API calls and configuration in index.js in the store folder.  I would link to display the listing gotten from the API call on my listing.vue page.
How do I print my retrieved data or make my index.js accessible anywhere in the app?
package.json
{
  "name": "lisngbook",
  "version": "1.0.0",
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate"
  },
  "dependencies": {
    "@nuxtjs/axios": "^5.13.6",
    "core-js": "^3.9.1",
    "nuxt": "^2.15.3",
  },
  "devDependencies": {
    "@nuxtjs/moment": "^1.6.1"
  },


text:
Q: How can I get rect from a sprite group? I have a spritegroup. When a member of the spritegroup has a collision, I want to know the rect's position. Here I got the error message  'Group' object has no attribute 'x'
class Landschaft(pygame.sprite.Sprite):
    def __init__(self,image):
        pygame.sprite.Sprite.__init__(self)
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.x = random.randrange(60, breite -60)
        self.rect.y = random.randrange(100, hoehe - 200)
        self.rect.center = ( self.rect.x,self.rect.y)

land = pygame.sprite.Group()

for i in range(5):
      image = gegend[i]
      m = Landschaft(image)
      hits = pygame.sprite.spritecollide(m,land,True)

      if hits:
          i-=1
          print(land.rect.x)

      land.add(m)

A: A Group has no rectangle and position. Only the items in the Group have a .rect attribute.
pygame.sprite.spritecollide returns a list of sprites.
Furthermore you need to pass False to the doKill argument of spritecollide. If the parameter is True, all Sprites that collide will be removed from the Group.
You have to pass False to doKill:
hits = pygame.sprite.spritecollide(m, land, False)
for hit_sprite in hits:
    i-=1
    print(hit_sprite.rect.x)

Also see How do I detect collision in pygame?


text:
Q: I'm a having an error with my flutter code when I run it The error says CastError (type 'Null' is not a subtype of type 'List<Map<String, Object>>' in type cast). When I try to debug the code, it point me to line 18 with that error message. Kindly assist me with it. I'm new to flutter development.
import 'package:flutter/material.dart';
import './question.dart';
import './answer.dart';

class Quiz extends StatelessWidget {
  final List<Map<String, Object>> questions;
  final int questionIndex;
  final Function answerQuestion;
  // const Quiz({super.key});

  Quiz({required this.questions, required this.answerQuestion, required this.questionIndex});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Question(questions[questionIndex]['questionText'] as String),
        ...(questions[questionIndex]['answers'] as List<Map<String, Object>>).map((answer) {
          return Answer(() => answerQuestion(answer['score']), answer['text'] as String);
        }).toList()
      ],
    );
  }
}

This is the code

A: According to the error message you posted, the data is null.
Specifically, questions[questionIndex]['answers'] is null. Try print out the data and see if you made any typo in the property name. You can do that by adding a print(questions[questionIndex]['answers']); before your return Column(...) statement.


text:
Q: Label won't appear on tkinter pop-up window I've been making an app in python and I made a pop-up window to add a new reminder, but the "reminder", "date" and "time" labels don't appear on the new window. The "add new reminder" label also shows up at the bottom left of the window instead of the top center.
I've tried packing and grid configure, but they still don't show up.
def popup():
    pop = tk.Toplevel()
    pop.wm_title("New Reminder")

    label = ttk.Label(pop, text="Add new reminder.")
    label.grid(row=0, column=1)
    label2 = ttk.Label(pop, text="Reminder")
    label.grid(row=1, column=0)
    label3 = ttk.Label(pop, text="Date")
    label.grid(row=2, column=0)
    label4 = ttk.Label(pop, text="Time")
    label.grid(row=3, column=0)

    rem = ttk.Entry(pop)
    rem.grid(row=1, column=1)
    date = ttk.Entry(pop)
    date.grid(row=2, column=1)
    time = ttk.Entry(pop)
    time.grid(row=3, column=1)

    addbutton = ttk.Button(pop, text="Add", command=pop.destroy)
    addbutton.grid(row=4, column=0)
    canbutton = ttk.Button(pop, text="Cancel", command=pop.destroy)
    canbutton.grid(row=4, column=1)

    pop.mainloop()

What instead shows up is the three entries stacked vertically at the top with the "add new reminder" label to the left of the last entry

A: Layout problems are much easier to visualize when you separate widget creation from widget layout.
Here's your layout code grouped together:
label.grid(row=0, column=1)
label.grid(row=1, column=0)
label.grid(row=2, column=0)
label.grid(row=3, column=0)
rem.grid(row=1, column=1)
date.grid(row=2, column=1)
time.grid(row=3, column=1)
addbutton.grid(row=4, column=0)
canbutton.grid(row=4, column=1)

Notice how you are calling grid on label four times, and never call grid on label2, label3, and label4.


text:
Q: URL Request Form I have this html form to pass my data from iphone to web server..
but I've got stucked how to build this form/data into a mutable request. Can you pls. advise me.
Html form:
<html>
<form method="post" action="https://mysite.com">
<input type="hidden" name="action" value="sale">
<input type="hidden" name="acctid" value="TEST123">
<input type="hidden" name="amount" value="1.00">
<input type="hidden" name="name" value="Joe Customer">
<input type="submit">
</form>
</html>

I don't know how to assign in the url request the "value" to the specific key (ex. action, acctid, amount, name) ???
This is my code:
NSString *urlString =  @"https://mysite.com";
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];

NSString *post = [[NSString alloc] initWithFormat:@"%@%@&%@%@&%@%@&%@%@",
   action, sale,
   acctid, TEST123,
   amount, 1.00,
                                      name, Joe Customer];  // ????

NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

[urlRequest setHTTPMethod:@"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];  // multipart/form-data
[urlRequest setHTTPBody:postData];

A: Looks about right, although you're missing some equals signs in your format string, and you need to wrap your string arguments up in @"":
NSString *post = [[NSString alloc] initWithFormat:@"%@=%@&%@=%@&%@=%@&%@=%@",
    @"action", @"sale",
    @"acctid", @"TEST123",
    @"amount", @"1.00",
    @"name", @"Joe Customer"];

For a more extendable solution you could store your key/value pairs in a dictionary then do something like this:
// Assuming the key/value pairs are in an NSDictionary called payload

NSMutableString *temp = [NSMutableString stringWithString:@""];
NSEnumerator *keyEnumerator = [payload keyEnumerator];
id key;
while (key = [keyEnumerator nextObject]) {
    [temp appendString:[NSString stringWithFormat:@"%@=%@&",
        [key description],
        [[payload objectForKey:key] description]]];
}
NSString *httpBody = [temp stringByTrimmingCharactersInSet:
    [NSCharacterSet characterSetWithCharactersInString:@"&"]];

(Bear in mind you may need to URL-encode the keys and values.)


text:
Q: Ado.net data provider is throwing an error when I try to return a command from a method I'm sorry for the bad title, not certain how to describe the issue completely.
I'm using SQLBase NET data provider.
When I attempt to create a command and add parameters, it is throwing an exception

Object not set to instance of an object

However, when I create a command outside of my object, I can add parameters with no issues.
SQLBaseDatabase class is a wrapper I wrote that will basically return a connection and create a command.
var db = new SQLBaseDatabase(ConfigurationManager.ConnectionStrings["UDSConnectionString"].ConnectionString);

This code works: I created this code in my HomeController as a test. I can add parameters with no problem.
var command = new SQLBaseCommand();
command.Connection = db.GetConnection() as SQLBaseConnection;
command.Parameters.Add(db.GetParameter(":1", "1234", DbType.String));

This code fails:
var parameters = new List<IDataParameter>();
parameters.Add(db.GetParameter(":1", "1234", DbType.String));
var cmd = db.GetCommand(db.GetConnection(), "Select * From DX_CODES Where (DX = :1)", parameters);

When I try to add parameters in this method via the passed in parameters, it throws the object not set error.
public IDbCommand GetCommand(IDbConnection connection, string sql, IEnumerable<IDataParameter> parameters)
{
    var command = new SQLBaseCommand(connection as SQLBaseConnection);

    foreach (var parameter in parameters)
        command.Parameters.Add(parameter); // This throws an error. Command.Parameters is read only.

    command.CommandText = sql;

    return command;
}

The command parameters is read only
Here is my method that creates the parameter
 public IDbDataParameter GetParameter(string name, object value, DbType type)
 {
     return new SQLBaseParameter(name, type, value);
 }

I'm not sure if I'm fundamentally doing some wrong in c# that could be causing this error. Or how I can fix it considering it works in one case, but not the other.
** Update **
Same issue happens with the SqlServer ADO.Provider.

A: I would try initializing the SQLBaseCommand in your method the same way you did in the first example.
var command = new SQLBaseCommand();
command.Connection = connection as SQLBaseConnection;

There could be a very different implementation of that constructor with and without constructor parameters. For example, the Parameters property may not get newed implicitly.


text:
Q: Will a daemonset always be deployed to all nodes? I'm wondering if a daemonset in kubernetes will always be deployed to all nodes.
My confusion comes from the following description of a daemonset

A DaemonSet makes sure that all or some kubernetes Nodes run a copy of a Pod.

The "or some" part, implies that there are cases when some nodes won't run a pod. For my use case it would be important that all nodes would run an instance. What are the cases in which a node won't run an instance of a pod, even though it is deployed as a daemonset?

A: It depends on which target of nodes are selected.

If you specify a .spec.template.spec.nodeSelector, then the DaemonSet controller will create Pods on nodes which match that node selector. Likewise if you specify a .spec.template.spec.affinity, then DaemonSet controller will create Pods on nodes which match that node affinity. If you do not specify either, then the DaemonSet controller will create Pods on all nodes.DaemonSet

Also I would  check the taint and toleration for Daemonset.


text:
Q: SQL filtering by aggregate functions Suppose I have an Employee table and a Department table. Every employee has one department.
Now, suppose I want to see all the departments --along with the employees of those departments-- that have exactly 1 employee.
Let's say my database looks like this.
Employee
EmployeeId  | EmployeeName  | DepartmentId
--------------------------------------------
1           | A Doe         | 1
--------------------------------------------
2           | B Doe         | 1
--------------------------------------------
3           | C Doe         | 1
--------------------------------------------
4           | D Doe         | 1
--------------------------------------------
5           | E Doe         | 2
--------------------------------------------

Department
DepartmentId  | DepartmentName
------------------------------------------
1             | Sales
------------------------------------------
2             | HR
------------------------------------------

What I want to see is the following results:
DepartmentName  | EmployeeId  | EmployeeName  | EmployeeId_COUNT
------------------------------------------------------------------
HR              | NULL        | NULL          | 1
------------------------------------------------------------------
HR              | 5           | E Doe         | 1
------------------------------------------------------------------

Obviously, this can be done with multiple, separate queries.
But, does anyone know of a way to solve this with a single query?
My initial idea was to do something simple, like this
SELECT
        d.DepartmentName 'Department'
        , e.EmployeeId 'EmployeeId'
        , e.EmployeeName
        , COUNT(e.EmployeeId) 'EmployeeId_COUNT'

FROM    Employee e
        LEFT JOIN Department d ON d.DepartmentId = e.DepartmentId

GROUP BY  GROUPING SETS (
                ( d.DepartmentName ),
                ( d.DepartmentName, e.EmployeeId, e.EmployeeName) )
HAVING COUNT(e.EmployeeId) IN (1)

But this doesn't work, since every row that is not a grouped row (and some grouped rows as well) has an EmployeeId count of 1.
So, the results will look something like this:
DepartmentName  | EmployeeId  | EmployeeName  | EmployeeId_COUNT
------------------------------------------------------------------
HR              | NULL        | NULL          | 1
------------------------------------------------------------------
HR              | 5           | E Doe         | 1
------------------------------------------------------------------
Sales           | 1           | A Doe         | 1
------------------------------------------------------------------
Sales           | 2           | B Doe         | 1
------------------------------------------------------------------
Sales           | 3           | C Doe         | 1
------------------------------------------------------------------
Sales           | 4           | D Doe         | 1
------------------------------------------------------------------

This is not what I want, at all.
My ideal solution is simple (no complex inner queries, UNIONs, or INTERSECTs needed) and is easily generalizable to similar problems (SUM, MAX, MIN, etc. as well as other columns in more complex queries).
I should also note that I am doing this in T-SQL 2012, so any special functions or commands that might be useful are fair game.

A: You can use COUNT() with OVER() to get what you're after:
;with cte AS (SELECT *,COUNT(*) OVER(PARTITION BY DepartmentID) AS Department_CT
              FROM   Employee)
SELECT *
FROM cte a
JOIN  Department b
  ON a.DepartmentID = b.DepartmentID
WHERE Department_CT = 1

This allows you to retain the full detail as well as returning the aggregate for filtering.


text:
Q: What parameters in a EC2 virtual machine should I use to optimize H2O's XGBoost performance? I'm trying to run H2O xgboost on r4.8x large. But it's taking too long to run (15+ hrs as opposed to 4 hours for GBM with same hyperparameter grid size).
Knowing that XGBoost uses cache optimization, is there any particular instance type that works best for H2O's XGBoost implementation?
My training data has 28K rows with 150 binary columns. And I'm running a grid search.

A: Changing your EC2 instance won't necessarily make it faster. You need to understand where is the bottleneck. Review the logs and see what takes time on GBM vs XGBoost. Is XGBoost creating deeper trees or more trees? It could be your settings are different between the two algorithms. Check that all the hyperparameters are similar (close as possible).
Also, XGBoost uses memory external to H2O's JVM. As mentioned in FAQ of H2O's XGBoost docs, try adding -extramempercent 120 and lowering your H2O memory.


text:
Q: Psycopg2 Full Outer Join with Python 2.6 I am brand new to using psycopg2 to interact with a postgreSQL database. I am attempting to do a full outer join and cannot find any documentation to help me with the command. Here is what I am attempting in Python 2.6:
cursor.execute("""
SELECT spl.id,
   spl.index,
   spl.d_id,
   spl.p_id,
   spl.pattern,
   spe.id,
   spe.index,
   spe.d_id,
   spe.p_id,
FROM s_phrase_label spl
FULL OUTER JOIN s_pattern_extraction spe
ON spl.thread.id = spe.id
   AND spl.d_id = spe.d_id,
   AND spl.index = spe.index
""")

but I keep getting errors. Thanks in advance for the help!
Edit: The error is
ProgrammingError: syntax error at or near "AND"
LINE 14:                        AND spl.index = spe.index

A: You're missing a comma:
spl.d_id,
   spl.p_id,
   spl.pattern  //Right here
spe.id,

A: You should not place a comma in the middle of a logical expression used in a WHERE clause:
...
AND spl.d_id = spe.d_id, -- This is an error.
AND spl.index = spe.index
...

Also, this has nothing to do with psycopg: it is an SQL syntax error.


text:
Q: Java EE Plugin Framework using CDI Instance Iterator I have an application that consists of wars, an core ejb with lots of service beans in a jar and remote interfaces in another jar. Everything is packaged in an ear and running on Glassfish 4.1.
Now i want to add extenstion points or plugin support to the core ejb.
The objective is to have different hot-pluggable data import services that all share the same interface because they fetch and normalize financial data from vendors like Reuters and Bloomberg.
These plugins should be detected and managed by a "Plugin Manager" bean in the core ejb jar. The plugins should support load, undload and replace at runtime.
Ideally the plugin interfaces are in a separate package, so that someone else can develop against them without the need for my application or a Glassfish and perfectly even without the Java EE stack. I also want to deploy plugins on demand and not always the whole application.
Currently i try to use the CDI Instance iterator which works fine with two import service implementations, as long as they are in the core ejb. If i put one implementation into a separate ejb jar, then it is simply not found by CDI. I guess the problem is that Glassfish loads each ejb jar as an application in a separate classloader.
Now comes my current simplified code!
The plugin interface in a separate jar package:
package com.photon.extensions;

import java.io.Serializable;

public interface ImportServiceExtension extends Serializable {
    String getImportServiceName();
}

The plugin implementation in a separate ejb jar package that is not found:
package com.photon.services.extensions.vitrex.services;

import com.photon.extensions.ImportServiceExtension;
import javax.ejb.Remote;
import javax.ejb.Stateless;

@Remote(ImportServiceExtension.class)
@Stateless
public class ReutersImportService implements ImportServiceExtension {
    @Override
    public String getImportServiceName() {
        return "Reuters";
    }
}

The plugin implementation in the core ejb jar package that is found:
package com.photon.services.extensions;

import com.photon.extensions.ImportServiceExtension;
import javax.ejb.Stateless;

@Stateless
public class BloombergImportService implements ImportServiceExtension {
    @Override
    public String getImportServiceName() {
        return "Bloomberg";
    }
}

The remote interface for the "Plugin Manager" in the remote interfaces jar:
package com.photon.services.extensions;

import java.util.List;
import javax.ejb.Remote;

@Remote
public interface ImportServiceExtensionsRemote {
    List<String> getImportServiceNames();
}

The "Plugin Manager" bean implementation in the core ejb jar:
package com.photon.services.extensions;

import com.photon.extensions.ImportServiceExtension;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.ejb.Stateless;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;

@Stateless
public class ImportersService implements ImportServiceExtensionsRemote {

    @Inject private Instance<ImportServiceExtension> importServiceExtensions;

    @Override
    public List<String> getImportServiceNames() {
        Iterator<ImportServiceExtension> iter = importServiceExtensions.iterator();
        List<String> names = new ArrayList<>();
        while ( iter.hasNext() ) {
            ImportServiceExtension extension = iter.next();
            names.add(extension.getImportServiceName());
        }
        return names;
    }
}

And finally the controller that renders the names to a website in the wars:
package com.photon.website;

import com.photon.services.extensions.ImportServiceExtensionsRemote;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@RequestScoped
@Named
public class ImportController implements Serializable {

    @EJB private ImportServiceExtensionsRemote importServiceExtensions;

    public String getImportServiceNames() {
        String names = "";
        for ( String name : importServiceExtensions.getImportServiceNames() ) {
            names += name;
        }
        return names;
    }
}

In the end only "Bloomberg" is rendered.
Now my questions:

*

*Am i on the right track?

*If so, what am i missing in the code?

*Are there better solutions to this problem (OSGI, custom
clazz.forName, ...)?

A: I cannot give you complete answer, but here is some food for thoughts...

I guess the problem is that Glassfish loads each ejb jar as an
  application in a separate classloader.

You nailed it. Sadly this is per JEE spec, so it's expected behaviour.
I don't know about Glassfish but there might be some feature allowing you to share classloader between deployments (there is some in Wildfly - called deployment isolation). That might resolve your problem.
Other thing I know from Wildfly is that you can have some application deployed as a server module which will then have access to all other deployments (and their class loaders). If there is something similar in Glassfish, you could try that. In case you are willing to give a shot to Wildfly, here is a link to issue where this was discussed.
Now, from CDI point of view this behaviour is also correct and I am afraid there is no way you could change it, because you do not have access to class loader from the other deployments (if you had, you might load the BeanManager for given deployment and search it for relevant bean).
I hope this gives you at least some insight.


text:
Q: Btrfs: RAID 1 on 3+ devices I currently have a Btrfs partition with four devices: three 3 TB drives and a 4 TB drive. Data and metadata are RAID 10, so I have 6 TB of usable space, which is almost full. I'd anticipated that RAID 5 support in Btrfs would be mature by the time my storage filled up, but apparently it's not a priority.
My question is: is there a reason to prefer RAID 10 over RAID 1? I know real RAID 1 on my current hardware should give me 3 TB of usable space with 4 copies of each block, but Btrfs apparently does not behave this way. From the Btrfs FAQ:

btrfs combines all the devices into a storage pool first, and then duplicates the chunks as file data is created. RAID-1 is defined currently as "2 copies of all the data on different devices". This differs from MD-RAID and dmraid, in that those make exactly n copies for n devices. In a btrfs RAID-1 on three 1 TB devices we get 1.5 TB of usable data. Because each block is only copied to 2 devices, writing a given block only requires exactly 2 devices to be written to; reading can be made from only one.

And from Jens Erat on Stack Overflow:

Btrfs distributes the data (and its RAID 1 copies) block-wise, thus deals very well with hard disks of different size. You will receive the sum of all hard disks, divided by two – and do not need to think on how to put them together in similar sized pairs.
If more than one disk fails, you're always in danger of losing data: RAID 1 cannot deal with losing two disks at the same time. In your example given above, if the wrong two disks die, you always lose data.

Does this mean that rebalancing from RAID 10 to RAID 1 will give me an extra 500 GB of data (6.5 TB rather than 6 TB) due to the 4 TB drive? And is there any reason for me to stick with RAID 10?

A: Yes, you get an extra 500 GB. Note that determining available space in btrfs remains elusive. Also: have a look at the btrfs disk usage calculator.
On your second question: You may lose some performance on your array. Naturally, your data is equally safe on both RAID configurations. When considering performance you can perhaps have a look at these benchmarks: kernel.org, phoronix.com.
Have you perhaps already tried converting to RAID 1? If so: what are your findings?

A: Don't use btrfs raid 5 or 6 the implementation is full of bugs, run zfs if you want that.
With raid10 you'll gain speed.
The optimal thing to do is make a 3TB partition on the 4TB drive (make sure all 3 are exactly the same size), combine those in to a RAID10 which will have 6 TB of free space. Use the extra 1 TB on the 4 TB drive for /boot (this has to be vfat anyway if you want to use efistub and avoid grub or any other boot loader which will make your boot a bit faster), swap (you can use a pretty large one, the optimal would be a small zram swap (4 gb works fine with 32 gb ram, 2 gb should be fine with 16 gb, if you have less than 16 idk if it's worth it and you should probably upgrade anyway) that's used first (set the priority to the highest) using zstd and as many compression streams as you have cores/threads... a ssd for / (everything except large media files) and a slightly larger swap with a lower priority (the higher the priority the sooner the swap gets used so the zram one should be highest) on it (8 GB for a 500 GB ssd, 16 for 1 TB, if you have a ssd over 1 TB more than 16 GB swap is probably pointless since if you are swapping that often to it you need more ram and if you have a ssd smaller than 500 GB, consider getting a 500 or 1 TB model since even the best sata ssds are extremely cheap now) and an even larger one on the hdd with the lowest priority (twice as big as the ssd one? Doesn't really matter since if it's getting used often you need more ram... and lowest priority), this still leaves enough space on that drive for another large partition (maybe something for vms or for dual boot with Windows or whatever). Also encrypt your swaps (other than the zram one, since any data on that one will be unrecoverable withing seconds unless someone pours liquid nitrogen on the ram before pulling the power) and / (if you want trim to work on the ssd you need to enable it in crypttab, security is slightly lower since an attacker can see which cells are empty but performance is better).


text:
Q: Linq databinding issue....data doesnt show up in gridview ...I get the message that number and name field are not found in the data source List<Emp> employees = new List<Emp>();
        Emp e1 = new Emp();
        e1.number = 2;
        e1.name = "Dinesh";
        employees.Add(e1);
        Emp e2 = new Emp();
        e2.number = 3;
        e2.name = "Vishal";
        employees.Add(e2);

        var query = from n in employees
                    orderby n.name descending
                    select n;

        GridView1.DataSource = query;
        GridView1.DataBind();

A: You should try to debug the situation as possibly some settings in GridView are not exactly matching DataSource.
Easily you could bind your grid in design time to type Emp, which would generate all the columns for you:
In YourGridFile.Designer.cs add:
 this.GridView1.AutoGenerateColumns = true;
 this.GridView1.DataSource = typeof(Emp);

somewhere before ResumeLayout lines.
Then you will be able to compare what you have set up manually and what should be in columns definitions.


text:
Q: php class_exits not working as expected I am trying to check if class exists and it returns false but if i check manually, it works successfully. Why is it so.
<?php

$controller_file = 'app/controllers/user.php';
$controller = 'User';

/**
 * Check if controller file exists
 */
if(!file_exists($controller_file)  ){
    throw new Exception(" Missing controller file");
}
require_once($controller_file);

/**
 * Check if controller and method exists
 */
if(class_exists($controller, false)){
    throw new Exception("Invalid Controller"); //this error thrown
}

$user = new User(); // these work
var_dump($controller);
?>

A: It is working, you forgot a !, it should actually be:
if (!class_exists($controller, false)){
    throw new Exception("Invalid Controller"); //this error thrown
}

Your current code reads "if class User exists, throw an exception". Pretty sure you want "If class User doesn't exist, throw an exception".


text:
Q: Curl based magento API creation I am planning to create a URL Based api which enable me to fetch resources using curl.
For example, If a client can request the resource by using the following url structure.
curl -some-variable http://mydomainname/magentoroot/api.php?func=addtwonum&parama=34&paramb=11
It should produce response within xml or json. Assume public key and private key encryption and decryption are done.
Is it a feasible method?? Or shall I go to REST or SOAP. I am much inclined to this method.

A: I would use REST. Magento 2 comes with REST APIs standard, and its easy to create a webapi.xml file to bind REST URLS to your own APIs you introduce as well. See http://devdocs.magento.com then go to "web services developer" in the menu bar. There are examples using CURL there as well.


text:
Q: How to get oldest part installation of consecutive installations the same boat in pandas? I have a pandas DataFrame with part installations in boats.
I would like to keep the oldest installation (see date) of consecutive installations for each boat/part. How can I do this?
Input:
| date  | boat | part
|-------|------|-----
| 01/01 | A    | C <-- Keep this row because this is first install of C in A
| 01/02 | A    | C
| 01/03 | A    | C
| 01/04 | A    | D <-- Keep this row because this is first install of D in A
| 01/05 | A    | D
| 01/06 | A    | C <-- Keep this row because this is first install of C in A after D
| 01/07 | A    | C
| 01/08 | A    | C
| 01/09 | B    | C <-- Keep this row because this is first install of C in B
| 01/10 | B    | C

Output:
| date  | boat | part
|-------|------|-----
| 01/01 | A    | C
| 01/04 | A    | D
| 01/06 | A    | C
| 01/09 | B    | C

A: Use:
df = df[df[['boat','part']].ne(df[['boat','part']].shift()).any(axis=1)]
print (df)

    date boat part
0  01/01    A    C
3  01/04    A    D
5  01/06    A    C
8  01/09    B    C

Detail:
First compare consecutive values with DataFrame.ne and shift:
print (df[['boat','part']].ne(df[['boat','part']].shift()))
    boat   part
0   True   True
1  False  False
2  False  False
3  False   True
4  False  False
5  False   True
6  False  False
7  False  False
8   True  False
9  False  False

And then test at least one True per rows by DataFrame.any:
print (df[['boat','part']].ne(df[['boat','part']].shift()).any(axis=1))
0     True
1    False
2    False
3     True
4    False
5     True
6    False
7    False
8     True
9    False
dtype: bool


text:
Q: $N(s) = 1$ if and only if s is a unit if and only if $s = \pm 1$ or $\pm i$. $s \in \mathbb{Z}[i]$ I'm confused. This is a homework question and I am not asking for the answer, but I was just wondering if I have to prove the second iff then use that to prove the first iff. Either that or my professor is confused.

A: If $ z=x+iy \in\mathbb{C} $
then $ N[s]=1 \Rightarrow x^{2}+y^{2}=1 $
$\Rightarrow (x^{2}=1$ and  $y^{2}=0)$ or $ (x^{2}=0$ and  $y^{2}=1)$
Because x,y are integer.
If $x^{2}=1
\Rightarrow x=1$ or $x=-1$
Thus, $z_{1}=1$ or $z_{2}=-1$
If $y^{2}=1
\Rightarrow y=1$ or $y=-1$
Thus, $z_{3}=i$ or $z_{4}=-i$


text:
Q: PowerShell: How to display in full? I tried running the following command in PS:
Get-EventLog -LogName Security | findstr 4720

The result I got seems to be squished as if the column widths need to be adjusted. How can I view all the text that is after the ellipses (...)? See screenshot: https://i.imgur.com/fqV5qIs.png
How to view the returned info in full?

A: As Santiago mentioned you can use Format-Table.
Though since it looks like you're looking for a specific Event ID, I'd recommend instead of using findstr (which may return unrelated results as it's searching for '4720' anywhere in your results - unless that's your intention of course) instead target the attribute using the Where-Object cmdlet (or its' alias ?). Also, if you want a "pure" PowerShell solution I'd recommend using Select-String instead of findstr
E.g.
Get-EventLog -LogName Security | Where-Object {$_.EventID -eq 4720} | Format-Table -AutoSize -Wrap

A: To expand on the answer from @Novalis, Where-Object like that is definitely faster than findstr, and the Format-Table should sort out the ... you're seeing.
But to take it one step further an even faster method is to use -FilterHashtable. Specifically :
Get-WinEvent -FilterHashtable @{Logname='Security';ID=4720} | Format-Table -AutoSize -Wrap

The reason it's faster is because when using Where-Object you're asking the system for ALL of the system logs, and then once received by your script you're then filtering them out (same with findstr). FilterHashtable just requests the log entries from system that match the require event ID, so less data needs to be sent to your script.


text:
Q: Asking for password when pushing to gitea with ssh I have just set up my own gitea service on the Ubuntu server (the server is run with user gitea). The following steps have been done:

*

*generate ssh key on my windows pc, and store at C:\Users<user_name>\.ssh, namely id_rsa_gitea and id_rsa_gitea.pub

*copy and set the public key on my gitea account setting page

There are existing key files for my GitHub account in the directory, namely id_rsa and id_rsa.pub. I modified the file config in the same directory as
Host github.com
  HostName github.com
  User git
  IdentityFile C:/Users/<user_name>/.ssh/id_rsa
  IdentitiesOnly yes

Host 192.168.200.101
  HostName 192.168.200.101
  User gitea
  IdentityFile C:/Users/<user_name>/.ssh/id_rsa_gitea
  IdentitiesOnly yes

Pushing to GitHub works fine. But when I try to push to gitea, it gets
$ git push -u origin master
gitea@192.168.200.101's password:
Permission denied, please try again.
gitea@192.168.200.101's password:
Permission denied, please try again.
gitea@192.168.200.101's password:
\302\226gitea@192.168.200.101: Permission denied (publickey,password).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I have tested the ssh connection in the git bash console with ssh -v gitea@192.168.200.101, and gets
OpenSSH_7.6p1, OpenSSL 1.0.2m  2 Nov 2017
debug1: Reading configuration data /c/Users/admin/.ssh/config
debug1: /c/Users/admin/.ssh/config line 26: Applying options for 192.168.200.101
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to 192.168.200.101 [192.168.200.101] port 22.
debug1: Connection established.
debug1: identity file C:/Users/admin/.ssh/id_rsa_gitea type 0
debug1: key_load_public: No such file or directory
debug1: identity file C:/Users/admin/.ssh/id_rsa_gitea-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.6
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.10
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.10 pat OpenSSH* compat 0x04000000
debug1: Authenticating to 192.168.200.101:22 as 'gitea'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: aes128-ctr MAC: umac-64-etm@openssh.com compression: none
debug1: kex: client->server cipher: aes128-ctr MAC: umac-64-etm@openssh.com compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:YqpRDueradBcei52m4ahex5DgTOwI3QvgJohoZSMzTs
debug1: Host '192.168.200.101' is known and matches the ECDSA host key.
debug1: Found key in /c/Users/admin/.ssh/known_hosts:23
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering public key: RSA SHA256:DCCnO6UzUiXYhZiNxeaS4SV05fIUZhHK/ZGDPPI6cwc C:/Users/admin/.ssh/id_rsa_gitea
debug1: Server accepts key: pkalg rsa-sha2-512 blen 535
debug1: Authentication succeeded (publickey).
Authenticated to 192.168.200.101 ([192.168.200.101]:22).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: pledge: network
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug1: Remote: Forced command.
debug1: Remote: Port forwarding disabled.
debug1: Remote: X11 forwarding disabled.
debug1: Remote: Agent forwarding disabled.
debug1: Remote: PTY allocation disabled.
debug1: Remote: Forced command.
debug1: Remote: Port forwarding disabled.
debug1: Remote: X11 forwarding disabled.
debug1: Remote: Agent forwarding disabled.
debug1: Remote: PTY allocation disabled.
PTY allocation request failed on channel 0
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: client_input_channel_req: channel 0 rtype eow@openssh.com reply 0
debug1: channel 0: free: client-session, nchannels 1
Connection to 192.168.200.101 closed.
Transferred: sent 3720, received 3624 bytes, in 0.2 seconds
Bytes per second: sent 15126.0, received 14735.7
debug1: Exit status 1

I've tried multiple variations of this, but none of them seem to work. Any ideas?
Update: Push with http works fine. I switched back to ssh and tried to push again, now I get:
Pushing to gitea@192.168.200.101:guanhuizhe/example-repo.git
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

During this push the sshd log of the ubuntu server is:
Oct 16 18:08:29 DataStorage2 sshd[29981]: Accepted publickey for gitea from 192.168.200.141 port 14967 ssh2: RSA SHA256:DCCnO6UzUiXYhZiNxeaS4SV05fIUZhHK/ZGDPPI6cwc
Oct 16 18:08:29 DataStorage2 sshd[29981]: pam_unix(sshd:session): session opened for user gitea by (uid=0)
Oct 16 18:08:29 DataStorage2 sshd[30017]: Received disconnect from 192.168.200.141 port 14967:11: disconnected by user
Oct 16 18:08:29 DataStorage2 sshd[30017]: Disconnected from 192.168.200.141 port 14967
Oct 16 18:08:29 DataStorage2 sshd[29981]: pam_unix(sshd:session): session closed for user gitea

Update v2:
The problem is caused by the Ubuntu user I used to run the gitea binary. This user does not have shell. I delete the user and configure a normal user. Everything works fine. Thanks for every one!!

A: \302\226gitea@192.168.200.101 means the origin in the local git config file .git/config is not gitea, but <START OF GUARDED AREA>gitea.
You can change your Host entry (in ~/.ssh/config) with "gitea" (easier to type than 192.168.200.101)
Test it with:
ssh -Tv gitea

Check also the ~gitea/.ssh/authorized_keys file, to ensure the public key has been added by gitea, and is in a SSH forced command line.
You should see something like:
command="/path/to/gitea --config='/path/to/app.ini' serv key-2",\
   no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty \
   ssh-rsa <yourPublicKey>

If you want to use your ~/.ssh/config entry, then you will need to change your remote:
cd /path/to/repo
git remote set-url origin gitea:<me>/myrepo


text:
Q: How to create a recommendation algorithm ("If you like X and Y, you might like Z")? How to create a recommendation algorithm ("If you like X and Y, you might like Z")?
I want to create an algorithm which recommends "You might also like" items from an itemlist, based on user's current liked itemlist (favorites) and based on those created by other users with similar preferences (in JS/MySQL, but that should not be of importance).
The input is simply a set of all items, and subsets (list of favorites) created by users.
Update: @Robert Harvy's Music example is a good one for clarification. Itemset: 100 bands. John likes bands 1,2,3,4,5, 11,12. Jane likes 1,2,3,4,5, 10,12. Their music tastes are likely to be similar, just as their fav lists are. The algorithm should notice this and recommend band 10 to John and 11 to Jane. No characteristics would need to be concidered in this simple scenario.

A: You find similarities between objects by identifying characteristics of those objects and then see which characteristics two or more objects have in common.  Or, you simply watch the behavior of online customers and compare what they buy with other things they also buy.
For example, if you Google "Bands Like Steely Dan," Google will respond with the Doobie Brothers, Steve Winwood, the Allman Brothers Band, Eagles, Fleetwood Mac, Jackson Browne, Talking Heads, Eric Clapton, Crosby Stills and Nash, Hall and Oates, James Taylor, Neil Young, Simon & Garfunkel, etc.
Now, it could be credibly argued that these bands don't really resemble Steely Dan's musical style all that much.  What they do have in common is that they all come from the same era, and they are all in the "classic rock" genre.  And yes, folks who like Steely Dan also tend to like these other bands.
That's how you make a recommendation engine.  You find things to recommend that have characteristics in common with the thing that the user searched or bought.


text:
Q: How to clear the input buffer with TTY set to raw mode using std::cin? So I've used the termios library to put the terminal into raw mode, which allows me to do this:
int getch() {
  int ch;
  do {
    ch = cin.get();
  } while(cin.eof());
  return ch;
}

This waits for a single character to be ready in the input buffer and returns it.
But if I try to do this:
void clear_input_buffer() {
  char ch;
  while(!cin.fail()) {
    cin.get(ch);
  }
}

It goes into an endless loop.
What would be the appropriate way to clear the input buffer?  I've tried this:
cin.clear();
cin.ignore(INT_MAX);

But it also hangs.  I'd also like to do this using only iostreams or standard posix functions.

A: Just do the usual:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');


text:
Q: Game stops reacting after 15th click when 15 balls generated This game will generate a ball in a random location on the grid after each click.

Issue
But it stops reacting on further clicks after reaching 15 balls (see screenshot above).
Pygame Code
import pygame
from random import randint

pygame.init()
gameDisplay = pygame.display.set_mode((915,915))
colors = [(102,51,0),(0,255,255),(0,255,0),(0,51,204),(102,0,204),(255,255,0),(255,0,0)]
slots = []
x = 0
y = 0
click_pos = (0,0)
play = True
#Size of squares
size = 83
white = (255,255,255)
gray = (200,200,200)
deep_gray = (20,20,20)
green = (0,255,0)
black = (0,0,0)
boardLength = 9
z = 0
clicked = False
selecting = False
ball_spawn = False
balls_x = []
balls_y = []
ball_amount = 0
ball_color = []
ball_drew = 0
get_ball_pos = False
click_once = 0
#bg color
gameDisplay.fill(deep_gray)

# GRID
while boardLength > z:
    #border
    pygame.draw.rect(gameDisplay, black, [size-5,size-5,boardLength*size+5 ,boardLength*size+5])
    #grid squares
    for i in range(1,boardLength+1):
        for z in range(1,boardLength+1):
            pygame.draw.rect(gameDisplay, gray, [size*z,size*i,size-5,size-5])

# GAME
while play == True:
    for events in pygame.event.get():
        if events.type == pygame.MOUSEBUTTONUP:
            click_pos = list(pygame.mouse.get_pos())
            clicked = True
        if events.type == pygame.QUIT:
            play = False
    #get click pos on grid
    if clicked == True:
        click_once += 1
        if click_once == 1:
            x = round((click_pos[0]-size/2) / size)
            y = round((click_pos[1]-size/2) / size)
            if x > 0 and x < 10 and y > 0 and y < 10:
                grid_x = x*size
                grid_y = y*size
            clicked = False
            selecting = True
            get_ball_pos = True
            ball_spawn = True
    else:
        click_once = 0
    #selector
    if selecting:
        pygame.draw.rect(gameDisplay, green, (grid_x,grid_y,size-5,size-5), 5)

    # BALLS
    while ball_spawn:
        while get_ball_pos:
            ball_grid_x = randint(1,9)
            ball_grid_y = randint(1,9)
            if not (ball_grid_x in balls_x and ball_grid_y in balls_y):
                get_ball_pos = False
                balls_x.append(ball_grid_x)
                balls_y.append(ball_grid_y)
                ball_color.append(colors[randint(0,6)])
                ball_amount += 1
        while ball_drew < ball_amount:
            pygame.draw.circle(gameDisplay, ball_color[ball_drew], (balls_x[ball_drew]*size + size*0.5 - 2, balls_y[ball_drew]*size + size*0.5 - 2), 25)
            pygame.draw.circle(gameDisplay, black, (balls_x[ball_drew]*size + size*0.5 - 2, balls_y[ball_drew]*size + size*0.5 - 2), 25, 5)
            ball_drew += 1
        ball_drew = 0
        ball_spawn = False
    #final result
    pygame.display.update()

pygame.quit()
quit()

Stacktrace after interrupting
Since the program does not react on clicks anymore I interrupted it in console  with CTRL + C. After interrupting execution the console shows following:
pygame 2.0.1 (SDL 2.0.14, Python 3.6.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
^CTraceback (most recent call last):
  File "SO_pygame.py", line 73, in <module>
    ball_grid_x = randint(1,9)
  File "/usr/lib/python3.6/random.py", line 221, in randint
    return self.randrange(a, b+1)
  File "/usr/lib/python3.6/random.py", line 192, in randrange
    istop = _int(stop)
KeyboardInterrupt

How can I fix this?

A: The problem is the condition:

if not (ball_grid_x in balls_x and ball_grid_y in balls_y):

This condition checks whether there is a ball in line ball_grid_x and whether there is a ball in column ball_grid_y. However, these can be different balls. Therefore, if there is a ball in every row and a ball in every column, this condition creates an infinite loop:
You need to test if there is a ball at positionv  (ball_grid_x, ball_grid_y):
if not (ball_grid_x, ball_grid_y) in zip(balls_x, balls_y):


text:
Q: Month duration input value in spotfire i have year,Month dropdown property and monthduration(input filed) property in text area.
can any one suggest me limit data or custom expression in table.
Year    Month   duration
2016    Apr 9
may
jun
jul
Aug
sep
Oct
nov
Dec
Jan 2017
above sample if user select year 2016 and month "Apr" and dropdown property and duration "9" (input filed ) means Apr + 9 months that would be jan 2017 values has to be displayed in Table.
can any one help me any limit data expression or custom expression.
Thanks
Naveenenter image description here

A: The question is a little difficult to understand but I'll give it a shot. I think you are looking for something like this:
# Assumptions: 3 document properties
# 1) StartYear = Integer, The starting year the user selects from the listbox
# 2) StartMonth = Integer, The starting month the user selects from the listbox (Can display as text (i.e. Apr.) but set to integer for actual property
# 3) RangeMonth = Integer, number of months user inputs to add to date range.

(Year([DATECOL]) >= DocumentProperty("StartYear")) and Month([DATECOL]) > DocumentProperty("StartMonth") and
 Year([DATECOL]) <= Year(DateAdd('month', DocumentProperty("RangeMonth"), Date(DocumentProperty("StartYear"), DocumentProperty("StartMonth"), 1))) and
 Month([DATECOL]) <= Month(DateAdd('month', DocumentProperty("RangeMonth"), Date(DocumentProperty("StartYear"), DocumentProperty("StartMonth"), 1)))

What is happening is first, you are ensuring DATECOL values are > the starting year and month. Then you are taking the starting year and month, adding the user input RangeMonth to that, and making sure DATECOL is <= that addition.


text:
Q: VBA code to set date format for a specific column as "yyyy-mm-dd" I have a macro which I specify the date (in mm/dd/yyyy) in a textbox and I want to set this value for column A in yyyy-mm-dd format.  I have the following code:
Sheets("Sheet1").Range("A2", "A50000").Value = TextBox3.Value
Sheet1.Range("A2", "A50000") = Format(Date, "yyyy-mm-dd")

...and when I run the macro, the date is still in mm/dd/yyyy format.
How can I change this so that it is in the format I want??  I've been trying many kinds of code researched through google and nothing will set the format the way I want it.
Any help will be appreciated...
EDIT: Full code from OP's comment below:
 Workbooks.Add
 Range("A1") = "Acctdate"
 Range("B1") = "Ledger"
 Range("C1") = "CY"
 Range("D1") = "BusinessUnit"
 Range("E1") = "OperatingUnit"
 Range("F1") = "LOB"
 Range("G1") = "Account"
 Range("H1") = "TreatyCode"
 Range("I1") = "Amount"
 Range("J1") = "TransactionCurrency"
 Range("K1") = "USDEquivalentAmount"
 Range("L1") = "KeyCol"
 Sheets("Sheet1").Range("A2", "A50000").Value = TextBox3.Value
 Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"

A: Use the range's NumberFormat property to force the format of the range like this:
Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"

A: It works, when you use both lines:
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000") = Format(Date, "yyyy-mm-dd")
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000").NumberFormat = "yyyy-mm-dd"

A: You are applying the formatting to the workbook that has the code, not the added workbook.  You'll want to get in the habit of fully qualifying sheet and range references.  The code below does that and works for me in Excel 2010:
Sub test()
Dim wb As Excel.Workbook
Set wb = Workbooks.Add
With wb.Sheets(1)
    .Range("A1") = "Acctdate"
    .Range("B1") = "Ledger"
    .Range("C1") = "CY"
    .Range("D1") = "BusinessUnit"
    .Range("E1") = "OperatingUnit"
    .Range("F1") = "LOB"
    .Range("G1") = "Account"
    .Range("H1") = "TreatyCode"
    .Range("I1") = "Amount"
    .Range("J1") = "TransactionCurrency"
    .Range("K1") = "USDEquivalentAmount"
    .Range("L1") = "KeyCol"
    .Range("A2", "A50000").Value = Me.TextBox3.Value
    .Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
End With
End Sub


text:
Q: Product identities I need to use the  following identities for poisson integral but i can't guz i don't know how to prove them.

$$\alpha^{2n}-1=\prod_{k=0}^{k=2n-1}(\alpha-e^{i\frac{2k\pi}{2n}})$$
$$\prod_{k=0}^{k=2n-1}(\alpha-e^{i\frac{2k\pi}{2n}})=(\alpha-1)(\alpha+1)\prod_{k=1}^{k=n-1}(\alpha-e^{i\frac{k\pi}{n}})(\alpha-e^{-i\frac{k\pi}{n}})$$

I would appreciate any help
what i did :
Let $\alpha >1\,\quad  \alpha^{2n} =1$
\begin{align*}
\alpha^{2n} &=1\\
(\rho.e^{i\phi})^{2n} &=1.e^{i.0} \text{ with $\rho \in \mathbb{R}^{+}_{*},\ \phi \in \mathbb{R}$}\\
\rho^{2n}.e^{i.2n.\phi}&=1.e^{i.0}\\
\rho^{2n}&=1, \quad  e^{i.2n\phi}=e^{i.0}\\
\rho&=1, \quad   2n.\phi=0[2\pi]\\
 \rho&=1, \quad         \exists k\in \mathbb{Z} \  2n.\phi=2.k.\pi\\
 \rho&=1, \quad         \phi=\frac{2.k.\pi}{2n} \text{ Then } \alpha_{k}=e^{i\frac{2.k.\pi}{2n}}\\
\text{Let } k &= t + 2nq \text{ or } t\in \{0,1,\ldots,2n-1\}  \text{ and } q \in \mathbb{Z}.\\
&\text{ Then } \alpha_{k}=e^{i\dfrac{2.t.\pi}{2n}+2.\pi.q}=Z_{t}
\\
S&=\{Z_{k}=e^{i\dfrac{2.k.\pi}{2n}}|k\in \{0,1,\ldots,2n-1\} \}
\end{align*}

A: The first line is a statement about roots of unity and factorization. The numbers $e^{2\pi i k / n}$ are precisely the $n$th roots of unity. (And the factor theorem, I suppose).
The second one is just a rearrangement of terms from the first. If you'd like an alternate view, you might think of $\alpha$ as a variable, and consider each side as polynomials in $\alpha$. Then since they have the same roots and the same value at $\alpha = 0$, they are the same polynomial.
In short: you should read up on roots of unity and possibly the factor theorem.

A: First Identity: Let $$p(x) = x^n + a_{n-1} x^{n-1}+ \ldots+a_0$$ a polynomial function of order $n$. Then, by the fundamental theorem of algebra, we have $$p(x) = \prod_{j=1}^n (x-x_j)$$ where $x_1,\ldots,x_n$ are the roots of $p$. Apply this to $p(x) := x^{2n}-1.$
Second Identity:
Write $$\prod_{k=0}^{2n-1} \left(\alpha - e^{\imath \frac{2k\pi}{2n}} \right) = \underbrace{\left(\prod_{k=0}^0 \dots \quad \cdot \prod_{k=n}^n \dots \right)}_{(\alpha-1)(\alpha+1)} \left( \prod_{k=1}^{n-1} \dots \quad \cdot \prod_{k=n+1}^{2n-1}  \dots \right).$$
Now note that
$$\exp \left( 2\pi \imath \frac{2n-\ell}{2n} \right) = \exp \left( 2\pi \imath - 2\pi \imath \frac{\ell}{2n} \right) = \exp \left(- 2\pi \imath \frac{\ell}{2n} \right) \tag{1}$$
as $x \mapsto e^{\imath x}$ is periodic. For $k \in \{n+1,\ldots,2n-1\}$ we write $k = 2n-\ell$ where $\ell \in \{1,\ldots,n-1\}$. Applying $(1)$, we get
$$\prod_{k=n+1}^{2n-1} \left(\alpha - e^{\imath \frac{2k\pi}{2n}} \right) = \prod_{\ell=1}^{n-1} \left(\alpha - e^{- \imath \pi \frac{\ell}{n}} \right).$$
This finishes the proof.


text:
Q: Change HTML markup used it PopupTemplate in ArcGIS (javascript api) everyone. I'm sorry if it is common question but I'd googled it for a couple days and still haven't find the answer. Everything I see in documentation is style an exist HTML layout, which looks like:

            Zoom to

But I need to setup totally different popup, put style on it and, surely, link it to data. I see there's the PopupTemplate class that allow to put data in 'content' block or 'title' block, but how to define own sections, change markup and do stuff like this?
What I tried:

*

*delete sections in popup.domNode and then add my ones - data stoped
synchronize.

*changed markup directly in popup.domNode.innerHTML - same thing

*thought that it is crucial to update ._title and ._content properties to show where's now these blocks placed, but have same result.


text:
Q: How to loop a list through lappy after the $ sign in r I have been trying to figure out how to apply the apply functions plyr is out there. I will learn that later. But, I need help. I can get output with actually typing the object name in, but I am trying to loop a list through it. The code is as follows:
    list<-noquote(c("T","AAVL"))
lapply(list,function(i) xts(l.df$i[,-1:-5],order.by=as.POSIXct(rownames(l.df$i))))

If I just do xts(l.df$T[,-1:-5],order.by=as.POSIXct(rownames(l.df$T))
I get the xts file that I need. Could someone please help me loop the names without quotes into the lapply(), so that I could have this work for numerous elements in my list? Thank you!

A: There are a number of ways to subset a list in R. See https://ramnathv.github.io/pycon2014-r/learn/subsetting.html or http://adv-r.had.co.nz/Subsetting.html for more detailed discussion.
However, in your case the issue is that the dollar operator $ takes a fixed string rather than a variable name. So myList[["item"]] and myList$item are equivalent. In the example you gave, you're trying to find the member of the data.frame called "i", not the one referenced by the variable i. The noquote class you used purely affects printing of a character vector; it has no effect on subsetting.
The version of your code that works doesn't work as you explain in your comment. It works because you're now subsetting the column whose name is stored in i not the one called "i".

A: I want to add 106 new columns to a dataframe that are the length of the df ofcourse and filled with zeros (0). How would I loop over i in this case:
geo <- unique(df$geo)

geo
[1] "AL" "AT1" "AT2" "AT3" "BE1" "BE2" "BE3"

for(i in geo) {
 df$i <- v(0,length(df)
}

Emil Krabbe 2 mins ago    Edit


text:
Q: Can't format moment object to date and time I'm using a react component for Date picking which returns a moment object. Also, I'm using my custom component to select time and saving the value like this for example 3:30 pm .
What I want to do is make this one moment object that I can later user and format however I want.
This is my current implementation but it's not working:
formatting the time is always returning AM
const time = moment(pickupTime.formattedTime, ['hh:mm a'])
        .locale('en')
        .format('hh:mm A');

const dateTime =
        startDay.locale('en').format('MMM Do YY') + // This is the Date which is a moment object
        ' ' +
        time;

A: Because string + string = string, you cannot get an object by concatenating strings.
What you need is to convert a string to a moment object:
moment('24/12/2019 09:15:00', "DD MM YYYY hh:mm:ss");

Result:
Moment {_isAMomentObject: true, _i: '24/12/2019 09:15:00', _f: 'DD MM YYYY hh:mm:ss', _isUTC: false, _pf: {…}, …}

Check out https://momentjs.com/docs/#/parsing/string-format/