问:
How to write a repeat element to each row in scrapy
I am testing my hand at scraping with scrapy. Thrilled with progress so far, I have an issue where the data model of the source website doesn't seem to align with my current scrapy output.

Source provides Categories, Type, and URL data - each category contains multiple types, and each type has a URL.

I am looking to get an output maintaining the nesting of the data where each row associates the category, type, and URL grouping.

Both XLM and CSV outputs provide unique categories but hold all subsequent type and url data in columns for each category row.

Source/example site:

Half-Cents and Cents

Liberty Cap Half Cent (1793-1797)

Draped Bust Half Cent (1800-1808)

Classic Head Half Cent (1809-1836)

Two and Three Cents

Two Cent (1864-1873)

Three Cent Silver (1851-1873)

Three Cent Nickel (1865-1889)

```

<p>Working spider scraping all necessary data, but not formatted as needed:</p>

<pre class="lang-py prettyprint-override"><code>import scrapy

class PCGSSpider(scrapy.Spider):
    name = "pcgs_spider"
    custom_settings = {
        'FEED_FORMAT': 'xml',
        'FEED_URI': 'pcgsspider.xml'
    }
    start_urls = ['abovesample.html']

    def parse(self, response):
        SET_SELECTOR = '.box'
        for pcgs in response.css(SET_SELECTOR):

            CAT_SELECTOR = 'h3 ::text'
            TYPE_SELECTOR = './/ul/li/a/text()'
            URL_SELECTOR = './/ul/li/a/@href'
            yield {
                    'categories': pcgs.css(CAT_SELECTOR).extract(),
                    'types': pcgs.xpath(TYPE_SELECTOR).extract(),
                    'type_url': pcgs.xpath(URL_SELECTOR).extract(),
            }
</code>```

And the XML showing the right data, but not nested with each URL with its TYPE, and TYPE with its CATEGORY

-<item>
-<categories>
    <value>Half-Cents and Cents</value>
</categories>
-<types>
    <value>Liberty Cap Half Cent (1793-1797)</value>
    <value>Draped Bust Half Cent (1800-1808)</value>
    <value>Classic Head Half Cent (1809-1836)</value>
</types>
-<type_url>
    <value>/auctionprices/category/lincoln-cent-wheat-reverse-1909-1958/46</value>
    <value>/auctionprices/category/lincoln-cent-modern-1959-date/47</value>
    <value>/auctionprices/category/lincoln-cent-modern-1959-date/47</value>
</type_url>
</item>
```

Very new to this all so pardon any ignorance - it seems some level of iteration would resolve the problem, though it isn't clear to me if within my spider is the best place to resolve as the data and core of the structure is complete.

答:
The only way I see is to duplicate CATEGORY value for each link with type and url:

```<code>import scrapy

class PCGSSpider(scrapy.Spider):
    name = "pcgs_spider"
    custom_settings = {
        'FEED_FORMAT': 'xml',
        'FEED_URI': 'pcgsspider.xml'
    }
    start_urls = ['abovesample.html']

    def parse(self, response):
        for div_box in response.css("div.box"):
            category = div_box.css("h3 ::text").extract_first()
            for li in div_box.css("ul li"):
                yield { 'category':category,
                        'type':li.css("a ::text").extract_first(),
                        'url' :li.css("a ::attr(href)").extract_first
                      }
</code>```

Body:
I am testing my hand at scraping with scrapy. Thrilled with progress so far, I have an issue where the data model of the source website doesn't seem to align with my current scrapy output.

Source provides Categories, Type, and URL data - each category contains multiple types, and each type has a URL.

I am looking to get an output maintaining the nesting of the data where each row associates the category, type, and URL grouping.

Both XLM and CSV outputs provide unique categories but hold all subsequent type and url data in columns for each category row.

Source/example site:

Half-Cents and Cents

Liberty Cap Half Cent (1793-1797)

Draped Bust Half Cent (1800-1808)

Classic Head Half Cent (1809-1836)

Two and Three Cents

Two Cent (1864-1873)

Three Cent Silver (1851-1873)

Three Cent Nickel (1865-1889)

Working spider scraping all necessary data, but not formatted as needed:

import scrapy

class PCGSSpider(scrapy.Spider):
    name = "pcgs_spider"
    custom_settings = {
        'FEED_FORMAT': 'xml',
        'FEED_URI': 'pcgsspider.xml'
    }
    start_urls = ['abovesample.html']

    def parse(self, response):
        SET_SELECTOR = '.box'
        for pcgs in response.css(SET_SELECTOR):

            CAT_SELECTOR = 'h3 ::text'
            TYPE_SELECTOR = './/ul/li/a/text()'
            URL_SELECTOR = './/ul/li/a/@href'
            yield {
                    'categories': pcgs.css(CAT_SELECTOR).extract(),
                    'types': pcgs.xpath(TYPE_SELECTOR).extract(),
                    'type_url': pcgs.xpath(URL_SELECTOR).extract(),
            }

And the XML showing the right data, but not nested with each URL with its TYPE, and TYPE with its CATEGORY

-<item>
-<categories>
    <value>Half-Cents and Cents</value>
</categories>
-<types>
    <value>Liberty Cap Half Cent (1793-1797)</value>
    <value>Draped Bust Half Cent (1800-1808)</value>
    <value>Classic Head Half Cent (1809-1836)</value>
</types>
-<type_url>
    <value>/auctionprices/category/lincoln-cent-wheat-reverse-1909-1958/46</value>
    <value>/auctionprices/category/lincoln-cent-modern-1959-date/47</value>
    <value>/auctionprices/category/lincoln-cent-modern-1959-date/47</value>
</type_url>
</item>

Very new to this all so pardon any ignorance - it seems some level of iteration would resolve the problem, though it isn't clear to me if within my spider is the best place to resolve as the data and core of the structure is complete.

Body:
The only way I see is to duplicate CATEGORY value for each link with type and url:

import scrapy

class PCGSSpider(scrapy.Spider):
    name = "pcgs_spider"
    custom_settings = {
        'FEED_FORMAT': 'xml',
        'FEED_URI': 'pcgsspider.xml'
    }
    start_urls = ['abovesample.html']

    def parse(self, response):
        for div_box in response.css("div.box"):
            category = div_box.css("h3 ::text").extract_first()
            for li in div_box.css("ul li"):
                yield { 'category':category,
                        'type':li.css("a ::text").extract_first(),
                        'url' :li.css("a ::attr(href)").extract_first
                      }


来源: stackexchange

问:
How do I properly include a wx.grid inside a wx.GridBagSizer?
I'm just beginning to lean python and the use of wxpython widgets. I tried creating a 50 X 3 wx.grid.  If it's the only object in a panel, then there's no problem.  However, if I tried to include other objects by using a GridBagSizer then it seem to occupy only one cell of the sizer even of I specified span=(5,3) for 5 row, 3 columns.

I tried using a separate BoxSizer for the panel containing the grid (commented in my code) by it also didn't work.

```<code>import wx
import wx.grid

class Screen(wx.Frame):
    def __init__(self, parent, title):
        super(Screen, self).__init__(parent, title=title,
            size=(500, 500))
                self.paneltab = wx.Panel(self.panel)
        self.paneltab.SetSize(size=(150,150))

        #this is the grid I want to display properly
        self.tab = wx.grid.Grid(self.paneltab)

        self.tab.CreateGrid(50,3)
        self.tab.SetColSize(0,150)
        self.tab.SetColSize(1,100)
        self.tab.SetColSize(2,50)
        self.tab.SetColLabelValue(0, "USER")
        self.tab.SetColLabelValue(1, "Log-In Time")
        self.tab.SetColLabelValue(2, "Status")
        self.SetLayout()
        self.Centre()

    def SetLayout(self):
        sizer = wx.GridBagSizer(0,0)
        #sizertab = wx.BoxSizer(wx.VERTICAL)
        #self.paneltab.SetSizer(sizerTab)

        sizer.Add((100,-1),     pos=(0,0))
        sizer.Add((100,-1),     pos=(0,1))
        sizer.Add((100,-1),     pos=(0,2))
        text1 = wx.StaticText(self.panel, label='Hello', style =
            wx.ALIGN_CENTER)
        text2 = wx.StaticText(self.panel, label='World', style =
            wx.ALIGN_CENTER)

        sizer.Add(text1,   pos=(1,0),  span=(1,1), flag=wx.TOP|wx.EXPAND,
            border=5)
        sizer.Add(text2,   pos=(1,2),  span=(1,2), flag=wx.TOP|wx.EXPAND,
            border=5)

        #sizer.Add(sizertab,     pos=(2,1),  span=(5,2),
            flag=wx.TOP|wx.EXPAND,  border=5)
        sizer.Add(self.paneltab,     pos=(2,0),  span=(5,3),
            flag=wx.TOP|wx.EXPAND,  border=5)

        self.panel.SetSizer(sizer)
        sizer.Fit(self)
        self.panel.SetBackgroundColour("thristle1")

def main():
    app = wx.App()
    screen = Screen(None, title='Server Consule')
    screen.Show()
    app.MainLoop()
if __name__ == '__main__':
    main()
</code>```

I expected the grid to be displayed in a span=(5,3) but it seem to be displayed in a span=(1,1).

答:
I think you miss this in your code:

```<code>    self.panel = wx.Panel(self)
</code>```

And to make, your StaticText for example, "use" the whole space maybe try it like this:

```<code>    sizer.Add(text1,(1,0),(1,1),1,wx.TOP|wx.EXPAND,5)
    sizer.Add(text2,(1,2),(1,2),1,wx.TOP|wx.EXPAND,5)
</code>```

Important is the "1" before the flags. That makes them use the whole space.

ContentLicense: CC BY-SA 4.0

Body:
I'm just beginning to lean python and the use of wxpython widgets. I tried creating a 50 X 3 wx.grid.  If it's the only object in a panel, then there's no problem.  However, if I tried to include other objects by using a GridBagSizer then it seem to occupy only one cell of the sizer even of I specified span=(5,3) for 5 row, 3 columns.

I tried using a separate BoxSizer for the panel containing the grid (commented in my code) by it also didn't work.

import wx
import wx.grid

class Screen(wx.Frame):
    def __init__(self, parent, title):
        super(Screen, self).__init__(parent, title=title,
            size=(500, 500))
                self.paneltab = wx.Panel(self.panel)
        self.paneltab.SetSize(size=(150,150))

        #this is the grid I want to display properly
        self.tab = wx.grid.Grid(self.paneltab)

        self.tab.CreateGrid(50,3)
        self.tab.SetColSize(0,150)
        self.tab.SetColSize(1,100)
        self.tab.SetColSize(2,50)
        self.tab.SetColLabelValue(0, "USER")
        self.tab.SetColLabelValue(1, "Log-In Time")
        self.tab.SetColLabelValue(2, "Status")
        self.SetLayout()
        self.Centre()

    def SetLayout(self):
        sizer = wx.GridBagSizer(0,0)
        #sizertab = wx.BoxSizer(wx.VERTICAL)
        #self.paneltab.SetSizer(sizerTab)

        sizer.Add((100,-1),     pos=(0,0))
        sizer.Add((100,-1),     pos=(0,1))
        sizer.Add((100,-1),     pos=(0,2))
        text1 = wx.StaticText(self.panel, label='Hello', style =
            wx.ALIGN_CENTER)
        text2 = wx.StaticText(self.panel, label='World', style =
            wx.ALIGN_CENTER)

        sizer.Add(text1,   pos=(1,0),  span=(1,1), flag=wx.TOP|wx.EXPAND,
            border=5)
        sizer.Add(text2,   pos=(1,2),  span=(1,2), flag=wx.TOP|wx.EXPAND,
            border=5)

        #sizer.Add(sizertab,     pos=(2,1),  span=(5,2),
            flag=wx.TOP|wx.EXPAND,  border=5)
        sizer.Add(self.paneltab,     pos=(2,0),  span=(5,3),
            flag=wx.TOP|wx.EXPAND,  border=5)

        self.panel.SetSizer(sizer)
        sizer.Fit(self)
        self.panel.SetBackgroundColour("thristle1")

def main():
    app = wx.App()
    screen = Screen(None, title='Server Consule')
    screen.Show()
    app.MainLoop()
if __name__ == '__main__':
    main()

I expected the grid to be displayed in a span=(5,3) but it seem to be displayed in a span=(1,1).

Body:
I think you miss this in your code:

    self.panel = wx.Panel(self)

And to make, your StaticText for example, "use" the whole space maybe try it like this:

    sizer.Add(text1,(1,0),(1,1),1,wx.TOP|wx.EXPAND,5)
    sizer.Add(text2,(1,2),(1,2),1,wx.TOP|wx.EXPAND,5)

Important is the "1" before the flags. That makes them use the whole space.


问:
How to detect touch device in 2019?
For my app, I need to radically change the entire UX for touch devices using an onscreen keyboard (eg. mobile, touch TV) vs mouse/kbd devices (eg. desktop, a mobile with a bluetooth mouse/kbd).

NB. I've already grokked responsive layout with CSS grid and media queries, so that aspect is dealt with. My issue isn't one of layout, it's that the entire UX needs to be fundamentally different. The best option I have so far is to listen for a mousemove on the whole viewport.

How can I do this using modern browsers?

Note I've already read the existing answers which are all several years old, and generally conclude that it can't be done.

答:
In javascript.

```<code> if ("ontouchstart" in document.documentElement)
    {
        document.write("your device is a touch screen device.");
    }
    else
    {
         document.write("your device is NOT a touch device");
    }
</code>```

code pen

Title: How to detect touch device in 2019?

Body:
In javascript.

 if ("ontouchstart" in document.documentElement)
    {
        document.write("your device is a touch screen device.");
    }
    else
    {
         document.write("your device is NOT a touch device");
    }

code pen


问:
Precedence of 'or' and 'and' operators in C
In the following code, I am getting 10 | 1 | 1 as a result. But according to precedence rules shouldn't 'and' operator must be evaluated first?(and yield c=9) Like : d = a || (--b)&&(--c) since 'and' has higher precedence. ( or shortcutting breaks precedence rules ?)Thanks in advance.</p>

```<code>#include <stdio.h>
#include <stdlib.h>

int main(){
    int a,b,c,d;
    a =1;
    b = c = 10;
    d = a|| --b&&--c;
    printf("%d\n",c);
    printf("%d\n",a);
    printf("%d\n",d);
    return 0;
}
</code>```

答:
Precedence only determines which operands are grouped with which operators - it does not control the order in which expressions are evaluated.

In your example, it means the expression is parsed as

```<code>a || (––b && ––c)
</code>```

Both || and && force left-to-right evaluation1.  Both introduce a sequence point (IOW, the left hand operand will be evaluated and all side effects will be applied before the right hand operand is evaluated).

Both operators short-circuit - if the left operand of || evaluates to non-zero, then the result of the expression is 1 (true) regardless of the value of the right operand, so the right operand isn’t evaluated at all.  If the left operand of && is 0, then the result of the expression is 0 (false) regardless of the value of the right operand, so the right operand isn’t evaluated at all.

In your expression, a is evaluated first.  It has a non-zero value (1), so ––b && ––c is not evaluated.

Along with the ?: and comma operators.  All other operators (arithmetic, equality, subscript, etc.) do not force a particular order of evaluation.

Body:
In the following code, I am getting 10 | 1 | 1 as a result. But according to precedence rules shouldn't 'and' operator must be evaluated first?(and yield c=9) Like : d = a || (--b)&&(--c) since 'and' has higher precedence. ( or shortcutting breaks precedence rules ?)Thanks in advance.

#include <stdio.h>
#include <stdlib.h>

int main(){
    int a,b,c,d;
    a =1;
    b = c = 10;
    d = a|| --b&&--c;
    printf("%d\n",c);
    printf("%d\n",a);
    printf("%d\n",d);
    return 0;
}

Body:
Precedence only determines which operands are grouped with which operators - it does not control the order in which expressions are evaluated.

In your example, it means the expression is parsed as

a || (––b && ––c)

Both || and && force left-to-right evaluation1.  Both introduce a sequence point (IOW, the left hand operand will be evaluated and all side effects will be applied before the right hand operand is evaluated).

Both operators short-circuit - if the left operand of || evaluates to non-zero, then the result of the expression is 1 (true) regardless of the value of the right operand, so the right operand isn’t evaluated at all.  If the left operand of && is 0, then the result of the expression is 0 (false) regardless of the value of the right operand, so the right operand isn’t evaluated at all.

In your expression, a is evaluated first.  It has a non-zero value (1), so ––b && ––c is not evaluated.

Along with the ?: and comma operators.  All other operators (arithmetic, equality, subscript, etc.) do not force a particular order of evaluation.


问:
Checking the regional settings
In my app I need to check if the regional settings are russian on the computer it's running on. Also, I need to know if russian keyboard layout is installed.

The intention behind this is to know whether this computer is likely (I don't need to be 100% sure, likely is good enough) to be owned by a russian. The idea is to check if the regional settings are set to russian, and/or if there is a russian keyboard layout installed, as those are both likely to be present in a computer owned by a russian, but unlikely to be present on a computer owned, say, by an american.

Btw it's not really about russian, it's other nationalities I'll check for, I was just using it as an example.

How can I check those?

答:
National Language Support Functions is a good place to start.

You need to decide which info you want - You can check which locales are existing, installed, system default, user default or active for a thread. GetThreadLocale will tell you the active locale for a thread, GetUserDefaultLCID and GetSystemDefaultLCID will tell you defaults, the EnumSystemLocales function will let you see which locales exist/are installed, or you can use IsValidLocale to check if a specific locale is installed.

ContentLicense: CC BY-SA 3.0

Title: Checking the regional settings


问:
Why javascript array accepts string value index
Why does a Javascript array accept a string as an index, and when it accepts any string value as index then why doesn't it change its length?

I am new to Javascript and encountered this issue.

var newArr = [];
newArr[0] = 0;
newArr[1] = 1;
newArr["2"] = 3;
newArr[3] = 3;
newArr[4] = 4;
newArr["a"] = "a";
console.log(newArr);```
</div>
</div>
</p>

```(5) [0, 1, 3, 3, 4, a: "a"]
length: 5
__proto__: Array(0)
```

答:
Why javscript array accepts string as index

All (normal) property keys get coerced to a string during assignment, if they aren't strings already.

```<code>newArr["2"] = 3;
</code>```

is the same as

```<code>newArr[2] = 3;
</code>```

Arrays are objects, and objects accept arbitrary key-value pairs, so

```<code>newArr["a"] = "a";
</code>```

is legal, it's just very strange to do.

The length of an array only checks numeric properties, see here:

The length property of this Array object is a data property whose value is always numerically greater than the name of every deletable property whose name is an array index.

By "array index", it means that the property key is numeric.

Note that it's also possible to have a Symbol key, which is the one case where a property key will not be a string:

const sym = Symbol();
const obj = {};
obj[sym] = 'foo';

console.log(typeof sym);
console.log(obj);```

Body:
Why does a Javascript array accept a string as an index, and when it accepts any string value as index then why doesn't it change its length?

I am new to Javascript and encountered this issue.

var newArr = [];
newArr[0] = 0;
newArr[1] = 1;
newArr["2"] = 3;
newArr[3] = 3;
newArr[4] = 4;
newArr["a"] = "a";
console.log(newArr);

(5) [0, 1, 3, 3, 4, a: "a"]
length: 5
__proto__: Array(0)

Body:
Why javscript array accepts string as index

All (normal) property keys get coerced to a string during assignment, if they aren't strings already.

newArr["2"] = 3;

is the same as

newArr[2] = 3;

Arrays are objects, and objects accept arbitrary key-value pairs, so

newArr["a"] = "a";

is legal, it's just very strange to do.

The length of an array only checks numeric properties, see here:

The length property of this Array object is a data property whose value is always numerically greater than the name of every deletable property whose name is an array index.

By "array index", it means that the property key is numeric.

Note that it's also possible to have a Symbol key, which is the one case where a property key will not be a string:

const sym = Symbol();
const obj = {};
obj[sym] = 'foo';

console.log(typeof sym);
console.log(obj);


问:
SyntaxError: Unexpected identifier jest & babel 7 & react-native 0.56
After upgrading react native version to 0.56, I could not run my tests.
I was testing my app before upgrade.

I get SyntaxError: Unexpected identifier error.

Details in below. Can you help me, please?

This is my devDependencies.

```<code>"@babel/core": "^7.0.0",
"@babel/plugin-proposal-optional-chaining": "^7.0.0",
"babel-core": "^7.0.0-bridge.0",
"babel-jest": "^23.4.2",
"babel-preset-react-native": "^5.0.2",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"enzyme-to-json": "^3.3.4",
"jest": "^23.4.2",
"react-addons-test-utils": "^15.6.2",
"react-dom": "^16.4.2",
"react-test-renderer": "^16.4.2",
"regenerator-runtime": "^0.12.1",
"sinon": "^6.1.5"
</code>```

I configured the jest in this way.

```<code>"jest": {
  "preset": "react-native",
  "snapshotSerializers": [
    "enzyme-to-json/serializer"
  ],
  "setupTestFrameworkScriptFile": "<rootDir>/setupTest.js"
}
</code>```

.babelrc

```<code>{
  "presets": ["react-native"],
  "plugins": [
    "@babel/plugin-proposal-optional-chaining"
  ]
}
</code>```

Error detail - 1

```<code>import KeyboardAwareMixin from './lib/KeyboardAwareMixin';
       ^^^^^^^^^^^^^^^^^^

SyntaxError: Unexpected identifier

  1 | import React from "react";
  2 | import {View} from "react-native";
> 3 | import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view";
    | ^
  4 | import PropTypes from 'prop-types';
  5 |
  6 | /**

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
</code>```

Error Detail - 2

```<code>import createIconSet from './lib/create-icon-set';
       ^^^^^^^^^^^^^

SyntaxError: Unexpected identifier

  1 | import React, {Component} from "react";
  2 | import {TouchableOpacity} from "react-native";
> 3 | import Icon from "react-native-vector-icons/FontAwesome";
    | ^
  4 | import {COLORS} from "../config/Constant";
  5 | import PropTypes from "prop-types";
  6 |

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
</code>```

Error Details - 3

```<code>SyntaxError: /Users/----/node_modules/react-native/Libraries/Components/Touchable/TouchableOpacity.js: Unexpected token (26:12)

  24 | const flattenStyle = require('flattenStyle');
  25 |
> 26 | import type {Props as TouchableWithoutFeedbackProps} from 'TouchableWithoutFeedback';
     |             ^
  27 | import type {ViewStyleProp} from 'StyleSheet';
  28 |
  29 | type Event = Object;

  at Parser.raise (node_modules/@babel/parser/lib/index.js:3938:15)
  at Parser.unexpected (node_modules/@babel/parser/lib/index.js:5247:16)
  at Parser.expectContextual (node_modules/@babel/parser/lib/index.js:5215:41)
  at Parser.parseImport (node_modules/@babel/parser/lib/index.js:8403:12)
  at Parser.parseStatementContent (node_modules/@babel/parser/lib/index.js:7225:27)
  at Parser.parseStatement (node_modules/@babel/parser/lib/index.js:7144:17)
  at Parser.parseBlockOrModuleBlockBody (node_modules/@babel/parser/lib/index.js:7695:23)
  at Parser.parseBlockBody (node_modules/@babel/parser/lib/index.js:7682:10)
  at Parser.parseTopLevel (node_modules/@babel/parser/lib/index.js:7109:10)
  at Parser.parse (node_modules/@babel/parser/lib/index.js:8495:17)
</code>```

答:
Not sure but maybe the OP had solved the problem here

https://github.com/facebook/react-native/issues/20966

You can

Use babel version from RN 0.56.

OR upgrade RN to 0.57 for babel 7

Body:
After upgrading react native version to 0.56, I could not run my tests.
I was testing my app before upgrade.

I get SyntaxError: Unexpected identifier error.

Details in below. Can you help me, please?

This is my devDependencies.

"@babel/core": "^7.0.0",
"@babel/plugin-proposal-optional-chaining": "^7.0.0",
"babel-core": "^7.0.0-bridge.0",
"babel-jest": "^23.4.2",
"babel-preset-react-native": "^5.0.2",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"enzyme-to-json": "^3.3.4",
"jest": "^23.4.2",
"react-addons-test-utils": "^15.6.2",
"react-dom": "^16.4.2",
"react-test-renderer": "^16.4.2",
"regenerator-runtime": "^0.12.1",
"sinon": "^6.1.5"

I configured the jest in this way.

"jest": {
  "preset": "react-native",
  "snapshotSerializers": [
    "enzyme-to-json/serializer"
  ],
  "setupTestFrameworkScriptFile": "<rootDir>/setupTest.js"
}

.babelrc

{
  "presets": ["react-native"],
  "plugins": [
    "@babel/plugin-proposal-optional-chaining"
  ]
}

Error detail - 1

import KeyboardAwareMixin from './lib/KeyboardAwareMixin';
       ^^^^^^^^^^^^^^^^^^

SyntaxError: Unexpected identifier

  1 | import React from "react";
  2 | import {View} from "react-native";
> 3 | import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view";
    | ^
  4 | import PropTypes from 'prop-types';
  5 |
  6 | /**

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

Error Detail - 2

import createIconSet from './lib/create-icon-set';
       ^^^^^^^^^^^^^

SyntaxError: Unexpected identifier

  1 | import React, {Component} from "react";
  2 | import {TouchableOpacity} from "react-native";
> 3 | import Icon from "react-native-vector-icons/FontAwesome";
    | ^
  4 | import {COLORS} from "../config/Constant";
  5 | import PropTypes from "prop-types";
  6 |

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

Error Details - 3

SyntaxError: /Users/----/node_modules/react-native/Libraries/Components/Touchable/TouchableOpacity.js: Unexpected token (26:12)

  24 | const flattenStyle = require('flattenStyle');
  25 |
> 26 | import type {Props as TouchableWithoutFeedbackProps} from 'TouchableWithoutFeedback';
     |             ^
  27 | import type {ViewStyleProp} from 'StyleSheet';
  28 |
  29 | type Event = Object;

  at Parser.raise (node_modules/@babel/parser/lib/index.js:3938:15)
  at Parser.unexpected (node_modules/@babel/parser/lib/index.js:5247:16)
  at Parser.expectContextual (node_modules/@babel/parser/lib/index.js:5215:41)
  at Parser.parseImport (node_modules/@babel/parser/lib/index.js:8403:12)
  at Parser.parseStatementContent (node_modules/@babel/parser/lib/index.js:7225:27)
  at Parser.parseStatement (node_modules/@babel/parser/lib/index.js:7144:17)
  at Parser.parseBlockOrModuleBlockBody (node_modules/@babel/parser/lib/index.js:7695:23)
  at Parser.parseBlockBody (node_modules/@babel/parser/lib/index.js:7682:10)
  at Parser.parseTopLevel (node_modules/@babel/parser/lib/index.js:7109:10)
  at Parser.parse (node_modules/@babel/parser/lib/index.js:8495:17)


问:
Can't Edit Files in Android Studio
For some unknown reason, I can't edit files in Android Studio. This includes both Java and XML files.

When I launch Android Studio (v1.2.2), everything is fine. However, after some time, I lose the ability to edit files content. Here is what I noticed:

When I click on any line in the source code, the lines get highlighted but the caret indicator is not showing.

When I start typing, a search for: box starts appearing on the top of the left panel (Project window), and it starts filtering the project files according to what I type!

Files are not locked as Read-Only. I checked.

Restarting Android Studio did not resolve it permanently. Everything seems fine for some time, then the problem appears again.

I did check my keyboard to see if I have a stucked keystroke that might cause this problem. Didn't notice anything.

In the Project window, I noticed that MainActivity file name is in grey (See the screenshot below). I'm not sure if this is because of something I did, or if it is how Android Studio identifies the main Activity in the project.

答: I had this issue appear after using external displays via USB DisplayLink for some time. After disconnecting USB and reconnecting everything returns to normal but the issue may still appear after a few days, this is just a temporary fix.</p>

Title: Can't Edit Files in Android Studio


问:
How to use "django-autocomplete-light" in inline form
I would like to use an inline model form with a 'django-autocomplete-light field'. I'm a little bit desperate also, because I don't know 'javascript' well.
This is a picture of my form. At first glance, it works as desired:

Unfortunately, only the first field loads correctly. If I add more fields there are errors (see pictures).

This is my form template where I suspect the error, because the first field works correctly as desired.

```<code><div class="container">
<form method="post" action="">
  {% csrf_token %}
  {{ form.as_p }}

  <!-- Medication Table -->
  <table class="table">
      {{ medication.management_form }}

      {% for form in medication.forms %}
          {% if forloop.first %}
              <thead>
              <tr>
                  {% for field in form.visible_fields %}
                      <th>{{ field.label|capfirst }}</th>
                  {% endfor %}
              </tr>
              </thead>
          {% endif %}
          <tr class="{% cycle "row1" "row2" %} formset_row">
              {% for field in form.visible_fields %}
                  <td>
                      {# Include the hidden fields in the form #}
                      {% if forloop.first %}
                          {% for hidden in form.hidden_fields %}
                              {{ hidden }}
                          {% endfor %}
                      {% endif %}
                      {{ field.errors.as_ul }}
                      {{ field }}
                  </td>
              {% endfor %}
          </tr>
      {% endfor %}
  </table>

  <input type="submit" value="Submit Form"/>

  <script type="text/javascript" src="{% static '/js/core/jquery.3.2.1.min.js' %}"></script>
  {{ form.media }}

    <!-- script for add, delete, update -->

    <script src="{% static 'formset/jquery.formset.js' %}"></script>
    <script type="text/javascript">
        $('.formset_row').formset({
            addText: 'add medication',
            deleteText: 'remove',
            prefix: 'medication_set'
        });
    </script>

</div>
</code>```

答:
After hours googling and going through other answers, what worked for me was this.
I added a key named clone in the defaults of the jquery.formset.js with default value as true.

```<code>    /* Setup plugin defaults */
    $.fn.formset.defaults = {
        prefix: 'form',                  // The form prefix for your django formset
        formTemplate: null,              // The jQuery selection cloned to generate new form instances
        clone: true,                     // Set this value to false when using autocomplete in formset
        addText: 'add another',          // Text for the add link
        deleteText: 'remove',            // Text for the delete link
        addCssClass: 'add-row',          // CSS class applied to the add link
        deleteCssClass: 'delete-row',    // CSS class applied to the delete link
        formCssClass: 'dynamic-form',    // CSS class applied to each form in a formset
        extraClasses: [],                // Additional CSS classes, which will be applied to each form in turn
        keepFieldValues: '',             // jQuery selector for fields whose values should be kept when the form is cloned
        added: null,                     // Function called each time a new form is added
        removed: null                    // Function called each time a form is deleted
    };
</code>```

Then replaced the code inside addButton.click() in  jquery.formset.js from

```<code>row = options.formTemplate.clone(true).removeClass('formset-custom-template')
</code>```

to

```<code>row = options.formTemplate.clone(options.clone).removeClass('formset-custom-template')
</code>```

Then in the template of the formset, changed formset function from this :

```<code>$('#brand_formset_div .parentdiv .form-group').formset({
                prefix: '{{ brand_formset.prefix }}',
                deleteText: 'Clear',
                deleteCssClass: 'shop-now-delete',
                addText: 'Add new Brand',
                addCssClass: 'btn btn-success ',
            });
</code>```

to this (a clone key as false is inserted along with a function added that is triggered when a new row is inserted.The function hides the extra autocomplete box.)

```<code>$('#brand_formset_div .parentdiv .form-group').formset({
                prefix: '{{ brand_formset.prefix }}',
                clone: false,
                deleteText: 'Clear',
                deleteCssClass: 'shop-now-delete',
                addText: 'Add new Brand',
                addCssClass: 'btn btn-success ',
                added: function(row) {
                    $('span .select2-selection--single:odd', row || null).css("display", "none");
                }
            });
</code>```

This worked fine for me.

Body:
I would like to use an inline model form with a 'django-autocomplete-light field'. I'm a little bit desperate also, because I don't know 'javascript' well.
This is a picture of my form. At first glance, it works as desired:

Unfortunately, only the first field loads correctly. If I add more fields there are errors (see pictures).

This is my form template where I suspect the error, because the first field works correctly as desired.

<form method="post" action="">
  {% csrf_token %}
  {{ form.as_p }}

      {{ medication.management_form }}

      {% for form in medication.forms %}
          {% if forloop.first %}

                  {% for field in form.visible_fields %}
                      {{ field.label|capfirst }}
                  {% endfor %}

          {% endif %}

              {% for field in form.visible_fields %}

                      {# Include the hidden fields in the form #}
                      {% if forloop.first %}
                          {% for hidden in form.hidden_fields %}
                              {{ hidden }}
                          {% endfor %}
                      {% endif %}
                      {{ field.errors.as_ul }}
                      {{ field }}

              {% endfor %}

      {% endfor %}

  <input type="submit" value="Submit Form"/>

  {{ form.media }}

Body:
After hours googling and going through other answers, what worked for me was this.
I added a key named clone in the defaults of the jquery.formset.js with default value as true.

    /* Setup plugin defaults */
    $.fn.formset.defaults = {
        prefix: 'form',                  // The form prefix for your django formset
        formTemplate: null,              // The jQuery selection cloned to generate new form instances
        clone: true,                     // Set this value to false when using autocomplete in formset
        addText: 'add another',          // Text for the add link
        deleteText: 'remove',            // Text for the delete link
        addCssClass: 'add-row',          // CSS class applied to the add link
        deleteCssClass: 'delete-row',    // CSS class applied to the delete link
        formCssClass: 'dynamic-form',    // CSS class applied to each form in a formset
        extraClasses: [],                // Additional CSS classes, which will be applied to each form in turn
        keepFieldValues: '',             // jQuery selector for fields whose values should be kept when the form is cloned
        added: null,                     // Function called each time a new form is added
        removed: null                    // Function called each time a form is deleted
    };

Then replaced the code inside addButton.click() in  jquery.formset.js from

row = options.formTemplate.clone(true).removeClass('formset-custom-template')

to

row = options.formTemplate.clone(options.clone).removeClass('formset-custom-template')

Then in the template of the formset, changed formset function from this :

$('#brand_formset_div .parentdiv .form-group').formset({
                prefix: '{{ brand_formset.prefix }}',
                deleteText: 'Clear',
                deleteCssClass: 'shop-now-delete',
                addText: 'Add new Brand',
                addCssClass: 'btn btn-success ',
            });

to this (a clone key as false is inserted along with a function added that is triggered when a new row is inserted.The function hides the extra autocomplete box.)

$('#brand_formset_div .parentdiv .form-group').formset({
                prefix: '{{ brand_formset.prefix }}',
                clone: false,
                deleteText: 'Clear',
                deleteCssClass: 'shop-now-delete',
                addText: 'Add new Brand',
                addCssClass: 'btn btn-success ',
                added: function(row) {
                    $('span .select2-selection--single:odd', row || null).css("display", "none");
                }
            });

This worked fine for me.


问:
Which is the best way to implement datatable in angular 6
I need to implement Datatable in Angular 6 project. I need to know which is the best way to implement it with full features. As it is confusing as we have multiple options.

I have came across multiple npms. In which i will select this 3 npms as my last options.

1. angular-datatables, 2. angular-6-datatable, 3. datatables.

angular-datatables :-  Well documented and many code samples is available, seems like i should go with this. But it is dependent to jquery and would it affect my angular project that is my major concern for this npm.

angular-6-datatable :- Not dependent on jquery, code samples are avialable but not that much.

datatables :- Looks like same as angular-datatables npm

Some one please suggest me the best way to go and why should i select that.

Thanks & Regards

答:
use angular material table it will support all operations like sorting, filter, lazy loading etc..

for more info read

refer live example


问:
WSO2 enterprise integrator. - datasource on server
It is possible deploy datasource  in WSO2 EI on server without GUI? I try find something on internet but i found only create datasource in GUI.

Thanks

答:
You may use Integration Studio for this purpose. Please refer https://docs.wso2.com/display/EI650/Managing+Data+Integration+Artifacts+via+Tooling#ManagingDataIntegrationArtifactsviaTooling-Step2:Creatingthedatasourceconnection.

You can create a carbon application in the tooling and deploy it to the server without using GUI.


问:
Does Flex 3 support threading?
Does Flex 3 support threading? If so, are there any examples or links I could look at?</p>

答:
As stated by Alex here:

Actionscript is single-threaded, if you spend lots of time doing heavy
  computation, the UI cannot be updated while you’re doing that
  computation so your application appears stuck or effects don’t run
  smoothly.

Similarly, there is no yielding or blocking in Actionscript either. If
  the next line of code is supposed to run, you cannot prevent the next
  line of code from running. That means that when you call Alert.show(),
  the next line of code following that runs right away.

In many other runtimes, the Alert window has to be closed before the
  next line of code continues. Threading may be a feature of
  Actionscript some day, but until then, you have to live with the fact
  that there is no such thing right now.

Title: Does Flex 3 support threading?


问:
join previous line with next depending of pattern of previous line
I have this Input:

```<code>1 a
a
2 b b
3 c
c
4 d d
5 e e
6 f
f
7 g
g
</code>```

I want this output using sed command

```<code>1 a a
2 b b
3 c c
4 d d
5 e e
6 f f
7 g g
</code>```

I'm trying this without success

```<code>sed '/^[^0-9]/ x; N; { s/\n/ / }; n' file
</code>```

答:
Another in awk:

```<code>$ awk 'BEGIN{RS=""}{for(i=1;i<=NF;i+=3)print $i,$(i+1),$(i+2)}' file
1 a a
2 b b
3 c c
4 d d
5 e e
6 f f
7 g g
</code>```

Explained:

```<code>$ awk 'BEGIN {
    RS=""                       # prime awk to read in a paragraph of data
}
{
    for(i=1;i<=NF;i+=3)         # jump forward 3 fields at a time
        print $i,$(i+1),$(i+2)  # print 3 fields
}' file
</code>```

Body:
I have this Input:

1 a
a
2 b b
3 c
c
4 d d
5 e e
6 f
f
7 g
g

I want this output using sed command

1 a a
2 b b
3 c c
4 d d
5 e e
6 f f
7 g g

I'm trying this without success

sed '/^[^0-9]/ x; N; { s/\n/ / }; n' file

Body:
Another in awk:

$ awk 'BEGIN{RS=""}{for(i=1;i<=NF;i+=3)print $i,$(i+1),$(i+2)}' file
1 a a
2 b b
3 c c
4 d d
5 e e
6 f f
7 g g

Explained:

$ awk 'BEGIN {
    RS=""                       # prime awk to read in a paragraph of data
}
{
    for(i=1;i<=NF;i+=3)         # jump forward 3 fields at a time
        print $i,$(i+1),$(i+2)  # print 3 fields
}' file


问:
How to change comments language of generated code from wsimport.exe
I want to import a .wsdl-file using %JAVA_HOME%/bin/wsimport.exe into my Java project. Everything works fine, except that the language of the comments is in german, but I want it to be in english. How can I change the language used by wsimport.exe?

答:
And another alternative using Apache CXF, which is hopefully more future proof:

```<code>Locale.setDefault(new Locale("en"));
// options: https://cxf.apache.org/docs/wsdl-to-java.html
List<String> args = new ArrayList<>();
args.add("-suppress-generated-date");
args.add("-d");
args.add(new File("src/main/java").getAbsolutePath());
args.add("-p");
args.add("com.company.targetpackage");
args.add(new File("sample.wsdl").getAbsolutePath());

WSDLToJava wsdlToJava = new WSDLToJava();
wsdlToJava.setArguments(args.toArray(new String[0]));
wsdlToJava.run(new ToolContext());
</code>```

Using the following maven dependencies:

```<code><dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-codegen-plugin</artifactId>
  <version>3.3.2</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.2</version>
</dependency>
</code>```

Body:
And another alternative using Apache CXF, which is hopefully more future proof:

Locale.setDefault(new Locale("en"));
// options: https://cxf.apache.org/docs/wsdl-to-java.html
List<String> args = new ArrayList<>();
args.add("-suppress-generated-date");
args.add("-d");
args.add(new File("src/main/java").getAbsolutePath());
args.add("-p");
args.add("com.company.targetpackage");
args.add(new File("sample.wsdl").getAbsolutePath());

WSDLToJava wsdlToJava = new WSDLToJava();
wsdlToJava.setArguments(args.toArray(new String[0]));
wsdlToJava.run(new ToolContext());

Using the following maven dependencies:

<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-codegen-plugin</artifactId>
  <version>3.3.2</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.2</version>
</dependency>


问:
How do you get a documetReference from DocumentID using the flutter cloud_firestore plugin
I'm trying to delete a specific document in a collection. each document in that collection is named with an auto generated ID.

To achieve this, i need to get a reference to that document using its ID.

I'm using the cloud_firestore plugin for flutter. theres no such luck for a function in the docs

I'm hoping for something like this

```<code>var reference = Firestore.instance.refFromID(docID);
reference.delete();
</code>```

答:
oh hey, its pretty simple actually.

```<code>Firestore.instance.collection('c').document(docID).delete();
</code>```

actually does the trick. passing the document ID into the document method gives you a reference to that document. you can do whatever you want with it afterwards

Body:
I'm trying to delete a specific document in a collection. each document in that collection is named with an auto generated ID.

To achieve this, i need to get a reference to that document using its ID.

I'm using the cloud_firestore plugin for flutter. theres no such luck for a function in the docs

I'm hoping for something like this

var reference = Firestore.instance.refFromID(docID);
reference.delete();

Body:
oh hey, its pretty simple actually.

Firestore.instance.collection('c').document(docID).delete();

actually does the trick. passing the document ID into the document method gives you a reference to that document. you can do whatever you want with it afterwards


问:
Making a chat room in Rails hosted on Heroku
I'm trying to make a pretty basic chat room in rails. I'd love to use juggernaut/node.js but heroku doesn't currently support it. I'm thinking I should just use the heroku addon "pusher." Does anyone recommend this solution or any other alternatives?</p>

答:
A real-time chat web app by Tom Arnfeld:
http://pusher-chat.heroku.com/

The code behind it:
https://github.com/tarnfeld/PusherChat-Rails

Hope that sets you in the right direction!

ContentLicense: CC BY-SA 2.5


问:
Get uncompressed size of the dataset on HDFS after being read by Spark
I am trying to improve the performance of my Spark application. To this end, I am trying to determine the optimal number of shuffle partitions for a dataset. I read from multiple sources that each partition should be about 128 MB.

So, if I have a 1GB file, I'll need around 8 partitions. But my question is how do I find the file size? I know I can find the file size on the hdfs using the following

```<code>hdfs dfs -du -s {data_path}
</code>```

But from what I understand this is the compressed size and the actual size of the file is different. (Spark uses a compression codec while writing parquet files, by default snappy). And this leads me to two questions actually

How do I find the actual uncompressed size of the file?

What should the number of shuffle partitions be based on- compressed size or actual size?

答:
Shuffle partitions are independent of the data size.

The data is uncompressed and then shuffled based on the number of shuffle partitions(using hash partitioner, range partitioner, etc).

Generally, the shuffle partitions are tuned

1. To increase the parallelism available in reducer stage.

2. To reduce the amount of data processed by shuffle partition(if we observe spills or it the reduce stage is memory intensive)

I read from multiple sources that each partition should be about 128 MB.

This is applicable only to mapper stages. The split sizes in the mapper are computed based on the size of compressed data. You can tune the size of the mapper splits using spark.sql.files.maxPartitionBytes

And the shuffle partitions(configured using spark.sql.shuffle.partitions, defaulting to 200) is related to reducer stages.

In short, compression comes into play only in mapper stages and not reducer stages.

Body:
I am trying to improve the performance of my Spark application. To this end, I am trying to determine the optimal number of shuffle partitions for a dataset. I read from multiple sources that each partition should be about 128 MB.

So, if I have a 1GB file, I'll need around 8 partitions. But my question is how do I find the file size? I know I can find the file size on the hdfs using the following

hdfs dfs -du -s {data_path}

But from what I understand this is the compressed size and the actual size of the file is different. (Spark uses a compression codec while writing parquet files, by default snappy). And this leads me to two questions actually

How do I find the actual uncompressed size of the file?

What should the number of shuffle partitions be based on- compressed size or actual size?


问:
Can I have two versions of Microsoft Access (2007 and 2013) installed at once so I can still open .adp files?
We have Access 2007 at work and we're updating to 2013 which doesn't support .adp files anymore. My superiors doesn't want to convert the .adp files to something different. They want to have both 2007 and 2013 versions installed at once so they can open the .adp files in the 2007 version and anything else in the 2013 version.

Both versions are already kind of installed but when I open one of the files in the version I want (either by right clicking and choosing a program or making a shortcut and specifying the program in the "target" field) it opens the installation window and installs the version. Then I can open files in this version all I want but when I try the other version it installs again. Then the first version is uninstalled again so they keep overwriting themselves. So I can still have just one version installed at once.

答:
Yes, the two versions will be fighting continuously.

Your solution could be to install the Microsoft Access 2010 Runtime to run the ADP application:

Microsoft Access Version Features and Differences Comparison Matrix


问:
Validator unit test fails because of custom constraint validator
I am writing tests for the constraint validators of my DTOs. They work for every DTO, except for the one which uses a custom written EmailUniqueConstraintValidator. This exception occurs:

```<code>javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.

    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:177)
    at org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints(SimpleConstraintTree.java:68)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:73)
    at org.hibernate.validator.internal.metadata.core.MetaConstraint.doValidateConstraint(MetaConstraint.java:127)
    at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:120)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:533)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:496)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:465)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:430)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:380)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:169)
    at be.ambrassade.jeugdlink.model.request.UserCreateRequestTest.passwordSizeTooShortOrLongReturnsValidationError(UserCreateRequestTest.java:71)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:532)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:171)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:167)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:114)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:59)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:108)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.NullPointerException
    at be.ambrassade.jeugdlink.validation.EmailUniqueConstraintValidator.isValid(EmailUniqueConstraintValidator.java:33)
    at be.ambrassade.jeugdlink.validation.EmailUniqueConstraintValidator.isValid(EmailUniqueConstraintValidator.java:21)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:171)
    ... 50 more
</code>```

This is the validator:

```<code>import be.ambrassade.jeugdlink.repo.UserRepository;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class EmailUniqueConstraintValidator implements ConstraintValidator<EmailUnique, String> {

    private UserRepository userRepository;

    public EmailUniqueConstraintValidator(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return value == null || !userRepository.existsByEmail(value);
    }
}
</code>```

It doesn't have a public no arg constructor, but adding one won't solve the issue either due to the repository dependency.

Because of the issue of that custom validator, none of the validation tests for that DTO work. How can I approach this issue?

答:
If you read your stacktrace again you will notice that the exception cause was a NullPointerException:

```<code>Caused by: java.lang.NullPointerException
    at be.ambrassade.jeugdlink.validation.EmailUniqueConstraintValidator.isValid(EmailUniqueConstraintValidator.java:33)
</code>```

So the solution to the problem is pretty straightforward, make sure that the userRepository field value is not null when you are accessing it in isValid method.

Body:
I am writing tests for the constraint validators of my DTOs. They work for every DTO, except for the one which uses a custom written EmailUniqueConstraintValidator. This exception occurs:

javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.

    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:177)
    at org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints(SimpleConstraintTree.java:68)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:73)
    at org.hibernate.validator.internal.metadata.core.MetaConstraint.doValidateConstraint(MetaConstraint.java:127)
    at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:120)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:533)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:496)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:465)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:430)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:380)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:169)
    at be.ambrassade.jeugdlink.model.request.UserCreateRequestTest.passwordSizeTooShortOrLongReturnsValidationError(UserCreateRequestTest.java:71)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:532)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:171)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:167)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:114)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:59)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:108)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.NullPointerException
    at be.ambrassade.jeugdlink.validation.EmailUniqueConstraintValidator.isValid(EmailUniqueConstraintValidator.java:33)
    at be.ambrassade.jeugdlink.validation.EmailUniqueConstraintValidator.isValid(EmailUniqueConstraintValidator.java:21)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:171)
    ... 50 more

This is the validator:

import be.ambrassade.jeugdlink.repo.UserRepository;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class EmailUniqueConstraintValidator implements ConstraintValidator<EmailUnique, String> {

    private UserRepository userRepository;

    public EmailUniqueConstraintValidator(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return value == null || !userRepository.existsByEmail(value);
    }
}

It doesn't have a public no arg constructor, but adding one won't solve the issue either due to the repository dependency.

Because of the issue of that custom validator, none of the validation tests for that DTO work. How can I approach this issue?

Body:
If you read your stacktrace again you will notice that the exception cause was a NullPointerException:

Caused by: java.lang.NullPointerException
    at be.ambrassade.jeugdlink.validation.EmailUniqueConstraintValidator.isValid(EmailUniqueConstraintValidator.java:33)

So the solution to the problem is pretty straightforward, make sure that the userRepository field value is not null when you are accessing it in isValid method.


问:
Javascript - Group by one property of object in an array of objects
I know that, there are countless of questions about group by one property from an array of object. But what I want to do is a litte more specific:

```<code>const lists = [
{ groupKey: 'ABC', key: 'r8', timestamp: '2014', index: 2 },
{ groupKey: 'ABC', key: 'q8', timestamp: '2012', index: 0 },
{ groupKey: 'ABC', key: 'w8', timestamp: '2013', index: 1 },
{ groupKey: 'CDE', key: 'r7', timestamp: '2019', index: 0 }
]
</code>```

Result should be grouped by groupKey and sorted by index

(indexes here are iterators 0,1,2,3... so no need to actually be sorted but rather to be placed in a right order of an array. Example: array[index] = ... ).

This should look like:

```<code>{
  ABC: [
    {  key: 'q8', timestamp: '2012', index: 0 },
    {  key: 'w8', timestamp: '2013', index: 1 },
    {  key: 'r8', timestamp: '2014', index: 2 }
  ],
  CDE: [
    { key: 'r7', timestamp: '2019', index: 0 }
  ]
}
</code>```

I have tried to group by without sorting:

```<code>const result = lists.reduce((r, item) => {
      let { groupKey, ...rest } = item
      r[item.groupKey] = [...(r[item.groupKey] || []), rest]
      return r
    }, {})
</code>```

And with sorting, not successful but you know what I mean:

```<code>const result = lists.reduce((r, item) => {
          let { groupKey, ...rest } = item
          r[item.groupKey][item.index] = rest //err: can not set property 2 of undefined
          return r
        }, {})
</code>```

Any suggestions are appreciated

答:
Try this:</p>

```<code>const result  = lists.reduce((r, item) => {
      let { groupKey, ...rest } = item
      r[item.groupKey] = [...(r[item.groupKey] || []), rest];
      (r[item.groupKey]).sort((a, b) => a.index - b.index);
      return r
    }, {});
</code>```

Body:
I know that, there are countless of questions about group by one property from an array of object. But what I want to do is a litte more specific:

const lists = [
{ groupKey: 'ABC', key: 'r8', timestamp: '2014', index: 2 },
{ groupKey: 'ABC', key: 'q8', timestamp: '2012', index: 0 },
{ groupKey: 'ABC', key: 'w8', timestamp: '2013', index: 1 },
{ groupKey: 'CDE', key: 'r7', timestamp: '2019', index: 0 }
]

Result should be grouped by groupKey and sorted by index

(indexes here are iterators 0,1,2,3... so no need to actually be sorted but rather to be placed in a right order of an array. Example: array[index] = ... ).

This should look like:

{
  ABC: [
    {  key: 'q8', timestamp: '2012', index: 0 },
    {  key: 'w8', timestamp: '2013', index: 1 },
    {  key: 'r8', timestamp: '2014', index: 2 }
  ],
  CDE: [
    { key: 'r7', timestamp: '2019', index: 0 }
  ]
}

I have tried to group by without sorting:

const result = lists.reduce((r, item) => {
      let { groupKey, ...rest } = item
      r[item.groupKey] = [...(r[item.groupKey] || []), rest]
      return r
    }, {})

And with sorting, not successful but you know what I mean:

const result = lists.reduce((r, item) => {
          let { groupKey, ...rest } = item
          r[item.groupKey][item.index] = rest //err: can not set property 2 of undefined
          return r
        }, {})

Any suggestions are appreciated

Body:
Try this:

const result  = lists.reduce((r, item) => {
      let { groupKey, ...rest } = item
      r[item.groupKey] = [...(r[item.groupKey] || []), rest];
      (r[item.groupKey]).sort((a, b) => a.index - b.index);
      return r
    }, {});


问:
why do not we use sqoop eval in production environment, what is the disadvantage by using sqoop eval?
using sqoop eval we can evaluate the connection with the database. but after that why do not we use for query propose in production environment, what's it's import in production.

sqoop eval \
    --connect jdbc:mysql://quickstart.cloudera:3306/retail_db \
    --username retail_dba \
    --password cloudera \
    --query "SELECT * FROM orders LIMIT 10"

答:
Sqoop Eval is only used to print the output of the query to the console. It is not used to import data from RDBMS to Hdfs. So "Sqoop eval" is a functionality where we get output only on console. It does not provide functionality to move data to hdfs.

Whereas, Sqoop import is actually used to import the data to hdfs.


问:
How can I return a struct if a condition is true and an int if the condition is false
First a simple example:

```<code>typedef struct
{
    char article[DIM_STRING];
    double price;
    char buyer[DIM_STRING];
}Order;

Order algorithm(int a, int b){
    if(a == b) return -1;   //Error
    else return ord;    //Returns the Order ord
}
</code>```

The question is: is it possible to return an int OR a struct? If not how can I make an escamotage to avoid the problem?

I thought I could've use pointers and return a pointer BUT pointer must have a type.

答:
if the function is of type Order it cannot return an int
but you can do this:

```<code>Order error_value;
error_value.article=""; error_value.price=-1.0; error_value.buyer="";

Order algorithm(int a,int b) {
    if (a==b) return error_value;
    else return ord;
}
</code>```

and later then you can check whether the return value is equal to ("",-1,"")

Body:
First a simple example:

typedef struct
{
    char article[DIM_STRING];
    double price;
    char buyer[DIM_STRING];
}Order;

Order algorithm(int a, int b){
    if(a == b) return -1;   //Error
    else return ord;    //Returns the Order ord
}

The question is: is it possible to return an int OR a struct? If not how can I make an escamotage to avoid the problem?

I thought I could've use pointers and return a pointer BUT pointer must have a type.

Body:
if the function is of type Order it cannot return an int
but you can do this:

Order error_value;
error_value.article=""; error_value.price=-1.0; error_value.buyer="";

Order algorithm(int a,int b) {
    if (a==b) return error_value;
    else return ord;
}

and later then you can check whether the return value is equal to ("",-1,"")


问:
PHP: are switch-case statements with strings inefficient?
In my PHP layer I'm receiving error codes as strings ("NOT_FOUND", "EXPIRED", etc). It's a small list of possible strings, perhaps a dozen. </p>

<p>What's the most efficient way of dealing with these? Using switch-case against string constants stored in a class, or should I parse them to numbers (or something) first? Or is PHP smart enough so it doesn't really matter? </p>

答:
It really depends on what you want to do with the strings. Do you want to output error messages? Then instead of a case statement you could use a lookup table like this:

```<code>$messages = array(
  'NOT_FOUND' => 'The file was not found',
  'EXPIRED' => 'The cookie expired'
  // ETC
);
echo empty($messages[$error]) ? "Unknown error" : $messages[$error];
</code>```

With PHP 5.3 you could also store code in the array to handle the error situations:

```<code>$handlers = array(
  'NOT_FOUND' => function() { /* Error handling code here */ },
  'EXPIRED' => function() { /* Other error handling code */ }
 );
 if(!empty($handlers[$error])) {
   $handler = $handlers[$error];
   $handler();
 }
 else {
   echo "Could not handle error!"; die();
 }
</code>```

With a technique like this you avoid case statements that go over several pages.

With PHP < 5.3 you might look into call_user_func for dynamic dispatching of error handling functions.

Body:
In my PHP layer I'm receiving error codes as strings ("NOT_FOUND", "EXPIRED", etc). It's a small list of possible strings, perhaps a dozen.

What's the most efficient way of dealing with these? Using switch-case against string constants stored in a class, or should I parse them to numbers (or something) first? Or is PHP smart enough so it doesn't really matter?

Body:
It really depends on what you want to do with the strings. Do you want to output error messages? Then instead of a case statement you could use a lookup table like this:

$messages = array(
  'NOT_FOUND' => 'The file was not found',
  'EXPIRED' => 'The cookie expired'
  // ETC
);
echo empty($messages[$error]) ? "Unknown error" : $messages[$error];

With PHP 5.3 you could also store code in the array to handle the error situations:

$handlers = array(
  'NOT_FOUND' => function() { /* Error handling code here */ },
  'EXPIRED' => function() { /* Other error handling code */ }
 );
 if(!empty($handlers[$error])) {
   $handler = $handlers[$error];
   $handler();
 }
 else {
   echo "Could not handle error!"; die();
 }

With a technique like this you avoid case statements that go over several pages.

With PHP < 5.3 you might look into call_user_func for dynamic dispatching of error handling functions.


问:
Limit of Freemium projects reached, but only 1 active project
I created an Here Freemium account a long time ago.
I'm using geocoding and map services.

I created some projects in the past and removed them a few months ago.

Today, I want to create new projects but I can't because :
"You've reached the limit of Freemium projects for this account.
Please visit your project page to see your existing projects.
Contact us if you need another project."

But We only have 1 active project on our account..
Here account page.

Cannot we be able to create 5 freemium project ?
We tried to contact the support but the support told us to find the answer here... Anyone can give us a clue ? :)

Thank you.

答:
In this case please contact selfservesupport@here.com
They can have a look at the details of your contract.</p>


答:
You can break it down into two parts

Let the function return an int value, where (usually), a return value of 0 indicates success and other negative values indicate different types of error.

Take a pointer to the structure variable as one of the arguments. In case of success condition, fill the structure, and in the caller, based on the return value of the function call, the structure can be accessed to retrieve the value stored into it's members.

Title: How can I return a struct if a condition is true and an int if the condition is false


问:
Replicate some data with relations
I have a problem i need to replicate the selected survey. When i click on the button he need to replicate all data from that selected survey.

I'm new to Laravel so i dont know how to do this. But i already tried some things but its not working. and i dont know why. Someone can help me out??

Public function controller:

```<code>public function copySurvey( Manager $fractal, SurveyTransformer $surveyTransformer ) {
    // Copy function (Alleen nog niet volledig hier nog even aanwerken.)
    $copy = Survey::first();

    //copy attributes
    $newsurvey = $copy->replicate();
    $newsurvey->sid = 123456;

    // save it
    $newsurvey->save();
}
</code>```

Model relations survey:

```<code>public function accuracy() {

    return $this->hasOne( 'App\Models\LimeSurvey\Accuracy', 'survey_id', 'sid' );
}

public function groups() {

    return $this->hasMany( 'App\Models\LimeSurvey\Group', 'sid', 'sid' )->orderBy('gid', 'asc')->orderBy('group_order', 'asc');
}

public function questions() {

    return $this->hasMany( 'App\Models\LimeSurvey\Question', 'sid', 'sid' )->orderBy('gid', 'asc')->orderBy('question_order', 'asc');
}

public function parentQuestions() {

    return $this->hasMany( 'App\Models\LimeSurvey\Question', 'sid', 'sid' )->where('parent_qid', '=', 0)->orderBy('gid', 'asc')->orderBy('question_order', 'asc');
}

public function languages() {

    return $this->hasMany( 'App\Models\LimeSurvey\Language', 'surveyls_survey_id', 'sid' );
}
</code>```

答:
You should iterate trougth relations after save:</p>

```<code>$original = Survey::first();

$new = $original->replicate();
$new->sid = 123456;
$new->save();

foreach($original->groups as $group){
    $new->groups()->attach($group);
}

foreach($original->questions as $question){
    $new->questions()->attach($question);
}
</code>```

Title: Replicate some data with relations

Body:
I have a problem i need to replicate the selected survey. When i click on the button he need to replicate all data from that selected survey.

I'm new to Laravel so i dont know how to do this. But i already tried some things but its not working. and i dont know why. Someone can help me out??

Public function controller:

public function copySurvey( Manager $fractal, SurveyTransformer $surveyTransformer ) {
    // Copy function (Alleen nog niet volledig hier nog even aanwerken.)
    $copy = Survey::first();

    //copy attributes
    $newsurvey = $copy->replicate();
    $newsurvey->sid = 123456;

    // save it
    $newsurvey->save();
}

Model relations survey:

public function accuracy() {

    return $this->hasOne( 'App\Models\LimeSurvey\Accuracy', 'survey_id', 'sid' );
}

public function groups() {

    return $this->hasMany( 'App\Models\LimeSurvey\Group', 'sid', 'sid' )->orderBy('gid', 'asc')->orderBy('group_order', 'asc');
}

public function questions() {

    return $this->hasMany( 'App\Models\LimeSurvey\Question', 'sid', 'sid' )->orderBy('gid', 'asc')->orderBy('question_order', 'asc');
}

public function parentQuestions() {

    return $this->hasMany( 'App\Models\LimeSurvey\Question', 'sid', 'sid' )->where('parent_qid', '=', 0)->orderBy('gid', 'asc')->orderBy('question_order', 'asc');
}

public function languages() {

    return $this->hasMany( 'App\Models\LimeSurvey\Language', 'surveyls_survey_id', 'sid' );
}

Body:
You should iterate trougth relations after save:

$original = Survey::first();

$new = $original->replicate();
$new->sid = 123456;
$new->save();

foreach($original->groups as $group){
    $new->groups()->attach($group);
}

foreach($original->questions as $question){
    $new->questions()->attach($question);
}


问:
How to use HashMap to compare and match colors
I would like to match color search results text with the checkbox text after clicking search button.  See pic.

Currently I can view the Search Results text color but it doesn't match the checkbox text color after clicking search button.  The code below is only for the Search Car Results text area and a class named CarBrand that matches the key of this HashMap carDetails.  I am not sure how to compare and match its color using HashMap.  Any suggestions would be great!

```<code>import java.awt.Color;
import java.swing.tree.DefaultTreeCellRenderer

public final class CarDetails extends DefaultTreeCellRenderer
{
    private final Color defaultColor;
    private final HashMap<String, Color> carDetails = new HashMap<>();

    public CarDetails()
    {
        int i = 0;
        defaultColor = getBackground(); //default color
        int [][] rgb = {
            { 200, 000, 200 },
            { 000, 140, 000 },
            { 000, 200, 200 }

        };
        for (CarBrand car: CarModel.getCarBrandDetails()) {
            carDetails.put(car.getCarBrand(), new Color(
                rgb[i][0], rgb[i][1], rgb[i][2]));
            i++;
            // TODO this part is what I am not sure.
            if (carDetails.containsKey(car.getCarBrand()) && carTable != null) {
                for (Component c : carTable.getComponents()) {
                    if (c.getName().equals(car.getCarBrand())) {
                       c.setForeground(carDetails.containsObject(new
                              Color(rgb[i][0], rgb[i][1], rgb[i][2])));
                    }
                }
            }
        }
    }
}
</code>```

I expect the output to match the color coding of the Search Car Results with the CheckBox text (Honda, Hundai, BMW) like the pic below.

答:
I agree with Andrew Thompson a lot of code is missing to be able to reproduce your problem.

You should check if your conditions are correct (if statements).
The declaration of carTable is missing so we can't verify how it is build up. You use Component.getName(), are you sure this contains the value you expect ?
see what-is-java-awt-component-getname-and-setname-used-for
It is not filled by default so if you fill it before with the expected values, than it's fine to use.

Assuming c.getName() returns the name of the carBrand, you can do the following:

```<code>    for (CarBrand car: CarModel.getCarBrandDetails()) {
        carDetails.put(car.getCarBrand(), new Color(
            rgb[i][0], rgb[i][1], rgb[i][2]));
        i++;
    }
    if (carTable != null) {
        for (Component c : carTable.getComponents()) {
            if(carDetails.containsKey(c.getName()) {
                c.setForeground(carDetails.get(c.getName())));
            }
        }
    }
</code>```

In your code you are not using the values from carDetails map you filled before. By calling ´carDetails.get()` method you reuse the created Color object.

Body:
I would like to match color search results text with the checkbox text after clicking search button.  See pic.

Currently I can view the Search Results text color but it doesn't match the checkbox text color after clicking search button.  The code below is only for the Search Car Results text area and a class named CarBrand that matches the key of this HashMap carDetails.  I am not sure how to compare and match its color using HashMap.  Any suggestions would be great!

import java.awt.Color;
import java.swing.tree.DefaultTreeCellRenderer

public final class CarDetails extends DefaultTreeCellRenderer
{
    private final Color defaultColor;
    private final HashMap<String, Color> carDetails = new HashMap<>();

    public CarDetails()
    {
        int i = 0;
        defaultColor = getBackground(); //default color
        int [][] rgb = {
            { 200, 000, 200 },
            { 000, 140, 000 },
            { 000, 200, 200 }

        };
        for (CarBrand car: CarModel.getCarBrandDetails()) {
            carDetails.put(car.getCarBrand(), new Color(
                rgb[i][0], rgb[i][1], rgb[i][2]));
            i++;
            // TODO this part is what I am not sure.
            if (carDetails.containsKey(car.getCarBrand()) && carTable != null) {
                for (Component c : carTable.getComponents()) {
                    if (c.getName().equals(car.getCarBrand())) {
                       c.setForeground(carDetails.containsObject(new
                              Color(rgb[i][0], rgb[i][1], rgb[i][2])));
                    }
                }
            }
        }
    }
}

I expect the output to match the color coding of the Search Car Results with the CheckBox text (Honda, Hundai, BMW) like the pic below.

Body:
I agree with Andrew Thompson a lot of code is missing to be able to reproduce your problem.

You should check if your conditions are correct (if statements).
The declaration of carTable is missing so we can't verify how it is build up. You use Component.getName(), are you sure this contains the value you expect ?
see what-is-java-awt-component-getname-and-setname-used-for
It is not filled by default so if you fill it before with the expected values, than it's fine to use.

Assuming c.getName() returns the name of the carBrand, you can do the following:

    for (CarBrand car: CarModel.getCarBrandDetails()) {
        carDetails.put(car.getCarBrand(), new Color(
            rgb[i][0], rgb[i][1], rgb[i][2]));
        i++;
    }
    if (carTable != null) {
        for (Component c : carTable.getComponents()) {
            if(carDetails.containsKey(c.getName()) {
                c.setForeground(carDetails.get(c.getName())));
            }
        }
    }

In your code you are not using the values from carDetails map you filled before. By calling ´carDetails.get()` method you reuse the created Color object.


问:
Is it possible to select only columns where at least one value is present?
I need to select all coulmns where at least one value is present. For example if this is my table:

```<code>----------------------------
name   |  keyword  |  zip
----------------------------
User1  |  test     |  ""
User2  |  test     |  ""
User3  |  ""       |  ""
</code>```

Should output something like this:

```<code>-----------------
name   |  keyword
-----------------
User1  |  test
User2  |  test
User3  |  ""
</code>```

The thing is that zip might not be empty and in this case the output should also include the zip column. The actual table I need this functionality for has many more columns that can potentially be empty.

I tried using SELECT * FROM myTable HAVING COUNT(*) > 0 but that did not work (empty columns were still showing).

Also tried solving it with php using loops but didn't get far that way either.

Is something like this even possible using SQL or should it be done using php for example?

SOLUTION

Here's the solution I came up with in PHP using the suggestions I got for this question.

```<code>$stack = array("keyword", "zip");
$id = $_POST["id"];
$sql = "SELECT name";
foreach($stack as $i){
    $q = "SELECT ".$i." FROM myTable WHERE ".$i." != '' AND id = '".$id."'";
    $result = mysqli_query($link, $q);
    if(mysqli_num_rows($result) > 0){
        $sql = $sql.", ".$i;
    }
}
$sql = $sql." FROM myTable WHERE id = '".$id."'";
</code>```

This will output the following sql query:
SELECT name, keyword FROM myTable WHERE id = 'postedId'

Notice the zip is missing from select, this is because for that particular query there were no values in zip. In the $stack array you can put whatever columns you want to check.

Also make note of how I used != '' to check for empty values but if your table has empty values as NULL make sure to use IS NOT NULL instead.

答:
This is quite painful and not really in the spirit of SQL -- where a select statement has a fixed number of columns defined when the statement is written.

That said, you can use two levels of dynamic SQL, one to get the columns and one to use them:

```<code>-- generate the SQL to identify the columns

select @sql := group_concat(replace('select max(''[column_name]'') as col from t having count([column_name]) > 0', '[column_name]', c.column_name)
                    separator ' union all ' )
from information_schema.columns c
where table_name = 't';

-- use the SQL to get the columns
select @sql := concat('select group_concat(col separator '', '') into @cols from (', @sql, ') x');

-- run the SQL
prepare s from @sql;
execute s  ;

-- create the final query using the columns
set @sql2 = concat('select ', @cols, ' from t');

-- and execute it
prepare s2 from @sql2;
execute s2;
</code>```

Note:  in a real application, you would want to deallocate the prepared statements.

Here is a db<>fiddle illustrating this process.

Body:
I need to select all coulmns where at least one value is present. For example if this is my table:

----------------------------
name   |  keyword  |  zip
----------------------------
User1  |  test     |  ""
User2  |  test     |  ""
User3  |  ""       |  ""

Should output something like this:

-----------------
name   |  keyword
-----------------
User1  |  test
User2  |  test
User3  |  ""

The thing is that zip might not be empty and in this case the output should also include the zip column. The actual table I need this functionality for has many more columns that can potentially be empty.

I tried using SELECT * FROM myTable HAVING COUNT(*) > 0 but that did not work (empty columns were still showing).

Also tried solving it with php using loops but didn't get far that way either.

Is something like this even possible using SQL or should it be done using php for example?

SOLUTION

Here's the solution I came up with in PHP using the suggestions I got for this question.

$stack = array("keyword", "zip");
$id = $_POST["id"];
$sql = "SELECT name";
foreach($stack as $i){
    $q = "SELECT ".$i." FROM myTable WHERE ".$i." != '' AND id = '".$id."'";
    $result = mysqli_query($link, $q);
    if(mysqli_num_rows($result) > 0){
        $sql = $sql.", ".$i;
    }
}
$sql = $sql." FROM myTable WHERE id = '".$id."'";

This will output the following sql query:
SELECT name, keyword FROM myTable WHERE id = 'postedId'

Notice the zip is missing from select, this is because for that particular query there were no values in zip. In the $stack array you can put whatever columns you want to check.

Also make note of how I used != '' to check for empty values but if your table has empty values as NULL make sure to use IS NOT NULL instead.

Body:
This is quite painful and not really in the spirit of SQL -- where a select statement has a fixed number of columns defined when the statement is written.

That said, you can use two levels of dynamic SQL, one to get the columns and one to use them:

-- generate the SQL to identify the columns

select @sql := group_concat(replace('select max(''[column_name]'') as col from t having count([column_name]) > 0', '[column_name]', c.column_name)
                    separator ' union all ' )
from information_schema.columns c
where table_name = 't';

-- use the SQL to get the columns
select @sql := concat('select group_concat(col separator '', '') into @cols from (', @sql, ') x');

-- run the SQL
prepare s from @sql;
execute s  ;

-- create the final query using the columns
set @sql2 = concat('select ', @cols, ' from t');

-- and execute it
prepare s2 from @sql2;
execute s2;

Note:  in a real application, you would want to deallocate the prepared statements.

Here is a db<>fiddle illustrating this process.


问:
Multiple form controls in child component with control value accessor using Angular 5
I want to implement a functionality with control value accessor in Angular 5. It's like to access multiple form control in child custom component from a parent. Please let me know if I can achieve this in another way. Template driven form compulsory.

If there is any other any to generic create a custom control with two-way data binding, please let me know. It would great if answers are in Plunker or StackBlitz.

Here is mine: https://stackblitz.com/edit/angular-qzioet

Parent component :-

```<code>export class AppComponent implements OnInit  {
  public countryList: any = [];
  public option: any =[ ];
      public personal = {
   identity: {
  name: {firstname: null, lastname: null },
  age: null,
  sex: null
   }
 }
  @ViewChild('personalForm') form: any;
 constructor() {

   }
</code>```

Parent html:-

<app-input name ='name'
  [(ngModel)]="personal.identity.name" [form]="personalForm"
    ngDefaultControl></app-input>

Child component :-

```<code>   import {Component, Input, forwardRef} from '@angular/core'
   import {
    FormControl,
         FormGroup,
    ControlValueAccessor,
    NG_VALUE_ACCESSOR,
        NG_VALIDATORS,
     Validator
         } from '@angular/forms';

    @Component({
 selector: 'app-input',
   templateUrl: "./input-child.html",
          providers: [
{
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => Child),
  multi: true
},
{
  provide: NG_VALIDATORS,
  useExisting: forwardRef(() => Child),
  multi: true,
}
   ]
   })

   export class Child implements ControlValueAccessor, Validator {
 @Input() form: any;
  @Input() name: any;
 childControl = new FormGroup({ firstname: new FormControl() ,
 lastname: new FormControl() });

 fn: (value: any) => void;
 constructor() {
     console.log(this.childControl);
  }

   writeValue(value: any) {
 if (value) {
  this.childControl.setValue(value);
 }
 }

  registerOnChange(fn: (value: any) => void) {
   this.fn = fn;
  }

   registerOnTouched() {}

    validate(c: FormControl) {

        return this.childControl.errors;
        };
    }
</code>```

Child html:-

```<code>    `<h1>Child</h1>
    <div>
 <input [formControl]="firstname" (input)="fn($event.target.value)"
    required>

<input [formControl]="lastname" name="lastname"
 (input)="fn($event.target.value)" required>

</div>`
</code>```

答:
What you want to do can be achieved more easily without implementing ControlValueAccessor.
Instead, you can simply set the viewProviders in the child component to use the existing parent NgForm as the ControlContainer.

Then, there's no need to pass the form as an input parameter to the child component as the form controls will automatically be part of the parent's form.

input-child.component.ts:

@Component({
    selector: 'input-child',
    templateUrl: './input-child.component.html',
    viewProviders: [{ provide: ControlContainer, useExisting: NgForm}]
})
export class Child {
    @Input() personalName = {};

    ...
}
```

<p>input-child.component.html:</p>

<pre class="lang-html prettyprint-override"><code><h1>Child</h1>
<div>
    <input [(ngModel)]="personalName.firstname" name="firstname" required>
    <input [(ngModel)]="personalName.lastname" name="lastname" required>
</div>
</code>```

parent.component.ts:

export class AppComponent {
    public countryList: any = [];
    public option: any =[ ];
    public personal = {
        identity: {
            name: {firstname: 'first-name', lastname: 'last-name' },
            age: null,
            sex: null
        }
    }

    ...
}
```

<p>parent.component.html:</p>

<pre class="lang-html prettyprint-override"><code><form #personalForm="ngForm" name="personalForm">
    <child-input [personalName]="personal.identity.name"></child-input>
</form>
</code>```

Body:
I want to implement a functionality with control value accessor in Angular 5. It's like to access multiple form control in child custom component from a parent. Please let me know if I can achieve this in another way. Template driven form compulsory.

If there is any other any to generic create a custom control with two-way data binding, please let me know. It would great if answers are in Plunker or StackBlitz.

Here is mine: https://stackblitz.com/edit/angular-qzioet

Parent component :-

export class AppComponent implements OnInit  {
  public countryList: any = [];
  public option: any =[ ];
      public personal = {
   identity: {
  name: {firstname: null, lastname: null },
  age: null,
  sex: null
   }
 }
  @ViewChild('personalForm') form: any;
 constructor() {

   }

Parent html:-

<app-input name ='name'
  [(ngModel)]="personal.identity.name" [form]="personalForm"
    ngDefaultControl></app-input>

Child component :-

   import {Component, Input, forwardRef} from '@angular/core'
   import {
    FormControl,
         FormGroup,
    ControlValueAccessor,
    NG_VALUE_ACCESSOR,
        NG_VALIDATORS,
     Validator
         } from '@angular/forms';

    @Component({
 selector: 'app-input',
   templateUrl: "./input-child.html",
          providers: [
{
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => Child),
  multi: true
},
{
  provide: NG_VALIDATORS,
  useExisting: forwardRef(() => Child),
  multi: true,
}
   ]
   })

   export class Child implements ControlValueAccessor, Validator {
 @Input() form: any;
  @Input() name: any;
 childControl = new FormGroup({ firstname: new FormControl() ,
 lastname: new FormControl() });

 fn: (value: any) => void;
 constructor() {
     console.log(this.childControl);
  }

   writeValue(value: any) {
 if (value) {
  this.childControl.setValue(value);
 }
 }

  registerOnChange(fn: (value: any) => void) {
   this.fn = fn;
  }

   registerOnTouched() {}

    validate(c: FormControl) {

        return this.childControl.errors;
        };
    }

Child html:-

    `
Child

 <input [formControl]="firstname" (input)="fn($event.target.value)"
    required>

<input [formControl]="lastname" name="lastname"
 (input)="fn($event.target.value)" required>

`

Body:
What you want to do can be achieved more easily without implementing ControlValueAccessor.
Instead, you can simply set the viewProviders in the child component to use the existing parent NgForm as the ControlContainer.

Then, there's no need to pass the form as an input parameter to the child component as the form controls will automatically be part of the parent's form.

input-child.component.ts:

@Component({
    selector: 'input-child',
    templateUrl: './input-child.component.html',
    viewProviders: [{ provide: ControlContainer, useExisting: NgForm}]
})
export class Child {
    @Input() personalName = {};

    ...
}

input-child.component.html:

<h1>Child</h1>
<div>
    <input [(ngModel)]="personalName.firstname" name="firstname" required>
    <input [(ngModel)]="personalName.lastname" name="lastname" required>
</div>

parent.component.ts:

export class AppComponent {
    public countryList: any = [];
    public option: any =[ ];
    public personal = {
        identity: {
            name: {firstname: 'first-name', lastname: 'last-name' },
            age: null,
            sex: null
        }
    }

    ...
}

parent.component.html:

<form #personalForm="ngForm" name="personalForm">
    <child-input [personalName]="personal.identity.name"></child-input>
</form>