text:
Q: java.lang.ClassNotFoundException: org.apache.cxf.transport.servlet.CXFServlet I am new to Apache CXF and I was trying to deploy a sample CXF webservice in Jboss 9.0.1.  But I am continuosly getting the error
java.lang.ClassNotFoundException: org.apache.cxf.transport.servlet.CXFServlet.
I spent a lot of time to fix this issues. The things I have done so far are
1) Checked for the jar file cxf-rt-transports-http-..*.jar. This is existing in my war file.
2) Made parent last class loading in jboss by specifying the xml file jboss-classloading.xml
But still the same error exists. Attached the files
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    version="2.5"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>cxf</display-name>
    <servlet>
        <description>Apache CXF Endpoint</description>
        <display-name>cxf</display-name>
        <servlet-name>cxf</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>cxf</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>60</session-timeout>
    </session-config>
</web-app>

cxf-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:soap="http://cxf.apache.org/bindings/soap"
    xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/bindings/soap http://cxf.apache.org/schemas/configuration/soap.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
    <jaxws:server id="jaxwsService" serviceClass="demo.hw.server.HelloWorld"
        address="/hello_world">
        <jaxws:serviceBean>
            <bean class="demo.hw.server.HelloWorldImpl" />
        </jaxws:serviceBean>
    </jaxws:server>
</beans>

pom.xml
<?xml version="1.0"?>
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor
    license agreements. See the NOTICE file distributed with this work for additional
    information regarding copyright ownership. The ASF licenses this file to
    you under the Apache License, Version 2.0 (the "License"); you may not use
    this file except in compliance with the License. You may obtain a copy of
    the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
    by applicable law or agreed to in writing, software distributed under the
    License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
    OF ANY KIND, either express or implied. See the License for the specific
    language governing permissions and limitations under the License. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>demo.hw.server</groupId>
    <artifactId>java_first_jaxws</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Java First demo using JAX-WS APIs</name>
    <description>Java First demo using JAX-WS APIs</description>
    <properties>
        <cxf.version>3.1.6</cxf.version>
        <cxf.release.base>${basedir}/../..</cxf.release.base>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
            <version>3.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-simple</artifactId>
            <version>2.7.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-core</artifactId>
            <version>2.7.18</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-databinding-aegis</artifactId>
            <version>3.0.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-local</artifactId>
            <version>3.1.6</version>
        </dependency>
    </dependencies>
</project>

A: I would recommend you reading http://cxf.apache.org/docs/cxf-architecture.html#CXFArchitecture-AJAX-WSexample  first before you start working with the Apache cxf.
 Also make sure you add the correct bundle of apache-cxf dependency.


text:
Q: Persisting hasMany assoc in emberdata Any examples of persisting new model entity with hasMany associacion?

A: Here is an example, see http://jsfiddle.net/pangratz666/vuT2v/
App.Comment = DS.Model.extend({
    text: DS.attr('string')
});

App.Post = DS.Model.extend({
    title: DS.attr('string'),
    comments: DS.hasMany('App.Comment')
});

var first = App.Comment.createRecord({
    id: 'firstComment',
    text: 'first comment'
});
var second = App.Comment.createRecord({
    id: 'secondComment',
    text: 'second comment'
});

var post = App.Post.createRecord({
    id: 1,
    title: 'post title'
});

var comments = post.get('comments');
comments.addObject(first);
comments.addObject(second);

App.store.commit();

redpajama_set_name: RedPajamaStackExchange


text:
Q: ORACLE PL/SQL - SCHEDULE CREATE TABLE I need to create a table every morning based on overnight generated data from a massive table. This will then be accessed by a handful of users form Excel.
My initial approach was to use a materilazed view and when this was rejected (for political reasons) to used Managed XLL but this was rejected for other reasons. I don't want to get messed up with Temporary tables and so really just need to know how to schedule an Oracle Create Table statement as our DBA says it can't be done.
My faith in SO users sasy otherwise though!

A: I don't see why you have to create a new table every morning and not use an existing one?

This creates your table from PL/SQL. Is this what you want?
CREATE OR REPLACE PROCEDURE make_table AS
BEGIN
  EXECUTE IMMEDIATE 'CREATE TABLE your_table ( column_1 INT PRIMARY KEY, column_2 VARCHAR2(10) )';
END make_table;
/

EXEC make_table;

Your user needs to have the necessary grants, grants given by role don't apply to compiled PL/SQL code.


text:
Q: How can I stack this Z-index configuration? I have a situation whereby:
My Hierarchy is:
box1: (z-index: 5000)
  -(other parent elements)
    -box1_child (z-index: 5001)
box2 (z-index: 5000)
  -(other parent elements)
    -box2_child (z-index: 5002)

So obviously, I want box1 and box2 at the same level.
I want box1_child to sit over box2.
I want box2_cihld to sit over box1_child.
But it's not working (in FF4), basically, box1_child isn't sitting over box2.
Is this possible, (on the more recent browsers?)
All elements have a non-static position.

A: Even if two adjacent elements have the same Z-index, they still have a certain stacking order: the one that comes later is drawn over the first.
Using this, you can use this CSS (simplified) to stack the elements in the way you want.
#box1{
    position: absolute;
    z-index:auto;
}
#box1_child {
    position: absolute;
    z-index:1;
}
#box2{
    position: absolute;
    z-index:auto;
}
#box2_child {
    position: absolute;
    z-index:1;
}

Then box2 is drawn on over box1 (if they overlap at all) and box2_child is drawn over box1_child, but both children are drawn over the parent boxes.
jsFiddle.
Tested on various newer browsers. I don't have Firefox 4 here, so can't confirm that it doesn't work there.
Edit: Seems I was wrong in my assumption that z-index:0 is the same as auto. Indeed it doesn't work with 0, so it won't work with 5000 either. My apologies.

A: Things with non-auto z-index form a new stacking context that stacks atomically.
So to get the effect you want you need box1 and box2 to have auto z-index...  Note that a positive z-index will stack above auto, so that should give you the behavior you want.


text:
Q: Como faço para fazer um case when no load data infile? Preciso fazer uma replace da mesma coluna de varias string distintas, fazer um load data infile.
Só que dá um erro de sintaxe na linha 12 onde tem o primeiro case, alguém sabe o que estou fazendo de errado o código esta abaixo?
LOAD DATA LOCAL INFILE 'c:/temp/reportes/fornecedor.csv'
                            INTO TABLE reparo.pn_digitron
                            FIELDS TERMINATED BY ','
                            ENCLOSED BY '"'
                            LINES TERMINATED BY '\r\n'
                            IGNORE 1 LINES
                            (@modelo,@tipo,
                            @part_number,@fornecedor,@descricao_bom)
                            SET
                            `Modelo` = trim(@modelo),
                            `tipo` = trim(@tipo),
                            case when `part_number` = 'DT' then
                            `part_number` = trim(replace(@part_number, 'DT', 'MB')),
                            when `part_number` = 'NB' then
                            `part_number` = trim(replace(@part_number, 'NB', 'MB')),
                            when `part_number` = 'EBG' then
                            `part_number` = trim(replace(@part_number, 'EBG', 'MB')),
                            when `part_number` = 'SMALL' then
                            `part_number` = trim(replace(@part_number, 'SMALL', 'SB')) end,
                            `fornecedor` = trim(@fornecedor),
                            `descricao_bom` = trim(@descricao_bom);

A: O CASE WHEN não te permite definir uma expressão de SET inteira como você tentou fazer. Você só pode usá-lo do lado direito da atribuição, assim:
...
SET
    `Modelo` = trim(@modelo),
    `tipo` = trim(@tipo),
    `part_number` = CASE
                      WHEN `part_number` = 'DT' THEN trim(replace(@part_number, 'DT', 'MB'))
                      WHEN `part_number` = 'NB' THEN
                      ...
                      END


text:
Q: Cannot close  element with display set to grid The HtmlDialogElement.close() function seems to have no effect on a <dialog> element when that dialog has its display style set to grid.
Does anyone happen to know why? Note that removing the display: grid allow the dialog to function correctly. I have seen this behavior on the latest versions of both Chrome and Firefox.
See minimum reproduction below. If you prefer, here's a Codepen: https://codepen.io/ChristianMay/pen/MWrmdzJ

let dialog = document.querySelector('dialog')
let closeButton = document.querySelector("#dialog-close");
closeButton.addEventListener('click', () => {
  dialog.close();
})
dialog {
  display: grid;
}
<dialog class="dialog" open="">
  Test
</dialog>

<button id="dialog-close">Close dialog</button>

A: The dialog is considered to be open (or shown) if the attribute open is present.
Once this attribute is not present, the dialog is hidden. I suppose that setting the display to grid overrides the default styling for dialog, which should hide the dialog whenever open is removed. We could restore this behavior by adding styling to the dialog without open attribute.

let dialog = document.querySelector('dialog')
let closeButton = document.querySelector("#dialog-close");
closeButton.addEventListener('click', () => {
   dialog.close();
})
dialog:not([open]){
  display:none;
}

dialog{
  display:grid;
}
<dialog class="dialog" open="">
  Test
</dialog>

<button id="dialog-close">Close dialog</button>

A: Already answered , but you could also display <dialog> as a grid only if it is an opened dialog ;)
dialog[open] {
  display: grid;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
The CSS attribute selector matches elements based on the presence or value of a given attribute.

Demo snippet using the CSS attribute selector

const dialog = document.querySelector('dialog')

let closeButton = document.querySelector("#dialog-close");
closeButton.addEventListener('click', () => {
  dialog.removeAttribute("open");
})

let openButton = document.querySelector("#dialog-open");
openButton.addEventListener('click', () => {
  dialog.setAttribute("open", "");
})
dialog[open] {
  display: grid;
}
<dialog class="dialog" open="">
  Test
</dialog>

<button id="dialog-close">Close dialog</button>
<button id="dialog-open">Open dialog</button>

fork of your pen


text:
Q: Galois Groups of Finite Extensions of Fixed Fields I am trying to prove the following proposition:

Let $L$ be an algebraically closed field, $g \in Aut(L)$ and $K=\{x \in L \; | \; g(x)=x\}$. Show that every finite extensions $E/K$ is a cyclic Galois extension.

So far my thoughts have led me to the following:
If $E=K$, then clearly $E/K$ is Galois and $Gal(E/K)=Aut(K/K)=i$, where $i$ is the identity automorphism, so it is trivially cyclic. Assume $[E:K]=n$ for some $n>1$. Since $E/K$ is a finite extension, it is algebraic. Note that if $\beta \in E\setminus F$ then we have the minimal polynomial $m_{\beta}(X)$ over $K[x]$. Since $K$ is fixed by $g$, we know that $g(\beta)$ is also a root of $m_{\beta}(X)$. We can also conclude that $g(\beta)\not \in K$ since $\beta \not \in K$.
Where to take any of these observations, I have yet to determine. I feel I must be missing something elementary, for I cannot see how to conclude this is a Galois extension from here.
Any tips would be greatly appreciated, especially over full solutions.

A: Hint: Assume that $x(\in L)$ is algebraic over $K$. The set $\{g^i(x)\mid i\in\mathbf{N}\}$ is then finite, as $x$ has only finitely many conjugates over $K$. It follows that a suitable polynomial of the form
$$
\prod_{i=0}^{n-1}(T-g^i(x))\in K[T].
$$
Using this you can hopefully prove that if $N$ is a normal closure of $E/K$, then $Gal(N/K)=\langle g\rangle$. The rest is easy.


text:
Q: How to run testcase and testsuite using Groovy in soapui? i have some projects in soapui.
i want to execute testsuites and testcases of these projects.
i tried with this groovy code:
//get test case from other project or from the same one
project = testRunner.getTestCase().getTestSuite().getProject().getWorkspace().getProjectByName("Project1")
testSuite = project.getTestSuiteByName("TestSuite 1 - Login");
testCase = testSuite.getTestCaseByName("TestCase 1-Login");
Thread.sleep(3000)
testSuite2 = project.getTestSuiteByName("TestSuite3 - Report");
testCase2 = testSuite.getTestCaseByName("TestCase1 - Report");

// run test case
runner = testCase.run(new com.eviware.soapui.support.types.StringToObjectMap(), false);
Thread.sleep(3000)
runner2 = testCase2.run(new com.eviware.soapui.support.types.StringToObjectMap(), false);

When i run this groovy code, i have the following error message:
java.lang.NullPointer.Exception
cannot invoke method run() on null object for the last line
runner2 = testCase2.run(new com.eviware.soapui.support.types.StringToObjectMap(), false);

If i remove the last line it's working well.
Any help please.
Thank you

A: I know this is super late to answer this question, but i will answer this so that it can help help seeking for help.
instead of Thread.sleep(3000), just use:
runner.waitUntilFinished()

Now it will wait until execution of step 1 get finished. Then it will start executing Step 2.

A: The only thing I can think of is that you're calling the wrong testcase on the step2, I tested the same with other test cases I have and it's happening the same If I put a wrong name for the test case I want to execute.

A: // TO RUN A TEST SUITEs ALL get APIs, getting testSuite handle from current          //test_Case
// TO POST COMMENT I HAVE ADDED underscore char BELOW

// u need to import here
 def my_TestSuite = testRunner.testCase.testSuite
 log.info(my_TestSuite.name)

 for (my_TestCase in my_TestSuite.get_TestCaseList())
 {
      for (testStep in myTestCase.get_TestStepList())
      {
         if( testStep instanceof WsdlTestRequestStep || testStep instanceof                       RestTestRequestStep ) {
                  def http_Verb = (testStep.getTestRequest().getMethod())
                  String apiType = http_Verb.toString()
                  if (apiType == "GET"){
                    log.info(myTestCase.name)
                 }
             }
         }
  }


text:
Q: Nest Js build to Heroku is successful but routes not working So for tow days i struggle to deploy my first backend app to Heroku (i use nest.js with prisma), but i get all sort of errors. I've bring all to latest versions and now I struggle with only one error but I can't figure it out. As far I can tell the problem is in my package.json. Can someone take a look at this package.json file and tell me what I missed?
I think that i've tried all posible version from stackoverflow and other tutorials for "start:prod" script. I'm not sure if this is the problem.
Thank you so much in advance!
If you have any hint on what I should do to fix this it's much apreciate because i'm stuck at this.
This is my package.json
{

  "name": "dez-backend",
  "version": "0.0.1",
  "engines": {
    "node":"18.x",
    "npm": "9.x"
  },
  "description": "Backend developed for edez mobile App",
  "author": "Draghici Adrian",
  "private": true,
  "license": "UNLICENSED",
  "type": "module",
  "scripts": {
    "prebuild": "rimraf dist",
    "postinstall": "npx prisma generate && npm run build",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },
  "dependencies": {
    "@nestjs/axios": "^2.0.0",
    "@nestjs/common": "^9.3.9",
    "@nestjs/core": "^9.3.9",
    "@nestjs/jwt": "^10.0.2",
    "@nestjs/passport": "^9.0.3",
    "@nestjs/platform-express": "^9.3.9",
    "@prisma/client": "^4.11.0",
    "@types/body-parser": "^1.19.2",
    "aws-sdk": "^2.997.0",
    "axios": "^1.3.4",
    "bcrypt": "^5.1.0",
    "body-parser": "^1.20.2",
    "class-transformer": "^0.4.0",
    "class-validator": "^0.14.0",
    "dotenv": "^10.0.0",
    "nestjs-s3": "^1.0.1",
    "nodemon": "^2.0.20",
    "passport": "^0.6.0",
    "passport-jwt": "^4.0.0",
    "path": "^0.12.7",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "ts-node": "^9.1.1"

  },
  "devDependencies": {
    "@nestjs/cli": "^9.2.0",
    "@nestjs/schematics": "^7.3.0",
    "@nestjs/testing": "^9.3.9",
    "@types/express": "^4.17.11",
    "@types/jest": "^26.0.22",
    "@types/multer": "^1.4.7",
    "@types/node": "^14.14.36",
    "@types/supertest": "^2.0.10",
    "@typescript-eslint/eslint-plugin": "^4.19.0",
    "@typescript-eslint/parser": "^4.19.0",
    "eslint": "^7.22.0",
    "eslint-config-prettier": "^8.1.0",
    "eslint-plugin-prettier": "^3.3.1",
    "jest": "^26.6.3",
    "prettier": "^2.2.1",
    "prisma": "^4.11.0",
    "supertest": "^6.1.3",
    "ts-jest": "^26.5.4",
    "ts-loader": "^8.0.18",
    "ts-node": "^9.1.1",
    "tsconfig-paths": "^3.9.0",
    "typescript": "^4.2.3"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}

And this are the logs from Heroku:

2023-03-04T10:39:37.000000+00:00 app[api]: Build succeeded
2023-03-0410:39:43.776332+00:00 heroku[web.1]: Starting process with command "npm run start:prod*
2023-03-04T10:39:47.341244+00:00 heroku[web.1]: State changed from starting to crashed
config
2023-03-04T10:39:46.879061+00:00 app [web. 1]: pm WARN config production Use
--omit=dev' instead.
2023-03-04T10:39:46.938577+00:00 app [web. 1]:
2023-03-04T10:39:46.938579+00:00 app [web. 1]: > dez-backend@0.0.1 start:prod
2023-03-04T10:39:46.938581+00:00 app [web. 1]: > node dist/main
2023-03-04T10:39:46.938581+00:00 app [web. 1]:
2023-03-04T10:39:47.029449+00:00 app [web. 1] : node: internal/modules/cjs/loader: 1078
2023-03-04T10:39:47.029452+00:00 app [web.1]: throw err;
2023-03-04T10:39:47.029452+00:00 app [web. 1]:
2023-03-04T10:39:47.029453+00:00 app [web. 1]:
2023-03-04T10:39:47.029453+00:00 app [web. 1]: Error: Cannot find module '/app/dist/main'
2023-03-04710:39:47.029453+00:00 app (web. 1]: at Module._resolveFilename (node: internal/modules/cis/loader: 1075:15)
2023-03-04T10:39:47.029454+00:00 app [web. 1]: at Module._load (node: internal/modules/cjs/loader: 920:27)
2023-03-04710:39:47.029454+00:00 app[web. 1]: at Function.executeUserEntryPoint [as runMain] (node: internal/modules/run_mai n:81:12)
2023-03-04T10:39:47.029454+00:00 app [web. 1]: at node: internal/main/run_main_module: 23:47 {
2023-03-04T10:39:47.029455+00:00 app [web. 1]: code: 'MODULE NOT FOUND'
2023-03-04T10:39:47.029455+00:00 app [web. 1]: requireStack: []
2023-03-04T10:39:47.029455+00:00 app [web. 1]: }
2023-03-04T10:39:47.029470+00:00 app [web. 1]:
2023-03-04T10:39:47.029470+00:00 app [web. 1]: Node.is v18.14.2
2023-03-04T10:39:47.292073+00:00 heroku[web. 1]: Process exited with status 1

Here is my Procfile:
web: npm run start:prod

A: I finally found the problem:
Instead of :
"start:prod": "node dist/main",

I added :
"start:prod": "node dist/src/main",

And it worked. The main file was located in ../src/main.ts. So i need to add the correct path to it.


text:
Q: Using Packery with Angular 2 I can't seem to get Packery working with Angular 2 using angular-cli and typescript 2.0.
I'm using Packery 1.4.1 and the typescript definitions for that version from DefinitelyTyped.
The issue is that the Packery reference to Outlayer cannot be found when running the project with ng serve.
Specifically the following exception is thrown due to that:

TypeError: Cannot set property 'position' of undefined
      at Object.utils.extend (eval at webpackJsonp.82.module.exports

Below is my code for the project.
Scripts section from angular-cli.json:
"scripts": [
        "../node_modules/packery/dist/packery.pkgd.js"],

I have also tried adding the dependent js files but the exception thrown is the same:
"scripts": [
        "../node_modules/packery/dist/packery.pkgd.js",
        "../node_modules/get-size/get-size.js",
        "../node_modules/outlayer/outlayer.js",
        "../node_modules/ev-emitter/ev-emitter.js",
        "../node_modules/fizzy-ui-utils/utils.js",
        "../node_modules/desandro-matches-selector/matches-selector.js"
        ],

app.component.ts:
import { Component, ViewChild, AfterViewInit } from '@angular/core';
declare var Packery: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit
{
  @ViewChild('grid') grid;

  private pckry: any;
  constructor() {}

  ngAfterViewInit(){
    this.pckry = new Packery(this.grid, {
      itemSelector: '.grid-item'});
  }
}

app.component.html

I would like help on how to get Packery to run in Angular 2 with or without typings (vanilla js would be ok for me).

A: The issue with the above was that I did not use the "nativeElement" property of the grid. This will work:
var packery = new Packery(this.grid.nativeElement, {
itemSelector: '.grid-item', columnWidth: 100 });

Also the only script needed in the scripts section of angular-cli is the following:
"scripts": [
        "../node_modules/packery/dist/packery.pkgd.js"
        ]

To add draggability use "npm install draggability --save" and add another script to the scripts section of angular-cli:
"scripts": [
        "../node_modules/packery/dist/packery.pkgd.min.js",
        "../node_modules/draggabilly/dist/draggabilly.pkgd.min.js"
        ]

Then update the component class as well:
import { Component, ViewChild, AfterViewInit } from '@angular/core';
declare var Packery: any;
declare var Draggabilly: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit
{
  @ViewChild('grid') grid;

  constructor() {}

  ngAfterViewInit(){
      var packery = new Packery(this.grid.nativeElement, {
        itemSelector: '.grid-item', columnWidth: 100 });

      packery.getItemElements().forEach( function( itemElem ) {
        var draggie = new Draggabilly( itemElem );
        packery.bindDraggabillyEvents( draggie );
      });
  }
}


text:
Q: Implementing MVC/MVP Design for TabControl ..design question I have a an Winform application with 2 forms.
In one form I have a Tab Control with 3 Tabs and navigation buttons to switch between tabs.
On the first tab the user selects a file and on navigating to next tab i want to do some
processing on the file selected in the first tab,and show the result in the 3rd tab.
The other form just invokes this form(start app.)
How can i do this using MVC/MVP ?
Currently i have created nested forms.
Starting application form creates instance of tab form and on SelectedIndexChanged on
the tab control and matching the selected tab property I'm doing the processing in the starting application form.and  On closing on the tab form setting the result in the
starting application form.(which isn't ideal).
Edit : Also each tab contains a User Control which i have to initialize on tab change (refereeing to the data selected in the previous tab.)
Simple example is selecting a .zip file in the first tab , clicking next
will show the list of files within the zip file and in the third tab do processing with
the file selected in the 2nd tab.(there are better ways to do the same..just for sake of example.)
EDIT 2 : Basically I'm confused on how to get values from first tab via controller, do processing, and pass it to the next tab( via controller) and set the user control properties on the 2nd tab (via controller).Also the Tab titles are removed ..please see ..so the Tab form looks more like a wizard form. that's why i was using the SelectedIndexChanged property.
Basically i need to separate view and processing logic from the Winform.
Thanks All.

A: Odd choices for a UI.  Anyhoo, there is no reason whatsoever to wait for SelectedIndexChanged to process the file.  You might as well do it as soon as the file is selected.  It will work better, the tab control becomes more responsive.  If you wait until the event then the control will be frozen for a while as your UI thread is busy iterating the .zip file.  The user will not consider this desirable.
Makes the MVC implementation a lot simpler too, whatever it might look like.  Extra bonus is that you now no longer depend on the TabControl and can use whatever controls are best for the job.

A: Your Model will deal with your zip file in this case, e.g. methods like Print(), Extract() etc. and events like  PrintCompleted and ExtractCompleted etc.
Your IView will expose methods and events that abstract your interaction with the UI behind an interface. So perhaps some methods such as DisplayFolderContents() and events like FileSelected() etc.
Your presenter will hook up to the Model and IView events and control which methods are called on each etc. The Form that you have a TabControl on is just an implemenation of the IView interface. You could have a different view just by injecting an implementation of IView into the Presenter, including a Mock IView for testing.
Values can be passed around the MVP pattern through the EventArgs you use.
/// <summary>
/// The event args for a selected file.
/// </summary>
public class FileSelectedEventArgs : EventArgs
{
    public string FileName { get; private set; }

    public FileSelectedEventArgs(string fileName)
    {
        this.FileName = fileName;
    }
}

When the user selects a file, the FileSelected event is raised in your View, with the FileName available in the FileSelectedEventArgs. The Presenter listens for this event, and calls a method on the Model - maybe ExtractFile(string fileName), passing in the fileName from the FileSelectedEventArgs from the View.
The Presenter then listens to the ExtractCompleted event to be fired from the Model (which also has whatever custom eventargs you want) and calls the appropriate method on your View, passing in the parameters from the Model. The method in the View can do whatever you want in terms of displaying the data in a TabControl or in another way.
This is just one way of doing it anyway.


text:
Q: MongoDB not allowed to save in Rockmongo I am using Rockmongo as the UI, and I am trying to save something every similar to this.
text text's text.
text this is where the text goes

haha

Now I am not sure if it is the .,' or even the ?
 etc.

A: I was unable to reproduce this.  Here is what I tried in the JavaScript shell:
> db.text.save({_id:1, text:"text text's text.
text this is where the text goes

haha
"})
> db.text.find()
{ "_id" : 1, "text" : "text text's text.
text this is where the text goes

haha
" }

The line was saved successfully.  Are you surrounding the text string with double quotes " ?  As bfavaretto mentioned, the issue could be from the single apostrophe in your string.  The following will not work:
> db.text.drop()
true
> db.text.save({_id:1, text:'This is text with an extra ' apostrophe.'})
...
...
> db.text.find()
>

As you can see, the above document was not saved because the string was not properly formatted.  In fact, the JS shell never even executed the command.
Mongo should be able to save a string containing all of these characters.  If you are still having issues, perhaps this could be an issue with RockMongo?  (Unfortunately, I am not familiar with this program.)  A simple way to troubleshoot is to test saving each unique character one at a time, and see which character causes the issue.  Hope this helps!


text:
Q: Search Replace Sed using wild card Hello I'm sort of new to scripting and have the following problem
I need to replace 20069.1216.0
HintPath..\packages\String.20069.1216.0\lib\net\Thoo.Tkc.dll/HintPath
This works fine at replacing 20069.1216.0 with whatever is provided in $2
`xargs sed -i 's/String.20.........0/String.'"${2}"'/g'`

I need a way for sed to search for **"String.*\lib\net\"**where anything in between **String.** and **\lib...** is wildcard
This what i have tried
sed -i 's/String.*\/String.'"${2}"'/g'
sed -i 's/String.*\\/String.'"${2}"'/g'
sed -i 's/String.\(.*\)\\/String.'"${2}"'/g'

A: I'll assume that you call sed inside a function.
So try this code:
#!/bin/bash

replace() {
  echo 'HintPath..\packages\String.20069.1216.0\lib\net\Thoo.Tkc.dll/HintPath' |\
  sed "s/String\.[0-9.]*/String\.${2}/"
}

replace dont_care filename

If your path may contain --SNAPSHOT this solution should work for you:
#!/bin/bash

replace() {
  echo 'HintPath..\packages\String.20069.1216.0--SNAPSHOT\lib\net\Thoo.Tkc.dll/HintPath' |\
  sed "s/String[0-9.]*\(--SNAPSHOT\)\{0,1\}/String\.${2}/"
}

replace dont_care filename


text:
Q: Regex returns undefined with underscore group I have some strings like this:
123a-124b.csv
123a_124b.csv
123-124b.csv
123_124.csv

I need to match the numbers only with a regex, so I've tried these 2 regexes with javascript:
/^(\d+)\w*(?:.(\d+)\w*)?\.CSV$/i
/^(\d+)\w*(?:[-|_](\d+)\w*)?\.CSV$/i

Running exec on this gives the correct result for - but a _ matches, but returns undefined for the second named group. In fact, the first regex works with any char except _. For example 123a=123b.csv works correctly.
Any idea what's wrong.
Some more example outputs:
var TEST = /^(\d+)\w*(?:.(\d+)\w*)?\.CSV$/i;
> undefined
TEST.exec('123a_123b.csv')
> ["123a_123b.csv", "123", undefined]
TEST.exec('123a+123b.csv')
> ["123a+123b.csv", "123", "123"]
TEST.exec('123a=123b.csv')
> ["123a=123b.csv", "123", "123"]
TEST.exec('123a?123b.csv')
> ["123a?123b.csv", "123", "123"]

A: ^(\d+)[a-zA-Z0-9]*(?:.(\d+)\w*)?\.CSV$

Try this.See demo.
http://regex101.com/r/yR3mM3/44
The problem with your regex is ^(\d+)\w*(?:_(\d+)\w*)?\.CSV$
                               ^^^

This \w* will consume everything and the second group will never get a chance to come into play.Change \w to [a-zA-Z0-9] to exclude _ from matching as it acts as delimter here to your second group


text:
Q: Prevent back to the previous page If I click logout link, it will be directed me to the 'logout' function that will destroy the login session.
After that I logged in again that directed me to the 'products' function. But if I click back button it will directed me to the 'logout' function, and destroyed login session without clicking the logout link.
logout function->products function->back to the logout by clicking the back button->login session destroyed.
        function logout(){

        $array_items = array('is_logged_in' => FALSE);

        $this->session->unset_userdata($array_items);

        $this->products();
        }

how can I prevent the page to back to the 'logout'  ? if it was possible, I would like to reload the current page rather than just prevent the page to go back.
Thank You so much for your help, and to share you knowledge.
Sorry for my bad explanation

A: You can use redirect('controller/products'); instead of $this->products(); at the end of your function after the user have clicked the logout function url, in other functions, you need to check if the user has already been logged in or not.
In your case, your url will be /logout, after redirecting, your url will be /products.
So, when user clicks back, you will return to the current page and not the logout page.

A: If you have an admin controller or something similar extending CI_CONTROLLER for your users types, I just throw this into the extended controller file:
function __construct() {
    parent::__construct();
    //check login, redirect if logged in or logging out
    $this->no_cache(); //runs if not logging out or logged in
}

protected function no_cache(){
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Cache-Control: post-check=0, pre-check=0',false);
    header('Pragma: no-cache');
}


text:
Q: Pig Python UDF and lxml I have a Python UDF that uses lxml. My Pig job that uses the UDF fails:
File "PigParse.py", line 10, in ParseToPig ImportError: No module named lxml

The Python script works fine as a stand alone program, its line 10 is:
from lxml import etree

Do I need to distribute lxml to the hadoop cluster somehow, and if so, how and which version should I use?
I have seen examples of distributing nltk using
    Hadoop -file
but nothing for Pig.
TIA!!!

A: I think my problem is because I'm using Jython:
`REGISTER 'PigParse.py' using jython as PP;

and you can't use lxml with Jython


text:
Q: Differentiate between selenium Exception and other exceptions My test cases are in  selenium with c# language. I need to differentiate the failures that occurred due to Selenium Exceptions and other coding Exceptions in order to provide appropriate error message.
I an not sure if what i have tried below is correct. does Selenium.SeleniumException group all possible selenium Exceptions togeather. here is the catch block that I have tried:
    catch(Exception e)
    {
            if(e is Selenium.SeleniumException)
        {
            Console.Writeline("Defect in Application - Failed due to Selenium Exception");
        }
        else
        {
             Console.Writeline("Coding Error - Exception raised in code");
        }
    }

A: instead of trying to find out the exception type using if-else statements, use multiple catch statements. This enables you to act differently on different exception types.
Also, unless you know how to handle an exception, just let it propagate.
try
{
...
}
catch(WebDriverException exception)
{
    Console.Writeline("Defect in Application - Failed due to Selenium Exception");
}
catch(Exception ex)
{
    Console.Writeline("Coding Error - Exception raised in code");
}


text:
Q: change color of parent in the expandableList I want to change the background color of the parent in an ExpandableList, in my mainActivity.
the background color will be changed in some particular parent.
How can i do this ?

A: Not sure what you meant but if you want to set the parent background color just add this to it's xml:
android:background = "@color/green"
If you meant only for the ExpendableList items, add the above line to their layout.
You can see an example here: http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/


text:
Q: How to store arrays in MySQL? I have two tables in MySQL. Table Person has the following columns:

id
name
fruits

The fruits column may hold null or an array of strings like ('apple', 'orange', 'banana'), or ('strawberry'), etc. The second table is Table Fruit and has the following three columns:

fruit_name
color
price

apple
red
2

orange
orange
3

-----------
--------
------

So how should I design the fruits column in the first table so that it can hold array of strings that take values from the fruit_name column in the second table? Since there is no array data type in MySQL, how should I do it?

A: The reason that there are no arrays in SQL, is because most people don't really need it. Relational databases (SQL is exactly that) work using relations, and most of the time, it is best if you assign one row of a table to each "bit of information". For example, where you may think "I'd like a list of stuff here", instead make a new table, linking the row in one table with the row in another table.[1] That way, you can represent M:N relationships. Another advantage is that those links will not clutter the row containing the linked item. And the database can index those rows. Arrays typically aren't indexed.
If you don't need relational databases, you can use e.g. a key-value store.
Read about database normalization, please. The golden rule is "[Every] non-key [attribute] must provide a fact about the key, the whole key, and nothing but the key.". An array does too much. It has multiple facts and it stores the order (which is not related to the relation itself). And the performance is poor (see above).
Imagine that you have a person table and you have a table with phone calls by people. Now you could make each person row have a list of his phone calls. But every person has many other relationships to many other things. Does that mean my person table should contain an array for every single thing he is connected to? No, that is not an attribute of the person itself.
[1]: It is okay if the linking table only has two columns (the primary keys from each table)! If the relationship itself has additional attributes though, they should be represented in this table as columns.

A: MySQL 5.7 now provides a JSON data type. This new datatype provides a convenient new way to store complex data: lists, dictionaries, etc.
That said, arrays don't map well databases which is why object-relational maps can be quite complex. Historically people have stored lists/arrays in MySQL by creating a table that describes them and adding each value as its own record. The table may have only 2 or 3 columns, or it may contain many more. How you store this type of data really depends on characteristics of the data.
For example, does the list contain a static or dynamic number of entries? Will the list stay small, or is it expected to grow to millions of records? Will there be lots of reads on this table? Lots of writes? Lots of updates? These are all factors that need to be considered when deciding how to store collections of data.
Also, Key/Value data stores, Document stores such as Cassandra, MongoDB, Redis etc provide a good solution as well. Just be aware of where the data is actually being stored (if its being stored on disk or in memory). Not all of your data needs to be in the same database. Some data does not map well to a relational database and you may have reasons for storing it elsewhere, or you may want to use an in-memory key:value database as a hot-cache for data stored on disk somewhere or as an ephemeral storage for things like sessions.

A: A sidenote to consider, you can store arrays in Postgres.

A: In MySQL, use the JSON type.
Contra the answers above, the SQL standard has included array types for almost twenty years; they are useful, even if MySQL has not implemented them.
In your example, however, you'll likely want to create three tables: person and fruit, then person_fruit to join them.
DROP TABLE IF EXISTS person_fruit;
DROP TABLE IF EXISTS person;
DROP TABLE IF EXISTS fruit;

CREATE TABLE person (
  person_id   INT           NOT NULL AUTO_INCREMENT,
  person_name VARCHAR(1000) NOT NULL,
  PRIMARY KEY (person_id)
);

CREATE TABLE fruit (
  fruit_id    INT           NOT NULL AUTO_INCREMENT,
  fruit_name  VARCHAR(1000) NOT NULL,
  fruit_color VARCHAR(1000) NOT NULL,
  fruit_price INT           NOT NULL,
  PRIMARY KEY (fruit_id)
);

CREATE TABLE person_fruit (
  pf_id     INT NOT NULL AUTO_INCREMENT,
  pf_person INT NOT NULL,
  pf_fruit  INT NOT NULL,
  PRIMARY KEY (pf_id),
  FOREIGN KEY (pf_person) REFERENCES person (person_id),
  FOREIGN KEY (pf_fruit) REFERENCES fruit (fruit_id)
);

INSERT INTO person (person_name)
VALUES
  ('John'),
  ('Mary'),
  ('John'); -- again

INSERT INTO fruit (fruit_name, fruit_color, fruit_price)
VALUES
  ('apple', 'red', 1),
  ('orange', 'orange', 2),
  ('pineapple', 'yellow', 3);

INSERT INTO person_fruit (pf_person, pf_fruit)
VALUES
  (1, 1),
  (1, 2),
  (2, 2),
  (2, 3),
  (3, 1),
  (3, 2),
  (3, 3);

If you wish to associate the person with an array of fruits, you can do so with a view:
DROP VIEW IF EXISTS person_fruit_summary;
CREATE VIEW person_fruit_summary AS
  SELECT
    person_id                                                                                AS pfs_person_id,
    max(person_name)                                                                                AS pfs_person_name,
    cast(concat('[', group_concat(json_quote(fruit_name) ORDER BY fruit_name SEPARATOR ','), ']') as json) AS pfs_fruit_name_array
  FROM
    person
    INNER JOIN person_fruit
      ON person.person_id = person_fruit.pf_person
    INNER JOIN fruit
      ON person_fruit.pf_fruit = fruit.fruit_id
  GROUP BY
    person_id;

The view shows the following data:
+---------------+-----------------+----------------------------------+
| pfs_person_id | pfs_person_name | pfs_fruit_name_array             |
+---------------+-----------------+----------------------------------+
|             1 | John            | ["apple", "orange"]              |
|             2 | Mary            | ["orange", "pineapple"]          |
|             3 | John            | ["apple", "orange", "pineapple"] |
+---------------+-----------------+----------------------------------+

In 5.7.22, you'll want to use JSON_ARRAYAGG, rather than hack the array together from a string.

A: The proper way to do this is to use multiple tables and JOIN them in your queries.
For example:
CREATE TABLE person (
`id` INT NOT NULL PRIMARY KEY,
`name` VARCHAR(50)
);

CREATE TABLE fruits (
`fruit_name` VARCHAR(20) NOT NULL PRIMARY KEY,
`color` VARCHAR(20),
`price` INT
);

CREATE TABLE person_fruit (
`person_id` INT NOT NULL,
`fruit_name` VARCHAR(20) NOT NULL,
PRIMARY KEY(`person_id`, `fruit_name`)
);

The person_fruit table contains one row for each fruit a person is associated with and effectively links the person and fruits tables together, I.E.
1 | "banana"
1 | "apple"
1 | "orange"
2 | "straberry"
2 | "banana"
2 | "apple"

When you want to retrieve a person and all of their fruit you can do something like this:
SELECT p.*, f.*
FROM person p
INNER JOIN person_fruit pf
ON pf.person_id = p.id
INNER JOIN fruits f
ON f.fruit_name = pf.fruit_name

A: Use database field type BLOB to store arrays.
Ref: http://us.php.net/manual/en/function.serialize.php

Return Values
Returns a string containing a byte-stream representation of value that
can be stored anywhere.
Note that this is a binary string which may include null bytes, and
needs to be stored and handled as such. For example, serialize()
output should generally be stored in a BLOB field in a database,
rather than a CHAR or TEXT field.

A: you can store your array using group_Concat like that
 INSERT into Table1 (fruits)  (SELECT GROUP_CONCAT(fruit_name) from table2)
 WHERE ..... //your clause here

HERE an example in fiddle


text:
Q: Combine a series of data frames and create new columns for data in each I have an Excel file with a sheet for each week in my data set. Each sheet has the same number of rows, and each row is identical across the sheets (with the exception of the time period… sheet 1 represents week 1, sheet 2 week 2, etc.). I'm trying to import all the Excel sheets as one data frame in R.
For example, my data is essentially structured like this (with several more columns and sheets):
Week 1 sheet
ID    Gender    DOB    Absences    Lates    Absences_excused
1     M         1997   5           14       5
2     F         1998   4           3        2

Week 2 sheet
ID    Gender    DOB    Absences    Lates    Absences_excused
1     M         1997   2           10       3
2     F         1998   8           2        9

I'm trying to build a script that will take x numbers of sheets and combine them into one data frame like this:
Combined (ideal)
ID    Gender    DOB    Absences.1    Lates.1    Absences.2    Lates.2
1     M         1997   5             14         2             10
2     F         1998   4             3          8             2

I'm using gdata to import the Excel files.
I've tried creating a loop (normally bad for R, I know...) that will go through all the sheets in the Excel file and add each to a list as a data frame:
library(gdata)

number_sheets <- 3
all.sheets <- vector(mode="list", length=number_sheets)

for (i in 1:number_sheets) {
  all.sheets[[i]] <- read.xls("/path/to/file.xlsx", sheet=i)
}

This gives me a nice list, all.sheets, that I can access, but I'm unsure about the best way to create a new data frame from specific columns in the list of data frames.
I've tried the code below, which creates a brand new data frame by looping through the list of data frames. On the first data frame, it saves the columns that are consistent in all the sheets, and then adds the week-specific columns.
Cleaned <- data.frame()
number_sheets <- 3

for (i in 1:number_sheets) {
  if (i == 1) {
    Cleaned <- all.sheets[[i]][,c("ID", "Gender", "DOB")]
  }
  Cleaned$Absences.i <- all.sheets[[i]][,c("Absences")]  # wrong... obviously doesn't work... but essentially what I want
  # Other week-specific columns go here... somehow...
}

This code doesn't work though, since Cleaned$Absences.i is obviously not how you create dynamic columns in a data frame.
What's the best way to combine a set of data frames and create new columns for each of the variables I'm trying to track?
Extra hurdle: I'm also trying to combine two columns, "Absences" and "Absences_excused" into a single "Absences" column in the final data frame, so I'm trying to make my solution let me perform transformations to the new columns, like so (again, this isn't right):
Cleaned$Absences.i <- all.sheets[[i]][,c("Absences")] + all.sheets[[i]][,c("Absences_excused")]

A: The merge strategy is:
> Week_1_sheet <- read.table(text="ID    Gender    DOB    Absences    Lates
+ 1     M         1997   5           14
+ 2     F         1998   4           3", header=TRUE)
> Week_2_sheet <- read.table(text="ID    Gender    DOB    Absences    Lates
+ 1     M         1997   2           10
+ 2     F         1998   8           2", header=TRUE)
> merge(Week_1_sheet, Week_2_sheet, 1:3)
  ID Gender  DOB Absences.x Lates.x Absences.y Lates.y
1  1      M 1997          5      14          2      10
2  2      F 1998          4       3          8       2

You can rename the columns with names(sheet) <- sub("x", 1, sheet), and again for y -> 2. I think the cbind strategy is OK but merge is probably better to learn.
@TylerRinker raises the question about acceptable arguments to the 'by' parameter. The relevant sentece in the help page is:  "Columns can be specified by name, number or by a logical vector: the name "row.names" or the number 0 specifies the row names."

A: @ DWin I think the poster's problem is a little more complex than the example leads us to believe.  I think the poster wants a multi merge as indicated by "week 1, sheet 2 week 2, etc.".  My approach is a bit different.  The extra hurdle can be taken care of before the merge using lapply with transform.  Here's my solution for the merge using 3 data frames instead of 2.
#First read in three data frames
Week_1_sheet <- read.table(text="ID Gender  DOB Absences Unexcused_Absences Lates
1  1      M 1997        5                  1    14
2  2      F 1998        4                  2     3", header=TRUE)

Week_2_sheet <- read.table(text="ID Gender  DOB Absences Unexcused_Absences Lates
1  1      M 1997        2                  1    10
2  2      F 1998        8                  2     2
3  3      M 1998        8                  2     2", header=TRUE)

Week_3_sheet <- read.table(text="ID Gender  DOB Absences Unexcused_Absences Lates
1  1      M 1997        2                  1    10
2  2      F 1998        8                  2     2", header=TRUE)

#Put them into a list structure
WEEKlist <- list(Week_1_sheet , Week_2_sheet , Week_3_sheet)

#Transform to add the absences and unexcused absences and drop unexcused
lapply(seq_along(WEEKlist), function(x) {
    WEEKlist[[x]] <<- transform(WEEKlist[[x]], Absences=sum(Absences,
        Unexcused_Absences))[, -5]
    }
)

#Rename each data frame in the list with `<<-` that acts on environments
lapply(seq_along(WEEKlist), function(x) {
    y <- names(WEEKlist[[x]])
    names(WEEKlist[[x]]) <<- c(y[1:3], paste(y[4:length(y)], ".", x, sep=""))
    }
)

#loop through and merge by the common columns
DF <- WEEKlist[[1]][, 1:3]
for (.df in WEEKlist) {
     DF <-merge(DF, .df, by=c('ID', 'Gender', 'DOB'), all=TRUE, suffixes=c("", ""))
}

DF

A 2nd approach (after renaming the data frame columns) is to use Reduce:
Taken from (LINK)
merge.all <- function(frames, by) {
    return (Reduce(function(x, y) {merge(x, y, by = by, all = TRUE)}, frames))
}

merge.all(frames=WEEKlist, by=c('ID', 'Gender', 'DOB'))

I'm not sure which one is faster though.
EDIT: On a windows 7 machine running 1000 iterations the Reduce was faster:
    test replications elapsed relative user.self sys.self
1   LOOP         1000   10.12  1.62701      7.89        0
2 REDUCE         1000    6.22  1.00000      5.34        0


text:
Q: Customize Session Registry spring security I'm using spring security 3.1.4 and I'm trying to create a costume session registry that uses data base for saving open sessions.
I used this SessionRegistryImpl implementation as reference :https://github.com/spring-projects/spring-security/blob/master/core/src/main/java/org/springframework/security/core/session/SessionRegistryImpl.java
This is my implementation:
@Component
public class ClusteredSessionRegistryImpl implements SessionRegistry, ApplicationListener<SessionDestroyedEvent> {

    @Autowired
    private PrincipalRepository principalRepository;

    @Autowired
    private SessionIdRepository sessionIdRepository;

    public List<Object> getAllPrincipals() {

    return new ArrayList<Object>(
                     this.principalRepository.findAllPrincipals());
    }

    public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) {

    final Set<String> sessionsUsedByPrincipal = this.principalRepository.findByPrincipal(
                                                 principal).getSessionsUsedByPrincipal();

    if (sessionsUsedByPrincipal == null) {
        return Collections.emptyList();
    }

    List<SessionInformation> list = new ArrayList<SessionInformation>(
                                      sessionsUsedByPrincipal.size());

    for (String sessionId : sessionsUsedByPrincipal) {
        SessionInformation sessionInformation = getSessionInformation(sessionId);

        if (sessionInformation == null) {
        continue;
        }

        if (includeExpiredSessions || !sessionInformation.isExpired()) {
        list.add(sessionInformation);
        }
    }

    return list;
    }

    public SessionInformation getSessionInformation(String sessionId) {

    Assert.hasText(
               sessionId,
               "SessionId required as per interface contract");
    SessionId sessionIdDoc = this.sessionIdRepository.findBySessionId(sessionId);

    if (sessionIdDoc == null)
        return null;

    return sessionIdDoc.getSessionInformation();
    }

    public void onApplicationEvent(SessionDestroyedEvent event) {

    String sessionId = event.getId();
    removeSessionInformation(sessionId);
    }

    public void refreshLastRequest(String sessionId) {

    Assert.hasText(
               sessionId,
               "SessionId required as per interface contract");

    SessionInformation info = getSessionInformation(sessionId);

    if (info != null) {
        info.refreshLastRequest();
    }
    }

    public void registerNewSession(String sessionId, Object principal) {

    Assert.hasText(
               sessionId,
               "SessionId required as per interface contract");
    Assert.notNull(
               principal,
               "Principal required as per interface contract");

    if (getSessionInformation(sessionId) != null) {
        removeSessionInformation(sessionId);
    }
    this.sessionIdRepository.save(new SessionId(
                            sessionId, new SessionInformation(
                                              principal, sessionId, new Date())));

    Principal principalDoc = this.putIfAbsent(principal);

    Set<String> sessionsUsedByPrincipal = principalDoc.getSessionsUsedByPrincipal();

    if (sessionsUsedByPrincipal == null) {
        sessionsUsedByPrincipal = new CopyOnWriteArraySet<String>();
    }

    sessionsUsedByPrincipal.add(sessionId);

    principalDoc.setSessionsUsedByPrincipal(sessionsUsedByPrincipal);

    this.principalRepository.save(principalDoc);

    }

    public void removeSessionInformation(String sessionId) {

    Assert.hasText(
               sessionId,
               "SessionId required as per interface contract");

    SessionInformation info = getSessionInformation(sessionId);

    if (info == null) {
        return;
    }

    SessionId sessionIdDoc = this.sessionIdRepository.findBySessionId(sessionId);
    if (sessionIdDoc == null) {
        return;
    }

    this.sessionIdRepository.delete(sessionIdDoc);

    Set<String> sessionsUsedByPrincipal = this.principalRepository.findByPrincipal(
                                               info.getPrincipal()).getSessionsUsedByPrincipal();

    if (sessionsUsedByPrincipal == null) {
        return;
    }

    sessionsUsedByPrincipal.remove(sessionId);

    if (sessionsUsedByPrincipal.isEmpty()) {

        Principal principalDoc = this.principalRepository.findByPrincipal(info.getPrincipal());

        this.principalRepository.delete(principalDoc);
    }
    else {

        Principal principalDoc = this.principalRepository.findByPrincipal(info.getPrincipal());

        principalDoc.setSessionsUsedByPrincipal(sessionsUsedByPrincipal);

        this.principalRepository.save(principalDoc);
    }

    }

    private Principal putIfAbsent(Object principal) {

    Principal principalDoc = this.principalRepository.findByPrincipal(principal);
    if (principalDoc == null) {
        return this.principalRepository.save(new Principal(
                                   principal, null));
    }
    else {
        return principalDoc;
    }

    }
}

my security xml:
    <security:http use-expressions="true" auto-config="false"
        entry-point-ref="loginUrlAuthenticationEntryPoint">

        <security:intercept-url pattern="/player/login"
            access="permitAll" />

        <security:custom-filter position="FORM_LOGIN_FILTER"
            ref="twoFactorAuthenticationFilter" />

        <security:intercept-url pattern="/**"
            access="isAuthenticated()" />

        <security:logout logout-url="/player/logout"
            success-handler-ref="playerLogoutSuccessHandler" />

        <security:session-management>
            <security:concurrency-control
                max-sessions="1" session-registry-ref="clusteredSessionRegistryImpl"
                error-if-maximum-exceeded="true" />
        </security:session-management>

    </security:http>

    <bean id="loginUrlAuthenticationEntryPoint"
        class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
        <property name="loginFormUrl" value="/demo/player/login" />
    </bean>

    <bean id="twoFactorAuthenticationFilter" class="com.xxx.filter.TwoFactorAuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager" />
        <property name="authenticationFailureHandler" ref="failureHandler" />
        <property name="authenticationSuccessHandler" ref="playerAuthenticationSuccessHandler" />
        <property name="postOnly" value="true" />
        <property name="extraParameter" value="domain" />
    </bean>

    <bean id="failureHandler"
        class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
        <property name="defaultFailureUrl" value="/login?login_error=true" />
    </bean>

    <bean id="bCryptPasswordEncoder"
        class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider
            ref="authenticationProvider">
        </security:authentication-provider>
    </security:authentication-manager>

</beans>

The problam is it never enters the public void registerNewSession(String sessionId, Object principal)
so nothing is saved in the db.
EDIT:
I added a call to registerNewSession() from my authenticationSuccessHandler, is this a legitimate solution?
My new problem is that the max-sessions="1" doesn't work and I can open more then 1 session. (I override the equals and hash code of my principal)


text:
Q: Fluid div with 100% width I have a html structure like the one below with a sidebar and a main container. What I want is to have a fixed width of the sidebar (and later on change it with media queries) and a main container that's fluid. This means that if I'm decreasing the browsers width the main container should decrease in width but not the sidebar.
I've tried 100% width of #container, 15% width of the sidebar and 85% width of the main container but this (of course) decreases the width of the sidebar as well. Only using 100% width of the main container and a fixed width of the sidebar container doesn't seem to work.
What is the best way of solving this?
html:

        //content

        //content

 ________________________
|     |                  |
|     |                  |
|     |                  |
|     |                  |
|     |                  |
|     |                  |
|     |                  |
|     |                  |
--------------------------

A: Use following css
.container{display:block; padding:0 0 0 200px;}
.sidebar{display:block; float:left; width:200px; margin:0 0 0 -200px;}
.main{display:block; width:100%}

A: Fiddle : http://jsfiddle.net/3ApFZ/
Css :
#sidebar{
    width:150px;
    position: absolute;
    background:blue;
    height:100%;

}
#main{
    width:100%;
    padding-left: 150px;
    background:red;
    height:100%;
}

A: I helped someone a few days ago with something similar. What if you used the following DEMO
Basically setting the left side a fix width and the right side a resizable width
.left {width:100%; height:20px; background-color:red; float:left; margin-left:-320px; display:inline}
.right {width:320px; height:20px; background-color:blue; float:right; display:inline}


text:
Q: Div positioning vertically and horizontally Is there a way to position div's like this:
|----------||----------||----------||----------|
|  div1    ||   div5   ||          ||   div10  |
|----------||----------||   div7   ||----------|
|  div2    ||          ||          ||   div11  |
|----------||   div6   ||----------||----------|
|  div3    ||          ||   div8   ||   div12  |
|----------||          ||----------||----------|
|  div4    ||          ||   div9   ||   div13  |
|----------||----------||----------||----------|

So what i'd like to do is having a horizontally expanding layout that doesn't scroll vertically, it just fills it with the space it has vertically and then moves horizontally.
 So the first element goes on the right top, second underneath it, third as well until there is no space left and then it goes back on top (like div5).

A: You should have a look at the blueprint CSS framework. I have used it to create a website which had a similar layout to your post, its very easy to use and fast too.
http://www.blueprintcss.org/

A: This is the vertical equivalent to how floated elements flow horizontally in a container (as if float:top were supported).
As @MarcB noted, in the future this will be easily doable with CSS3 columns. The standard hasn't been fully defined yet, but it may look something like the following:
.container {
    height: 200px;
    column-width: 100px;
    column-gap: 10px;
    column-fill: auto;
}

In the meantime, a jQuery plug-in may be the best bet. For example, jQuery Masonry has one-column formatting that might do the trick. There may be simpler jQuery plug-ins out there that would also be adequate.
Related search terms: jQuery, CSS columns, multi-column layout, tiled layout, mosaic layout


text:
Q: Find out longest palindromic substring I want to run this code and I am getting aba but not bab. How can I get the solution from this code? Suggestions with explanations so that I can understand properly.
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.

var longestPalindrome = function(s) {
    let splitString = s.split("");
    let reverse = splitString.reverse()
    console.log(reverse)
    let check_value = s.split("")
    console.log(check_value)
    let store = []
    check_value.map((x,id) => {
        if(x == reverse[id]){
            store.push(x)
        }
    })
    console.log(store)
};

A: Your function is not doing the job right. It assumes that the center of the palindrome is always in the center of the input string. So that explains why "bab" is not found.
But even worse, it will even give false positives.
For instance:
Input: "dobad"
Output: ["d", "b", "d"]
So you'll need to revisit the code challenge. The approach you had in mind is not the right one.
If you cannot find how to do it, have a look at Longest palindromic substring on Wikipedia. Also on this site there are several Q&A on the subject.

A: So, you have these letters in the arrays:
check_value => 0: b, 1: a, 2: b, 3: a, 4: d
reverse     => 0: d, 1: a, 2: b, 3: a, 4: b
And in your algorithm, you are doing
First step:

*

*x = b

*id = 0

*reverse[id] = d
x != d then the value is not saved

Second step:

*

*x = a

*id = 1

*reverse[id] = a
x == a then the value is saved

*store = [a]

And so on, so that is the reason why the algorithm is not working
A tip, iterate the string and find the next index of the current character, so, if the character is b find the indexes of any other b in the same array and validate if the substring generated between the current character index and the found indexes is a palindrome


text:
Q: ControleSend send weird output Autohotkey I wrote a script that sends some keystroke to my command line. However, the values are coming out totally messed up. What could be the reasons?
BlockInput, on
WinGetActiveTitle, Title
DetectHiddenWindows, on
ControlClick, x660 y391, Notepad
ControlSend, , {Backspace}{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}, Notepad
Sleep 30
ControlSend, ,  2, Notepad
Sleep 30
ControlSend, , echo stat_id: 78 : SETTING PRICE TO 2 toactivate: %Title% >>  logs.txt{Enter} , ahk_exe cmd.exe
ControlClick, x668 y640, Notepad
ControlSend, , echo  ACTION NEXT (after SETTING PRICE) >> logs.txt{Enter} , ahk_exe cmd.exe
WinActivate, %Title%
Send {Ctrl down}+{Ctrl up}
Send {Ctrl down}+{Ctrl up}
Send {Ctrl down}+{Ctrl up}
Send {Ctrl down}+{Ctrl up}
Send {Ctrl down}+{Ctrl up}
BlockInput, off
ExitApp
Return

This is one example of output:
at-idec; ho78   B: EFSOETRTEI SNGCR PERENIC ESH TOOOT  2 DOTNOEAC >T>I valotges;. tixqt

echo  ACTION NEXT (after SETTING PREICCEHO)  >A>CT lioogn s.ntexxtt

A: Quite a few things to mention
1) You shouldn't be using controlsend to send text to a cmd prompt. Instead, you should be using Run, % Compsec. ComSpec is just a shortcut to cmd.exe. So when you do Run, % Compsec you're really just passing whatever comes next to the cmd prompt. Example for running ipconfig: Run, % ComSpec " /k ipconfig"
To easily remember which switch to use, remember that /k will "keep the command prompt open when it's done" and /c will "close it after the commands have run".
Also, make sure you understand the difference between Expression and non-expression.
The following lines of code look different, but each line does the exact same thing:
Run, % ComSpec " /k ipconfig"
Run, %ComSpec% /k ipconfig

2) Instead of writing {Backspace}{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}, instead, include how many times you want the key repated after the key name but before the closing curly brace. {Backspace 6}. This works for any key.
3) BlockInput can be a dangerous command and, usually, I advise others to avoid it when possible. By using Run ComSpec instead of control send, you remove any need to use BlockInput.
4) The problem you were initially having most likely had to do with the text being sent too fast. Lower the send speed with SetKeyDelay.

Try replacing this:
ControlSend, , echo stat_id: 78 : SETTING PRICE TO 2 toactivate: %Title% >>  logs.txt{Enter} , ahk_exe cmd.exe

With this:
Run, % ComSpec " /k echo stat_id: 78 : SETTING PRICE TO 2 toactivate: " Title " >>  logs.txt"

A: If you do want to send to the console there are alternatives:

*

*ConsoleSend() https://autohotkey.com/board/topic/25446-consolesend/

*Windows 10: You could try pasting text and then send an Enter. Older versions of Windows - Requires additional software: I find Clink to be reliable as you can just Send ^v after installing it https://mridgers.github.io/clink/


text:
Q: SQLite not working on real Device - Xamarin.iOS Xamarin.ios not inserting data in table on real device but working properly on simulator. I've set sqlite DB file build action property to 'Bundle Resource' but still not working. Getting data from a DB is working properly on Both simulator and on real device.
if (_person == null)
{
var a = conn.Execute("insert into Person(Id,Name,Gender) values(?,?,?,?,?)", _person.Id, _person.Name, _person.Gender);
}
conn.Commit();


text:
Q: Turning off encryption with OpenVPN I want to run a local OpenVPN for localhost access (loopback), so local encryption is a complete waste of time. So how do I turn off the whole thing? I'm using OpenVPN 2.4.7.

A: I believe the following options in your config should do the trick:
cipher none
auth none

Note: I haven't tried it though.


text:
Q: Existe alguma maneira de atribuir valores a um vetor mais rapidamente? Por exemplo, tenho a declaração do seguinte vetor:
float vet[3] = {1, 1, 1};

Teria como mudar todos valores do mesmo de uma só vez, sem ter que mudar um por um elemento ou criar um novo vetor e atribuir a ele:
vet[0] = -1;
vet[1] = 0;
vet[2] = 1;

Algo mais ou menos assim:
vet = {-1, 0, 1};

A: De forma direta não tem não. Poderia criar uma função onde passa os parâmetros e ela atribui cada elemento. Mas isso é o oposto de ser mais rápido, no máximo fica mais curto.
Isso de forma geral vai contra a filosofia básica do C, embora nada impede de ser usado se for o mais adequado pontualmente.


text:
Q: How to normalize a recursive relationship? (Conceptual to logical) conceptual ERD of a recursive relationship

A: This relationship is employee mentor employees and employees mentored by employee.
since this is an Optional both side and one to many relationship, you just need to create a foreign key mentor(Fk) inside the employee table and remove the recursive line form the table.


text:
Q: How to set FontFamily globally for all controls in the project with text property in Xamarin.Form app? I'm creating a Xamarin.Form app for Android and iOS, and some users replace system default font with their own fonts, and FontSize property in Xaml doesn't work with these fonts, and these fonts are not so readable in my App. 1. So can I force the font used in my App to be system default font even the user changed font in their system config page?
2. If I can't do the above, can I set the FontFamily of all controls in my App with a text property to the font I included in my Android and iOS assets folder globally once and for all?
I've searched for some global font solution, but found no Xamarin.Form solution, and some solution seems to have been outdated.
For now, I set the FontFamily for controls one by one like this:
<Button FontFamily="{OnPlatform Android=xiaozuan.ttf#xiaozuan}"/>

There are so many controls that I can't really do this one by one...
Any clue or help would be appreicated!

A:

*

*So can I force the font used in my App to be system default font even the user changed font in their system config page?

If you want to change default fontfamily, I think you can override  default font using custom font.
https://www.infragistics.com/help/xamarin/overriding-default-font

If I can't do the above, can I set the FontFamily of all controls in my App with a text property to the font I included in my Android and iOS assets folder globally once and for all

You can use Global Styles in Xamarin.Forms to change all element in your project, here is changing the font of all label.
 <Application.Resources>
    <ResourceDictionary>
        <Style TargetType="Label">
            <Setter Property="FontFamily" Value="sans-serif" />
            <Setter Property="FontSize" Value="20" />
        </Style>
    </ResourceDictionary>

</Application.Resources>


text:
Q: Difference between passing string "0x30" and hexadecimal number 0x30 to hex() function print hex("0x30"); gives the correct hex to decimal conversion.
What does
print hex(0x30); mean?
The value it's giving is 72.

A: To expand on marcog's answer: From perldoc -f hex

hex EXPR: Interprets EXPR as a hex string and returns the corresponding value.

So hex really is for conversion between string and hex value. By typing in 0x30 you have already created a hex value.
perl -E '
  say 0x30;
  say hex("0x30");
  say 0x48;
  say hex(0x30);
  say hex(hex("0x30"));'

gives
48
48
72
72
72

A: hex() parses a hex string and returns the appropriate integer.
So when you do hex(0x30) your numeric literal (0x30) gets interpreted as such (0x30 is 48 in hex format), then hex() treats that scalar value as a string ("48") and converts it into a number, assuming the string is in hex format. 0x48 == 72, which is where the 72 is coming from.

A: hex() takes a string argument, so due to Perl's weak typing it will read the argument as a string whatever you pass it.
The former is passing 0x30 as a string, which hex() then directly converts to decimal.
The latter is a hex number 0x30, which is 48 in decimal, is passed to hex() which is then interpreted as hex again and converted to decimal number 72. Think of it as doing hex(hex("0x30")).
You should stick with hex("0x30").
$ perl -e 'print 0x30';
48
$ perl -e 'print hex(0x30)';
72
$ perl -e 'print hex(30)';
48
$ perl -e 'print hex("0x30")';
48
$ perl -e 'print hex(hex(30))';
72


text:
Q: Fail to Increase Hive Mapper Tasks? I have a managed Hive table, which contains only one 150MB file. I then do "select count(*) from tbl" to it, and it uses 2 mappers. I want to set it to a bigger number.
First I tried 'set mapred.max.split.size=8388608;', so hopefully it will use 19 mappers. But it only uses 3. Somehow it still split the input by 64MB. I also used 'set dfs.block.size=8388608;', not working either.
Then I tried a vanilla map-reduce job to do the same thing. It initially uses 3 mappers, and when I set mapred.max.split.size, it uses 19. So the problem lies in Hive, I suppose.
I read some of the Hive source code, like CombineHiveInputFormat, ExecDriver, etc. can't find a clue.
What else settings can I use?

A: I combined @javadba 's answer with that I received from Hive mailing list, here's the solution:
set hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat;
set mapred.map.tasks = 20;
select count(*) from dw_stage.st_dw_marketing_touch_pi_metrics_basic;

From the mailing list:

It seems that HIVE is using the old Hadoop MapReduce API and so mapred.max.split.size won't work.

I would dig into source code later.

A: Try adding the following:
set hive.merge.mapfiles=false;
set hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat;


text:
Q: Why am I getting SQL Error [1064] [42000] syntax Error when running the below SQL Query i get the error message SQL Error [1064] [42000]: You have an error in your SQL syntax;
select  (IFNULL(SUM(ls.principal_amount),0) - IFNULL(SUM(ls.principal_writtenoff_derived),0)
+ IFNULL(SUM(ls.interest_amount),0) - IFNULL(SUM(ls.interest_writtenoff_derived),0)
- IFNULL(SUM(ls.interest_waived_derived),0)
+ IFNULL(SUM(ls.fee_charges_amount),0) - IFNULL(SUM(ls.fee_charges_writtenoff_derived),0)
- IFNULL(SUM(ls.fee_charges_waived_derived),0)
+ IFNULL(SUM(ls.penalty_charges_amount),0) - IFNULL(SUM(ls.penalty_charges_writtenoff_derived),0)
- IFNULL(SUM(ls.penalty_charges_waived_derived),0) ) AS "totalDue" from m_loan_repayment_schedule ls;

How can I resolve this error.


text:
Q: Installing a jupyter notebook extension I tried without success to install some extensions to jupyter notebook and can't figure out how to do it.
So basically I would like to have pep8 code checking in my notebook.
I checked this post:
Verifying PEP8 in iPython notebook code
However %install_ext is deprecated so instead I used
jupyter nbextension install https://raw.githubusercontent.com/SiggyF/notebooks/master/pep8_magic.py --user

So I get:
Copying: /tmp/tmpw74yl7m2/pep8_magic.py -> /home/louis/.local/share/jupyter/nbextensions/pep8_magic.py

To initialize this nbextension in the browser every time the notebook (or other app) loads:

          jupyter nbextension enable <the entry point> --user

From now on I could not get it working.
I tried:
~$ jupyter nbextension enable pep8_magic.py --user
Enabling notebook extension pep8_magic.py...
      - Validating: problems found:
        - require?  X pep8_magic.py

Without success.
Can someone explain a simple method to get it working and what I missed about jupyter extensions ?
Thank you !

A: I manually copied the file from the link and then added to /.ipython/extensions (or /nbextensions) and loaded in the notebook: %load_ext pep8_magic
Currently testing but looks fine to me


text:
Q: Concatenate / join / aggregate functions in python I created a function for generating heatmaps and the data I feed in can be groupby by different columns and aggregated with different functions (mean, sum, count).
Up to know I had a if-elif configuration, where the condition is to match the string of the wanted function (if fun=="mean" for example).
What I have:
df_ex = pd.DataFrame({"id_place":np.random.randint(20, size=133),
                    "id_center": np.random.randint(35, size=133),
                    "flow": np.random.randint(500, size=133),
                    "temperature": np.random.randint(35, size=133),
                    })
def prep_df(df,columns,variable, fun):

   columns= columns
   grouped_data = df.groupby(columns)[variable]

   if fun== 'mean':
       grouped_data = grouped_data.mean()
   elif fun == 'count':
       grouped_data = grouped_data.count()
   elif fun == 'sum':
       grouped_data = grouped_data.sum()

   return grouped_data

prep_df(df_ex,["id_place","id_center"], "flow", "mean")

To make the code cleaner I would like to have something like a dictionary to have only one line instead of all the lines required for the if-elif where then I could call the function of interest by feeding the function argument as a key.
Something like:
def prep_df(df,columns,variable, fun):
    dict_fun = {'mean': mean(),
                'count': count(),
                'sum': sum()
                }
    grouped_data = df.groupby(columns)[variable].dict_fun[fun]

Things is the values aren´t function themselves, and this approach fails.
So what I would like is call the function that are available of the groupby result to aggregate, setting the function I want passing a variable or calling a dictionary.
Is this has a specific name please let me know so I can rename the question more accurately.

A: Define your function like this:
def prep_df2(df, columns, variable, fun):
    assert fun in {'mean', 'count', 'sum'}
    return getattr(df.groupby(columns)[variable], fun)()

It takes advantage of calling a function of a module by using its name (a string).
The reason why your dict cannot work is that you didn't assign the right function, which should be bounded inside of the module and shouldn't be called.


text:
Q: Problems in creating rules in iptable Hello to all :) I need a little help with creating a rules. Im starting to learn iptables and firewalls but I have some questions. I need to allow HTTP communication only from PcA to PcB./
My code is:
iptables  -A INPUT -s PcA's_IP -d PcB's_IP --sport 80 -j ACCEPT

iptables     -A INPUT -d PcB's_IP --dport 80 -jDROP

My question here is whether I should use INPUT or FORWARD.
Then if I want to allow the rest traffic what should I write ? Maybe:
iptables -A INPUT -P ACCEPT

I am writing into the INPUT file of the PcB. I would be very pleased if someone help me. I've been reading a lot but there are only complex examples that are hard for me to understand.

A: You may want to look at a tool which builds the rules for you, then examine the rules to understand what they do.  There are a few standard rules which should be enabled to allowed.  I prefer Shorewall, which is well documented and I find easy to use for simple and complex setups.  It also has good example configuration to use as a starting point.

A: One crucial thing to understand with iptables is that it will go through the rules in sequential order, so your question cannot be answered without knowing what are all the other existing rules in your iptables configuration. This you can see for individual chains with "iptables -vL chain" (f.ex. iptables -vL INPUT), or for all chains with "iptables-save".

There is also one implicit rule in the three default chains (INPUT, OUTPUT, and FORWARD); that is the chain policy, which defines what happens to packets that do not match the criterias of any of the existing rules in that chain. From your example, it seems you've already realized this.

As of use of INPUT as opposed to FORWARD, use INPUT. FORWARD is meant only when forwarding the packets to other machines (i.e. when the machine with iptables is acting as firewall for other machines.

To sum these up, and to get back to your original question, the rules you wrote seem almost ok (I think there should be a "-p tcp" within the flags, to indicate that the rules concern tcp protocol. And of course, if there are other rules we don't know about, then they might well block the http traffic before it hits these rules. So, in iptables, the first terminal rule (i.e. rule with ACCEPT, REJECT or DROP) that has criteria matching to a packet will process that packet, and no other rules after it in the same chain have no effect in processing.


text:
Q: How to read out a value from a txt and add it to a drop down list in php? I write out each line from a txt file where the word 'free' can be found.
<?php
$filename = "data.txt";
$fp = fopen($filename, "r") or die("Couldn't open $filename");
while(!feof($fp))
{ $line = fgets($fp);
if (preg_match('/free/',$line)) // Print the line if it contains the word 'Ravi'
print "$line<br>";
}
fclose($fp);
?>

I would like to add every lines with the word 'free' into a drop down list, where i can pick one and forward this vaule to my email. Is it possible to do?

A: Yes, it is possible to do so.
Add some echo statements as follows:
$filename = "data.txt";
$fp = fopen($filename, "r") or die("Couldn't open $filename");
echo "<select>";      //  THIS ONE
while(!feof($fp)) {
  $line = fgets($fp);
  if (preg_match('/free/',$line))
    echo "<option>" . $line . "</option>";   // THIS ONE
}
echo "</select>";         // AND THIS ONE
fclose($fp);

A: just build a select-element by php and feed it with $line:
// after $fp = fopen...
$h = '<select name="aname" id="aname">';

// within your while-loop
$h .= '<option value="'.$line.'">'.$line.'</option>';

// after your while-loop
$h .= '</select>';

echo $h;


text:
Q: app crashes when fetching contact image from ABAddressBook MY app is crashing when i try to fetching contact image from ABAddressbook the crashing result is due to "Receive memory warning.."

A: There is a readymade code available in Git.I have used this and this will resolve you problem.
Try this:
https://github.com/AliSoftware/OHAttributedLabel

A: you have to use CoreText FrameWork.
Maybe this tutorial can help you

A: You can not create this with simple UILabel
https://github.com/honcheng/RTLabel best one, lightwaited.


text:
Q: clearTimeout vs setInterval I have a WordPress site that I made a plugin slider for.
I want to pause the setTimeout on hover and resume or reset it on mouseout.
My code has gotten a little messy as I have been adding things as I go.
I think I should've used the setInterval method, but I'm not sure.
The site is at **
and here is my .js file:
$(document).ready(function(){
addActive();
})

function addActive(){

$time = constants.transition;
$delay = constants.delay+'000';
$control = constants.control;
var $change = $($control);

console.log($time);
console.log($delay);
console.log($control);

var $slider = $('.slider-plus');
var $value1 = $slider.find('li:nth-child(1) .sas-values').html();
$('.slider-plus li:nth-child(1)').addClass('active').css({'z-index':'1','opacity':'1'});
$change.html($value1);
setTimeout(translate1, $delay);

function translate1(){
    var $change = $($control);
    var $value2 = $slider.find('li:nth-child(2) .sas-values').html();
    $slider.find('li:nth-child(3)').removeClass('translate');
    $slider.find('li:nth-child(1)').removeClass('active').addClass('translate').animate({'z-index':'0','opacity':'0'},$time);
    $slider.find('li:nth-child(2)').addClass('active').animate({'z-index':'1','opacity':'1'},$time);
    $change.html($value2);
    if ($slider.find('li:nth-child(2)').hasClass('active')) {
        $slider.hover(function(){
            clearTimeout($(this).data('timeout'));
        }, function(){
            setTimeout(translate2, $delay);
        });
    }
}

function translate2(){
    var $change = $($control);
    var $value3 = $slider.find('li:nth-child(3) .sas-values').html();
    $slider.find('li:nth-child(1)').removeClass('translate');
    $slider.find('li:nth-child(2)').removeClass('active').addClass('translate').animate({'z-index':'0','opacity':'0'},$time);
    $slider.find('li:nth-child(3)').addClass('active').animate({'z-index':'1','opacity':'1'},$time);
    $change.html($value3);
    setTimeout(translate3, $delay);
}

function translate3(){
    var $change = $($control);
    var $value3 = $slider.find('li:nth-child(3) .sas-values').html();
    $slider.find('li:nth-child(2)').removeClass('translate');
    $slider.find('li:nth-child(3)').removeClass('active').addClass('translate').animate({'z-index':'0','opacity':'0'},$time);
    $slider.find('li:nth-child(1)').addClass('active').animate({'z-index':'1','opacity':'1'},$time);
    $change.html($value1);
    setTimeout(translate1, $delay);
}

}

Thanks for any help,
Matt

A: Use the DRY concept and let JS calculate the number of slides for you.
Also, you can animate much fluidly using CSS3.
All you need is to assign a class to the current slide using JS.
Yes, you can use setInterval:

$(".slider").each(function() {

  var $cont = $(".cont", this), // Get DIV for content
      $li   = $("li", this),    // Get slides
      tot   = $li.length,       // How many slides?
      itv   = null,             // setInterval variable
      c     = 0                 // Dummy incremental counter

  function anim() {
    var $liC = $li.removeClass("show").eq(c).addClass("show");
    $cont.html($liC.find(".to-cont").html());
    c = ++c % tot; // Increment and loop counter
  }

  function stop() {
    clearInterval( itv );
  }

  function play() {
    itv = setInterval(anim, 3000);
  }

  $(this).hover(stop, play);    // Pause on hover

  anim();                       // Animate first slide in!
  play();                       // Start loop!

});
*{margin:0;box-sizing:border-box;}

.slider{
  position:relative;
  height:50vh;
}
.slider .cont{
  position:relative;
  background:#eee;
  width:33.333%;  height:100%;
  padding:24px 16px;
}
.slider ul{
  position:absolute;
  overflow:hidden;
  right:0;  top:0;
  width:66.666%;  height:100%;
  padding:0;  list-style:none;
}
.slider ul li{
  position:absolute;
  width:100%;  height:100%;
  background:50%;  background-size:cover;

  transition: transform 1s, opacity 1s;
  opacity:0;
  transform:translateX(-100%);
}
.slider ul li.show{
  transition: transform 0s, opacity 1s;
  opacity:1;
  transform:translateX(   0%);
}
.slider ul li div{
  position:absolute;
  right:0;  bottom:0;
  padding:16px;
  background:rgba(255,255,255,0.5)
}
.slider ul li .to-cont{display:none;}

This is slide 1

Slide 1
 1orem ipsum...

This is some slide 2

Slide 2
 2orem ipsum...

Slide 3

Slide 3
 3orem ipsum...

Offtopic: (as a UI designer) I'd suggest you a much "nicer?" way to animate that stuff, and that's to:
keep the old slide and instead slidein the new one.
The human eye is more attracted to moving objects. A new moving slide makes more conceptual and introductory sense to a new gallery/slideshow topic.


text:
Q: Which "one hundred rules" did Harry and Ron break to find the Chamber of Secrets? Towards the end of Harry Potter and the Chamber of Secrets Professor McGonagall says that Harry and Ron broke "a hundred school rules".

"Very well," Professor McGonagall prompted him as he paused, "so you found out where the entrance was — breaking a hundred school rules into pieces along the way, I might add —"

Which hundred rules did they break?

A: *

*First of all, she's probably exaggregating for effect in-universe.

*Second of all JKR likes to exaggregate for effect the same way in general

'Filch'll have me there all night,' said Ron heavily. 'No magic! There must be about a hundred cups in that room. I'm no good at Muggle cleaning.'
'I'll make it,' Lockhart butted in. 'I must have done it a hundred times, I could whip up a Mandrake Restorative Draught in my sleep –'
'I was so sure it was Malfoy' said Ron, for about the hundredth time.

*Some of the rules they broke (Bolded are the ones that are {almost} certain to be rules)

*

*The "fifty rules" Hermione mentioned breaking to Polyjuice themselves.

*Harry repeatedly lying to Dumbledore about not having anything important to tell him (like hearing the snake)

*Doing magic in the corridors

Percy said, 'As a school Prefect –', but Harry had lost his temper. He pulled out his wand and shouted, 'Expelliarmus!' and just as Snape had disarmed Lockhart, so Malfoy found the diary shooting out of his hand into the air. Ron, grinning broadly, caught it.
  'Harry!' said Percy loudly. 'No magic in the corridors. I'll have to report this, you know!'

*Fighting with a cupid dwarf in the corridor. Not sure if that's against school rules, but if I put on my McGonagall hat (yes I own one!), I think it would be.
The rest will be subsequent to Hermione's petrificarion:

*

*Going to see Hagrid using Invisibility Cloak

*Going to the Forbidden Forest

*Talking to Acromantula (classification XXXXX in Fantastic Beasts)

*Going to Moaning Mirtle's bathroom (first, girls'! and second, going alone without an adult)

*Lying to Prof. McGonagall that they were going to see Hermione in Hospital Wing when she caught them going to bathroom

*Going alone into another corridor to teacher's staffroom

*Listening in to teachers discussing another attack

*NOT telling the teachers what they (or rather, Hermione) found.

*Going alone to see Lockhart

*Pulling a wand on a teacher (I won't count casting Expelliarmus as a sin)

*Forced Lockhart to go with them at wandpoint

*Went to the girls' bathroom AGAIN

*Spoke in Parseltongue (not sure it's a sin, but I'll be as strict as McGonagle and ding them a point anyway)

*Pushed a professor down the entrance (Ron "gave him a push", literally).

*Spoke Parseltongue again to open the Chamber door

*Killed an endangered animal

*Handled a highly cursed object (2 of them - fang and diary)

*Lied to a Professor (Lockhart) who he and they were


text:
Q: Vectorized assignment of a 2-dimensional array I work with Python 2.7, numpy and pandas.
I have :

*

*a function y=f(x) where both x and y are scalars.

*a one-dimensional array of scalars of length n : [x0, x1, ..., x(n-1)]

I need to construct a 2-dimensional array D[i,j]=f(xi)*f(xj) where i,j are indices in [0,...,n-1].
I could use loops and/or a comprehension list, but that would be slow. I would like to use a vectorized approach instead.
I thought that "numpy.indices" would help me (see Create a numpy matrix with elements a function of indices), but I admit I am at a loss on how to use that command for my purpose.
Thanks in advance!

A: Ignore the comments that dismiss vectorization; it's a good habit to have, and it does deliver performance with the right accelerators. Anyway, what I really wanted to say was that you want to find the outer product:
x_ = numpy.array(x)
y = f(x_)
numpy.outer(y, y)

If you're working with numbers you should be working with numpy data structures anyway. Then you get fast, readable code like this.

A:
I would like to use a vectorized approach instead.

You sound like you might be a Matlab user -- you should be aware that numpy's vectorize function provides no performance benefit:

The vectorize function is provided primarily for convenience, not for
  performance. The implementation is essentially a for loop.

Unless it just so happens that there's already an operation in numpy that does exactly what you want, you're going to be stuck with numpy.vectorize and nothing to really gain over a for loop. With that being said, you should be able to do that like so:
def makeArray():
    a = [1, 2, 3, 4]
    def addTo(arr):
        return f(a[math.floor(arr/4)]) * f(a[arr % 4])
    vecAdd = numpy.vectorize(addTo)
    return vecAdd(numpy.arange(4 * 4).reshape(4, 4))

EDIT:
If f is actually a one-dimensional array, you can do this:
f_matrix = numpy.matrix(f)
D = f_matrix.T * f_matrix

A: You can use fromfunc to vectorize the function then use the dot product to multiply:
f2 = numpy.fromfunc(f, 1, 1)  # vectorize the function
res1 = f2(x)  # get the results for f(x)
res1 = res1[np.newaxis]  # result has to be 2D for the next step
res2 = np.dot(a.T, a)  # get f(xi)*f(xj)


text:
Q: Unknown Error on embeding Stripe Pricing Table I have an error when I try to embed a stripe princing table on a web page.
When I copy the code provided by stripe during the cration of the pricing table and refresh the page it gives me unknown error. I used the HTML method to embed the pricing table.
Here my code :
<html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>test</title>

  </head>

  <body>
    <script async src="https://js.stripe.com/v3/pricing-table.js">

    </script>
    <stripe-pricing-table pricing-table-id="{{PRICING_TABLE_ID}}"
    publishable-key="{{PUBLISHABLE_KEY}}">

    </stripe-pricing-table>
  </body>
</html>

Do you guys have any solution ?

A: In order to test the pricing table in your local environment, you need to have have a local HTTP Server(e.g. Nginx, Apache).
The pricing table requires a website domain to render. You need to run a local HTTP server and host your website's index.html file over the localhost domain.
More details can be found here [1].
[1] https://stripe.com/docs/payments/checkout/pricing-table#limitations:~:text=Testing%20the%20pricing,server%20npm%20module.


text:
Q: Studying C++/CLI without prior knowledge of ANSI/ISO C++ I used to program in C#, and I want to study C++. Can I study C++/CLI directly before having prior knowledge of the ANSI/ISO C++?

A: C++/CLI is a language that allows you to write pure managed code.  The compiler even has an option for that, /clr:pure.  But the code it generates then is not different from the code that the C# compiler generates.  There is therefore no point in using that feature, unless you are a die-hard C++ programmer that favors a C++-like syntax.
It is not equivalent to C++ and there's very little in the language that will prepare you to learn native C++.  Very basic native C++ constructs like multiple inheritance, RAII and const are either not available or only approximated.  Especially the new C++11 additions are not covered at all, not something you ever want to skip when you start out learning C++.
C++/CLI is targeted as an interop language, it makes it very easy to write a managed class wrapper around existing native C or C++ code.  Clearly that is no use to you either if you don't yet know what these languages look like.
Only consider using native C++ if that's the language you want to learn.  Learning C++/CLI will only confuse you.

A: You can, but why?
If you want to learn about C++, you better start programming in C++ (without /Cli).
C++/Cli adds a set of complex behavior and managed pointer types that are not really useful outside of writing wrappers between C++ and C#, and ref classes lack some of the major benefits of C++; namely, RAII (deterministic destruction), const, and  templates.


text:
Q: deserializing entities with relationships We receive JSON that looks like:
{ name: "john", surname: "smith", company: "1234342" }

Our Client Side framework can also handle relationships between objects and company is mapped to its ID.
We have an Hibernate Customer entity, which has a Company member which is a relationship to another Company entity.
We use Spring's @RequestMapping method(@RequestBody Customer c) to process requests and deserialize Entities, but we fail to deserialize the provided JSON. Hibernate does not know how to build a Company from a String, regardless of the fact that the String is its primary key.
It is very easy to serialize entities from Hibernate into JSON, but deserialization seems a different story.
Is there any pattern/construct to handle what we want to achieve? Can anybody point me in the right direction?

A: The simplest solution is to have two separate class models, one for Hibernate and one for JSON, and convert between them as necessary.
It's not very elegant, though, so Jackson (which is the the JSON implementation used by Spring) provides an extension mechanism (called Modules), which in turn allows you to register custom deserialization logic (i.e. how to turn JSON tokens into java objects).  Have a look at that, see if it works for you.
You;d then have to configure Jackson in the Spring context to use the custom mapper.

A: I think Dozer would be ideal to do such serialization/deserialization. If you receive the JSON structure as a map then you can tell dozer to convert that map to a corresponding entity object.


text:
Q: configure Laravel mix mix.webpackConfig({}) with entry points and outputs I'm developing an application that use php 5.6 and laravel 5.4. I'm using laravel mix for build my assets. I need to know how to use mix.webpackConfig({}) method to use another webpack configurations like use babel-loader, riot-tag-loader etc. Is there any way to use this method to do that with entry point and output files? For an example, I need to do following thing inside my mix.webpackConfig({}).
module.exports = {
    entry: {
        admin: ['./resources/assets/admin/js/app.js'],
        'manuals/parent/child/js': ['./resources/views/manuals/parent/child/js/app.js']
    },
    output: {
        filename: '[name]/app.js',
        path: path.resolve(__dirname + '/public')
    },
    module: {
        rules: [
            {
                test: /\.tag$/,
                exclude: /node_modules/,
                loader: 'riot-tag-loader',
                query: {
                    type: 'es6',
                    hot: true
                }
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader'
                }
            }
        ]
    }
};

Is that possible? Is that so, please let me know how to do that. Thanks

A: I've hardly found the laravel-mix mix.webpackConfig({}) successfully initiated, and even working samples are rear. I do not know what framework you are trying to manage but this sample works; this is a config for less-loader, hope you can tune it to suit your purpose.
const path = require('path');
mix.webpackConfig({
 module: {
   rules: [
      {
        test: /\.less$/,
        loader: "style-loader!css-loader!less-loader",
        exclude: [
            path.resolve(__dirname, "node-modules"),
            path.resolve(__dirname, "resources/assets/less"),
        ],
      },
  ]}
})

A: Mix is a configuration layer on top of Webpack, so to run your Mix tasks you only need to execute one of the NPM scripts that is included with the default Laravel package.json file: more details in official site
https://laravel.com/docs/5.7/mix