text:
Q: Graphql express nested schema I am currently building mern + graphql app. I am new to graphql and I have two different models a User Model and Character model. The Character Model is nested in the User. When I create a user in the Graphiql interface I want it to display its data and the character that is associated with the specific user but instead it is displaying every character that has been created in the database and adding them to every user created instead of the specific user. Trying to figure out how to fix this. Link to Github Repo
Mongoose User Model
const mongoose = require('../db/connection')
const Schema = mongoose.Schema

const User = new Schema({
    id: String,
    name: String,
    totalwins: Number,
    description: String,
    charactersID: [
        {
            type: Schema.Types.ObjectId,
            ref: "Character"
        }
    ]
})

module.exports = mongoose.model('User', User)

Mongoose Character Model
const mongoose = require('mongoose')
const Schema = mongoose.Schema

const Character = new Schema({
    name: String,
    wins: Number,
    losses: Number,
    percentage: Number,
    image: String

})

module.exports = mongoose.model('Character', Character)

const graphql = require('graphql')
const { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLID, GraphQLList,
GraphQLNonNull } = graphql
const Character = require("../models/Character")
const User = require("../models/User")

Types
// User Schema
const userType = new GraphQLObjectType({
name: 'User',
fields : () => ({
    _id: {type: GraphQLID},
    name : { type: GraphQLString},
    totalwins : { type: GraphQLInt },
    description :  { type: GraphQLString },
    character : {
        type : new GraphQLList(characterType),
        resolve(parent, args){
            return Character.find({charactersID: parent.id})

        }
    }

})
})

// Character Schema
const characterType = new GraphQLObjectType({
name: 'Character',
fields : () => ({
    id: {type: GraphQLID},
    name : { type: GraphQLString},
    wins : { type: GraphQLInt },
    losses :  { type: GraphQLInt },
    percentage: {type: (GraphQLInt)},
    image: { type: GraphQLString },
})
})

Query
//query the graph to grab the data
const Query = new GraphQLObjectType({
name: 'Query',
fields: {
    user : {
        type: userType,
        // arguments passed by the user while making the query
        args: {id : {type : GraphQLID}},
        resolve(parent, args){

            // return User.find((item) => { return item.id == args.id});
            //finding a single user by id
            return User.findById(args.id)

        }
    },

    users : {
        type: new GraphQLList(userType),
        resolve(parent, args) {
            return User.find({})
        }
    },

    character : {
        type: characterType,
        args: {id : {type : GraphQLID}},
        resolve(parent, args){

            return Character.findById(args.id)
        }
    },

    characters : {
        type: new GraphQLList(characterType),
        resolve(parent, args) {
            return Character.find({})
        }
    }

}
})

Mutations
 //allows user to add, update and delete to mondodb through graphql
 const Mutation = new GraphQLObjectType({
 name: 'Mutation',
 fields: {
    addUser: {
        type: userType,
        args: {
            name: {type: GraphQLNonNull(GraphQLString)},
            totalwins: {type: (GraphQLInt)},
            description: {type: (GraphQLString)},
            charactersID: { type: new GraphQLNonNull(GraphQLID)}
        },
        resolve(parent, args){
            let user = new User({
                name: args.name,
                totalwins: args.totalwins,
                description: args.description,
                charactersID: args.charactersID

            })
            return user.save()

        }

    },

    addCharacter: {
        type: characterType,
        args: {
            name: {type: GraphQLNonNull(GraphQLString)},
            wins: {type: (GraphQLInt)},
            losses: {type: (GraphQLInt)},
            percentage: {type: (GraphQLInt)},
            image: {type: (GraphQLString)},

        },
        resolve(parent, args){
            let character = new Character({
                name: args.name,
                wins: args.wins,
                losses: args.losses,
                percentage: args.percentage,
                image: args.image
            })
            return character.save()

        }
    },

    deleteUser: {
        type: userType,
        args: {
            id: {type: new GraphQLNonNull(GraphQLString)}
        },
        resolve(parent, args){
                const remUser = User.findByIdAndRemove(args.id)
                if(!remUser){
                    throw new Error('No character found')
            }
            return remUser

        }
    },

    deleteCharacter: {
        type: characterType,
        args: {
            id: {type: new GraphQLNonNull(GraphQLString)}
        },
        resolve(parent, args){
                const remCharacter = Character.findByIdAndRemove(args.id)
                if(!remCharacter){
                    throw new Error('No character found')
            }
            return remCharacter

        }
    },
}
})

module.exports = new GraphQLSchema({ query : Query, mutation : Mutation})

Image of results from Grapiql interface


text:
Q: NestJS: Dependency Injection and Provider Registration Can anyone help me to understand DI Nest Fundamentals, my question:
"Is it possible to have a service class without @Injectable annotattion, and also this class does not belong to any module?" I saw on internet an example like below:
This class exists in a common folder:
export class NotificationService {
  constructor(
    @Inject(Logger) private readonly logger: LoggerService,
    private readonly appConfigService: AppConfigService,
    @Inject(HttpService) private readonly httpService: HttpService
  ) {}

  async sendNotification(msg: string) {
   ....
  }
}

And then it was registered in another module in the the providers array:
import { Module, Logger, forwardRef, HttpModule } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { NotificationService } from '../../commons/notification/notification.service';

@Module({
    imports: [
        ...
    ],
    controllers: [InvoiceController],
    providers: [
        InvoiceService,
        NotificationService,
        Logger],
    exports: [InvoiceService]
})
export class InvoiceModule { }

Then it was injected in other service's constructor method
@Injectable()
export class InvoiceService {

    constructor(
        @Inject(Logger) private readonly logger: LoggerService,
        private readonly notificationService: NotificationService) { }

...
}

This works fine, but I don't know why. Why the notification service was injected correctly without add @Injectable, and without and import module?

A: So let's break down what's really happening with the @Injectable() decorator.
Normally, we use decorators for setting metadata about the class, parameter, method, or property that we are decorating, or we are using it to somehow modify the method (if method decorator) or the property (property decorator) via descriptors. In the case of @Injectable() we aren't really doing either of these. Sure we're setting the scope metadata, but this doesn't really seem to set any metadata about "Hey, this class is injectable via the Nest framework". That's because what @Injectable() is really setting us up for is a special property of the tsconfig and tsc compiler, the emitDecoratorMetadata property. With this property, typescript will add on a bunch of extra functions at the beginning and end of the file. These functions look generally like this
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};

and
DelegatorService = __decorate([
    common_1.Injectable(),
    __metadata("design:paramtypes", [http_interceptor_service_1.HttpInterceptorService,
        websocket_interceptor_service_1.WebsocketInterceptorService,
        rpc_interceptor_service_1.RpcInterceptorService,
        gql_interceptor_service_1.GqlInterceptorService])
], DelegatorService);

This is the super important part, because this "design:paramtypes" is actually what Nest is reading when it comes determining what to inject.
This metadata is only available when a decorator is used anywhere in the class, and there was actually an eslint-typescript discussion about the metadata and how import type breaks it, along with a recent PR that really gets into the weeds of things.
I bring all of this up to say that because you have @Inject() in the constructor, the @Injectable() is actually extraneous, and not necessary unless you're going to be setting scope level metadata. The type metadata will already be emitted, so that explains why you don't need @Injectable() (though I still think it's a good idea to have it cause it provides clear intent).
Now for why the injection works properly, I promise this one is less complex: you added the NotificationsService to the InvoiceModule's providersarray. This tells Nest that any service inside ofInvoiceModulehas access toNotificationsService` so it can be injected here without a problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inheriting from template struct with multiple template arguments of typename this is my first question on this platform after using it as a grateful visitor for years. Please be gentle with me.
I am currently implementing an interface for ADCs that can be used with different types of microcontrollers and different architectures.
Sadly, this limits the usable c++ version to 11 to guarantee compatibility between the MCUs.
The idea was to define a general API ADC struct, in which a typename of a fixed width integer type is passed, together with the maximum achievable Min and Max values of a the ADC. These two values are intended to be stored as a constexpr.
Therefore I came up with this:
template<typename T, T max, T min>
struct ADC
{
public:
    static constexpr T maximum = max;
    static constexpr T minimum = min;
    virtual void reset() = 0;
    // ...
};

template<typename T, T max, T min>
struct xyzAdc : ADC<typename T, T max, T min>
{
public:
    uint8_t someSpecificADCStuff = 0xac; // arbitrarily chosen
    // ....
};

For example, there might be an ADC which provides a 12 bit resolution. This could be used in single ended or differential mode resulting in a usage something like this:
xyzADC<uint16_t, 0, 4095> singleEndedADC;
// or
xyzADC<int16_t, -2048, 2047> diffADC;

Unfortunately, this does not compile. The resulting error message is
error: wrong number of template arguments (1, should be 3)
struct xyzAdc : ADC<typename T, T max, T min>

To be honest, I could not find out, to what this error message is hinting.
I did some research but was not able to find a similar question, in which this is covered.
What am I doing wrong? Does c++11 provide another way to achieve what I am trying to do?
Is this in general a reasonable pattern / idea to go with?
Or should I write another template, which wraps these parameters?
Any help or hints for sources including deeper reading would be greatly appreciated.
Thanks in advance.
EDIT:
fixed integer type sizes in code, typo not related to question

A: Maybe
template<typename T, T max, T min>
struct xyzAdc : ADC<T, max, min> // no "<typename T, T max, T min>"
{ // ...............^..^^^..^^^
public:
    uint8_t someSpecificADCStuff = 0xac; // arbitrarily chosen
    // ....
};

?
Anyway, 4095 is too much for a std::uint8_t
xyzADC<uint8_t, 0, 4095> singleEndedADC;


text:
Q: Implementation of user.bot discord.py rewrite I'm doin a command that checks if a user is a bot or a normal user
@client.command()
async def maybebot(ctx, user: discord.Member):
    embed = discord.Embed(title="Cheks if a user is a bot", description="Let's find out!")
    if user.bot == True:
        embed.add_field(name="And..", value="It is!")
    if user.bot == False:
        embed.add_field(name="And...", value="It's not!")
    await ctx.send(embed=embed)

This is not working, no traceback, no error. What i should do?

A: @client.command()
async def maybebot(ctx, user: discord.Member):
    embed = discord.Embed(title="Checks if a user is a bot", description="Let's find out!")
    if user.bot:
        embed.add_field(name="And...", value="It is!")
    else:
        embed.add_field(name="And...", value="It's not!")
    await ctx.send(embed=embed)


text:
Q: Different File Versions in Visual Studio and windows Properties Anyone knows why am I having different file versions of a executable file in windows properties and visual Studio?

I'm querying the same file... for sure! What am I mising....
This is my code:
private string getFileVersion(string filePath)
    {
        try
        {
            return FileVersionInfo.GetVersionInfo(filePath).FileVersion;
        }
        catch (FileNotFoundException ex)
        {
            mLogFile.addLogEntry("XML file. " + ex.Message);
            return null;
        }
    }

UPDATE:The File I'm querying it is not the project executable file.
thanks

A: The developer of that application didn't update the "FileVersion" string to match the information in the other properties.

Build the file version information from the following information:
FileVersionInfo info  = FileVersionInfo.GetVersionInfo(filePath);
String version = String.Format("{0}.{1}.{2}.{3}", info.FileMajorPart
                                                , info.FileMinorPart
                                                , info.FileBuildPart
                                                , info.FilePrivatePart);


text:
Q: Removing Tkinter Objects (created in a function) in a separate function I need to be able to clear my tkinter window of all objects (with a function), and create the objects again with a function. However, I cannot access the objects created with my first function with the second function. I recreated my problem below.
import tkinter
window = tkinter.Tk()
def create():
    test = tkinter.Button(window, text="Example", command=delete)
    test.place(x=75, y=100)

def delete():
    test.place_forget()

create()
window.mainloop()

This returns the error - NameError: name 'test' is not defined

A: Here's a quick sample of how your code might look, using an object oriented structure:
import tkinter as tk

class MyApp: # No need to inherit 'object' in Python 3
    def __init__(self, root):
        self.root = root

    def create_button(self):
        self.test_button = tk.Button(self.root,
                text="Example",
                command=self.delete_button)
        self.test_button.place(x=75, y=100)

    def delete_button(self):
        self.test_button.place_forget()

    def run(self):
        self.create_button()
        self.root.mainloop()

if __name__=='__main__':
    root = tk.Tk()
    app = MyApp(root)
    app.run()

You create a MyApp object that 'owns' the button, and has methods that explicitly act on the things that it owns.  Any method of the MyApp object has a reference to various widgets, via the self argument that automatically gets sent in.
This is a lot more code than you had before, and to be honest, for what your code does right now, it's an overkill.  Malik's solution of using global is probably fine.  However, if you want to add more widgets, layer them out, have them interact in more complex ways etc, then using global can introduce hard-to-find bugs, and makes it incredibly hard to wrap your head around what's going on.
Any non-trivial use of Tkinter that I have seen has used an object-oriented style similar to the above example.
As an aside, I wouldn't create the delete function - using the .config method to set the command after you create the button would be better:
def create_button(self):
    self.test_button = tk.Button(self.root, text="Example")
    self.test_button.config(command=self.test_button.place_forget)
    self.test_button.place(x=75, y=100)

Using .config allows you to set commands that are methods of the button you just created, which you can't do when you set the command as a part of the button instantiation.

A: Well if you're using two different functions, you're going to need global variables:
import tkinter
window = tkinter.Tk()

test = None

def create():
    global test
    test = tkinter.Button(window, text="Example", command=delete)
    test.place(x=75, y=100)

def delete():
    global test
    test.destroy() # or place_forget if you want
    window.after(5000, create) # button reappears after 5 seconds

create()
window.mainloop()

Your delete function could not destroy the button as it was only defined in the create function. The workaround is to create a global variable that can be accessed by both.


text:
Q: Error devise don't generate factory with factory_bot I'm using rails 5.1.4
devise 4.4.1
factory_bot_rails 4.8.2
rails g devise User
Running via Spring preloader in process 15889
      invoke  active_record
      create    db/migrate/20180213152941_devise_create_users.rb
      create    app/models/user.rb
      invoke    rspec
      create      spec/models/user_spec.rb
       error      factory_bot_rails [not found]
      insert    app/models/user.rb
       route  devise_for :users

A: Thanks for replay, the problem was that in config/application.rb, fixture_replacement need to pass :factory_bot and not factory_bot_rails, reading the doc I see that are distinct gems.


text:
Q: Determine function's domain type I'm trying to solve this two excercise:
1) Determine the domain of $f(x,y)=\sqrt{3-xy}$, then say if it is open, close, not open neither close; say if it is bounded or not.
To find the solution I solve $3-xy \ge 0$ and I find $y \le \frac{3}{x}$. In my opinion the domain is not open neither close, and it is not bounded.
2) Determine the domain of $f(x,y)=\log({3-xy})$, then say if it is open, close, not open neither close; say if it is bounded or not.
To find the solution I solve $3-xy \gt 0$ and I find $y \lt \frac{3}{x}$. In my opinion the domain is open, and it is not bounded.
I'm not sure of my answers can someone help me?

A: You want to solve $xy \le 3$.
$x = 0$ is a solution for all $y$.
If $x > 0$, then $y \le \dfrac 3x$.
If $x < 0$, then $y \ge \dfrac 3x$
Below is a graph of $xy \le 3$.
clearly its complement is an open set. So it must be a closed set.

A: 1) Be careful when dividing by $x$. If $x$ is negative, the inequality switches directions. If $x$ is $0$, you can't divide by it, but $x=0$ is still a solution to your inequality. The domain is slightly more complicated than what you have expressed.
2) Ditto for the dividing by $x$ problem. Also, depending on what you come up with for an answer, it might not be open EVEN IF you have strict inequalities $<$ running around everywhere. That gives you a good hunch that it might be open, but look carefully at the boundary. Sets don't necessarily have to be open or closed.
In either case, it's important to justify why the set is open or closed. Go back to whichever definition your book uses and see if these domains have those properties.


text:
Q: How to enrich a command for some parameters only? I would like to use the systemctl command in a way where

*

*systemctl start (and stop and restart) also triggers a systemctl status for the same service

*all other systemctl commands are ran as it

*features such as expansion are retained

I currently have a primitive solution in the form of
function sys --wraps systemctl -d "Start service and show its status"
    systemctl restart $argv
    systemctl status $argv
end

but not only I usually forget to use it, but it is extremely limited.
I believe that there is first a conditional decision to be made on the first parameter, and then either chain systemctl <parameter 1> <parameter 2> or just run systemctl <parameter 1> ...
I am stuck at the condition (if the command is systemctl and first argument is one of ['stop', 'start', 'restart'] then ...) but also on whether the expansion and memory will work.

A:
I am stuck at the condition (if the command is systemctl and first argument is one of ['stop', 'start', 'restart'] then ...)

That's actually quite simple, in the simple case [1], especially since you don't need to check systemctl - you want to run sys start, not sys systemctl start, do you?
So the conditional becomes:
if contains -- $argv[1] start stop restart
     systemctl $argv
     systemctl status $argv[2..-1]
else
     systemctl $argv
end

which can be simplified as
systemctl $argv
if contains -- $argv[1] start stop restart
    systemctl status $argv[2..-1]
end

I would like to use the systemctl command in a way where

This sounds you would like to have a "true" wrapper function, with the same name as the underlying command. That's possible, only it requires specifying command $thething every time the underlying command is called.
Also remember that fish functions are usually available even if the shell isn't interactive, so if you have any scripts calling the wrapped thing, they will end up calling the function.
So you do something like
# --wraps isn't necessary because the name is the same.
function systemctl
    # without `command`, this will be an infinite loop
    command systemctl $argv
    if contains -- $argv[1] start stop restart
        command systemctl status $argv[2..-1]
    end
end

features such as expansion are retained

You don't need to do anything here, as the expansions happen before your function is called.

[1]: There is a general problem with options. If you do systemctl --user start, the command is start, but it's not the first argument! You could skip all arguments starting with - for the purpose of determining the command, but there are also options that take arguments (e.g. systemctl --host status start). A general solution here is basically impossible, so the best you can do is something like fish's argparse, which requires adding all options that the tool supports, and then redoes the argument parsing.


text:
Q: how to rewrite url with post data by htaccess The original url is result of post =>
http://www.mywebsite.com/index.php?s=&where=townsearch&search_simple=find
I wish to have this url =>
http://www.mywebsite.com/town/townsearch.html
That's possible with htaccess ?
I wish to keep the two url functionnal but rewrite the first to the second automatically if possible.
So when we enter the first url, it rewrite it on the browser to the second, or it redirect it.

A: Add this rule to you htaccess file and it will work.
RewriteCond %{QUERY_STRING} (^|&)s=($|&)
RewriteCond %{QUERY_STRING} (^|&)where=townsearch($|&)
RewriteCond %{QUERY_STRING} (^|&)search_simple=find($|&)
RewriteRule ^index\.php$ /town/townsearch.html?&%{QUERY_STRING}

A: Use this:
RewriteEngine On
RewriteRule ^town([^/]*)/([^/]*)\.html$ /index.php?s=$1&where=$2&search_simple=find [L]

It will leave you with the URL: http://www.mywebsite.com/town/townsearch.html


text:
Q: How to populate quantities between 2 transaction dates I have a table with dates,  Products, Quantity (Purchase is positive and Sales are negative) and Price, like the following

Date        Prod_Name   Qty Price
1/3/2017    ProductA    8   150
1/9/2017    ProductB    2   170
1/11/2017   ProductA    -8  160
1/12/2017   ProductB    -2  180

I would like to have a query that generates the total quantity by product for every business day like the following:

date        A   B
1/3/2017    8   0
1/4/2017    8   0
1/5/2017    8   0
1/6/2017    8   0
1/9/2017    8   2
1/10/2017   8   2
1/11/2017   8   2
1/12/2017   0   2
1/13/2017   0   0

A: You require to generate dates and need to do sum over windowing function as below:
Declare @startdate date = '2017-01-03'
Declare @enddate date = '2017-01-13'

;with Datescte as (
Select top (datediff(day, @startdate, @enddate) +1) Dt = Dateadd(day, Row_Number() over (order by (Select null))-1, @startdate)
    from master..spt_values s1, master..spt_values s2
    ), cte2 as (
    Select * from
        ( Select [Date], Prod_name, Qty from #Dates ) a
        pivot (max(Qty) for prod_name in ([ProductA],[ProductB])) p
    )
    Select Dt as [Date], sum(ProductA) over(order by Dt) as [A], Coalesce(sum(ProductB) over(order by dt),0) as [B]
        from Datescte d
        left join cte2 d2
        on d.dt = d2.Date

First CTE generates dates between two dates.
Second CTE does pivot for two products and query returns sum based on date column

A: WITH C AS
(
SELECT        Date, Prod_Name,qty,price
FROM          YourTable
)
SELECT *
FROM C
  PIVOT(SUM([qty])
    FOR Prod_Name IN ([ProductA],[ProductB])) AS P;


text:
Q: What is the proper way to find the inverse of a function? I am a little confused on the subject of inverse functions and the methods used to do the transformation from function to inverse. How do you make an inverse? Just so i can avoid any ambiguity in my question, let's change it to the following: Would anyone on this fantastic website be kind enough to list the steps of "inversing", may be the word, the simple function of $$f(x)= \frac{(x-3)}{2}$$

A: I know there's already an accepted answer, but I'm not a fan of how its laid out, and it also has some errors in the algebra. So, here's my version.
Please comment with any questions you may have.
Let $f$ denote the unique function $\mathbb{R} \rightarrow \mathbb{R}$ defined as follows. $$f(x)=\frac{x−3}{2}$$
Problem. Find the inverse of $f$.
Solution. Let $x,y \in \mathbb{R}$ be fixed but arbitrary. Then TFAE.

*

*$f(x)=y$

*$\dfrac{x-3}{2}=y$

*$x-3=2y$

*$x=2y+3$

Therefore, the inverse of $f$ is the unique function $g : \mathbb{R} \rightarrow \mathbb{R}$ defined as follows.
$$g(y)=2y+3$$

A: I would do it by solving for $x$ first, then switching $x$ and $y$. I will use your function $f(x)=\dfrac{x-3}{2}$. First we solve for $x$ like this:
$$f(x)=\dfrac{x-2}{3}$$
$$x-3=2f(x)$$
$$x=2f(x)-3$$
$$f^{-1}(x)=2x-3$$

Let's try another example. If $f(x)=x^2-1$, and I want to find $f^{-1}(x)$, I would do this.
$$f(x)=x^2-1$$
$$x^2=f(x)+1$$
$$x=\pm\sqrt{f(x)+1}$$
Switching $f(x)$ and $x$...
$$f^{-1}(x)=\pm\sqrt{x+1}$$
Believe it or not, the inverse is wrong. Why? For a function to have an inverse, it must pass the horizontal line test. If the function has two or more x-values for one y-value, it does not have an inverse. But we can restrict the domain of $x^2$ to be $x \ge 0$. Now it has an inverse; $f^{-1}(x)=\sqrt{x+1}$, $x \ge 0$.

Extra information about inverse of functions:
$$f^{-1}(f(x))=x$$
$$f(f^{-1}(x))=x$$
The graph of $f^{-1}(x)$ is the graph of $f(x)$ reflected in the line $y=x$

Common inverses of functions:
If $f(x)=\dfrac{1}{x}$, then $f^{-1}(x)=\dfrac{1}{x}$, $x \neq 0$.
If $f(x)=e^x$, then $f^{-1}(x)=\ln(x)$, $x > 0$.
If $f(x)=a^x$, then $f^{-1}(x)=\log_{a}(x)$, $a, \ x > 0$.
If $f(x)=x^2$, then $f^{-1}(x)=\sqrt{x}$, $x \ge 0$.
If $f(x)=\sin(x)$, then $f^{-1}(x)=\sin^{-1}(x)$, $-\dfrac{\pi}{2}\leq x \leq \dfrac{\pi}{2}$.
If $f(x)=\cos(x)$, then $f^{-1}(x)=\cos^{-1}(x)$, $-\dfrac{\pi}{2}\leq x \leq \dfrac{\pi}{2}$.
If $f(x)=\tan(x)$, then $f^{-1}(x)=\tan^{-1}(x)$, $-\pi\leq x \leq \pi$.

Sometimes, a function will never have an inverse, because the function is unsolvable for $x$. For example, take the function $f(x)=2x+\cos(x)$. How are you going to solve for $x$? I don't think you can. Therefore this function does not have an inverse.

Hope I helped.

A: First of all, to type 3/over 2 in latex you should enter "\frac{3}{2}". For more informations you could just search Latex and there will be a lot of supporting instructions you can look at.
Next, once you have a function, say $y=f(x)$ and you wish to find the inverse function of it. The simplest idea is you treat $y$ as a given number and you find the number of $x$ in terms of $y$. Hence you will have a function such that $x=g(y)$ where $g(y)$ is the inverse function you are looking for. Of course, there are many situations that you can not explicitly solve $x$ in terms of $y$ but I think you won't meet those cases in your homework, exams, etc.
Of couse, $f(x) = 2x+3$ is the correct answer.

A: If a function has an inverse then the roles of $x$ and $y$ are switched. For the function you gave $f(x)=\frac{x-3}{2}$ follow the steps.
1) Replace $f(x)$ by $y$:  $$y=\frac{x-3}{2}$$
2) Switch the variables $x$ and $y$:  $$x=\frac{y-3}{2}$$
3) Solve for $y$: $$2x=y-3 \Longrightarrow y=2x+3$$
4) Replace $y$ by $f^{-1}$: $$f^{-1}(x)=2x+3$$


text:
Q: Auto eager load navigation property in the DbContext Is there a way to tamper with the DbContext in order to auto eager load a specific Navigation property when the entity is requested in a query? (no lazy loading).

Entity Framework 5

Example:
var supremeEmployee = context.Employees.FirstOrDefault(x => x.EmployeeId == 42);
and the returned model would come back pre-populated with the "Department" navigation property.

A: Depends on what your model looks like. If you're using interfaces or inheritance you could add a function to your DbContext class with a generic constraint on that type that always includes the navigation property.
In my experience though you're usually better off not doing that, performance wise. I prefer to load into anonymous types just the fields i need in the moment.
In the most basic way  you could do this:
public class Department
    {
        public int Id { get; set; }
    }

    public class Employee
    {
        public int Id { get; set; }
        public Department Department { get; set; }
    }

    public class MyContext : DbContext
    {
        protected DbSet<Employee> Employees { get; set; }

        public IQueryable<Employee> LoadEmployees()
        {
            return Employees.Include(p => p.Department);
        }
    }


text:
Q: Add weekend day backgrounds I'm using flatpicker calendar and want to make every weekend day's background #7a73aa. Unfortunately flatpicker does not add a class to weekend day's.
I've tried this with css but that's not working:
.dayContainer span:nth-child(6n) {
  background: #7a73aa;
  font-size: 20px;
}

Page source:

Any idea how I could do this with css?

A: You can replace 6n with 7n to highlight sundays. Then add a rule for 7n-1 to highlight saturdays :

flatpickr('#calendar', {
  "locale": {
    "firstDayOfWeek": 1 // start week on Monday
  }
});
.dayContainer > .flatpickr-day:nth-child(7n),
.dayContainer > .flatpickr-day:nth-child(7n-1) {
    background: #7a73aa;
    font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.5.1/flatpickr.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet"/>
<input type="text" id="calendar">


text:
Q: hive create an array from string In my data I have comma seperated strings. It would be much easier if these would be arrays, so I can easily match them with another array for example. However, I am not able to create an array from the string.
Example code:
create table tmp_array_string as
select '"abc", "def"' as tmp_string
      , array("abc", "def") as tmp_array

select a.*
     , array(tmp_string) as not_a_proper_array
     , size(tmp_array) as array_size
     , size(array(tmp_string) ) not_the_proper_array_size
from tmp_array_string a

Why is array(tmp_string not resulting in an array with 2 elements and is there a way to make this work?
Thanks a lot!

After leftjoins answer, here is the proof of the correctness. :-)

select a.*
     , array(tmp_string) as not_a_proper_array
     , split(regexp_replace(tmp_string,'"',''),',\\s*') as correct_array
     , size(tmp_array) as array_size
     , size(split(regexp_replace(tmp_string,'"',''),',\\s*')) as correct_size
     , size(array(tmp_string) ) not_the_proper_array_size
from tmp_array_string ater code here

correct size results in 2 :-)

A: Use split(str, ',') to get an array. See dosc: here
select split('abc, def',',\\s*'); --Delimiter is comma+zero or more spaces

Result:
OK
["abc","def"]
Time taken: 1.676 seconds, Fetched: 1 row(s)

If your delimited string contains extra  double quotes, then remove them using regex_replace:
 select split(regexp_replace('"abc", "def"','"',''),',\\s*');

Result:
OK
["abc","def"]
Time taken: 3.735 seconds, Fetched: 1 row(s)


text:
Q: spring security redirect user by ROLE I want to redirect user to a page based on his ROLE but i don't know how to do it.
I serched all over but it doesn't work for me. It's taking the redirect for ROLE_MASTER even if the user has ROLE_USER or other.
I tried in different ways as you can see in the commented code but none of them worked correctly.
the code is:
    @Configuration
    @EnableWebSecurity
    public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UsersDetailsServiceImpl usersDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("stefan").password("1234").roles("ADMIN");
        auth.userDetailsService(usersDetailsService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/res/**");
    }

    //.csrf() is optional, enabled by default, if using WebSecurityConfigurerAdapter constructor
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http    .authorizeRequests()
                .antMatchers("/master/**").access("hasRole('ROLE_MASTER')")
                .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/user/**").access("hasRole('ROLE_USER')")
                .antMatchers("/viewer/**").access("hasRole('ROLE_VIEWER')")
                .and()
                .formLogin().loginPage("/").failureUrl("/?error")
                .usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/master")
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/?logout")
                .and()
                .csrf();

//                .and()
//                .authorizeRequests()
//                .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
//                .and()
//                .formLogin().loginPage("/").failureUrl("/?error")
//                .usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/admin")
//                .and()
//                .logout().logoutUrl("/logout").logoutSuccessUrl("/?logout")
//                .and()
//                .csrf()
//
//                .and()
//                .authorizeRequests()
//                .antMatchers("/user/**").access("hasRole('ROLE_USER')")
//                .and()
//                .formLogin().loginPage("/").failureUrl("/?error")
//                .usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/user")
//                .and()
//                .logout().logoutUrl("/logout").logoutSuccessUrl("/?logout")
//                .and()
//                .csrf()
//
//                .and()
//                .authorizeRequests()
//                .antMatchers("/viewer/**").access("hasRole('ROLE_VIEWER')")
//                .and()
//                .formLogin().loginPage("/").failureUrl("/?error")
//                .usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/viewer")
//                .and()
//                .logout().logoutUrl("/logout").logoutSuccessUrl("/?logout")
//                .and()
//                .csrf();

//        http.authorizeRequests()
//                .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
//                .and()
//                .formLogin().loginPage("/").failureUrl("/?error")
//                .usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/admin")
//                .and()
//                .logout().logoutUrl("/logout").logoutSuccessUrl("/?logout")
//                .and()
//                .csrf();

//        http.authorizeRequests()
//                .antMatchers("/user/**").access("hasRole('ROLE_USER')")
//                .and()
//                .formLogin().loginPage("/").failureUrl("/?error")
//                .usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/user")
//                .and()
//                .logout().logoutUrl("/logout").logoutSuccessUrl("/?logout")
//                .and()
//                .csrf();

//        http.authorizeRequests()
//                .antMatchers("/viewer/**").access("hasRole('ROLE_VIEWER')")
//                .and()
//                .formLogin().loginPage("/").failureUrl("/?error")
//                .usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/viewer")
//                .and()
//                .logout().logoutUrl("/logout").logoutSuccessUrl("/?logout")
//                .and()
//                .csrf();
        //  http.formLogin().loginPage("/admin/login").failureUrl("/admin/login?error").defaultSuccessUrl("/main",true).usernameParameter("username").passwordParameter("password");

    }

}

any ideea how can i do it ?

A: Implement your own  AuthenticationSuccessHandler check user role from authentication  object and send redirect to suitable URL
<bean id="authenticationSuccessHandler" class="..." />
<form-login authentication-success-handler-ref="authenticationSuccessHandler" ... />

full example with roles


text:
Q: Is a $PL$-manifold necessarily a pure simplicial complex? A text I am reading treats $PL$-manifolds as if they were pure simplicial complexes. However it defines $n$-dimensional $PL$-manifold as $n$-dimensional simplicial complex with the property that link of every vertex is a piecewise linear sphere $S^{n-1}$. How does this definition guarantee that the simplicial complex must be pure?
Thanks.

A: I presume that by "pure" in this context you mean that every simplex is a face of some $n$-simplex, in which case this follows from an algebraic topology calculation.
First, the condition on links implies that $X$ is an $n$-manifold in the topological sense.
In a simplicial complex $X$, if $\sigma \subset X$ is a simplex of dimension $m$, and if $\sigma$ is not a face of any higher dimensional simplex of $X$, then for any $x \in \text{interior}(\sigma)$ and any integer $i \ge 0$, the relative homology of $X$ relative to its subspace $X-x$ is given by:
$$H_i(X,X-x) \approx \begin{cases}
0 & \quad\text{if $i \ne m$} \\
\mathbb Z &\quad\text{if $i=m$}
\end{cases}
$$
But if $X$ is an $n$-manifold, then $H_n(X,X-x) \approx \mathbb Z$.


text:
Q: Angular5 Testing with Jasmine. Component is part of the declarations of 2 modules: AppModule and DynamicTestModule I'm writing the first test and dealing with this error:

Error: Type SearchComponent is part of the declarations of 2 modules: AppModule and DynamicTestModule! Please consider moving SearchComponent to a higher module that imports AppModule and DynamicTestModule. You can also create a new NgModule that exports and includes SearchComponent then import that NgModule in AppModule and DynamicTestModule.

In my app I have only one module: AppModule.ts. And SearchComponent is declared only there. If I create a second module (aka ChildModule) and move SearchComponent there, the error message will have the same content but the name of a module will be changed from AppModule to ChildModule. I have the same error in every component I have.
If I remove AppModule from the imports in spec file, and add NO_ERRORS_SCHEMA, the error disappears.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule  } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { OtherComponentOne} from './tools/features/other-component-one.component';
import { OtherComponentTwo} from './tools/features/other-component-two.component';
import {routing} from "./app.routes";
import { environment } from '../environments/environment';
import {SearchComponent} from "./tools/features/search/search.component";
import {FilterPipe} from "./tools/shared/filter-pipe/filter.pipe";
import { SomeDirective } from './tools/shared/directives/some.directive';
import {ServiceOne} from "./tools/services/service-one.service";
import {ServiceTwo} from "./tools/services/service-two.service";

@NgModule({
  declarations: [
  FilterPipe,
  AppComponent,
  OtherComponentOne,
  OtherComponentTwo,
  SearchComponent,
  SomeDirective
],
imports: [
  routing,
  HttpClientModule,
  BrowserModule,
  FormsModule,
  CommonModule,
  ReactiveFormsModule
],
exports: [SomeDirective ],
providers: [ServiceOne, ServiceTwo],
bootstrap: [AppComponent]
})
export class AppModule {}

Search.component.spec.ts
import {TestBed, async, ComponentFixture} from '@angular/core/testing';
import { SearchComponent } from './search.component';
import { ServiceOne} from '../../services/service-one';
import { ServiceTwo} from '../../services/service-two';
import { FilterPipe } from '../../shared/filter-pipe/filter.pipe';
import {AppModule} from "../../../app.module";

describe('Search Component', () => {
  let component: SearchComponent;
  let fixture: ComponentFixture<SearchComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        SearchComponent, FilterPipe
      ],
      imports: [AppModule], <----If I have NO_ERRORS_SCHEMA here instead of AppModule, test passes
      providers: [ServiceOne, ServiceTwo]
    });
    fixture = TestBed.createComponent(SearchComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be initialized', async(() => {
   expect(component).toBeTruthy();
  }));
});

A: Please remove AppModule from your Search.component.spec.ts
Your test using TestingModule (DynamicTestModule) which is from TestBed. Apparently, you declared your SearchComponent when configuring TestingModule in the mean time you imported AppModule that you also declared your SearchComponent. That causes error message.


text:
Q: Find Index of Last Occurence in Multidimensional Array I use the following code to add new values to my array.
I'd like however to be able to insert values after a certain match.
var Arr = [];
a = document.getElementById("f").value;
b = document.getElementById("s").value;
c = document.getElementById("t").value;

Arr.push([f,s,t])

If for example the first element in my array contains a value that's equal to the value in "a", I'd like the new value ("a") to be inserted right after the last occurrence of that particular value in the array
for example the following array:
["OPEL", "BLACK", "4"]
["OPEL", "BLUE", "5"]
["OPEL", "RED", "4"]
["FIAT", "BLACK", "5"]
["FIAT", "WHITE", "5"]
["FORD", "GREY", "4"]

Now I'd like to insert the following item:
["FIAT", "ORANGE", "4"]

It needs to be inserted after the last occurrence of "FIAT", so the result will be:
["OPEL", "BLACK", "4"]
["OPEL", "BLUE", "5"]
["OPEL", "RED", "4"]
["FIAT", "BLACK", "5"]
["FIAT", "WHITE", "5"]
["FIAT", "ORANGE", "4"]
["FORD", "GREY", "4"]

Any ideas?

A: As you proposed, we have the following array:
var arr = [
        ["OPEL", "BLACK", "4"],
        ["OPEL", "BLUE", "5"],
        ["OPEL", "RED", "4"],
        ["FIAT", "BLACK", "5"],
        ["FIAT", "WHITE", "5"],
        ["FORD", "GREY", "4"]
];

Then, we want to put the following child after the last occurrence of an array with the same first element as it:
var child = ["FIAT", "ORANGE", "4"];

To do this, we just traverse the array and we insert child after we find an array with the same first element as it, then we find the first array without the same first element. If we haven't inserted it by the end of the array, we insert it at the end.
//Create an insert method of arr:
arr.insert = function(child) {
    //This Bool is true iff we've found an array that has the same first element as it:
    var foundSameFirstElement = false;
    //Traverse arr:
    for (var i = 0; i < this.length; i++) {
        //If we haven't found an array with the same first element as child and this element has the same first element as child, then set foundSameFirstElement to true:
        if (!foundSameFirstElement && this[i][0] === child[0]) {
            foundSameFirstElement = true;
        }
        //If we have found an array with the same first element as child and this element does not have the same first element as child, then insert child into the array here and break to exit the loop:
        if (foundSameFirstElement && this[i][0] !== child[0]) {
            this.splice(i, 0, child);
            break;
        }
    }
    //If i is this.length, then we traversed the whole loop without breaking, meaning we haven't inserted child yet. Thus, if i is this.length, insert child at the end:
    if (i === this.length) this.splice(this.length, 0, child);
};
//Now to finish it off, pass child through arr.insert:
arr.insert(child);
//If we check the value of arr, it is just like how we want it to be, with child as index 5:
console.log(arr);


text:
Q: How to save embedded PDF opened in Chrome from Python Selenium ChromeDriver The ChromeDriver for Selenium was able to open an embedded PDF after login, but how can I save the PDF file in chrome to local disk? thanks.

A: def download_pdf(lnk):
    options = webdriver.ChromeOptions()
    tgt = tempfile.mkdtemp()
    profile = {"plugins.plugins_list": [{"enabled":False,"name":"Chrome PDF Viewer"}],
        "download.default_directory" : tgt}
    options.add_experimental_option("prefs",profile)
    driver = webdriver.Chrome(CHROMEDRIVER, chrome_options = options)
    driver.get(lnk)
    driver.find_element_by_id('userName1').send_keys('username')
    driver.find_element_by_id('password1').send_keys('password')
    driver.find_element_by_id('loginButton1').click()

    ftgt = os.path.join(tgt,'downloaed.pdf')
    while not os.path.exists(ftgt):
        time.sleep(3)
    driver.close()
    return ftgt


text:
Q: Tracking user views in a news feed app on Angular 4 I am currently building a news feed app and am trying to implement a tracking feature where i can check if the user has looked over the post. Currently i was thinking of implementing tracking by calling a service when a when a user interacts with the post by commenting or upvoting. Is there a better method to track posts on the user viewing it?
I couldn't find any methods or lifecycle hooks that could address this on angular docs.


text: Q: PWA app dosen't receives push notifications after app is closed I have implemented Onesignals web push in my PWA app made on nuxt it works fine and it receive push notification till the app is opened, but after closing the app no more notifications are received but i checked on oneSignals dashboard it shows 'Received'. (This happens in some devices, while other devices receive notifiacation even if the app is closed )


text:
Q: Symfony 4: как вывести шаблон на главной? Ввел в терминале:
$ php bin/console make:controller DefaultController

Указал в контроллере:
// ...
class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function new(Request $request)
    {

        // ...
        return $this->render('default/new.html.twig', [
            'default' => $default->createView(),
        ]);
    }
}

Теперь вместо: "Welcome to Symfony 4.3.1. Your application is now ready..." (base.html.twig). Выводится шаблон new.html.twig.
Вопрос: я вывел сформированный DefaultController шаблон new.html.twig на главной. Правильно ли я его вывел? Нужно было использовать base.html.twig указанным ниже образом? index.php не трогать? Может когда-нибудь потребоваться не использовать routing, а просто создать страницу? Например: /public/page.php
// ...
  /**
   * @Route("/")
   */
  public function new(Request $request)
  {
    // ...
    return $this->render('base.html.twig', [
        'default' => $default->createView(),
    ]);
  }
// ...

A: Что бы понять использовать  или не использовать base.html.twig, нужно немного понять идею шаблонизатора twig, да и вообще шаблонизаторов. Его базовые элементы - это блоки. Блоки могут наследоваться/перезависываться. В результате у Вас получиться некая иерархия шаблонов, где, возможно, самый главный шаблон будет base.html.twig какой-нибудь дочерний categories.html.twig и дочерний дочернего new.html.twig.
Выделяем общее. Как написал @AntonKucenko, в базовый контроллер вы можете подключить скрипты, стили, определить общие блоки страницы: хедер, футер, задать блок контента и меню:
В результате чего базовый шаблон будет иметь вид
base.html.twig

     <title>{{ title }}</title>

      {% block stylesheets %}
           <link href="{{ asset('css/base.css') }}" rel="stylesheet"/>
        {% endblock %}

    {% block header %}

Верстка общего хидера

    {% endblock %}

    {% block menu %}
      верстка меню
    {% endblock %}

    {% block content %}{% endblock %}

    {% block footer %}

Верстка общего футера

    {% endblock %}

    {% block javascripts %}

    {% endblock %}

Допустим DefaultController это домашняя страница, у которой есть свой блок контента, свои стили + стили базового шаблона (хедер футер ...) и свой фронт + базовый. Тогда new.html.twig будет выглядеть так.
new.html.twig
{% extends 'base.html.twig' %}

 {% block stylesheets %}
     {{ parent() }}
      <link href="{{ asset('css/new.css') }}" rel="stylesheet"/>
 {% endblock %}

 {% block javascripts %}
     {{ parent() }}

 {% endblock %}

 {% block content %}

разметка контента

 {% endblock %}

Теперь в base.html.twig "вставлятся" блоки из new.twig.html, и все это выведется на экран.
Плюсом есть и то, что блоки в дочерних шаблонах можно описывать в любом порядке, а также можно совмещать родительские блоки и дочерние используя метод parent.


text:
Q: Delete a post with Vue + Laravel + Fetch Hi I am trying to delete a post but it is not working at all, when I check the url in the browser it displays a blank page:
So my api route in Laravel is:
Route::resource('/bank', 'BankController');

My HTML code which it's inside a component:
<button v-on:click="deletePost(post.bank_id)" class="btn btn-danger btn-circle btn-sm">
  <i class="fas fa-trash"></i>
</button>

The vue code is:
methods: {
    deletePost: function (id) {
        fetch('/api/bank/'+ id)
        .then(res => res.json())
        .catch(error => console.error('Error:', error))
        .then(response => console.log('Success:', response));
    }
 },

When I click:
It displays a blank page if I do that by URL but the console shows:

Error: SyntaxError: Unexpected end of JSON input

what could it be?

A: You have to change request method to DELETE while using resource.
In case fetch does not support delete method, try this spoofing trick:
fetch('/api/bank/'+ id + '?_method=delete')

Moreover, I recommend you to use axios in vuejs instead of fetch.

A: What it worked.. it was this:
fetch('/api/bank/' + id,  {
  method: 'DELETE'
})


text:
Q: Backup upgradable packages with dpkg-repack on debian I want to list upgradable packages and automatically repack them to .debs. My try:
fakeroot -u dpkg-repack `apt list --upgradable | cut -f1 -d"/" | awk '{if(NR>2)print}'`

So it gets package names, then redirects names to dpkg-repack. It works partially, because dpkg-repack throws error when amd64 and i386 package exists and both have the same name - in this case it expects architecture to be added to package name.
Do you have any idea how to manage it and in case of multiple arch exists, auto generate both debs? It seems dpkg-repack is not smart enough to be able to generate multiple architectures automatically, it only throws error message  saying multiple packages with the same name are installed

A: I use the following script to dpkg-repack all packages that would be affected by an apt-get operation:
#!/bin/zsh
#
# creates subdir and dpkg-repacks all relevant packages in it
#
DIR=$(date +%Y%m%d)
OPER=${@:-dist-upgrade}
mkdir -p $DIR
cd $DIR || exit 1
zmodload zsh/system

renice -n 20 -p $$ >/dev/null 2>/dev/null

nproc=$(nproc)
native_arch=$(dpkg --print-architecture)
typeset -U possible_arch=($native_arch all)
[[ $native_arch = amd64 ]] && possible_arch=($possible_arch i386)

function repacked() {
    local p=$1
    local a=$2
    local existing
    existing=(${p}_*${a}.deb(N) ${p}_*all.deb(N))   # no need to try repacking in a binary arch if _all already exists, because arch-specific and arch=all packages of the same name can't exist simultaneously
    if (($#existing)); then
        [[ "$a" = none ]] && unset a    # avoid confusing message with arch specified as "none"
        echo "Skipping $p${a:+:$a}, already repacked." >&2
        return 0
    fi
    return 1
}

function worker() {
    local pkg=$1
    local arch=$2
    local lockfd lockfd2
    local success=0
    local try_arch
    [[ -z "$pkg" ]] && return 0
    : >>"$pkg.$arch.lock"
    if zsystem flock -f lockfd -t 0 "$pkg.$arch.lock" 2>/dev/null; then
        if [[ $arch = none ]]; then
            for try_arch in $possible_arch; do
                repacked $pkg $try_arch && success=1
            done
            if ! ((success)) && ! dpkg-repack $pkg; then
                for try_arch in $possible_arch; do
                    echo "*** DEBUG: *** entering architecture guessing branch in worker()." >&2    # it's unclear whether this branch will ever even be run
                    repacked $pkg $try_arch && break    # avoid even locking if another thread got here first; allows main thread to start an additional worker sooner
                    : >>"$pkg.$try_arch.lock"
                    if zsystem flock -f lockfd2 -t 0 "$pkg.$try_arch.lock" 2>/dev/null; then
                        if repacked $pkg $try_arch; then    # make sure another thread didn't get to this package after our previous check but before acquiring the lock
                            success=1
                        else
                            dpkg-repack --arch=$try_arch $pkg:$try_arch && success=1
                        fi
                        rm $pkg.$try_arch.lock
                        zsystem flock -u $lockfd2
                        ((success)) && break
                    fi
                done
            fi
        else
            repacked $pkg $arch || dpkg-repack --arch=$arch $pkg:$arch  # TODO: run with loadwatch
        fi
        rm $pkg.$arch.lock
        zsystem flock -u $lockfd
    fi
}

# clean up any leftover locks from a previous invocation
for i in *.lock(N); do
    zsystem flock -f lockfd $i  # if they're still locked, a dpkg-repack may still be running; wait for it to finish
    rm $i
    zsystem flock -u $lockfd
done

for i in $(echo n \
    | LC_MESSAGES=C apt-get -d -u ${=OPER} 2>&1 \
    | sed -r '/^The following packages were automatically installed/,/^Use .apt(-get)? autoremove. to remove them/d
          /^The following NEW packages will be installed:/,/^The/s/^[[:space:]].*//
          /^The following packages have been kept back:/,/^The following packages will be upgraded:/d
          /^The following packages have unmet dependencies:/,$d' \
    | grep '^[[:space:]]' \
    | tr -d '*'); do
        if ((${i[(I):]})); then # package name includes architecture (separated by colon) -- index of colon within $i is not zero
            echo ${${i:t}/:/ }  # print name and architecture
        else
            p=${i:t}
            # guess architecture:
            [[ -e /var/lib/dpkg/info/${p}.list ]] && echo $p none   # we don't know the architecture, but perhaps dpkg-repack doesn't need it; have the worker try
            for try_arch in $possible_arch; do
                [[ -e /var/lib/dpkg/info/${p}:${try_arch}.list ]] && echo $p $try_arch
            done
        fi
done | sort -u | while read p a; do
    if ! repacked $p $a; then
        workers=(*.lock(N))
        while [[ $#workers -ge $nproc ]]; do    # wait for a worker slot to become available
            sleep 0.5
            workers=(*.lock(N))
        done
        [[ -n "$p" ]] && worker $p $a &
    fi
done
wait
rm -f *.lock(N)

Just call it with the same arguments you would pass to apt-get. It'll create a directory named for today's date, and put all generated .debs in there. It will repack as many packages in parallel as you have CPU cores. It's idempotent in the sense that if a .deb for a package already exists, it won't repack it again, making it safe to abort and restart.
It has the i386 and amd64 architectures hardwired, so if you have something else you'll need to change it.


text:
Q: Does datastore supports inequality filter? I'm trying to run a query using the inequality filter but it errors out:datastore: invalid operator "!=" in filter "Field1 !="
 Isn't this supported?
I'm using Go whose documentation doesn't mention this filter but the python docs seem to support negation so I'm wondering if it's a go specific issue or if I'm missing something.
q.Query = q.Query.Filter("Field1 !=", value)

A: In the doc, it states that filter only supports these: =, <, <=, >, >=.
So != isn't supported. However you may have a workaround like this:
q.Query = q.Query.Filter("Field1 >", value).Filter("Field1 <", value)

which should yield the result as !=.


text:
Q: Basic concatenation in Powershell doesn't work I cannot push to $filepaths, can't see why :
$filepaths=@()
$files= @('file1.text','file2.txt')
foreach ($file in $files) {
  $filepaths.add("c:\test\" + $file)
}
$filepaths

A: @() is a System.Array (a fixed collection), reading from Remarks on the .Add method from this Class:

Ordinarily, an IList.Add implementation adds a member to a collection. However, because arrays have a fixed size (the IsFixedSize property always returns true), this method always throws a NotSupportedException exception.

PowerShell offers us the ability to recreate the array with a new element using the += operator, however this is not recommended for reasons very well explained in this answer.
You can either assign to a variable the output of your enumeration:
$filepaths = foreach($file in 'file1.txt', 'file2.txt') {
    "c:\test\" + $file
}
$filepaths

In this example, PowerShell will dynamically assign the type for $filepaths, if 1 element is returned from the enumeration it would be string, for more than one it would become object[] (Array).
Or use a collection that allows adding new elements, such as ArrayList or List<T>:
$filepaths = [Collections.Generic.List[string]]::new()
foreach($file in 'file1.txt', 'file2.txt') {
    $filepaths.Add("c:\test\" + $file)
}
$filepaths

Here, $filepaths would always be of the type List`1.


text:
Q: unique=true doesn't create index Email = models.EmailField(max_length = 300, unique = True)

Doesn't create an index on SQLite 3. Documentation says unique = True will create a index. But checking SQLite it is not created.
Documentation

A: Most database backends will automatically create an index if the field is marked as unique. Indeed, in the source code [GitHub] we see:

def _field_should_be_indexed(self, model, field):
    return field.db_index and not field.unique

So if a field is marked as unique, by default it will not be indexed, since the database itself will already do that.
This is the same for foreign keys, for which some databases will also create an index automatically.


text:
Q: PyYAML giving constructor errors? So I'm currently trying to simulate an Insecure Deserialization attack. Here's the code I'm using:
import yaml

with open('malicious.yml') as yaml_file:
    contents = yaml.load(yaml_file)
    print(contents['foo'])

The file malicious.yml contains the following:
foo: !!python/object/apply:subprocess.check_output ['ls']

However, when I run the script, I get the following error:
yaml.constructor.ConstructorError: could not determine a constructor for the tag 'tag:yaml.org,2002:python/object/apply:subprocess.check_output'
in "malicious.yml", line 1, column 6

I looked around a bit but still couldn't find why. Any help would be appreciated.

A: If you are trying to simulate an insecure deserialization attack, you should use
contents = yaml.danger_load(yaml_file)

or use an older version of PyYAML (pip install pyyaml<4). The API was changed with version 4.1 without any documentation changes.


text:
Q: Download SVG content as PNG file, Following code is working fine in chrome but not working in IE browser.Any suggestions? Download SVG content as PNG file, Following code is working fine in chrome but not working in IE browser.Any suggestions?
.
var svg = document.querySelector( "svg" );
var svgData = new XMLSerializer().serializeToString( svg );
var canvas = document.createElement( "canvas" );

var svgSize = svg.getBoundingClientRect();
canvas.width = svgSize.width;
canvas.height = svgSize.height;
var ctx = canvas.getContext( "2d" );
var img = document.createElement( "img" );
img.setAttribute( "src", "data:image/svg+xml;base64," + btoa( svgData ) );

img.onload = function() {
    ctx.drawImage( img, 0, 0 );

    setTimeout(function(){
        var a = document.createElement("a");
        a.download = "networkmap.png";
        a.href = canvas.toDataURL("image/png");console.log(a.href);
        a.click();
     }, 500);
};

A: data:image/svg+xml; seems fishy for a Canvas/PNG element, data:image/png is the right Mime-Type for PNG.


text:
Q: How do I return a list of the three lowest values in another list How do I return a list of the 3 lowest values in another list. For example, I want to get the 3 lowest values like this:
in_list = [2, 3, 4, 5, 6, 1]

To this:
out_list: [2, 3, n, n, n, 1]

Maybe a function like this:
out_list = function(in_list, 3)?

in_list and ouput list is declared like this:
List<string> in_list = new List<string>();
List<string> out_list = new List<string>();

Can you help me developing a C# code for this? Further explanation can be given.

A: If you really want those weird n, there's this simple solution:
public static List<string> Function(List<string> inputList, int max)
{
    var inputIntegers = inputList
        .Select(z => int.Parse(z))
        .ToList();

    var maxAuthorizedValue = inputIntegers
        .OrderBy(z => z)
        .Take(max)
        .Last();

    return inputIntegers
        .Select(z => z <= maxAuthorizedValue ? z.ToString() : "n")
        .ToList();
}

public static void Main(string[] args)
{
    List<string> in_list = new List<string> { "2", "3", "4", "6", "1", "7" };

    var res = Function(in_list, 3);

    Console.Read();
}

For your new requirement about duplicates, you could limit the max number of integer your return:
public static List<string> Function(List<string> inputList, int max)
{
    var inputIntegers = inputList.Select(z => int.Parse(z)).ToList();

    var maxAuthorizedValue = inputIntegers
        .OrderBy(z => z)
        .Take(max)
        .Last();

    // I don't really like that kind of LINQ query (which modifies some variable
    // inside the Select projection), so a good old for loop would probably
    // be more appropriated
    int returnedItems = 0;
    return inputIntegers.Select(z =>
        {
            return (z <= maxAuthorizedValue && ++returnedItems <= max) ? z.ToString() : "n";
        }).ToList();
}

A: You need two queries, one to determine the lowest items and one to fill the result-list. You can use a HashSet for faster loookups:
var lowest = new HashSet<String>(in_list
    .Select(s => new { s, val = int.Parse(s) })
    .OrderBy(x => x.val)
    .Take(3)
    .Select(x => x.s));
List<string> out_list = in_list.Select(s => lowest.Contains(s) ? s : "n").ToList();

If you actually only want 3 and duplicates are possible this is the best i've come up with:
var lowest = new HashSet<String>(in_list
    .Select(s => new { s, val = int.Parse(s) })
    .Distinct()
    .OrderBy(x => x.val)
    .Take(3)
    .Select(x => x.s));
List<string> out_list = in_list
    .Select((str, index) => new { str, index, value = int.Parse(str) })
    .GroupBy(x => x.str)
    .SelectMany(g => lowest.Contains(g.Key)
        ?  g.Take(1).Concat(g.Skip(1).Select(x => new { str = "n", x.index, x.value }))
        :  g.Select(x => new { str = "n", x.index, x.value }))
    .OrderBy(x => x.index)
    .Select(x => x.str)
    .ToList();

A: You could use Aggregate to grab a Dictionary of each element with its corresponding number of allowed occurrences which you could then use to grab your values from the input list:
public static List<string> GetList(List<string> in_list, int max)
{
    Dictionary<string, int> occurrences = new Dictionary<string, int>();
    int itemsAdded = 0;

    in_list.OrderBy(x => x).Aggregate(occurrences, (list, aggr) =>
    {
        if (itemsAdded++ < max)
        {
            if (occurrences.ContainsKey(aggr))
                occurrences[aggr]++;
            else
                occurrences.Add(aggr, 1);
        }

        return list;
    });

    //occurrences now contains only each required elements
    //with the number of occurrences allowed of that element

    List<string> out_list = in_list.Select(x =>
    {
        return (occurrences.ContainsKey(x) && occurrences[x]-- > 0 ? x : "n");
    }).ToList();

    return out_list;
}


text:
Q: i want to get key value of array in ruby In a .rb file I am using result = JSON.parse(res.body)['data']['results'] and get
[
  {"suggestion":"Lineman","id":"49.10526"},
  {"suggestion":"Linguist","id":"27.10195"},
  {"suggestion":"Librarian","id":"25.47"},
  {"suggestion":"Lifeguard","id":"33.39"},
  {"suggestion":"Line Cook","id":"35.30125"},
  {"suggestion":"Life Coach","id":"21.209"},
  {"suggestion":"Life Guard","id":"33.1001"}
]

now I want an array like
[
  "Lineman",
  "Linguist",
  "Librarian",
  "Lifeguard",
  "Line Cook",
  "Life Coach",
  "Life Guard"
]

What should I apply to JSON.parse(res.body)['data']['results']?

A: You can use Enumerable#map:
  other_result = result.map { |val| val['suggestion'] }

it returns a new array with results of applying the block to initial array elements

A: Try this:
suggestions = result.pluck(:suggestion)
# ["Lineman", "Linguist", "Librarian", "Lifeguard", "Line Cook", "Life Coach", "Life Guard"]

This plucks all the suggestion values and returns them as an array.


text:
Q: An unexpected end of file was encountered in the data file during Bulk insert from text file I was looking for the answer and could not fine the one for my question. It seems that I'm doing everything as explained, but it does not work in my case...
I'm doing a bulk insert with "|" as a field separator and I have a text file with a content like that:
111       |234567|111111111111|22222222222|33333333333333|444444444444|D|        |         |        |
222       |890111|222211111111|33332222222|34444333333333|555544444444|V|        |         |        |

At the end of each line when I look at Notepad++ I have "CRLF"
I have a table named Bulk_Table_Sample with the same amount of columns as separated in the file
Column1,Column2,Column3,Column4,Column5,Column6,Column7,Column8,Column9,Column10,Column11

And I have a view based on that table:
CREATE VIEW [dbo].[vw_Bulk_Table_Sample]
AS
    SELECT Column1,Column2,Column3,Column4,Column5,Column6,Column7,Column8,Column9,Column10,Column11
    FROM Bulk_Table_Sample

This is my Bulk Statement:
declare @cmd varchar(1000)
declare @FullFilePath varchar(1000)

set @FullFilePath = '\\File_Path\Data_Sample.DAT'

           SET @cmd = 'BULK INSERT dbo.vw_Bulk_Table_Sample FROM '''+ @FullFilePath +
                    ''' WITH(BATCHSIZE=20000,TABLOCK,FIRSTROW=1,FIELDTERMINATOR=''"|"'',ROWTERMINATOR=''\r'')'
           EXEC (@cmd)

When executing the statement, I'm getting the following error:
Msg 4832, Level 16, State 1, Line 183
Bulk load: An unexpected end of file was encountered in the data file.
Msg 7399, Level 16, State 1, Line 183
The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error.
Msg 7330, Level 16, State 2, Line 183
Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".

What is wrong with what I'm doing?


text:
Q: memoir: chapter style: recapitulation What is the right way to make chapter recapitulations (or is there the proper way to call it?) old fashioned style, like in Gulliver's Travels?
PART I--A VOYAGE TO LILLIPUT.
1. CHAPTER I.
[The author gives some account of himself and family. His first inducements to travel. He is shipwrecked, and swims for his life. Gets safe on shore in the country of Lilliput; is made a prisoner, and carried up the country.]
My father had a small estate in Nottinghamshire: I was the third of five sons. He sent me to Emanuel College in Cambridge at fourteen years old, where I resided three years, and applied myself close to my studies;
I mean the part inside brackets. I suppose you remember how it looks on paper :)

A: I did it. The name is chapter precis.
\chapter{Feature-Based Multi-Resolution Registration of Immunostained Serial Sections}
\label{cha:media16}
\chapterprecishere{In which we discuss the fine-grain registration of
  serial sections and its quality. We are able to register the serial
  sections up to smallest capillaries, despite a lot of
  self-similarity.}
% ...

There is also an option to state some precis for the TOC, \chapterprecistoc. The \chapterprecis command does both.
Update: It looks like this. I took a different chapter such that the precis is small enough.


text:
Q: R wanting to limit the amount of digits from csv file There are plenty of threads about people thinking they have lost digits when reading in a csv file, and it's just a digits setting that isn't displaying all of them.
I on the other hand want to round or truncate my incoming data to two decimal places. I am having an issue in Rmarkdown where I can't limit the decimal places after highlighting fields.
This has lead to me attempting to round before the highlighting, but that leads to undesirable results if I go lower than 4 places since I am working with numbers near 0. It'll also throw scientific numbers in from time to time....which just doesn't look clean in my table.
df.csv
     Sample   blank   square   stool   ball       triangle     circle    hammer     dog
 1:    16-ww3 0.00090 0.93100 0.01219 0.00006      0.00606      0.00180 0.00000 0.00003
 2:      17-e 0.00034 0.67452 0.00297 0.00006      0.00357      0.00172 0.00008 0.00001
 3:    21-r9a 0.00186 0.34577 0.01558 0.00020      0.02277      0.00586 0.00009 0.00012
 4:       7-d 0.00003 0.00352 0.01179 0.00003      0.01640      0.56326 0.00349 0.00064
 5:    7401-1 0.00151 0.55153 0.00196 0.00017      0.00055      0.00029 0.00012 0.00000
 6:    7401-2 0.00056 0.50825 0.00433 0.00010      0.00000      0.00008 0.00006 0.00003

Code
library(kableExtra)
library(magrittr)

DF <- read.csv(file="df.csv"), header=TRUE, sep=",",stringsAsFactors = FALSE)

DF[1:nrow(DF), 2:ncol(DF)] <- round(DF[1:nrow(DF), 2:ncol(DF)], 4)

paint <- function(x) {
  ifelse(x < 0.1, "white", ifelse(x < 0.2, "yellow", "red"))
}

DF %<>%
  mutate_if(is.numeric, function(x) {
   cell_spec(x, background = paint(x), format = "latex")
  })

kable(DF, caption = "Highlighted numbers near zero", digits = 2, format = "latex", booktabs = T, escape = F, longtable = T)%>%
  kable_styling(latex_options = c("striped", "hold_position", "repeat_header", font_size = 6))%>%
  landscape()%>%
  row_spec(0, angle = 45)

Desired output
 numbers formatted like:  0.00  0.01  0.10  1.10
 AND highlighted as described in the paint function

A: If I understand correctly what you want, this should work:
First let's convert your numeric columns into character vectors, with the required number of decimal places, using formatC
DF[, -1] = lapply(DF[, -1], formatC, format = 'f', flag='0', digits = 2)

Now we can apply the latex formatting using:
DF[,-1] = lapply(DF[,-1], function(x) cell_spec(x, background = paint(x), format = "latex"))

Note that paint still works on the character vectors, because the comparison to a numeric value coerces them to numeric.
Here's a complete reproducible example, demonstrating this in practice
set.seed(1234)
DF <- data.frame(V1 = sample(letters,10,T), V2 = abs(rnorm(10)), V3 = abs(rnorm(10)))
DF[, -1] = lapply(DF[, -1], formatC, format = 'f', flag='0', digits = 2)
DF[, -1] = lapply(DF[,-1], function(x) cell_spec(x, background = paint(x), format = "latex"))
#    V1                       V2                        V3
# 1   c   \\cellcolor{red}{0.51} \\cellcolor{yellow}{0.11}
# 2   q   \\cellcolor{red}{0.57}    \\cellcolor{red}{0.51}
# 3   p   \\cellcolor{red}{0.55}    \\cellcolor{red}{0.91}
# 4   q   \\cellcolor{red}{0.56}    \\cellcolor{red}{0.84}
# 5   w   \\cellcolor{red}{0.89}    \\cellcolor{red}{2.42}
# 6   q   \\cellcolor{red}{0.48} \\cellcolor{yellow}{0.13}
# 7   a   \\cellcolor{red}{1.00}    \\cellcolor{red}{0.49}
# 8   g   \\cellcolor{red}{0.78}    \\cellcolor{red}{0.44}
# 9   r \\cellcolor{white}{0.06}    \\cellcolor{red}{0.46}
# 10  n   \\cellcolor{red}{0.96}    \\cellcolor{red}{0.69}

kable(DF, caption = "Highlighted numbers near zero",
  digits = 2, format = "latex", booktabs = T, escape = F, longtable = T) %>%
  kable_styling(latex_options = c("striped", "hold_position",
    "repeat_header", font_size = 6)) %>%
  landscape() %>%
  row_spec(0, angle = 45)

# \begin{landscape}
# \begin{longtable}{lll}
# \caption{\label{tab:}Highlighted numbers near zero}\\
# \toprule
# \rotatebox{45}{V1} & \rotatebox{45}{V2} & \rotatebox{45}{V3}\\
# \midrule
# \endfirsthead
# \caption[]{Highlighted numbers near zero \textit{(continued)}}\\
# \toprule
# \rotatebox{45}{V1} & \rotatebox{45}{V2} & \rotatebox{45}{V3}\\
# \midrule
# \endhead
# \
# \endfoot
# \bottomrule
# \endlastfoot
# \rowcolor{gray!6}  c & \cellcolor{red}{0.51} & \cellcolor{yellow}{0.11}\\
# q & \cellcolor{red}{0.57} & \cellcolor{red}{0.51}\\
# \rowcolor{gray!6}  p & \cellcolor{red}{0.55} & \cellcolor{red}{0.91}\\
# q & \cellcolor{red}{0.56} & \cellcolor{red}{0.84}\\
# \rowcolor{gray!6}  w & \cellcolor{red}{0.89} & \cellcolor{red}{2.42}\\
# \addlinespace
# q & \cellcolor{red}{0.48} & \cellcolor{yellow}{0.13}\\
# \rowcolor{gray!6}  a & \cellcolor{red}{1.00} & \cellcolor{red}{0.49}\\
# g & \cellcolor{red}{0.78} & \cellcolor{red}{0.44}\\
# \rowcolor{gray!6}  r & \cellcolor{white}{0.06} & \cellcolor{red}{0.46}\\
# n & \cellcolor{red}{0.96} & \cellcolor{red}{0.69}\\*
#   \end{longtable}
# \end{landscape}


text:
Q: Why is my SQL Server query failing?  connect();
 $arr = mssql_fetch_assoc(mssql_query("SELECT Applications.ProductName,
        Applications.ProductVersion, Applications.ProductSize,
        Applications.Description, Applications.ProductKey, Applications.ProductKeyID,
        Applications.AutomatedInstaller, Applications.AutomatedInstallerName,
        Applications.ISO, Applications.ISOName, Applications.Internet,
        Applications.InternetURL, Applications.DatePublished, Applications.LicenseID,
        Applications.InstallationGuide, Vendors.VendorName
FROM Applications
INNER JOIN Vendors ON Applications.VendorID = Vendors.VendorID
WHERE ApplicationID = ".$ApplicationID));

$query1 = mssql_query("SELECT Issues.AppID, Issues.KnownIssues
      FROM Issues
      WHERE Issues.AppID=".$ApplicationID);
$issues = mssql_fetch_assoc($query1);
$query2 = mssql_query("SELECT ApplicationInfo.AppID,
               ApplicationInfo.Support_Status, ApplicationInfo.UD_Training,
               ApplicationInfo.AtomicTraining, ApplicationInfo.VendorURL
   FROM  ApplicationInfo
   WHERE ApplicationInfo.AppID = ".$ApplicationID);
$row = mssql_fetch_assoc($query2);
function connect(){
 $connect =  mssql_connect(DBSERVER, DBO, DBPW) or
        die("Unable to connect to server");
 $selected = mssql_select_db(DBNAME, $connect) or
        die("Unable to connect to database");
 return $connect;
}

Above is the code. The first query/fetch_assoc works perfectly fine, however the next 2 queries fail and I cannot figure out why. Here is the error statement that shows up from php:

Warning: mssql_query() [function.mssql-query]: message: Invalid object name 'Issues'. (severity 16) in /srv/www/htdocs/agreement.php on line 47
Warning: mssql_query() [function.mssql-query]: General SQL Server error: Check messages from the SQL Server (severity 16) in /srv/www/htdocs/agreement.php on line 47
  Warning: mssql_query() [function.mssql-query]: Query failed in /srv/www/htdocs/agreement.php on line 47
Warning: mssql_fetch_assoc(): supplied argument is not a valid MS SQL-result resource in /srv/www/htdocs/agreement.php on line 48
Warning: mssql_query() [function.mssql-query]: message: Invalid object name 'software.software_dbo.ApplicationInfo'. (severity 16) in /srv/www/htdocs/agreement.php on line 51
Warning: mssql_query() [function.mssql-query]: General SQL Server error: Check messages from the SQL Server (severity 16) in /srv/www/htdocs/agreement.php on line 51
Warning: mssql_query() [function.mssql-query]: Query failed in /srv/www/htdocs/agreement.php on line 51
Warning: mssql_fetch_assoc(): supplied argument is not a valid MS SQL-result resource in /srv/www/htdocs/agreement.php on line 52

The error clearly centers around the fact that the query is not executing. In my database I have a table called Issues and a table called ApplicationInfo so I am unsure why it is telling me that they are invalid objects.

A: Check that you're querying the right database or schema.
software.software_dbo.ApplicationInfo means:

*

*a database named software

*a schema named software_dbo - likely this is the problem. Likely is dbo on your SQL Server.

*a view/table named ApplicationInfo
Perhaps check what the value of DBO, amongst the other arguments, is in this statement: $connect =  mssql_connect(DBSERVER, DBO, DBPW)

A: Check to see that the user you are connecting with has permission to use the tables you are trying to query. Seams like the issue is that the tables cannot be found.
The best way to handle this would be to grant the user permssions to all objects in that database:
GRANT SELECT, INSERT, DELETE <any other permissions that user needs> ON `database`.`*` TO `user`@`localhost` IDENTIFIED BY 'password'


text:
Q: Android foreground service consistently throws "java.lang.IllegalArgumentException: Service not registered" exception My project requires an android foreground service to run continuously (even after the application is destroyed). To this effect I have the following code snippets:
build.gradle
implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.android.gms:play-services-places:16.0.0'
implementation 'com.google.android.libraries.places:places:1.1.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.android.gms:play-services-ads:17.2.0'

Manifest permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

MainActivity.java
@Override
public void onCreate() {
    Intent intent = new Intent(getApplicationContext(), MyService.class);
    if (!isMyServiceRunning(MyService.class, MainActivity.this)) {
        intent.setAction(MYConstants.ACTION_START_GPS_SERVICE);
        intent.setAction(MyConstants.ACTION_START_GPS_SERVICE);
        startService(intent);
        Log.i(TAG, "MyService call made.");
    }
}

MyService.java
public class MyService extends Service {
       @Override
       public void onCreate() {
           super.onCreate();
           if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
               startServiceWithNotification();
           } else{
               startForeground(9999, new Notification());
           }
       }

       @Override
       public int onStartCommand(Intent intent, int flags, int startId) {
            super.onStartCommand(intent, flags, startId);
            return START_STICKY;
       }

       @Override
       public void onTaskRemoved(Intent rootIntent){
          stopMyService();
          Intent broadcastIntent = new Intent(this, MyBroadcastReceiver.class);
          sendBroadcast(broadcastIntent);
       }

       @Override
       public void onDestroy() {
           stopMyService();
           super.onDestroy();
      }

      @Override
      public IBinder onBind(Intent intent) {
           // Used only in case of bound services.
           return null;
     }

     void stopMyService() {
          stopForeground(true);
          stopSelf();
     }

     @RequiresApi(Build.VERSION_CODES.O)
     void startServiceWithNotification() {
        String channelId = "com.mypackage.myapp";
        String channelName = "Your Service";

        NotificationChannel chan;

        chan = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager mNotificationManager = (NotificationManager)
               getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,
              channelId);

        Notification notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("App is running in background")
            .setPriority(NotificationManager.IMPORTANCE_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build();
        startForeground(10000, notification);
    }
}

MyBroadcastReceiver.java
@Override
public void onReceive(Context context, Intent intent) {
    Intent intent =  new Intent(context, MyService.class);
    intent.setAction(MYConstants.ACTION_START_GPS_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(intent);
        Log.i(TAG, "MyService call made.");
    } else {
        context.startService(intent);
    }
}

This Application is working as expected, the foreground service runs fine doing what it is intended to do even after the app is destroyed, but I consistently see a Warning as an IllegalArgumentException while running the application. The exception is attached below:
D/EGL_emulation: eglMakeCurrent: 0xdda12a20: ver 3 0 (tinfo 0xdda81230)
W/System: A resource failed to call close.
W/ConnectionTracker: Exception thrown while unbinding
   java.lang.IllegalArgumentException: Service not registered: ll@85f600c
       at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1731)
       at android.app.ContextImpl.unbindService(ContextImpl.java:1755)
       at android.content.ContextWrapper.unbindService(ContextWrapper.java:735)
       at ce.b(:com.google.android.gms.dynamite_measurementdynamite@201817068@20.18.17 (100700-0):1)
       at ce.a(:com.google.android.gms.dynamite_measurementdynamite@201817068@20.18.17 (100700-0):5)
       at lm.A(:com.google.android.gms.dynamite_measurementdynamite@201817068@20.18.17 (100700-0):10)
       at kx.a(:com.google.android.gms.dynamite_measurementdynamite@201817068@20.18.17 (100700-0):3)
       at dx.run(:com.google.android.gms.dynamite_measurementdynamite@201817068@20.18.17 (100700-
          0):2)
       at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
       at java.util.concurrent.FutureTask.run(FutureTask.java:266)
       at iv.run(:com.google.android.gms.dynamite_measurementdynamite@201817068@20.18.17 (100700-
         0):15)
 W/.myapp: Reducing the number of considered missed Gc histogram windows from 186 to 100
 W/System: A resource failed to call close.

Can someone help me out in understanding why this exception is consistently being thrown and how can I resolve this??

A: As suggested by @CommonsWare in the comments above, the exceptions observed here are being logged by Play Services which is quite common and isn't a consequence of the application.
Unless the exceptions are causing serious problems (such as the app crashing), such exceptions must not be considered as a pain point.


text:
Q: Cannot get the `name` claim from IdentittyServer4, when the client is written in .NET Framework I authenticate a user to a ASP.NET (.NET Framework) site using IdentityServer4 (separate application written in .NET Core).
Everything works fine, but the name claim is never returned.
If the client was written in .NET Core, there seems to be this GetClaimsFromUserInfoEndpoint property (assembly Microsoft.AspNetCore.Authentication.OpenIdConnect, Version=3.1.3.0):
        services
            .AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                options.Authority = Configuration["AppSettings:IdentityServerUrl"];
                options.RequireHttpsMetadata = true;

                options.ClientId = Configuration["AppSettings:ClientId"];
                options.ClientSecret = Configuration["AppSettings:ClientSecret"];
                options.ResponseType = "code id_token";

                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true; // <<<<<<<<<<<---
            ....

However, in .NET Framework, I have no such property. All I have is this code (extension assembly: Microsoft.Owin.Security.OpenIdConnect v3.1.0.0):
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
        });

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            AuthenticationType = "oidc",
            SignInAsAuthenticationType = "Cookies",
            Authority = identityServerUrl,
            RedirectUri = appUrl + "/signin-oidc",
            PostLogoutRedirectUri = appUrl + "/signout-callback-oidc",
            ClientId = "clientId",
            ClientSecret = @"secret",
            ResponseType = OpenIdConnectResponseTypes.CodeIdToken,
            Scope = "openid profile offline_access",
            UseTokenLifetime = false,
        });

I have tried various things on the client and on the identity server, but nothing seems to help.
Can someone tell me how I can get this claim inside my token?
I am getting other claims, but it seems to skip calling the user info endpoint on IdentityServer, and that's why this user claim is not there.

A: You must implement IPorfileService interface for .NET
read: http://docs.identityserver.io/en/latest/reference/profileservice.html
and : https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2013/dn277201(v%3Dvs.120)
I hope that helps you ! :)
Later edit:
 var oidcOptions = new OpenIdConnectAuthenticationOptions
       {
           Authority = OidcAuthority,
           ClientId = OidcClientId,
           ClientSecret = OidcClientSecret,

          GetClaimsFromUserInfoEndpoint = true,

           PostLogoutRedirectUri = OidcRedirectUrl,
           RedirectUri = OidcRedirectUrl,
           ResponseType = OpenIdConnectResponseType.Code,
           Scope = OpenIdConnectScope.OpenId
       };
       app.UseOpenIdConnectAuthentication(oidcOptions);

A: You can try to add this to your client, to fix the mapping between that Microsoft consider to be the name and what Identity Server consider to be the name claim.
options.TokenValidationParameters = new TokenValidationParameters
{
    NameClaimType = JwtClaimTypes.Name,
    RoleClaimType = JwtClaimTypes.Role,
};


text:
Q: $\omega$-consistent in Gödel I In a very accessible form one could state the first incompleteness as follows:
Incompleteness Theorem I
Assume that $\textbf{PA}$ is consistent. Then there is a sentence $\phi$ such that

*

*$\textbf{PA}\nvdash \phi$ and

*if $\textbf{PA}\vdash\textsf{Pr}_{\textbf{PA}}(\overline{\phi}) \Rightarrow \textbf{PA}\vdash\phi$, then $\textbf{PA}\nvdash\neg\phi$,

where $\textsf{Pr}_{\textbf{PA}}(y)$ is the "is provable in $\textbf{PA}$" predicate, i.e. $\exists x . \textsf{Prov}_{\textbf{PA}}(x,y)$.
$\omega$-consistence
My question is about the relation between the assumption given in 2. and the $\omega$-consistence of $\mathbf{PA}$, since one can state Gödel I like above but with the $\omega$-consistence as assumption instead.
The definition I know is the following:
There is no formula $\phi(x)$ such that $\mathbf{PA}\vdash\exists x.\phi(x)$ and simultaneously that we have for every $n$: $\mathbf{PA}\vdash \neg\phi(\overline{n})$.
I've tried a few times, always running into the syntactic negation of the assumption. At least I would like to know if it is equivalent at all!?
Thanks!

A: The assumption in 2. indeed follows from $\omega$-consistency: Consider the formula $\textsf{Pr}_{\textbf{PA}}(x,\overline{\phi})$ in the free variable $x$ expressing that $x$ codes a proof of $\phi$. If $\textbf{PA}\vdash \textsf{Pr}_{\textbf{PA}}(\overline{\phi})$, then $\textbf{PA}\vdash \exists x. \textsf{Pr}_{\textbf{PA}}(x,\overline{\phi})$, so $\omega$-consistency implies the existence of some $n$ such that $\textbf{PA}\not\vdash\neg\textsf{Pr}_{\textbf{PA}}(n,\overline{\phi})$, so $\textbf{PA}\vdash\textsf{Pr}_{\textbf{PA}}(n,\overline{\phi})$ by the soundness of the coding $\textsf{Pr}_{\textbf{PA}}$. Now, in the meta theory you can decode this $n$ and check whether it is indeed a proof of $\phi$ in $\textbf{PA}$ - if it is, fine, and if it is not, the soundness of the coding would also give $\textbf{PA}\vdash \neg\textsf{Pr}_{\textbf{PA}}(n,\overline{\phi})$, hence an inconsistency.


text:
Q: How setVisible invisible Buttons in a CustomAdapter My problem is editing on click see

But I need that on click "EDITAR" it does

I have a Button that set my DELETE button visible for each element of the ListView.
But it only sets visible the last element. How can I set all the elements visible ?
MyButton is Ocult in my custom adapter and when I call the method that set my buttons visible ... This button Works Fine.
    //button "EDITAR"
    btnBoton2 = (Button)findViewById(R.id.eliminar_primero);
    btnBoton2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0)
        {
         personaAdapter.setVisibility();
        }
    });

My adapter :
public class PersonaCustomAdapter  extends ArrayAdapter<Persona> {

    Context context;
    int layoutResourceId;
    ArrayList<Persona> data = new ArrayList<Persona>();
    private PersonaDAO personaDao;
    UserHolder holder;
    int posicion;

    public PersonaCustomAdapter(Context context, int layoutResourceId,ArrayList<Persona> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;

    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View row = convertView;
        holder = null;
        posicion = position;

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
            holder = new UserHolder();
            holder.textName = (TextView) row.findViewById(R.id.textView1);
            holder.btnEdit = (Button) row.findViewById(R.id.boton_eliminame);
            holder.btnEdit.setVisibility(View.INVISIBLE);
            row.setTag(holder);
        } else {
            holder = (UserHolder) row.getTag();
        }
        personaDao = new PersonaDAO(context);
        personaDao.open();

        holder.textName.setText(persona.getNombre_persona());

         holder.btnEdit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if (persona.getId_persona() > 0) {
                    MyActivity hola = new MyActivity();
                    if ( personaDao.eliminarPersona(persona)){
                        data.remove(position);
                        notifyDataSetChanged();
                    } else {
                        System.out.println("No se logro eliminar");
                    }

                }
            }
        });

        return row;
    }
    public void setVisibility()
    {

     // Here is where i getVisibility of my elementos.. is INVISIBLE by Default but
    //only setVisible The lastElement

            if(holder.btnEdit.getVisibility() == View.INVISIBLE){
                holder.btnEdit.setVisibility(View.VISIBLE);
            } else if(holder.btnEdit.getVisibility() == View.VISIBLE){
                holder.btnEdit.setVisibility(View.INVISIBLE);
           }
            notifyDataSetChanged();

        }

    public int getCount() {
        return data.size();
    }

A: Sadd a field like:
public class PersonaCustomAdapter extends ArrayAdapter {
private boolean buttonsVisible = false;
    ...
    public void setButtonsVisible(boolean isVisible) {
        buttonsVisible = isVisible;
    }
    ...
    public View getView(...) {
        ...
        holder.btnEdit.setVisibility(buttonsVisible ? View.VISIBLE : View.INVISIBLE)
        ...
    }
}

now to set your buttons visible call
adapter.setButtonsVisible(true);
adapter.notifyDataSetChanged();

this will cause your ListView to call getView() again for all Views (with the buttonsVisibleFlag now set to true)


text:
Q: How to know if a horizontal scrollerbar is shown in a QPlainTextEdit inherited class? How can i know that whether the scrollbar is displayed in a QPlainTextEdit ?
I tried QScrollBar::isHidden() , but always return true.
Appreciate any of your help !

A: You should try using the isVisible() method on your edit's verticalScrollBar().
This works as expected here:
#include <QtGui>

class Win: public QWidget
{
    Q_OBJECT

    public:
        Win(QWidget *parent=0): QWidget(parent)
        {
            edit = new QPlainTextEdit;
            QPushButton *b1 = new QPushButton("click");
            QVBoxLayout *vl = new QVBoxLayout;
            vl->addWidget(edit);
            vl->addWidget(b1);
            setLayout(vl);
            connect(b1, SIGNAL(clicked()), this, SLOT(clicked()));
        }

    public slots:
        void clicked()
        {
            qDebug() << edit->verticalScrollBar()->isVisible();
        }

    private:
        QPlainTextEdit *edit;
};


text:
Q: wrong version of pygame installed or not installed correctly When I want to run a game I programmed, I get the error message:
ModuleNotFoundError: No module named 'pygame'
I had problems installing pygame on my iMac (OSX Catalina). I have python 3.8.
From the command line I achieved installing pygame with:
pip3 install --user pygame
So what to next:
Check if I have the correct pygame version installed?
Does it matter where I install pygame?
What could be the reason of the error message?
My game worked on my MacBookPro but I had to give it away because of a damage. I remember, that I had to install some different version of pygame (some development version), because I couldn't install the normal one.

A: I could solve the problem now. python3 -m pip install --user --pre pygame=2.0.0-dev6 worked for me.


text:
Q: pickle needs 'write' attribute? My error when using the program:
file must have 'write' attribute

My program:
import pickle

inp = input()

if inp == "in":
    f = open ("txt.txt", 'wb')
    pickle.dump(f, inp)
    f.close()

if inp == "out":
    f = open ("txt.txt", "rb")
    print(pickle.load(f))
    f.close()

Has anyone an idea how to solve this?

A: The pickle.dump function has the following signature:
pickle.dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)

So the file object should be the second argument.
So in your case, you would want:
pickle.dump(inp, f)


text:
Q: Что означает does not implement interface member Скачал игровую платформу -  ссылка

Match Me Kernel (Personal) Match-3 Solution

При загруске в Юнити выдаёт 2 похожие ошибки

Assets/GooglePlayGames/ISocialPlatform/PlayGamesPlatform.cs(41,18): error CS0535: GooglePlayGames.PlayGamesPlatform' does not implement interface memberUnityEngine.SocialPlatforms.ISocialPlatform.Authenticate(UnityEngine.SocialPlatforms.ILocalUser, System.Action)'

К сожалению я не так силён в юнити да и в С#.
помогите понять что означает эта ошибка.
П.С. у меня версия Юнити 5.5.0f3

A: Это значит, что класс PlayGamesPlatform имплементирует какой-то интерфейс, в котором описан метод Authenticate. А раз он описан в интерфейсе, то он должен быть обязательно реализован и в том классе. Однако её (реализации) там (в том классе) почему-то нет.

A: Это довольно известная проблема Unity 5.5.
Как решение можно отредактировать ваш код в соответствии с этим комитом. Но лучше всего будет актуализировать версию Unity до 2017.1+