text:
Q: Apollo File Upload & React Apollo Upload Client, Zero Byte File Hi I am using Node & Apollo in backend, and Apollo Upload Client in React frontend to upload file in server.
Everything is working fine, I am not getting any warning or issue but the problem is,
File which is uploaded on server, it's size is always 0 byte. I don't know what is causing this problem, so I tried by doing simple example of file upload(even this behaves same).
Sharing the simple upload example in github. React content is in Frontend folder & root folder is nodejs backend.
Github Link.
I am also sharing code of simple file upload code right here if some of you don't want github
NodeJS:
const { ApolloServer, gql } = require("apollo-server");
const fs = require("fs");
const path = require("path");

const typeDefs = gql`
    type File {
        url: String!
    }

    type Query {
        hello: String!
    }

    type Mutation {
        uploadFile(file: Upload!): File!
    }
`;

const resolvers = {
    Query: {
        hello: () => "Hello World",
    },
    Mutation: {
        uploadFile: async (parent, { file }) => {
            const { createReadStream, filename, mimetype, encoding } = await file;
            const stream = createReadStream();
            const pathName = path.join(__dirname, `/public/images/${filename}`);
            await stream.pipe(fs.createWriteStream(pathName));

            return {
                url: `http://localhost:4000/images/${filename}`,
            };
        },
    },
};

const server = new ApolloServer({
    typeDefs,
    resolvers,
});

server.listen().then(({ url }) => {
    console.log(` Server ready at ${url}`);
});

React Fileupload
import React from "react";
import logo from "./logo.svg";

import { useMutation, gql } from "@apollo/client";

const UPLOAD_FILE = gql`
    mutation uploadFile($file: Upload!) {
        uploadFile(file: $file) {
            url
        }
    }
`;

const UploadForm = () => {
    const [uploadFile] = useMutation(UPLOAD_FILE, {
        onCompleted: (data) => console.log(data),
    });

    const handleFileChange = (e) => {
        const file = e.target.files[0];
        if (!file) return;
        uploadFile({ variables: { file } });
    };

    return (

Upload File

                <input type="file" onChange={handleFileChange} />

    );
};

export default UploadForm;

Setting up Apollo Upload Client(app.js)
import "./App.css";

import { ApolloClient, ApolloProvider, InMemoryCache } from "@apollo/client";
import { createUploadLink } from "apollo-upload-client";
import UploadForm from "./UploadForm";

const client = new ApolloClient({
    link: createUploadLink({
        uri: "http://localhost:4000/",
    }),
    cache: new InMemoryCache(),
});

function App() {
    return (
        <ApolloProvider client={client}>
            <UploadForm />
        </ApolloProvider>
    );
}

export default App;

A: This took me forever to find a solution when I had the same problem. This is what worked for me for anyone else who comes across this issue in the future.
install this package:
https://www.npmjs.com/package/npm-force-resolutions
into server directory.
Then write this in the package.json
"resolutions": {
    "**/**/fs-capacitor":"3.0.0"
  },

Make sure it is version 3 and not a higher version.
Also if you are using any  filenames that have spaces or numbers in them make sure to change the filename that gets uploaded in the resolver to something else or else the file may become corrupted.


text:
Q: upload with java with node.js server. req.files is empty I'm trying to upload my file to node.js server with javaFX
This code is for node.js server to upload my file.
Simplified my code.
var express = require('express');
var path = require('path');
var logger = require('morgan');
var methodOverride = require('method-override');
var app      = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var argv = require('optimist').argv;
var fs = require('fs');
app.use('/js', express.static(__dirname + '/js'));
app.use(morgan('dev'));
app.use(methodOverride());
app.use(bodyParser({keepExtensions:true,uploadDir:path.join(__dirname,'/files')}));
var busboy = require('connect-busboy');
app.use(busboy());
var fileupload = require('fileupload').createFileUpload('/home/kimmj8409/Myweb_front_end').middleware
app.post('/upload', fileupload, function(req, res) {
    res.send(req.body);
})

app.listen(8080, argv.fe_ip);
console.log("App listening on port 8080");

and It is javacode to connect with this node.js server
MultipartUtility.java
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;

public MultipartUtility(String requestURL, String charset)
        throws IOException {
    this.charset = charset;
    boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    httpConn.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);
    httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
    httpConn.setRequestProperty("Test", "Bonjour");
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
            true);
}

public void addFormField(String name, String value) {
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
            .append(LINE_FEED);
    writer.append("Content-Type: text/plain; charset=" + charset).append(
            LINE_FEED);
    writer.append(LINE_FEED);
    writer.append(value).append(LINE_FEED);
    writer.flush();
}

public void addFilePart(String fieldName, File uploadFile)
        throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append(
            "Content-Disposition: form-data; name=\"" + fieldName
                    + "\"; filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append(
            "Content-Type: "
                    + URLConnection.guessContentTypeFromName(fileName))
            .append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();

    writer.append(LINE_FEED);
    writer.flush();
}

public void addHeaderField(String name, String value) {
    writer.append(name + ": " + value).append(LINE_FEED);
    writer.flush();
}

public List<String> finish() throws IOException {
    List<String> response = new ArrayList<String>();

    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpConn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }

    return response;
}
}

Main code :
private void TCP_File_Client() throws IOException{
    String url = PATH +"/upload";
    String charset = "UTF-8";
    String param = "value";
    File textFile = new File(data_n3_PATH);
    File binaryFile = new File(data_n3_PATH);
    String boundary = Long.toHexString(System.currentTimeMillis());
    String CRLF = "\r\n";
    URLConnection connection = new URL(url).openConnection();
    HttpURLConnection http = (HttpURLConnection) connection;
    http.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

    File uploadFile1 = new File(data_n3_PATH);
    File uploadFile2 = new File(data_n3_PATH);
    String requestURL = PATH +"/upload";

    try {
        MultipartUtility multipart = new MultipartUtility(requestURL, charset);

        multipart.addHeaderField("User-Agent", "CodeJava");
        multipart.addHeaderField("Test-Header", "Header-Value");

        multipart.addFormField("description", "Cool Pictures");
        multipart.addFormField("keywords", "Java,upload,Spring");

        multipart.addFilePart("fileUpload", uploadFile1);
        multipart.addFilePart("fileUpload", uploadFile2);

        List<String> response = multipart.finish();

        System.out.println("SERVER REPLIED:");

        for (String line : response) {
            System.out.println(line);
        }
    } catch (IOException ex) {
        System.err.println(ex);
    }

}

With debugging my code, I found that POST request can go to node.js server, but I can not find file.
req.files is empty and I can not find anything looks like file in req.
and I receive IOException("Server returned non-OK status: " + status); with 500 status
How can I connect these?

A: read https://github.com/expressjs/multer/issues/345.
You can you node.js module multer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Avoid repeating recipient information multiple times while creating DocuSign envelope with composite template I am working with composite template because I need to include multiple templates in the envelope. In all templates, signing roles are same. I have following roles and signing order.

I also have need to provide custom email subject and body for each role, when I create envelope.
Here is my request json to create envelope using composite template. Purposefully left second composite template section empty so that its not too big.
{
    "status": "created",
    "compositeTemplates": [
        {
            "serverTemplates": [
                {
                    "sequence": "1",
                    "templateId": "de231abb-4566-4433-8c10-6fae41d5f36e"
                }
            ],
            "inlineTemplates": [
                {
                    "envelope": {
                        "customFields": {
                            "textCustomFields": [
                                {
                                    "name": "policy",
                                    "value": "12345"
                                }
                            ]
                        }
                    },
                    "sequence": "1",
                    "recipients": {
                        "carbonCopies": [
                            {
                                "recipientId": "1",
                                "email": "email2@domain.com",
                                "name": "Supervisor Name",
                                "roleName": "Supervisor",
                                "routingOrder": "2",
                                "emailNotification": {
                                    "supportedLanguage": "en",
                                    "emailSubject": "Custom email subject for supervisor",
                                    "emailBody": "Custom email body for supervisor"
                                }
                            },
                            {
                                "recipientId": "2",
                                "email": "email1@domain.com",
                                "name": "Admin Name",
                                "roleName": "Admin",
                                "routingOrder": "4",
                                "emailNotification": {
                                    "supportedLanguage": "en",
                                    "emailSubject": "Custom email subject for admin",
                                    "emailBody": "Custom email body for admin"
                                }
                            }
                        ],
                        "signers": [
                            {
                                "recipientId": "3",
                                "email": "email3@domain.com",
                                "name": "Data entry person Name",
                                "roleName": "DataEntry",
                                "routingOrder": "1",
                                "emailNotification": {
                                    "supportedLanguage": "en",
                                    "emailSubject": "Custom email subject for data entry person",
                                    "emailBody": "Custom email body for data entry person"
                                },
                                "tabs": {
                                    "textTabs": [
                                        {
                                            "tabLabel": "field name",
                                            "value": "field value"
                                        }
                                    ]
                                }
                            },
                            {
                                "recipientId": "4",
                                "email": "email4@domain.com",
                                "name": "client Name",
                                "roleName": "Client",
                                "routingOrder": "3",
                                "emailNotification": {
                                    "supportedLanguage": "en",
                                    "emailSubject": "Custom email subject for the client",
                                    "emailBody": "Custom email body for the client"
                                },
                                "tabs": {
                                    "textTabs": [
                                        {
                                            "tabLabel": "other field name",
                                            "value": "other value"
                                        },
                                        {
                                            "tabLabel": "other2 field name",
                                            "value": "other2 value"
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            ]
        },
        {
            "serverTemplates": [
                {
                    "sequence": "1",
                    "templateId": "de231abb-4566-4433-8c10-6fae41d5f36e"
                }
            ],
            "inlineTemplates": [
                {
                    .
                    - repeat same recipient information again
                    .
                }
            ]
        }
    ]
}

When I am preparing envelope create request json, I have to create one CompositeTemplate for each template I need to include. Within compositeTemplates[x]/inlineTemplates[0]/recipients I have specify information (name, email, roleName, routingOrder, email subject, email body and tabs if applicable) for all 4 recipients. I have to repeat same compositeTemplates[x]/inlineTemplates[0]/recipients for with in CompositeTemplate with duplicate information (name, email, roleName, routingOrder, email subject, email body) which sounds not right to me.
Question#1 - Do you know if there is any way to provide recipient at one single place instead of duplicating it under each CompositeTemplate?
My next question is about proving recipient and tab information but from different viewpoint. In Composite template under inlineTemplates I have to use EnvelopeRecipients to specify recipient and it's tabs. In this case I need to know signing authority of each recipient/role because I need to put them under signers, corbonCopy etc. In case of envelope with single template I can easily use templateRole under EnvelopDefinition to specify recipient and their tab information just by role. I don't need to know role's signing authority.
Question#2 – Is there way to specify recipient information by role in CompositeTemplate without knowing signing authority like we can do with single template envelope?

A: Answer # 1
I do not believe so. If this workflow is a common occurrence, you might consider creating a third template containing the documents & tabs of the first two templates.
Then, you could simply send an envelope containing just that third template. In this case, you would only have to specify the recipient's information once.
However, we usually advise the composite templates pattern since it's far easier to customize and scale when your use case changes in the future.
Answer # 2
No. You are mixing two different DocuSign design patterns, i.e you should not mix Composite Template and TemplateRole.
Template Role is needed when you have one server template and you want to prepopulate the signer information and/or any DocuSign tab information present in the template from your application.
What you can do (which I'm sure you've realized) is to retrieve the signing authorities for the templates with a GET /template before making your POST /envelopes containing composite templates.


text:
Q: How to set up proxy in graphql? I have problem with graphql server connection, I think it's proxy problem, but im not sure.
I try to do a search for this,but i can't find my problem.
Here is the error:
{
  "errors": [
    {
      "message": "connect ECONNREFUSED 104.31.87.73:443",
      "locations": [
        {
          "line": 1,
          "column": 2
        }
      ],
      "path": [
        "launches"
      ]
    }
  ],
  "data": {
    "launches": null
  }
}

Server.js:
const express = require("express");
const graphqlHTTP = require("express-graphql");
const schema = require("./schema");
const cors = require("cors");

const app = express();
app.use(cors());
app.use(
  "/graphql",
  graphqlHTTP({
    schema,
    graphiql: true
  })
);

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server started on ${PORT}`));

I try to set up proxy,but it's not working.
Can somebody help me how to set up a proxy in graphql?


text:
Q: How to create a CreatedTime column with differing behaviour I want to add a new createdtime column to a table. But, I want that all the previous entries in the table show '19700101' date while all the new entries from this point forward (i.e. after the new column is introduced) should show the current date by using the getDate()

A: @Roopesh's comments do work just fine:
create table T (ID int not null,Col1 varchar(9) not null)
go
insert into T(ID,Col1) values (1,'abc'),(2,'def')
go
alter table T add CreatedDate date not null constraint DF_tmp default '19700101'
go
alter table T drop constraint DF_tmp
go
alter table T add constraint DF_Permanent
     DEFAULT CURRENT_TIMESTAMP for CreatedDate
go
insert into T(ID,Col1) values (3,'ghi')
go
select * from T

Result is:
ID          Col1      CreatedDate
----------- --------- -----------
1           abc       1970-01-01
2           def       1970-01-01
3           ghi       2014-06-13

This has the advantage that the column doesn't allow NULLs. If you use Mikael's approach, you can make the column non-nullable after you've applied the UPDATE but that's going to require two scans of the table (once to apply the UPDATE, the second time to check for any NULLs when making the column not null).

A: First add a column that has the default value getdate()
alter table YourTable add createddate date default getdate()

The default value is not applied in this step. Every row has null as value for createddate.
Update the value of createddate to 1970-01-01 for all rows.
update YourTable set createddate = '1970-01-01'

A: --Create Table
CREATE TABLE [dbo].[MyTestTable](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
) ON [PRIMARY]

GO

--Put in some data
INSERT INTO [MyTestTable] (Name) VALUES ('Eoin')
INSERT INTO [MyTestTable] (Name) VALUES ('Living Thing')

GO

-- Add a new column datetime with a default value of min date
ALTER TABLE dbo.MyTestTable ADD
    CreatedDate datetime NOT NULL CONSTRAINT DF_MyTestTable_CreatedDate DEFAULT Convert(Datetime, '19700101')
GO

-- Existing Records are now updated to Jan 1970
SELECT * FROM MyTestTable
GO
-- Alter the table again but with a new default
ALTER TABLE dbo.MyTestTable
    DROP CONSTRAINT DF_MyTestTable_CreatedDate
GO
ALTER TABLE dbo.MyTestTable ADD CONSTRAINT
    DF_MyTestTable_CreatedDate DEFAULT getdate() FOR CreatedDate
GO

--Put in some more data.

INSERT INTO [MyTestTable] (Name) VALUES ('John')

GO

-- newer Records are now updated to current date
SELECT * FROM MyTestTable
GO


text:
Q: How to configure Solr Custom Query Parser? I am configuring Solr on cloud mode, and want to configure a Custom Query Parser.
to configure it I am using a PowerShell Script as follows.
# Variables ###########
$hostName = 'localhost'
$port = 8983
$numberOfShards = 1
$replicationFactor = 1

# These should be picked from an external file
$collections = 'Collection1', 'Collection2', 'Collection3', 'Collection4', 'Collection5', 'Collection6', 'Collection7', 'Collection8', 'Collection9';
#######################

# Following 3 commands needs file system access and can be extracted out of this script in case we want to use already hosted Solr instance on cloud
# Start Solr in Cloud Mode
'####### Starting Solr #######';
..\bin\solr start -c -h $hostName -p $port "-Denable.runtime.lib=true"

# Upload configuration to ZooKeeper
# We need to upload multiple copies of the configuration to the ZooKeeper one for each collection, so each collection can have it's different schema
$zooKeeperPort = $port + 1000;
foreach ($c in $collections) {
    $configName = $c + 'SearchConfig';
    '####### Uploading Config to ZooKeeper for collection {0} #######' -f $c;
    $configPath = './xuber_basic_config/conf/';
    ..\server\scripts\cloud-scripts\zkcli.bat -zkhost localhost:$zooKeeperPort -cmd upconfig -confdir $configPath -confname $configName;
}

$urlPrefix = 'http://' + $hostName + ':' + $port + '/solr';

function PostToSolr
{
   'HTTP POST: {0}' -f $args[0];
   Invoke-WebRequest -uri $args[0] -Method POST -ContentType "application/json" -Body $args[1];
}

function GetToSolr
{
    'HTTP GET: {0}' -f $args[0];
    Invoke-WebRequest -uri $args[0] -Method GET -ContentType "application/json";
}

function PostSchema
{
    $schemaFileName = $args[0];
    $url = $args[1];
    $jsonToPost = Get-Content ./$schemaFileName;
    PostToSolr $url $jsonToPost;
}

# Get a list of collections already present in Solr
$readCollectionUrl = $urlPrefix + '/admin/collections?action=LIST&wt=json';
$alreadyExistingCollections = ((GetToSolr $readCollectionUrl).Content | ConvertFrom-Json).collections;

# Create .system collection
$systemCollectionName = '.system';
If ($alreadyExistingCollections -contains $systemCollectionName) {
    $deleteCollectionUrl = $urlPrefix + '/admin/collections?action=DELETE&name={0}' -f $systemCollectionName;
    GetToSolr $deleteCollectionUrl;
}

$addSystemCollectionPath =  $urlPrefix + '/admin/collections?action=CREATE&name=' + $systemCollectionName;
GetToSolr $addSystemCollectionPath;

$dataSecurityPlugin = 'customQueryPlugin';
$addBlobPath = $urlPrefix + '/'+ $systemCollectionName + '/blob/' + $dataSecurityPlugin;
'HTTP POST: {0}' -f $addBlobPath;
Invoke-WebRequest -uri $addBlobPath -Method Post -InFile .\customQueryPlugin.jar -ContentType application/octet-stream;

$createCollectionPrefix = $urlPrefix + '/admin/collections?action=CREATE&name={0}&numShards={1}&replicationFactor={2}&collection.configName={3}';
$schemaApiUrlPrefix = $urlPrefix + '/{0}/schema';

# Create Solr Collections
foreach ($c in $collections) {
    # Check to see if the collection already exists, if yes, delete it.
    If ($alreadyExistingCollections -contains $c) {
        '####### Collection {0} already present hence deleting it #######' -f $c
        $deleteCollectionUrl = $urlPrefix + '/admin/collections?action=DELETE&name={0}' -f $c;
        GetToSolr $deleteCollectionUrl;
    }

    '####### Creating collection {0} #######' -f $c;
    $configName = $c + 'SearchConfig';
    $tempPath = $createCollectionPrefix -f $c,$numberOfShards,$replicationFactor,$configName;
    GetToSolr $tempPath;

    # Add data security plugin to runtime
    $addToRuntimePath = $urlPrefix + '/'+ $c + '/config';
    $runtimeJsonData = @{"add-runtimelib" = @{name = "customQueryPlugin"; version = 1}} | ConvertTo-Json;
    $runtimeJsonData;
    PostToSolr $addToRuntimePath $runtimeJsonData;

    $schemaAddUrl = $schemaApiUrlPrefix -f $c;
    # Push the common Schema
    '####### Adding common schema for collection {0} #######' -f $c;
    $schemaFileName = 'Common_Schema.json';
    PostSchema $schemaFileName $schemaAddUrl;

    # Push the Schema specific to the collection
    '####### Adding specific schema for collection {0} #######' -f $c;
    $schemaFileName = $c + '_Schema.json';
    PostSchema $schemaFileName $schemaAddUrl;

    # Register QueryParser
    $addQueryParserPath = $addToRuntimePath;
    $addQueryParserData = @{"create-queryparser" = @{name = "acl"; runtimeLib = $true; class = "customQueryPlugin.customSearchQueryParser"}} | ConvertTo-Json;
    PostToSolr $addQueryParserPath $addQueryParserData;
}

I am using edismax, and able to search my data without filter Query
but with filter query it's not giving any data, Can you tell if I am missing something ??

A: I think the clue is in the last lines of your script:
$addQueryParserData = @{"create-queryparser" = @{name = "acl"; runtimeLib = $true; class = "customQueryPlugin.customSearchQueryParser"}} | ConvertTo-Json;

Are you sure you have $true variable: runtimeLib = $true? I bet it should be rather runtimeLib = true.
Also noteworthy is the name of your Query Parser class: class = "customQueryPlugin.customSearchQueryParser".  Please make sure your customQueryPlugin.jar does have it inside as a fully qualified name.


text:
Q: Uniform convergence of Fourier Series I am currently studying Fourier Analysis on my own. In the Notes I use the following comment is made, which I unfortunately don't understand:
Given that we know the series
$f(x) = \sum c_k e^{ikx}$
converges pointwise (where the $c_k$ are the Fourier coefficients and $f$ is a periodic function), to show uniform convergence it is enough to show that
$
\sum |c_k| < \infty
$
I tried to find the result regarding uniform convergence that this comment refers to but so far I wasn't successful.
Could somebody help me and give a hint as to why this is true ? Many thanks!

A: This is just an application of the Weierstrass M-test.
It's a rather simple result, and it is edifying to prove the uniform convergence of your series  directly:
Let $m> n$, then
$$
\biggl| \sum_{j=1}^m c_j e^{ijx}  - \sum_{j=1}^n c_j e^{ijx} \biggr|
=\biggl| \sum_{j=n+1}^m c_j e^{ijx}   \biggr|
\le \sum_{j=n+1}^m |c_j e^{ijx} |=  \sum_{j=n+1}^m |c_j   |.
$$
Since $\sum\limits_{j=1}^\infty |c_j|<\infty$, we can make the right hand side of the above as small as we wish provided $n$ is sufficiently large. Thus, we can make the left hand side as small as we wish, independently of  $x$, as long as $n$ is sufficiently large.
It follows that $ \sum\limits_{j=1}^\infty c_j e^{ijx} $ is uniformly Cauchy, and, thus, uniformly convergent.


text:
Q: configure magento database connection to connect to other PC on same LAN (team members work in one database) how to

configure magento  database connection

to connect to other PC on same LAN (team members work in one database which on PC in our LAN )
i'm new to magento and i searched for that but nothing lead me

A: You can look into your local.xml file, this should be under app/etc/local.xml. This will have your database connection information. When setting up a db connection you can specify a lot of information but I guess the really important part for you will be the host node.
If you have already installed Magento on your local machine then you could update this file. If not then you should be able to setup your database connection via the setup configuration.


text:
Q: implementar gradiente en Vue Native he intentado implementar una gradiente de color en Vue Native, pero sin éxito. Intenté utilizando LinearGradient desde expo-linear-gradient, pero sin resultado. Tampoco me resulta haciéndolo en css con:
 background-color: linearGradient(to bottom, red, blue)

¿Cuál es la manera correcta para hacerlo?.


text:
Q: Showing there exists no Division algebra on $\mathbb R^3$ indirectly (Sort of...) Before you read my question please consider that i HAVE to do this exercise as i did below.
So i am showing there exists no division algebra on $\mathbb R^3$.
To show that,  i have to show that for $*: \mathbb R^3 \times \mathbb R^3 \to \mathbb R^3$ it exists $0 \ne x,y \in \mathbb R^3$ with $x*y = 0$ $(1)$
I first showed that there exists a linear matrix $A(x) \in \mathbb R^{3 \times 3}$ with $A: x \to A(x)$.
Then i did show that $det(A(x)) = 0$  for some $x \in \mathbb R^3 \setminus \{0\}$
At last i defined $L_x:\mathbb R^3 \to \mathbb R^3, y \to x*y$ and i showed it is linear and it satisfies $L_x(y) = A(x).y$.
Now to my problem:
I have to use what i did here and the fact that a Matrix $A$ is invertible if $Ay \ne 0$ for all $y \in  \mathbb R^3 \setminus \{0\}$.
How and Why follows $(1)$ from what i did here.
I am unable to make a connection between what i did and what i shall show ( maybe because i am still newbie ).


text:
Q: apache user and permissions for document roots I think this is not too specific, in fact I think it's a very common problem. But I didn't find any threads giving a solution to the following.
I want to run website1 and website2 on a server.
Each virtual host has its own Document in /var/www/website1/web/ and /var/www/website2/web/
Permissions are set like this: rwx rwx r-x
Owner of both folders is: somedeveloperuser
Group of both folders is: www-data
I want PHP scripts in /var/www/website1/web/ to have write access to /var/www/website1/web/
EDITED:
What could be a good practice to forbid a script in /var/www/website1/web/ write access to /var/www/website2/web/ or any other folder grouped by www-data?
I am asking because I don't want any site, which could be in some way insecure to harm other website folders.
Thank you for reading and helping!


text:
Q: Pyrometer device compatible with arduino I am an undergraduate Mechanical Engineer and currently I am using a laser which heats and melts a surface of any material (plastic, metal etc) which is formed in powder. Although, I have managed to melt some plastic's powder, I want to put more accuracy in the control system of the laser with the temperature of the surface which is being heated.
To be more specific, I want to measure, relatively accurately, the heated material's temperature and when the temperature reaches the melting point I want the laser to be turned off. I googled about the thermal radiation effect and I found about the pyrometer device. I would like to ask if there is a pyrometer which is compatible with Arduino/Tiva microprocessor with a normal range of temperatures. I found some pyrometers/contactless thermometers that can measure up to 380 degrees Celsius which is not enough since the melting point of aluminum is 660 degrees (I want to use later aluminum).
Any suggestions?
Thank you for your time and for your answer in advance,
Chris
EDIT (after Jonk's suggestion):
Chamber:
The chamber currently is in room conditions (20-25 degrees of Celsius) as I just finished building it but I was thinking of inserting an inert gas later to prevent oxidization of the product (in room temperature).
Laser:
The laser is a YLIA M20 with a wavelength of 1064nm and the diameter of the beam is around 1mm. I use it at the maximum power at 20W. I want to measure the temperature of the area that the beam heats (local measurement). The laser distance between the laser and the surface is not fixed but after some experiments I made I calculated that it would be best around 100mm.
Budget:
The budget is around 500-1000 euros. If my idea for the pyrometer works and is a good solution it could be higher (1500-2000 euros).
Material:
The materials are formed in thin powder and supposed to be of any kind (plastic, metal, ceramic, glass). I cannot tell you with certainty the exact types yet because I don't know in what range I am going to use the machine I am going to build, but for a start I want to be able to measure 700 degrees of Celsius. The minimum emisivity could be at 0.5 since I don't use polished materials.
Microcontroller:
The laser's position is controlled by two motors (X and Y axis) via Arduino boards. The Z-axis of the laser is controlled through the movement of the base that hold the powder (the height of the laser in regard to the ground is fixed). The Z-axis' motor is also controlled with an Arduino board. The Arduino boards are then connected via an electronic system with a pmac board, which I use to write G code to control the movements of the laser. This whole set-up has been implemented and it works. So what I want is a control system that can also get feedback from the heated points (so for example if the melting is correct the laser can move from point to point). The microprocessor board compatibility with a non-contact thermometer is a must so I can use it in the system that I already have created.
In case I missed again something, please tell me to include it in my question.

A: The easiest way to go about solving this is to have information about the material to be melted pre-loaded within Arduino code so that you can calculate exactly when to shut the laser off by also knowing the specifications of the laser. In other words, if you know how the thermal characteristics of the laser from the datasheet, you can use thermodynamics equations to calculate precisely how much time the laser needs to be turned on. The equations can be implemented within Arduino code and can directly turn the laser on and off. Again, I suggest creating a class within your code to organize the different materials that you will be melting so that all of the important parameters are included. Finally, create an interface for the user to input the type of material to be melted so that the systems knows exactly which formulas to use within code and control the laser's operation.


text:
Q: error de Jest has detected the following 1 open handle potentially keeping Jest from exiting: estoy ejectuando una pruebas end-to-end con supertest jest en strapi y la instancia del servidor no funciona todas las rutas lanzan un 404 y no se porque.
tengo configurado todo a como dicta la documentacion de strapi v3
y me lanza esto:
Jest has detected the following 1 open handle potentially keeping Jest from exiting:

  ●  onerror

      18 |   it('deberia retornar un codigo de estado 200', async () => {
      19 |     const resp = await supertest(app.server) // app server is and instance of Class: http.Server
    > 20 |       .get('/unidads')
         |        ^
      21 |       .set('Authorization', `Bearer ${mockToken}`)
      22 |
      23 |     expect(resp.status).toEqual(202)


text:
Q: Fading elements in / out with animations based on the current state I have an element that I want to show/hide based on a boolean state, but I also want it to do it using transitions. Check the following example:

const App = () => {
  const [visible, setVisible] = React.useState(false)
    return (

            <button onClick={() => {setVisible(!visible)}}> Show/HIde </button>

 I'm a div

    );
}

ReactDOM.render(
    <App />,
    document.getElementById("root")
);
.hidden,
.visible {
    border: 2px solid black;
    display: inline;
}

.hidden {
    animation-name: fadeInOpacity;
    animation-duration: 1s;
    opacity: 0;
  height: 0px;
  overflow: hidden;
  width: 0px;
}
.visible {
    opacity: 1;
    animation-name: fadeOutOpacity;
    animation-duration: 1s;
}

@keyframes fadeOutOpacity {
    0% {
        opacity: 0;
        scale: 0.8;
    }
    100% {
        opacity: 1;
        scale: 1;
    }
}

@keyframes fadeInOpacity {
    0% {
        opacity: 1;
        scale: 1;
    }
    100% {
        opacity: 0;
        scale: 0.8;
    }
}

I have a few problems with it: it appears on the page load/refresh and then does the animation. Also, when it's invisible, the div still exists. It only has opacity set to zero. So there is a potential risk of it interacting with other elements. For example, when you hover over the space next to the button, the cursor changes because it hovers over the text, even though it's invisible.
Ideally, I want it to disappear entirely or move off the screen. The element will have a position: fixed in my project.
What is the best practice for dealing with a scenario like this? Can I have a snippet, please?

A: I managed to fix it with the following code:

const App = () => {
  const [visible, setVisible] = React.useState(false);
  const divRef = React.useRef(false);

  React.useLayoutEffect(() => {
    divRef.current.className = 'hidden-did-fade-out';
  }, []);

  function onAnimationEnd(e) {
    if (e.animationName === 'fadeOutOpacity') {
      e.target.className = 'hidden-did-fade-out';
    }
  }

  return (

      <button
        onClick={() => {
          setVisible(!visible);
        }}
      >
        Show/HIde
      </button>

        I'm a div

  );
};

ReactDOM.render(<App />, document.getElementById('root'));
.hidden,
.visible {
  border: 2px solid black;
  display: flex;
  visibility: visible;
}

.hidden {
  animation-name: fadeOutOpacity;
  animation-duration: 1s;
  opacity: 0;
}

.hidden-did-fade-out {
  display: none;
}

.visible {
  animation-name: fadeInOpacity;
  animation-duration: 1s;
  opacity: 1;
}

@keyframes fadeInOpacity {
  0% {
    opacity: 0;
    scale: 0.8;
  }
  100% {
    opacity: 1;
    scale: 1;
  }
}

@keyframes fadeOutOpacity {
  0% {
    opacity: 1;
    scale: 1;
  }
  100% {
    opacity: 0;
    scale: 0.8;
  }
}


text:
Q: How to remove both duplicate values in an array of objects I have following code for remove duplicate record. It shows me unique values and removes the last duplicate record. However, what I want is, if two passports are the same, remove both elements from the array.
Example

var array = [{
    "PassportNo": "abced",
    "Name": "John"
  },
  {
    "PassportNo": "abcederrr",
    "Name": "Johnss",

  },
  {
    "PassportNo": "abced",
    "Name": "John"

  }
];

function removeDuplicates(originalArray, objKey) {
  var trimmedArray = [];
  var values = [];
  var value;

  for (var i = 0; i < originalArray.length; i++) {
    value = originalArray[i][objKey];

    if (values.indexOf(value) === -1) {
      trimmedArray.push(originalArray[i]);
      values.push(value);
    }
  }
  return trimmedArray;
}

var noDuplicates = removeDuplicates(array, 'PassportNo');
console.log(noDuplicates);
/*
[
  {
    "PassportNo": "abced",
    "Name": "John"
  },
  {
    "PassportNo": "abcederrr",
    "Name": "Johnss"
  }
]
*/

I want like this (remove both values):
[{
  "PassportNo": "abcederrr",
  "Name": "Johnss"
}]

A: You can do this with a simple filter after storing counts in a separate object (i.e. only choose passports that have count 1).

var array = [{
    "PassportNo": "abced",
    "Name": "John"
  },
  {
    "PassportNo": "abcederrr",
    "Name": "Johnss",
  },
  {
    "PassportNo": "abced",
    "Name": "John"
  }
];

var passportCounts = array.reduce((map, curr) => {
  if (curr.PassportNo in map) map[curr.PassportNo] += 1;
  else map[curr.PassportNo] = 1;
  return map;
}, {});

console.log(array.filter(p => passportCounts[p.PassportNo] === 1));


text:
Q: How duplicate a duplicated row in jQuery? How duplicate a duplicated row using jQuery?
$("tr").click(function(){
    var thIndex = $(this).index() + 1;
    var teste = "";
    var i = 0;
    var $tableBody = $('#tbl_id').find("tbody"),
            $trSelected = $tableBody.find("tr:nth-child("+ thIndex +")"),
        $trLast = $tableBody.find("tr:last"),
        $trNew = $trSelected.clone();
        console.log($trSelected);
        $trLast.after($trNew);
    });

http://jsfiddle.net/2qgzx85o/

A: try $('body').on('click', 'tr', function()...
The way you're doing it now, it only applies to existing rows.
http://jsfiddle.net/2qgzx85o/3/

A: If the problem is with allowing the new rows to be clicked, then you should pass true to the .clone method.
.clone( [withDataAndEvents ])

withDataAndEvents (default: false)
Type: Boolean
  A Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4, element data will be copied as well.


text:
Q: python requests, I got different response status than postman's result. requests: 2.19.1
python: 3.6
url(It's just url, There's no special meaning): http://moneycake.tistory.com/43
Python code(actually, pycharm django code):
try:
    r = requests.head('http://moneycake.tistory.com/43', allow_redirects=False)
    print(r.status_code)
except requests.exceptions.RequestException as e:
    pass

It returns >>> 403
But when I do this on Postman with method GET and default settings,
It returns 200 OK.
Why this happen?
And How can I get 200 OK status response on pycharm?

A: You need to set the User-Agent:
import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
}

try:
    r = requests.head('http://moneycake.tistory.com/43', allow_redirects=False, headers=headers)
    print(r.status_code)
except requests.exceptions.RequestException as e:
    pass

Output
200


text:
Q: Doctrine and left join I'm re-coding an old web app with Symfony 3 and I have to deal with Doctrine (not the fun part for me :/)
I'm trying to get a file from a table with the rights in another table :

*

*un right per file per user (unique index to be sure)

*a file can have multiple user rights

Here's the query for MySQL (very basic I must say)
SELECT f.*, fr.access_type FROM files f
LEFT JOIN file_rights fr ON (fr.file_id = f.id AND fr.user_id = 2)
WHERE f.code = "xxxx"

So to do that with doctrine, I have my 2 entities "File" and "FileRights"
The goal was to do this in my controller :
$file = $em->getRepository('AppBundle:File')->getFile($code, $this->getUser());

if (!is_null($file) && !is_null($file->getRights()) {
    dump($file->getRights()->getAccessType());
}

and the repository looks like this :
public function getFile($code, $user) {
    return $this->createQueryBuilder('f')
        ->select('f, fr')
        ->leftJoin('f.rights', 'fr', Expr\Join::WITH, 'fr.user = :userId')
        ->where('f.code = :code')
        ->setParameter('userId', $user)
        ->setParameter('code', $code)
        ->getQuery()
        ->getOneOrNullResult();
}

but I dont know what to put in the entities ... I tried something like this but doesn't work ...
File.php
class File
{
    /**
     * @var int
     *
     * @ORM\Id
     * @ORM\Column(name="id", type="integer", options={"unsigned"=true})
     */
     private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="code", type="string", unique=true, length=20)
     */
     private $code;

     ...

     /**
      * @var \AppBundle\Entity\FileRights
      *
      * @ORM\OneToMany(targetEntity="AppBundle\Entity\FileRights", mappedBy="file")
      */
      private $rights;

FileRights.php
class FileRights
{
     ...

     /**
      * @var \AppBundle\Entity\File
      *
      * @ORM\ManyToOne(targetEntity="AppBundle\Entity\File")
      * @ORM\Column(name="file_id", type="string", length=20)
      */
      private $file;

but i have this error :

Notice: Undefined index: file

Could you help me with this very simple case ?
Thanks

A: Nice one ! There was 2 mistakes in the FileRights entity. It should have been :
/**
  * @var \AppBundle\Entity\File
  *
  * @ORM\ManyToOne(targetEntity="AppBundle\Entity\File", inversedBy="rights")
  * @ORM\JoinColumn(name="file_id", referencedColumnName="id")
  */
  private $file;

and in the controller :
if (!is_null($file) && !is_null($file->getRights()) {
    dump($file->getRights()[0]->getAccessType());
}

Thanks for the help :)


text:
Q: SED: insert text after the last line? This sed command inserts a tag to the beginning of a file:
sed -i "1s/^/<?php /" file

How can I insert something to the end of each file with sed?

A: See your original post for the all-in-one sed command.
find . -type f -exec sed -i -e "1s/^/<?php /" -e "\$s/\$/ ?>/" {} \;

A: Use sed 'append (a)' command. For example, to append two lines at the end of file:
sed -i -e '$a\
foo1 bar1\
foo2 bar2' file

A: The equivalent of your sed -i '1s/^/<start</' file would be:
sed -i '$s/$/>end>/' file

That will add the text >end> to the last line (without newlines) of the file. Of course, in this case (as in your example also) it needs that the file contains at least one line (not empty).
Using double quotes (as in the selected answer) is not a good idea as then the shell will try to process each $ in the string. The command will convert to:
sed -i "\$s/\$/>end>/" file

Using a (append, end) or i (insert, start) will also insert a newline, demand different calls in BSD and GNU and still need a non-empty file.
For GNU:
$ sed '1i<start<' file
$ sed '$a>end>' file

For BSD:
$ sed '1i\
<start<' file
$ sed '$a\
>end>' file

Or, in shells that allow it (C-string):
$ sed $'1i\\\n<start<' file
$ sed $'$a\\\n>end>' file

Of course, nothing is simpler than:
echo '>end>' >> file

which works with empty files as well.

A: No need to use sed in that case. How about
echo "<?php" >> file

A: Assuming you want to put the ending php tag to the files, then
sed -i '$s/$/\n?>/' file

should do the trick

A: In a simple way to write and make the changes in the contents at a specific line in a file .
If you want to insert anything at a specific line number then below command can be used:
sed -i '2i i have started' sheikh.log

where 2i - line number 2 and i stands for inserting . If you have to insert at the last line then use $ in place of 2 .
i have started - text to be inserted and sheikh.log is the filename .
We can also make the changes in the line by using the below command
sed -i '2c we have started' sheikh.log

i is changed to we .

A: The simplest way is:

sed -i -e '$aTEXTTOEND' filename

How it works
$ matches the last line (it's a normal sed address; 4aTEXTTOEND would insert after the fourth line), a is the append command, and TEXTTOEND is what to append, filename is the file where the TEXTTOEND will be inserted

A: First and Last
I would assume that anyone who searched for how to insert/append text to the beginning/end of a file probably also needs to know how to do the other also.
cal |                            \
  gsed -E                        \
       -e     '1i\{'             \
       -e     '1i\  "lines": ['  \
       -e 's/(.*)/    "\1",/'    \
       -e '$s/,$//'              \
       -e     '$a\  ]'           \
       -e     '$a\}'

Explanation
This is cal output piped to GNU sed (called gsed on macOS installed via brew.sh, and simply sed on GNU installations) with extended RegEx (-E) and 6 "scripts" applied (-e) and line breaks escaped with \ for readability.

*

*Scripts 1 & 2 use 1i\ to "at line 1, insert".

*Scripts 5 & 6 use $a\ to "at line <last>, append". I vertically aligned the text outputs to make the code represent what is expected in the result.

*Scripts 3 & 4 do substitutions (the latter applying only to "line <last>").

The result is converting command output to valid JSON.
Output
{
  "lines": [
    "    October 2019      ",
    "Su Mo Tu We Th Fr Sa  ",
    "       1  2  3  4  5  ",
    " 6  7  8  9 10 11 12  ",
    "13 14 15 16 17 18 19  ",
    "20 21 22 23 24 25 26  ",
    "27 28 29 30 31        ",
    "                      "
  ]
}


text:
Q: A basic question on irreducible periodic markov chain For an irreducible periodic (period $2$) Markov Chain I know that both of the following two quantities are same and equal to $\pi(i)$:
$$ \lim_{n\to \infty} \frac{1}{2}(p_n(j,i) + p_{n+1}(j,i))$$
$$ \lim_{n \to \infty} \frac{1}{2}(\phi P^{n+1} + \phi P^{n+2})_i$$
where $\phi$ is the initial distribution.
But, I could not understand the meaning of the above two quantities.

A: The first expression is a special case of the second.  Both represent the fraction of the time the system spends in state $i$ in the long run, the second when there is an arbitrary initial distribution, the first when the system starts in a particular state, $j.$
If a finite chain is irreducible and aperiodic, then the probability it is found in state $i$ after $n$ transitions approaches $\pi(i)$ as $n$ gets large, for any choice of initial distribution.
If the finite chain is irreducible and periodic, then the large $n$ limit of $p_n(j,i)$ does not exist.  Nevertheless, you can still say that, in the long term, the fraction of the time the system spends in state $i$ is $\pi(i)$.
If the chain has period $2,$ the set of states can be partitioned into two parts, $A$ and $B,$ such that the probability of a single-step transition from a state in $A$ to a state in $A$ or from a state in $B$ to a state in $B$ is $0.$  The transition matrix can therefore be written
$$
P=\begin{bmatrix}0 & R\\ S & 0\end{bmatrix},
$$
where $R$ contains the probabilities of a transition from a state in $A$ to a state in $B,$ and $S$ contains the probabilities of a transition from a state in $B$ to a state in $A.$  Then $p_{2n}(j,i)=0$ if $j$ and $i$ are in different parts and $p_{2n+1}(j,i)=0$ if $j$ and $i$ are in the same part.  Since
$$
P^2=\begin{bmatrix}RS & 0\\ 0 & SR\end{bmatrix},
$$
the chain $P^2$ is reducible.  The chains $(RS)$ and $(SR)$ do have steady-state probabilities; if $j$ and $i$ are in the same part, then $p_{2n}(j,i)$ tends toward the steady-state value for state $i;$ if $j$ and $i$ are in different parts, then $p_{2n+1}(j,i)$ tends toward the same steady-state value.
So in the expression
$$\frac{1}{2}\left(p_n(j,i)+p_{n+1}(j,i)\right),
$$
one of the terms will be $0$ and the other will tend toward a steady-state value.  Hence the expression tends toward half the steady-state value, reflecting the fact that half the time, it is impossible for the system to be in state $i,$ and half the time, the probability the system will be in state $i$ is approaching the steady-state value.
The situation is similar when there's an initial distribution $\phi.$  Let $a$ be the sum of the elements of $\phi$ corresponding to states in $A,$ and let $b$ be defined similarly for states in $B.$  So $a+b=1;$ $a$ and $b$ represent the probabilities the system is initially in a state of $A$ or a state of $B.$  Then the $i^\text{th}$ component of $\phi P_{2n}$ will approach $a$ times the steady-state value for state $i$ if $i\in A,$ and $b$ times the steady-state value for state $i$ if $i\in B.$  Likewise, the $i^\text{th}$ component of $\phi P_{2n+1}$ will approach $b$ times the steady-state value for state $i$ if $i\in A,$ and $a$ times the steady-state value for state $i$ if $i\in B.$  Your second expression contains the average of these probabilities, which makes sense, since each applies half the time.  Again, the limiting value is half the steady state value for state $i.$


text:
Q: Maven Metadata Plugin unable to get the maven-metadata.xml due to java.net.UnknownHostException I have been trying to configure a Jenkins Job for the deployment task of Java artifacts. I want the user to be able to select the artifact version to be deployed which are stored in Nexus repository. For this I'm using the Maven Metadata Plugin to get the list of artifact versions from the repository.
The problem is, Jenkins server is unable to resolve the Repository Base URL (https://nexus.repos.prod.com/nexus/content/groups/prod-pds-releases-all) due to
java.net.UnknownHostException
Below is the stack trace:
01-Jul-2015 15:45:34.460 WARNING [Handling GET /jenkins/job/Prod_PDS_Deploy/build from 10.11.131.69 : http-nio-9091-exec-9 ParametersDefinitionProperty/index.jelly MavenMetadataParameterDefinition/index.jelly] null.null Could not parse maven-metadata.xml
 java.net.UnknownHostException: nexus.repos.prod.com
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:589)
        at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:656)
        at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
        at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
        at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:275)
        at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:371)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
        at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1104)
        at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:998)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1512)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
        at eu.markov.jenkins.plugin.mvnmeta.MavenMetadataParameterDefinition.getArtifactMetadata(MavenMetadataParameterDefinition.java:196)
        at eu.markov.jenkins.plugin.mvnmeta.MavenMetadataParameterDefinition.getVersions(MavenMetadataParameterDefinition.java:187)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.apache.commons.jexl.util.PropertyExecutor.execute(PropertyExecutor.java:125)
        at org.apache.commons.jexl.util.introspection.UberspectImpl$VelGetterImpl.invoke(UberspectImpl.java:314)
        at org.apache.commons.jexl.parser.ASTArrayAccess.evaluateExpr(ASTArrayAccess.java:185)
        at org.apache.commons.jexl.parser.ASTIdentifier.execute(ASTIdentifier.java:75)
        at org.apache.commons.jexl.parser.ASTReference.execute(ASTReference.java:83)
        at org.apache.commons.jexl.parser.ASTReference.value(ASTReference.java:57)
        at org.apache.commons.jexl.parser.ASTReferenceExpression.value(ASTReferenceExpression.java:51)
        at org.apache.commons.jexl.ExpressionImpl.evaluate(ExpressionImpl.java:80)
        at hudson.ExpressionFactory2$JexlExpression.evaluate(ExpressionFactory2.java:74)
        at org.apache.commons.jelly.expression.ExpressionSupport.evaluateRecurse(ExpressionSupport.java:61)
        at org.apache.commons.jelly.expression.ExpressionSupport.evaluateAsIterator(ExpressionSupport.java:94)
        at org.apache.commons.jelly.tags.core.ForEachTag.doTag(ForEachTag.java:89)
        at org.apache.commons.jelly.impl.TagScript.run(TagScript.java:269)
        at org.kohsuke.stapler.jelly.ReallyStaticTagLibrary$1.run(ReallyStaticTagLibrary.java:99)
        at org.apache.commons.jelly.TagSupport.invokeBody(TagSupport.java:161)
        at org.apache.commons.jelly.tags.core.OtherwiseTag.doTag(OtherwiseTag.java:41)
        at org.apache.commons.jelly.impl.TagScript.run(TagScript.java:269)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.apache.commons.jelly.TagSupport.invokeBody(TagSupport.java:161)
        at org.apache.commons.jelly.tags.core.ChooseTag.doTag(ChooseTag.java:38)
        at org.apache.commons.jelly.impl.TagScript.run(TagScript.java:269)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.kohsuke.stapler.jelly.ReallyStaticTagLibrary$1.run(ReallyStaticTagLibrary.java:99)
        at org.kohsuke.stapler.jelly.CallTagLibScript$1.run(CallTagLibScript.java:99)
        at org.apache.commons.jelly.tags.define.InvokeBodyTag.doTag(InvokeBodyTag.java:91)
        at org.apache.commons.jelly.impl.TagScript.run(TagScript.java:269)
        at org.kohsuke.stapler.jelly.ReallyStaticTagLibrary$1.run(ReallyStaticTagLibrary.java:99)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.kohsuke.stapler.jelly.ReallyStaticTagLibrary$1.run(ReallyStaticTagLibrary.java:99)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.apache.commons.jelly.tags.core.CoreTagLibrary$2.run(CoreTagLibrary.java:105)
        at org.kohsuke.stapler.jelly.CallTagLibScript.run(CallTagLibScript.java:120)
        at org.apache.commons.jelly.tags.core.CoreTagLibrary$2.run(CoreTagLibrary.java:105)
        at org.kohsuke.stapler.jelly.JellyViewScript.run(JellyViewScript.java:95)
        at org.kohsuke.stapler.jelly.IncludeTag.doTag(IncludeTag.java:147)
        at org.apache.commons.jelly.impl.TagScript.run(TagScript.java:269)
        at org.kohsuke.stapler.jelly.ReallyStaticTagLibrary$1.run(ReallyStaticTagLibrary.java:99)
        at org.apache.commons.jelly.TagSupport.invokeBody(TagSupport.java:161)
        at org.apache.commons.jelly.tags.core.ForEachTag.doTag(ForEachTag.java:150)
        at org.apache.commons.jelly.impl.TagScript.run(TagScript.java:269)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.kohsuke.stapler.jelly.CallTagLibScript$1.run(CallTagLibScript.java:99)
        at org.apache.commons.jelly.tags.define.InvokeBodyTag.doTag(InvokeBodyTag.java:91)
        at org.apache.commons.jelly.impl.TagScript.run(TagScript.java:269)
        at org.kohsuke.stapler.jelly.ReallyStaticTagLibrary$1.run(ReallyStaticTagLibrary.java:99)
        at org.kohsuke.stapler.jelly.ReallyStaticTagLibrary$1.run(ReallyStaticTagLibrary.java:99)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.apache.commons.jelly.tags.core.CoreTagLibrary$2.run(CoreTagLibrary.java:105)
        at org.kohsuke.stapler.jelly.CallTagLibScript.run(CallTagLibScript.java:120)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.kohsuke.stapler.jelly.CallTagLibScript$1.run(CallTagLibScript.java:99)
        at org.apache.commons.jelly.tags.define.InvokeBodyTag.doTag(InvokeBodyTag.java:91)
        at org.apache.commons.jelly.impl.TagScript.run(TagScript.java:269)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.apache.commons.jelly.tags.core.CoreTagLibrary$1.run(CoreTagLibrary.java:98)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.apache.commons.jelly.tags.core.CoreTagLibrary$2.run(CoreTagLibrary.java:105)
        at org.kohsuke.stapler.jelly.CallTagLibScript.run(CallTagLibScript.java:120)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.kohsuke.stapler.jelly.CallTagLibScript$1.run(CallTagLibScript.java:99)
        at org.apache.commons.jelly.tags.define.InvokeBodyTag.doTag(InvokeBodyTag.java:91)
        at org.apache.commons.jelly.impl.TagScript.run(TagScript.java:269)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.kohsuke.stapler.jelly.ReallyStaticTagLibrary$1.run(ReallyStaticTagLibrary.java:99)
        at org.kohsuke.stapler.jelly.ReallyStaticTagLibrary$1.run(ReallyStaticTagLibrary.java:99)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.kohsuke.stapler.jelly.ReallyStaticTagLibrary$1.run(ReallyStaticTagLibrary.java:99)
        at org.kohsuke.stapler.jelly.ReallyStaticTagLibrary$1.run(ReallyStaticTagLibrary.java:99)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.kohsuke.stapler.jelly.ReallyStaticTagLibrary$1.run(ReallyStaticTagLibrary.java:99)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.kohsuke.stapler.jelly.ReallyStaticTagLibrary$1.run(ReallyStaticTagLibrary.java:99)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.apache.commons.jelly.tags.core.CoreTagLibrary$2.run(CoreTagLibrary.java:105)
        at org.kohsuke.stapler.jelly.CallTagLibScript.run(CallTagLibScript.java:120)
        at org.apache.commons.jelly.impl.ScriptBlock.run(ScriptBlock.java:95)
        at org.apache.commons.jelly.tags.core.CoreTagLibrary$2.run(CoreTagLibrary.java:105)
        at org.kohsuke.stapler.jelly.JellyViewScript.run(JellyViewScript.java:95)
        at org.kohsuke.stapler.jelly.DefaultScriptInvoker.invokeScript(DefaultScriptInvoker.java:63)
        at org.kohsuke.stapler.jelly.DefaultScriptInvoker.invokeScript(DefaultScriptInvoker.java:53)
        at org.kohsuke.stapler.jelly.JellyRequestDispatcher.forward(JellyRequestDispatcher.java:55)
        at jenkins.model.ParameterizedJobMixIn.doBuild(ParameterizedJobMixIn.java:162)
        at hudson.model.AbstractProject.doBuild(AbstractProject.java:1757)
        at hudson.model.AbstractProject.doBuild(AbstractProject.java:1763)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:298)
        at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:161)
        at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:96)
        at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:121)
        at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:53)
        at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
        at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
        at org.kohsuke.stapler.MetaClass$6.doDispatch(MetaClass.java:249)
        at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:53)
        at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
        at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
        at org.kohsuke.stapler.Stapler.invoke(Stapler.java:649)
        at org.kohsuke.stapler.Stapler.service(Stapler.java:238)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:123)
        at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:114)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:48)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
        at hudson.security.UnwrapSecurityExceptionFilter.doFilter(UnwrapSecurityExceptionFilter.java:51)
        at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
        at jenkins.security.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:117)
        at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
        at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)
        at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
        at org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:142)
        at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
        at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
        at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
        at jenkins.security.BasicHeaderProcessor.doFilter(BasicHeaderProcessor.java:93)
        at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
        at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
        at hudson.security.HttpSessionContextIntegrationFilter2.doFilter(HttpSessionContextIntegrationFilter2.java:67)
        at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
        at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:76)
        at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:81)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:613)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
        at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)

I have tried to access the maven-metadata.xml url from the Jenkins Server machine using wget and successfully download the metadata! So there are no issues with the Jenkins server accessing nexus repository.
[jenkins@jenkinshost ~]$ wget --proxy-user="username" --proxy-password=$pwd https://nexus.repos.prod.com/nexus/content/groups/prod-pds-releases-all/com/prod/pds/pds-ear/maven-metadata.xml --user=$nexususer --password=$nexuspwd
--2015-07-01 15:49:01--  https://nexus.repos.prod.com/nexus/content/groups/prod-pds-releases-all/com/prod/pds/pds-ear/maven-metadata.xml
Resolving adproxy.hq.prod.com... 10.12.44.22, 10.13.14.16
Connecting to adproxy.hq.prod.com|10.12.44.22|:8080... connected.
Proxy request sent, awaiting response... 401 Unauthorized
Connecting to adproxy.hq.prod.com|10.12.44.22|:8080... connected.
Proxy request sent, awaiting response... 200 OK
Length: 5863 (5.7K) [application/xml]
Saving to: `maven-metadata.xml'
100%[===========================================================================================================================================================================>] 5,863       --.-K/s   in 0s

I'm struggling to understand why Jenkins is not able to resolve the nexus url when running the job whereas the same is accessible from command line! Is there a difference in the way Jenkins Maven Metadata plugin access the repository to that of accessing the repos directly using wget?
I have setup the proxy host and port in the Jenkins Plugin Manager (Advanced) settings.
But still Jenkins doesn't seem to use these values or expecting some other value to be set.
On the Jenkins machine I have the environment properties http_proxy & https_proxy defined in .bash_profile. Without these variables I get the same error (UnknownHost) even from command line using wget! So I suspect that these env properties are not getting set when Jenkins is trying to download the metadata xml. I would've thought Jenkins would use the same system properties but apparently not!
That is the only difference I can think of between downloading the metadata xml manually from Jenkins machine using wget command and using Jenkins.
Is there a way to set these properties http_proxy & https_proxy before Jenkins tries to download the xml?
Thanks.

A: Ok, finally I got it working!
The problem was that the Proxy definition in Plugin Manager settings is only used to download/upload the Plugins. I have setup the proxy as specified in the link https://wiki.jenkins-ci.org/display/JENKINS/JenkinsBehindProxy like below. java -Dhttp.proxyHost=some.proxy.host -Dhttp.proxyPort=1234 -Dhttps.proxyHost=some.otherorsame.host -Dhttps.proxyPort=2345 -jar jenkins.war and restarted the Jenkins Server which did the trick!
Thanks to @Tome & @Manfred Moser for pointing me to Proxy Settings.


text:
Q: Why do the usual access control checking applies to names used to specify explicit instantiation when accessed through template parameters? The C++11/14 standards state the following in note 14.7.2/12 [temp.explicit]:

The usual access checking rules do not apply to names used to specify
  explicit instantiations. [ Note: In particular, the template arguments
  and names used in the function declarator (including parameter types,
  return types and exception specifications) may be private types or objects
  which would normally not be accessible and the template may be a member
  template or member function which would not normally be accessible. — end note ]

I would expect to be allowed to use a template if I can instantiate it.
I tried with gcc-4.8.2 and I get the expected behaviour when I access private members of explicitly named classes. However, the access checking rules do apply when I access private members through template parameters. Is this a bug in gcc, or am I missing something?
In the code below, the only difference between 'succeeds' and 'fails' is that the former accesses the private member directly via 'A', while the latter accesses it via the template parameter 'T'. The compiler complains that privateFoobar is private in that context.
#include <iostream>
#include <string>

struct A
{
private:
    std::string privateFoobar() {return "private foobar!";}
};

typedef std::string (A::*Foobar)();

template <class Type, Type value>
struct Access
{
    static Type getValue() {return value;}
};

template <class T>
struct IndirectAccess
{
    static Foobar succeeds() {return Access<Foobar, &A::privateFoobar>::getValue();}
    static Foobar fails() {return Access<Foobar, &T::privateFoobar>::getValue();}
};

template class Access<Foobar, &A::privateFoobar>;

int main() {
    std::cout << (A().*Access<Foobar,&A::privateFoobar>::getValue())() << std::endl;
    std::cout << (A().*IndirectAccess<A>::succeeds())() << std::endl;
    std::cout << (A().*IndirectAccess<A>::fails())() << std::endl;
}

In case you are wondering what is the use case for such a sackable offence: creating a framework that would automate the configuration of an application based on implementation choices for the selected components.

A: Explicit instantiations have to be at namespace scope, which means private members of classes would not normally be accessible. Without the rule you quote, this would be impossible:
class Foo
{
private:
  struct Bar;

  template<typename T> class Baz { };

public:
  void f();  // does things with Baz<Bar>
};

// explicit instantiation declaration
extern template class Foo::Baz<Foo::Bar>;

Without that rule, I would not be able to name Foo::Bar or even Foo::Baz at namespace scope, because those names are private to Foo.
Since I'm not actually using Foo::Bar or Foo::Baz here, just referring to their names to tell the compiler I'm instantiating the template somewhere else, there is no real access violation (although it is possible to use this rule to perform a very sneaky trick not possible otherwise).
Similarly, when I write the explicit instantiation definition in some other file, I need to be able to refer to the private names again at namespace scope.


text:
Q: Laravel 9 - Pivot table - Intermediate table - 2 tier organising system Having a bit of trouble getting my head round this.
I have three models - Sectors, Industries, Companies.
Companies is the viewable resource and are oraganised into Sectors and Industries.
Sectors contain Industries. Industries contain companies.
Previously this was achieved by a table column containing comma separated values of the industry and sector IDs - tacky, I know.
I'm now using a pivot table (company_industry) along with a bi-directional 'belongsToMany' relationship between the company and industry models.
That works fine! For a single tier organising system. But when I come to add Sectors as a parent to Industries, that's when my brain explodes.
I wonder if anyone recognises this problem and can share with me a good resource to explain a best practice resolution.
Thank you kindly.


text:
Q: $\zeta(2)$ Euler's proof (Basel problem) At one point Euler assumes that
$$\frac{\sin x}{x} = \prod_{n=1}^{\infty}\left(1-\frac{x}{n\pi} \right)\left(1-\frac{-x}{n\pi} \right)$$
Why does he assume that? If we factor random functions according to their roots, we can conclude
$$e^x \frac{\sin x}{x}= \prod_{n=1}^{\infty}\left(1-\frac{x}{n\pi} \right)\left(1-\frac{-x}{n\pi} \right)=\frac{\sin x}x$$


text:
Q: How to pass in a SQL parameter when its too long I have a very big 'Where' statement that's longer then the maximum allowed.
Currently I build the full sql in the vb.net code and I execute it.
The problem is that this way is known to be slow because its not a compiled query.
Is there any other way to do it?
EDIT:
  For i As Integer = 0 To List.Count - 1
        If Filter = String.Empty Then
            Filter = " Where OrderID = "
        Else
            Filter += " OR OrderID ="
        End If
        Filter = Filter + "(" & List(i) + ")"
    Next

    Sql = "Select * from OrderPickSheet " & Filter & " And Status > -1 Order by SortOrder"
    cmd.CommandText = Sql
    cmd.ExecuteReader()

A: Instead of constructing the SQL statement on the client, you can call a stored procedure and pass the values in a DataTable.  In your stored procedure, join to the values that are passed in, which means you won't need to build a long dynamic sql statement, and mitigates the risk of sql injection attack.
For example, if you create this type and procedure in your database (I'm guessing here as to the data types):
create type dbo.OrderIdInfo as table
(
    OrderId nvarchar(20)
)

create procedure dbo.SelectOrders
(
    @orderIds dbo.OrderIdInfo readonly
)
as

    select o.*
    from OrderPickSheet o
        inner join @orderIds i on o.OrderId = i.OrderId
    where o.Status > -1
    order by o.SortOrder

You can call the procedure as shown below.  The code does run (tested in LINQPad), but VB is not my primary language, so forgive any clumsiness:
Dim table As New DataTable
Dim results As New DataTable

table.Columns.Add("OrderId", GetType(String))

table.Rows.Add("1")
table.Rows.Add("2")
table.Rows.Add("4")

Dim parameter As New SqlParameter("@orderIds", SqlDbType.Structured)

parameter.Value = table

Using connection As SqlConnection = New SqlConnection("server=localhost;database=Test;integrated security=true")
    Using command As SqlCommand = connection.CreateCommand()

        command.CommandText = "dbo.SelectOrders"
        command.CommandType = CommandType.StoredProcedure
        command.Parameters.Add(parameter)

        connection.Open()

        Dim reader As SqlDataReader = command.ExecuteReader()

        results.Load(reader)

    End Using
End Using

A: You can create the SQL dynamically in a stored procedure instead of in .NET.
The query still won't be compiled, but you can pass all your variables in via comma delimited string or XML

A: You can save a fair amount of length in the SQL command (and protect yourself from SQL injection attacks, to boot) by building a set of parameters dynamically:
    Dim paramList As New StringBuilder
    For i As Integer = 0 To List.Count - 1
        Dim paramName As String = String.Format("@p{0}", i)
        If paramList.Length > 0 Then
            paramList.Append(",")
        End If
        paramList.Append(String.Format(paramName))
        cmd.Parameters.AddWithValue(paramName, List(i))
    Next
    cmd.CommandText = "Select * from OrderPickSheet Where OrderID in (" & paramList.ToString() & ") And Status > -1 Order by SortOrder"
    cmd.ExecuteReader()


text:
Q: How to display relationships between accounts? We service many customers. Many of our customers have relationships between themselves, which are important for us to know.
E.g:
A is customer of B, C and D (which on the reverse makes: B,C and D suppliers of A)
B is supplier of A and D (which also makes D a customer of B)
I want to display, for each account, it's suppliers and customer.
If I look on a related list result, it will look like this (for Account 'D')
D Customer of B
D Supplier of A

For account 'A' it will look like this:
A Customer of B
A Customer of C
A Customer of D

*

*I can use a junction object for this.  (how do I set the reverse names?) - very complicated for managing the complete list.

*Is there another object way to do it? (appexchange?)

A: I recommend you take a look at Astrea Object Hierarchy which is free in the the App Exchange. It's intended to do exactly what you're asking about in terms of finding up to 2-level hierarchies within a single object. However, I don't believe it's designed to display things in a parent, grandparent context, but perhaps that might be a paid option that might be well worth the price. In any case, it clearly will get you at least half way to the solving the the problem at hand.


text:
Q: Adding additional targets to .NET portable project I took over a Xamarin project that was previously outsourced to a 3rd party. Oh boy, what a nightmare. There is a portable c# project that is refrenced in a separate Android project. Whenever I try to fix the broken reference I'm getting this error message:

Taking a look at the project properties, I can see that there is nothing targeting Xamarin.Android which I'm assuming should definitely be there since this library is clearly being referenced in a Xamarin project. By the way, there is a separate project for iOS that also references this portable library so I'm assuming Xamarin.iOS will also have to be targeted. Completely baffled here all information from Google has been useless.
I have looked at:

*

*https://learn.microsoft.com/en-us/dotnet/framework/cross-platform/portable-class-library

*https://lastexitcode.com/blog/2014/11/16/InstallingPortableClassLibrariesForXamarinStudio/
and all related linked in those pages and endless google searches frustratingly obscure topic.
Taking a look at the packages.config I can see these types targeted as well but again have no idea how these are linked to this package.config.
Are my assumptions correct and how on earth can I add these targets?


text:
Q: Laravel: Getting extra column (from other model) in eloquent query -- What do i expect --
I am in progress of filling a form select based on the selection of another select.
The first select is:
{{Form::select('country',$countries,$player->city->country->id,['class' => 'form-control','id' => 'selectCountry'])}}

The Second select should fill the cities that are linked to the country.
-- My controller trying to receive necesarry info--
return Country::find($request->get('country'))->cities->where('player_id','!=',null);

And this all works fine. Now here is the issue, my JSON object (the model Country) has a player_id, but i want the result to also include the 'player_name' column that he finds in the App\Player model.
Anyone has an idea how to build up the Eloquent query? Or can it only be done by a DB:: query, if so how do i build up this query?
Thanks for your help in advance!

A: If you have a player_id column on the Country table, you should have a player() relation on the Country model.
So you can do :
return Country::find($request->get('country'))->cities->where('player_id','!=',null)->with('player');

And then $country->player->player_name;


text:
Q: How can i modify this string and get the value I want from JSON Object in java? This is the response.
{
  "code": 200,
  "data": {
    "createdAt": "2019-12-09 15:21:07.0",
    "id": 3,
    "title": "{\"v\":\"1\"}",
    "token": "INACTIVE"
  },
  "message": "SUCCESS"
}

I need value of v which is 1. I'm getting this
{"v":"1"}

through
JSONObject r2 = new JSONObject(operation);
                String title = r2.getString("title");
                System.out.println(title);

How do I get the value of v after this?  It would be great if I could get any suggestions.

A: The value of title is a string with JSON text, so you need to re-invoke the JSON parser.
Also, in the question code, you forgot to navigate past the data node.
JSONObject rootObj = new JSONObject(operation); // parse JSON text
String title = rootObj.getJSONObject("data").getString("title"); // get "title" value
JSONObject titleObj = new JSONObject(title); // parse JSON text
String v = titleObj.getString("v"); // get "v" value
System.out.println(v); // prints: 1

A: String v= r2.getJSONObject("title").getString("v");
System.out.println(v);

PS: Don't forget to handle nulls,etc.
UPDATE: Please refer Andreas's answer as it is the correct answer.  This answer wrongly assumes that title also contains json.


text:
Q: Android Activity Animations Timing I want to put some animations on my activities when they open and close.  But so far if i put them on it just makes it feel like the phone is lagging. And if I speed them up then you barely notice them.
What is the smallest time fragment which the average human can identify to? 50ms 100ms?
How can I make an animation noticeable, but not take away from the responsiveness of the application? Because obviously the animations them selves probably slow down the app allot.
Maybe Im asking a stupid question, If so I am sorry. But I thought that it is a fairly important aspect of designing a gpood app.

A: http://en.wikipedia.org/wiki/Frame_rate says:
"The human eye and its brain interface, the human visual system, can process 10 to 12 separate images per second, perceiving them individually."
The 1896 standard movie frame rate was 16 fps. Today it is at least 24 fps.
I also remember the rate 18 events per second, not sure if it was MS-DOS or old TV.
The car driver's reaction time is estimated to be about 0.2 sec. (In the case that the driver is prepared to react.) This means that if something happens faster, a human has no time to move, despite of seeing it.
You can base your design on these digits.


text:
Q: Facebook url randomly unreachable I'm sure anyone who has worked with Facebook has encountered the url unreachable problem with the comments plugin and alike.
I managed to get around this initially by making urls go to the facebook app page rather the hosted page, figuring facebook would be able to find itself, and ammended the url with a query string which could internally redirect them to right content. For example "app.facebook.com/myApp/?myAppP=videos&myAppId=0001" would first of all load the facebook app page then redirect the iframe to show the videos page and play video 0001.
This worked great at first but seems to have become a little unpredictable. I have a list of different videos, all of which use the same url except that the "myAppId" is different so the correct video is loaded. However whilst the "comments" and "like" plugins work fine for about a 1/3 of them, the other 2/3 show the "url unreachable". I can see no correlation between the urls that work and those that don't. It seems completely random, but it is always the same one that do and don't work.
This has got me completely stumped. Any ideas?

A: try to disable sandbox on app settings


text:
Q: ModelForm saving over model data with empty fields I'm building an Edit form for a model in my database using a ModelForm in Django. Each field in the form is optional as the user may want to only edit one field.
The problem I am having is that when I call save() in the view, any empty fields are being saved over the instance's original values (e.g. if I only enter a new first_name, the last_name and ecf_code fields will save an empty string in the corresponding instance.)
The form:
class EditPlayerForm(forms.ModelForm):

    class Meta:
        model = Player
        fields = ['first_name', 'last_name', 'ecf_code']

    def __init__(self, *args, **kwargs):
        super(EditPlayerForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].required = False
        self.fields['last_name'].required = False
        self.fields['ecf_code'].required = False

The view:
def view(request, player_pk = ''):

    edit_player_form = forms.EditPlayerForm(auto_id="edit_%s")

    if "edit_player_form" in request.POST:

        if not player_pk:

            messages.error(request, "No player pk given.")

        else:

            try:

                selected_player = Player.objects.get(pk = player_pk)

            except Player.DoesNotExist:

                messages.error(request, "The selected player could not be found in the database.")
                return redirect("players:management")

            else:

                edit_player_form = forms.EditPlayerForm(
                    request.POST,
                    instance = selected_player
                )

                if edit_player_form.is_valid():

                    player = edit_player_form.save()
                    messages.success(request, "The changes were made successfully.")
                    return redirect("players:management")

                else:
                    form_errors.convert_form_errors_to_messages(edit_player_form, request)

    return render(
        request,
        "players/playerManagement.html",
        {
            "edit_player_form": edit_player_form,
            "players": Player.objects.all(),
        }
    )

I've tried overriding the save() method of the form to explicitly check which fields have values in the POST request but that didn't seem to make any difference either.
Attempt at overriding the save method:
def save(self, commit = True):

    # Tried this way to get instance as well
    # instance = super(EditPlayerForm, self).save(commit = False)

    self.cleaned_data = dict([ (k,v) for k,v in self.cleaned_data.items() if v != "" ])

    try:
        self.instance.first_name = self.cleaned_data["first_name"]
    except KeyError:
        pass

    try:
        self.instance.last_name = self.cleaned_data["last_name"]
    except KeyError:
        pass

    try:
        self.instance.ecf_code = self.cleaned_data["ecf_code"]
    except KeyError:
        pass

    if commit:
        self.instance.save()

    return self.instance

I also do not have any default values for the Player model as the docs say the ModeForm will use these for values absent in the form submission.
EDIT:
Here is the whole EditPlayerForm:
class EditPlayerForm(forms.ModelForm):

    class Meta:
        model = Player
        fields = ['first_name', 'last_name', 'ecf_code']

    def __init__(self, *args, **kwargs):
        super(EditPlayerForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].required = False
        self.fields['last_name'].required = False
        self.fields['ecf_code'].required = False

    def save(self, commit = True):

        # If I print instance variables here they've already
        # been updated with the form values

        self.cleaned_data = [ k for k,v in self.cleaned_data.items() if v ]

        self.instance.save(update_fields = self.cleaned_data)

        if commit:

            self.instance.save()

        return self.instance

EDIT:
Ok so here is the solution, I figured I'd put it here as it might be useful to other people (I've certainly learned a bit from this).
So it turns out that the is_valid() method of the model form actually makes the changes to the instance you pass into the form, ready for the save() method to save them. So in order to fix this problem, I extended the clean() method of the form:
 def clean(self):

    if not self.cleaned_data.get("first_name"):
        self.cleaned_data["first_name"] = self.instance.first_name

    if not self.cleaned_data.get("last_name"):
        self.cleaned_data["last_name"] = self.instance.last_name

    if not self.cleaned_data.get("ecf_code"):
        self.cleaned_data["ecf_code"] = self.instance.ecf_code

This basically just checks to see if the fields are empty and if a field is empty, fill it with the existing value from the given instance. clean() gets called before the instance variables are set with the new form values, so this way, any empty fields were actually filled with the corresponding existing instance data.

A: You could maybe use the update() method instead of save()
or the argument  update_field
self.instance.save(update_fields=['fields_to_update'])

by building the list ['fields_to_update'] only with the not empty values.
It should even work with the comprehension you've tried :
self.cleaned_data = [ k for k,v in self.cleaned_data.items() if v ]

self.instance.save(update_fields=self.cleaned_data)

EDIT :
Without overriding the save method (and commenting out this attempt in the form):
not_empty_data = [ k for k,v in edit_player_form.cleaned_data.items() if v ]
print(not_empty_data)
player = edit_player_form.save(update_fields=not_empty_data)

A: You could check the values if it's not empty in your view without overriding save()
if edit_player_form.is_valid():
    if edit_player_form.cleaned_data["first_name"]:
        selected_player.first_name = edit_player_form.cleaned_data["first_name"]
    if edit_player_form.cleaned_data["last_name"]:
        selected_player.last_name= edit_player_form.cleaned_data["last_name"]
    if edit_player_form.cleaned_data["ecf_code"]:
        selected_player.ecf_code= edit_player_form.cleaned_data["ecf_code"]
    selected_player.save()

This should work fine with what you want. I'm not sure if it's the best way to do it but it should work fine.


text:
Q: C++ code throwing Seg. Fault I have a C++ code as follow:
tryIt.h file
class tryIt : public someOtherClass
{
public:
       bool insertI ();
private:
       CommandI* m_pInsertI;
       bool createInsertI();
}

tryIt.cpp file
tryIt ::tryIt () : m_pInsertI(NULL)
{
    createInsertI();
}

tryIt ::~tryIt ()
{
   if(m_pInsertI!=NULL)
   {
      delete m_pInsertI;
      m_pInsertI=NULL
   }
}
bool createInsertI()
{
    m_pInsertI = returnFromSomeOtherFunction();
    return true;
}

bool insertI()
{
    // Over here if I use m_pInsertI anyhow my code fails with seg fault
    // even checking if(m_pInsertI==NULL) make the code throw seg fault
}

So the issue is touching m_pInsertI anywhere make my code throw Seg. fault (Signal 11). Even debugged the code with GDB but didn't got any useful info.
Compiler is GCC
Please help.

A: Sounds like the instance of this class does not exist or damaged.
That is why you can't access any of its members and even if(m_pInsertI==NULL) check raises the exception.

A: in tryIt.cpp shouldn't
bool createInsertI()

be
bool tryIt::createInsertI()

same with insertI()

A: I see the following two possibilities:

*

*returnFromSomeOtherFunction() already returns a corrupted pointer

*You are copying your instance using the compiler generated methods (see example below)

Example (Rule of three violation)
tryIt instance1; // allocates instance2.m_pInsertI

{
    tryIt instance2;
    instance1 = instance 2; // performs a shallow copy

} // here, instance2.m_pInsertI is deleted

instance1.insertI(); // access violation

Recommendation:
Whether or not this is cause your problem: Do not implement manual memory management. Simply use a std::unique_ptr<CommandI> for m_pInsertI instead, so you do not need to implement the destructor or copy constructors/operators.