text:
Q: docker-compose doesn't work from Visual Studio I have three web projects in one solution, they work together on gRPC. I am trying to bring all three projects up with docker-compose, but the problem is when the command
docker-compose up --build

This is how everything works, but when I try to start using the Visual Studio interface with a debugger connected, it does not work
When you run the application via docker-compose in Visual Studio, then when you start the containers themselves, an error appears with the following content:
Can't find a program for debugging in the container

And then it immediately pops out this:
The target process exited without raising an event fired by CoreCLR. Make sure the target process is configured to use .NET Core. This may be necessary if the target process has not started in .NET Core.

This message appears in the container logs:
Could not execute because the application was not found or a compatible .NET SDK is not installed.
Possible reasons for this include:
  * You intended to execute a .NET program:
      The application '/app/bin/Debug/net5.0/Votinger.Gateway.Web.dll' does not exist.
  * You intended to execute a .NET SDK command:
      It was not possible to find any installed .NET SDKs.
      Install a .NET SDK from:
        https://aka.ms/dotnet-download

This is a Dockerfile which is auto-generated by Visual Studio, it is the same for every project except for the paths to the project
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 5000
EXPOSE 5001

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY ["Votinger.Gateway/Votinger.Gateway.Web/Votinger.Gateway.Web.csproj", "Votinger.Gateway/Votinger.Gateway.Web/"]
RUN dotnet restore "Votinger.Gateway/Votinger.Gateway.Web/Votinger.Gateway.Web.csproj"
COPY . .
WORKDIR "/src/Votinger.Gateway/Votinger.Gateway.Web"
RUN dotnet build "Votinger.Gateway.Web.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Votinger.Gateway.Web.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
FROM mcr.microsoft.com/dotnet/sdk:5.0
ENTRYPOINT ["dotnet", "Votinger.Gateway.Web.dll"]

docker-compose.yml
version: '3.4'

services:
  votinger.authserver.db:
    image: mysql:8
    container_name: Votinger.AuthServer.Db
    restart: always
    environment:
        MYSQL_ALLOW_EMPTY_PASSWORD: "yes"

  votinger.pollserver.db:
    image: mysql:8
    container_name: Votinger.PollServer.Db
    restart: always
    environment:
        MYSQL_ALLOW_EMPTY_PASSWORD: "yes"

  votinger.authserver.web:
    image: ${DOCKER_REGISTRY-}votingerauthserverweb
    container_name: Votinger.AuthServer.Web
    build:
      context: .
      dockerfile: Votinger.AuthServer/Votinger.AuthServer.Web/Dockerfile
    links:
        - votinger.authserver.db:authdb

  votinger.gateway.web:
    image: ${DOCKER_REGISTRY-}votingergatewayweb
    container_name: Votinger.Gateway.Web
    build:
      context: .
      dockerfile: Votinger.Gateway/Votinger.Gateway.Web/Dockerfile
    ports:
        - 5000:5000
    links:
        - votinger.authserver.web:authserver
        - votinger.pollserver.web:pollserver

  votinger.pollserver.web:
    image: ${DOCKER_REGISTRY-}votingerpollserverweb
    container_name: Votinger.PollServer.Web
    build:
      context: .
      dockerfile: Votinger.PollServer/Votinger.PollServer.Web/Dockerfile
    links:
        - votinger.pollserver.db:polldb

docker-compose.override.yml
version: '3.4'

services:
  votinger.authserver.web:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=https://+:5000;http://+:5001
      - ASPNETCORE_Kestrel__Certificates__Default__Password=password
      - ASPNETCORE_Kestrel__Certificates__Default__Path=/https/aspnetapp.pfx
    volumes:
      - ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
      - ${APPDATA}/ASP.NET/Https:/https:ro

  votinger.gateway.web:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=https://+:5000;http://+:5001
      - ASPNETCORE_Kestrel__Certificates__Default__Password=password
      - ASPNETCORE_Kestrel__Certificates__Default__Path=/https/aspnetapp.pfx
    volumes:
      - ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
      - ${APPDATA}/ASP.NET/Https:/https:ro
  votinger.pollserver.web:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=https://+:5000;http://+:5001
      - ASPNETCORE_Kestrel__Certificates__Default__Password=password
      - ASPNETCORE_Kestrel__Certificates__Default__Path=/https/aspnetapp.pfx
    volumes:
      - ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
      - ${APPDATA}/ASP.NET/Https:/https:ro

I will also post a link to GitHub where this project is located
(dev branch)
https://github.com/SeanWoo/Votinger
I will forgive your help

A: I found a solution, the problem was that in the docker-compose.vs.debug.yml file is generated by Visual Studio, full paths to the project and debugger are indicated there, and my path went through a folder named as C #, and Visual Studio decided to calculate the symbol # unnecessary and deleted it, it turned out to be a path with the C folder, which led to a completely different place


text:
Q: Pass 2D array to function I am new to programming.
User will be enter the size of 2D array and then I want to pass this array to function. How can I do this?

A: There are two ways to accomplish your goal.
The first way is using dynamically allocated C-style arrays. You shouldn't do this in C++ unless you are forced to support existing code. But in this case it is better to consider refactoring, maybe.
The second way is using std::vector. This class encapsulates low-level manipulations with memory. It will free you from many potential bugs.
To show you advantages of std::vector I have written two programs. They input sizes of 2D array (in another way, it is called a matrix) and create it.
Creating matrix using C-style arrays requests a lot of code and manipulations with pointers. For the sake of simplicity the following code doesn't handle exceptions. In real code you should do it to avoid memory leaks, but the code would become even harder.
#include <iostream>
#include <cstddef>

using namespace std;

void function(int** matrix, size_t nrows, size_t ncols)
{

}

int main()
{
    size_t nrows;
    size_t ncols;

    cin >> nrows >> ncols;

    // allocate memory for matrix
    int** matrix = new int*[nrows];
    for (size_t i = 0; i < nrows; ++i)
        matrix[i] = new int[ncols];

    function(matrix, nrows, ncols);

    // release memory
    for (size_t i = 0; i < nrows; ++i)
        delete[] matrix[i];
    delete[] matrix;
}

So in C++ it would be very easier using std::vector. Since std::vector is a class it has constructor and destructor encapsulating allocating and releasing memory.
#include <iostream>
#include <vector>

using namespace std;

void function(vector<vector<int>>& matrix)
{

}

int main()
{
    size_t nrows;
    size_t ncols;

    cin >> nrows >> ncols;

    // create matrix
    vector<vector<int>> matrix(nrows);
    for (size_t i = 0; i < nrows; ++i)
        matrix[i] = vector<int>(ncols);

    // you don't even need to pass sizes of matrix
    function(matrix);

    // automatically called destructor of matrix releases memory
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Grunt server local host not responding Just built using
yo webapp

afterwards tried to preview it, as the website says, with
grunt server

and I get the error in the browser "No data received"
Any idea what the issue could be here?
The command
grunt test

works fine, I get back
Running "mocha:all" (mocha) task
Testing: http://localhost:9000/index.html

  ․

  1 test complete (109 ms)

>> 1 passed! (0.11s)

A: The latest version of livereload (0.2.0) needs to installed.
In the webapp folder use the command
npm install connect-livereload

and the error is fixed


text:
Q: How can a macro define a valid global name based on the type passed to it? I believe the title is self-explanatory, but here's an example to illustrate what I'm trying to accomplish:
#define PASTE2(_0, _1)  _0 ## _1

#define DEFINE_OPS_FOR_TYPE(TYPE)                   \
    int PASTE2(do_something_with_, TYPE)(void) {    \
        /* do_something_with_<TYPE> */              \
    }

Everything works fine for char, int, and single-worded types, but when it
comes to unsigned types, or others that have multiple keywords, using token pasting (a ## b) does not generate a valid name due to the whitespace (e.g.: do_something_with_foo bar).
The easiest solution I could think of is to change the DEFINE_OPS_FOR_TYPE macro
to take a valid name as the 2nd parameter. For example:
#define DEFINE_OPS_FOR_TYPE(TYPE, NAME_FOR_TYPE)            \
    int PASTE2(do_something_with_, NAME_FOR_TYPE)(void) {   \
        /* do_something_with_<NAME_FOR_TYPE> */             \
    }

This works as expected, but I'm curious about other possible solutions, even if they're overly complex. I thought of using _Generic, but I fail to see how it would help in defining a name.
Can you think of another solution?

A: On the level of declaration or definition of the symbols that you want to do there is not much way out of typedefing things to a unique identifier for the type in question. _Generic or equivalent replacements kick in too late to be useful for the preprocessor.
But there is only a finite number of standard types that pose such a problem. So you can easily come up with a convention for typedeffing these.
Where _Generic can help is on the usage side of your such defined symbols. Here you can then do something like
_Generic((X),
  unsigned long: do_something_with_ulong,
  unsigned char: do_something with_uchar,
  ...
)(X)

In P99 I follow this scheme, and you would find a lot of support macros for it already in place.

A: I ended up using a macro with an empty argument. Example:
#define STR2(x)             # x
#define STR(x)              STR2(x)
#define PASTE3(_1,_2,_3)    _1 ## _2 ## _3
#define FOO(_1,_2,_3)       PASTE3(_1, _2, _3)

printf("%s\n", STR(FOO(int,,)));
printf("%s\n", STR(FOO(unsigned, int,)));
printf("%s\n", STR(FOO(unsigned, long, long)));

As you can see here, the output is:
int
unsignedint
unsignedlonglong

I don't remember whether using empty macro arguments is well defined according to the standard, but I can tell you that Clang 3.1 doesn't emit any warnings for -std=c11 with -pedantic.
Here's some code if you want to try:
#include <stdio.h>
#include <limits.h>

#define PASTE4(_1,_2,_3,_4) _1 ## _2 ## _3 ## _4

#define DEFINE_OPS_FOR_TYPE1(T1)        DEFINE_OPS_FOR_TYPE2(T1,)
#define DEFINE_OPS_FOR_TYPE2(T1, T2)    DEFINE_OPS_FOR_TYPE3(T1,T2,)
#define DEFINE_OPS_FOR_TYPE3(T1, T2, T3)                                    \
    int PASTE4(write_,T1,T2,T3)(FILE *file, void *data) {                   \
        T1 T2 T3 foo;                                                       \
        int written = fprintf(file, fmt_specifier(foo), *((T1 T2 T3 *)data));\
        return written > 0 ? 0 : -1;                                        \
    }

#define fmt_specifier(x)                \
    _Generic((x),                       \
        int: "%i",                      \
        unsigned int: "%u",             \
        unsigned long long: "%llu",     \
        default: NULL                   \
    )

DEFINE_OPS_FOR_TYPE1(int)
DEFINE_OPS_FOR_TYPE2(unsigned, int)
DEFINE_OPS_FOR_TYPE3(unsigned, long, long)

int main() {
    int var_int = INT_MAX;
    write_int(stdout, &var_int);
    printf("\n");
    unsigned int var_uint = UINT_MAX;
    write_unsignedint(stdout, &var_uint);
    printf("\n");
    unsigned long long var_ullong = ULLONG_MAX;
    write_unsignedlonglong(stdout, &var_ullong);
    printf("\n");
    return 0
}


text:
Q: intellij undo formatting CTRL+ALT+L intellij: how to undo formatting CTRL+ALT+L?
Now the svn diff is a mess.
CTRL+Z did not work.
svn revert: does not work since there are many changes in addition to formatting.
How to disable auto-formatting?

A: Ctrl+z works for me when I do a ctrl+alt+l.  You could also hit
Edit->Undo Reformat Code

If its on a Mac its cmd+z but I assume everyone knew that.
I am not 100% sure about svn, but in intellij you can view "Local History" of a file and revert to the "preformatted version"


text:
Q: Is it a good idea or at least possible to use Handlebars with Angular 2? As the syntax for angular expressions and Handlebars expressions are same ({{ }}), I am wondering whether we can use both simultaneously or not.

A: In some cases it would make sense to use handlebars in the front-end. But probably not for what you think.

*

*e.g. If you have a website that creates commands, invoices or reports, and you want your users to create custom layouts for those documents, then you could offer them handlebars templates.

*e.g. If your website is actually a code generator tool, then you could let users tweak their output using handlebar scripts.
So, on that level, yes you can use handlebars.
By contrast, don't use it to actually render the html of your angular components. That would be a terrible idea.
However, if you really really wanted to do that, you could. After all, you can inject a variable which contains html directly inside your angular component templates. Of course it would be extremely limited.
<div [innerHTML]="htmlstring"></div>


text:
Q: Add custom field in shipping address form of Checkout for Magento 2? Below I have a shipping address form of checkout page and I would like to add another field(P.O. Box) in this form. I tried to look it up every forums and most of the answers were based on overriding Magento\Checkout\Block\Checkout\LayoutProcessor. I checked app/code/company/Checkout/etc/di.xml but wasn't referencing layoutprocessor.
I am still confused from where this form is getting values from Magento\Quote\Api\Data\AddressInterface or Magento\Checkout\view\frontend\layout\checkout_index_index.xml

how can I add custom field to this form? Can anyone give me any suggestions? It would be really helpful appreciate it

A: you should check Magento\Customer\Api\Data\AddressInterface to add a new field to the address.

A: So after referring to lot of blogs I believe there are only 2 ways of creating custom field in which could be either by extending Magento\Customer\Api\Data\AddressInterface or by extending Magento\Checkout\Block\Checkout\LayoutProcessor with the plugin created in  app/code/vendor/Checkout/etc/di.xml. Also I noticed that the only purpose of Magento\Checkout\view\frontend\layout\checkout_index_index.xml was to load the whole chunk in a single block rendering in one page as it could be used for adding validation.


text:
Q: What are the benefits of redirecting main() method to another method on program start? In the Android Source Code repository I found  a Main.java file including this:
public static void main(String[] args) {
    Main main = new Main();
    main.run(args);
}

void run(String[] args) {
    //CODE CONTUNIES
}

I found some articles saying creating instance of Main class is not allowed. I tried this in IntelliJ and it works. Is there any benefit of this or is it just a code beauty?

A: The article you posted says only that the JVM does not create an instance of Main when running the application. This is why it's a static method.

As per benefits, I do not see any except for leaving the main method as clean as possible and move some cumbersome logic in an other place.
Unless you are using Main.java as an actual objects with fields and useful methods you should use other static methods to organize your logic.
The class you posted, in fact, contains other methods besides run. They could as well have written another class. I feel it's more of a personal choice.

A: I'm pretty sure that the articles don't say that you can create instances of different objects in your main method!!! The articles said that it's not necessary to create an instance of a specific object to call the main method.
Let's suppose that you have the Application class where you have declared the main method. For calling the main method, you don't need to create an instance of Application like this Application app = new Application(), and after that to call the main method like this: app.main();


text:
Q: Get an HTML element based on the element before with Beautiful Soup (EPA website) I would like to print the "Civil Penalty" section of EPA settlements like https://www.epa.gov/enforcement/chevron-settlement-information-sheet or https://www.epa.gov/enforcement/ngl-crude-logistics-llc-clean-air-act-settlement
Out of the following HTML source

Civil Penalty

Chevron U.S.A. will pay a $2.95 million civil penalty, of which $2,492,750 will be paid to the United States and $457,250 to the State of Mississippi.

I would like to get Chevron U.S.A. will pay a $2.95 million civil penalty ...
This structure is the same for all settlement factsheets.

Civil Penalty

NGL will pay a civil penalty of $25 million. The penalty is based, in part, on the company's limited ability to pay a larger penalty.

I've found similarities to Get an element before a string with Beautiful Soup – but this is not fully identical to my question.
Here is my code skeleton:
import requests
from bs4 import BeautifulSoup
import sys

for i in ['chevron-settlement-information-sheet', 'ngl-crude-logistics-llc-clean-air-act-settlement', 'derive-systems-clean-air-act-settlement']:

    page = requests.get("https://www.epa.gov/enforcement/"+i)
    soup = BeautifulSoup(page.content, 'html.parser')

    data = []

    for result in soup.find_all('h2', id='civil'):
        data.append(result)

print(data)

How can I print the
 section directly following a
?

A: You can try the sibling selector, +.
p=soup.select('#civil + p')
print(p[0].getText())

This will select only the p element that is the very next sibling of the #civil element.

A: One reason you may not have been getting the results you were looking for is you were adding /history to the URL, which leads to a 404 error page. If you remove that part and then use findNext('p') to get the next paragraph element on the page after the
 element, you will get the expected result:
import requests
from bs4 import BeautifulSoup

for url in ['chevron-settlement-information-sheet', 'ngl-crude-logistics-llc-clean-air-act-settlement', 'derive-systems-clean-air-act-settlement']:

    page = requests.get("https://www.epa.gov/enforcement/" + url)
    soup = BeautifulSoup(page.content, 'html.parser')

    result = soup.find('h2', {'id': 'civil'}).findNext('p')
    print(result.text)

This prints out:
Chevron U.S.A. will pay a $2.95 million civil penalty, of which $2,492,750 will be paid to the United States and $457,250 to the State of Mississippi.
NGL will pay a civil penalty of $25 million. The penalty is based, in part, on the company's limited ability to pay a larger penalty.
Derive will pay a civil penalty of $300,000, as the company has limited financial ability to pay a higher penalty.


text:
Q: PersistenceManager cannot connect to database When trying to run app which uses Jackrabbit (locally on Tomcat7), from any reason it doesn't connect to database. Connection to db works from regular Java app with the same credentials.
How to investigate what is wrong about connectivity? There is a question Cannot instantiate persistence manager org.apache.jackrabbit.core.persistence.pool.MySqlPersistenceManager
but no explanation.
DB connection configuration:
<PersistenceManager class="org.apache.jackrabbit.core.persistence.pool.MySqlPersistenceManager">
      <param name="driver" value="com.mysql.jdbc.Driver"/>
      <param name="url" value="jdbc:mysql://localhost:3306/repo"/>
      <param name="databaseType" value="mysql"/>
      <param name="user" value="admin" />
      <param name="password" value="password11.." />
      <param name="schemaObjectPrefix" value="${wsp.name}_"/>
      <param name="externalBLOBs" value="true"/>
</PersistenceManager>

Error output:
[localhost-startStop-1] INFO org.apache.jackrabbit.core.RepositoryImpl - Starting repository...
[localhost-startStop-1] INFO org.apache.jackrabbit.core.fs.local.LocalFileSystem - LocalFileSystem initialized at path jackrabbit\repository
[localhost-startStop-1] INFO org.apache.jackrabbit.core.fs.local.LocalFileSystem - LocalFileSystem initialized at path jackrabbit\version
Tue Aug 21 10:46:47 CEST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
[localhost-startStop-1] ERROR org.apache.jackrabbit.core.RepositoryImpl - failed to start Repository: Cannot instantiate persistence manager org.apache.jackrabbit.core.persistence.pool.MySqlPersistenceManager
javax.jcr.RepositoryException: Cannot instantiate persistence manager org.apache.jackrabbit.core.persistence.pool.MySqlPersistenceManager
    at org.apache.jackrabbit.core.RepositoryImpl.createPersistenceManager(RepositoryImpl.java:1379)
    at org.apache.jackrabbit.core.RepositoryImpl.createVersionManager(RepositoryImpl.java:512)
    at org.apache.jackrabbit.core.RepositoryImpl.<init>(RepositoryImpl.java:313)
    at org.apache.jackrabbit.core.RepositoryImpl.create(RepositoryImpl.java:615)
    at org.apache.jackrabbit.core.TransientRepository$3.getRepository(TransientRepository.java:250)
    at org.apache.jackrabbit.core.TransientRepository.startRepository(TransientRepository.java:280)
    at org.apache.jackrabbit.core.TransientRepository.login(TransientRepository.java:376)
    at org.apache.jackrabbit.commons.AbstractRepository.login(AbstractRepository.java:144)
    at org.omilab.services.repo.service.JackRabbitRepositoryProvider.<init>(JackRabbitRepositoryProvider.java:60)
    at org.omilab.services.repo.service.JackRabbitRepositoryProvider.getInstance(JackRabbitRepositoryProvider.java:41)
    at org.omilab.services.repo.service.JackRabbitConnector.<init>(JackRabbitConnector.java:45)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at codes.thischwa.c5c.ConnectorServlet.init(ConnectorServlet.java:79)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1282)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1195)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1085)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5318)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5610)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:899)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:875)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1092)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1984)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Could not create connection to database server.)
    at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1549)
    at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1388)
    at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
    at org.apache.jackrabbit.core.util.db.ConnectionHelper.getExtraNameCharacters(ConnectionHelper.java:187)
    at org.apache.jackrabbit.core.util.db.ConnectionHelper.prepareDbIdentifier(ConnectionHelper.java:142)
    at org.apache.jackrabbit.core.persistence.pool.BundleDbPersistenceManager.init(BundleDbPersistenceManager.java:542)
    at org.apache.jackrabbit.core.persistence.pool.MySqlPersistenceManager.init(MySqlPersistenceManager.java:51)
    at org.apache.jackrabbit.core.RepositoryImpl.createPersistenceManager(RepositoryImpl.java:1375)
    ... 33 more

EDIT1:
on the same tomcat built with the same maven this simple app can connect to the same database:
<%@ page import="java.sql.*"%>

<title>DB</title>

DB connectivity test!

        <%
  String db = "repo";
  String user = "admin";
  String password = "password11..";
  try {
    java.sql.Connection con;
    Class.forName("org.gjt.mm.mysql.Driver");
    con = DriverManager.getConnection("jdbc:mysql://localhost/"+db, user, password);
    out.println (db+ " database successfully opened.");
  }
  catch(SQLException e) {
    out.println("SQLException caught: " +e.getMessage());
  }
%>

A: I have solved the issue already.
Maven was attaching to this app old version of mysql connector which was supposed to be compatible but wasn't working.


text:
Q: how to parse this json file without array name and object name? I want to parse this json but this json have no array name or no object name. i need to get id,color,description.
[
    {
        "id": "mLPjQs-YK5g",
        "created_at": "2018-06-20T02:06:38-04:00",
        "updated_at": "2018-06-20T10:56:38-04:00",
        "width": 4016,
        "height": 6016,
        "color": "#D7A694",
        "description": null
    },
    {
        "id": "HcgDLkDbo7U",
        "created_at": "2018-06-20T10:15:12-04:00",
        "updated_at": "2018-06-20T10:54:30-04:00",
        "width": 3648,
        "height": 5472,
        "color": "#E1D6DE",
        "description": null
    }
]


text:
Q: How to delete all rows over 50 count? My table:
_id | state | timeStamp

I want select all the rows that are of state=0 and order that result by timeStamp.  I than want to delete all items passed a particular limit, say 50 rows.
*Essentially, I don't want there to be more than 50 rows with the state=0
How can I achieve this?  I tried writing one but I'm getting a bit lost...
DELETE FROM table WHERE (state=0) ORDER BY timeStamp

A: Use the NOT IN statement with a sub query:
DELETE FROM table WHERE state = 0 AND _id NOT IN(SELECT _id FROM table WHERE state = 0 ORDER BY timeStamp LIMIT 50);
What it does is select all rows where state = 0 and then removes the 50 first rows that has state = 0 all while ordering on timeStamp

A: You can find what the time stamp is for the 50th row and then do a delete statement for rows whose state = 0 and whose timestamp is older (or newer, whichever applies here) than the time stamp you found.


text:
Q: ViewPager - How to know when a cached fragment is displayed I have a ViewPager using a TabLayout. I am changing pages within a fragment of ViewPager via parentActivity.setCurrentItem() which directs to a sibling Fragment.
Only when I redirect to this fragment from a sibling I would like to display a different view. I am having a issue since the fragment is being cached and OnCreateView is not firing when the fragment is being displayed.
Is there an event that gets fired when a cached fragment is displayed?

A: Overriding setUserVisible(boolean isVisibleToUser) in the fragment seems to do the trick. This is triggered when the fragment is created and whenever the fragment is displayed.
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    ParentActivity parent = (ParentActivity)getActivity();

    if (parent != null){
        String leftMenuToShow = parent.getMenuItemToShowInFragment();
        String elementToShow = parent.getElementToShowInFragment();
    }
}


text:
Q: Rails best practice for creating a resource on a relational model I would like to know what would be the best way to create / destroy a relational resource. For Eg.: I have two models called Picture and Favorite. A user can add a picture to his favorites.
class Picture

end

class Favorite

 belongs_to :picture
 belongs_to :user

end

I would like to know which is the best place(practice) to add login in order to add a picture to his / her favorites. Is it better to add it in the PicturesController with a favorite action that would create or delete the favorite based on its existence, or else create a separate controller called FavoritesController and add two actions called create and destroy?

A: The best approach following both Rails conventions and RESTful principles would be to create a controller per resource, containing the actions necessary to manipulate that resource. Based on your situation, you have a Favorite resource that can be both created and destroyed, so the route mapping should be something like this:
  Prefix Verb   URI      Pattern                  Controller#Action
  favorites     POST     /favorites(.:format)     favorites#create
  favorite      DELETE   /favorites/:id(.:format) favorites#destroy

And your controller should look like this:
class FavoritesController < ApplicationController
  def create
    # Create a favorite here based on its params !
  end

  def destroy
    # Destroy a favorite here based on its id !
  end
end

About the login process, I really think it should be a concern of your UsersController, though some Ruby devs prefer to use SessionsController, since it is a Devise default.
Notice that you have the option to create nested resource routes which is a good idea when mapping has_one / belongs_to relations into routes, and it is indeed a best practice. You can check Rails Guides for details.
I'm not suggesting this kind of approach here, because when it comes to the User resource, it is not a good idea to have its id on your routes, and it is kind of a default to work with it in the backend.
I hope it helps :P


text:
Q: upcast of nullptr through class with multiple inheritance The problem is that an implicit cast of nullptr, to the second super class, of a class with multiple inheritance results (at least with LLVM 7.0.2) in an adjustment being applied to the nullptr. The pointer is now no longer null which (if null checks are being performed in the methods of the super class) can result in a crash (I guess technically undefined behaviour).
Here's a minimal example:
#include <iostream>

inline bool pointerIsNotNull(const void* ptr) { return ptr != nullptr; }

class IntValue {
    public:
        IntValue() { }
        int getIntValue() { return pointerIsNotNull(this) ? value : 0; }
    private:
        int value;
};

static const char* nullptrChar = "nullptr";

class CharValue {
    public:
        CharValue() { }
        const char* getCharValue() { return pointerIsNotNull(this) ? value : nullptrChar; }
    private:
        char* value;
};

class Foo : public IntValue, public CharValue {
    public:
        Foo() { }
        double getDoubleValue() { return pointerIsNotNull(this) ? value : 0; }
    protected:
        double value;
};

int main(int argc, const char * argv[])
{
    Foo* foo = nullptr;

    std::cout << foo->getIntValue() << std::endl;

    CharValue* charValue = foo;
    std::cout << charValue->getCharValue() << std::endl;

    std::cout << foo->getCharValue() << std::endl;
}

My question is this:
Is there a way to check for this kind of shenanigans without manually checking for nullptr before calls into a second superclass?
You know, is there an elegant way to do this (maybe in the second superclass) which would assure me that I've caught all possible examples of this behaviour?
EDIT: Yes, I know calling member functions from a nullptr isn't modern practice. I thought (until I posted this question) that it used to be accepted practice and in any case I'm constrained by standards I don't have control over. So, with the assumption that calling a member function on a nullptr will always enter the correct function, is there an elegant solution to my problem?

A: foo->getIntValue() is undefined when foo is the null pointer, which makes your entire program undefined.
That is, the dereferencing itself is undefined, and your program is doomed before it reaches the check.
There is no point in checking whether this is null, since a compiler is free to assume that it isn't (if it were, the program would be undefined, so the compiler can do whatever it wants).


text:
Q: Help with optimization of Reduce/Solve function I have a set of vectors in $3$D  as shown below,
v1 = {1, 1, 1}/Sqrt[3];
v2 = {1, -1, -1}/Sqrt[3];
v3 = {-1, 1, -1}/Sqrt[3];
v4 = {-1, -1, 1}/Sqrt[3];
r1 = a1 v1 + a2 v2 + a3 v3;
r2 = b1 v1 + b2 v2 + b3 v3;
r3 = c1 v1 + c2 v2 + c3 v3;
r4 = d1 v1 + d2 v2 + d3 v3;

Based on some constraints on these vectors, I obtained the values for a1,a2,...,d2,d3, in terms of other variables t11,...,t24.(The relations are given at the end of this question.)
Now, given W,
W = 1/2 (Sqrt[Dot[r1 + r2 - r3 - r4, r1 + r2 - r3 - r4]] +
 Sqrt[Dot[r1 - r2 + r3 - r4, r1 - r2 + r3 - r4]] +
 Sqrt[Dot[r1 - r2 - r3 + r4, r1 - r2 - r3 + r4]] -
 1/2 (4 + r1 . v1 + r2 . v2 + r3 . v3 + r4 . v4));

I want to evaluate the following expression,
Reduce[{D[W, t11] == 0, D[W, t12] == 0, D[W, t22] == 0,
D[W, t13] == 0, D[W, t23] == 0, D[W, t14] == 0,
D[W, t24] == 0}, {t11, t12, t22, t13, t23, t14, t24}]

This is taking too long to compute in my system. Is there any known way to optimize this problem?
Here are the relations between the variables a1,a2,...,d2,d3, and  t11,...,t24
 a1 = t11 - 1/12 Sqrt[24 - 27 t11^2 - 18 t11 t21 - 27 t21^2] +
      1/8 (t11 + 3 t21 - 1/3 Sqrt[24 - 27 t11^2 - 18 t11 t21 -
      27 t21^2]);
 a2 = 3/8 (t11 + 3 t21 -
      1/3 Sqrt[24 - 27 t11^2 - 18 t11 t21 - 27 t21^2]);
 a3 = -(1/4) Sqrt[24 - 27 t11^2 - 18 t11 t21 - 27 t21^2];
 b1 = t12 - 1/12 Sqrt[24 - 27 t12^2 - 18 t12 t22 - 27 t22^2] +
      1/8 (t12 + 3 t22 - 1/3 Sqrt[24 - 27 t12^2 - 18 t12 t22 -
      27 t22^2]);
 b2 = 3/8 (t12 + 3 t22 -
      1/3 Sqrt[24 - 27 t12^2 - 18 t12 t22 - 27 t22^2]);
 b3 = -(1/4) Sqrt[24 - 27 t12^2 - 18 t12 t22 - 27 t22^2];
 c1 = t13 - 1/12 Sqrt[24 - 27 t13^2 - 18 t13 t23 - 27 t23^2] +
      1/8 (t13 + 3 t23 -
      1/3 Sqrt[24 - 27 t13^2 - 18 t13 t23 - 27 t23^2]);
 c2 = 3/8 (t13 + 3 t23 -
      1/3 Sqrt[24 - 27 t13^2 - 18 t13 t23 - 27 t23^2]);
 c3 = -(1/4) Sqrt[24 - 27 t13^2 - 18 t13 t23 - 27 t23^2];
 d1 = t14 - 1/12 Sqrt[24 - 27 t14^2 - 18 t14 t24 - 27 t24^2] +
      1/8 (t14 + 3 t24 - 1/3 Sqrt[24 - 27 t14^2 - 18 t14 t24 -
      27 t24^2]);
 d2 = 3/8 (t14 + 3 t24 -
      1/3 Sqrt[24 - 27 t14^2 - 18 t14 t24 - 27 t24^2]);
 d3 = -(1/4) Sqrt[24 - 27 t14^2 - 18 t14 t24 - 27 t24^2];

All the variables are real. Also note that I'm taking derivative of W w.r.t every variable of the form tij except t21 and setting them to zero. I'm tryin
g to find the extreme values of W in terms of those variables. I've also tried fixing t21 before the Reduce operation, with no luck. I have also tried this with Solve.
Any help is appreciated!

A: Instead of looking for a zero of the derivatives, you could minimize/maximize your function W numerically.
I've extracted the constraints for making all intermediate variables real:
With[{T21 = 0.3},
  NMinimize[{W,
             t11^2 <= 1 && t12^2 <= 1 && t22^2 <= 1 &
             t13^2 <= 1 && t23^2 <= 1 && t14^2 <= 1 &&
             t24^2 <= 1 &&
             3 t11^2 + 2 t11 t21 + 3 t21^2 <= 8/3 &&
             3 t12^2 + 2 t12 t22 + 3 t22^2 <= 8/3 &&
             3 t13^2 + 2 t13 t23 + 3 t23^2 <= 8/3 &&
             3 t14^2 + 2 t14 t24 + 3 t24^2 <= 8/3} /. t21 -> T21,
            {t11, t12, t22, t13, t23, t14, t24},
            Method -> "RandomSearch"]]

(*    {-1., {t11 -> -0.168568,
             t12 -> -0.168568, t22 -> 0.3,
             t13 -> -0.168568, t23 -> 0.3,
             t14 -> -0.168568, t24 -> 0.3}}    *)

This minimum looks very symmetric and can be a starting point for an analytic search, where $t_{11}=t_{12}=t_{13}=t_{14}$ and $t_{21}=t_{22}=t_{23}=t_{24}$.


text:
Q: Adding new Main Menu object to project in Xcode 4 If I delete Main Menu object in MainMenu.xib for whatever reason, is it possible to recreate it?
I have tried to add Menu object, but unfortunately I cannot make it main menu. Meaning, it is there, I can add menu items, but only in one column and I cannot add other Menus - columns. It doesn't appear visually above in the IB window as well....
Anybody knows?
I have Xcode 4.2, Lion 10.7.2 installed.

A: If found a solution for XCode 6.2:

*

*Create a Menu in your MainMenu.xib (or whatever you main xib-file is)

*Add the default "Application Menu Item" and the "Edit Menu Item" from the object library.

*Save and close XCode

*Locate your menu's XIB file in finder and open it with your favorite text editor. It should be XML

*find the line with "Main Menu". It should look like

<menu title="Main Menu" id="AYu-sK-qS6">

*Add a systemMenu="main" property. Your XML should look like

<menu title="Main Menu" systemMenu="main" id="AYu-sK-qS6">

*Save the XIB and re-open XCode. Your MenuBar should be back.

A: I couldn't figure this out either. I deleted the menubar to make a menubar-only app, but it turns out you need to have an (invisible) menubar to use any keyboard shortcuts. So I had to get the menubar back.
I ended up creating a new Xcode project, selecting the (automatically created) menubar there, copying it, and pasting it into my original project.
You have to clean up a few things, but you are able to paste the menubar. That's the only way I could get it back.
NOTE: This may break the connections between the menubar items and their actions. I had to go re-hook-up the Edit > Copy menu item, for example, to the App Delegate's "Copy" action.

A: I had the very same problem. The solution for me was to tell XCode inside my projects Info.plist which nib file to load as the base nib. So just create a new Menu.xib and change the 'Main nib file base name' property inside the info.plist to the name of your Menu.xib file. So if your Menu.xib files name is 'mainMenu.xib', change 'Main nib file base name' property to 'mainMenu'.


text:
Q: How to detect page removal and show confirmation dialog before page remove from the stack in flutter I want to show confirmation dialog on page removal if user say yes then pop the page or else user stay in same page.
I have bottom navigation bar and on press on any icon it will take the user to respective page but I want to notify the user on leaving the page
Thank you.


text:
Q: Why will `np.savetxt` work with file inside `with`, but not outside? Can anyone shed some light on why this example works:
import numpy as np

def write_data(fn, var):
    with open(fn, 'wb') as fout:
        header = 'TEST\n'
        np.savetxt(fout, var, fmt='%.2f', header=header, delimiter=' ', comments='')

data = np.asarray([[1.0, 2.0], [3.0, 4.0]])
out_file = 'out/test.txt'
write_data(out_file, data)

But it stops working if you change write_data to:
def write_data(fn, var):
    fout = open(fn, 'wb')
    header = 'TEST\n'
    np.savetxt(fout, var, fmt='%.2f', header=header, delimiter=' ', comments='')

I would not want to write the code as shown below, but someone came to me asking why this code does not work and I simply have no answer for them. In the top case, a file is written with the expected header and data, but in the bottom case, a file is created, but it is empty. No errors are reported, no exceptions are thrown.
Oddly, in the original case (which was much longer), printing the var would also cause the non-with example to start working, which makes me think this may be a timing issue, as printing the var in the example as shown makes no difference on my machine.
It's been pointed out that both these examples also fix the issue:
def write_data(fn, var):
    fout = open(fn, 'wb')
    header = 'TEST\n'
    np.savetxt(fout, var, fmt='%.2f', header=header, delimiter=' ', comments='')
    fout.close()

def write_data(fn, var):
    fout = open(fn, 'wb', buffering=0)
    header = 'TEST\n'
    np.savetxt(fout, var, fmt='%.2f', header=header, delimiter=' ', comments='')

But that serves to narrow down the question to: why does Python not flush file handles that are dereferenced and what causes a file buffer to get flushed, since apparently performing some other operation can cause this to happen automatically?
For example, the example below caused the problem to get 'solved', or rather circumvented in the original problem as it was brought to me (with a lot of added code not relevant to the problem).
def write_data(fn, var):
    fout = open(fn, 'wb')
    header = 'TEST\n'
    print(var)
    np.savetxt(fout, var, fmt='%.2f', header=header, delimiter=' ', comments='')

A: I guess you should close the open file:
def write_data(fn, var):
    fout = open(fn, 'wb')
    header = 'TEST\n'
    np.savetxt(fout, var, fmt='%.2f', header=header, delimiter=' ', comments='')
    fout.close()


text:
Q: Flex justify-content center and left/right align items Need some help please.
Using Bootstrap 5 and I'm trying to achieve this layout alignment:

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Hello, world!</title>

        1 of 3

        <svg viewBox="0 0 360 640" class="h-100" fill="none" xmlns="http://www.w3.org/2000/svg">
          <rect width="360" height="640" fill="#9E3D3D" />
          <path d="M77.3438 279.34H55.1602V297.48H80.9297V303H48.4102V251.812H80.5781V257.367H55.1602V273.82H77.3438V279.34ZM101.074 278.848L109.512 264.961H117.105L104.66 283.77L117.492 303H109.969L101.18 288.762L92.3906 303H84.832L97.6641 283.77L85.2188 264.961H92.7422L101.074 278.848ZM147.516 303C147.141 302.25 146.836 300.914 146.602 298.992C143.578 302.133 139.969 303.703 135.773 303.703C132.023 303.703 128.941 302.648 126.527 300.539C124.137 298.406 122.941 295.711 122.941 292.453C122.941 288.492 124.441 285.422 127.441 283.242C130.465 281.039 134.707 279.938 140.168 279.938H146.496V276.949C146.496 274.676 145.816 272.871 144.457 271.535C143.098 270.176 141.094 269.496 138.445 269.496C136.125 269.496 134.18 270.082 132.609 271.254C131.039 272.426 130.254 273.844 130.254 275.508H123.715C123.715 273.609 124.383 271.781 125.719 270.023C127.078 268.242 128.906 266.836 131.203 265.805C133.523 264.773 136.066 264.258 138.832 264.258C143.215 264.258 146.648 265.359 149.133 267.562C151.617 269.742 152.906 272.754 153 276.598V294.105C153 297.598 153.445 300.375 154.336 302.438V303H147.516ZM136.723 298.043C138.762 298.043 140.695 297.516 142.523 296.461C144.352 295.406 145.676 294.035 146.496 292.348V284.543H141.398C133.43 284.543 129.445 286.875 129.445 291.539C129.445 293.578 130.125 295.172 131.484 296.32C132.844 297.469 134.59 298.043 136.723 298.043ZM169.312 264.961L169.488 269.18C172.277 265.898 176.039 264.258 180.773 264.258C186.094 264.258 189.715 266.297 191.637 270.375C192.902 268.547 194.543 267.07 196.559 265.945C198.598 264.82 201 264.258 203.766 264.258C212.109 264.258 216.352 268.676 216.492 277.512V303H209.988V277.898C209.988 275.18 209.367 273.152 208.125 271.816C206.883 270.457 204.797 269.777 201.867 269.777C199.453 269.777 197.449 270.504 195.855 271.957C194.262 273.387 193.336 275.32 193.078 277.758V303H186.539V278.074C186.539 272.543 183.832 269.777 178.418 269.777C174.152 269.777 171.234 271.594 169.664 275.227V303H163.16V264.961H169.312ZM258.469 284.402C258.469 290.191 257.145 294.855 254.496 298.395C251.848 301.934 248.262 303.703 243.738 303.703C239.121 303.703 235.488 302.238 232.84 299.309V317.625H226.336V264.961H232.277L232.594 269.18C235.242 265.898 238.922 264.258 243.633 264.258C248.203 264.258 251.812 265.98 254.461 269.426C257.133 272.871 258.469 277.664 258.469 283.805V284.402ZM251.965 283.664C251.965 279.375 251.051 275.988 249.223 273.504C247.395 271.02 244.887 269.777 241.699 269.777C237.762 269.777 234.809 271.523 232.84 275.016V293.191C234.785 296.66 237.762 298.395 241.77 298.395C244.887 298.395 247.359 297.164 249.188 294.703C251.039 292.219 251.965 288.539 251.965 283.664ZM273.832 303H267.328V249H273.832V303ZM300.059 303.703C294.902 303.703 290.707 302.016 287.473 298.641C284.238 295.242 282.621 290.707 282.621 285.035V283.84C282.621 280.066 283.336 276.703 284.766 273.75C286.219 270.773 288.234 268.453 290.812 266.789C293.414 265.102 296.227 264.258 299.25 264.258C304.195 264.258 308.039 265.887 310.781 269.145C313.523 272.402 314.895 277.066 314.895 283.137V285.844H289.125C289.219 289.594 290.309 292.629 292.395 294.949C294.504 297.246 297.176 298.395 300.41 298.395C302.707 298.395 304.652 297.926 306.246 296.988C307.84 296.051 309.234 294.809 310.43 293.262L314.402 296.355C311.215 301.254 306.434 303.703 300.059 303.703ZM299.25 269.602C296.625 269.602 294.422 270.562 292.641 272.484C290.859 274.383 289.758 277.055 289.336 280.5H308.391V280.008C308.203 276.703 307.312 274.148 305.719 272.344C304.125 270.516 301.969 269.602 299.25 269.602ZM152.859 341.367H136.406V387H129.691V341.367H113.273V335.812H152.859V341.367ZM171.703 387.703C166.547 387.703 162.352 386.016 159.117 382.641C155.883 379.242 154.266 374.707 154.266 369.035V367.84C154.266 364.066 154.98 360.703 156.41 357.75C157.863 354.773 159.879 352.453 162.457 350.789C165.059 349.102 167.871 348.258 170.895 348.258C175.84 348.258 179.684 349.887 182.426 353.145C185.168 356.402 186.539 361.066 186.539 367.137V369.844H160.77C160.863 373.594 161.953 376.629 164.039 378.949C166.148 381.246 168.82 382.395 172.055 382.395C174.352 382.395 176.297 381.926 177.891 380.988C179.484 380.051 180.879 378.809 182.074 377.262L186.047 380.355C182.859 385.254 178.078 387.703 171.703 387.703ZM170.895 353.602C168.27 353.602 166.066 354.562 164.285 356.484C162.504 358.383 161.402 361.055 160.98 364.5H180.035V364.008C179.848 360.703 178.957 358.148 177.363 356.344C175.77 354.516 173.613 353.602 170.895 353.602ZM206.859 362.848L215.297 348.961H222.891L210.445 367.77L223.277 387H215.754L206.965 372.762L198.176 387H190.617L203.449 367.77L191.004 348.961H198.527L206.859 362.848ZM238.641 339.75V348.961H245.742V353.988H238.641V377.578C238.641 379.102 238.957 380.25 239.59 381.023C240.223 381.773 241.301 382.148 242.824 382.148C243.574 382.148 244.605 382.008 245.918 381.727V387C244.207 387.469 242.543 387.703 240.926 387.703C238.02 387.703 235.828 386.824 234.352 385.066C232.875 383.309 232.137 380.812 232.137 377.578V353.988H225.211V348.961H232.137V339.75H238.641Z" fill="white" />
        </svg>

        3 of 3

text1 text1 text1

text2 text2 text2

Basically, there 5 divs: 3 main columns and then 2 divs wrapped underneath.
I want the 3 main divs to be centered and then the 2 divs underneath to be left and right aligned to the edge of the first and third columns respectively (as per image).
I can achieve the desired effect by changing justify-content-md-center to justify-content-md-between but that adds a gap between the columns, and I don't want this as the 3 main columns need to be centered.
I've tried to adding align-self-end and align-self-start to the bottom divs but that doesn't do anything.
Thanks for the help.

A: Change justify-content-md-center to justify-content-center

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Hello, world!</title>

        1 of 3

        <svg viewBox="0 0 360 640" class="h-100" fill="none" xmlns="http://www.w3.org/2000/svg">
          <rect width="360" height="640" fill="#9E3D3D" />
          <path d="M77.3438 279.34H55.1602V297.48H80.9297V303H48.4102V251.812H80.5781V257.367H55.1602V273.82H77.3438V279.34ZM101.074 278.848L109.512 264.961H117.105L104.66 283.77L117.492 303H109.969L101.18 288.762L92.3906 303H84.832L97.6641 283.77L85.2188 264.961H92.7422L101.074 278.848ZM147.516 303C147.141 302.25 146.836 300.914 146.602 298.992C143.578 302.133 139.969 303.703 135.773 303.703C132.023 303.703 128.941 302.648 126.527 300.539C124.137 298.406 122.941 295.711 122.941 292.453C122.941 288.492 124.441 285.422 127.441 283.242C130.465 281.039 134.707 279.938 140.168 279.938H146.496V276.949C146.496 274.676 145.816 272.871 144.457 271.535C143.098 270.176 141.094 269.496 138.445 269.496C136.125 269.496 134.18 270.082 132.609 271.254C131.039 272.426 130.254 273.844 130.254 275.508H123.715C123.715 273.609 124.383 271.781 125.719 270.023C127.078 268.242 128.906 266.836 131.203 265.805C133.523 264.773 136.066 264.258 138.832 264.258C143.215 264.258 146.648 265.359 149.133 267.562C151.617 269.742 152.906 272.754 153 276.598V294.105C153 297.598 153.445 300.375 154.336 302.438V303H147.516ZM136.723 298.043C138.762 298.043 140.695 297.516 142.523 296.461C144.352 295.406 145.676 294.035 146.496 292.348V284.543H141.398C133.43 284.543 129.445 286.875 129.445 291.539C129.445 293.578 130.125 295.172 131.484 296.32C132.844 297.469 134.59 298.043 136.723 298.043ZM169.312 264.961L169.488 269.18C172.277 265.898 176.039 264.258 180.773 264.258C186.094 264.258 189.715 266.297 191.637 270.375C192.902 268.547 194.543 267.07 196.559 265.945C198.598 264.82 201 264.258 203.766 264.258C212.109 264.258 216.352 268.676 216.492 277.512V303H209.988V277.898C209.988 275.18 209.367 273.152 208.125 271.816C206.883 270.457 204.797 269.777 201.867 269.777C199.453 269.777 197.449 270.504 195.855 271.957C194.262 273.387 193.336 275.32 193.078 277.758V303H186.539V278.074C186.539 272.543 183.832 269.777 178.418 269.777C174.152 269.777 171.234 271.594 169.664 275.227V303H163.16V264.961H169.312ZM258.469 284.402C258.469 290.191 257.145 294.855 254.496 298.395C251.848 301.934 248.262 303.703 243.738 303.703C239.121 303.703 235.488 302.238 232.84 299.309V317.625H226.336V264.961H232.277L232.594 269.18C235.242 265.898 238.922 264.258 243.633 264.258C248.203 264.258 251.812 265.98 254.461 269.426C257.133 272.871 258.469 277.664 258.469 283.805V284.402ZM251.965 283.664C251.965 279.375 251.051 275.988 249.223 273.504C247.395 271.02 244.887 269.777 241.699 269.777C237.762 269.777 234.809 271.523 232.84 275.016V293.191C234.785 296.66 237.762 298.395 241.77 298.395C244.887 298.395 247.359 297.164 249.188 294.703C251.039 292.219 251.965 288.539 251.965 283.664ZM273.832 303H267.328V249H273.832V303ZM300.059 303.703C294.902 303.703 290.707 302.016 287.473 298.641C284.238 295.242 282.621 290.707 282.621 285.035V283.84C282.621 280.066 283.336 276.703 284.766 273.75C286.219 270.773 288.234 268.453 290.812 266.789C293.414 265.102 296.227 264.258 299.25 264.258C304.195 264.258 308.039 265.887 310.781 269.145C313.523 272.402 314.895 277.066 314.895 283.137V285.844H289.125C289.219 289.594 290.309 292.629 292.395 294.949C294.504 297.246 297.176 298.395 300.41 298.395C302.707 298.395 304.652 297.926 306.246 296.988C307.84 296.051 309.234 294.809 310.43 293.262L314.402 296.355C311.215 301.254 306.434 303.703 300.059 303.703ZM299.25 269.602C296.625 269.602 294.422 270.562 292.641 272.484C290.859 274.383 289.758 277.055 289.336 280.5H308.391V280.008C308.203 276.703 307.312 274.148 305.719 272.344C304.125 270.516 301.969 269.602 299.25 269.602ZM152.859 341.367H136.406V387H129.691V341.367H113.273V335.812H152.859V341.367ZM171.703 387.703C166.547 387.703 162.352 386.016 159.117 382.641C155.883 379.242 154.266 374.707 154.266 369.035V367.84C154.266 364.066 154.98 360.703 156.41 357.75C157.863 354.773 159.879 352.453 162.457 350.789C165.059 349.102 167.871 348.258 170.895 348.258C175.84 348.258 179.684 349.887 182.426 353.145C185.168 356.402 186.539 361.066 186.539 367.137V369.844H160.77C160.863 373.594 161.953 376.629 164.039 378.949C166.148 381.246 168.82 382.395 172.055 382.395C174.352 382.395 176.297 381.926 177.891 380.988C179.484 380.051 180.879 378.809 182.074 377.262L186.047 380.355C182.859 385.254 178.078 387.703 171.703 387.703ZM170.895 353.602C168.27 353.602 166.066 354.562 164.285 356.484C162.504 358.383 161.402 361.055 160.98 364.5H180.035V364.008C179.848 360.703 178.957 358.148 177.363 356.344C175.77 354.516 173.613 353.602 170.895 353.602ZM206.859 362.848L215.297 348.961H222.891L210.445 367.77L223.277 387H215.754L206.965 372.762L198.176 387H190.617L203.449 367.77L191.004 348.961H198.527L206.859 362.848ZM238.641 339.75V348.961H245.742V353.988H238.641V377.578C238.641 379.102 238.957 380.25 239.59 381.023C240.223 381.773 241.301 382.148 242.824 382.148C243.574 382.148 244.605 382.008 245.918 381.727V387C244.207 387.469 242.543 387.703 240.926 387.703C238.02 387.703 235.828 386.824 234.352 385.066C232.875 383.309 232.137 380.812 232.137 377.578V353.988H225.211V348.961H232.137V339.75H238.641Z" fill="white" />
        </svg>

        3 of 3

text1 text1 text1

text2 text2 text2

A: You'd need to separate the rows and treat the second as a flex.

*

*Remove the col-auto from both the elements.

*Enclose in a d-flex accompanied with justify-content-between as you were trying to.

*Add a px-0 to remove any padding from the side.

View here: JSFiddle Is this what you are looking for?


text:
Q: How do I convert a ResultSet in a List of Hashtable? Well, that must be an easy one but I can't find the solution anywhere. And I am still not enough comfortable using Java to figure out the way to do it.
So far, I am able to loop through a ResultSet and I'm quite proud of myself already.
I would like a List so I could simply loop through it and then call something like myRow.get('ColumnName');.
Also, there MIGHT another data type instead of a Hashtable to store the key/value. Any tips?
Thank you very much!

A: myRow.get('ColumnName'); is already in ResultSet, see getObject(String columnLabel). Now, one difference between ResultSet and Map is that a ResultSet is not (always) random access. Once you go past a row, using ResultSet.next(), it may not allow you to "rewind" to the previous row. There is good reason for this: the number of elements in ReusltSet can be arbitrarily large and the memory requirement on a list of map would be prohibitive.
If you do decide to convert it to a List<Map<String, Object>> then you should create your own implementation of both the List and the Map, such that a Map<String /*columnName*/, Integer /*Index*/> is gives the index of a column-name in each array. I am speaking from experience, I had to change an implementation where a iterating through list of column names was too expensive.

A: I would use HashMap. Hashtable is old school...
Example:
HashMap<String, Object> p = new HashMap<String, Object>();
p.put("ResultSetkey1","ResultSetvalue1");
p.put("ResultSetkey2","ResultSetvalue2");

A: what I understand it would be something like this:
LinkedList<HashTable<String,String>> list = new LinkedList<>();

while(rs.next()){
    Hashtable<String, String> currentRowMap = new Hashtable<>();

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    for (int i = 1; i <= columnCount; i++) {
        // retrieves column name and value.
        String key = rsmd.getColumnLabel(i);
        String value = rs.getString(rsmd.getColumnName(i));
        if (value == null) {
            value = "null";
        }
        // builds map.
        currentRowMap .put(key, value);
    }
    list.add(currentRowMap);
}

return list;


text:
Q: Partially convert to grayscale using AForge? Converting a bitmap to grayscale is pretty easy with AForge:
public static Bitmap ConvertToGrayScale(this Bitmap me)
{
     if (me == null)
         return null;

     // first convert to a grey scale image
     var filterGreyScale = new Grayscale(0.2125, 0.7154, 0.0721);

     me = filterGreyScale.Apply(me);
     return me;
}

But I need something more tricky:
Imagine you want to convert everything to grayscale except for a circle in the middle of the bitmap. In other words: a circle in the middle of the given bitmap should keep its original colours.
Let's assume the radius of the circle is 20px, how should I approach this?

A: This can be accomplished using MaskedFilter with a mask that defines the circled area you describe. As the documentation states

Mask can be specified as .NET's managed Bitmap, as UnmanagedImage or
  as byte array. In the case if mask is specified as image, it must be 8
  bpp grayscale image. In all case mask size must be the same as size of
  the image to process.

So the mask image has to be generated based on the source image's width and height.
I haven't compiled the following code but it should get you on your way. If the circle is always in the same spot, you could generate the image mask outside the method so that it doesn't have to be regenerated each time you apply the filter. Actually you could have the whole MaskedFilter generated outside the method that applies it if nothing changes but the source image.
public static Bitmap ConvertToGrayScale(this Bitmap me)
{
     if (me == null)
         return null;

     var radius = 20, x = me.Width / 2, y = me.Height / 2;

     using (Bitmap maskImage = new Bitmap(me.Width, me.Height, PixelFormat.Format8bppIndexed))
     {
        using (Graphics g = Graphics.FromImage(maskImage))
           using (Brush b = new SolidBrush(ColorTranslator.FromHtml("#00000000")))
              g.FillEllipse(b, x, y, radius, radius);

        var maskedFilter = new MaskedFilter(new Grayscale(0.2125, 0.7154, 0.0721), maskImage);

        return maskedFilter.Apply(me);
     }
}

EDIT
The solution for this turned out to be a lot more trickier than I expected. The main problem was that the MaskedFilter doesn't allow the usage of filters that change the images format, which the Grayscale filter does (it changes the source to an 8bpp or 16 bpp image).
The following is the resulting code, which I have tested, with comments added to each part of the ConvertToGrayScale method explaining the logic behind it. The gray-scaled portion of the image has to be converted back to RGB since the Merge filter doesn't support merging two images with different formats.
static class MaskedImage
{
    public static void DrawCircle(byte[,] img, int x, int y, int radius, byte val)
    {
        int west = Math.Max(0, x - radius),
            east = Math.Min(x + radius, img.GetLength(1)),
            north = Math.Max(0, y - radius),
            south = Math.Min(y + radius, img.GetLength(0));

        for (int i = north; i < south; i++)
            for (int j = west; j < east; j++)
            {
                int dx = i - y;
                int dy = j - x;
                if (Math.Sqrt(dx * dx + dy * dy) < radius)
                    img[i, j] = val;
            }
    }

    public static void Initialize(byte[,] arr, byte val)
    {
        for (int i = 0; i < arr.GetLength(0); i++)
            for (int j = 0; j < arr.GetLength(1); j++)
                arr[i, j] = val;
    }

    public static void Invert(byte[,] arr)
    {
        for (int i = 0; i < arr.GetLength(0); i++)
            for (int j = 0; j < arr.GetLength(1); j++)
                arr[i, j] = (byte)~arr[i, j];
    }

    public static Bitmap ConvertToGrayScale(this Bitmap me)
    {
        if (me == null)
            return null;

        int radius = 20, x = me.Width / 2, y = me.Height / 2;
        // Generate a two-dimensional `byte` array that has the same size as the source image, which will be used as the mask.
        byte[,] mask = new byte[me.Height, me.Width];
        // Initialize all its elements to the value 0xFF (255 in decimal).
        Initialize(mask, 0xFF);
        // "Draw" a circle in the `byte` array setting the positions inside the circle with the value 0.
        DrawCircle(mask, x, y, radius, 0);

        var grayFilter = new Grayscale(0.2125, 0.7154, 0.0721);
        var rgbFilter = new GrayscaleToRGB();
        var maskFilter = new ApplyMask(mask);
        // Apply the `Grayscale` filter to everything outside the circle, convert the resulting image back to RGB
        Bitmap img = rgbFilter.Apply(grayFilter.Apply(maskFilter.Apply(me)));
        // Invert the mask
        Invert(mask);
        // Get only the cirle in color from the original image
        Bitmap circleImg = new ApplyMask(mask).Apply(me);
        // Merge both the grayscaled part of the image and the circle in color in a single one.
        return new Merge(img).Apply(circleImg);
    }
}


text:
Q: fsockopen timing out due to no new line being added to reply The string that is returned back from server does not contain a new line. What would be a better method or replace fgets since also the string length is not known until the data is received.
At the moment im using 200 character count but this is truncating the full string. When the # is exceeded we are presented with internal server 500.
$fp = fsockopen("IP Address", 2000, $errno, $errstr, 20);

if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, 'String of Data');

    while (!feof($fp)) {
        echo fgets($fp, 200);
    }
    fclose($fp);
}


text:
Q: Does "$\lnot P$" mean "$P$ is false"? Or not? ( syntax versus semantics) [ edited 11th april 2019]
Does the distinction between syntax and semantics imply that ( rigorously) the negation of P should not be read as " P is false"?
I'll try by the following comments to explain why the question is not off-topic from my point of view.
It can be argued that logical operators have a syntactic side and a semantic side.
From a syntactic point of view , the negation operator is simply ( if I am correct) a function from the set of wff to the set of wff. So the expression "~P" does not refer to the truth value of P, it only refers to  the image of the proposition symbol P under the function  " ~ "  ( that is , the function : negation).
But  from a semantic point of view, the negation operator is a function from {T,F} to {T,F}, namely the function { (T,F), (F,T) }.
So could one say that, at least from a semantic point of view, "  ~ P " could be read as " P is false" ?
Or is this reading absolutely erroneous, as not taking into account the strict distinction between syntax and semantics?
Let me add an example.
Does the formula (P --> ~P) rigorouly mean that " P is false" ? I think it would be more correct to say that the formula only means " not-P". So there would be a difference between " not-P" and "P is false".

A: If $P$ is false, then $\lnot P$ is true; if $P$ is true, then $\lnot P$ is false. It is the negation of $P$, whatever truth value $P$ might have, so perhaps that's where the confusion lies.


text:
Q: Transparent background for SWFLoader I created a "Loading" spinner in a SWF.  I display this spinner in my main application SWF using SWFLoader.  How do I make the SWFLoader transparent?  Currently it uses Flex's default background color even though I've set backgroundAlpha="0".
My spinner SWF's main MXML: (Note the use of backgroundAlpha)
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:Controls="Controls.*" width="30" height="30" backgroundAlpha="0">
    <Controls:Spinner id="ctrlSpinner" />  <!-- spinner logic encapsulated in a component -->
</mx:Application>

My application SWF's main MXML:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" height="801">
    <mx:SWFLoader x="10" y="173" id="swfSpinner" autoLoad="true" scaleContent="true" >
        <mx:source>SWFs/LoadingSpinnerApp.swf</mx:source>
    </mx:SWFLoader>
</mx:Application>

Note that the Spinner control itself is transparent.  There's just something about the SWFLoader that causes it to ignore my backgroundAlpha setting.  Any ideas?

A: I think your problem is within the Spinner component you must be setting the background color or alpha in there and that's causing your loader to have a background color.  if you not setting it then set it because it probably defaults to an alpha of 1.  when I do the following I don't get any background but when I change the alpha to 1 the black background appears.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" backgroundAlpha="1"
backgroundColor="#000000">
    <mx:Text id="textBox" text="Hey World"/>
</mx:Application>

and
<?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" backgroundColor="#ffffff">

    <mx:Canvas backgroundColor="#ff0000" width="200"
height="200" verticalCenter="0" horizontalCenter="0">
        <mx:SWFLoader x="10" y="173" id="swfSpinner"
autoLoad="true" scaleContent="true" source="DebuggerTest.swf"/>
    </mx:Canvas>

    </mx:Application>

A: It turns out that I was doing the correct thing -- Flex just wasn't copying the latest version of my spinner SWF to the bin of my main app.  Instead it had been holding on to a previous version built before I added the transparency.
I manually copied the new spinner SWF to the main app's bin and then it worked!


text:
Q: jQuery, how to test of a variable is a text node, containing no markup? http://jsfiddle.net/DerNalia/zrppg/8/
I have two lines of code that pretty much do the same thing
var doesntbreak = $j("hello");
var breaks = $j(" ");

The first one doesn't error, but the second one throws this
  Syntax error, unrecognized expression:

should'nt they both behave the same?
any insight as to how to solve this?
in the actual method I'm using, ele is from the Dom, so it could eb a text node, or any other kind of node.
UPDATE:
the input to the function that I'm using that I noticed this takes selection from the dom.
updated example: http://jsfiddle.net/DerNalia/zrppg/11/ <- includes html markup.
So, I guess, my question is, how do I test if something is JUST a text node? and doesn't contain any markup?

A: In general, you cannot create standalone text nodes with the jQuery function. If a string isn't obviously HTML, it gets treated as a selector, and   is not recognized by jQuery as a valid selector.
Assuming you want to parse arbitrary strings (which may have HTML tags or not), I suggest something like var result = $('

').html(' ').contents();. Place your your HTML or text string in a div to parse it and then immediately extract the parsed result as a jQuery object with the list of elements.  You can append the resultant list of elements with $(parentElem).append(result);

A: try this:
function isTextNode(node){
    div=document.createElement('div');
    div.innerHTML=node;
    return $(div).text()==$(div).html();
}

And " " is'nt a valid selector if you want to find a elements containing some text you must use the :contains selector http://api.jquery.com/contains-selector/

A: Internet Explorer (older versions at least) don't have built in "querySelector" functions, so the Sizzle engine has to do the work directly. Thus, the slightly different tolerances for bogus input can cause differences in error reporting.
Your selector expression " " is equally invalid in all browsers, however. The library is not obliged to quietly accept anything you pass it, so perhaps you should reconsider your application design.
If you want to check for entities, you could use a regular expression if you're confident that it's just a text node. Or you could get the contents with .text() instead of .html().

A: So, I have to thank Apsillers and Rolando for pointing me in the right direction. Their answers were very close, but gave me the information I needed.
This is what I ended up using:
TEXT_NODE = 3;
objectify = function(n) {
    return $j("

").html(n).contents();
}

function textOnly(n) {
    var o = objectify(n);
    for (var i = 0; i < o.length; i++) {
        if (objectify(o[i])[0].nodeType != TEXT_NODE) {
            return false
        }
    }
    return true;
}

And here is a jsFiddle with some test cases, that neither of the original code submissions passed.
to pass, it needed to handle this kind of input
"hello" // true
"hellothere" // false
"there" // false
" " // false

A: Not actual answer, but may help someone with similar issue as mine and loosely related to this question. :)
I was getting same issue today, so fixed by removing
Changed:
var breaks = $j(" ");
to:
var breaks = $j(" ".replace(/&.*;/g, ""));
Here I am removing  , < etc...
Note: value at   is dynamic for me, so it can be anything.


text:
Q: How can I call multiple number at once in Twilio using node js? I want to send my customers a pre recorded voice on call const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);

client.calls
      .create({
         twiml: '<Response><Say>Ahoy, World!</Say></Response>',
         to: '+14155551212',
         from: '+15017122661'
       })
      .then(call => console.log(call.sid));

How can I modify this to accept more than one number?

A: Twilio developer evangelist here.
You can only make one call per API request, so to make calls to more than one number you will need to loop and make a request for each number. Like so:
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);

async function makeCalls(numbers) {
  numbers.forEach(async (number) => {
    await client.calls
      .create({
         twiml: '<Response><Say>Ahoy, World!</Say></Response>',
         to: number,
         from: '+15017122661'
       })
      .then(call => console.log(call.sid));
  });
}

const numbers = []; // An array of the numbers you want to make calls to.

makeCalls(numbers);


text:
Q: Crawling youtube user info I'm trying to crawl Youtube to retrieve information about a group of users (approx. 200 people).  I'm interested in looking for relationships between the users:

*

*contacts

*subscribers

*subscriptions

*what videos they commented on

*etc

I've managed to get contact information with the following source:
import gdata.youtube
import gdata.youtube.service
from gdata.service import RequestError
from pub_author import KEY, NAME_REGEX
def get_details(name):
    yt_service = gdata.youtube.service.YouTubeService()
    yt_service.developer_key = KEY
    contact_feed = yt_service.GetYouTubeContactFeed(username=name)
    contacts = [ e.title.text for e in contact_feed.entry ]
    return contacts

I can't seem the get the other bits of information I need.  The reference guide says that I can grab the XML feed from http://gdata.youtube.com/feeds/api/users/username/subscriptions?v=2 (for some arbitrary user).  However, if I try to get other users' subscriptions, I get the a 403 error with the following message:

User must be logged in to access these subscriptions.

If I use the gdata API:
sub_feed = yt_service.GetYouTubeSubscriptionFeed(username=name)
sub = [ e.title.text for e in contact_feed.entry ]

then I get the same error.
How can I get these subscriptions without logging in?  It should be possible, as you can access this information without logging in to the Youtube web-site.
Also, there seems to be no feed for the subscribers of particular user.  Is this information available through the API?
EDIT
So, it appears this can't be done through the API.  I had to do this the quick and dirty way:
for f in `cat users.txt`; do wget "www.youtube.com/profile?user=$f&view=subscriptions" --output-document subscriptions/$f.html; done

Then use this script to get out the usernames from the downloaded HTML files:
"""Extract usernames from a Youtube profile using regex"""
import re
def main():
    import sys
    lines = open(sys.argv[1]).read().split('\n')
    #
    # The html files has two  tags for each user: once for an
    # image thumbnail, and once for a text link.
    #
    users = set()
    for l in lines:
        match = re.search('<a href="/user/(?P<name>[^"]+)" onmousedown', l)
        if match:
            users.add(match.group('name'))
    users = list(users)
    users.sort()
    print users
if __name__ == '__main__':
    main()

A: In order to access a user's subscriptions feed without the user being logged in, the user must check the "Subscribe to a channel" checkbox under his Account Sharing settings.
Currently, there is no direct way to get a channel's subscribers through the gdata API. In fact, there has been an outstanding feature request for it that has remained open for over 3 years! See Retrieving a list of a user's subscribers?.


text:
Q: Creating a Function to make cin only allow numbers #include<iostream>
#include<limits>
using namespace std;
int main()
{

    cout << "Enter an int: ";
    int x = 0;
    while(!(cin >> x))
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid input.  Try again: ";
    }
    cout << "You entered: " << x << endl;
}

I want to create a simple function out of this code.
So i did the following. But it will obviously run cin twice how do i make it so it only uses cin once?
void nInput(int x)
{

//cout << "Enter an int: ";
int y = 0;
while (!(cin >> y))
{
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "Invalid input.  Try again: ";
}
cout << "You entered: " << y << endl;
}

int main()
{
    int a;
    cout << "Enter an int:  ";
    cin >> a;
    nInput(a);
}

i tried changing the
 while (!(cin >> y))

to
 while (!(x >> y))

But it doesn't really work. Thanks in advance.

A: You are not using x inside of nInput(), so there is no point in calling cin >> a before calling nInput(), so just remove it.  If you don't want cin called twice, then don't call it twice to begin with:
int nInput()
{
    cout << "Enter an int:  ";
    int y = 0;
    while (!(cin >> y))
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid input.  Try again: ";
    }
    cout << "You entered: " << y << endl;
    return y;
}

int main()
{
    int a = nInput();
    // use a as needed...
}


text:
Q: Carousel doesn't work when Content Security Policy enabled I am using CSP and my Javascript carousel doesn't work, everything works but the carousel.
The carousels CSS is in another file and works, the Java Script is in another file also but doesn't work.
I have received no errors.
What am I doing wrong?
Thanks in advance for your time.
CSP:
<meta http-equiv="Content-Security-Policy" content="style-src 'self' https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css;
script-src 'self' https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js;
script-src 'self' https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">
Carousel html:

JavaScript file:
(function(){
    $('#carousel123').carousel({ interval: 2000 });
    $('#carouselABC').carousel({ interval: 3600 });
}());
(function(){
    $('.carousel-showsixmoveone .item').each(function(){
        var itemToClone = $(this);
        for (var i=1;i<6;i++) {
            itemToClone = itemToClone.next();
            if (!itemToClone.length) {
                itemToClone = $(this).siblings(':first');
            }
            itemToClone.children(':first-child').clone()
           .addClass("cloneditem-"+(i))
           .appendTo($(this));
        }
    });
}());

A: There cannot be multiple script-src 'self' in the code so the CSP meta will be like this:
<meta http-equiv="Content-Security-Policy" content="
style-src 'self' https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css;
script-src 'self' https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">


text:
Q: How can i organize a list whose elements are stored in a struct? Im currently working on a project (for school, yes) in which i've spent quite a few hours trying to get it to work, but now i found myself with an error that i cant seem to solve, and so i came here looking for help. The following is the code that i think is necessary, not the full code.
typedef struct
{
    int day, month, year;
} typeDate;

typedef struct
{
    int number;
    char name[20];
    char lastname[20];
    typeDate date_of_birth;
} typeCard;

typedef struct
{
    int associate_number;
    typeCard associates[MAX_ELEM];
} typeAssociation;

typeDate date;
typeCard card;
typeCard aux;

int get_data(typeAssociation association)
{
    association.associate_number = 0;

    int e, i;

    FILE* read = fopen("associados.txt", "r");

    for (i = 0; fscanf(read, "%s %s %d %d %d %d", card.name, card.lastname, &card.number,
                    &date.day, &date.month, &date.year)
         != EOF;
         i++)
    {
        association.associate_number++;
        card.date_of_birth = date;
        association.associates[i] = card;
    }
    fclose(read);

    printf("Sort list[1/2/3]?");

    scanf("%d", &e);

    if (e == 1)
    {
       ordenar_n(&associacao);
    }
    (...)
}

int sort_by_date(typeAssociation association)
{
    int g, m, i;

    for (i = 0; i < association.associate_number - 1; i++)
    {
        m = i;
        for (g = i + 1; g < data.year; g++)
        {
            if (date.year[g] < date.year[m])
            {
                m = g;
            }

            if (date.year[g] == date.year[m])
            {
                if (date.month[g] < date.month[m])
                {
                    m = g;
                }

                else if (date.month[g] == date.month[m])
                {
                    if (date.day[g] < date.day[m])
                    {
                        m = g;
                    }
                }
            }

            aux = association.associates[i];
            association.associates[i] = association.associates[m];
            association.associates[m] = aux;
        }
    }
}

on another file i have (after calling the file):
int main(void)
{
   typeAssociation association;

   get_data(association);

}

The error is in the function sort_by_date and this function is supposed to sort a list (given by associados.txt) by date (stored in the struct typeDate) (from newest member to the oldest). I think (correct me if I'm wrong) i have the general idea going, but not the code. Can anyone help me? (it's my first post so sorry for any mistakes).

My error is in the function sort_by_date.

A: You are passing typeAssociation by value. Your sort is not applying to the object passed in. Also, don't write your own sort. qsort is a library function.
int sort_by_date(typeAssociation *association)
{
    qsort(association->associates, association->associate_number, sizeof(typeCard), compare_typeCard);
}

int compare_typeCard(const void *avoid, const void *bvoid)
{
    typeCard *a = avoid;
    typeCard *b = bvoid;
    /* put your comparison code here */
}

And, you have the same pass-by-value mistake calling getAssociation.

A: You need to pass address of typeAssociation variable.
Also in your code, you are comparing array elements with some global variables which is wrong.
int sort_by_date(typeAssociation *association)
{
    int g=0, m=0, i=0;

    for (i = 0; i < association->associate_number - 2; i++)
    {
        m = i;
        for (g = i + 1; g < association->associate_number; g++)
        {
            if (association->associates[g].date.year < association->associates[m].date.year)
            {
                m = g;
            }

            else if (association->associates[g].date.year == association->associates[m].date.year)
            {
                if (association->associates[g].date.month < association->associates[m].date.month)
                {
                    m = g;
                }

                else if (association->associates[g].date.month == association->associates[m].date.month)
                {
                    if (association->associates[g].date.day < association->associates[m].date.day)
                    {
                        m = g;
                    }
                }
            }
        }

        //No need to do it in i loop
        if(i != m)
        {
            aux = association.associates[i];
            association.associates[i] = association.associates[m];
            association.associates[m] = aux;
        }
    }

    return 0; //Need to return an int value.
}


text:
Q: android activities i have 2 activities.
1-Messaging
2-fileBrowser
from MESSAGING onButtonClick i call the FILEBROWSER activity. in the FILEBROWSER activity i take the path of the selected file and put it to a interface and then call the MESSAGING activity again like this :
  Intent i = new Intent(FileBrowser.this, Messaging.class);
        i.putExtra(FriendInfo.P, path);
        System.out.println("path at fb" + path);

        startActivity(i);
        this.finish();

now when i m returned back to the MESSAGING activity everything over here is null. all the variables and everything and if i call some other methods, the arguments i pass are also null. what do i do ?

A: Try to start your Intent with StartActivityForResult(Intent intent)

A: when first time you move Messaging to FileBrowser
instead of stariActivity()

you can use StartActivityForResult()

method and at Activity FileBrowser just set result and put data in bundle then you can use this result in Messaging Activity's
onActivityResult().

Then your Messaging Activity's all variable remain same. No NULL value.
EDIT: In MessagingActivity
  Intent intent = new Intent(Messaging.this, FileExplorer.class);
            intent.putExtra("Key", value);
            startActivityForResult(intent, RESULT_OK);

and also make this method
  @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            //getting value from FileExplorer activity here
        }

 }


text:
Q: Selenium IDE - Slow is too fast I want to create tests with Selenium IDE for SharePoint 2010. I set the control in Selenium IDE to slow, but it is often to fast and the test fails because javascripts are loading etc.
Is there a way to slow down the script?

A: I had best results using functions like waitForElementPresent or waitForVisible. This way you can just wait for specific element you want to work with. For example if you click link Next and want to click Previous when page reloads, instead of writing andWait abbreviation you could use something like this:
waitForElementPresent(Previous)
click(Previous)

A: Aside from placing pause(waitTime) between your statements, I would recommend to transition the IDE scripts to Selenium RC and use the selenium.setSpeed("milliseconds"); statement (java) to control the execution speed.

A: Using pauses means your tests are going to pass while your server is under the same load but they will start failing as soon as your server is under heavier load.
You should use the clickAndWait command, which waits for the next page to load before continuing with anymore commands.

click/clickAndWait - performs a click operation, and optionally waits for a new page to load.
waitForPageToLoad - pauses execution until an expected new page loads. Called automatically when clickAndWait is used.

Reference

A: Put this after your click commands: pause(length of time in ms)
For example:
pause(1000)

This pauses for 1 second. Start with a higher value until it works, then work your way down to find the smallest possible pause.

A: You can set the speed of each step with Selenium IDE
Command    Target
setSpeed   65           (set the speed of item)
setSpeed   0            (reset the speed)


text:
Q: TortoiseSVN very slow over proxy if Windows internet explorer proxy settings are not set and using only TortoiseSVN proxy settings When I try to do any TortoiseSVN command even show log etc, it take a very LONG time for the pop-up to accept ssl certificate to show up. I can make it work quite nicely/fast if I simply go into Internet Explorer connect options and enable the PROXY settings there. But I don't want to. I want to let only TortoiseSVN use the proxy not all windows apps. TortoiseSVN is already configured in Settings/Network for the correct proxy etc and I even clicked the edit button and edited the Subversion text files as well.
Any idea why TortoiseSVN is so slow unless I also add the proxy settings into Internet Explorer (even though TortoiseSVN has them) and how to fix that?

A: Such problem should indicate that you are on disconnected network or don't have access to the Windows Update site (http://ctldl.windowsupdate.com/). Windows tries to update its Certificate Trust List (CTL) from the Windows Update site and fails. That's why there is a delay and it seems that configuring system-wide proxy allows Windows to reach the Windows Update site.
Contact your admin and read https://blogs.technet.microsoft.com/configurationmgr/2015/05/19/support-tip-why-cant-i-deploy-this-digital-certificate-security-advisory-with-wsus-or-configuration-manager/
Check this page to learn how to disable CTL's network retrieval:

If you cannot avoid installing this update on disconnected systems,
  you can disable the network retrieval of the trusted and untrusted
  CTLs. To do this, you disable automatic root updates by using Group
  Policy settings. To disable automatic root updates by using policy
  settings, follow these steps:

*

*Create a Group Policy or change an existing Group Policy in the Local Group Policy Editor.

*In the Local Group Policy Editor, double-click Policies under the Computer Configuration node.

*Double-click Windows Settings, double-click Security Settings, and then double-click Public Key Policies.

*In the details pane, double-click Certificate Path Validation Settings.

*Click the Network Retrieval tab, select Define these policy settings, and then clear the Automatically update certificates in the
  Microsoft Root Certificate Program (recommended) check box.

*Click OK, and then close the Local Group Policy Editor.

  After you make this change, automatic root updates are disabled on
  those systems to which the policy is applied. We recommend that the
  policy be applied only to those systems that do not have Internet
  access or that are prevented from accessing Windows Update because of
  firewall rules.


text:
Q: I'm using PyInstaller to turn a .py file into a .exe file, but I'm having difficulty? I've changed it into a .spec file, after which it tells me to run build.py. I do this, but it comes up Build.py: Error: Requires exactly one .spec file, and then doesn't do anything. What am I doing wrong?

A: I recommend you use the standard PyInstaller script pyinstaller.py, which combines all the other scripts into a single interface.
Just type:

python   pyinstaller.py  your_script.py

and PyInstaller will create a Build and Dist folder, and put your exe in the Dist folder.

A: *

*put your script in a new folder.

*run the 1st script (configure.py if memory serves)

*run the 2nd script (make.py yourfolder\yourscript.py again from memory)

*run the last script(build.py yourfolder\yourscript.spec)

you should have an exe now.
good luck.

A: Following is what I use to make an exe.
using python ../pysinstaller-1.5/Configure.py
python ../pyinstaller-1.5/MakeSpec.py -F --noconsole -n name-of-the-app path-to-your main-.py-file
python ../pyinstaller-1.5/Build.py path-to-name-of-the-app.spec-file-produced
Note: You should need to run Configure only once after a fresh install.

A: If you have pyinstaller set in your path variable, as I do, all you have to do is:
pyinstaller -F
And it automatically generates everything else.


text:
Q: How can I add writing inside this field Selenium enter image description here
I wrote it like this but it didn't work

first = driver.execute_script(By.ID,'adyen-checkout-encryptedCardNumber-1664069061344')
first.send_keys(firstName)


text:
Q: What does " she seemed no more put out than she would be by a light rain." means? I'm reading a Light Novel called "Overlord" and in a fight scene the author is describing a character action and reaction to the enemy's attacks,being one of them,this sentence " she seemed no more put out than she would be by a light rain."
I can't understand what the author means by that, is it a poetical sentence or something like that?

A: To be put out means to be inconvenienced or caused discomfort.
Merriam-Webster put out
5.a : disconcert, embarrass
b : annoy, irritate
c : inconvenience
"no more put out than by a light rain" means that she was not caused more discomfort by the attacks than she would be by a light rain. The attacks were a minor inconvenience.


text:
Q: rails generate - "Could not find generator" I am following the Ruby on Rails tutorial by Michael Hartl. In section 6.3.1, I am trying to generate a migration file to add a Password field to my user model. Here is the code that I run:
rails generate add_passsword_digest_to_users password_digest:string

but this throws the error: Could not find generator add_passsword_digest_to_users.
i have used the rails generate command before and it worked perfectly. I'm not sure why I am getting this problem now.
version: Rails 3.2.8, ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]

A: Try:
rails generate migration add_passsword_digest_to_users password_digest:string

You simply forgot migration which is the generator to use for the other arguments.

A: You have forget to include migration in the command. You can simply do
rails generate migration add_passsword_digest_to_users password_digest:string


text:
Q: Легальность использования интернет-справочников Это всего лишь предположение, но...
В интернете есть, как, наверное, все знают, много справочников и прочих полезных вещей, очень помогающих писать код.
Но откуда эта информация берется на сайтах? Если из чьих-то книг, тогда эти сайты можно считать пиратскими? Куда выгоднее получить бесплатную информацию там, чем отдавать несколько десятков долларов только за одну книгу. Потому автор книг теряет хлеб. Я не прав? Кто знает - просветите, я совсем запутался.
Примеры таких справочников:

*

*www.cppreference.com

*www.cppstudio.com

A: Каждый сайт имеет свое соглашение, но как правило оно схоже с Cretive Commons. Существют пермиссивные солгашения,  , используемые такими сайтами или отдельными авторами: WTFPL (делай-все-что-ты-хочешь), CC0  и др. Естественно, любой код с  "открытыми" лицензиями  GPL и DFSL может приводиться свободно.  Вообще , по международному соглашению (которое Россия подписала но некоторые российские компании его отрицают), исходный код рассматривается так же как литературное произведение. Цитирование с целью обучения, цитирование, не нарушающее исходной лицензии и создание кода по мотивам цитируемого не является нарушением, хотя использование патентованных средств. алгоритмов и т.п. может вызвать проблемы (например, если вы находитесь в США и пытаетесь реализовать сжатие mp3)
Следует заметить, что код, не содержащий уникального\оригинального материала не может быть защищен копирайтом (аналогично абстрактному тексту на любом человеческом языке). Таким образом, обобщенные примеры, не содержащие ничего оригинального, не защищены ничем, кроме как закона , определяющих их принадлежность к  Public Domain - публичному достоянию. Принадлежность к публичному достоянию определяется каждой юрисдикцией по отдельности, и тем не менее, не отрицает авторского права, если такое существовало. "Обшие" примеры, могут не быть предметом авторского права, но и не являться Public domain, просто они не могут являться предметом регистрации ( степень общности так же зависит от юрисдикции, это часто является причиной диспутов).
В ряде стран код не может быть  предметом копирайта. В России алгоритм не может быть предметом копирайта, но конкретная реализация может подлежать  авторскому праву, НО не автоматом, а только при регистрации такового. В США  алгоритмы и шаблоны разработки являются предметом патента. Каждый сайт оперирует в законодательной среде страны, в которой он расположен, в остальном  будучи защищенным нейтральностью сети. Так что сайт не считается пиратским, если оперирует по закону своей страны и соблюдает Бернскую конвенцию (российское законодательство имеет превратный взгляд на данный момент)


text: Q: Where is documentation for Android Open Source Project? My company tries to build up a customized android OS. Where can I find the documentation on the Android open source project? I wanna know the structure and modules within the system, relationship among those modules and how to make changes on the lower level frameworks etc. I can find source code and build android platform based on instruction of the site, http://source.android.com/. However there is not enough documents I can find there to help me customize the Android OS.


text:
Q: What is the name for this sequence? I just interested if this sequence is studied or it has a special name. Let $\xi_1,\xi_2,...$ i.i.d random variables with
$$\mathbb{P}\{\xi_i=1\} = p, \mathbb{P}\{\xi_i=-1\} = 1-p$$
And the sequence is
$$\eta_1, \eta_2, \eta_3, ...,$$
where $\eta_j = \xi_j\cdot \xi_{j+1}$


text:
Q: getting fileNotFoundException when running code on docker container using sbt native-packager i am creating a docker image of my akka http project using sbt native-packager
here is my build.sbt file
name := "myproject-auth"

version := "0.0.1"

enablePlugins(DockerPlugin)

enablePlugins(JavaAppPackaging)

dockerExposedPorts := Seq(8083)

then i create my app image as

sbt docker:publishLocal

it created my project image and runs fine the problem is
in my code i am reading a json file which reads from src/main/resources/json1.json
val jsonString = os.read(os.pwd / "src" / "main" / "resources" / "json1.json")

when i run this code in a docker container it says
docker-project-auth-container | java.nio.file.NoSuchFileException: /opt/docker/src/main/resources/json1.json

the problem is how can i make my code to work in this scenario
as  i need to keep using sbt native packager it creates my project jar and the working dir is /opt/docker in docker container where the my project's shell script resides created by docker
here is the docker file created by sbt native-packager
FROM openjdk:8 as stage0
LABEL snp-multi-stage="intermediate"
LABEL snp-multi-stage-id="cc5bb9ac-866b-4baa-98e1-c4541030c6ae"
WORKDIR /opt/docker
COPY opt /opt
USER root
RUN ["chmod", "-R", "u=rX,g=rX", "/opt/docker"]
RUN ["chmod", "u+x,g+x", "/opt/docker/bin/myproject-auth"]

FROM openjdk:8
USER root
RUN id -u demiourgos728 1>/dev/null 2>&1 || (( getent group 0 1>/dev/null 2>&1 || ( type groupadd 1>/dev/null 2>&1 && groupadd -g 0 root || addgroup -g 0 -S root )) && ( type useradd 1>/dev/null 2>&1 && useradd --system --create-home --uid 1001 --gid 0 demiourgos728 || adduser -S -u 1001 -G root demiourgos728 ))
WORKDIR /opt/docker
COPY --from=stage0 --chown=demiourgos728:root /opt/docker /opt/docker
EXPOSE 8083
USER 1001:0
ENTRYPOINT ["/opt/docker/bin/myproject-auth"]
CMD []

json1.json exists in a jar created by native-packager but it exists in root not in src/main/resources
opt/docker/ contains two folder bin and lib
bin contains myproject-auth.sh and myproject-auth.bat and lib contains myproject-auth.jar with other library dependencies
how can i make my code work inside a docker container


text:
Q: How to properly dolly (move in and out from an object) in OpenGL I have been searching through many forums (here and elsewhere) to find how to properly zoom in on an object in OpenGL. After reading up a lot, I finally sorta figured how to use GluLookAt(). I am able to get the camera moving like I want to without any problems. I know it works because the objects disappear as it should as the camera moves in. However, I want to zoom in on the object as I pan the camera. I thought the camera position would take care of it but updating the camera position doesn't seem to help. I also tried gScalef(), but it's getting called only once when I press the 'w' key.
void keyboard(unsigned char c, int x,int y)
{
  if(c==27)
    {exit(0);}
  if (c=='w')
    {
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();

      float forward_x, forward_y,forward_z;
      gluLookAt(current[0], current[1], current[2],
        current[0]+center_x, current[1]+center_y, current[2]+center_z,
        0.0, 1.0, 0.0);
      // glScalef(1.2,1.2,1.2);
      current[0]= (current[0]- 0.1*center_x);
      current[1]= (current[1]-0.1*center_y);
      current[2]= (current[2]- 0.1*center_z);

    }

}

void Camera_rotation(int x, int y)
{
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  center_x = cos(-0.05*x)*sin(-.05*y);
  center_y = cos(-.05*y);
  center_z = sin(0.05*x)*sin(.05*y);
  eye_x = x; eye_y = 1.0,
  float new_x = x;
  gluLookAt(current[0], current[1], current[2],
            current[0]+center_x,
            current[1]+center_y,
            current[2]+center_z,
            0.0, 1.0, 0.0);
  render();
}

'current' and 'center_x[yz]' are global variables. Can someone help?

A: As long as the camera is aiming at the object you should be able to set FOV (Field of View) on the Perspective Projection Matrix to achieve zooming effect. The smaller the FOV the smaller the viewing area which gives the illusion of zoom.
Brilliant tutorial on the subject can be found here. It talks about zoom right at the end.

A: Possible solution after a discussion:
In the render() function (or your display function), mention the projection matrix. This sets how your camera behaves. Code:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(30.0,1.0,-1.0,1.0);// FOV = 30 degrees, aspect ratio is one and I can see throughout the plane