问:
Scrolling of multiple recycler view in an activity. (how to make it smooth)
I have 2 recyclerviews in my activity 1st one is horizontally scrollable and the 2nd one is vertically scrollable. (XML code given below)
But the scrolling is not smooth.

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#eeeeee"
    android:clickable="true"
    >
    <ProgressBar
        android:id="@+id/progressBarCircularIndetermininatesearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminateTintMode="src_atop"
        android:indeterminateTint="#f44336"
        android:layout_centerInParent="true"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/progressbacklin"
        android:scrollbars="none"
        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/videolist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:layout_alignParentTop="true"
        android:scrollbars="none"
        />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:layout_below="@+id/videolist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:scrollbars="none"
        />
        </RelativeLayout>
</ScrollView>
    <LinearLayout
        android:id="@+id/progressbacklin"
        android:layout_above="@+id/adViewsearch"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_marginBottom="90dp"
        android:layout_marginTop="5dp"
        android:background="@drawable/white"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        >
        <ProgressBar
            android:id="@+id/progressBarCircularIndetermininate"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="#f44336"
            android:layout_centerInParent="true"/>
    </LinearLayout>
    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adViewsearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="@string/banner_ad_unit_id" />

</RelativeLayout>
</code>```

i use

```<code>setNestedScrollingEnabled(false);
</code>```

for both recycler view.

Any ideas to implement this with a smooth scrolling?

答:
How i solved this problem is by using a single Recycler view instead of two and setting up the other (1st recycler view in question) recycler view as first item of it.
Now it works perfect and scrolling smoothly.</p>

Body:
I have 2 recyclerviews in my activity 1st one is horizontally scrollable and the 2nd one is vertically scrollable. (XML code given below)
But the scrolling is not smooth.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#eeeeee"
    android:clickable="true"
    >
    <ProgressBar
        android:id="@+id/progressBarCircularIndetermininatesearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminateTintMode="src_atop"
        android:indeterminateTint="#f44336"
        android:layout_centerInParent="true"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/progressbacklin"
        android:scrollbars="none"
        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/videolist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:layout_alignParentTop="true"
        android:scrollbars="none"
        />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:layout_below="@+id/videolist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:scrollbars="none"
        />
        </RelativeLayout>
</ScrollView>
    <LinearLayout
        android:id="@+id/progressbacklin"
        android:layout_above="@+id/adViewsearch"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_marginBottom="90dp"
        android:layout_marginTop="5dp"
        android:background="@drawable/white"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        >
        <ProgressBar
            android:id="@+id/progressBarCircularIndetermininate"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="#f44336"
            android:layout_centerInParent="true"/>
    </LinearLayout>
    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adViewsearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="@string/banner_ad_unit_id" />

</RelativeLayout>

i use

setNestedScrollingEnabled(false);

for both recycler view.

Any ideas to implement this with a smooth scrolling?


来源: stackexchange

问:
Django-Autocomplete-light widgets not showing up
I've just installed Django-Autocomplete-Light and followed the guide on their site. I've setup the autocomplete-view and it works as intended (returning a JASON of autocomplete options). I can't seem to get the widgets to show up, though. in and out of the admin panel.

Everything compiles without errors but instead the widget I get an empty drop down selection box.

Image of empty selection box in admin panel

This is my settings.py:

```<code>INSTALLED_APPS = [
    'dal',
    'dal_select2',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'selectable',
    'videos.apps.VideosConfig',
]
</code>```

This is views.py:

```<code>class ActorAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        # Don't forget to filter out results depending on the visitor !

        qs = Actor.objects.all()

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs
</code>```

urls.py:

```<code>url(r'^actor-autocomplete/$', views.ActorAutocomplete.as_view(), name='actor-autocomplete'),
</code>```

forms.py:

```<code>class ActorForm(forms.ModelForm):
    class Meta:
        model = Actor
        fields = ('name',)
        widgets = {
            'name': autocomplete.Select(url='videos/actor-autocomplete')
        }
</code>```

It feels like I'm missing something simple, but I don't know what it is. Perhaps it can't access the static files, but adding 'dal' to installed_app in settings.py should have solved that according to the documentation.
I'll appreciate any help!

I forgot to mention that Actor.name is of type CharField. Perhaps I'm not using the correct widget, but I haven't found one that is specific for CharField.

As I have the same problem, here is the content of my console in Firefox:

Select2: An instance of jQuery or a jQuery-compatible library was not found. Make sure that you are including jQuery before Select2 on your web page.

It seems that jQuery is needed but not found, but I can't find a way to link it properly.

It is also running perfectly in Chromium. I don't have any other browser to test.

答:
I did have the exact same problem. It is a problem due to the google chrome cache... It did take me a certain time to identify the cause... to solve it do ctrl + SHIFT + R

See this issue on DAL: github Issue 858

ContentLicense: CC BY-SA 3.0

Body:
I've just installed Django-Autocomplete-Light and followed the guide on their site. I've setup the autocomplete-view and it works as intended (returning a JASON of autocomplete options). I can't seem to get the widgets to show up, though. in and out of the admin panel.

Everything compiles without errors but instead the widget I get an empty drop down selection box.

Image of empty selection box in admin panel

This is my settings.py:

INSTALLED_APPS = [
    'dal',
    'dal_select2',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'selectable',
    'videos.apps.VideosConfig',
]

This is views.py:

class ActorAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        # Don't forget to filter out results depending on the visitor !

        qs = Actor.objects.all()

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs

urls.py:

url(r'^actor-autocomplete/$', views.ActorAutocomplete.as_view(), name='actor-autocomplete'),

forms.py:

class ActorForm(forms.ModelForm):
    class Meta:
        model = Actor
        fields = ('name',)
        widgets = {
            'name': autocomplete.Select(url='videos/actor-autocomplete')
        }

It feels like I'm missing something simple, but I don't know what it is. Perhaps it can't access the static files, but adding 'dal' to installed_app in settings.py should have solved that according to the documentation.
I'll appreciate any help!

I forgot to mention that Actor.name is of type CharField. Perhaps I'm not using the correct widget, but I haven't found one that is specific for CharField.

As I have the same problem, here is the content of my console in Firefox:

Select2: An instance of jQuery or a jQuery-compatible library was not found. Make sure that you are including jQuery before Select2 on your web page.

It seems that jQuery is needed but not found, but I can't find a way to link it properly.

It is also running perfectly in Chromium. I don't have any other browser to test.


问:
Inserting python code with PHP variables inside EOT
I'm trying to generate a Python script with PHP. The PHP script embeds variables in the python code and then outputs the resulting python script.

Using the  <<<EOT  it should read the php variables while leaving any other (like python related)

```<code> // PHP Var
        $date = '12/04/2017';
        $id = '2';
        $phparray['value1'] = '03:45';
        $phparray['value2'] = '08:00';
        $phparray['value3'] = '17:00';
        $phparray['value4'] = '21:30';

// Embed Variables in the Python script code to be later generated

        $PythonContents =  <<<EOT
    I'm, trying to embed "$phpvar" inside python code.

    '''
    Python script generated on {$date}

    '''

    # Python Function specific imports
    import datetime

    ################    Python configs ############
    myvar = 'fixed'
    function_id   = {$id}
    Python-With-PHP-var-Range = [['{$phparray['value1']}','{$phparray['value2']}'],['{$phparray['value3']}','{$phparray['value4']}']]

Result-IN-Python-range = [['03:45','08:00'],['17:00','21:30']]

Python-and-PHP-var2 = {
             '{$generateID}/f/{$data_sensor['device_id']}/test/{$data['heatControlRelay']}/rstate': 'heatingisLocked',
              }
ResultINPython = {
              '44/f/folder1/test/85111': 'Value',
             }
################    End of Python config     #############################
################    Python script below     #############################

################    End of Python script   #############################

                EOT;
echo $PythonContents;
</code>```

答:
The main breakage is with the additional spacing before the ending EOT, but its also full of undefined vars.

So heres it fixed:

```<code><?php
// PHP Var
$generateID = '123';

$data_sensor['device_id'] = 'xyz';
$data['heatControlRelay'] = '12345';

$date = '12/04/2017';
$id = '2';
$phparray['value1'] = '03:45';
$phparray['value2'] = '08:00';
$phparray['value3'] = '17:00';
$phparray['value4'] = '21:30';

// Embed Variables in the Python script code to be later generated
$PythonContents =  <<<EOT
    I'm, trying to embed "\$phpvar" inside python code.

    '''
    Python script generated on {$date}

    '''

    # Python Function specific imports
    import datetime

    ################    Python configs ############
    myvar = 'fixed'
    function_id   = {$id}
    Python-With-PHP-var-Range = [['{$phparray['value1']}','{$phparray['value2']}'],['{$phparray['value3']}','{$phparray['value4']}']]

    Result-IN-Python-range = [['03:45','08:00'],['17:00','21:30']]

    Python-and-PHP-var2 = {
        '{$generateID}/f/{$data_sensor['device_id']}/test/{$data['heatControlRelay']}/rstate': 'heatingisLocked',
    }

    ResultINPython = {
        '44/f/folder1/test/85111': 'Value',
    }
EOT;
echo $PythonContents;
</code>```

Body:
I'm trying to generate a Python script with PHP. The PHP script embeds variables in the python code and then outputs the resulting python script.

Using the  <<<EOT  it should read the php variables while leaving any other (like python related)

 // PHP Var
        $date = '12/04/2017';
        $id = '2';
        $phparray['value1'] = '03:45';
        $phparray['value2'] = '08:00';
        $phparray['value3'] = '17:00';
        $phparray['value4'] = '21:30';

// Embed Variables in the Python script code to be later generated

        $PythonContents =  <<<EOT
    I'm, trying to embed "$phpvar" inside python code.

    '''
    Python script generated on {$date}

    '''

    # Python Function specific imports
    import datetime

    ################    Python configs ############
    myvar = 'fixed'
    function_id   = {$id}
    Python-With-PHP-var-Range = [['{$phparray['value1']}','{$phparray['value2']}'],['{$phparray['value3']}','{$phparray['value4']}']]

Result-IN-Python-range = [['03:45','08:00'],['17:00','21:30']]

Python-and-PHP-var2 = {
             '{$generateID}/f/{$data_sensor['device_id']}/test/{$data['heatControlRelay']}/rstate': 'heatingisLocked',
              }
ResultINPython = {
              '44/f/folder1/test/85111': 'Value',
             }
################    End of Python config     #############################
################    Python script below     #############################

################    End of Python script   #############################

                EOT;
echo $PythonContents;

Body:
The main breakage is with the additional spacing before the ending EOT, but its also full of undefined vars.

So heres it fixed:

<?php
// PHP Var
$generateID = '123';

$data_sensor['device_id'] = 'xyz';
$data['heatControlRelay'] = '12345';

$date = '12/04/2017';
$id = '2';
$phparray['value1'] = '03:45';
$phparray['value2'] = '08:00';
$phparray['value3'] = '17:00';
$phparray['value4'] = '21:30';

// Embed Variables in the Python script code to be later generated
$PythonContents =  <<<EOT
    I'm, trying to embed "\$phpvar" inside python code.

    '''
    Python script generated on {$date}

    '''

    # Python Function specific imports
    import datetime

    ################    Python configs ############
    myvar = 'fixed'
    function_id   = {$id}
    Python-With-PHP-var-Range = [['{$phparray['value1']}','{$phparray['value2']}'],['{$phparray['value3']}','{$phparray['value4']}']]

    Result-IN-Python-range = [['03:45','08:00'],['17:00','21:30']]

    Python-and-PHP-var2 = {
        '{$generateID}/f/{$data_sensor['device_id']}/test/{$data['heatControlRelay']}/rstate': 'heatingisLocked',
    }

    ResultINPython = {
        '44/f/folder1/test/85111': 'Value',
    }
EOT;
echo $PythonContents;


问:
Undefined is not callable
I'm writing a transaction which adds a participant and an asset to the network. Adding the participant to the network works, but when I try to access the Medical asset file registry the function returns undefined.

Error: TypeError: undefined not callable

The logic of the transaction:

```<code>return getParticipantRegistry(namespace + '.Patient')
        .then(function (patientRegistry) {
            return patientRegistry.add(newPatient);
        }).then(function() {
            return getAssetRegistry('nl.epd.blockchain.MedicalFile');
        }).then(function (registry) {
            var medicalFile = factory.newResource(namespace, 'MedicalFile', "test");
            medicalFile.id = "test";
            medicalFile.owner = newPatient.bsn;
            medicalFile.mentors = [];
            medicalFile.permissions = [];
            medicalFile.allergies = [];
            medicalFile.treatments = [];
            medicalFile.medicine = [];

            // registry is undefined
            return registry.add(medicalFile);
        });
}
</code>```

Models:

```<code>namespace nl.epd.blockchain

asset MedicalFile identified by id {
  o String                      id
  --> Patient                   owner
  --> Patient[]                 mentors
  o OrganisationPermission[]  permissions
  o Visit[]                   visits
  o String[]                  allergies
  o Treatment[]               treatments
  o Medicine[]                medicine
}

participant Patient identified by bsn {
  o String bsn
  o String firstName
  o String namePrefix optional
  o String lastName
  o String email
  o String telephoneNumber
  o String birthday
  o String gender
  o String city
  o String zipCode
  o String street
  o String houseNumber
  o String houseNumberExtra optional
}
</code>```

NPM dependencies:

```<code>"dependencies": {
    "fabric-ca-client": "1.0.0-alpha.0",
    "fabric-client": "1.0.0-alpha",
    "homedir": "^0.6.0",
    "composer-client": "^0.7.0",
    "composer-rest-server": "^0.7.0"
  }
</code>```

Any idea what's wrong?

答:
The assumption that the registry was empty was incorrect. The problem was that the owner wasn't a relationship. It was just a string, I thought that was allowed.

This caused the error described above.

The fix:

```<code>medicalFile.owner = factory.newRelationship(namespace, 'Patient', newPatient.bsn);
</code>```

Title: Undefined is not callable

Body:
I'm writing a transaction which adds a participant and an asset to the network. Adding the participant to the network works, but when I try to access the Medical asset file registry the function returns undefined.

Error: TypeError: undefined not callable

The logic of the transaction:

return getParticipantRegistry(namespace + '.Patient')
        .then(function (patientRegistry) {
            return patientRegistry.add(newPatient);
        }).then(function() {
            return getAssetRegistry('nl.epd.blockchain.MedicalFile');
        }).then(function (registry) {
            var medicalFile = factory.newResource(namespace, 'MedicalFile', "test");
            medicalFile.id = "test";
            medicalFile.owner = newPatient.bsn;
            medicalFile.mentors = [];
            medicalFile.permissions = [];
            medicalFile.allergies = [];
            medicalFile.treatments = [];
            medicalFile.medicine = [];

            // registry is undefined
            return registry.add(medicalFile);
        });
}

Models:

namespace nl.epd.blockchain

asset MedicalFile identified by id {
  o String                      id
  --> Patient                   owner
  --> Patient[]                 mentors
  o OrganisationPermission[]  permissions
  o Visit[]                   visits
  o String[]                  allergies
  o Treatment[]               treatments
  o Medicine[]                medicine
}

participant Patient identified by bsn {
  o String bsn
  o String firstName
  o String namePrefix optional
  o String lastName
  o String email
  o String telephoneNumber
  o String birthday
  o String gender
  o String city
  o String zipCode
  o String street
  o String houseNumber
  o String houseNumberExtra optional
}

NPM dependencies:

"dependencies": {
    "fabric-ca-client": "1.0.0-alpha.0",
    "fabric-client": "1.0.0-alpha",
    "homedir": "^0.6.0",
    "composer-client": "^0.7.0",
    "composer-rest-server": "^0.7.0"
  }

Any idea what's wrong?

Body:
The assumption that the registry was empty was incorrect. The problem was that the owner wasn't a relationship. It was just a string, I thought that was allowed.

This caused the error described above.

The fix:

medicalFile.owner = factory.newRelationship(namespace, 'Patient', newPatient.bsn);


问:
X86 Assembly Problems
I'm attempting to get through a book on X86 that was written using examples from Visual C++ and Visual Studio. I'm trying to convert the examples for use with gcc. After a number of problems, I finally wound up with code that would at least compile, but now I'm getting segfaults. Here's the code:

assembly.s:

```<code>.intel_syntax noprefix
.section .text
.globl CalcSum
.type CalcSum, @function
// extern "C" int CalcSum_(int a, int b, int c)
CalcSum:

// Initialize a stack frame pointer
    pushq rbp
    mov ebp,esp

// Load the argument values
    mov eax,[ebp+8]
    mov ecx,[ebp+12]
    mov edx,[ebp+16]

// Calculate the sum
    add eax, ecx
    add eax, edx

// Restore the caller's stack frame pointer
    popq rbp
    ret
</code>```

test.c:

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

extern int CalcSum(int a, int b, int c);

int main() {
   int sum = CalcSum(5,6,7);
   printf(" result: %d\n",sum);
   return 0;
}
</code>```

I'm using gcc -o execute test.c assembly.s to compile. If I change all the 32 bit instructions to 64 bit (i.e. ebp to rbp) it will run but give completely random output. Could anyone point out what I'm doing wrong here? Thanks!

答:
As hinted in the comments, it's a matter of calling convention. 32-bit C functions follow the CDECL calling convention in Windows and in Linux. In 64-bit Linux you have to use the System V AMD64 ABI. The 64-bit calling convention of Windows is different. There might be specifics to use functions of the operating system.

32-bit C (GCC):

```<code>.intel_syntax noprefix
.section .text
.globl CalcSum
.type CalcSum, @function
// extern "C" int CalcSum_(int a, int b, int c)
CalcSum:     // with underscore in Windows: _CalcSum

// Initialize a stack frame pointer
    push ebp
    mov ebp,esp

// Load the argument values
    mov eax,[ebp+8]
    mov ecx,[ebp+12]
    mov edx,[ebp+16]

// Calculate the sum
    add eax, ecx
    add eax, edx

// Restore the caller's stack frame pointer
    pop ebp
    ret
</code>```

64-bit Linux (GCC):

```<code>.intel_syntax noprefix
.section .text
.globl CalcSum
.type CalcSum, @function
// extern "C" int CalcSum_(int a, int b, int c)
CalcSum:

// Load the argument values
    mov rax, rdi
    add rax, rsi
    add rax, rdx

    ret
</code>```

64-bit Windows (MingW-GCC):

```<code>.intel_syntax noprefix
.section .text
.globl CalcSum
// .type CalcSum, @function
// extern "C" int CalcSum_(int a, int b, int c)
CalcSum:

// Load the argument values
    mov rax, rcx
    add rax, rdx
    add rax, r8

    ret
</code>```

Title: X86 Assembly Problems

Body:
I'm attempting to get through a book on X86 that was written using examples from Visual C++ and Visual Studio. I'm trying to convert the examples for use with gcc. After a number of problems, I finally wound up with code that would at least compile, but now I'm getting segfaults. Here's the code:

assembly.s:

.intel_syntax noprefix
.section .text
.globl CalcSum
.type CalcSum, @function
// extern "C" int CalcSum_(int a, int b, int c)
CalcSum:

// Initialize a stack frame pointer
    pushq rbp
    mov ebp,esp

// Load the argument values
    mov eax,[ebp+8]
    mov ecx,[ebp+12]
    mov edx,[ebp+16]

// Calculate the sum
    add eax, ecx
    add eax, edx

// Restore the caller's stack frame pointer
    popq rbp
    ret

test.c:

#include <stdio.h>

extern int CalcSum(int a, int b, int c);

int main() {
   int sum = CalcSum(5,6,7);
   printf(" result: %d\n",sum);
   return 0;
}

I'm using gcc -o execute test.c assembly.s to compile. If I change all the 32 bit instructions to 64 bit (i.e. ebp to rbp) it will run but give completely random output. Could anyone point out what I'm doing wrong here? Thanks!

Body:
As hinted in the comments, it's a matter of calling convention. 32-bit C functions follow the CDECL calling convention in Windows and in Linux. In 64-bit Linux you have to use the System V AMD64 ABI. The 64-bit calling convention of Windows is different. There might be specifics to use functions of the operating system.

32-bit C (GCC):

.intel_syntax noprefix
.section .text
.globl CalcSum
.type CalcSum, @function
// extern "C" int CalcSum_(int a, int b, int c)
CalcSum:     // with underscore in Windows: _CalcSum

// Initialize a stack frame pointer
    push ebp
    mov ebp,esp

// Load the argument values
    mov eax,[ebp+8]
    mov ecx,[ebp+12]
    mov edx,[ebp+16]

// Calculate the sum
    add eax, ecx
    add eax, edx

// Restore the caller's stack frame pointer
    pop ebp
    ret

64-bit Linux (GCC):

.intel_syntax noprefix
.section .text
.globl CalcSum
.type CalcSum, @function
// extern "C" int CalcSum_(int a, int b, int c)
CalcSum:

// Load the argument values
    mov rax, rdi
    add rax, rsi
    add rax, rdx

    ret

64-bit Windows (MingW-GCC):

.intel_syntax noprefix
.section .text
.globl CalcSum
// .type CalcSum, @function
// extern "C" int CalcSum_(int a, int b, int c)
CalcSum:

// Load the argument values
    mov rax, rcx
    add rax, rdx
    add rax, r8

    ret


问:
Linebreak in javascript
```<code>var y=21.5;
document.write(y);

var num = 10;
document.write(num == 8);
</code>```

Hi guys, it's my first time here to ask question in this forum. I am currently studying the basics of javascript and i want to know how can i put a linebreak after an integer. I've already tried putting
 inside and outside variable y and i still can't get my desired result. Here's the output of my code.

http://imgur.com/LLhGteY

答:
Since you are using document.write, what you need is a HTML line break, not a Javascript line break.

Try using
:

var y = 21.5;
var num = 10;

document.write(y + '
');
document.write(num == 8);```

Title: Linebreak in javascript

Body:
var y=21.5;
document.write(y);

var num = 10;
document.write(num == 8);

Hi guys, it's my first time here to ask question in this forum. I am currently studying the basics of javascript and i want to know how can i put a linebreak after an integer. I've already tried putting
 inside and outside variable y and i still can't get my desired result. Here's the output of my code.

http://imgur.com/LLhGteY

Body:
Since you are using document.write, what you need is a HTML line break, not a Javascript line break.

Try using <br>:

var y = 21.5;
var num = 10;

document.write(y + '<br>');
document.write(num == 8);


问:
how to extract a number from a string if I know when its starting and when its finishing
for example:

I have the following string

```<code>"somestringthatcanbeanything theStringBeforeTheNumber20.47theStringAfterTheNumber somestringthatcanbeanything"
</code>```

so the number is always between

```<code>theStringBeforeTheNumber{number}theStringAfterTheNumber
</code>```

What I want is to extract the number from the whole string, how can I do that? im using scala how should my regex look like?   val myRgx: Regex = """myRegexGoesHere""".r

答:
You can use your suggested pattern, slightly modified as:

```<code>val string = "theStringBeforeTheNumber20.47theStringAfterTheNumber"
val pattern = """theStringBeforeTheNumber(.*?)theStringAfterTheNumber""".r
pattern.findAllIn(string).matchData foreach {
    m => println(m.group(1))
}
</code>```

The quantity in parentheses (.*?) is a capture group and it uses a lazy dot.  This says to match everything between the first string and the first occurrence of the second string.  We print out the first capture group in the code snippet.

Body:
for example:

I have the following string

"somestringthatcanbeanything theStringBeforeTheNumber20.47theStringAfterTheNumber somestringthatcanbeanything"

so the number is always between

theStringBeforeTheNumber{number}theStringAfterTheNumber

What I want is to extract the number from the whole string, how can I do that? im using scala how should my regex look like?   val myRgx: Regex = """myRegexGoesHere""".r

Body:
You can use your suggested pattern, slightly modified as:

val string = "theStringBeforeTheNumber20.47theStringAfterTheNumber"
val pattern = """theStringBeforeTheNumber(.*?)theStringAfterTheNumber""".r
pattern.findAllIn(string).matchData foreach {
    m => println(m.group(1))
}

The quantity in parentheses (.*?) is a capture group and it uses a lazy dot.  This says to match everything between the first string and the first occurrence of the second string.  We print out the first capture group in the code snippet.


答:
The solution appeared to be to tweak the importObject used in WebAssembly.Instance(module, importObject):

```<code>{
  'env': {
    'memoryBase': 0,
    'tableBase': 0,
    'memory': new WebAssembly.Memory({initial: 256}),
    'table': new WebAssembly.Table({initial: 0, element: 'anyfunc'})
  }
}
</code>```

memoryBase and tableBase were needed and the initial memory value was too low (throwed a LinkedError: Memory of incompatible size).

Also I had to call counter.exports._count() and not counter.exports.count() once the instantiation was done.

Also thanks to @Ghillie as the -O1 optimization flag was indeed needed.

Edit: if you are reading this and just getting started with WebAssembly, I made a summary of my first experience, in case it helps: WebAssembly 101: a developer's first steps.

Title: WebAssembly Link Error: import object field 'DYNAMICTOP_PTR' is not a Number

Body:
The following C file is compiled to wasm with emscripten:

int counter = 100;

int count() {
    counter += 1;
    return counter;
}

$ emcc counter.c -o counter.wasm -s WASM=1 -s SIDE_MODULE=1

With no issues. I then have webpack loading the wasm file (with wasm-loader) as an UInt8Array:

var buffer = new ArrayBuffer(648);
var uint8 = new Uint8Array(buffer);
uint8.set([0,97,115,109,1,0,0,0,0,12,6,100,121,108,105,110,107,144,128,192,2,0,1,150,128,128,128,0,5,96,1,127,0,96,1,127,1,127,96,0,1,127,96,2,127,127,0,96,0,0,2,179,129,128,128,0,10,3,101,110,118,14,68,89,78,65,77,73,67,84,79,80,95,80,84,82,3,127,0,3,101,110,118,13,116,101,109,112,68,111,117,98,108,101,80,116,114,3,127,0,3,101,110,118,5,65,66,79,82,84,3,127,0,3,101,110,118,10,109,101,109,111,114,121,66,97,115,101,3,127,0,3,101,110,118,9,116,97,98,108,101,66,97,115,101,3,127,0,6,103,108,111,98,97,108,3,78,97,78,3,124,0,6,103,108,111,98,97,108,8,73,110,102,105,110,105,116,121,3,124,0,3,101,110,118,18,97,98,111,114,116,83,116,97,99,107,79,118,101,114,102,108,111,119,0,0,3,101,110,118,6,109,101,109,111,114,121,2,0,128,2,3,101,110,118,5,116,97,98,108,101,1,112,0,0,3,137,128,128,128,0,8,1,2,0,3,3,2,4,4,6,242,128,128,128,0,20,127,1,35,0,11,127,1,35,1,11,127,1,35,2,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,124,1,35,5,11,124,1,35,6,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,124,1,68,0,0,0,0,0,0,0,0,11,127,1,65,0,11,125,1,67,0,0,0,0,11,125,1,67,0,0,0,0,11,127,0,65,0,11,7,184,128,128,128,0,4,6,95,99,111,117,110,116,0,6,18,95,95,112,111,115,116,95,105,110,115,116,97,110,116,105,97,116,101,0,8,11,114,117,110,80,111,115,116,83,101,116,115,0,7,8,95,99,111,117,110,116,101,114,3,26,9,129,128,128,128,0,0,10,190,129,128,128,0,8,173,128,128,128,0,1,1,127,2,64,35,10,33,1,35,10,32,0,106,36,10,35,10,65,15,106,65,112,113,36,10,35,10,35,11,78,4,64,32,0,16,0,11,32,1,15,0,11,0,11,133,128,128,128,0,0,35,10,15,11,134,128,128,128,0,0,32,0,36,10,11,141,128,128,128,0,0,2,64,32,0,36,10,32,1,36,11,11,11,146,128,128,128,0,0,35,12,65,0,70,4,64,32,0,36,12,32,1,36,13,11,11,161,128,128,128,0,1,4,127,2,64,35,10,33,3,35,3,65,0,106,40,2,0,33,0,32,0,65,1,106,33,1,32,1,15,0,11,0,11,133,128,128,128,0,1,1,127,1,11,152,128,128,128,0,0,2,64,35,3,65,16,106,36,10,35,10,65,128,128,192,2,106,36,11,16,7,11,11,11,135,128,128,128,0,1,0,35,3,11,1,100,]);

My JS code then call the following:

import Counter from './wasm/counter'
const counter = new Counter();

And fails on the instantiation with the following Error:

LinkError: import object field 'DYNAMICTOP_PTR' is not a Number

wasm-loader uses the following default options (importObject) for WebAssembly.Instance(module, importObject):

{
  'global': {},
  'env': {
    'memory': new Memory({initial: 10, limit: 100}),
    'table': new Table({initial: 0, element: 'anyfunc'})
  }
}

Am I doing something wrong ? How can I successfully load the wasm code ?

Edit:
Following @Ghillie advice I tried to compile the C code with different optimization flags:

-O1, -02, -O3, -Os and -Oz  throw a LinkError: import object field 'memoryBase' is not a Number which is a different error but doesn't solve the issue.

Edit 2:

Solely adding the -O1 optimization flag didn't work but having a different error message allowed to debug the code so both @Ghillie and my answer offer the complete solution to my question.

Body:
The solution appeared to be to tweak the importObject used in WebAssembly.Instance(module, importObject):

{
  'env': {
    'memoryBase': 0,
    'tableBase': 0,
    'memory': new WebAssembly.Memory({initial: 256}),
    'table': new WebAssembly.Table({initial: 0, element: 'anyfunc'})
  }
}

memoryBase and tableBase were needed and the initial memory value was too low (throwed a LinkedError: Memory of incompatible size).

Also I had to call counter.exports._count() and not counter.exports.count() once the instantiation was done.

Also thanks to @Ghillie as the -O1 optimization flag was indeed needed.

Edit: if you are reading this and just getting started with WebAssembly, I made a summary of my first experience, in case it helps: WebAssembly 101: a developer's first steps.


问:
Golang/gin: How to Pass db to router functions
I'm using gin framework. And I'm opening the sqlite database in the main function like this

```<code>func main() {
...
db, err := sql.Open("sqlite3", "./libreread.db")
CheckError(err)
defer db.Close()
...
}
</code>```

And I have these router handlers in the main function.

```<code>...
r.GET("/", GetHomePage)
r.GET("/signin", GetSignIn)
r.POST("/signin", PostSignIn)
...
</code>```

How to pass that db value through the router handler func PostSignin(c *gin.Context) ?

So that I could avoid opening and closing the database each time in the functions.

UPDATE: I'm using go-sqlite3 package.

Thanks!

答:
Let's say you have your sql client initialized in db, then, you can pass it to different routes with

```<code>r.GET("/", GetHomePageHandler(&db))
</code>```

And in your GetHomePageHandler:

```<code>func GetHomePageHandler(sqldb *SQLiteConn) func (*gin.Context) {
    return  func (*gin.Context) {
      . . .
    }
}
</code>```

Where *SQLiteConn is the type of your sql db instance. I don't know which package you are currently using so this is just an example.

You can find also a more elegant way of solving it in this answer,

Body:
I'm using gin framework. And I'm opening the sqlite database in the main function like this

func main() {
...
db, err := sql.Open("sqlite3", "./libreread.db")
CheckError(err)
defer db.Close()
...
}

And I have these router handlers in the main function.

...
r.GET("/", GetHomePage)
r.GET("/signin", GetSignIn)
r.POST("/signin", PostSignIn)
...

How to pass that db value through the router handler func PostSignin(c *gin.Context) ?

So that I could avoid opening and closing the database each time in the functions.

UPDATE: I'm using go-sqlite3 package.

Thanks!

Body:
Let's say you have your sql client initialized in db, then, you can pass it to different routes with

r.GET("/", GetHomePageHandler(&db))

And in your GetHomePageHandler:

func GetHomePageHandler(sqldb *SQLiteConn) func (*gin.Context) {
    return  func (*gin.Context) {
      . . .
    }
}

Where *SQLiteConn is the type of your sql db instance. I don't know which package you are currently using so this is just an example.

You can find also a more elegant way of solving it in this answer,


问:
C# Excel Number Format error
I'm having troubles setting columns format in Excel with Interop. I'm using C#, below is the code:

```<code>Excelop.Range rg = (Excelop.Range)wb.Worksheets[1].Cells[1, i];
rg.NumberFormat = "@"; //Exception is raised here
</code>```

I get the below exception when compiled:

"An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll

Additional information: Unable to set the NumberFormat property of the Range class"

Appreciate your support.

答:
My guess is that your worksheet is protected.

You likely need to do something like:

wb.Worksheets[1].Unprotect (Password:"your_password")

These may be of assistance:

https://www.mrexcel.com/forum/excel-questions/449829-run-time-error-1004-unable-set-numberformat-property-range-class.html

"Unable to set the NumberFormat property of the Range class"

Title: C# Excel Number Format error

Body:
I'm having troubles setting columns format in Excel with Interop. I'm using C#, below is the code:

Excelop.Range rg = (Excelop.Range)wb.Worksheets[1].Cells[1, i];
rg.NumberFormat = "@"; //Exception is raised here

I get the below exception when compiled:

"An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll

Additional information: Unable to set the NumberFormat property of the Range class"

Appreciate your support.


问:
Nested resource with multiple parent resources in Rails 3
I want to create a model to store comments related to articles. I have a strong feeling that in the future I will want comments on other objects in the app too. How do I design commenting in my app so that it will be forward compatible with adding new parent objects. I want to avoid a scenario where have multiple controllers/models for each object to comment relationship.

After watching Ryan Bates screen cast on Nested Resource I have a firm grasp on how tp nest a resource under a single parent. How do I achieve this under 2 or more parent resources?

Thanks!

答:
For "forward compatible with adding new parent objects" part of the question:

You could use Polymorphic Associations. Here's a nice example. Also see RailsCast #154.

An example of how it could look like for you:

The comments table columns' could be like this:

```<code>id:integer
commentable_type:string
commentable_id:integer
comment_text:string
</code>```

Some Sample records:

```<code>1,'Article',12,'My first comment' #comment on an Article model
2,'Question',12,'My first comment' #comment on a Question model
3,'Question',15,'My first comment' #comment on a Question model
</code>```

ContentLicense: CC BY-SA 2.5

Body:
For "forward compatible with adding new parent objects" part of the question:

You could use Polymorphic Associations. Here's a nice example. Also see RailsCast #154.

An example of how it could look like for you:

The comments table columns' could be like this:

id:integer
commentable_type:string
commentable_id:integer
comment_text:string

Some Sample records:

1,'Article',12,'My first comment' #comment on an Article model
2,'Question',12,'My first comment' #comment on a Question model
3,'Question',15,'My first comment' #comment on a Question model


问:
Regex not matching all hyphens
In the following example, only the third string is matched, even though there are hyphens in all three strings:

```<code>grep("-", c("January 7–9, 2015", "January a–b, 2015", "Janua-ry 14, 2015"))
[1] 3
</code>```

How can I match all three hyphens with grep?

答:
The reason why the 3 hyphens are not matching is because only the 3 is the standard hyphen.  One way is to match only those hyphen characters by not matching the alpha numeric, , and space characters

```<code>grep("[^[:alnum:], ]+", v1)
#[1] 1 2 3
</code>```

Another option is to copy the hyphen character which is the same for the first two strings and use | to match with the standard hypen

```<code>grep("–|-", v1)
#[1] 1 2 3
</code>```

data

```<code>v1 <- c("January 7–9, 2015", "January a–b, 2015", "Janua-ry 14, 2015")
</code>```

ContentLicense: CC BY-SA 4.0

Title: Regex not matching all hyphens

Body:
In the following example, only the third string is matched, even though there are hyphens in all three strings:

grep("-", c("January 7–9, 2015", "January a–b, 2015", "Janua-ry 14, 2015"))
[1] 3

How can I match all three hyphens with grep?

Body:
The reason why the 3 hyphens are not matching is because only the 3 is the standard hyphen.  One way is to match only those hyphen characters by not matching the alpha numeric, , and space characters

grep("[^[:alnum:], ]+", v1)
#[1] 1 2 3

Another option is to copy the hyphen character which is the same for the first two strings and use | to match with the standard hypen

grep("–|-", v1)
#[1] 1 2 3

data

v1 <- c("January 7–9, 2015", "January a–b, 2015", "Janua-ry 14, 2015")


问:
multiple page in react router v4
I am using react router v4 for routing. The layout my app is, there is homepage which is for end user. The path for homepage is obviously /. There is dashboard section too. One for admin, one for agent and another for owner. They have their own layout from top to bottom. For homepage its working. But when i hit url /admin/dashboard, the main page of admin dasboard is not shown. The same homepage is shown.

Here is what i have done

```<code>const AsyncRoute = ({ load, ...others }) => (
  <Route
    {...others} render={(props) => (
      <Bundle load={load} {...props} />
  )}
  />
);
</code>```

app.js

```<code>const render = messages => {
  ReactDOM.render(
    <Provider store={store}>
        <ConnectedRouter history={history}>
          <App />
        </ConnectedRouter>
    </Provider>,
    document.getElementById("app")
  );
};

import Routes from 'routes';
class App extends React.Component {
render() {
  return (
    <div>
      <Navbar userForm={this.handleDialog} />
      <Routes />
    </div>
  );
}
}

routes.js
function Routes({ location }) {
  return (
    <Switch location={location}>
      <AsyncRoute exact path="/" load={loadHomePage} />
      <AsyncRoute exact path="/features" load={loadFeaturePage} />
      <AsyncRoute path="" load={loadNotFoundPage} />
    </Switch>
  );
}
</code>```

I want now admin dashboard a complete new page with different layout not children of App component so i did
the following

```<code>class AdminDashboard extends React.Component {
  render() {
    return (
      <div>
        <TopNavigation />
        <SideNavigation />{/* it will have link */}
        <Routes /> {/* it will display page */}
      </div>
    );
  }
}

function AdminRoutes({ location }) {
  return (
        <Switch location={location}>
          <AsyncRoute
            exact
            path="/admin/dashboard"
            load={loadAdminDashboardPage}
          />
          <AsyncRoute exact path="/commission" load={loadCommissionPage} />
          <AsyncRoute path="" load={loadNotFoundPage} />
        </Switch>
  );
}
</code>```

when i hit the url /admin/dashboard i get the app page not the admin dashboard page and same with the
/commission which should be a child of AdminDashboard

How can i make my router work for different layout?

答:
From Meteorchef Base, dedicated routing according to the user (loggingIn prop in this case):

Public.js, only for non admin, redirect if not :

```<code>import React from 'react';
import PropTypes from 'prop-types';
import { Route, Redirect } from 'react-router-dom';

const Public = ({ loggingIn, authenticated, component, ...rest }) => (
  <Route {...rest} render={(props) => {
    if (loggingIn) return <div></div>;
    return !authenticated ?
    (React.createElement(component, { ...props, loggingIn, authenticated })) :
    (<Redirect to="/account" />);
  }} />
);

Public.propTypes = {
  loggingIn: PropTypes.bool,
  authenticated: PropTypes.bool,
  component: PropTypes.func,
};

export default Public;
</code>```

Authenticated.js, only for admin, also redirect if not :

```<code>import React from 'react';
import PropTypes from 'prop-types';
import { Route, Redirect } from 'react-router-dom';

const Authenticated = ({ loggingIn, authenticated, component, ...rest }) => (
  <Route {...rest} render={(props) => {
    if (loggingIn) return <div></div>;
    return authenticated ?
    (React.createElement(component, { ...props, loggingIn, authenticated })) :
    (<Redirect to="/login" />);
  }} />
);

Authenticated.propTypes = {
  loggingIn: PropTypes.bool,
  authenticated: PropTypes.bool,
  component: PropTypes.func,
};

export default Authenticated;
</code>```

then in your App, (stateless in this case, but you can create a class as well too) :

```<code>// import everything

const App = appProps => (
  <Router>
      <div>
        <Switch>
          <Route exact name="index" path="/" component={Home} />
          <Authenticated exact path="/account" component={Account} {...appProps} />
          <Public path="/signup" component={Signup} {...appProps} />
          <Public path="/login" component={Login} {...appProps} />
          <Route component={NotFound} />
        </Switch>
      </div>
  </Router>
);

App.propTypes = {
  loggingIn: PropTypes.bool,
  authenticated: PropTypes.bool,
};
</code>```

Title: multiple page in react router v4

Body:
I am using react router v4 for routing. The layout my app is, there is homepage which is for end user. The path for homepage is obviously /. There is dashboard section too. One for admin, one for agent and another for owner. They have their own layout from top to bottom. For homepage its working. But when i hit url /admin/dashboard, the main page of admin dasboard is not shown. The same homepage is shown.

Here is what i have done

const AsyncRoute = ({ load, ...others }) => (
  <Route
    {...others} render={(props) => (
      <Bundle load={load} {...props} />
  )}
  />
);

app.js

const render = messages => {
  ReactDOM.render(
    <Provider store={store}>
        <ConnectedRouter history={history}>
          <App />
        </ConnectedRouter>
    </Provider>,
    document.getElementById("app")
  );
};

import Routes from 'routes';
class App extends React.Component {
render() {
  return (

      <Navbar userForm={this.handleDialog} />
      <Routes />

  );
}
}

routes.js
function Routes({ location }) {
  return (
    <Switch location={location}>
      <AsyncRoute exact path="/" load={loadHomePage} />
      <AsyncRoute exact path="/features" load={loadFeaturePage} />
      <AsyncRoute path="" load={loadNotFoundPage} />
    </Switch>
  );
}

I want now admin dashboard a complete new page with different layout not children of App component so i did
the following

class AdminDashboard extends React.Component {
  render() {
    return (

        <TopNavigation />
        <SideNavigation />{/* it will have link */}
        <Routes /> {/* it will display page */}

    );
  }
}

function AdminRoutes({ location }) {
  return (
        <Switch location={location}>
          <AsyncRoute
            exact
            path="/admin/dashboard"
            load={loadAdminDashboardPage}
          />
          <AsyncRoute exact path="/commission" load={loadCommissionPage} />
          <AsyncRoute path="" load={loadNotFoundPage} />
        </Switch>
  );
}

when i hit the url /admin/dashboard i get the app page not the admin dashboard page and same with the
/commission which should be a child of AdminDashboard

How can i make my router work for different layout?

Body:
From Meteorchef Base, dedicated routing according to the user (loggingIn prop in this case):

Public.js, only for non admin, redirect if not :

import React from 'react';
import PropTypes from 'prop-types';
import { Route, Redirect } from 'react-router-dom';

const Public = ({ loggingIn, authenticated, component, ...rest }) => (
  <Route {...rest} render={(props) => {
    if (loggingIn) return <div></div>;
    return !authenticated ?
    (React.createElement(component, { ...props, loggingIn, authenticated })) :
    (<Redirect to="/account" />);
  }} />
);

Public.propTypes = {
  loggingIn: PropTypes.bool,
  authenticated: PropTypes.bool,
  component: PropTypes.func,
};

export default Public;

Authenticated.js, only for admin, also redirect if not :

import React from 'react';
import PropTypes from 'prop-types';
import { Route, Redirect } from 'react-router-dom';

const Authenticated = ({ loggingIn, authenticated, component, ...rest }) => (
  <Route {...rest} render={(props) => {
    if (loggingIn) return <div></div>;
    return authenticated ?
    (React.createElement(component, { ...props, loggingIn, authenticated })) :
    (<Redirect to="/login" />);
  }} />
);

Authenticated.propTypes = {
  loggingIn: PropTypes.bool,
  authenticated: PropTypes.bool,
  component: PropTypes.func,
};

export default Authenticated;

then in your App, (stateless in this case, but you can create a class as well too) :

// import everything

const App = appProps => (
  <Router>
      <div>
        <Switch>
          <Route exact name="index" path="/" component={Home} />
          <Authenticated exact path="/account" component={Account} {...appProps} />
          <Public path="/signup" component={Signup} {...appProps} />
          <Public path="/login" component={Login} {...appProps} />
          <Route component={NotFound} />
        </Switch>
      </div>
  </Router>
);

App.propTypes = {
  loggingIn: PropTypes.bool,
  authenticated: PropTypes.bool,
};


问:
how to merge two strings using c?
```<code>#include<stdio.h>

/* a function to merge two strings */

void stringMerge(char* f, char* s){

while(*f++);

while((*f++ = *s++));

}

int main(){

char s1[] = "Hello ";

char s2[] = "World";

stringMerge(s1,s2);

printf("%s",s1);

return 0;

}
</code>```

答:
I suggest you to use the strncat() from string.h. Here is your code:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
    char *s1 = "Hello ";
    char *s2 = "World\n";
    size_t s1_size = strlen(s1);
    size_t s2_size = strlen(s2);
    char *concat = calloc((s1_size + 1 + s2_size + 1), sizeof(char));
    if (concat == NULL) {
        perror("Calloc");
        exit(EXIT_FAILURE);
    }
    strncat(concat, s1, s1_size);
    strncat(concat, s2, s2_size);
    printf("%s", concat);
    free(concat);
    return 0;

}
</code>```

Title: how to merge two strings using c?

Body:
I suggest you to use the strncat() from string.h. Here is your code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
    char *s1 = "Hello ";
    char *s2 = "World\n";
    size_t s1_size = strlen(s1);
    size_t s2_size = strlen(s2);
    char *concat = calloc((s1_size + 1 + s2_size + 1), sizeof(char));
    if (concat == NULL) {
        perror("Calloc");
        exit(EXIT_FAILURE);
    }
    strncat(concat, s1, s1_size);
    strncat(concat, s2, s2_size);
    printf("%s", concat);
    free(concat);
    return 0;

}


问:
Finding all numbers in a array with top frequency?
I am trying to find out all the numbers with maximum frequency. i.e If maximum frequency is 5 then, I need all numbers that occurred 5 times in a array.

let us consider following example of array:

1 8 7 8 9 2 1 9 6 4 3 5

Here, Most frequent numbers are 8, 1, 9 with highest frequency of 2. My expected output is something like this:

```<code>8 => 2
1 => 2
9 => 2
</code>```

In my project, I am trying to find out most frequent numbers and least frequent numbers. Here I want just most frequent numbers.

I have generated 1000 random numbers similar to my project scenario and have calculated distinct numbers and then their occurrence.

```<code>    int n=100;
    int N=1000;

    int data[] = new int[N];
    Set<Integer> set = new HashSet<Integer>();

    Random random = new Random();

    for(int i=0;i<N;i++){
        int  number = random.nextInt(n);
        data[i] = number;
        set.add(number);
    }

    int frequency[] = new int[set.size()];
    Integer[] distinct = set.toArray(new Integer[set.size()]);

    for (int j=0;j<set.size();j++){
        int count=0;
        for(int k=0;k<N;k++){
            if(distinct[j]==data[k]){
                count = count+1;
            }
        }
        frequency[j] = count;
    }
</code>```

After calculating frequencies of each number, I have calculated numbers with most frequencies using answer from here which is optimized one.

```<code>    int max = Integer.MIN_VALUE;
    List<Integer> vals = new ArrayList<>();

    for (int q=0; q < frequency.length; ++q) {

        if (frequency[q] == max) {
            vals.add(q);
        }

        else if (frequency[q] > max) {
            vals.clear();
            vals.add(q);
            max = frequency[q];
        }
    }

    for(int num : vals){
        System.out.println(distinct[num]+" => "+frequency[num]);
    }
</code>```

Here, Loop in first code making whole process slower. This is only part of large code and sample test case.

I want to make the process faster since there may be large elements in the array in real case.

Anyone have way to optimize those loops ?
 or
some other way to get the result ?

Any kind of help is appreciated.

答:
I would use streams for this. It doens’t turn out to be very much shorter, but once you get comfortable with streams, it will be conceptually simpler.

```<code>    Map<Integer, Long> frequencies = Arrays.stream(data)
            .boxed()
            .collect(Collectors.groupingBy(i -> i, Collectors.counting()));
    if (frequencies.isEmpty()) {
        System.out.println("No data");
    } else {
        long topFrequency = frequencies.values()
                .stream()
                .max(Long::compareTo)
                .get();
        int[] topNumbers = frequencies.entrySet()
                .stream()
                .filter(e -> e.getValue() == topFrequency)
                .mapToInt(Map.Entry::getKey)
                .toArray();
        for (int number : topNumbers) {
            System.out.println("" + number + " => " + topFrequency);
        }
    }
</code>```

With the example data from the question it prints the desired (only in another unpredictable order):

```<code>1 => 2
8 => 2
9 => 2
</code>```

Edit: tucuxi asked: why not use the stream to print with too? You may do that of course, for shorter and yet simpler code:

```<code>        frequencies.entrySet()
                .stream()
                .filter(e -> e.getValue() == topFrequency)
                .mapToInt(Map.Entry::getKey)
                .forEach(n -> System.out.println("" + n + " => " + topFrequency));
</code>```

What to choose depends on both requirements and taste. I was expecting that the OP would need to store the top frequency numbers, so I demonstrated how to do that, and just printed them to show the result. Also some hold the ideal that streams should be free from side effects, where I would consider printing to standard output a side effect. But use it if you like.

Body:
I am trying to find out all the numbers with maximum frequency. i.e If maximum frequency is 5 then, I need all numbers that occurred 5 times in a array.

let us consider following example of array:

1 8 7 8 9 2 1 9 6 4 3 5

Here, Most frequent numbers are 8, 1, 9 with highest frequency of 2. My expected output is something like this:

8 => 2
1 => 2
9 => 2

In my project, I am trying to find out most frequent numbers and least frequent numbers. Here I want just most frequent numbers.

I have generated 1000 random numbers similar to my project scenario and have calculated distinct numbers and then their occurrence.

    int n=100;
    int N=1000;

    int data[] = new int[N];
    Set<Integer> set = new HashSet<Integer>();

    Random random = new Random();

    for(int i=0;i<N;i++){
        int  number = random.nextInt(n);
        data[i] = number;
        set.add(number);
    }

    int frequency[] = new int[set.size()];
    Integer[] distinct = set.toArray(new Integer[set.size()]);

    for (int j=0;j<set.size();j++){
        int count=0;
        for(int k=0;k<N;k++){
            if(distinct[j]==data[k]){
                count = count+1;
            }
        }
        frequency[j] = count;
    }

After calculating frequencies of each number, I have calculated numbers with most frequencies using answer from here which is optimized one.

    int max = Integer.MIN_VALUE;
    List<Integer> vals = new ArrayList<>();

    for (int q=0; q < frequency.length; ++q) {

        if (frequency[q] == max) {
            vals.add(q);
        }

        else if (frequency[q] > max) {
            vals.clear();
            vals.add(q);
            max = frequency[q];
        }
    }

    for(int num : vals){
        System.out.println(distinct[num]+" => "+frequency[num]);
    }

Here, Loop in first code making whole process slower. This is only part of large code and sample test case.

I want to make the process faster since there may be large elements in the array in real case.

Anyone have way to optimize those loops ?
 or
some other way to get the result ?

Any kind of help is appreciated.

Body:
I would use streams for this. It doens’t turn out to be very much shorter, but once you get comfortable with streams, it will be conceptually simpler.

    Map<Integer, Long> frequencies = Arrays.stream(data)
            .boxed()
            .collect(Collectors.groupingBy(i -> i, Collectors.counting()));
    if (frequencies.isEmpty()) {
        System.out.println("No data");
    } else {
        long topFrequency = frequencies.values()
                .stream()
                .max(Long::compareTo)
                .get();
        int[] topNumbers = frequencies.entrySet()
                .stream()
                .filter(e -> e.getValue() == topFrequency)
                .mapToInt(Map.Entry::getKey)
                .toArray();
        for (int number : topNumbers) {
            System.out.println("" + number + " => " + topFrequency);
        }
    }

With the example data from the question it prints the desired (only in another unpredictable order):

1 => 2
8 => 2
9 => 2

Edit: tucuxi asked: why not use the stream to print with too? You may do that of course, for shorter and yet simpler code:

        frequencies.entrySet()
                .stream()
                .filter(e -> e.getValue() == topFrequency)
                .mapToInt(Map.Entry::getKey)
                .forEach(n -> System.out.println("" + n + " => " + topFrequency));

What to choose depends on both requirements and taste. I was expecting that the OP would need to store the top frequency numbers, so I demonstrated how to do that, and just printed them to show the result. Also some hold the ideal that streams should be free from side effects, where I would consider printing to standard output a side effect. But use it if you like.


问:
search data in table column ignore special characters
I want to search a string in DB column by ignoring special characters i am working on MYSQL. I have word like

Manama - Alsalmaniya

and DB i have

Manama - Al-Salmaniya

can i search this word i only want to search alphabets match.Words are different not same always.
i have tried but its not matching this case my query

```<code>Select * from mainmwx_deliveryzone_areas where name_en LIKE 'Manama - Alsalmaniya'"
</code>```

its returning me 0 rows found.

答:
You can use it like this (with replace)

```<code>Select *
from mainmwx_deliveryzone_areas
where replace(name_en,'-','') LIKE replace('Manama - Alsalmaniya','-','')"
</code>```

so you won´t take account of '-'

Body:
I want to search a string in DB column by ignoring special characters i am working on MYSQL. I have word like

Manama - Alsalmaniya

and DB i have

Manama - Al-Salmaniya

can i search this word i only want to search alphabets match.Words are different not same always.
i have tried but its not matching this case my query

Select * from mainmwx_deliveryzone_areas where name_en LIKE 'Manama - Alsalmaniya'"

its returning me 0 rows found.

Body:
You can use it like this (with replace)

Select *
from mainmwx_deliveryzone_areas
where replace(name_en,'-','') LIKE replace('Manama - Alsalmaniya','-','')"

so you won´t take account of '-'


问:
UITableView inside static cell
i have a problem when put UITableView inside static cell of another UITableView in UITableViewController. If self.skillsTableView has more cells than self.tableView my app crashes with exeption:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayI objectAtIndex:]: index 6 beyond bounds [0 ..
  5]'

Here is my code:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *skillsCellIdentifier = @"skill_cell";
    if (tableView == self.skillsTableView) {
        NSLog(@"GET DYNAMIC %li", [tableView numberOfRowsInSection:0]);
        ServicesTableViewCell *cell = (ServicesTableViewCell*)[tableView dequeueReusableCellWithIdentifier:skillsCellIdentifier forIndexPath:indexPath];
        Services *skill = [self.servicesArray objectAtIndex:indexPath.row];
        cell.titleLabel.text = skill.title;
        cell.priceLabel.text = skill.price;
        return cell;
    }
    else {
        NSLog(@"GET STATIC %li", [super tableView:tableView numberOfRowsInSection:0]);
        return [super tableView:tableView cellForRowAtIndexPath:indexPath];
    }
}
</code>```

and:

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.skillsTableView) {
        NSLog(@"DYNAMIC -- %li", self.servicesArray.count);
        return self.servicesArray.count;
    }
    else {
        NSLog(@"Static == %li", [super tableView:tableView numberOfRowsInSection:section]);
        return [super tableView:tableView numberOfRowsInSection:section];
    }
}
</code>```

Output:

```<code>2014-05-28 09:19:55.461 SesApp[32289:60b] Static == 6
2014-05-28 09:19:55.461 SesApp[32289:60b] GET STATIC 6
2014-05-28 09:19:55.463 SesApp[32289:60b] GET STATIC 6
2014-05-28 09:19:55.464 SesApp[32289:60b] GET STATIC 6
2014-05-28 09:19:55.465 SesApp[32289:60b] GET STATIC 6
2014-05-28 09:19:55.466 SesApp[32289:60b] GET STATIC 6
2014-05-28 09:19:55.470 SesApp[32289:60b] DYNAMIC -- 0
2014-05-28 09:19:55.610 SesApp[32289:60b] Static == 6
2014-05-28 09:19:55.611 SesApp[32289:60b] DYNAMIC -- 7
2014-05-28 09:19:55.612 SesApp[32289:60b] GET STATIC 6
2014-05-28 09:19:55.613 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:19:55.617 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:19:55.619 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:19:55.621 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:19:55.623 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:19:55.625 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:19:55.627 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:23:08.897 SesApp[32289:60b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 6 beyond bounds [0 .. 5]'
</code>```

答:
I was also facing similar issue. When I checked the stack trace, it says there's issue in following method, which was throwing 'NSRangeException'

```<code>tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath)
</code>```

I did override the method to always return 0

```<code>override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
        return 0
}
</code>```

It's working now.

Title: UITableView inside static cell

Body:
i have a problem when put UITableView inside static cell of another UITableView in UITableViewController. If self.skillsTableView has more cells than self.tableView my app crashes with exeption:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayI objectAtIndex:]: index 6 beyond bounds [0 ..
  5]'

Here is my code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *skillsCellIdentifier = @"skill_cell";
    if (tableView == self.skillsTableView) {
        NSLog(@"GET DYNAMIC %li", [tableView numberOfRowsInSection:0]);
        ServicesTableViewCell *cell = (ServicesTableViewCell*)[tableView dequeueReusableCellWithIdentifier:skillsCellIdentifier forIndexPath:indexPath];
        Services *skill = [self.servicesArray objectAtIndex:indexPath.row];
        cell.titleLabel.text = skill.title;
        cell.priceLabel.text = skill.price;
        return cell;
    }
    else {
        NSLog(@"GET STATIC %li", [super tableView:tableView numberOfRowsInSection:0]);
        return [super tableView:tableView cellForRowAtIndexPath:indexPath];
    }
}

and:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.skillsTableView) {
        NSLog(@"DYNAMIC -- %li", self.servicesArray.count);
        return self.servicesArray.count;
    }
    else {
        NSLog(@"Static == %li", [super tableView:tableView numberOfRowsInSection:section]);
        return [super tableView:tableView numberOfRowsInSection:section];
    }
}

Output:

2014-05-28 09:19:55.461 SesApp[32289:60b] Static == 6
2014-05-28 09:19:55.461 SesApp[32289:60b] GET STATIC 6
2014-05-28 09:19:55.463 SesApp[32289:60b] GET STATIC 6
2014-05-28 09:19:55.464 SesApp[32289:60b] GET STATIC 6
2014-05-28 09:19:55.465 SesApp[32289:60b] GET STATIC 6
2014-05-28 09:19:55.466 SesApp[32289:60b] GET STATIC 6
2014-05-28 09:19:55.470 SesApp[32289:60b] DYNAMIC -- 0
2014-05-28 09:19:55.610 SesApp[32289:60b] Static == 6
2014-05-28 09:19:55.611 SesApp[32289:60b] DYNAMIC -- 7
2014-05-28 09:19:55.612 SesApp[32289:60b] GET STATIC 6
2014-05-28 09:19:55.613 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:19:55.617 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:19:55.619 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:19:55.621 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:19:55.623 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:19:55.625 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:19:55.627 SesApp[32289:60b] GET DYNAMIC 7
2014-05-28 09:23:08.897 SesApp[32289:60b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 6 beyond bounds [0 .. 5]'

Body:
I was also facing similar issue. When I checked the stack trace, it says there's issue in following method, which was throwing 'NSRangeException'

tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath)

I did override the method to always return 0

override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
        return 0
}

It's working now.


问:
Replacing occurrences of a number in specific columns from a data table
I've come across this post on how to replace occurrences of a number in all columns of a data frame (e.g. replace all 4 by 10 in all columns): DF[DF == 4] <- 10. With data tables the same results can be achieved in exactly the same way: DT[DT == 4] <- 10.

However, how should I procede if I want to apply this modification but only to specific columns from the data table, whether these columns are specified by position (e.g. 2:4) or by name (e.g. c("V2", "V3", "V4"))?

I will favor an "elegant" solution rather than iterations over every column.

答:
We can use set which would be more efficient

```<code>for(j in 2:4) {
  set(DT, i = which(DT[[j]]==4), j=j, value = 10)
 }
DT
#   V1 V2 V3 V4
#1:  A  2  2 10
#2:  B  1 10 10
#3:  C  3 10  3
#4:  D  3  2 10
#5:  E  3  3  3
#6:  F 10  3  3
</code>```

The above can be done with column names as well

```<code>for(j in names(DT)[2:4]){
   set(DT, i = which(DT[[j]]==4), j=j, value = 10)
 }
</code>```

Or another option is to specify the .SDcols with the columns of interest (either the numeric index or the column names), loop through the Subset of Data.table (.SD), replace the values that are 4 to 10 and assign (:=) the output back to columns of interest

```<code>DT[, (2:4) := lapply(.SD, function(x) replace(x, x==4, 10)), .SDcols = 2:4]
</code>```

Or with column names

```<code>DT[, (names(DT)[2:4]) := lapply(.SD, function(x) replace(x, x==4, 10)),
      .SDcols = names(DT)[2:4]]
</code>```

data

```<code>set.seed(24)
DT <- data.table(V1 = LETTERS[1:6], V2 = sample(1:4, 6, replace = TRUE),
   V3 = sample(2:4, 6, replace = TRUE), V4 = sample(3:4, 6, replace= TRUE))
</code>```

Body:
We can use set which would be more efficient

for(j in 2:4) {
  set(DT, i = which(DT[[j]]==4), j=j, value = 10)
 }
DT
#   V1 V2 V3 V4
#1:  A  2  2 10
#2:  B  1 10 10
#3:  C  3 10  3
#4:  D  3  2 10
#5:  E  3  3  3
#6:  F 10  3  3

The above can be done with column names as well

for(j in names(DT)[2:4]){
   set(DT, i = which(DT[[j]]==4), j=j, value = 10)
 }

Or another option is to specify the .SDcols with the columns of interest (either the numeric index or the column names), loop through the Subset of Data.table (.SD), replace the values that are 4 to 10 and assign (:=) the output back to columns of interest

DT[, (2:4) := lapply(.SD, function(x) replace(x, x==4, 10)), .SDcols = 2:4]

Or with column names

DT[, (names(DT)[2:4]) := lapply(.SD, function(x) replace(x, x==4, 10)),
      .SDcols = names(DT)[2:4]]

data

set.seed(24)
DT <- data.table(V1 = LETTERS[1:6], V2 = sample(1:4, 6, replace = TRUE),
   V3 = sample(2:4, 6, replace = TRUE), V4 = sample(3:4, 6, replace= TRUE))


问:
Subclipse synchronisation history?
In Eclipse (subclipse), is there a way to see the synchronisation history - i.e. not the individual files/directories history, but an history of

when synchronisation was performed,

what was synchronized?

答:
I'd say "no".

Maybe you could glean some of this info from Eclipse's log files. During synchronization, the individual SVN commands and results (such as U file.txt) are displayed in the console view, but I doubt that it gets saved anywhere, at least not by default.

You might also find something interesting in the HTTP access logs of the web server that hosts the repository.

Title: Subclipse synchronisation history?


问:
Cannot read property 'post' of undefined - Angular 2
Below is the code snippet from my component file

```<code>import { Component,Injectable,Inject,OnInit, OnDestroy, EventEmitter,Output } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/switchMap';
...
@Injectable()
export class MyComponent {
    constructor (private http: Http) { }
    saveDetails()
    {
        var response:any;
        var body       = customer_details;
        var headers    = new Headers({ 'Content-Type': 'application/json' });
        var options    = new RequestOptions({ headers: headers });
        this.http.post("/user/add-customer-details", body, options)
            .map((res:Response) => res.json()).subscribe(
                data => { response = data},
                err => console.error(err),
                () => {
                    console.log(response);
                }
        );
    }
}
</code>```

There is no compilation error or any other error but
when I am calling the post method it's saying Cannot read property 'post' of undefined so I tried console.log(this.http); right before the post method call, then its showing undefined in the browser console, I tried all the possible solutions but unable to understand why it's not working, please help...

thanks in advance!!!

答:
You have to add HTTP_PROVIDERS to either the component providers array like this:

```<code>providers: [HTTP_PROVIDERS]
</code>```

EDIT

HTTP_PROVIDERS is deprecated. Import the http module instead.

```<code>@NgModule({
    imports: [
        BrowserModule,
        HttpModule
        ],
    declarations: [AppComponent],
    providers: [],
    bootstrap: [AppComponent],
})
</code>```

Body:
Below is the code snippet from my component file

import { Component,Injectable,Inject,OnInit, OnDestroy, EventEmitter,Output } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/switchMap';
...
@Injectable()
export class MyComponent {
    constructor (private http: Http) { }
    saveDetails()
    {
        var response:any;
        var body       = customer_details;
        var headers    = new Headers({ 'Content-Type': 'application/json' });
        var options    = new RequestOptions({ headers: headers });
        this.http.post("/user/add-customer-details", body, options)
            .map((res:Response) => res.json()).subscribe(
                data => { response = data},
                err => console.error(err),
                () => {
                    console.log(response);
                }
        );
    }
}

There is no compilation error or any other error but
when I am calling the post method it's saying Cannot read property 'post' of undefined so I tried console.log(this.http); right before the post method call, then its showing undefined in the browser console, I tried all the possible solutions but unable to understand why it's not working, please help...

thanks in advance!!!

Body:
You have to add HTTP_PROVIDERS to either the component providers array like this:

providers: [HTTP_PROVIDERS]

EDIT

HTTP_PROVIDERS is deprecated. Import the http module instead.

@NgModule({
    imports: [
        BrowserModule,
        HttpModule
        ],
    declarations: [AppComponent],
    providers: [],
    bootstrap: [AppComponent],
})


问:
How does Node.js convert your code to events?
When you first run your Node program, how/what is the first event supplied to the event loop? Is your program like a top-level callback that is being executed the entire time? (And I would assume this top-level callback is usually "server.listen()"?)</p>

答:
I'm confused about whether the event loop exists outside of the "main" script (or entry point) being ran, or if the event loop runs the "main" script itself

Both, actually. The event loop is the mechanism that wraps all execution of js code, and won't stop as long as there are events to be awaited.

what is the first event supplied to the event loop?

It's the evaluation of the main script. (Or rather, the native node.js code that will eventually evaluate your main script is the thing that is put first on the V8 event loop).

Is your program like a top-level callback that is being executed the entire time?

No, nothing is executed the entire time, every callback is executed on its own.


答:
SELECT * FROM mainmwx_deliveryzone_areas WHERE MATCH(name_en) AGAINST('Manama - Alsalmaniya' IN BOOLEAN MODE)
```

Title: search data in table column ignore special characters


问:
Join three entities using spring data
i'm working with spring data in my project herers the entities:

rr:

```<code>@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long   id;
private String model;

@ManyToOne
@JoinColumn( name = "owner" )
private ffperson;
private String constructor;
//getters and setters
</code>```

zaa:

```<code>@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long   id;

@Column( name = "name" )
private String Name;
//getters and setters
</code>```

gff
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    private Long   id;

```<code>@Column( name = "lastname", unique = true )
private String lastName;

@Column( name = "firstname", unique = true )
private String firstName;

@Column( name = "birth_date", unique = true )
private Date   dateOfBirth;
</code>```

gfff:

```<code>@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long   id;

@ManyToOne
@JoinColumn( name = "dog_id" )
private ffdog;

@ManyToOne
@JoinColumn( name = "person_id" )
private ffperson;
</code>```

i want to write a query with spring data which can fetch all the persons with thier own dogs and cars..Can any body help please

答:
The easiest way to fetch them - change the current data model.

Person:

```<code>@Entity
public class Person {

    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    private Long id;

    @Column(name = "lastname")
    private String lastName;

    @Column(name = "firstname")
    private String firstName;

    @Column(name = "birth_date")
    private Date  dateOfBirth;

    @MayToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "PERSON_DOG",
               joinColumns = {@JoinColumn(name = "PERSON_ID")},
               inverseJoinColumns = {@JoinColumn(name = "DOG_ID")})
    private List<Dog> dogs = new ArrayList<>();

    @OneToMany(mappedBy = "person")
    private List<Car> cars = new ArrayList<>();
}
</code>```

Dog:

```<code>@Entity
public class Dog {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY )
    private Long  id;

    @Column(name = "name" )
    private String Name;
    //getters and setters
}
</code>```

Car:

```<code>@Entity
public class Car {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY )
    private Long  id;
    private String model;

    @ManyToOne
    @JoinColumn(name = "owner")
    @JsonIgnore // this will prevent the loop on response
    private Person person;

    private String constructor;
    //getters and setters
}
</code>```

Then just querying Person you will get all relations.

```<code>public interface PersonRepository extends CrudRepository<Person, Long> {
    List<Person> findAll();
}
</code>```

Also notice, that I've how created JoinTable. You don't need to do it manually, if you will not manage it on your own (sometimes it required if you will populate it with certain conditions or if you have additional column).

There is also some strange things in you model, why should first_name, last_name and date_of_birth are unique? Many persons may have similar data for these columns.

Title: Join three entities using spring data

Body:
i'm working with spring data in my project herers the entities:

rr:

@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long   id;
private String model;

@ManyToOne
@JoinColumn( name = "owner" )
private ffperson;
private String constructor;
//getters and setters

zaa:

@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long   id;

@Column( name = "name" )
private String Name;
//getters and setters

gff
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    private Long   id;

@Column( name = "lastname", unique = true )
private String lastName;

@Column( name = "firstname", unique = true )
private String firstName;

@Column( name = "birth_date", unique = true )
private Date   dateOfBirth;

gfff:

@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long   id;

@ManyToOne
@JoinColumn( name = "dog_id" )
private ffdog;

@ManyToOne
@JoinColumn( name = "person_id" )
private ffperson;

i want to write a query with spring data which can fetch all the persons with thier own dogs and cars..Can any body help please

Body:
The easiest way to fetch them - change the current data model.

Person:

@Entity
public class Person {

    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    private Long id;

    @Column(name = "lastname")
    private String lastName;

    @Column(name = "firstname")
    private String firstName;

    @Column(name = "birth_date")
    private Date  dateOfBirth;

    @MayToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "PERSON_DOG",
               joinColumns = {@JoinColumn(name = "PERSON_ID")},
               inverseJoinColumns = {@JoinColumn(name = "DOG_ID")})
    private List<Dog> dogs = new ArrayList<>();

    @OneToMany(mappedBy = "person")
    private List<Car> cars = new ArrayList<>();
}

Dog:

@Entity
public class Dog {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY )
    private Long  id;

    @Column(name = "name" )
    private String Name;
    //getters and setters
}

Car:

@Entity
public class Car {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY )
    private Long  id;
    private String model;

    @ManyToOne
    @JoinColumn(name = "owner")
    @JsonIgnore // this will prevent the loop on response
    private Person person;

    private String constructor;
    //getters and setters
}

Then just querying Person you will get all relations.

public interface PersonRepository extends CrudRepository<Person, Long> {
    List<Person> findAll();
}

Also notice, that I've how created JoinTable. You don't need to do it manually, if you will not manage it on your own (sometimes it required if you will populate it with certain conditions or if you have additional column).

There is also some strange things in you model, why should first_name, last_name and date_of_birth are unique? Many persons may have similar data for these columns.


问:
Connection string from web.config causing NullReferenceException
I have a local SQL Server database (managed via Management Studio) and a local
ASP.NET project. VS2017 correctly sees the database in the Server Explorer. This is also the place where I got my connection string; as recommended by a few posts on the internet. I placed the string next to the existing one (for the account management) in my web.config. The file looks like this:

```<code><configuration>
    <connectionStrings>
        <add name="DefaultConnection"
             connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Project-20170524124716.mdf;Initial Catalog=aspnet-Project-20170524124716;Integrated Security=True"
             providerName="System.Data.SqlClient" />
        <add name="MyLocalDb"
             connectionString="Data Source=MYLAPTOP;Initial Catalog=TestDb;Integrated Security=True;"
             providerName="System.Data.SqlClient" />
    </connectionStrings>
    <!--More things-->
</configuration>
</code>```

I try to access the second string like this:

```<code>string connString = ConfigurationManager.ConnectionStrings["MyLocalDb"].ConnectionString;
</code>```

Which is the way it's done here, here, here and here (among almost every other post on the subject). But, when I run the code I get the following exception:

System.NullReferenceException: Object reference not set to an instance of an object.

at ProjectUnitTests.DatabaseTests.TestConnection() in ProjectUnitTests\DatabaseTests.cs:line 16

I have the reference to using System.Configuration; set here. I'm also pretty sure that the formatting on my web.config is right, given this post made my recheck it about 10 times. I've tried removing the first string, but it had no effect.

The connection string is correct. When I use it directly in my code I can access the database.

Note that the code is run from another project; I have a class library that the code is running from. The Web.config file is in another project. I've read in my long search for the answer that this could be an issue; although I can't find more sources on this.

Edit:

On request; the entire method from the Unit Tests:

```<code>[TestMethod]
public void TestConnection()
{
    //Connection tester will be called from the constructor
    Database instance = Database.Instance(); //The Database class is in a class library. When calling the instance it will get the connection string itself
    string connString = ConfigurationManager.ConnectionStrings["TicketSlothLocalDb"].ConnectionString; //Test if I was able to get the string at all. Apparently this is never possible.
    Console.WriteLine(connString);
}
</code>```

The Database class:

```<code>    private Database()
    {
        openConnection();
    }

    public static Database Instance()
    {
        _instance = _instance ?? new Database();

        return _instance;
    }

    private void openConnection()
    {
        try
        {
            string connString = ConfigurationManager.ConnectionStrings["TicketSlothLocalDb"].ConnectionString;
            conn = new SqlConnection(connString);
            conn.Open();
            openConn = true;
            testConnection(); //Function with a small SQL query inside to verify that it is able to retrieve data from the database
        }
        catch (SqlException ex)
        {
            Console.WriteLine(ex);
            Console.WriteLine("Password is incorrect");
            connectionstring = null;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Threw other exception: {0}", ex);
        }
    }
</code>```

Why can't I access the web.config property here?

答:
You need to add the database entry to the config for your unit test project. This file would be called app.config and would be in the root folder of your unit test project. When the project builds, the file will 'become' dllname.config in your bin folder (the build process should take care of this for you).

(My assumption that this is true is based on this mention in the stack trace - ProjectUnitTests).

Body:
I have a local SQL Server database (managed via Management Studio) and a local
ASP.NET project. VS2017 correctly sees the database in the Server Explorer. This is also the place where I got my connection string; as recommended by a few posts on the internet. I placed the string next to the existing one (for the account management) in my web.config. The file looks like this:

<configuration>
    <connectionStrings>
        <add name="DefaultConnection"
             connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Project-20170524124716.mdf;Initial Catalog=aspnet-Project-20170524124716;Integrated Security=True"
             providerName="System.Data.SqlClient" />
        <add name="MyLocalDb"
             connectionString="Data Source=MYLAPTOP;Initial Catalog=TestDb;Integrated Security=True;"
             providerName="System.Data.SqlClient" />
    </connectionStrings>

</configuration>

I try to access the second string like this:

string connString = ConfigurationManager.ConnectionStrings["MyLocalDb"].ConnectionString;

Which is the way it's done here, here, here and here (among almost every other post on the subject). But, when I run the code I get the following exception:

System.NullReferenceException: Object reference not set to an instance of an object.

at ProjectUnitTests.DatabaseTests.TestConnection() in ProjectUnitTests\DatabaseTests.cs:line 16

I have the reference to using System.Configuration; set here. I'm also pretty sure that the formatting on my web.config is right, given this post made my recheck it about 10 times. I've tried removing the first string, but it had no effect.

The connection string is correct. When I use it directly in my code I can access the database.

Note that the code is run from another project; I have a class library that the code is running from. The Web.config file is in another project. I've read in my long search for the answer that this could be an issue; although I can't find more sources on this.

Edit:

On request; the entire method from the Unit Tests:

[TestMethod]
public void TestConnection()
{
    //Connection tester will be called from the constructor
    Database instance = Database.Instance(); //The Database class is in a class library. When calling the instance it will get the connection string itself
    string connString = ConfigurationManager.ConnectionStrings["TicketSlothLocalDb"].ConnectionString; //Test if I was able to get the string at all. Apparently this is never possible.
    Console.WriteLine(connString);
}

The Database class:

    private Database()
    {
        openConnection();
    }

    public static Database Instance()
    {
        _instance = _instance ?? new Database();

        return _instance;
    }

    private void openConnection()
    {
        try
        {
            string connString = ConfigurationManager.ConnectionStrings["TicketSlothLocalDb"].ConnectionString;
            conn = new SqlConnection(connString);
            conn.Open();
            openConn = true;
            testConnection(); //Function with a small SQL query inside to verify that it is able to retrieve data from the database
        }
        catch (SqlException ex)
        {
            Console.WriteLine(ex);
            Console.WriteLine("Password is incorrect");
            connectionstring = null;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Threw other exception: {0}", ex);
        }
    }

Why can't I access the web.config property here?


问:
How do i get "sed" to delete everything else but email address.
how do i get "sed" to delete everything else but email address. </p>

```<code>db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com
</code>```

答:
Does it have to be sed? What about grep? Here's how to use it with the regex you gave:

```<code>$ cat dbdump.txt
db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com
another line with two e-mail addresses <test@example.com> on it -- bob@example.org

$ grep -EiEio '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b' dbdump.txt
joesmith@gmail.com
test@example.com
bob@example.org
</code>```

The -o flag prints only the matching portions, i.e. just the e-mail addresses. -i makes the matching case insensitive. It even finds multiple e-mail addresses on the same line.

Edit: I couldn't resist the -EiEio. I suppose grep -Eio or egrep -io would also work...

Body:
how do i get "sed" to delete everything else but email address.

db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com

Body:
Does it have to be sed? What about grep? Here's how to use it with the regex you gave:

$ cat dbdump.txt
db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com
another line with two e-mail addresses <test@example.com> on it -- bob@example.org

$ grep -EiEio '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b' dbdump.txt
joesmith@gmail.com
test@example.com
bob@example.org

The -o flag prints only the matching portions, i.e. just the e-mail addresses. -i makes the matching case insensitive. It even finds multiple e-mail addresses on the same line.

Edit: I couldn't resist the -EiEio. I suppose grep -Eio or egrep -io would also work...


问:
How to remove an element from a list by index
How do I remove an element from a list by index?

I found list.remove(), but this slowly scans the list for an item by value.

答:
Use the del statement:

```<code>del listName[-N]
</code>```

For example, if you want to remove the last 3 items, your code should be:

```<code>del listName[-3:]
</code>```

For example, if you want to remove the last 8 items, your code should be:

```<code>del listName[-8:]
</code>```

OwnerDisplayName: Joan Venge

Body:
Use the del statement:

del listName[-N]

For example, if you want to remove the last 3 items, your code should be:

del listName[-3:]

For example, if you want to remove the last 8 items, your code should be:

del listName[-8:]