text:
Q: Wicket and embedded jetty - classNotFoundException I'm trying to run my (seam and) wicket app on an embedded jetty server.
I get the following exception:
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:366)
    at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:337)
    ... 28 more

However, the LoggerFactory class is on my classpath. I tested this as follows:
public class StartJetty {
    public static void main(String[] args) throws Exception {
        ILoggerFactory fac = LoggerFactory.getILoggerFactory(); //this works!

        Server server = new Server();
        ...

Complete class:
public class StartJetty {
    public static void main(String[] args) throws Exception {
        Logger log = LoggerFactory.getLogger(StartJetty.class);

        Server server = new Server();
        SocketConnector connector = new SocketConnector();
        connector.setMaxIdleTime(1000 * 60 * 60);
        connector.setSoLingerTime(-1);
        connector.setPort(8090);
        server.setConnectors(new Connector[] { connector });
        WebAppContext bb = new WebAppContext();
        bb.setParentLoaderPriority(true);
        bb.setServer(server);
        bb.setContextPath("/wicket");
        bb.setWar("C:/wicket/exploded-archives/wicket.war");
        server.setHandler(bb);
        try {
            server.start();
            while (System.in.available() == 0) {
                Thread.sleep(1000);
            }
            server.stop();
            server.join();
        } catch (Throwable e) {
            e.printStackTrace();

            System.exit(100);
        }
    }
}

A: 1 - update to jetty 7 or jetty 8, your using jetty 6 by the looks of it and that is getting quite gray behind the ears...we are working on jetty-9 at this point (jetty7 if you want servlet 2.5 and jetty8 if you want servlet 3.0 support)
2 - a webapp executes in an isolated classloader so what you are seeing is that working correctly, you need to set the parent class loader priority on the webapp context that you are creating, or use the server/system mechanism to expose just those org.slf4j classes.
See http://wiki.eclipse.org/Jetty/Reference/Jetty_Classloading for more information on classloading in jetty.

A: I found the answer from Martjin Dashorst here is a good advice for debugging: https://stackoverflow.com/a/13413342/1915920

*

*remove all *.jars from WEB-INF/lib to some tmp folder

*restart via service jetty restart or similar

*look at the logs for problems or which classes are found to be missing

*add some jars back (e.g. grouped by type to speed it up ... orm/db-related, ui-related, different functionality-scopes and their dependencies) to the WEB-INF/lib folder

*repeat 2. to 4. till you likely spot the real conflicting problem
(or none if the conflicting jars are not needed in your WEB-INF/lib folder at all (anymore)

applying some class loader related stuff to the web.xml did not help me there: https://jira.codehaus.org/browse/JETTY-574


text:
Q: HTML5 Canvas drawImage results are always slightly darker than source video. How do I stop this? I would like to freeze a frame of a <video /> and modify it in a <canvas />. However, I've found the result of the canvas "drawImage" function is always slightly darker than the original video. This is noticeable when the canvas is placed over top of the original video, which is necessary for my purposes. I don't understand why this is the case. Is there any way to get around it?
Here's an example: https://jsfiddle.net/atd8vbkg/
PS I tried mirroring the entire original video to a canvas, so the darkness would be consistent when I overlayed the frame. This worked for desktop, however the video to canvas mirroring in mobile safari was very slow/low FPS, and therefor not a viable solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Transfer data between two different servers using SSIS I'm trying to create a SSIS package which will copy data from Table-A on Server-A into Table-B on Server-B. And to avoid duplicates, I want to update the data of the records which already exist in Table-B if there are any changes to the data. Please let me know what would be the best approach for this.
Thank You

A: You should use the SSIS Sort Transformation to remove duplicate records
Drag Sort Transformation and Connect Flat File Source to it. Double-Click on Sort Transformation and Choose the columns to sort. Also Check the Checkbox : Remove rows with duplicate sort values and then click OK
The SSIS Sort Transformation task is useful when you need to sort data into a certain sort order.

A: Create regular data flow with 2 components - OLE DB Source and OLE DB Destination (I assume you are using MS SQL Server, in general, use whatever components your company uses to connect to the DB).
In case of 2 DBs, create 2 connection managers, each pointing to its DB. Point OLE DB Source to first connection manager configured to point to source of data, and OLE DB Destination to second connection manager configured to point to destination DB.
Now point OLE DB Source to the source table in source DB, leave all the fields intact. Connect source and destination components with green arrow originally going out of source component. Now point OLE DB Destination to the destination table in target DB. Double-click destination, go to mappings and make sure they are correct (SSIS tries to map automatically using strick name matching), otherwise (in case names are different) connect source and destination fields manually. That's it, you just don't provide mappings for the fields which cannot be accommodated by destination table.
Alternatively, you can leave out the columns you don't need at source component - double-click it, go to Columns and uncheck columns you don't need.


text:
Q: How to capture direct query and Linq to sql calls to database from my system I am able to capture WCF HTTP calls made from my system with the help of fiddler and i hope you understood my question.
I want to capture calls to made to SQL Server by LINQ to Sql and Direct query expression from system, i was on google for this but dint get any help, is there any tool available or something that can help me to capture.
let me know if my you dont understand my question.
Thanks
Syed


text:
Q: How to configure SwaggerUI to properly set the Bearer Token on the header when using the OAuth 2.0 URL to generated token? I have Swagger 2 configs set up to connect to our OAuth2 accesstoken URL.
It is able to connect to the URL without issue when connected using the Apigee URL, but when I go to execute the POST request, I get an Invalid access token error. (See stack-trace below)
I've verified the URL, client id & secret using curl, and that works. And I've verified that when I use the provided token -H "Authorization: Bearer ********token*********" in my curl POST command, that that works correctly.
However, it doesn't appear that I've properly configured Swagger to create the "Bearer" header as it doesn't show up in the curl command displayed in swagger
After Authorizing through Swagger:

Manual Curl Command to generate token:
curl -k -v -X POST -u *****************:*************** -d "grant_type=client_credentials" https://***********************/oauth/accesstoken

accesstoken response body:
{
  "refresh_token_expires_in" : "0",
  "api_product_list" : "[********, ********]",
  "api_product_list_json" : [ "********", "********" ],
  "organization_name" : "********",
  "developer.email" : "********",
  "token_type" : "BearerToken",
  "issued_at" : "********",
  "client_id" : "************************",
  "access_token" : "************************",
  "application_name" : "********-****-****-****-********",
  "scope" : "",
  "expires_in" : "1799",
  "refresh_count" : "0",
  "status" : "approved"
}

Successful Manual Curl command to access endpoint:
curl -k -v -X POST "https://*********************/start" -H "accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer *****************" -d "{}"

Failing Curl Command generated by swagger:
curl -X POST "https://*********************/start" -H "accept: application/json" -H "Content-Type: application/json" -d "{}"

Swagger Error Message:
{
  "fault": {
    "faultstring": "Invalid access token",
    "detail": {
      "errorcode": "oauth.v2.InvalidAccessToken"
    }
  }
}

POM.xml:
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

Swagger Configs:
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${swagger.host:}")
    private String swaggerHost;

    @Value("${swagger.basePath:}")
    private String swaggerBasePath;

    @Value("${swagger.oauth2.security.schema:oauth2}")
    private String securitySchemaOAuth2;

    @Value("${swagger.oauth2.token.request.url:}")
    private String oauthTokenRequestURL;

    @Autowired
    ServletContext servletContext;

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .host(swaggerHost)
                .pathProvider(new RelativePathProvider(servletContext) {

                    @Override
                    public String getApplicationBasePath() {
                        return swaggerBasePath;
                    }
                })
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo())
                .securitySchemes(Collections.singletonList(oauth()))
                .securityContexts(Collections.singletonList(securityContext()))
                .useDefaultResponseMessages(false);
    }

    private OAuth oauth() {
        List<AuthorizationScope> authorizationScopeList = new ArrayList<>();

        List<GrantType> grantTypes = new ArrayList<>();
        GrantType creGrant = new ClientCredentialsGrant(oauthTokenRequestURL);

        grantTypes.add(creGrant);

        return new OAuth("oauth2schema", authorizationScopeList, grantTypes);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Blah")
                .description("Blah")
                .version("2019.0.1")
                .contact(new Contact("Blah", "", ""))
                .build();
    }

    private SecurityContext securityContext() {
        return SecurityContext
                .builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("/.*"))
                .build();
    }

    private List<SecurityReference> defaultAuth() {

        final AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        final AuthorizationScope[] authorizationScopes = new AuthorizationScope[] { authorizationScope };

        return Collections.singletonList(new SecurityReference(securitySchemaOAuth2, authorizationScopes));
    }
}


text:
Q: How can I get my module exported to the browser without using Module.default notation? How can I make webpack expose my module to the browser directly to the Module name instead of using Module.default?
Here is my app setup in a simplified manner to hopefully portray what I am hoping to achieve.
webpack.config.js
module.exports = {
    entry: './src/app.js',
    devtool: 'source-map',
    output: {
        path: './lib',
        filename: 'app.js',
        library: 'App',
        libraryTarget: 'umd',
        umdNamedDefine: true
    },
    module: {
        loaders: [{
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader'
        }]
    }
};

.babelrc
{
    "presets": ["es2015"],
    "plugins": ["babel-plugin-add-module-exports"]
}

app.js
export default function main() {
    console.log('The default function');
}

export function other() {
    console.log('A random function');
}

Because I specified "App" as the "library" in the output, my library is available in the browser as App.
The weird thing is... in order to use the default function that was exported I have to do App.default. But to use the other exported function I can do this: App.other. I would expect that I could do App() to call the default exported function, and the other would be the same App.other().
Is this standard behavior in the browser or a UMD wrapped library with webpack? This does not seem to mimic the behavior of the lodash library. Is my configuration off in some way?

However, if you take a look at the lodash library (repo) in the browser, you can see that they acheived it.
Lodash is built using webpack. If you take a look inside of the package.json for lodash, you can see that the main file is lodash.js. If you take a look at that file, it appears to be UMD wrapped (UMD definition at the bottom of the file). Therefore, when I do things like:
import _ from 'lodash';
// or
import {clamp} from 'lodash';

everything works fine.
The other thing that works fine is referencing that exact file in an HTML file:
<script src="node_modules/lodash/lodash.js"></script>

Which allows me access to the lodash object.
console.log(_) // function
console.log(_.clamp) // function clamp(number, lower, upper) { ... }

How can I get the same behavior. Lodash's webpack config is much more complicated than I need, and am not sure what I need to reverse engineer.

A: add libraryExport: 'default' to the output configuration of webpack;
also you don't need babel-plugin-add-module-exports.


text:
Q: Visual studio 2022 remote profiler Good afternoon.
Faced with the need to profile remote execution of the program (Dot Net Core 3.1, AtraLinux).
When developing a program, I use Visual Studio 2022 on Windows 10.
I know that Visual Studio 2022 has a rich selection of profilers, as a result of this the question arises:
Can Visial Studio 2022 profile my remote execution?
P.S:
Found a similar question only for Visual Studio 2013.
enter link description here


text:
Q: Command to move line up or down in Atom Editor I have used Sublime for years and am trying out Atom for the first time.
How can I move a single line or selected block up or down by one line? In sublime I could do this with ctrl+shift+Up, but that doesn't seem to work in Atom. Any ideas?

A: Windows: Ctrl+Up/Down
Mac: Ctrl+Cmd+Up/Down
Don't have enough Rep to leave as a comment. But for @DanielM question.
To move several lines in Atom:
Select all the several lines you want move by mouse or by holding shift and moving up or down the lines you want, and then use either the commands for Windows Ctrl+Up/Down or Mac Ctrl+Cmd+Up/Down
Note: The whole line does not have to be selected as long as part of it is, it will move with the commands.

A: '.editor':
  'alt-up': 'editor:move-line-up'
  'alt-down': 'editor:move-line-down'

A: Depends on your OS:
Linux & Windows: Ctrl + Up/Down
Mac: Ctrl + Cmd + Up/Down

A: I had the same problem, I solved editing keymap file and adding this:
'atom-workspace atom-text-editor':
  'alt-up': 'editor:move-line-up'
  'alt-down': 'editor:move-line-down'

So to move I use "alt+up" or "alt+down".

A: In Atom you can just use Ctrl + Up.
You can find these options on Atom menu : Edit > Lines > Move Line Up


text:
Q: Does the order of components going to ground count? Building a PCB, following the schematic there would be a specific order of the components going ground, but if I decide to let the signal go to ground in another point as shown in the schematic, would it affect the signal?

in the picture:
If I take R3 and plug it to ground after R21 instead of after R2, it still goes to ground, but the order is different.
Does it affect the signal? Does the output signal change?

A:
Figure 1. R3 and R21's ground points in what appears to be an audio pre-amplifier.

... but if I decide to let the signal go to ground in another point as shown in the schematic, would it affect the signal?

*

*A schematic is not a physical wiring or layout diagram. It is supposed to show the schema or function and connections of the various componenents.

*All of the GND points are connected together and usually by extra-wide PCB tracks so that there is very low resistance between the components connected to GND.

*The PBC designer will use experience and design rules to minimise the likelihood of problems caused by poor layout. This generally means avoiding placing sensitive parts of the circuit close to high-powered parts where interference might result and placement of components such as decoupling capacitors C3 and C4 in their optimum position to do their intended job.

If I take R3 and plug it to ground after R21 instead of after R2, it still goes to ground, but the order is different.

There is no order but you have probably increased the length of PCB trace into the circuit and this could cause problems such as interference pickup.

Does it affect the signal? Does the output signal change?

If all goes well, no.

A: Depends what kind of circuits and return currents you have, but knowing how to ground is important and that is why concepts like star ground or ground plane exist. Obviously long wires with large currents are worse that short wires with large currents, and for example when building an audio amplifier, you dont't want the power amp ground path current cause any noise (fluctuation) on the preamp stage ground.


text:
Q: What are best practices for deleting/altering cassandra columns of collection data-type? In our Cassandra table, every time we change data-types of "collection-type" columns it start causing issue. For example:
For changing datatype from text to Map<text,float> we do this:

*

*drop existing column

*wait for cassandra to assimilate this change.

*add column (same name) but different data-type.

This reflects fine in all nodes, but Cassandra logs start complaining during compaction with:

RuntimeException: 6d6...73 is not defined as a collection

I figured out the comparator entries are not correct in "system.schema_columnfamilies" table. Dropping table and recreating it fixes the problem but its not possible always.
Are there some best-practices when we are dealing with collection type columns in situations like above ?

database-version:   DataStax-Enterprise: 4.7.1   Cassandra 2.1.8.621
  cqlsh 5.0.1

A: I guess you stumbled upon one of those WAT moments in Cassandra. Its a bad practice to name a new column as previously dropped one. Sometimes it even doesn't work.
Regarding schema (or data) migrations take a look at our tool. It can help you execute schema updates while keeping data and populating fields.


text:
Q: Ejecución de funciones dinamicamente Tratando de ser lo más resumido posible, si tengo el siguiente arreglo en Javascript
(3) [{…}, {…}, {…}]
0: {action: "doSetLibraryTreeData", data: Array(1)}
1: {action: "doSetSource", data: Array(3)}
2: {action: "doSetFunctionDefinitionList", data: Array(3)}
length: 3
__proto__: Array(0)

¿Cómo puedo ejecutar dinamicamente cada una de las funciones "action" y pasarle el "data" como parámetro?
Es que quiero ejecutar un batch de redux dada una respuesta de un Web Worker.
Saludos y gracias de antemano

A: Mi propuesta es la siguiente: define las funciones como métodos dentro de un objeto, de este modo podrás acceder a ellas mediantes la notación de corchetes:

const functions = {
  doSetLibraryTreeData: function ([d1,d2,d3]){
    console.log('Ejecutando doSetLibraryTreeData con', d1,d2,d3)
  },
  doSetSource: function ([d1,d2,d3]){
    console.log('Ejecutando doSetSource con', d1,d2,d3)
  },
  doSetFunctionDefinitionList: function ([d1,d2,d3]){
    console.log('Ejecutando doSetFunctionDefinitionList con',d1,d2,d3)
  },

  runFn: function (functionName, ...params) {
    this[functionName](params);
  }
};

const batch = [{action: "doSetLibraryTreeData", data: [1,2,3]},
{action: "doSetSource", data: [4,5,6]},
{action: "doSetFunctionDefinitionList", data: [7,8,9]}];

batch.forEach( step => functions[step.action](step.data));

A: Una posible forma es usando eval:

const func = [{action: "doSetLibraryTreeData", data: [1,2,3]},
{action: "doSetSource", data: [4,5,6]},
{action: "doSetFunctionDefinitionList", data: [7,8,9]}];

function doSetLibraryTreeData(data){
    console.log(data)
}
function doSetSource(data){
    console.log(data)
}
function doSetFunctionDefinitionList(data){
    console.log(data)
}

func.forEach(f=>{
    eval(f.action)(f.data);
})

El uso de eval no es recomendado, pero para ejecutar código como string no hay muchas mas opciones. Hay mucha discusión sobre porque no es recomendado, sugiero leer esta pregunta en SO en inglés.


text:
Q: MySQL selecting names of customer with most purchase I have 5 tables connected with each other in the image
[![Image1][1]][1]

I have tried writing query
SELECT lastname,firstname
FROM customer,purchase_order
where customer.customer_id=purchase_order.customer_id

What parameter should I consider for most purchase?

A: You can solve that by adjusting the select clause (remove order_id).
Then you will need a HAVING clause to implement the condition to only show the customers with the most purchase orders.

A: SELECT lastname,firstname
FROM customer
INNER JOIN purchase_order
ON customer.customer_id=purchase_order.customer_id
GROUP BY customer_id
ORDER BY COUNT(order_id) DESC LIMIT 1;

A: select lastname, firstname from customer c
inner join (
select customer_id, count(1) from purchase_order
group by 1
order by 2 desc limit 1) most
/* the above sub-query named as 'most' fetched the customer id with the maximum
number of orders */
on c.customer_id = most.customer_id; -- this is a simple join of customers table with the table generated from sub-query above

A: SELECT c.firstname,c.lastname
FROM customer c
JOIN purchase_order po
ON c.customer_id = po.customer_id
GROUP BY c.firstname,c.lastname
ORDER BY COUNT(po.order_id) DESC LIMIT 1;


text:
Q: Can not include javascript file from WEB-INF directory in JSP. How to include a file in the following folder WEB-INF\includes\header.js in jsp using tomcat. I have the included the following in jsp file but it does not work "
<script type="text/javascript" src="WEB-INF/includes/header.js"></script>

". It is not getting the header.js and when i view source and try to click on the src link it says resource not found 404 error.

A: Put a "/" before "WEB-INF" like this,
<script type="text/javascript" src='<c:url value="/WEB-INF/includes/header.js"/>'></script>

and it will work fine. :)

A: <script type="text/javascript">
<%@include file="../foo.js" %>
</script>

foo.js is under WEB-INF/jsp and the file include it is under WEB-INF/jsp/common


text:
Q: Janus GridEx: Add custom row and select a specific row I have GridEx object on my form and...

*

*I want to add some items in it with a for...next loop. Actually I couldn't find any method for adding a new row with a custom data.

*I want to select a specific row in that GridEx object. For example: I want to select the 6th row, is there anything like mygrid.rows(6).value or something like that?!
Thanks in Advance...

A: Assuming you have a GridEX control called grid...
To add new data:
GridEXRow row = grid.AddItem();
row.BeginEdit();
row.Cells[0].Value = "Whatever"; // refer to columns by index or name
...
row.EndEdit();

To retrieve a specific row:
GridEXRow row = grid.GetRow(5); // returns the 6th row

To select a specific row:
grid.MoveTo(5); // moves the selection to the 6th row

A: To add new row to gridex called MyGridEX:
object[] data = { "value0", "value1", "value2", ... };
this.MyGridEX.AddItem(data);

To select a specific row:
this.MyGridEX.GetRow(1); // select the second row


text:
Q: Track Laravel routes quickly I am working with a big, messy Laravel Project in which routes file (web.php, api.php) include  thousands of nested routes. Finding which controller@function responds to the url is time consuming and error-prone. Is there any elegant method for that?
for example convert "https://stackoverflow.com/questions/ask" to QuestionContrller@newQuestion.

A: I am sure there are other ways to go about that, but you can get the route collection of all the routes and attempt to have it match a request to a route:
$request = Illuminate\Http\Request::create('questions/ask');

try {
    $route = Route::getRoutes()->match($request);
    $action = $route->getAction('uses');
    dump($action):
} catch (...) {
    // couldn't match a route
}

If you needed to use a different method other than GET, that would be the second argument to Request::create.

A: I normally find my associated Controller method to a route by executing this command in my terminal:
php artisan route:list | grep my/url/which/im/looking/for

Or if you want to be more specific you can write more specific REGEX in grep:
php artisan route:list | grep POST.*my/url/which/im/looking/for


text:
Q: Boostrap table only top border I have a bootstrap table (data-card type) to display a ranking.
I want to hide all borders of my table except the top one.
Actually, I can hide bottom of table with this code:
#table1 {
    border-bottom:0 px;
}

but for example,border-right:0 px; or even left doesnt work. Could you help me please? Thanks

A: Override the td element styles
#table1 td {
    border-left:0;
    border-right:0;
    border-bottom:0;
}


text:
Q: SQL: Get a list and use all items in the output for another query I use several SQL queries for completing a table, but i think it's also possible to get it with only one query. Here is the structure:
There is the table 'wp_postmeta'; including id, post_id, meta_key and meta_value as the columns. In that table, rows with meta_key = x has user ID values in the meta_value part. I want to get the post_id value with a given meta_key and user id value (which is in meta_value part) and use that post_id to get certain meta_values with given meta_keys. Here is an example. Let's say that User ID is 9:
SELECT CONCAT((SELECT 'meta_value' FROM 'wp_postmeta' WHERE 'meta_key' = y AND 'post_id' = (SELECT 'post_id' FROM 'wp_postmeta' WHERE 'meta_key' = x AND 'meta_value' = 9)),(SELECT 'meta_value' FROM 'wp_postmeta' WHERE 'meta_key' = z AND 'post_id' = (SELECT 'post_id' FROM 'wp_postmeta' WHERE 'meta_key' = x AND 'meta_value' = 9)),(SELECT 'meta_value' FROM 'wp_postmeta' WHERE 'meta_key' = w AND 'post_id' = (SELECT 'post_id' FROM 'wp_postmeta' WHERE 'meta_key' = x AND 'meta_value' = 9)))
With that query, I have concatenated the meta values for given meta keys, belonging to a post related to a given user ID. (y,z,w). The issue is that I can get what I want correctly for a given User ID, but I want to give a list of User ID's and get their corresponding concatenated results. How can I achieve that? Thanks for any help.

A: You seem to be describing something like this (using MySQL syntax):
select p.*, group_concat(pm.metavalue) as metavalues
from wp_posts p left join
     wp_postmeta pm
     on pm.post_id =  p.post_id
where p.user_id in ( . . . )
group by p.user_id;


text:
Q: not seeing a sequelize model property that is required after seeding database UPDATE
someone below suggested adding in a model id for shoutouts and I'm no longer getting the error, but now nothing is being saved to my database?
adding in the new information below:
I have a one to many relationship between users and shoutouts. Both models have email property,
I am trying to use a magic method to setup the shoutout. When I use user.createShoutout()
I can generate the shoutout, but the email property doesn't show up in the database.
const Sequelize = require('sequelize')
const db = require('../db')

const Shoutout = db.define('shoutout', {
//NEW
  id: {
    allowNull: false,
    autoIncrement: true,
    primaryKey: true,
    type: Sequelize.INTEGER
  }, //OLD
  name: {
    type: Sequelize.STRING,
    validate: {
      notEmpty: true
    },
    email: {
      type: Sequelize.STRING,
      unique: true,
      allowNull: false
    }
  },
  message: {
    type: Sequelize.TEXT,
    allowNull: false
  },
  from: {
    type: Sequelize.STRING
  }
})

module.exports = Shoutout

associations:
User.hasMany(Shoutouts)
Shoutouts.belongsTo(User)

User.hasMany(Emails)
Emails.belongsTo(User)

when I use user.AddShoutout()
as follows:
   let paramsObj = {
        name: addEmail.firstName,
        email:addEmail.email,
        message: 'test msg',
        userId: 3
}
//NEW
let id = 1;
    const addInfo = await userThree.addShoutout(id,paramsObj)

//NEW
not getting the object error anymore, in fact not seeing any errors. But when I look in my shoutouts table nothing is getting added.
when I console.log addInfo
The user who tried to create the shoutout gets returned?
I need help with trying to get this user model magic method to generate a new shoutout!
Thanks for reading this, and any advice!

A: Your email field is nested within name field
const Sequelize = require('sequelize')
const db = require('../db')

const Shoutout = db.define('shoutout', {

  id: {
    allowNull: false,
    autoIncrement: true,
    primaryKey: true,
    type: Sequelize.INTEGER
  }, //OLD
  name: {
    type: Sequelize.STRING,
    validate: {
      notEmpty: true
    },
    email: { # <----------------------------- nested too deep
      type: Sequelize.STRING,
      unique: true,
      allowNull: false
    }
  },
  message: {
    type: Sequelize.TEXT,
    allowNull: false
  },
  from: {
    type: Sequelize.STRING
  }
})

module.exports = Shoutout


text:
Q: Improve quality of ffmpeg created jpgs I'm using ffmpeg to take a mjpeg feed from an IP camera and convert it into a series of still jpeg images.  Here's the command I'm using:
ffmpeg -i http://xxx:xxx@xx.xx.xx.xx/vid.mjpg -f image2 -vcodec mjpeg %05d.jpg

Does anyone know a way to specify the level of jpg compression when using ffmpeg to create stills?

A: $ ffmpeg -r 1/4 -i %03d.jpg -b 5000 -vcodec mjpeg -qscale 1 5000.avi
OR
$ ffmpeg -r 1/4 -i %03d.jpg -vcodec copy -qscale 1 copy.avi
Reference:
r       delay between next jpg, results 4 second
b       bitrate
vcodec  use jpeg encode
qscale  quality ratio

A: Here's what ended up doing the trick for me:
ffmpeg -i http://xx.xx/mjpg/video.mjpg -q:v 1 %05d.jpg

The -q:v 1 was the ticket. It sets the quality of the video encoder, where the -q means quality and the :v means video. Values range from 1 to 31, where lower means better.

A: You could try to export into PPM and use some other tool to convert into JPEG.
I looked into ffmpeg/libavcodec/mjpeg.c. I believe the quality is set to a fixed value.
Also you seem to convert a MJPEG video into JPEG still frames. I think in this case the code in ffmpeg/libavcodec/mjpeg2jpeg_bsf.c runs and the data isn't recoded. So the image quality wouldn't improve anyway.
This is the quantization table definition, I didn't see any reference to *val_?c where the values were scaled before use.
/* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
/* IMPORTANT: these are only valid for 8-bit data precision! */
const uint8_t ff_mjpeg_bits_dc_luminance[17] =
{ /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
const uint8_t ff_mjpeg_val_dc[12] =
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

const uint8_t ff_mjpeg_bits_dc_chrominance[17] =
{ /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };

const uint8_t ff_mjpeg_bits_ac_luminance[17] =
{ /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
const uint8_t ff_mjpeg_val_ac_luminance[] =
{ 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,

A: Simpliest way I found
Explode video file in .png (lossless) then convert them in jpeg:
ffmpeg -i inputfile.avi image-%07d.png

(without option, this will extract all frames.)
I prefer using png compression even if ffmpeg is able to produce .ppm files (not compressed). Because using PPM will require a lot of disk space and won't be quicker (due to disk write time, of course not tested with SSD;).
Then (using netpbm tools)
JPEGQUALITY=95
for file in *.png;do
    echo -n $file...
    pngtopnm $file | pnmtojpeg -q $JPEGQUALITY >${file%.png}.jpg
    echo -e \\e[6Djpg\\e[K.
done


text:
Q: Update child page's column in Linq Please see the following code:
public void UpdateChildPagesReWrittenUrl(int parentPageId)
    {
        var childPageList = db.PcPages.Where(m => m.ParentID == parentPageId);

        if (childPageList.Count() > 0)
        {
            foreach (var item in childPageList)
            {
                db.ExecuteNonQuery(string.Format("UPDATE pcPage SET Url = {0}/{1} WHERE PageID = {2}",
                    GetRootUrl(item.ParentID),
                    hnUrlHelper.UrlSafe(item.PageName), item.PageID));
                db.SaveChanges();
            }
        }

    }

I trying to update all the child pages url when a parent page updates the page name itself. This code I thought it working. but not.  Anyone can advise better in better way  please ?

A: Is it updating anything ?  Can you use SQL Profiler to see what queries are actually sent ?
Could also set a breakpoint and make sure it is doing what you expect.

A: Try to add quotes around new url address:
"UPDATE pcPage SET Url = '{0}/{1}' WHERE PageID = {2}"

Also I believe you can update child rows without fetching them
var query = @"UPDATE pcPage SET Url = Concat(ParentID, '/', PageName)
              WHERE ParentID = " + parentPageId;
db.ExecuteNonQuery(query);

A: Why not just do this:
public void UpdateChildPagesReWrittenUrl(int parentPageId)
{
    Func<PcPage, string> url = item => String.Format("{0}/{1}",
        GetRootUrl(item.ParentID), hnUrlHelper.UrlSafe(item.PageName));

    Array.ForEach(db.PcPages.Where(m => m.ParentID == parentPageId).ToArray(),
        x => { x.Url = url(x); });

    db.SaveChanges();
}


text:
Q: Graphql object ( or JSON) as filter argument Is it possible to have a JSON object as filed in filter arguments. Something like:
    Query{
      building(location:{lon,lat}){
        name,...
      }
    }

I need to pass location, and I would like to pass it as js object ( to apollo client) or as stringified JSON.

A: You can use input types to achieve that. You need to edit your schema
type Query {
    building(location: Location): Building
}

input Location {
    lon: String
    lat: String
}

Then you can post your query like this
query {
  building(location: {lon:"100.332680",lat:"5.416393"}) {
    name,...
  }
}


text:
Q: Which is the fastest method to calculate means square error in large image dataset? I'm trying to calculate the mean square error in an image dataset(CIFAR-10). I have a numpy array of dimension 5*10000*32*32*3 which is, in words, 5 batches of 10000 images each with dimensions of 32*32*3. These images belong to 10 categories of images. I have calculated average of each class and now I'm trying to calculate the mean square error of each of the 50000 images wrt the 10 average images. Here is the code:
for i in range(0, 5):
  for j in range(0, 10000):
      min_diff, min_class = float('inf'), 0
      for avg in class_avg:  # avg class comprises of 10 average images
          temp = mse(avg[1], images[i][j])
          if temp < min_diff:
              min_diff = temp
              min_class = avg[0]
      train_pred[i][j] = min_class

Problem: Is there any way to make it faster. Any numpy magic? Thank you.

A: You can use expand_dims and tile.
There are many ways of expanding the dimension of an array, I will use one of them, which is something like [:,None,:], this adds a new axis in the middle.
Below is an example of how you can combine the two methods to fulfill your task:
test = np.ones((5,100,32,32,3)) # batches of images
average = np.ones((10,32,32,3)) # the 10 images
average = average[None,None,...] # reshape to (1,1,10,32,32,3)

test = test[:,:,None,...] # insert an axis
test = np.tile(test,(1,1,10,1,1,1)) # reshape to (5,100,10,32,32,3)
print(test.shape,average.shape)

mse = ((test-average)**2).mean(axis=(3,4,5))
class_idx = np.argmin(mse,axis=-1)

UPDATE
The purpose of using expand_dims and tile is to avoid using a for-loop. However, the np.tile operation will create 10 replicates of the original array, this will definitely hurt the performance if the array is large. To avoid using np.tile, you can try the code below:
labels = np.empty((5,100,10))
average = np.ones((10,32,32,3))
average = average[None,...]

test = np.ones((5,100,32,32,3))

for ind in range(10):
    labels[...,ind] = ((test-average[:,ind,...])**2).mean(axis=(2,3,4))
labels = np.argmin(labels,axis=-1)


text:
Q: Magento2 category images not showing and not changing I have a strange problem with Magento 2.2.3. A few month ago we added some category images and they were shown correctly. Today we added some new category images and changes some of the old ones. But no new image is shown and also changed images are not shown. Category page always shows old images ... in admin new category image is correctly shown.
We run reindex, ran:
cd httpdocs && find var vendor pub/static pub/media app/etc -type f -exec chmod u+w {} \; \
&& find var vendor pub/static pub/media app/etc -type d -exec chmod u+w {} \; \
&& chmod u+x bin/magento

and also tried to set permissions to 777 of folder and files.
Anyone an idea what is wrong?

A: Go to System > Cache Management and scroll to the bottom of the page. Then click the Flush Catalog Images Cache button and the clear the other caches.

Update: After chat, it turned out that there were image upload at either the website or store scope that were preventing the newly uploaded images from showing.

A: You can follow my way

*

*Remove old image (if exist)

*Save

*Upload new image

*Save

*Reindex everything about category

*clear and flush cache


text:
Q: When is a clause not essential? I am having trouble figuring out when to use commas to set off "nonessential" information.  Sometimes it's obvious:

Bob, who is thirty years old, is an alcoholic.

But other times I'm not sure:

The day he quits drinking * he will start a llama farm
He has his heart set on owning El Duderino ranch * in New Mexico.

In the first case, my ear says that there should be a comma at *, even though information before it seems essential to me.  In the second case, the stuff after * is not essential, and yet it seems a little much to use a comma.
Even that last sentence I wrote confuses me.  "In the second case" seems essential but I used a comma.  Is this correct?
Does it depend on personal style and the length of the clause?  Or perhaps I'm misinterpreting the meaning of "essential" in this context?

A: *

*In the second case, the stuff after [asterisk] is not essential, and yet it seems a little much to use a comma. Even that last sentence I wrote confuses me. "In the second case" seems essential but I used a comma. Is this correct?

According to the Chicago Manual of Style it's optional, even though according to them skipping the comma might be a good idea. I'd use it.
It does depend on personal style, as some authors prefer a breezier style, with less punctuation. Read Cormac McCarthy.

A: I believe the answer depends entirely on the conversational effect you wish to deliver. Whenever I add in tangential information to a sentence, I find that it is almost impossible to cut down on cognitive load somewhere else to make your sentence as equally accessible as before.
The example of "The day he quits drinking..." where you trail off the sentence is stylistic. It's more about implying that you can't even summon the thought that comes after.
Meaning is in the eye of the beholder.


text:
Q: unable to resolve method in class 1.is it possible to call the native method in the gwt into the other native method ?
this is the method i am calling from the VectorSource.java into Map.java
https://github.com/VOL3/v-ol3/blob/master/gwt-ol3/src/main/java/org/vaadin/gwtol3/client/source/VectorSource.java
 public final native JsArray<Feature> getFeatures()/*-{
        return this.getFeatures();
    }-*/;

and i created a native method in  Map.java class and getting the Features and i want to return these feature values to  addOnPostRenderListener method  below are the  changes in the Map.java class
    public native final Feature getFeatures(VectorSource sourceFeature)/*-{
    var features=sourceFeature.@org.vaadin.gwtol3.client.source.VectorSource::getFeatures();
    return features;
    }-*/;

    public native final void addOnPostRenderListener(OnPostRenderListener listener)/*-{

       if(!this.__registered){
       var that=this;

       that.once('postrender',function(){
        var feature=that.@org.vaadin.gwtol3.client.Map::getFeatures(vectorSource);
        if(feature!=null){
        var coordinate=feature.getGeometry().getCoordinate();
        if(coordinates!=null){
        var MapEvent={Pixel:that.getPixelFromCoordinate(that.__transformInputCoordinate(coordinates))};
        that.__notifyPostRenderListeners(MapEvent);
        }
        }})
        this.__postRenderListeners.push(listener);
        }
    }-*/;

the remaining code remains the same as shown in the below link
https://github.com/VOL3/v-ol3/blob/master/gwt-ol3/src/main/java/org/vaadin/gwtol3/client/Map.java
at the below code  i am getting the error,as Expected a valid parameter type signature in JSNI method reference these lines of code  is in the addOnPostRenderListener method
 var feature=that.@org.vaadin.gwtol3.client.Map::getFeatures(vectorSource);

my target is to call the method getFeatures() from VectorSource.java class  into the Map.java class  and send the values to the other native method which is   addOnPostRenderListener method.
Interface
public interface OnPostRenderListener {

    public void onRender(MapEvent posEvent);
}

MapEvent
public class MapEvent extends JavaScriptObject {

    protected MapEvent() {

    }

     public static final native Feature create()/*-{
     return new $wnd.ol.Feature();
      }-*/;

     public native final Geometry getGeometry()-{
        return this.getGeometry();
       }-;*/

    public native final Geometry getGeometry()/*-{
        return this.geometry;
    }-*/;

    public native final Coordinate getCoordinate()/*-{
    return this.coordinate;
     }-*/;

   public native final Pixel getPixel()/*-{
    return this.Pixel;
    }-*/;

   //written code not used
   public native final Map getPixelFromCoordinate(Coordinate coord)/*-{
     return this.getPixelFromCoordinate(coord);
    }-*/;
}

A: You need to pass your VectorSource sourceFeature parameter too. You are missing it in that.@org.vaadin.gwtol3.client.Map::getFeatures(Lcom/google/gwt/core/client/Source;);.
One way to do this, would be add it to your
addOnPostRenderListener(OnPostRenderListener listener)
e.g. addOnPostRenderListener(OnPostRenderListener listener, VectorSource vectorSource)
and then to access it like this:
var feature=that.@org.vaadin.gwtol3.client.Map::getFeatures(vectorSource);

Although I would recommend to completely drop JSNI and use the much better JsInterop. There is an OL-implementation using JsInterop too. Take a look here


text:
Q: angular factory. how to create new instances of the factory? I am trying to create new instances of a factory but, all the time it prints the last instance (because of its singleton).
How can I achieve new instance every time I create with the new keyword?
I created example of what I am trying to achieve in jsfiddle.net
Thanks.
angular.module('mainModule', []);

  Crud.$inject = ['$http'];

    function Crud($http) {

        function CrudFactory(crudDTO) {
            var vm = CrudFactory;
                        vm.x = 1;
            vm.addX = addX;
            vm.getX = getX;
            vm.print = print;

            function addX(){
                vm.x +=1;
            }
            function getX(){

                return vm.x;
            }
            function print(){
                console.log(crudDTO.entity);
            }

            return vm;
        }

        return CrudFactory;
    }

    angular
        .module('mainModule')
        .factory('Crud', Crud);

    angular.module('mainModule').controller('mainCtrl', function($scope,Crud){
    var a = new Crud({entity:"test1"});
    var b = new Crud({entity:"test2"});
    //a.addX();
    //$scope.a =b.getX();
    a.print();
    b.print();
    a.print();
});

A: You are referencing it wrongly. You have to reference the instance of the called function with this rather than with the function name again.
Instead
var vm = CrudFactory;

change
var vm = this;

Working Demo:
http://jsfiddle.net/haqL7m5q/2/


text:
Q: iOS build size is too large how can i upload ipa? I have finally ready to upload my App to the App store, but my build size is too large.
Anyone has an idea to solve this problem to upload my application. ?
Thanks in advance.


text:
Q: react native streaming stop with react navigation I am making an application that has two streams (A AND B) which can be accessed from the home screen.
well, the problem is the following:
when I enter any of the two streams (A) everything works fine, but when I access the other stream (B) from the Drawer navigation, said stream pauses every time I press play
I am passing them through an iframe with react native webView
my navigation method is in React navigation Drawer
I have tried several ways to solve this, changing to Stack, using jumTo, etc, but with none I have been successful
I am new to react native, please help me with this problem

A: UPDATE!!!!
I found that my videos in the iframe are stopping because the screens are not closing, I tried this by creating a copy of my app and using Stack with the "Replace" component, but now I see that drawer has no replace component.
How could I do this using Drawer navigation?


text:
Q: Rails: How can I render multiple objects to JSON? I am trying to render multiple objects as JSON. This is my render call:
render :json => {:widget => @widget.to_json(:include => :foo),
                 :updated => Time.now.to_i}

I have to use to_json because of the include, and the addition updated so I know when the last call was made. The problem is that the to_json is rendered as a String instead of the object structure of the widget.
How do I get the full object structure of the widget and the updated information?

A: Move the :include => :foo into your Widget model.
class Widget < ActiveRecord::Base
  def as_json(options = {})
    super options.merge(:include => :foo)
  end
end


text:
Q: Gprof with CMake I'm trying to compile a project using gcc and gprof. Thus I added to CMakeLists.txt in CLion the following lines:
SET(GCC_COVERAGE_COMPILE_FLAGS "-pg")
add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})

However when I run the compiled binary I doesn't generate the gmon.out file.
These are the messages built:
/home/matteo/Desktop/Xilinx/App/clion-2016.3.3/bin/cmake/bin/cmake --build "/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug" --target OpenCV_Stitching_Detailed -- -j 4
/home/matteo/Desktop/Xilinx/App/clion-2016.3.3/bin/cmake/bin/cmake -H"/home/matteo/CLionProjects/OpenCV Stitching Detailed" -B"/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug" --check-build-system CMakeFiles/Makefile.cmake 0
/usr/bin/make -f CMakeFiles/Makefile2 OpenCV_Stitching_Detailed
make[1]: Entering directory '/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug'
/home/matteo/Desktop/Xilinx/App/clion-2016.3.3/bin/cmake/bin/cmake -H"/home/matteo/CLionProjects/OpenCV Stitching Detailed" -B"/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug" --check-build-system CMakeFiles/Makefile.cmake 0
/home/matteo/Desktop/Xilinx/App/clion-2016.3.3/bin/cmake/bin/cmake -E cmake_progress_start "/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug/CMakeFiles" 2
/usr/bin/make -f CMakeFiles/Makefile2 CMakeFiles/OpenCV_Stitching_Detailed.dir/all
make[2]: Entering directory '/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug'
/usr/bin/make -f CMakeFiles/OpenCV_Stitching_Detailed.dir/build.make CMakeFiles/OpenCV_Stitching_Detailed.dir/depend
make[3]: Entering directory '/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug'
cd "/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug" && /home/matteo/Desktop/Xilinx/App/clion-2016.3.3/bin/cmake/bin/cmake -E cmake_depends "Unix Makefiles" "/home/matteo/CLionProjects/OpenCV Stitching Detailed" "/home/matteo/CLionProjects/OpenCV Stitching Detailed" "/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug" "/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug" "/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug/CMakeFiles/OpenCV_Stitching_Detailed.dir/DependInfo.cmake" --color=
make[3]: Leaving directory '/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug'
/usr/bin/make -f CMakeFiles/OpenCV_Stitching_Detailed.dir/build.make CMakeFiles/OpenCV_Stitching_Detailed.dir/build
make[3]: Entering directory '/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug'
[ 50%] Building CXX object CMakeFiles/OpenCV_Stitching_Detailed.dir/main.cpp.o
/usr/bin/c++    -isystem /usr/local/include -isystem /usr/local/include/opencv  -g   -pg -std=gnu++11 -o CMakeFiles/OpenCV_Stitching_Detailed.dir/main.cpp.o -c "/home/matteo/CLionProjects/OpenCV Stitching Detailed/main.cpp"
[100%] Linking CXX executable OpenCV_Stitching_Detailed
/home/matteo/Desktop/Xilinx/App/clion-2016.3.3/bin/cmake/bin/cmake -E cmake_link_script CMakeFiles/OpenCV_Stitching_Detailed.dir/link.txt --verbose=1
/usr/bin/c++   -g   CMakeFiles/OpenCV_Stitching_Detailed.dir/main.cpp.o  -o OpenCV_Stitching_Detailed /usr/local/lib/libopencv_stitching.so.3.2.0 /usr/local/lib/libopencv_superres.so.3.2.0 /usr/local/lib/libopencv_videostab.so.3.2.0 /usr/local/lib/libopencv_aruco.so.3.2.0 /usr/local/lib/libopencv_bgsegm.so.3.2.0 /usr/local/lib/libopencv_bioinspired.so.3.2.0 /usr/local/lib/libopencv_ccalib.so.3.2.0 /usr/local/lib/libopencv_dpm.so.3.2.0 /usr/local/lib/libopencv_face.so.3.2.0 /usr/local/lib/libopencv_freetype.so.3.2.0 /usr/local/lib/libopencv_fuzzy.so.3.2.0 /usr/local/lib/libopencv_line_descriptor.so.3.2.0 /usr/local/lib/libopencv_optflow.so.3.2.0 /usr/local/lib/libopencv_reg.so.3.2.0 /usr/local/lib/libopencv_saliency.so.3.2.0 /usr/local/lib/libopencv_stereo.so.3.2.0 /usr/local/lib/libopencv_structured_light.so.3.2.0 /usr/local/lib/libopencv_surface_matching.so.3.2.0 /usr/local/lib/libopencv_tracking.so.3.2.0 /usr/local/lib/libopencv_xfeatures2d.so.3.2.0 /usr/local/lib/libopencv_ximgproc.so.3.2.0 /usr/local/lib/libopencv_xobjdetect.so.3.2.0 /usr/local/lib/libopencv_xphoto.so.3.2.0 /usr/local/lib/libopencv_shape.so.3.2.0 /usr/local/lib/libopencv_phase_unwrapping.so.3.2.0 /usr/local/lib/libopencv_rgbd.so.3.2.0 /usr/local/lib/libopencv_calib3d.so.3.2.0 /usr/local/lib/libopencv_video.so.3.2.0 /usr/local/lib/libopencv_datasets.so.3.2.0 /usr/local/lib/libopencv_dnn.so.3.2.0 /usr/local/lib/libopencv_plot.so.3.2.0 /usr/local/lib/libopencv_text.so.3.2.0 /usr/local/lib/libopencv_features2d.so.3.2.0 /usr/local/lib/libopencv_flann.so.3.2.0 /usr/local/lib/libopencv_objdetect.so.3.2.0 /usr/local/lib/libopencv_ml.so.3.2.0 /usr/local/lib/libopencv_highgui.so.3.2.0 /usr/local/lib/libopencv_photo.so.3.2.0 /usr/local/lib/libopencv_videoio.so.3.2.0 /usr/local/lib/libopencv_imgcodecs.so.3.2.0 /usr/local/lib/libopencv_imgproc.so.3.2.0 /usr/local/lib/libopencv_core.so.3.2.0 -Wl,-rpath,/usr/local/lib
make[3]: Leaving directory '/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug'
[100%] Built target OpenCV_Stitching_Detailed
make[2]: Leaving directory '/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug'
/home/matteo/Desktop/Xilinx/App/clion-2016.3.3/bin/cmake/bin/cmake -E cmake_progress_start "/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug/CMakeFiles" 0
make[1]: Leaving directory '/home/matteo/CLionProjects/OpenCV Stitching Detailed/cmake-build-debug'


text:
Q: How do I create an http request from Twilio Studio I'm technical, but not experienced in coding and could use some help. I need to create an http request from Twilio studio. I am setting up a phone survey for my client and I need to log both voice and number inputs from the call to a database. I already have the database set up externally. It logs responses with an http request from CLI curl. I'm using the following curl request successfully:
curl --data "q=1 -X POST localhost/test.php

When I try to duplicate the same curl request using the http request widget (no http parameters), I only get error 500 back. By the way, I know it's collecting the data correctly with the flow because I've had it collect and then read back to me successfully.
Twilio studio http request.
I have tried adding http parameters instead of putting them in the body as well. Nothing I try works. My guess is that I have a fundamental misunderstanding of http requests and thus can't duplicate it in Twilio.
Any help you could give me would be great! Thank you!

A: When you add http parameters instead of putting them in the body (see the capture below)

there is a big red "Save" button on bottom left corner, and a gray (hard to see and easy to miss) "Save" link on the right, above the trash bin.
The gray "Save" link needs to be clicked when adding each name/value pair of the parameters.
The red "Save" button is to be clicked at the end when you're done with the http widget.


text: Q: Abel-Jacobi map (not) holomorphic It is well known (Miranda's Algebraic Curves and Riemann surfaces, p. 266) that if $X$ is a Riemann surface of genus one, then the Abel-Jacobi map, that is defined (locally) as $$J(p)=\int_{p_0}^p \omega,$$ where $p_0$ is a fixed basepoint on $X$, and $\omega$ is a holomorphic 1-form on $X$, is a holomorphic function (of $p$). This fact is used to show that Riemann surfaces of genus 1 and complex 1-tori are the same thing. If the genus of $X$ is $g\geq 2$, then we fix a basis $\omega_1, \ldots. \omega_g$ of the holomorphic 1-forms on $X$, and we define the Abel-Jacobi map as $$J(p)=\Big(\int_{p_0}^p \omega_1, \ldots, \int_{p_0}^p \omega_g\Big).$$ Now, this map cannot be holomorphic, because it would induce a biolomorphism between a Riemann surface of genus $g$ and a complex $g$-torus, right? But what prevents this map to be holomorphic?


text:
Q: PHP closures require arguments passed Trying to figure out why php anonymous functions only work when they are given parameters in the function header.
For example
$f = function(){
    echo "hello world";
};
$f;
$f();

won't work.  But
$f = function($argument){
    echo $argument;
}
$f('hello world');

works just fine.
Why does it need arguments and is there any work around for this?
EDIT
This must be a version issue.  I'm on 5.3.18 and my first example definitely doesn't work.  For those not believing, it throws:
Parse error: syntax error, unexpected T_FUNCTION in index.php(192) :
  eval()'d code on line 1

EDIT
After looking at DaveRandom's answer I'm back to having no idea what's happening.  That is if they are correct that it works in 5.3.10 ...

A: This is perfectly valid syntax and outputs hello world:
$f = function(){
    echo "hello world";
};
$f();

The line $f; does nothing, and would be equivalent to declaring any other variable and then writing that new variable name and a semicolon.
Anonymous functions do not require parameters, see the manual for more details about them.
You are getting those syntax errors because you are running a PHP version < 5.3.

A: This doesn't invoke the closure:
$f;

But this one does:
$f();

Function calls require parens to be recognized by the parser. If you just mention the variable $f; then that's an empty expression. The closure object contained in $f gets assigned to a temporary zval (variable placeholder), then thrown away.

A: The first code works fine if you remove the meaningless $f; line.
Edit Actually, it still works even if you leave that line in. And in 5.3.10 as well.


text:
Q: PHPMailer não reconhece carácter "-" no input do formulário Oi boa noite/manhã/tarde.
To tendo um problema em um input de cadastro simples. Ele simplesmente não reconhece o carácter "-". Fiz um email pra teste "luiz--123@hotmail.com" só que quando retorna com a mensagem se foi ou não enviado fala que o email foi enviado para "luiz123@hotmail.com". Não faço ideia do que seja (AQUI VAI A PARTE DO CÓDIGO DO FORMULÁRIO
`

       Email: *

      Confirma email: *

        <input id="email" type="text" style="width:340px;" autocomplete="off" name="email"></input>

        <input id="confirm_email" type="text" style="width:340px;" autocomplete="off" name="email2"></input>

`

e o php:
<?php
/*
*/
include('../_conf/conf.php');
$validacaocord = "check";
$ck_Config = mssql_fetch_array(mssql_query("SELECT * FROM ".DB_ACC.".dbo.SITE_CONFIG"));
if($ck_Config['Cadastrar'] == 0)
  {
      include('../_erros/manutencao_sistema.php');
  }
if(anti_injection($_POST['checkregister']) != $validacaocord)
    {
      include header('Location: ../index.php');
    }

else
  {
    if ($_POST['sbmtReg']) {
    if($_GET['write'] == true)
        if(preg_match("/[^0-9a-zA-Z]/i", $_GET['write']))
        {
          include header('Location: ../index.php');
        }

    function valid_email($str)
    {
        return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
    }

        $userName     = anti_injection($_POST['userName']);
        $userPwd      = anti_injection($_POST['userPwd']);
        $userPwd2     = anti_injection($_POST['userPwd2']);
        $email        = anti_injection($_POST['email']);
        $email2       = anti_injection($_POST['email2']);
        $PergSecreta  = anti_injection($_POST['PergSecreta']);
        $RespPergun   = anti_injection($_POST['RespPergun']);
        $Hash         = md5(uniqid());
        $Chave        = anti_injection($_POST['Chave']);
        $Nome         = anti_injection($_POST['Nome']);
        $Cidade       = anti_injection($_POST['Cidade']);
        $Enquete      = anti_injection($_POST['Enquete']);
        $sexo         = anti_injection($_POST['sexo']);
        //TEMPJOGO// 0
        $Apelido      = anti_injection($_POST['Apelido']);
        $cpf          = anti_injection($_POST['cpf']);
        //Ativado// 0
        $Pais         = anti_injection($_POST['Pais']);
        $cep          = anti_injection($_POST['cep']);
        $tel     = anti_injection($_POST['tel']);
        $localizacao = anti_injection($_POST['localizacao']);
        $MyTermos = anti_injection($_POST['termoss']);

        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
        $captcha      = anti_injection($_POST['captcha']);
        $captchafinal = anti_injection($_POST['captchafinal']);
        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::://

        ///////////Restricao de Nomes login////////////
        $string = anti_injection($userName);
        $os = array("ADM", "Admin", "GM", "GameMaster", "origi", "machine1", "mania", "adminlixo", "adminnub", "gmlixo", "mamotinho", "mamotinho1", "jeffynho", "serverlixo", "gamenub", "servernub", "falido", "nexus", "sonny", "proxy", "gamemaxx", "estsoft", "cbgames", "pirata", "piratagames", "brutal", "thief");
        /////////////END Names/////////////////

        /////////////SISTEMA DE IMPEDI DOMINIO DE E-MAIL TEMPORARIO///////////////////////////
        $dominioT1 = substr ($email2, strpos ($email2, '@')+1); // Divisão de Dominio após¨ "@"
        ///////////Restricao de Nomes login////////////
        $RestDominio = array("boxtemp.com.br", "getairmail.com", "guerrillamail.com", "sharklasers.com", "mailinator.com", "trashymail.com", "dunflimblag.mailexpire.com", "trbvm.com", "meltmail.com", "mailnesia.com", "filzmail.com", "trashmail.com", "yopmail.com", "mailtemp.net", "ce.mintemail.com", "mt2014.com");
        /////////////THE END DE IMPEDI DOMINIO DE E-MAIL TEMPORARIO///////////////////////////

        $SQL_Q1 = mssql_query("SELECT 1 FROM ".DB_ACC.".dbo.cabal_auth_table WHERE ID ='". $userName ."';");
        $SQL1 = mssql_num_rows($SQL_Q1);
        $SQL_Q2 = mssql_query("SELECT 1 FROM ".DB_ACC.".dbo.cabal_auth_table WHERE Email='". $email ."';");
        $SQL2 = mssql_num_rows($SQL_Q2);
        $SQL_Q3 = mssql_query("SELECT 1 FROM ".DB_CCA.".dbo.CashAccount WHERE ID='". $userName ."';");
        $SQL3 = mssql_num_rows($SQL_Q3);

    if($SQL1 > 0)
      $Error .= "
Login ".$userName." ja esta em uso.
 ";

    if($SQL2 > 0)
     $Error .= "
Email ".$email." ja esta em uso.
 ";

    if($SQL3 > 0)
    $Error .= "
Login ".$userName." esta registrado no banco de dados (Cash) por favor entre em contato com a administração.
 ";

    if(valid_email($email)==FALSE)
       $Error .= "
  Email , formato invalido, exemplo meunome@dominio.com
";

    if($email2 <> $email)//VERIFICAR SI E-MAIL CORRESPONDE AO MESMO RE-DIGITADO //
       $Error .= "
  E-Mail Nao Corresponde ao primeiro E-Mail Digitado Acima.

";

    if(strlen($userName) < 4 || strlen($userName) > 15)
       $Error .= "
  Login requer minimo 4 e maximo 15 digitos
";
    if(preg_match("/[^0-9a-zA-Z]/i", $userName))
       $Error .= "
  Login , digite apenas letras ou numeros
";

    if(strlen($userPwd) < 5 || strlen($userPwd) > 15)//Verificacao de Password //
       $Error .= "
  Senha requer minimo 5 e maximo 15 digitos
";
    if(preg_match("/[^0-9a-zA-Z]/i", $userPwd))
       $Error .= "
  Senha , digite apenas letras ou numeros
";

    if($captcha != $captchafinal)//ERRO CALCULO CAPTACHE//
       $Error .= "
 Os caracteres mostrados na imagem acima nao corresponde aos caracteres que voce digitou
";

    if (in_array($string, $os))//Restricao de Nomes de Usuario//
       $Error .= "
  Voce nao pode ultilizar a palavra ( $userName ) no Campo Login.
";

    if (in_array($dominioT1, $RestDominio))//RESTRINGIR DOMINIO TEMPORARIO//
       $Error .= "
 Desculpe esse é um E-Mail Temporario Não Permitimos, tente utilizar outro dominio de E-Mail.
";

    if($MyTermos != 1)
       $Error .= "
É Obrigatorio você aceite os termos de serviço
";

    if($userPwd2 <> $userPwd)// verificacao de pasword //
       $Error .= "
  Re-senha incorreta

";
    if(strlen($userPwd2) < 5 || strlen($userPwd2) > 15)
       $Error .= "
  Re-senha requer minimo 5 e maximo 15 digitos
";

    if(strlen($Chave) < 4 || strlen($Chave) > 19)
       $Error .= "
  Palavra Chave requer minimo 4 e maximo 19 digitos
";

    if(strlen($Nome) < 3 || strlen($Nome) > 15) //Verificacao de Quantidade de Caracteres Digitados no Campo "NOME"
       $Error .= "
  Nome requer minimo 4 e maximo 10 digitos
";
    if(preg_match("/[^0-9a-zA-Z]/i", $Nome))
       $Error .= "
  Nome , digite apenas letras

  Nome , Nao Use Espacos
";

    if(preg_match("/[^a-zA-Z]/i", $Apelido))
       $Error .= "
  Apelido , digite apenas letras

  Apelido , Nao Use Espacos
";

    if($Apelido == '')
       $Error .= "
  Campo Apelido não pode fica em branco.
";

    if(strlen($Apelido) < 3 || strlen($Apelido) > 15) //Verificacao de Quantidade de Caracteres Digitados no Campo "Apelido"
       $Error .= "
  Apelido requer minimo 4 e maximo 14 digitos
";

    if(preg_match("/[^0-9a-zA-Z]/i", $RespPergun))
       $Error .= "
  Resposta Secreta , digite apenas letras

  Resposta Secreta , Nao Use Espacos
";

    if(strlen($RespPergun) < 3 || strlen($RespPergun) > 16)
       $Error .= "
  O Campo Resposta Secreta Reque no Minimo 4 e no Maximo 15 Caracteres!
";

    if(preg_match("/[^a-zA-Z]/i", $Cidade))
       $Error .= "
  Cidade , digite apenas letras

  Apelido , Nao Use Espacos
";

    if($Cidade == '')
       $Error .= "
  Nao e possivel completo o cadastro com o Campo Cidade Em Branco!
";

    if($Sobrenome == $Nome) //Error Sobrenome Igual a Nome e um uma formar de valida o nome correto d apessoa caso tente coloca os 2 nome iguais//
       $Error .= "
 Error no Campo ,Sobrenome. por favor nao tente nos enganar colocando nome e sobrenome iguais!
";

    if(preg_match("/[^0-9a-zA-Z]/i", $userName))
       $Error .= "
  Palavra Chave , digite apenas letras ou numeros
";

        if(empty($Error) == false)
            echo '

                   Erros encontrados

'.$Error.'

';
                        else

          {

require("../smtp/class.phpmailer.php");

$mail = new PHPMailer();
$mail->SetLanguage("br", "smtp/"); //Idioma
$mail->IsSMTP();

$mail->SMTPAuth = true;
$mail->Host     =   MAIL_HOST;          //Host do servidor SMTP
$mail->Username =   MAIL_USER;          //Nome do usuario SMTP
$mail->Password =   MAIL_PASS;          //Senha do usuario SMTP
$mail->From     =   MAIL_FROM;          //Email de quem envia
$mail->FromName =   MAIL_NAME;          //nome de quem ta enviando, vai aparecer na coluna "De:"

//INICIO --- Quem vai receber-----------------------------------------------
$mail->AddAddress("$email");
//FIM --- Quem vai receber--------------------------------------------------

$mail->AddReplyTo(MAIL_FROM); //Quem ira receber a resposta (quando a pessoal responder)
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';

//Assunto
$mail->Subject = "A batalha vai começar...";
//Corpo da mensagem, pode usar tags html
$mail->Body ="";

if(!$mail->Send())
{
echo "A mensagem nao pode ser enviada.
";
echo "Erro do envio: " . $mail->ErrorInfo;

exit;
}

           //FUNÇÃO SEPARAR DATA DE NASCIMENTO COM VIRGULA//
           $CreatDate = $CampoData;
           $Dat1 =  substr($CreatDate, 0, 2); // Dia
           $Dat2 = substr($CreatDate, 2,2);   // Mês
           $Dat3 = substr($CreatDate, 4, 4);  // Ano
           $DatFinal = "$Dat1-$Dat2-$Dat3";
           //END FUNÇÃO SEPARAR DATA DE NASCIMENTO COM VIRGULA//

            $ROOT = $_SERVER["REMOTE_ADDR"];
            $MEUIP = str_replace("." , "" , $ROOT ); // Primeiro tira os pontos
            $confirm_code= md5 (uniqid(rand())).sha1($email.$userName);

            $hash = md5(date('[d-m-Y]'));
            mssql_query('exec '.DB_ACC.'.dbo.tool_registerAccount "'. $userName .'", "'. $userPwd .'", "'. $email .'", "'. $PergSecreta .'", "'. $RespPergun .'", "'. $Hash .'", "'. $Chave .'", "'. $Nome .'", "'. $Cidade .'", "'. $Enquete .'", "'. $sexo .'", 0, "'. $Apelido .'", 0, "'. $Pais .'", "'. $cep .'", "'. $tel .'", "'. $localizacao .'"');

            echo '
 CADASTRO CONCLUIDO:

Seu registro foi efetuado com sucesso!

 E Obrigatorio voce Realizar a Ativacao de sua conta,

 Foi enviado um Email para '.$email.' com os dados e instrucoes

 Si a Mensagem nao estiver na Caixa de Entrada , Verifique sua Lixeira

';
                      exit;
          }
    }
  }
        ?>

A: Tente em seu formulário:
<input type="email" class="form_control" name="email" required />

E esquece a validação pelo PHP.
Ou:
<input type="text" name="email" pattern="[^ @]*@[^ @]*" required />

Validando em seu HTML. E retira a validação do PHP.
Um exemplo meu é este, mas não sei se cabe no seu, por ser HTML5:

                            E-mail
                            <input type="email" class="form_control" ng-model="usuario.email" name="email" placeholder="E-Mail" ng-required="true" />
                            Preencha o campo E-Mail.


text:
Q: Uncaught ReferenceError: sakla is not defined at HTMLImageElement.onclick I'm new to JavaScript and I'm getting this error. here below is my code:

What could be the problem?

A: Try below code

A: Hey guys here is the answer but I dont know why should I write the script tag twice. Can someone explain?


text:
Q: QT Model/View Project doesnt show Strings from QList My QTableView doesn't show strings from a QStringList.
In QTableWidget I have QTableWidgetItems. Must I set the strings manually or will the view show them automatically? In all the tutorials I don't see a "->setItem", they appear automatically.
I have 2 QLineEdits that give the QStrings to my Model :
void View::pushButtonClicked() {
  meinModel->setData(txtname->text(), txtvalue->text());
}

In setData I push the Strings in two QLists.
names.push_back(name);
values.push_back(value);

I emit a dataChanged signal with the index from topleft and bottomright.
QModelIndex topLeft = createIndex(names.size()+1,0);
QModelIndex bottomRights = createIndex(names.size()-1,1);
emit dataChanged(topLeft, bottomRights);

I have a QAbstractTableModel and so i override the columnCount, rowCount and data Method.
In my data() Method I return my value and name:
QString returnValue;
if(0 == index.column()) { returnValue = names.at(index.row()); }

All of this compiles without warnings, but doesn't work correctly :( Is there something I'm doing obviously wrong?

A: One obvious problem is that you didn't get the semantics of dataChanged correctly. dataChanged means that an existing item has changed its value. When you change the structure of the model by adding/removing rows or columns, you have to enclose the modification in beginXxx and endXxx calls - see this answer for details.
For example:
void MyModel::setData(const QString & name, const QString & value) {
  beginInsertRows(QModelIndex(), names.size(), names.size());
  names.push_back(name);
  values.push_back(value);
  endInsertRows();
}


text:
Q: Statusbar become transparent I need to remove the UINavigationBar shadow image.

so I'm using the code below:
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = UIImage()

It is working perfectly, but the area behind the status bar became transparent, like the image below:

and I don't need this. It should be white. What should I do? Any help will be appreciated.
Thanks in Advance.

A: This occurs beause the navigation bar does not have a specified bar tint color. If you want to have a navigation bar with a bar tint color, you can set it in the IB inspector or programmatically:
navigationController?.navigationBar.barTintColor = .white

A: Well I found the the answer:
It was just online statement, i.e:
navigationController?.navigationBar.isTranslucent = false

By adding this in viewDidLoad it started working as I wanted.
I got helped from this post https://stackoverflow.com/questions/38796259/remove-shadow-line-below-navigation-bar-without-removing-bar-color

A: You have to hide the status bar to remove it.
1.  Open Info.plist file
2.  Click + button to add new key
3.  "UIViewControllerBasedStatusBarAppearance" set to NO


text:
Q: Bintray docker repository storage On Bintray I found out that I have a private docker repository consuming quite a lot of space:
Account usage by repository
I then proceeded to do some house keeping and kept only the last 3 tags of all the images I have. However, that didn't help much. The storage didn't change at all after deleting all these old tags.
I got this API endpoint here: https://bintray.com/docs/api/#_get_package_files to have an estimate on the package files size:
for img in $(cat images) ; do curl -s -XGET -u "user:pass" https://bintray.com/api/v1/packages/my-org/internal-docker/$img/files | python -m json.tool | jq '.[] | .size' | awk '{ sum += $1 } END { print sum }' ; done

Suming all those up gets me 63723101568 bytes, 60GB.
Any idea where the other 310GBs are?
Notice that, even if the 3 tags were completely different from each other, I would get worst case 3x that figure, so 180GB. But the 375GB is still there.

A: Where are you getting the array 'images'?
You are not curling for the entire list but rather single files.
It's possible your list did not include all the images in this repo.
Check to make sure you have traversed all subfolders for images as well.

A: After some time, something changed in the backend storage
I asked on their support (you have to click on Feedback when logged in to Bintary) and they're checking if there was any house keeping done or only after I complained to them something was done.
I'll update if I hear more from them.


text:
Q: R - regex, grep prints out everything I have this:
"81 Delaware St, Staten Island, NY 10304, USA"

I want to capture 81 Delaware St,
Running
grep("^.+?,", "81 Delaware St, Staten Island, NY 10304, USA", value= TRUE)

Returns:
81 Delaware St, Staten Island, NY 10304, USA

I tried perl=TRUE no help, still everything gets printed out.
Example: RegEx, so I know the expression is not wrong.

A: You are confused with the result as your regex actually matches the string you pass to grep and grep just returns all character vectors that where it finds a match. grep does not return substrings.
You may use a sub with a ,.* regex that will match a , and all chars after it and remove that part leaving just the required substring:
s <- "81 Delaware St, Staten Island, NY 10304, USA"
sub(",.*", "", s)
## => [1] "81 Delaware St"

See R demo
Alternative way is to match the substring up to the first ,:
unlist(regmatches(s, gregexpr("^[^,]+", s)))

See this R demo.

A:
...so I know the expression is not wrong.

The expression is wrong. The ^.+? tells grep to return every character from beginning to end.
Here are some helpful resources beyond the R documentation.
Regular Expressions with The R Language
R Regular Expression
Getting and Cleaning Data
One hint: if your street addresses always contain a comma followed by a space (, ) before listing the street - you can use that to split the addresses from the cities. But there is always a way to extract data.


text:
Q: How to pass a string between two activities I am just starting with Android development and I have a problem. I am trying to the next thing:
I have an Activity1 that has a button, "0". Also I have Activity2 that has a TextView and an OK button.
When I press on "0", I want to pass some string to Activity2.
When I press on 0, Activity2 has to open, and in it TextView have to show the string that I passed. After pressing on OK (in Activity2), I want to come back to the Activity1.
I tried to do this in this way:
Activity1
case R.id.b0:
    errorString = "Error: a number can't start with 0";
    Bundle basket = new Bundle();
    basket.putString("error", errorString);
    Intent person = new Intent("my.firsttraining.app.vitali.ERRORPAGE");
    person.putExtras(basket);
    startActivity(person);

Activity2
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    bOK= (Button)findViewById(R.id.bOKonError);
    errorDisplay = (TextView)findViewById(R.id.tvError);

    bOK.setOnClickListener(this);
    setContentView(R.layout.errorpage);

    Bundle gotBasket = getIntent().getExtras();
    String error = gotBasket.getString("error");
    errorDisplay.setText(error); ``

I also tried to do something like this:
Activity1
case R.id.b0:
    errorString = "Error: a number can't start with 0";
    basket = new Bundle();
    basket.putString("error", errorString);
    person = new Intent("my.firsttraining.app.vitali.ERRORPAGE");
    person.putExtras(basket);
    setResult(RESULT_OK, person);
    finish();

Activity2
    bOK.setOnClickListener(this);
    setContentView(R.layout.errorpage);
}

public void onClick(View v)
{
    Intent in = new Intent("my.firsttraining.app.vitali.MENU");
    startActivity(in);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        Bundle gotBasket= data.getExtras();
        String err = gotBasket.getString("error");
        errorDisplay.setText(err);
    }
}

After all this, I have an error. After clicking on Button 0, my application crashes. I get the following error.

The application has stopped unexpectedly. Please try again

and the button with text "Force Close".
I have to say that I do not really understand the second option. I just saw it in some tutorial.

A: In your Activity2.java write setContentView(R.layout.errorpage); after super.onCreate(savedInstanceState); so that view can be intit and then you can get button form view.
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        //Just write this line. You it will load view for
        //activity and then you can get button from it
        setContentView(R.layout.errorpage);

        bOK= (Button)findViewById(R.id.bOKonError);
        errorDisplay = (TextView)findViewById(R.id.tvError);

        bOK.setOnClickListener(this);

        Bundle gotBasket = getIntent().getExtras();
        String error = gotBasket.getString("error");
        errorDisplay.setText(error);


text:
Q: MySQL or PHP to merge 2 tables to give me over table I am running a competition where a user enters a team of 3 golfers chosen form a specific list. These entries are then stored in a table - entries with username,player1,player2,player3.
In a different table in the same database I have players results with each player have a player_name,round1score,round2score,round3score,round4score & totalscore.
I want to create a results set which adds the results of a users 3 players (their team) and sorts them with the lowest score for the combined 3 players.
I am having trouble combining the 2 tables and some people are saying the to merge them using PHP afterwards but not sure the best option.
Also I need to after the final round if there is a tie for 1st place make the team with the lowest round4score the top of the results.
Any help or advice on how to achieve this would be greatly appreciated.
Thanks


text:
Q: How to capture infrared stream from webcam using ffmpeg? I'm able to capture from my webcam using ffmpeg, but it's real color.  But my webcam is advertised as having IR capability.  How do I access this?
When I run ffmpeg -f v4l2 -list_formats all -i /dev/video0 I get this output:
Compressed:       mjpeg :          Motion-JPEG : 1280x720 640x360 640x480 848x480 960x540
Raw       :     yuyv422 :           YUYV 4:2:2 : 160x120 320x180 320x240 424x240 640x360 640x480

The camera specs are given as video: 1280x720 at 30 fps, IR Video: 340x340 at 60 fps
Also, here is the output of v4l2-ctl --list-devices:
Integrated_Webcam_HD: Integrate (usb-0000:00:14.0-11):
    /dev/video0
    /dev/video1

I thought maybe the Raw stream would contain the Infrared video stream, but when I run this:
ffplay -input_format yuyv422 -video_size 320x240 -i /dev/video0

The output looks identical to the 1280x720 output except smaller.
I also ran ffmpeg -f v4l2 -list_formats all -i /dev/video1 and got this output:
Raw       : Unsupported : 00000032-0002-0010-8000-00aa003 : 640x360

But I don't seem to be able to play anything from this device, I get:
Cannot find a proper format for codec 'none' (id 0), pixel format 'none' (id -1)
Assertion *codec_id != AV_CODEC_ID_NONE failed at src/libavdevice/v4l2.c:811

How do I capture infrared video from the webcam?


text:
Q: Number of ways to travel 20 blocks Ying lives at location A and works at location B as indicated below. Note that Ying needs to travel at least 20 blocks to go to work, namely 10 block south and 10 block east. Find a formula for the number of ways Ying can get from home to work (under the condition that she travels only 20 blocks).
This is the diagram:

I know it isn't that hard but something about this just makes me stuck. I am thinking that the answer is 20C10 but I don't think it is correct, and how I would arrive to that.

A: You are correct, the answer is $\binom{20}{10}$.  Think of it this way: to go from $A$ to $B$, you have to exactly $20$ blocks, and $10$ of them must be going south, and $10$ of them east.  So you can think of a path as a sequence consisting of $20$ letters, $10$ of which are an $S$, and the other $10$ must be an $E$.  The number of such sequences is $\binom{20}{10}$.


text:
Q: Current timestamp relative time help :) First off, I want to apologize beforehand, as I know there is a lot of information about this subject on the net. But this has been annoying me the whole day.
In my database (MySQL), I have comments stored with the time they have been written (by using CURRENT_TIMESTAMP). Now I would like to make a script that relates the time between the present and the time that a user wrote a comment (for instance "comment written 6 hours ago...").
But here's the thing, I have tried loads of different scripts and I'm always ending up with the same question. How do I convert my CURRENT_TIMESTAMP to the type of date the script wants me to use?
http://snipplr.com/view/4912/
In the link above there's a code, and you should define the variable with a date. Now, I have the CURRENT_TIMESTAMP and it looks like this:  2012-01-15 16:21:32
Should I just do the date (2012-01-15 16:21:32)?
Sorry again, I know there's a lot of information about this on the web, but I've been working on this the whole day without results.

A: Most scripts out there calculate with epoc time (seconds since 1970), so you'll need to convert the date to seconds then plug into the script: $row['dateUNIX'].
MySQL:
SELECT UNIX_TIMESTAMP(myDateColumnName) as dateUNIX,* FROM `myTable`

A: Yes, I tried the format you had in the post and it worked.

A: If you want to use the linked code for formatting, change this line
$diff = time() - strtotime($date);

to
$diff = time() - $date;

Do as matt has suggested above to get the timestamp of the comment then just:
$date = $row['dateUNIX'];
getRelativeTime($date);

A: Have you tried this script yet?
$diff = time() - strtotime($date); would take your 2012-01-15 16:21:32 and convert it to a useable epoch time.
The script works as intended, with your data, and no changes.
Maybe I'm misunderstanding the issue?


text:
Q: SharePoint 2013 sub-sites is it possible to create parent-child relationships between sub-sites in SP2013? For instance if I set up a master Site called "Projects", and then set up a sub-site in "Projects" called "Website design for X". Could I then create a sub-site that would be a child of "Website Design for X", something like "Design wireframes", so that when I am in "Website design for X" I can see all items that are also part of the sub-site "Design wireframes" ?

A: Yes, you can create a site hierarchy like the one you describe:
1) Projects --> 2) Website Design X --> 3) Design Wireframes
Content Rollup from the sub-sites can be done using Search or Content Query.
However, you should first rethink if it is really necessary to build a site hierarchy of three levels. Creating "Design Wireframes" as a separate Document Library or Picture Library within "Website Design X" may be sufficient in many cases. This would reduce complexity for users while browsing. At the same time your content rollup could be done much easier.


text:
Q: Add time, date and title to UITable cell view I have a table cell view with, currently a date and title. But I want to add the current time to it as well, but I cant seem to add another section in the cell. Can someone show me how?
Here is my cellForRowAt:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath)

    let contact = userInput[indexPath.row]

    cell.detailTextLabel?.numberOfLines = 3
    cell.detailTextLabel?.text = contact.value(forKey:"thf") as? String
    cell.textLabel?.text = contact.value(forKey:"date") as? String

    return cell
}

I dont mind adding the time anywhere but preferably somewhere noticeable
Here is how it looks like

A: *

*First of all write the below code into your date Extension
extension Date {
    func getFormattedDate(format: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        let strDate = dateFormatter.string(from: self)
        return strDate
    }

    func getTimeStamp() -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "hh:mm a"
        let dateString = dateFormatter.string(from: self)
        return dateString
    }
}

*Now use date methods as I have used below:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath)
    let contact = userInput[indexPath.row]
    cell.yourDateLabel?.text = (contact.value(forKey:"keyforDate") as? Date).getFormattedDate(format: "MMM dd,yyyy")
    cell.yourTimeLabel?.text = (contact.value(forKey:"keyforDate") as? Date).getTimeStamp()
    return cell
}


text:
Q: onDraw not called in a custom view added to overlay with windows manager I'm tearing my hair out over why my view only draws the first time.  I've created a  custom view that draws a bitmap for me.  It's onDraw looks like this:
protected void onDraw(Canvas canvas) {
            Paint p = new Paint();
            canvas.drawBitmap(mBitmap, 0, 0, p);
            Log.e(TAG, "CALLED");
}

Then in my main activity I set it up like this:
mDView = new drawableView(this, null);
mDView.setLayoutParams(new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.MATCH_PARENT,
    LinearLayout.LayoutParams.MATCH_PARENT));
mDView.setOnClickListener(this);
mDView.setClickable(false);
mDView.setFocusable(false);
mDView.setWillNotDraw(false);
int id = 201;
mDView.setId(id);
wm.addView(mDView, topLeftParams);

wm is my windows manager
wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

Then finally I have a call back function that gets called in my main activity:
@Override
public void onFillEvent()
{
    Log.e(TAG, "onFillMain");
    mDView.setBitmap(mDepth.mFrameBuffer);
    mDepth.fillDepthBuffer();
    int id = 201;
    getParent().findViewById(id).invalidate();
    mDView.invalidate();
    mDView.postInvalidate();

}

I've tried all three methods to invalidate the view in the windows manager.  But what happens is the first bitmap it drew stays on the screen.  I never see onDraw log "CALLED" after the first time.  I do see my call back getting called all the time and logging onFillMain.
I later tried adding an onLayout method to my custom view but that doesn't call and log either. I'm pretty stuck what am I missing?

A: In order to trigger a change in the overlay, you have to call
wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
wm.updateViewLayout(mDView, topLeftParams);


text:
Q: Why might Chrome (inside Electron) suddenly redirect to chrome-error://chromewebdata? My electron app is randomly redirecting to chrome-error://chromewebdata, and I've no idea why. There's no errors in the console, etc.
When the Electron app first starts, the window opens, and it redirects away from my application to that URL and I see an empty blank white screen. No user interaction is necessary, it just happens when the app starts.
If I open devtools, I can see that window.location.href contains chrome-error://chromewebdata instead of http://localhost:9080 (the Electron app runs using a localhost URL).
I tried deleting the local Electron/Chrome data folder at ~/Library/Application Support/my-app-name and starting over, but no luck.
What are reasons that Chrome (in Electron?) can decide to redirect to chrome-error://chromewebdata?

A: For some reason, your code is trying to navigate to an invalid (non-existing) URL, which then results in window.location.href being chrome-error://chromewebdata.
To reiterate: there is no direct redirection to chrome-error://chromewebdata, but instead to a URL that doesn't exist or is not reachable.
Check if your code causes this navigation (possibly a redirect). It is very useful to inspect the Network tab in DevTools, making sure that "Preserve log" is checked. This should give some indication about what exactly is happening.

A: This is happening for me in my Angular based Electron project. In my case, the problem is that Angular's Webpack server isn't ready to receive requests when I first launch the project. This is only at startup and simple reload can get around it - any live changes to the Angular code will refresh the page without any issue.
This isn't a problem in production as I switch to loading static files in my releases.
To make this a little less annoying, I added a delay to my electron startup:
"start": "concurrently -k \"ng serve\" \"npm run delay && nodemon\"",
"delay": "node -e \"setTimeout(() => true, 3000)\"",

Where:

*

*concurrently runs Electron and Angular/Webpack at the same time for faster development.

*nodemon watches my electron files and restarts the app when I save changes

*delay just uses node to delay nodemon's first startup (works on all operating systems...)

And just for clarity, my nodemon.json:
{
    "watch": ["nucleus"],
    "ext": "*",
    "exec": "tsc -p nucleus/tsconfig.json && electron ."
}

A: view-vhcl-cntr-ctgrs.tpl
i replace this file name like below.
view-vhclcntr-ctgrs.tpl
and it worked....

A: To me it was launchPath issue. As I had multiple electron apps in my workspace (NX).
So all I needed to do is to set correct url to launch electron.
It was 4200 by default so I updated it to 4202 b/c I already had 4200 & 4201.
let launchPath;
  if (serve) {
    require('electron-reload')(__dirname, {
      electron: require(`${__dirname}/../../../node_modules/electron`),
    });
    launchPath = 'http://localhost:4202';
    win.loadURL(launchPath);
  } else {
    launchPath = url.format({
      pathname: path.join(__dirname, 'index.html'),
      protocol: 'file:',
      slashes: true,
    });
    win.loadURL(launchPath);
  }

  console.log('launched electron with:', launchPath);


text:
Q: How to get a total sum for each Description and order it in dynamic pivot I need to display only top 10 rows based on total sum for each Class and order it by Total sum desc.
This is what I am trying to achieve:

So I have my dynamic pivot but I cant understand how to get total column for each row and then display only top 10 by Total column.
DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)

SELECT @cols = STUFF(
                    (SELECT distinct ',' + QUOTENAME([YearMonth])
                    FROM #MyTable
                    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
--print @cols

SELECT @query =
'
        ;with cte_TopClasses
AS  (
        SELECT
                    CAST(b.MonthNum as varchar(2)) + ''/''+ CAST(b.YearNum as varchar(4)) as YearMonth,
                    b.YearNum,
                    b.MonthNum,
                    GovClassCode + ''- '' + dda.GovClassDesc as Class,
                    ISNULL(SUM(Premium),0) as NetWrittenPremium
        FROM        tblCalendar b
        LEFT JOIN   ProductionReportMetrics prm ON b.YearNum = Year(prm.EffectiveDate) AND b.MonthNum=Month(prm.EffectiveDate) AND  CompanyLine = ''Arch Insurance Company''
        LEFT JOIN   [dbo].[Dynamic_Data_ArchWC] dda ON prm.QuoteGUID = dda.QuoteGuid
        WHERE
                    ( b.YearNum = YEAR(GETDATE())-1 and b.MonthNum >= MONTH(GETDATE())+1 ) OR
                    ( b.YearNum = YEAR(GETDATE()) and b.MonthNum <= MONTH(GETDATE()) )
                    AND GovClassCode + '' - '' + dda.GovClassDesc IS NOT NULL
        GROUP BY    b.YearNum ,
                    b.MonthNum,
                    GovClassCode,
                    dda.GovClassDesc
    )
SELECT * FROM
(SELECT
    [YearMonth],
    Class,
    NetWrittenPremium
FROM cte_TopClasses)X

PIVOT
(
    sum(NetWrittenPremium)
    for [YearMonth] in (' + @cols + ')
) P
'

EXEC SP_EXECUTESQL @query

output from that is 73 rows:

UPDATE: using GROUPING SETS

UPDATE: This is how data looks before PIVOT:

A: What about this:
DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)

SELECT @cols = STUFF(
                    (SELECT distinct ',' + QUOTENAME([YearMonth])
                    FROM #MyTable
                    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') + ',' + '[Total]'
--print @cols

SELECT @query =
'
        ;with cte_TopClasses
AS  (
        SELECT
                    ISNULL(CAST(b.MonthNum as varchar(2)) + ''/''+ CAST(b.YearNum as varchar(4)), ''Total'') as YearMonth,
                    b.YearNum,
                    b.MonthNum,
                    GovClassCode + ''- '' + dda.GovClassDesc as Class,
                    ISNULL(SUM(Premium),0) as NetWrittenPremium
        FROM        tblCalendar b
        LEFT JOIN   ProductionReportMetrics prm ON b.YearNum = Year(prm.EffectiveDate) AND b.MonthNum=Month(prm.EffectiveDate) AND  CompanyLine = ''Arch Insurance Company''
        LEFT JOIN   [dbo].[Dynamic_Data_ArchWC] dda ON prm.QuoteGUID = dda.QuoteGuid
        WHERE
                    ( b.YearNum = YEAR(GETDATE())-1 and b.MonthNum >= MONTH(GETDATE())+1 ) OR
                    ( b.YearNum = YEAR(GETDATE()) and b.MonthNum <= MONTH(GETDATE()) )
                    AND GovClassCode + '' - '' + dda.GovClassDesc IS NOT NULL
        GROUP BY    GROUPING SETS
        (
                (
                    b.YearNum ,
                    b.MonthNum,
                    GovClassCode,
                    dda.GovClassDesc
                )
                ,
                (
                    GovClassCode
                   ,dda.GovClassDesc
                )
        )
    )
SELECT * FROM
(SELECT
    [YearMonth],
    Class,
    NetWrittenPremium
FROM cte_TopClasses)X

PIVOT
(
    sum(NetWrittenPremium)
    for [YearMonth] in (' + @cols + ')
) P
'

EXEC SP_EXECUTESQL @query

The idea is to add the Total column in T-SQL using GROUPING SETS


text:
Q: What is the difference between assignment and overriding in a child class? This has been bugging me for a while and appears hard to google.
In the following code can anyone explain the pragmatic difference between FirstChild and SecondChild.  It's clear from experiments that both "work" and arguably SecondChild is marginally more efficient.  But is there something that I'm missing about the way these two behave?  Are they different and how are they different?
import collections

class Parent:

    def send_message(self, message: str):
        pass

class FirstChild(Parent):

    def __init__(self):
        self.message_queue = collections.deque()

    def send_message(self, message: str):
        self.message_queue.append(message)

class SecondChild(Parent):

    def __init__(self):
        self.message_queue = collections.deque()
        self.send_message = self.message_queue.append

A: FirstChild creates a descriptor in the class called send_message. When you do instance.send_message, the interpreter first searches the instance __dict__ for the name, then the class. When it's found in the class, the function is bound to the instance to create a method object that doesn't accept self. It happens every time you do the lookup, and it looks something like
method = type(instance).send_message.__get__(type(instance), instance)

SecondChild assigns a bound method as the attribute send_message in the instance. It cuts out the lookup in its own class object, as well as the lookup in the deque class object, and binding. That is probably why it appears marginally more efficient.
A major practical difference between these approaches is that send_message in SecondChild is not overridable. Since functions are non data descriptors (they have a __get__ method but not __set__ (and yes, functions have a class type and methods, like any other object)), the instance attribute send_message in SecondChild will always trump any class-level function. This means that a child of SecondChild that calls the parent __init__ method will hide any implementation of send_message it creates.
You will likely find the official descriptor guide to be quite informative: https://docs.python.org/3/howto/descriptor.html