问:
Liferay: BooleanQuery MUST NOT some values
I want to create a search with multiple values, for example:

I want to search in database all Articles that do not contain the category:

Car
Bus
motorcycle
truck
On database exist articles with a category 'Car' foe example but not with category 'Car' and 'Bus' (One Article & One Category). So ... I need to make some like to "OR" (I need all articles that do not have category with 'Car' OR with 'Bus' OR with 'truck' etc ..)

We're using Liferay 6.1 for this search.

答:
I couldn't completely understand the description given. If you are trying to fetch records that do not have a category like CAR, BUS, TRUCK etc. You can try by negating your query.

```<code>-category:(car bus truck motorcycle)
</code>```

The minus( - ) sign placed before category will negate the search. So it returns records that do not have these categories.

Body:
I couldn't completely understand the description given. If you are trying to fetch records that do not have a category like CAR, BUS, TRUCK etc. You can try by negating your query.

-category:(car bus truck motorcycle)

The minus( - ) sign placed before category will negate the search. So it returns records that do not have these categories.


来源: stackexchange

问:
Name of this type of inheritance semantic
```<code>public class _base
{
    protected int x = 5;
    protected int GetX(_base b) { return b.x; }
}

public class _derived : _base
{
    public int Foo()
    {
        var b = new _base();
        //return b.x;  // <-- this would be illegal
        return GetX(b); // <-- This works and does exactly the same as the line above
    }
}
</code>```

(Please don't change code. It is working and shows the problem.)

The error is

```<code>Cannot access protected member '_base.x' via a qualifier of type '_base'; the qualifier must be of type '_derived' (or derived from it)
</code>```

Note that because b is of type _base and we are not in base we cannot access it's protected members. I imagine the reason is because _base might be of some other derived type and hence it is not protecting the code but that's not the point. What I'm doing is creating a work around for the above problem using the extra protected methods. This gives me the behavior I want and the protection I want. I wish there were a keyword that allows this kinda access but there isn't. What I'm interested in is if this "pattern" has a name.

(I'm using protected because internal allows anyone in the same assembly access)

答:
I think I understand what you mean. Do not create base class' instances in methods. It gets created by the constructor. Reference base class members either using only the member name or you case precede it with the base keyword.

In the above example you would use it as follows:

```<code>class A : _base {
     void Foo() {
         x = 10; //or base.x = 10;
         SetX(10); //or base.SetX(10);
         Console.WriteLine(GetX()); //or base.GetX()
     }
}
</code>```

Moreover you may be interested in Properties construct which is a nice syntactic sugar for java's ugly getX and setX pattern.

ContentLicense: CC BY-SA 2.5

Body:
public class _base
{
    protected int x = 5;
    protected int GetX(_base b) { return b.x; }
}

public class _derived : _base
{
    public int Foo()
    {
        var b = new _base();
        //return b.x;  // <-- this would be illegal
        return GetX(b); // <-- This works and does exactly the same as the line above
    }
}

(Please don't change code. It is working and shows the problem.)

The error is

Cannot access protected member '_base.x' via a qualifier of type '_base'; the qualifier must be of type '_derived' (or derived from it)

Note that because b is of type _base and we are not in base we cannot access it's protected members. I imagine the reason is because _base might be of some other derived type and hence it is not protecting the code but that's not the point. What I'm doing is creating a work around for the above problem using the extra protected methods. This gives me the behavior I want and the protection I want. I wish there were a keyword that allows this kinda access but there isn't. What I'm interested in is if this "pattern" has a name.

(I'm using protected because internal allows anyone in the same assembly access)

Body:
I think I understand what you mean. Do not create base class' instances in methods. It gets created by the constructor. Reference base class members either using only the member name or you case precede it with the base keyword.

In the above example you would use it as follows:

class A : _base {
     void Foo() {
         x = 10; //or base.x = 10;
         SetX(10); //or base.SetX(10);
         Console.WriteLine(GetX()); //or base.GetX()
     }
}

Moreover you may be interested in Properties construct which is a nice syntactic sugar for java's ugly getX and setX pattern.


问:
How to find a value if we have 2 same columns in 2 different tables?
As you can see on the photo. I have 2 tables(A and B). KlantId is common in 2 tables. What I want to achieve is, if I provide the Email then I can get the reservatieNummer.

答:
To use linq:</p>

```<code>var ReservatieID =  tableA.Join(tableB, ta =>ta.KlantId, tb =>tb.KlantId, (ta,tb) =>new{tableA = ta, tableB = tb})
                    .Where(a=> a.email == "whatever@domain.com").Select(a=> new{a.reservatieID});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
To use linq:

var ReservatieID =  tableA.Join(tableB, ta =>ta.KlantId, tb =>tb.KlantId, (ta,tb) =>new{tableA = ta, tableB = tb})
                    .Where(a=> a.email == "whatever@domain.com").Select(a=> new{a.reservatieID});


问:
how to display date and time picker when I switch on the button
When I switch ON the button, I want 2 text views to appear and if I click each text view it shows open a date and time picker so that I can select them.</p>

答:
Android How do I correctly get the value from a Switch?

You can refer this link for checking if switch is on or off and accordingly handle visibility of textview.And you can put your date and time picker onclick of textviews

Do you need even date and time picker code?


问:
Get current Hour/Minute/Secong/Millisecond using timezone of some specific city like America/Mexico_City in swift 3 xcode
Here, I want to get current Hour/Minute/Secong/Millisecond using timezone of some specific city like America/Mexico_City using swift 3 xcode. I tried to get current Time-hrs/min/sec/millisec of Mexico city like,

```<code>    let date = Date()
    var calendar = Calendar.current
    calendar.timeZone = TimeZone.init(identifier: "America/Mexico_City")! /* Something wrong here */

    hrOfDay = calendar.component(.hour, from: date)
    curMin = calendar.component(.minute, from: date)
    curSec = calendar.component(.second, from: date)
    curMillSec = Int(Int64(Date().timeIntervalSince1970 * 1000)) /* this should be fetched using calendar object */
    print("hours = \(hrOfDay):\(curMin):\(curSec):\(curMillSec)")
</code>```

But I'm unable to get current time of some specific city like MexicoCity. So, Please help me out.

答:
TimeZone.init(identifier: "America/Mexico_City")

'America/Mexico_City' is ID, not a name.

so, you can compare to get TimeZone ID by City name from list:

```<code>https://raw.githubusercontent.com/dmfilipenko/timezones.json/master/timezones.json
</code>```

Ref: https://github.com/dmfilipenko/timezones.json

Body:
Here, I want to get current Hour/Minute/Secong/Millisecond using timezone of some specific city like America/Mexico_City using swift 3 xcode. I tried to get current Time-hrs/min/sec/millisec of Mexico city like,

    let date = Date()
    var calendar = Calendar.current
    calendar.timeZone = TimeZone.init(identifier: "America/Mexico_City")! /* Something wrong here */

    hrOfDay = calendar.component(.hour, from: date)
    curMin = calendar.component(.minute, from: date)
    curSec = calendar.component(.second, from: date)
    curMillSec = Int(Int64(Date().timeIntervalSince1970 * 1000)) /* this should be fetched using calendar object */
    print("hours = \(hrOfDay):\(curMin):\(curSec):\(curMillSec)")

But I'm unable to get current time of some specific city like MexicoCity. So, Please help me out.

Body:
TimeZone.init(identifier: "America/Mexico_City")

'America/Mexico_City' is ID, not a name.

so, you can compare to get TimeZone ID by City name from list:

https://raw.githubusercontent.com/dmfilipenko/timezones.json/master/timezones.json

Ref: https://github.com/dmfilipenko/timezones.json


问:
Convert facebook birthday to age swift
When retrieving birthday from the Facebook SDK i get this string "01/12/1990".

My question is, how would you convert the birthday into the age of the user using this string?

答:
Swift 4

My use case is also for Facebook and I have used UserDefaults to store the birthdate. The below function will retrieve birthdate from UserDefaults, as returned by the graphRequest which is in the same format as your Date. The function will return an Integer with the user's age.

```<code>    func getAgeFromBirthdate() -> Int {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/dd/yyyy"
    let birthday = UserDefaults.standard.object(forKey: "birthday")
    let birthdayString = birthday as! String
    let birthdate = dateFormatter.date(from: birthdayString)
    let currentDate = Date()
    let calendar: Calendar = Calendar(identifier: .gregorian)
    let age = calendar.component(.year, from: birthdate!).distance(to: calendar.component(.year, from: currentDate))
    return age
}
</code>```

Title: Convert facebook birthday to age swift

Body:
Swift 4

My use case is also for Facebook and I have used UserDefaults to store the birthdate. The below function will retrieve birthdate from UserDefaults, as returned by the graphRequest which is in the same format as your Date. The function will return an Integer with the user's age.

    func getAgeFromBirthdate() -> Int {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/dd/yyyy"
    let birthday = UserDefaults.standard.object(forKey: "birthday")
    let birthdayString = birthday as! String
    let birthdate = dateFormatter.date(from: birthdayString)
    let currentDate = Date()
    let calendar: Calendar = Calendar(identifier: .gregorian)
    let age = calendar.component(.year, from: birthdate!).distance(to: calendar.component(.year, from: currentDate))
    return age
}


问:
Need to show/hide a dropdown after checking/unchecking a checkbox in angular 4
I have a specific requirement in Angular4.
I need to display a dropdown after selecting/checking a checkbox and if I uncheck the checkbox then dropdown will hide.
Below is the code of the checkbox.

```<code>    <div *ngIf="item.showOperationField">
        <p-checkbox
            value ="inflationaryImpactCheck"
            label="Save for Inflationary Impact"
            name = "calculationSaveInflation"
            [(ngModel)]="item.inflationaryImpact"
            pTooltip="Check the Inflationary Impact box to map this calculation to an index for Inflationary Pressure calculation.">
        </p-checkbox>
    </div>
</code>```

After clicking/unclicking the checkbox

```<code>    <div *ngIf="item.showOperationField">
        <p-dropdown
            [style]="{'width':'200px'}"
            [options]="inflation"
            name = "calculationInflation"
            [(ngModel)]="item.selectedInflation">
        </p-dropdown>
    </div>
</code>```

Please help me and let me know how to do this

答:
I can see you're using PrimeNG.

Enable the binary option binary="true" in your p-checkbox tag.

From the doc :

A single boolean value can be bound using the ngModel property as well by enabling the binary option.

Then you just have to display your p-dropdown if item.inflationaryImpact is true :

```<code><div *ngIf="item.showOperationField">
  <p-checkbox binary="true" value="inflationaryImpactCheck" label="Save for Inflationary Impact" name="calculationSaveInflation" [(ngModel)]="item.inflationaryImpact" pTooltip="Check the Inflationary Impact box to map this calculation to an index for Inflationary Pressure calculation.">
  </p-checkbox>
</div>

<p-dropdown *ngIf="item.inflationaryImpact" [options]="cities" [(ngModel)]="selectedCity"></p-dropdown>
</code>```

If item.inflationaryImpact is false, then the dropdown won't be displayed.

Demo

Body:
I have a specific requirement in Angular4.
I need to display a dropdown after selecting/checking a checkbox and if I uncheck the checkbox then dropdown will hide.
Below is the code of the checkbox.

After clicking/unclicking the checkbox

Please help me and let me know how to do this

Body:
I can see you're using PrimeNG.

Enable the binary option binary="true" in your p-checkbox tag.

From the doc :

A single boolean value can be bound using the ngModel property as well by enabling the binary option.

Then you just have to display your p-dropdown if item.inflationaryImpact is true :

<div *ngIf="item.showOperationField">
  <p-checkbox binary="true" value="inflationaryImpactCheck" label="Save for Inflationary Impact" name="calculationSaveInflation" [(ngModel)]="item.inflationaryImpact" pTooltip="Check the Inflationary Impact box to map this calculation to an index for Inflationary Pressure calculation.">
  </p-checkbox>
</div>

<p-dropdown *ngIf="item.inflationaryImpact" [options]="cities" [(ngModel)]="selectedCity"></p-dropdown>

If item.inflationaryImpact is false, then the dropdown won't be displayed.

Demo


问:
PHP line break inside of cell remove qoute
This is my PHP

```<code>$val = "";
foreach($data as $v){
  $val .= '"' . $v . "\n" . '"';
}
</code>```

The result is

```<code>//this is inside of cell
sample
"sample
"sample
</code>```

This is correct but I cant figure out how to remove the double quote in "sample. Only the first value dont have a double quote the rest will have a double quote.

EDIT

This is the result of my code

This is what I want

答:
```<code> $val .= '"' . $v . "</br>" . '"';
$val=str_replace('"','',$val);
</code>```

I think this is what you are looking for inside  your loop. It will remove every double quote.

Body:
This is my PHP

$val = "";
foreach($data as $v){
  $val .= '"' . $v . "\n" . '"';
}

The result is

//this is inside of cell
sample
"sample
"sample

This is correct but I cant figure out how to remove the double quote in "sample. Only the first value dont have a double quote the rest will have a double quote.

EDIT

This is the result of my code

This is what I want

Body:
 $val .= '"' . $v . "</br>" . '"';
$val=str_replace('"','',$val);

I think this is what you are looking for inside  your loop. It will remove every double quote.


问:
Retrieve specific lines from text file and use them to make a dictionary
I want to create a dictionary using certain lines in a textfile. Here an examples from my textfile (each 'page' is separated by '//'):

```<code>//
UNIQUE-ID - INDOLE-3-ACETYL-BETA-4-D-GLUCOSE
TYPES - Compounds
COMMON-NAME - 4-<i>O</i>-(indol-3-ylacetyl)-β-D-glucose
DBLINKS - (HMDB "HMDB12213" NIL |kothari| 3594494404 NIL NIL)
INCHI - InChI=1S/C16H19NO7/c18-7-11-15(13(20)14(21)16(22)23-11)24-12(19)5-8-6-17-10-4-2-1-3-9(8)10/h1-4,6,11,13-18,20-22H,5,7H2/t11-,13-,14-,15-,16-/m1/s1
SMILES - C(C3(C(OC(=O)CC1(=CNC2(C=CC=CC1=2)))C(O)C(O)C(O)O3))O
SYNONYMS - indole-3-acetyl-β-4-D-glucose
//
UNIQUE-ID - CPD-6783
TYPES - Myo-inositol-bisphosphates
COMMON-NAME - D-<i>myo</i>-inositol (2,4) bisphosphate
DBLINKS - (HMDB "HMDB03905" NIL |kothari| 3608597114 NIL NIL)
DBLINKS - (PUBCHEM "25245743" NIL |taltman| 3466375284 NIL NIL)
INCHI - InChI=1S/C6H14O12P2/c7-1-2(8)5(17-19(11,12)13)4(10)6(3(1)9)18-20(14,15)16/h1-10H,(H2,11,12,13)(H2,14,15,16)/p-4/t1-,2-,3+,4-,5-,6-/m0/s1
//
</code>```

The dictionary should have the line starting with 'INCHI - InChI=' as a key and the line containg 'DBLINKS - (HMDB' as the value. And here is my code:

```<code>data = open('compounds.dat', 'r', errors = 'ignore')
compounds = data.readlines()

INCHI_list = []
HMDB_list = []
dict_Inchi_HMDB = dict()

for i,line in enumerate(compounds):
    if 'INCHI - InChI=' in line:
        INCHI_list.append(line)

    if 'DBLINKS - (HMDB' in line:
        HMDB_list.append(line)
dict_Inchi_HMDB[INCHI_list] = HMDB_list
</code>```

Which gives me the error unhashable type: 'list'. I understand why I get the error but I wasnt able to come up with a better approach... Could somebody help?

Note that: 'DBLINKS - (HMDB' always comes before 'INCHI - InChI=' but the number of lines in between might vary. Also, the datafile contains several hundreds of these examples. And  the line 'DBLINKS - (HMDB' is not present in each 'page'

答:
```<code>result = {}
with open('compounds.dat', errors = 'ignore') as my_file:  # Using with open one does not need to run my_file.close() after, that is taken care of for you.
    for page in my_file.read().split('//'):  # Since each page is delimited by // lets split on that and create a list of pages.
        for line in reversed(page.split('\n')):  # Split on every newline and reverse the list so the INCHI line comes up first, we'll use it as the key.
            k, v = line.split(' - ') # if line is e.g. UNIQUE-ID - CPD-6783, this creates k = 'UNIQUE-ID', v = 'CPD-6783'
            if 'INCHI - ' in line:  # We found our key line.
                curr_k = v  # Let's remember the key so that when we hit the  DBLINKS - (HMDB line, we can assign the value to the correct key.
            elif 'DBLINKS - (HMDB' in line: # We found our value line
                result[curr_k] = v  # We found the value and we remember what key to assign it to (curr_k)
</code>```

Body:
I want to create a dictionary using certain lines in a textfile. Here an examples from my textfile (each 'page' is separated by '//'):

//
UNIQUE-ID - INDOLE-3-ACETYL-BETA-4-D-GLUCOSE
TYPES - Compounds
COMMON-NAME - 4-O-(indol-3-ylacetyl)-β-D-glucose
DBLINKS - (HMDB "HMDB12213" NIL |kothari| 3594494404 NIL NIL)
INCHI - InChI=1S/C16H19NO7/c18-7-11-15(13(20)14(21)16(22)23-11)24-12(19)5-8-6-17-10-4-2-1-3-9(8)10/h1-4,6,11,13-18,20-22H,5,7H2/t11-,13-,14-,15-,16-/m1/s1
SMILES - C(C3(C(OC(=O)CC1(=CNC2(C=CC=CC1=2)))C(O)C(O)C(O)O3))O
SYNONYMS - indole-3-acetyl-β-4-D-glucose
//
UNIQUE-ID - CPD-6783
TYPES - Myo-inositol-bisphosphates
COMMON-NAME - D-myo-inositol (2,4) bisphosphate
DBLINKS - (HMDB "HMDB03905" NIL |kothari| 3608597114 NIL NIL)
DBLINKS - (PUBCHEM "25245743" NIL |taltman| 3466375284 NIL NIL)
INCHI - InChI=1S/C6H14O12P2/c7-1-2(8)5(17-19(11,12)13)4(10)6(3(1)9)18-20(14,15)16/h1-10H,(H2,11,12,13)(H2,14,15,16)/p-4/t1-,2-,3+,4-,5-,6-/m0/s1
//

The dictionary should have the line starting with 'INCHI - InChI=' as a key and the line containg 'DBLINKS - (HMDB' as the value. And here is my code:

data = open('compounds.dat', 'r', errors = 'ignore')
compounds = data.readlines()

INCHI_list = []
HMDB_list = []
dict_Inchi_HMDB = dict()

for i,line in enumerate(compounds):
    if 'INCHI - InChI=' in line:
        INCHI_list.append(line)

    if 'DBLINKS - (HMDB' in line:
        HMDB_list.append(line)
dict_Inchi_HMDB[INCHI_list] = HMDB_list

Which gives me the error unhashable type: 'list'. I understand why I get the error but I wasnt able to come up with a better approach... Could somebody help?

Note that: 'DBLINKS - (HMDB' always comes before 'INCHI - InChI=' but the number of lines in between might vary. Also, the datafile contains several hundreds of these examples. And  the line 'DBLINKS - (HMDB' is not present in each 'page'


问:
Dynamically Linking GLEW with CMake
I've looked over Stack Overflow and Google to try to figure this out, but everything I've seen regarding a dynamic linking either doesn't work or they end up static linking.

```<code>E:/CLion/GLEW-Test/main.cpp:8: undefined reference to `_imp__glewInit@0'
E:/CLion/GLEW-Test/main.cpp:12: undefined reference to `_imp__glewGetErrorString@4'
E:/CLion/GLEW-Test/main.cpp:14: undefined reference to `_imp__glewGetString@4'
</code>```

I am trying to dynamically link GLEW using CLion. The problem is, I've grown up with Visual Studio so I've never really had to think much about it. I'm trying to teach myself CMake and OpenGL, so this would have been a perfect exercise.

I downloaded the source for GLEW and built it with CMake and MinGW. I placed the resulting glew32.dll in C:/Windows/System32/, and I placed the libglew32.a in C:/MinGW/lib, and I placed glew.h, glxew.h, and wglew.h into C:/MinGW/include/GL.

Currently, I also have the libraries glew32.dll, libglu32.a, and libopengl32.a in my build directory.

Here is my CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.8)
project(GLEW_Test)

set(CMAKE_CXX_STANDARD 11)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra")
set( CMAKE_VERBOSE_MAKEFILE on )

set(SOURCE_FILES main.cpp)
add_executable(GLEW_Test ${SOURCE_FILES})
target_link_libraries(GLEW_Test glew32 glu32 opengl32)
</code>```

and this is my main.cpp:

```<code>#include <iostream>
#include <GL/glew.h>

int main()
{
    std::cout << "Hello, World!" << std::endl;

    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

    return 0;
}
</code>```

Now, if I #define GLEW_STATIC before I #include <GL/glew.h>, the program compiles and outputs the expected output (An error for having no GLContext).    However, to my knowledge, that is static linking, and I want to dynamically link GLEW.  This is what I see when I compile without #define GLEW_STATIC:

```<code>"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" --build E:\CLion\GLEW-Test\cmake-build-debug --target GLEW_Test -- -j 2
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -HE:\CLion\GLEW-Test -BE:\CLion\GLEW-Test\cmake-build-debug --check-build-system CMakeFiles\Makefile.cmake 0
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\Makefile2 GLEW_Test
mingw32-make.exe[1]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -HE:\CLion\GLEW-Test -BE:\CLion\GLEW-Test\cmake-build-debug --check-build-system CMakeFiles\Makefile.cmake 0
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_progress_start E:\CLion\GLEW-Test\cmake-build-debug\CMakeFiles 2
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\Makefile2 CMakeFiles/GLEW_Test.dir/all
mingw32-make.exe[2]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\GLEW_Test.dir\build.make CMakeFiles/GLEW_Test.dir/depend
mingw32-make.exe[3]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_depends "MinGW Makefiles" E:\CLion\GLEW-Test E:\CLion\GLEW-Test E:\CLion\GLEW-Test\cmake-build-debug E:\CLion\GLEW-Test\cmake-build-debug E:\CLion\GLEW-Test\cmake-build-debug\CMakeFiles\GLEW_Test.dir\DependInfo.cmake --color=
mingw32-make.exe[3]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\GLEW_Test.dir\build.make CMakeFiles/GLEW_Test.dir/build
mingw32-make.exe[3]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
[ 50%] Linking CXX executable GLEW_Test.exe
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_link_script CMakeFiles\GLEW_Test.dir\link.txt --verbose=1
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E remove -f CMakeFiles\GLEW_Test.dir/objects.a
C:\MinGW\bin\ar.exe cr CMakeFiles\GLEW_Test.dir/objects.a @CMakeFiles\GLEW_Test.dir\objects1.rsp
C:\MinGW\bin\g++.exe  -Wall -Wextra -g   -Wl,--whole-archive CMakeFiles\GLEW_Test.dir/objects.a -Wl,--no-whole-archive  -o GLEW_Test.exe -Wl,--out-implib,libGLEW_Test.dll.a -Wl,--major-image-version,0,--minor-image-version,0 @CMakeFiles\GLEW_Test.dir\linklibs.rsp
CMakeFiles\GLEW_Test.dir/objects.a(main.cpp.obj): In function `main':
E:/CLion/GLEW-Test/main.cpp:8: undefined reference to `_imp__glewInit@0'
E:/CLion/GLEW-Test/main.cpp:12: undefined reference to `_imp__glewGetErrorString@4'
E:/CLion/GLEW-Test/main.cpp:14: undefined reference to `_imp__glewGetString@4'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [GLEW_Test.exe] Error 1
CMakeFiles\GLEW_Test.dir\build.make:98: recipe for target 'GLEW_Test.exe' failed
mingw32-make.exe[2]: *** [CMakeFiles/GLEW_Test.dir/all] Error 2
mingw32-make.exe[3]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
mingw32-make.exe[1]: *** [CMakeFiles/GLEW_Test.dir/rule] Error 2
CMakeFiles\Makefile2:69: recipe for target 'CMakeFiles/GLEW_Test.dir/all' failed
mingw32-make.exe[2]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
CMakeFiles\Makefile2:81: recipe for target 'CMakeFiles/GLEW_Test.dir/rule' failed
mingw32-make.exe[1]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
Makefile:120: recipe for target 'GLEW_Test' failed
mingw32-make.exe: *** [GLEW_Test] Error 2
</code>```

What am I doing wrong? I followed the guide at glew's sourceforge, and placed the .dll in my System32 folder. Since I built with CMake and MinGW, I have .a files instead of .lib files, and I stuck those in my MinGW/lib directory.
The only thing I didn't do (because I wasn't sure), was do nothing with my libglew32.dll.a
Is this the culprit? I'm not sure what to do with it, and googling for information on a .dll.a file turned up nothing.

答:
```<code>target_link_libraries(GLEW_Test libglew32.a libglu32.a libopengl32.a)
</code>```

You should never include "lib" prefix and the file extension of a library in your target_link_libraries. Instead you should do it like this

```<code>target_link_libraries(GLEW_Test glew32 glu32 opengl32)
</code>```

as cmake already will search for e.g. glew32.dll, libglew32.a by itself then. This way, you also stay platform/compiler independent.

For testing/bughunt purpose, I would recommend that you put the required libraries in the directory of your executable first and check if the error still occurs, since the windows linker searches the executable's directory first for libraries.

If it does not occur anymore but does when the libraries are located in the other locations, be sure that those locations are part of the PATH environmental variable.

Title: Dynamically Linking GLEW with CMake

Body:
I've looked over Stack Overflow and Google to try to figure this out, but everything I've seen regarding a dynamic linking either doesn't work or they end up static linking.

E:/CLion/GLEW-Test/main.cpp:8: undefined reference to `_imp__glewInit@0'
E:/CLion/GLEW-Test/main.cpp:12: undefined reference to `_imp__glewGetErrorString@4'
E:/CLion/GLEW-Test/main.cpp:14: undefined reference to `_imp__glewGetString@4'

I am trying to dynamically link GLEW using CLion. The problem is, I've grown up with Visual Studio so I've never really had to think much about it. I'm trying to teach myself CMake and OpenGL, so this would have been a perfect exercise.

I downloaded the source for GLEW and built it with CMake and MinGW. I placed the resulting glew32.dll in C:/Windows/System32/, and I placed the libglew32.a in C:/MinGW/lib, and I placed glew.h, glxew.h, and wglew.h into C:/MinGW/include/GL.

Currently, I also have the libraries glew32.dll, libglu32.a, and libopengl32.a in my build directory.

Here is my CMakeLists.txt:

cmake_minimum_required(VERSION 3.8)
project(GLEW_Test)

set(CMAKE_CXX_STANDARD 11)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra")
set( CMAKE_VERBOSE_MAKEFILE on )

set(SOURCE_FILES main.cpp)
add_executable(GLEW_Test ${SOURCE_FILES})
target_link_libraries(GLEW_Test glew32 glu32 opengl32)

and this is my main.cpp:

#include <iostream>
#include <GL/glew.h>

int main()
{
    std::cout << "Hello, World!" << std::endl;

    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

    return 0;
}

Now, if I #define GLEW_STATIC before I #include <GL/glew.h>, the program compiles and outputs the expected output (An error for having no GLContext).    However, to my knowledge, that is static linking, and I want to dynamically link GLEW.  This is what I see when I compile without #define GLEW_STATIC:

"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" --build E:\CLion\GLEW-Test\cmake-build-debug --target GLEW_Test -- -j 2
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -HE:\CLion\GLEW-Test -BE:\CLion\GLEW-Test\cmake-build-debug --check-build-system CMakeFiles\Makefile.cmake 0
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\Makefile2 GLEW_Test
mingw32-make.exe[1]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -HE:\CLion\GLEW-Test -BE:\CLion\GLEW-Test\cmake-build-debug --check-build-system CMakeFiles\Makefile.cmake 0
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_progress_start E:\CLion\GLEW-Test\cmake-build-debug\CMakeFiles 2
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\Makefile2 CMakeFiles/GLEW_Test.dir/all
mingw32-make.exe[2]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\GLEW_Test.dir\build.make CMakeFiles/GLEW_Test.dir/depend
mingw32-make.exe[3]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_depends "MinGW Makefiles" E:\CLion\GLEW-Test E:\CLion\GLEW-Test E:\CLion\GLEW-Test\cmake-build-debug E:\CLion\GLEW-Test\cmake-build-debug E:\CLion\GLEW-Test\cmake-build-debug\CMakeFiles\GLEW_Test.dir\DependInfo.cmake --color=
mingw32-make.exe[3]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\GLEW_Test.dir\build.make CMakeFiles/GLEW_Test.dir/build
mingw32-make.exe[3]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
[ 50%] Linking CXX executable GLEW_Test.exe
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_link_script CMakeFiles\GLEW_Test.dir\link.txt --verbose=1
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E remove -f CMakeFiles\GLEW_Test.dir/objects.a
C:\MinGW\bin\ar.exe cr CMakeFiles\GLEW_Test.dir/objects.a @CMakeFiles\GLEW_Test.dir\objects1.rsp
C:\MinGW\bin\g++.exe  -Wall -Wextra -g   -Wl,--whole-archive CMakeFiles\GLEW_Test.dir/objects.a -Wl,--no-whole-archive  -o GLEW_Test.exe -Wl,--out-implib,libGLEW_Test.dll.a -Wl,--major-image-version,0,--minor-image-version,0 @CMakeFiles\GLEW_Test.dir\linklibs.rsp
CMakeFiles\GLEW_Test.dir/objects.a(main.cpp.obj): In function `main':
E:/CLion/GLEW-Test/main.cpp:8: undefined reference to `_imp__glewInit@0'
E:/CLion/GLEW-Test/main.cpp:12: undefined reference to `_imp__glewGetErrorString@4'
E:/CLion/GLEW-Test/main.cpp:14: undefined reference to `_imp__glewGetString@4'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [GLEW_Test.exe] Error 1
CMakeFiles\GLEW_Test.dir\build.make:98: recipe for target 'GLEW_Test.exe' failed
mingw32-make.exe[2]: *** [CMakeFiles/GLEW_Test.dir/all] Error 2
mingw32-make.exe[3]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
mingw32-make.exe[1]: *** [CMakeFiles/GLEW_Test.dir/rule] Error 2
CMakeFiles\Makefile2:69: recipe for target 'CMakeFiles/GLEW_Test.dir/all' failed
mingw32-make.exe[2]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
CMakeFiles\Makefile2:81: recipe for target 'CMakeFiles/GLEW_Test.dir/rule' failed
mingw32-make.exe[1]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
Makefile:120: recipe for target 'GLEW_Test' failed
mingw32-make.exe: *** [GLEW_Test] Error 2

What am I doing wrong? I followed the guide at glew's sourceforge, and placed the .dll in my System32 folder. Since I built with CMake and MinGW, I have .a files instead of .lib files, and I stuck those in my MinGW/lib directory.
The only thing I didn't do (because I wasn't sure), was do nothing with my libglew32.dll.a
Is this the culprit? I'm not sure what to do with it, and googling for information on a .dll.a file turned up nothing.

Body:
target_link_libraries(GLEW_Test libglew32.a libglu32.a libopengl32.a)

You should never include "lib" prefix and the file extension of a library in your target_link_libraries. Instead you should do it like this

target_link_libraries(GLEW_Test glew32 glu32 opengl32)

as cmake already will search for e.g. glew32.dll, libglew32.a by itself then. This way, you also stay platform/compiler independent.

For testing/bughunt purpose, I would recommend that you put the required libraries in the directory of your executable first and check if the error still occurs, since the windows linker searches the executable's directory first for libraries.

If it does not occur anymore but does when the libraries are located in the other locations, be sure that those locations are part of the PATH environmental variable.


问:
How do I write 'this' less often?
Using ES6 classes is great and all, but I find myself using this.variable everywhere, and it is always referring to my class. Is there a way to have implied globals within my class be implied this.variable instead? So if I write 'width' it will be defaulted to this.width instead of an implied global?

Or if there are some best practices that I might not be aware of to cut down on my 'this' addiction I'd love to read that too. In the file I'm currently working on there are about half as many this keywords as there are lines of code...

答:
Using constructor functions / classes and this is just one way to use JavaScript. JavaScript is a multi-paradigm language and yes, it's entirely possible to use it largely without using this. One way is via closures.

Consider this class example:

class Person {
  constructor(first, last) {
    this.first = first;
    this.last = last;
    this.things = [];
  }
  sayHello() {
    console.log(`Hi, I'm ${this.first} ${this.last}`);
  }
  grabThing(thing) {
    this.things.push(thing);
  }
}
const p1 = new Person("Joe", "Bloggs");
p1.sayHello();
p1.grabThing("thing1");
console.log(p1.first + "'s things: " + p1.things.join(", "));
const p2 = new Person("Suresh", "Kumar");
p2.sayHello();
p2.grabThing("thing2");
p2.grabThing("thing3");
console.log(p2.first + "'s things: " + p2.things.join(", "));```
</div>
</div>
</p>

<p>Now, consider this approach with closures:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function createPerson(first, last) {
  const things = [];
  return {
    sayHello() {
      console.log(`Hi, I'm ${first} ${last}`);
    },
    grabThing(thing) {
      things.push(thing);
    },
    get things() {
      return things;
    },
    get first() {
      return first;
    },
    get last() {
      return last;
    }
  };
}
const p1 = createPerson("Joe", "Bloggs");
p1.sayHello();
p1.grabThing("thing1");
console.log(p1.first + "'s things: " + p1.things.join(", "));
const p2 = createPerson("Suresh", "Kumar");
p2.sayHello();
p2.grabThing("thing2");
p2.grabThing("thing3");
console.log(p2.first + "'s things: " + p2.things.join(", "));</code>```

Notice how we just use the first and last parameters provided to the createPerson function directly in sayHello, and we just declare things as a local constant which grabThing closes over. In that example, we also provide getters for the various bits of information (first, last, things) so they can be used from the object we return, but if there were information we wanted to keep private, we could leave out the getter. (And some prefer to make those explicitly functions rather than getters.)

One downside to this approach is that there are separate function objects for sayHello, grabThing, the getters, etc., for each object created by createPerson, while in the class example, there's only one sayHello function object, which is shared amongst Person objects via prototypical inheritance. On the one hand, creating additional sayHello function objects seems wasteful; but modern JavaScript engines reuse the underlying function code even though there are distinct sayHello objects, and objects are fairly cheap in our modern world.

Upsides are the easy way to have private information and not having to use and manage this.

Douglas Crockford (amongst others) promotes this approach, if you want to learn more about it. (Note that in his writing, Crockford sometimes fails to clearly distinguish between fact and his opinion — and boy does he have opinions — but his writing is well worth reading regardless.)

(I'm not advocating either class or non-class, just noting there are options.)

Title: How do I write 'this' less often?

Body:
Using constructor functions / classes and this is just one way to use JavaScript. JavaScript is a multi-paradigm language and yes, it's entirely possible to use it largely without using this. One way is via closures.

Consider this class example:

class Person {
  constructor(first, last) {
    this.first = first;
    this.last = last;
    this.things = [];
  }
  sayHello() {
    console.log(`Hi, I'm ${this.first} ${this.last}`);
  }
  grabThing(thing) {
    this.things.push(thing);
  }
}
const p1 = new Person("Joe", "Bloggs");
p1.sayHello();
p1.grabThing("thing1");
console.log(p1.first + "'s things: " + p1.things.join(", "));
const p2 = new Person("Suresh", "Kumar");
p2.sayHello();
p2.grabThing("thing2");
p2.grabThing("thing3");
console.log(p2.first + "'s things: " + p2.things.join(", "));

Now, consider this approach with closures:

function createPerson(first, last) {
  const things = [];
  return {
    sayHello() {
      console.log(`Hi, I'm ${first} ${last}`);
    },
    grabThing(thing) {
      things.push(thing);
    },
    get things() {
      return things;
    },
    get first() {
      return first;
    },
    get last() {
      return last;
    }
  };
}
const p1 = createPerson("Joe", "Bloggs");
p1.sayHello();
p1.grabThing("thing1");
console.log(p1.first + "'s things: " + p1.things.join(", "));
const p2 = createPerson("Suresh", "Kumar");
p2.sayHello();
p2.grabThing("thing2");
p2.grabThing("thing3");
console.log(p2.first + "'s things: " + p2.things.join(", "));

Notice how we just use the first and last parameters provided to the createPerson function directly in sayHello, and we just declare things as a local constant which grabThing closes over. In that example, we also provide getters for the various bits of information (first, last, things) so they can be used from the object we return, but if there were information we wanted to keep private, we could leave out the getter. (And some prefer to make those explicitly functions rather than getters.)

One downside to this approach is that there are separate function objects for sayHello, grabThing, the getters, etc., for each object created by createPerson, while in the class example, there's only one sayHello function object, which is shared amongst Person objects via prototypical inheritance. On the one hand, creating additional sayHello function objects seems wasteful; but modern JavaScript engines reuse the underlying function code even though there are distinct sayHello objects, and objects are fairly cheap in our modern world.

Upsides are the easy way to have private information and not having to use and manage this.

Douglas Crockford (amongst others) promotes this approach, if you want to learn more about it. (Note that in his writing, Crockford sometimes fails to clearly distinguish between fact and his opinion — and boy does he have opinions — but his writing is well worth reading regardless.)

(I'm not advocating either class or non-class, just noting there are options.)


问:
UITextField placeholder text: adjust to fit
I have UITextField with longer text in it set as placeholder. What I want is for this placeholder text to adjust its font size when the width of field is too small.

I already tried this solution described in other posts (programmatically and in IB)

```<code>self.fieldTest.adjustsFontSizeToFitWidth = true
self.fieldTest.minimumFontSize = 10.0
</code>```

What am I missing here?

答:
The whole approach or shrinking font size to fit is misguided in the day and age of accessibility.

Firstly you have zero business specifying text size in the first place, let alone shrinking that further: you have to rely on the accessibility API.

Thus if the placeholder is likely to not fit it has to be placed
as a UILabel preceding the UITextField. The placeholders are supposed to be SHORT and fit without clippage.

To determine if it's clipped I guess you could use - (CGRect)placeholderRectForBounds:(CGRect)bounds; but then you are in
murky waters of using an API which Apple says you should only override (but not call yourself even though it's probably meaningful and safe
within the confines of didlayoutsubviews method[s])

If placeholder text is dynamic (server served) dump it into a UILabel.

Body:
I have UITextField with longer text in it set as placeholder. What I want is for this placeholder text to adjust its font size when the width of field is too small.

I already tried this solution described in other posts (programmatically and in IB)

self.fieldTest.adjustsFontSizeToFitWidth = true
self.fieldTest.minimumFontSize = 10.0

What am I missing here?


问:
Why cant I ping a virtual guest from host by default
I ran into some trouble when I tried to ping my Ubuntu virtual guest from my Windows 10 host, but this solution  did the trick.

I'm wondering what exactly is a "host-only-adapter" and why cant the I ping the virtual machine by default? How exactly does the virtual machine access the internet when I cant ping it?

答:
As the name suggests, host-only is intended to create a new interface that is virtual and visible to the host and not in anyway connected to the physical interface that actually connects to the internet.

Itcan be thought of as a hybrid between the bridged and internal networking modes: as with bridged networking, the virtual machines can talk to each other and the host as if they were connected through a physical Ethernet switch. Similarly, as with internal networking however, a physical networking interface need not be present, and the virtual machines cannot talk to the world outside the host since they are not connected to a physical networking interface.

You might be wondering what the use-case for this would be.Think for example: one virtual machine may contain a web server and a second one a database, and since they are intended to talk to each other, the appliance can instruct VirtualBox to set up a host-only network for the two. A second (bridged) network would then connect the web server to the outside world to serve data to, but the outside world cannot connect to the database.

How it works

when host-only networking is used, VirtualBox creates a new software interface on the host which then appears next to your existing network interfaces. In other words, whereas with bridged networking an existing physical interface is used to attach virtual machines to, with host-only networking a new "loopback" interface is created on the host. And whereas with internal networking, the traffic between the virtual machines cannot be seen, the traffic on the "loopback" interface on the host can be intercepted.

The great thing about host-only networks is that the host itself sits on this network and so, upon proper config as in you link above, you can reach all the VMs.

Hope my explanation helps!


答:
You can use colRanks from matrixstats package, i.e.

```<code>library(matrixStats)

t(colRanks(df))
</code>```

which gives,

```<code>      [,1] [,2] [,3] [,4]
[1,]    1    2    2    2
[2,]    3    1    4    3
[3,]    4    4    1    4
[4,]    2    3    3    1
</code>```

Title: Order a space matrix by index

Body:
I have matrix space some locations 1, 2, 3, and 4

df<-matrix(data=c(0.00, 4.69, 12.63, 2.99, 4.69, 0.00, 17.30, 5.15, 12.63, 17.30, 0.00, 13.72, 2.99, 5.15, 13.72, 0.00), ncol=4)
colnames(df)<-c(seq(1:4))
rownames(df)<-c(seq(1:4))
df

#    1     2     3     4
#1  0.00  4.69 12.63  2.99
#2  4.69  0.00 17.30  5.15
#3 12.63 17.30  0.00 13.72
#4  2.99  5.15 13.72  0.00

and I would like to order this matrix in descending order by rank of each space row, so get

#       1     2     3     4
#1      1     2     2     2
#2      3     1     4     3
#3      4     4     1     4
#4      2     3     3     1

Any suggestions on how I could achieve this? Thanks.

Body:
You can use colRanks from matrixstats package, i.e.

library(matrixStats)

t(colRanks(df))

which gives,

      [,1] [,2] [,3] [,4]
[1,]    1    2    2    2
[2,]    3    1    4    3
[3,]    4    4    1    4
[4,]    2    3    3    1


问:
MessageBodyWriter not found for media type=application/xml
I want to make a REST API Response in two formats depending on the HttpHeaders of the request :

```<code>@Context
HttpHeaders headers;

public Response toResponse(MyValidationException exception) {
   if(headers.getMediaType().toString().equals(MediaType.APPLICATION_XML)){
     return Response.status(Status.BAD_REQUEST).entity(exception.getErrors()).type(MediaType.APPLICATION_XML).build();
  }else{
     return Response.status(Status.BAD_REQUEST).entity(exception.getErrors()).type(MediaType.APPLICATION_JSON).build();
}}
</code>```

It's working for the MediaType.APPLICATION_JSON, but for MediaType.APPLICATION_XML I get the following Error :

```<code>org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo MessageBodyWriter not found for media type=application/xml, type=class java.util.HashMap$EntrySet, genericType=class java.util.HashMap$EntrySet.
</code>```

Any Idea to solve this problem?

答:
Do you have the jaxb dependency in your project?

```<code><dependency>
  <groupId>org.glassfish.jersey.media</groupId>
  <artifactId>jersey-media-jaxb</artifactId>
  <version>x.x.x</version>
</dependency>
</code>```

If yes, perhaps you could try to wrap the exception.getErrors() (which appears to be a Map?) into a GenericEntity and giving that entity to the response:

```<code>GenericEntity<Map<?, ?>> entity = new GenericEntity..

return Response.status(Status.X).entity(entity).type(MediaType.APPLICATION_XML).build();
</code>```

Body:
I want to make a REST API Response in two formats depending on the HttpHeaders of the request :

@Context
HttpHeaders headers;

public Response toResponse(MyValidationException exception) {
   if(headers.getMediaType().toString().equals(MediaType.APPLICATION_XML)){
     return Response.status(Status.BAD_REQUEST).entity(exception.getErrors()).type(MediaType.APPLICATION_XML).build();
  }else{
     return Response.status(Status.BAD_REQUEST).entity(exception.getErrors()).type(MediaType.APPLICATION_JSON).build();
}}

It's working for the MediaType.APPLICATION_JSON, but for MediaType.APPLICATION_XML I get the following Error :

org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo MessageBodyWriter not found for media type=application/xml, type=class java.util.HashMap$EntrySet, genericType=class java.util.HashMap$EntrySet.

Any Idea to solve this problem?

Body:
Do you have the jaxb dependency in your project?

<dependency>
  <groupId>org.glassfish.jersey.media</groupId>
  <artifactId>jersey-media-jaxb</artifactId>
  <version>x.x.x</version>
</dependency>

If yes, perhaps you could try to wrap the exception.getErrors() (which appears to be a Map?) into a GenericEntity and giving that entity to the response:

GenericEntity<Map<?, ?>> entity = new GenericEntity..

return Response.status(Status.X).entity(entity).type(MediaType.APPLICATION_XML).build();


问:
mule code to add list in dataweave mule
I am trying to pull physical and mailing address from a JSON file. I am able to retrieve them separately but not able to merge them in the dataweave. The below dataweave code will provide physical address and mailing address list, but I want the one address list which contains both physical and mailing address.

Below is the dataweave code used:

```<code>    physicaladdress: payload01.attributes.PhysicalAddress map ((physicalAddress , indexOfPhysicalAddress) -> {
type: physicalAddress.value.AddressType.value ,
lineOne: physicalAddress.value.AddressLine1[0].value as :string ,
lineTwo: physicalAddress.value.AddressLine2[0].value as :string,
country: physicalAddress.value.Country[0].value as :string
}) when payload01.attributes.PhysicalAddress != null  otherwise null,
    mailingaddress: payload01.attributes.MailingAddress map ((mailingAddress , indexOfMailingAddress) -> {
type: mailingAddress.value.AddressType.value ,
lineOne: mailingAddress.value.AddressLine1[0].value as :string,
lineTwo: mailingAddress.value.AddressLine2[0].value as :string ,
country: mailingAddress.value.Country[0].value as :string
}) when payload01.attributes.MailingAddress != null otherwise null,
</code>```

Any help is greatly appreciated...

Current response using the dataweave code attached:

```<code>    "physicaladdress": [
  {
    "type": "Physical",
    "addressLine1": "1166 Quail Ct310",
    "cityName": "Pewaukee",
    "country": "United States"
  },
  {
    "type": "Physical",
    "addressLine1": "1166 Quail Ct Ste 310-310 Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  }
],
"mailingaddress": [
  {
    "type": "Mailing",
    "lineOne": "1166 Quail Ct Ste 310-310 Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  },
  {
    "type": "Mailing",
    "lineOne": "1166 Quail Ct Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  }
]
</code>```

Expected response:

```<code>    "address": [
  {
    "type": "Physical",
    "addressLine1": "1166 Quail Ct Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  },
  {
    "type": "Physical",
    "addressLine1": "1166 Quail Ct Ste 310-310 Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  },
{
    "type": "Mailing",
    "lineOne": "1166 Quail Ct Ste 310-310 Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  },
  {
    "type": "Mailing",
    "lineOne": "1166 Quail Ct Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  }
]
</code>```

If i change the dataweave code to the one below, I will get only mailing address, think mailing address is overriding the physical address:

```<code>    address: payload01.attributes.PhysicalAddress map ((physicalAddress , indexOfPhysicalAddress) -> {
type: physicalAddress.value.AddressType.value ,
lineOne: physicalAddress.value.AddressLine1[0].value as :string ,
lineTwo: physicalAddress.value.AddressLine2[0].value as :string,
country: physicalAddress.value.Country[0].value as :string
}) when payload01.attributes.PhysicalAddress != null  otherwise null,
    address: payload01.attributes.MailingAddress map ((mailingAddress , indexOfMailingAddress) -> {
type: mailingAddress.value.AddressType.value ,
lineOne: mailingAddress.value.AddressLine1[0].value as :string,
lineTwo: mailingAddress.value.AddressLine2[0].value as :string ,
country: mailingAddress.value.Country[0].value as :string
}) when payload01.attributes.MailingAddress != null otherwise null,
</code>```

I am looking for address having both the list (physical and mailing) example attached, for reference.

答:
input:

```<code>{
    "Address": {
      "PhysicalAddress": {
        "Type": "01",
        "AddressLine1": " PhysicalAddress Address Line1(P)",
        "AddressLine2": " PhysicalAddress Address Line2 (P)",
        "Country": "INDIA"
      },
      "MailingAddress": {
        "Type": "04",
        "AddressLine1": "MailingAddress Address Line1(M)",
        "AddressLine2": "MailingAddress Address Line2(M)",
        "Country": "INDIA"
      }
    }
  }
</code>```

Dataweave

```<code>%dw 1.0
%output application/json
---

{Address : "MailingAddress": payload.Address.MailingAddress.AddressLine1
+"PhysicalAddress":payload.Address.PhysicalAddress.AddressLine1,
Address2 : "MailingAddress": payload.Address.MailingAddress.AddressLine2
+"PhysicalAddress":payload.Address.PhysicalAddress.AddressLine2}
</code>```

output

```<code>{"Address": {
"MailingAddress": [
  "MailingAddress Address Line1(M)",
  " PhysicalAddress Address Line1(P)"
]  "Address2": {
"MailingAddress": [
  "MailingAddress Address Line2(M)",
  " PhysicalAddress Address Line2 (P)"
]}}}
</code>```

Title: mule code to add list in dataweave mule

Body:
I am trying to pull physical and mailing address from a JSON file. I am able to retrieve them separately but not able to merge them in the dataweave. The below dataweave code will provide physical address and mailing address list, but I want the one address list which contains both physical and mailing address.

Below is the dataweave code used:

    physicaladdress: payload01.attributes.PhysicalAddress map ((physicalAddress , indexOfPhysicalAddress) -> {
type: physicalAddress.value.AddressType.value ,
lineOne: physicalAddress.value.AddressLine1[0].value as :string ,
lineTwo: physicalAddress.value.AddressLine2[0].value as :string,
country: physicalAddress.value.Country[0].value as :string
}) when payload01.attributes.PhysicalAddress != null  otherwise null,
    mailingaddress: payload01.attributes.MailingAddress map ((mailingAddress , indexOfMailingAddress) -> {
type: mailingAddress.value.AddressType.value ,
lineOne: mailingAddress.value.AddressLine1[0].value as :string,
lineTwo: mailingAddress.value.AddressLine2[0].value as :string ,
country: mailingAddress.value.Country[0].value as :string
}) when payload01.attributes.MailingAddress != null otherwise null,

Any help is greatly appreciated...

Current response using the dataweave code attached:

    "physicaladdress": [
  {
    "type": "Physical",
    "addressLine1": "1166 Quail Ct310",
    "cityName": "Pewaukee",
    "country": "United States"
  },
  {
    "type": "Physical",
    "addressLine1": "1166 Quail Ct Ste 310-310 Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  }
],
"mailingaddress": [
  {
    "type": "Mailing",
    "lineOne": "1166 Quail Ct Ste 310-310 Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  },
  {
    "type": "Mailing",
    "lineOne": "1166 Quail Ct Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  }
]

Expected response:

    "address": [
  {
    "type": "Physical",
    "addressLine1": "1166 Quail Ct Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  },
  {
    "type": "Physical",
    "addressLine1": "1166 Quail Ct Ste 310-310 Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  },
{
    "type": "Mailing",
    "lineOne": "1166 Quail Ct Ste 310-310 Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  },
  {
    "type": "Mailing",
    "lineOne": "1166 Quail Ct Ste 310",
    "cityName": "Pewaukee",
    "country": "United States"
  }
]

If i change the dataweave code to the one below, I will get only mailing address, think mailing address is overriding the physical address:

    address: payload01.attributes.PhysicalAddress map ((physicalAddress , indexOfPhysicalAddress) -> {
type: physicalAddress.value.AddressType.value ,
lineOne: physicalAddress.value.AddressLine1[0].value as :string ,
lineTwo: physicalAddress.value.AddressLine2[0].value as :string,
country: physicalAddress.value.Country[0].value as :string
}) when payload01.attributes.PhysicalAddress != null  otherwise null,
    address: payload01.attributes.MailingAddress map ((mailingAddress , indexOfMailingAddress) -> {
type: mailingAddress.value.AddressType.value ,
lineOne: mailingAddress.value.AddressLine1[0].value as :string,
lineTwo: mailingAddress.value.AddressLine2[0].value as :string ,
country: mailingAddress.value.Country[0].value as :string
}) when payload01.attributes.MailingAddress != null otherwise null,

I am looking for address having both the list (physical and mailing) example attached, for reference.

Body:
input:

{
    "Address": {
      "PhysicalAddress": {
        "Type": "01",
        "AddressLine1": " PhysicalAddress Address Line1(P)",
        "AddressLine2": " PhysicalAddress Address Line2 (P)",
        "Country": "INDIA"
      },
      "MailingAddress": {
        "Type": "04",
        "AddressLine1": "MailingAddress Address Line1(M)",
        "AddressLine2": "MailingAddress Address Line2(M)",
        "Country": "INDIA"
      }
    }
  }

Dataweave

%dw 1.0
%output application/json
---

{Address : "MailingAddress": payload.Address.MailingAddress.AddressLine1
+"PhysicalAddress":payload.Address.PhysicalAddress.AddressLine1,
Address2 : "MailingAddress": payload.Address.MailingAddress.AddressLine2
+"PhysicalAddress":payload.Address.PhysicalAddress.AddressLine2}

output

{"Address": {
"MailingAddress": [
  "MailingAddress Address Line1(M)",
  " PhysicalAddress Address Line1(P)"
]  "Address2": {
"MailingAddress": [
  "MailingAddress Address Line2(M)",
  " PhysicalAddress Address Line2 (P)"
]}}}


问:
Redis SCARD result does not match size of the set returned by SMEMBERS
According to Redis documentation, SMEMBERS returns the whole set by some key. While another command - SCARD - returns cardinality (size) of the set.

In my case SMEMBERS returns set of 22899 elements for some key, while SCARD returns just '2' for the same key. How can I explain this fact?

Redis version is 2.8.24

I'm running redis commands with redis-cli:

```<code>127.0.0.1:6379> scard myfancykey
(integer) 2
127.0.0.1:6379> myfancykey
....(22898 results go here)
22899) "my-fancy-value-63899173647738-foo[bar-baz:12343123]"
</code>```

答: Looks like I shot myself in the foot. Redis works normally, at the end.</p>

Body:
According to Redis documentation, SMEMBERS returns the whole set by some key. While another command - SCARD - returns cardinality (size) of the set.

In my case SMEMBERS returns set of 22899 elements for some key, while SCARD returns just '2' for the same key. How can I explain this fact?

Redis version is 2.8.24

I'm running redis commands with redis-cli:

127.0.0.1:6379> scard myfancykey
(integer) 2
127.0.0.1:6379> myfancykey
....(22898 results go here)
22899) "my-fancy-value-63899173647738-foo[bar-baz:12343123]"


问:
Android API Response handling
I want to handle the json response from my API in my Android app, but i can't find a lot of tutorials on how to do this, does anyone have some tips?

Android code:

```<code>                    URL url = new URL("http://thelinktomyapi.com");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                    conn.setRequestProperty("Accept", "application/json");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);

                    Log.i("JSON", jsonObj.toString());
                    DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                    //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
                    os.writeBytes(jsonObj.toString());

                    os.flush();
                    os.close();

                    Log.i("STATUS", String.valueOf(conn.getResponseCode()));
                    Log.i("MSG", conn.getResponseMessage());

                    conn.disconnect();
</code>```

Reponse part of my flask code(very simple)

```<code>respdata = {
        'imgurl2': 'google.nl'
    }
    resp = jsonify(respdata)
    resp.status_code = 200
    return resp
</code>```

答:
Try this I Think This Will Help

```<code>                URL url = new URL("http://thelinktomyapi.com");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                conn.setRequestProperty("Accept", "application/json");
                conn.setDoOutput(true);
                conn.setDoInput(true);

                Log.i("JSON", jsonObj.toString());
                DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
                os.writeBytes(jsonObj.toString());

                os.flush();
                os.close();

                Log.i("STATUS", String.valueOf(conn.getResponseCode()));
                Log.i("MSG", conn.getResponseMessage());

               DataInputStream inputStream = new DataInputStream(conn.getInputStream());
               BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
               StringBuilder result = new StringBuilder();
               String line = "";
               while((line = reader.readLine()) != null) {
                     result.append(line);
               }

                conn.disconnect();
</code>```

Credits to https://stackoverflow.com/a/9856272/5726600

Title: Android API Response handling

Body:
I want to handle the json response from my API in my Android app, but i can't find a lot of tutorials on how to do this, does anyone have some tips?

Android code:

                    URL url = new URL("http://thelinktomyapi.com");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                    conn.setRequestProperty("Accept", "application/json");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);

                    Log.i("JSON", jsonObj.toString());
                    DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                    //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
                    os.writeBytes(jsonObj.toString());

                    os.flush();
                    os.close();

                    Log.i("STATUS", String.valueOf(conn.getResponseCode()));
                    Log.i("MSG", conn.getResponseMessage());

                    conn.disconnect();

Reponse part of my flask code(very simple)

respdata = {
        'imgurl2': 'google.nl'
    }
    resp = jsonify(respdata)
    resp.status_code = 200
    return resp

Body:
Try this I Think This Will Help

                URL url = new URL("http://thelinktomyapi.com");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                conn.setRequestProperty("Accept", "application/json");
                conn.setDoOutput(true);
                conn.setDoInput(true);

                Log.i("JSON", jsonObj.toString());
                DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
                os.writeBytes(jsonObj.toString());

                os.flush();
                os.close();

                Log.i("STATUS", String.valueOf(conn.getResponseCode()));
                Log.i("MSG", conn.getResponseMessage());

               DataInputStream inputStream = new DataInputStream(conn.getInputStream());
               BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
               StringBuilder result = new StringBuilder();
               String line = "";
               while((line = reader.readLine()) != null) {
                     result.append(line);
               }

                conn.disconnect();

Credits to https://stackoverflow.com/a/9856272/5726600


问:
Palindrome check in Javascript
I have the following:

```<code>function checkPalindrom(palindrom)
{

    for( var i = palindrom.length; i > 0; i-- )
    {
        if( palindrom[i] = palindrom.charAt(palindrom.length)-1 )
        {
            document.write('the word is palindrome.');
        }else{
            document.write('the word is not palindrome!');
        }
    }
}
checkPalindrom('wordthatwillbechecked');
</code>```

What is wrong with my code? I want to check if the word is a palindrome.

答:
```<code><script>
    function checkForPally() {
        var input = document.getElementById("inputTable").value;
        var input = input.replace(/\s/g, '');
        var arrayInput = input.split();
        var inputReversed = arrayInput.reverse();
        var stringInputReversed = inputReversed.join("");

        if (input == stringInputReversed) {
            check.value = "The word you enter is a palindrome"
        }
        if (input != stringInputReversed) {
            check.value = "The word you entered is not a palindrome"
        }
    }
</script>
</code>```

You first use the getElement tag to set the initial variable of the palindrome. Seeing as a palindrome can be multiple words you use the regex entry to remove the whitespaces. You then use the split function to convert the string into an array.

Next up, you use the reverse method to reverse the array when this is done you join the reversed array back into a string. Lastly, you just use a very basic if statement to check for equality, if the reversed value is equall to the initial variable you have yourself a palindrome.

ContentLicense: CC BY-SA 4.0

Title: Palindrome check in Javascript

Body:
I have the following:

function checkPalindrom(palindrom)
{

    for( var i = palindrom.length; i > 0; i-- )
    {
        if( palindrom[i] = palindrom.charAt(palindrom.length)-1 )
        {
            document.write('the word is palindrome.');
        }else{
            document.write('the word is not palindrome!');
        }
    }
}
checkPalindrom('wordthatwillbechecked');

What is wrong with my code? I want to check if the word is a palindrome.

Body:
<script>
    function checkForPally() {
        var input = document.getElementById("inputTable").value;
        var input = input.replace(/\s/g, '');
        var arrayInput = input.split();
        var inputReversed = arrayInput.reverse();
        var stringInputReversed = inputReversed.join("");

        if (input == stringInputReversed) {
            check.value = "The word you enter is a palindrome"
        }
        if (input != stringInputReversed) {
            check.value = "The word you entered is not a palindrome"
        }
    }
</script>

You first use the getElement tag to set the initial variable of the palindrome. Seeing as a palindrome can be multiple words you use the regex entry to remove the whitespaces. You then use the split function to convert the string into an array.

Next up, you use the reverse method to reverse the array when this is done you join the reversed array back into a string. Lastly, you just use a very basic if statement to check for equality, if the reversed value is equall to the initial variable you have yourself a palindrome.


问:
why "abc" + null results abcnull
why "abc" + null  results abcnull

```<code>String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

System.out.println(s3);
</code>```

Result: abcnull

答: i don't know java, but from the looks of it, it seems like you are type casting s2 as a String object which then turns null into "null".  Please correct me if i'm wrong.

Title: why "abc" + null results abcnull

Body:
why "abc" + null  results abcnull

String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

System.out.println(s3);

Result: abcnull


问:
PromiseKit go back one step
I have a series of UIViewControllers (popups) in my app that I use to gather information from the end user. I managed to chain them with promises like this:

```<code>firstly {
        return showFirstPopup()
    }
    .then { info1 -> Promise<Info2> in
        dismissFirstPopup()
        //Do sth with info1...
        return showSecondPopup()
    }
    .then { info2 -> Promise<Info3> in
        dismissSecondPopup()
        //Do sth with info2...
        return showThirdPopup()
    }
    .then { info3 -> Promise<Info4> in
        dismissThirdPopup()
        //Do sth with info3...
        return showForthPopup()
    }
    ...
    .catch { error in
        //Handle any error or cancellation...
     }
</code>```

If, for example, the user presses back in the third popup I need to go back to the previous "then" and not cancel the whole flow.

Basically I need to be able to go back one step, let the user edit the data, then continue the flow.

Is there a way to do this with PromiseKit?

答:
This is what I ended up using. Hope this helps someone else out there as well.</p>

```<code>func myFunc(info: Info) -> Promise<()>
{
    return Promise { fulfill, reject in

        let firstPromise = shouldShowFirstPopup ? showFirstPopup() : Promise(value: info.info1)

        firstPromise
        .then { info1 -> Promise<Info2> in
            info.info1 = info1

            if (info.shouldShowSecondPopup) {
                return showSecondPopup()
            }

            return Promise(value: info.info2)
        }
        .then { info2 -> Promise<Info3> in
            info.info2 = info2
            info.shouldShowSecondPopup = false

            if (info.shouldShowThirdPopup) {
                return showThirdPopup()
            }

            return Promise(value: info.info3)
        }
        .then { info3 -> Promise<()> in
            info.info3 = info3
            info.shouldShowThirdPopup = false

            return processEverything()
        }
        .then { _ -> () in
            fulfill(())
        }
        .catch { error in
            switch error {
                case MyErrors.backPressed(let popupType):
                    switch popupType {
                        case .firstPopup:
                        reject(MyErrors.userCanceled)
                        return

                        case .secondPopup:
                        info.shouldShowFirstPopup = true
                        info.shouldShowSecondPopup = true

                        case .thirdPopup:
                        info.shouldShowSecondPopup = true
                        info.shouldShowThirdPopup = true

                        default:
                        reject(MyErrors.defaultError(message: "Not implemented case exception"))
                        return
                    }

                    firstly {
                        return myFunc(info: info)
                    }
                    .then { _ -> () in
                        fulfill(())
                    }
                    .catch { error2 in
                        reject(error2)
                    }

                default:
                reject(error)
            }
        }
    }
}
</code>```

Title: PromiseKit go back one step

Body:
I have a series of UIViewControllers (popups) in my app that I use to gather information from the end user. I managed to chain them with promises like this:

firstly {
        return showFirstPopup()
    }
    .then { info1 -> Promise<Info2> in
        dismissFirstPopup()
        //Do sth with info1...
        return showSecondPopup()
    }
    .then { info2 -> Promise<Info3> in
        dismissSecondPopup()
        //Do sth with info2...
        return showThirdPopup()
    }
    .then { info3 -> Promise<Info4> in
        dismissThirdPopup()
        //Do sth with info3...
        return showForthPopup()
    }
    ...
    .catch { error in
        //Handle any error or cancellation...
     }

If, for example, the user presses back in the third popup I need to go back to the previous "then" and not cancel the whole flow.

Basically I need to be able to go back one step, let the user edit the data, then continue the flow.

Is there a way to do this with PromiseKit?

Body:
This is what I ended up using. Hope this helps someone else out there as well.

func myFunc(info: Info) -> Promise<()>
{
    return Promise { fulfill, reject in

        let firstPromise = shouldShowFirstPopup ? showFirstPopup() : Promise(value: info.info1)

        firstPromise
        .then { info1 -> Promise<Info2> in
            info.info1 = info1

            if (info.shouldShowSecondPopup) {
                return showSecondPopup()
            }

            return Promise(value: info.info2)
        }
        .then { info2 -> Promise<Info3> in
            info.info2 = info2
            info.shouldShowSecondPopup = false

            if (info.shouldShowThirdPopup) {
                return showThirdPopup()
            }

            return Promise(value: info.info3)
        }
        .then { info3 -> Promise<()> in
            info.info3 = info3
            info.shouldShowThirdPopup = false

            return processEverything()
        }
        .then { _ -> () in
            fulfill(())
        }
        .catch { error in
            switch error {
                case MyErrors.backPressed(let popupType):
                    switch popupType {
                        case .firstPopup:
                        reject(MyErrors.userCanceled)
                        return

                        case .secondPopup:
                        info.shouldShowFirstPopup = true
                        info.shouldShowSecondPopup = true

                        case .thirdPopup:
                        info.shouldShowSecondPopup = true
                        info.shouldShowThirdPopup = true

                        default:
                        reject(MyErrors.defaultError(message: "Not implemented case exception"))
                        return
                    }

                    firstly {
                        return myFunc(info: info)
                    }
                    .then { _ -> () in
                        fulfill(())
                    }
                    .catch { error2 in
                        reject(error2)
                    }

                default:
                reject(error)
            }
        }
    }
}


问:
Filter from a table Active Record
I have two tables: Restaurant and Meal

restaurant has_many meals and meal belongs_to restaurant.
Hence each meal has a restaurant_id column.

I have a @meals_search variable in my controller that is a list of meals from a search of a user in a search bar.

I want to display the restaurants corresponding to the @meals_search.restaurant_id but so far I can't find the right ActiveRecord query.

For example, if @meals_search.pluck(:restaurant_id) is equal to [1,7,44,53], then I want to create a @restaurants variable that stores restaurants with id 1,7, 44 and 53.

I populate the @meals_search variable like this:

meals_controller.rb

@meals_search = @meals.search(params[:search])

model.meal.rb

```<code>  belongs_to :restaurant

def self.search(search)
  if search
    where('name LIKE ?', "%#{search}%")
  else
    all
  end
end
</code>```

Any idea ?

答:
You can also use map insted of pluck

```<code>@restaurants = Restaurant.where(id: @meals_search.map {|m| m.restaurant_id})
</code>```

Title: Filter from a table Active Record

Body:
I have two tables: Restaurant and Meal

restaurant has_many meals and meal belongs_to restaurant.
Hence each meal has a restaurant_id column.

I have a @meals_search variable in my controller that is a list of meals from a search of a user in a search bar.

I want to display the restaurants corresponding to the @meals_search.restaurant_id but so far I can't find the right ActiveRecord query.

For example, if @meals_search.pluck(:restaurant_id) is equal to [1,7,44,53], then I want to create a @restaurants variable that stores restaurants with id 1,7, 44 and 53.

I populate the @meals_search variable like this:

meals_controller.rb

@meals_search = @meals.search(params[:search])

model.meal.rb

  belongs_to :restaurant

def self.search(search)
  if search
    where('name LIKE ?', "%#{search}%")
  else
    all
  end
end

Any idea ?

Body:
You can also use map insted of pluck

@restaurants = Restaurant.where(id: @meals_search.map {|m| m.restaurant_id})


问:
Running Scala Spark Jobs on Existing EMR
I have Spark Job aggregationfinal_2.11-0.1 jar which I am running on my machine.the composition of it is as follows :

```<code>package deploy
    object FinalJob {
      def main(args: Array[String]): Unit = {
        val spark = SparkSession
          .builder()
          .appName(s"${this.getClass.getSimpleName}")
          .config("spark.sql.shuffle.partitions", "4")
          .getOrCreate()

    //continued code
    }
    }
</code>```

When I am running this code in local mode, it is running fine but when I am deploying this on the EMR cluster with putting its jar in main node.It is giving error as :

```<code>ClassNotFoundException : deploy.FinalJob
</code>```

What am i missing here?

答: The best option is to deploy your uber jar(you can use sbt assembly plugin to build jar) to s3 and add spark step to EMR cluster. Please check:http://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-submit-step.html</p>

Body:
I have Spark Job aggregationfinal_2.11-0.1 jar which I am running on my machine.the composition of it is as follows :

package deploy
    object FinalJob {
      def main(args: Array[String]): Unit = {
        val spark = SparkSession
          .builder()
          .appName(s"${this.getClass.getSimpleName}")
          .config("spark.sql.shuffle.partitions", "4")
          .getOrCreate()

    //continued code
    }
    }

When I am running this code in local mode, it is running fine but when I am deploying this on the EMR cluster with putting its jar in main node.It is giving error as :

ClassNotFoundException : deploy.FinalJob

What am i missing here?


问:
Is there a generic library to hold Delphi application's user defined values
After I added too many user defined values to my application, I had to develop something like below. And now, it is getting complex. I do not want to keep developing this tool. At least, I would like to compare my tool's properties to other solutions.

So, I wonder if there is a generic solution for this kind of job. I googled but I do not know right keywords for this approach (I use Delphi 6. I can read C++ and C#).

My goal is,

Avoid coding user defined parameter definition

Avoid coding user defined parameter user interface and coding business rule

In code, accessing parameter as if strictly defined (not like this: GetParameter('parameter_name_str'))

In code, accessing parameter without type casting from a generic type

--

Okay, I wrote a tool program. By using it, one can produce xml files like this:

```<code>    <?xml version="1.0"?>
    <parameters>
      <parameter id="PrinterEnable">
        <description>Select yes to use printer.</description>
        <group>Printer Settings</group>
        <title>Enable Your Printer</title>
        <type>boolean</type>
      </parameter>
      <parameter id="PrinterConnection">
        <description>You can refer to your printer's manuel to select correct cable.</description>
        <group>Printer Settings</group>
        <title>How to connect your printer</title>
        <type>list</type>
        <items>
          <item value="1">Usb</item>
          <item value="2">Serial</item>
          <item value="3">Parallel</item>
        </items>
      </parameter>
      <parameter id="PrinterWidth">
        <description>Enter width of paper to use in millimeters</description>
        <group>Printer Settings</group>
        <title>Paper Width</title>
        <type>integer</type>
        <default>25</default>
        <min>20</min>
        <max>200</max>
      </parameter>
    </parameters>
</code>```

Then, same tool, automatically creates two files: A Delphi rc file includes a referance to above xml file and (after ask me a few question like class name, unit name) another Delphi pas unit file like this below :

```<code>    unit AppParameters;

    interface

    uses
      libParameters3;

    type
      TAppParameters =class(TParameters3)
      private
        FFileName :string;
      public
        constructor Create;
        procedure Load;
        procedure Save;
            function PrinterEnable: Boolean;
        function PrinterConnection: Integer;
        function PrinterWidth: Integer;
      end;

    implementation

    uses
      Classes, Forms, SysUtils, Windows;

    { AppParameters }

    constructor TAppParameters.Create;
    var
      AStream :TResourceStream;
    begin
      AStream :=TResourceStream.Create(HInstance, 'APP_PARAMETERS', RT_RCDATA);
      try
        inherited LoadDefFromStream(AStream);
      finally
        AStream.Free;
      end;

      FFileName :=ChangeFileExt(Application.ExeName, '.ini');
    end;

    procedure TAppParameters.Load;
    var
      AFileStream :TFileStream;
    begin
      AFileStream :=TFileStream.Create(FFileName, fmOpenRead or fmShareDenyWrite);
      try
        LoadValFromStream(AFileStream);
      finally
        AFileStream.Free;
      end;
    end;

    procedure TAppParameters.Save;
    var
      AFileStream :TFileStream;
    begin
      AFileStream :=TFileStream.Create(FFileName, fmCreate or fmShareDenyWrite);
      try
        SaveValToStream(AFileStream);
      finally
        AFileStream.Free;
      end;
    end;

    function TAppParameters.PrinterEnable: Boolean;
    begin
      Result :=GetParameter('PrinterEnable').AsBoolean;
    end;

    function TAppParameters.PrinterConnection: Integer;
    begin
      Result :=GetParameter('PrinterConnection').AsInteger;
    end;

    function TAppParameters.PrinterWidth: Integer;
    begin
      Result :=GetParameter('PrinterWidth').AsInteger;
    end;

    end.
</code>```

After all, in Delphi on my real code, I can use it like this below:

```<code>    procedure TForm1.FormCreate(Sender: TObject);
    var
      AWidth :integer;
    begin
      FAppParameters :=TAppParameters.Create; //defined in TForm1 private

      FAppParameters.Load;
      if FAppParameters.PrinterEnable then begin
        case FAppParameters.PrinterConnection of
          1 : begin end; {Do Usb}
          2 : begin end; {Do Serial}
          3 : begin end; {Do Parallel}
        end;

        AWidth :=FAppParameters.PrinterWidth;
        //Do something with AWidth
      end;
    end;

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      Form2 :=TForm2.Create(Self);
      try
        Form2.Caption :='Options';
        FAppParameters.PopulateEditor(Form2, Form2);
        Form2.ShowModal;
      finally
        Form2.Free;
      end;
    end;
</code>```

答:
As you don't mention XML as a constraint and use Delphi 6, I'd like to propose to use the Windows registry instead with standard TRegistry class. The Windows registry is the hierarchical database to store application settings.

```<code>uses
  SysUtils, Windows, Registry, Forms;

procedure SaveFormLayout(const AForm: TForm);
var
  R: TRegistry;
begin
  R := TRegistry.Create;
  try
    R.RootKey := HKEY_CURRENT_USER; // HKEY_LOCAL_MACHINE requires admin rights
    R.OpenKey('My Software\Forms\' + AForm.Name, true);
    R.WriteInteger('Top', AForm.Top);
    R.WriteInteger('Left', AForm.Left);
    R.WriteInteger('Height', AForm.Height);
    R.WriteInteger('Width', AForm.Width);
    R.WriteInteger('WindowState', integer(AForm.WindowState));
    R.CloseKey;
  finally
    R.Free;
  end;
end;
</code>```

Registry settings can be easily exported into the file and then imported with REGEDIT or REG command line Windows utilities so you can migrate user profile like a file copy.

Body:
After I added too many user defined values to my application, I had to develop something like below. And now, it is getting complex. I do not want to keep developing this tool. At least, I would like to compare my tool's properties to other solutions.

So, I wonder if there is a generic solution for this kind of job. I googled but I do not know right keywords for this approach (I use Delphi 6. I can read C++ and C#).

My goal is,

Avoid coding user defined parameter definition

Avoid coding user defined parameter user interface and coding business rule

In code, accessing parameter as if strictly defined (not like this: GetParameter('parameter_name_str'))

In code, accessing parameter without type casting from a generic type

--

Okay, I wrote a tool program. By using it, one can produce xml files like this:

    <?xml version="1.0"?>
    <parameters>
      <parameter id="PrinterEnable">
        <description>Select yes to use printer.</description>
        <group>Printer Settings</group>
        <title>Enable Your Printer</title>
        <type>boolean</type>
      </parameter>
      <parameter id="PrinterConnection">
        <description>You can refer to your printer's manuel to select correct cable.</description>
        <group>Printer Settings</group>
        <title>How to connect your printer</title>
        <type>list</type>
        <items>
          <item value="1">Usb</item>
          <item value="2">Serial</item>
          <item value="3">Parallel</item>
        </items>
      </parameter>
      <parameter id="PrinterWidth">
        <description>Enter width of paper to use in millimeters</description>
        <group>Printer Settings</group>
        <title>Paper Width</title>
        <type>integer</type>
        <default>25</default>
        <min>20</min>
        <max>200</max>
      </parameter>
    </parameters>

Then, same tool, automatically creates two files: A Delphi rc file includes a referance to above xml file and (after ask me a few question like class name, unit name) another Delphi pas unit file like this below :

    unit AppParameters;

    interface

    uses
      libParameters3;

    type
      TAppParameters =class(TParameters3)
      private
        FFileName :string;
      public
        constructor Create;
        procedure Load;
        procedure Save;
            function PrinterEnable: Boolean;
        function PrinterConnection: Integer;
        function PrinterWidth: Integer;
      end;

    implementation

    uses
      Classes, Forms, SysUtils, Windows;

    { AppParameters }

    constructor TAppParameters.Create;
    var
      AStream :TResourceStream;
    begin
      AStream :=TResourceStream.Create(HInstance, 'APP_PARAMETERS', RT_RCDATA);
      try
        inherited LoadDefFromStream(AStream);
      finally
        AStream.Free;
      end;

      FFileName :=ChangeFileExt(Application.ExeName, '.ini');
    end;

    procedure TAppParameters.Load;
    var
      AFileStream :TFileStream;
    begin
      AFileStream :=TFileStream.Create(FFileName, fmOpenRead or fmShareDenyWrite);
      try
        LoadValFromStream(AFileStream);
      finally
        AFileStream.Free;
      end;
    end;

    procedure TAppParameters.Save;
    var
      AFileStream :TFileStream;
    begin
      AFileStream :=TFileStream.Create(FFileName, fmCreate or fmShareDenyWrite);
      try
        SaveValToStream(AFileStream);
      finally
        AFileStream.Free;
      end;
    end;

    function TAppParameters.PrinterEnable: Boolean;
    begin
      Result :=GetParameter('PrinterEnable').AsBoolean;
    end;

    function TAppParameters.PrinterConnection: Integer;
    begin
      Result :=GetParameter('PrinterConnection').AsInteger;
    end;

    function TAppParameters.PrinterWidth: Integer;
    begin
      Result :=GetParameter('PrinterWidth').AsInteger;
    end;

    end.

After all, in Delphi on my real code, I can use it like this below:

    procedure TForm1.FormCreate(Sender: TObject);
    var
      AWidth :integer;
    begin
      FAppParameters :=TAppParameters.Create; //defined in TForm1 private

      FAppParameters.Load;
      if FAppParameters.PrinterEnable then begin
        case FAppParameters.PrinterConnection of
          1 : begin end; {Do Usb}
          2 : begin end; {Do Serial}
          3 : begin end; {Do Parallel}
        end;

        AWidth :=FAppParameters.PrinterWidth;
        //Do something with AWidth
      end;
    end;

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      Form2 :=TForm2.Create(Self);
      try
        Form2.Caption :='Options';
        FAppParameters.PopulateEditor(Form2, Form2);
        Form2.ShowModal;
      finally
        Form2.Free;
      end;
    end;

Body:
As you don't mention XML as a constraint and use Delphi 6, I'd like to propose to use the Windows registry instead with standard TRegistry class. The Windows registry is the hierarchical database to store application settings.

uses
  SysUtils, Windows, Registry, Forms;

procedure SaveFormLayout(const AForm: TForm);
var
  R: TRegistry;
begin
  R := TRegistry.Create;
  try
    R.RootKey := HKEY_CURRENT_USER; // HKEY_LOCAL_MACHINE requires admin rights
    R.OpenKey('My Software\Forms\' + AForm.Name, true);
    R.WriteInteger('Top', AForm.Top);
    R.WriteInteger('Left', AForm.Left);
    R.WriteInteger('Height', AForm.Height);
    R.WriteInteger('Width', AForm.Width);
    R.WriteInteger('WindowState', integer(AForm.WindowState));
    R.CloseKey;
  finally
    R.Free;
  end;
end;

Registry settings can be easily exported into the file and then imported with REGEDIT or REG command line Windows utilities so you can migrate user profile like a file copy.


问:
What return if FileContentResult is null
I have method, that return FileContentResult:

```<code>    public FileContentResult fileStream(string EAN)
    {
        //Finding byte[] of PDF
        byte[] pdf = findPDF(EAN);

        return new FileContentResult(pdf, "application/pdf");
    }
</code>```

And I use it in iframe:

```<code><iframe src="@Url.Action("fileStream", "Approve", new { EAN = Model.ID_EAN })" frameborder="0"></iframe>
</code>```

What should I return if pdf is null (FileContentResult is null). Now it shows Error page with controller name and controller action.

答:
I've changed  return value of my method to ActionResult and returned new HttpNotFoundResult();</p>

```<code>    public ActionResult fileStream(string EAN)
    {
        //Hledani byte[] pdf
        byte[] pdf = findPDF(EAN);

        if (pdf == null)
            return new HttpNotFoundResult();

        return new FileContentResult(pdf, "application/pdf");
    }
</code>```

Body:
I have method, that return FileContentResult:

    public FileContentResult fileStream(string EAN)
    {
        //Finding byte[] of PDF
        byte[] pdf = findPDF(EAN);

        return new FileContentResult(pdf, "application/pdf");
    }

And I use it in iframe:

What should I return if pdf is null (FileContentResult is null). Now it shows Error page with controller name and controller action.

Body:
I've changed  return value of my method to ActionResult and returned new HttpNotFoundResult();

    public ActionResult fileStream(string EAN)
    {
        //Hledani byte[] pdf
        byte[] pdf = findPDF(EAN);

        if (pdf == null)
            return new HttpNotFoundResult();

        return new FileContentResult(pdf, "application/pdf");
    }


问:
MySQL Select User id based on multiple AND conditions on same table
I want to select a userid from a single table based on multiple and condition.

```<code>UserID   FieldID  Value
-----------------------------------
1        51         Yes
1        6          Dog
2        6          Cat
1        68         TX
1        69         78701
2        68         LA
</code>```

What I'm trying to get in simple words:

if user search for texas or 78701,
Select userId where (68 = TX OR 69=78701) AND (51=yes) AND (6=Dog)

This should return user id 1.

This is what I tried, but returns null.

```<code>SELECT user_id FROM `metadata`
WHERE ( (`field_id` = '68' AND value LIKE '%TX%')
   OR (`field_id` = '69' AND value LIKE '%78701%') )
   AND `field_id` = '51' AND value = 'Yes'
   AND `field_id` = '6' AND value = 'Dog'
</code>```

答:
SELECT user_id FROM metadata
WHERE
    (field_id = '68' AND value LIKE '%TX%')
        OR (field_id = '69' AND value LIKE '%78701%')
        AND (field_id = '51' AND value = 'Yes')
        AND (field_id = '6' AND value = 'Dog');

I have little bit changed your query and tried with the same,it gives output as, user_id is 1

Body:
I want to select a userid from a single table based on multiple and condition.

UserID   FieldID  Value
-----------------------------------
1        51         Yes
1        6          Dog
2        6          Cat
1        68         TX
1        69         78701
2        68         LA

What I'm trying to get in simple words:

if user search for texas or 78701,
Select userId where (68 = TX OR 69=78701) AND (51=yes) AND (6=Dog)

This should return user id 1.

This is what I tried, but returns null.

SELECT user_id FROM `metadata`
WHERE ( (`field_id` = '68' AND value LIKE '%TX%')
   OR (`field_id` = '69' AND value LIKE '%78701%') )
   AND `field_id` = '51' AND value = 'Yes'
   AND `field_id` = '6' AND value = 'Dog'


问:
How to check if a file contains a specific string using Bash
I want to check if a file contains a specific string or not in bash. I used this script, but it doesn't work:

```<code> if [[ 'grep 'SomeString' $File' ]];then
   # Some Actions
 fi
</code>```

What's wrong in my code?

答:
Try this:</p>

```<code>if [[ $(grep "SomeString" $File) ]] ; then
   echo "Found"
else
   echo "Not Found"
fi
</code>```

Body:
I want to check if a file contains a specific string or not in bash. I used this script, but it doesn't work:

 if [[ 'grep 'SomeString' $File' ]];then
   # Some Actions
 fi

What's wrong in my code?

Body:
Try this:

if [[ $(grep "SomeString" $File) ]] ; then
   echo "Found"
else
   echo "Not Found"
fi