问:
Preserve multi-column sort in AdvancedDataGrid with dataProvider as GroupingCollection
I have three attributes in my XML object: last name, first name, and age.
My sample XML looks like:

```<code><dataXML>
 <info last="Abc" first="Def" age="20"/>
 <info last="Abc" first="Hij" age="10"/>
 <info last="Xyz" first="Klm" age="25"/>
 <info last="Xyz" first="Opq" age="64"/>
 <info last="Xyz" first="Rst" age="08"/>
</dataXML>
</code>```

I am using Grouping Collection and AdvancedDataGrid to show the data.
My problem is to preserve multi-column sort.
After a refresh happens, the user selected sorting order goes away, and the grid gets sorted by first column only.
So suppose, user has sorted the table, first ascending by "Age" and then descending by "Name"; after a refresh happens, the grid again gets sorted ascending by "Name".
I don't want the refresh event to change the sort order, only the data should get refreshed.

Thanks in advance.

P.S. I can't use any other datatype like ArrayCollection, to store the data.

Part of my code looks as follows:

```<code><mx:Script>
<![CDATA[
 [Bindable]
 private var dataXML:XMLListCollection = new XMLListCollection();

 private function refresh(data:Object):void
 {
  dataXML.source = XML(data.result.value).info;
  gc.refresh();
  adGrid.dataProvider = gc;
  adGrid.validateNow();
  adGrid.dataProvider.refresh();
 }

 private function nameCompareFunction(a:XML, b:XML):int
 {
  return ObjectUtil.stringCompare(a.attribute("last") + a.attribute("first"), b.attribute("last") + b.attribute("first"));
 }

 private function valueSortCompareFunction(a:XML, b:XML):int
 {
  return ObjectUtil.numericCompare(Number(a.attribute("age")), Number(b.attribute("age")));
 }
]]>
</mx:Script>

<Control:AdvancedDataGrid id="adGrid">
 <Control:dataProvider>
  <mx:GroupingCollection id="gc" source="{dataXML}">
   <mx:grouping>
    <mx:Grouping>
     <mx:GroupingField name="@last" compareFunction="nameCompareFunction"/>
    </mx:Grouping>
   </mx:grouping>
  </mx:GroupingCollection>
 </Control:dataProvider>

 <Control:columns>
  <mx:AdvancedDataGridColumn id="ADGCName" dataField="@first" headerText="Name" wordWrap="true"/>
  <mx:AdvancedDataGridColumn id="ADGCAge" dataField="@age" headerText="Age" sortCompareFunction="valueSortCompareFunction"/>
 </Control:columns>
</Control:AdvancedDataGrid>
</code>```

答:
I think JTtheGeek's anwser is not quite correct. The code would just work when you sort on one column. Because except the descending order, you also need to remember the priority between different columns in sorting.

In fact, it is so easy, create a temp sort object to store the sort in the dataProvider, and then restore it after you apply the new dataProver, then refresh it.

Body:
I have three attributes in my XML object: last name, first name, and age.
My sample XML looks like:

<dataXML>
 <info last="Abc" first="Def" age="20"/>
 <info last="Abc" first="Hij" age="10"/>
 <info last="Xyz" first="Klm" age="25"/>
 <info last="Xyz" first="Opq" age="64"/>
 <info last="Xyz" first="Rst" age="08"/>
</dataXML>

I am using Grouping Collection and AdvancedDataGrid to show the data.
My problem is to preserve multi-column sort.
After a refresh happens, the user selected sorting order goes away, and the grid gets sorted by first column only.
So suppose, user has sorted the table, first ascending by "Age" and then descending by "Name"; after a refresh happens, the grid again gets sorted ascending by "Name".
I don't want the refresh event to change the sort order, only the data should get refreshed.

Thanks in advance.

P.S. I can't use any other datatype like ArrayCollection, to store the data.

Part of my code looks as follows:

<mx:Script>
<![CDATA[
 [Bindable]
 private var dataXML:XMLListCollection = new XMLListCollection();

 private function refresh(data:Object):void
 {
  dataXML.source = XML(data.result.value).info;
  gc.refresh();
  adGrid.dataProvider = gc;
  adGrid.validateNow();
  adGrid.dataProvider.refresh();
 }

 private function nameCompareFunction(a:XML, b:XML):int
 {
  return ObjectUtil.stringCompare(a.attribute("last") + a.attribute("first"), b.attribute("last") + b.attribute("first"));
 }

 private function valueSortCompareFunction(a:XML, b:XML):int
 {
  return ObjectUtil.numericCompare(Number(a.attribute("age")), Number(b.attribute("age")));
 }
]]>
</mx:Script>

<Control:AdvancedDataGrid id="adGrid">
 <Control:dataProvider>
  <mx:GroupingCollection id="gc" source="{dataXML}">
   <mx:grouping>
    <mx:Grouping>
     <mx:GroupingField name="@last" compareFunction="nameCompareFunction"/>
    </mx:Grouping>
   </mx:grouping>
  </mx:GroupingCollection>
 </Control:dataProvider>

 <Control:columns>
  <mx:AdvancedDataGridColumn id="ADGCName" dataField="@first" headerText="Name" wordWrap="true"/>
  <mx:AdvancedDataGridColumn id="ADGCAge" dataField="@age" headerText="Age" sortCompareFunction="valueSortCompareFunction"/>
 </Control:columns>
</Control:AdvancedDataGrid>


来源: stackexchange

问:
Response object is not defined when passed in a function
I am using Facebook Graph NodeJS API to fetch user_posts. The response has pagination and therefore I need to loop over the response to fetch all the posts. I am using following route to fetch facebook posts and I am looping over pagination using get_user_statuses function:

```<code>var posts = "";

function get_user_statuses(response_posts, res) {

    var link_regex = /https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,}/g;
    var isNextPageAvailable = true;

    if ("paging" in response_posts) {
        var nextPage = response_posts.paging.next;
        isNextPageAvailable = true;

    } else {
        isNextPageAvailable = false;
    }

    for (var i = 0; i < response_posts.data.length; i++) {

        var post = response_posts.data[i].message + " ";

        if ("message" in response_posts.data[i]) {
            posts += post.replace(link_regex, "");
        }
    }

    if (nextPage !== undefined) {
        request(nextPage, function (error, response, body) {

            if (!error && response.statusCode === 200) {
                get_user_statuses(JSON.parse(body));

            } else {
                console.log(error);
            }
        });
    }

    if (!isNextPageAvailable){
        //Sending posts to facebook Modal
        console.log(posts);
        res.send(JSON.stringify({posts: posts}));    //res is not defined here
    }
}

router.post('/fbData', function (req, response, next) {

    FB.setAccessToken(req.body.access_token);
    FB.api('/me?fields=posts&posts.limit=1000', function (res) {

        if (!res || res.error) {
            if (!res) {
                response.send(JSON.stringify({error: 'An error occurred. Please try again.'}))
            }
            response.send(JSON.stringify({error: response.error}));
            return;
        }

        get_user_statuses(res.posts, response);   //Passing response object here

    });
});
</code>```

The issue is that response object passed from express route is not defined in get_user_statuses function. Now I have two question:

Why is response object is not defined?

Is there better approach to achieve this arrangement?

答: res is not defined because  you forgot to pass it in internal call. Change get_user_statuses(JSON.parse(body)); to get_user_statuses(JSON.parse(body), res); and it should work

ContentLicense: CC BY-SA 3.0

Body:
I am using Facebook Graph NodeJS API to fetch user_posts. The response has pagination and therefore I need to loop over the response to fetch all the posts. I am using following route to fetch facebook posts and I am looping over pagination using get_user_statuses function:

var posts = "";

function get_user_statuses(response_posts, res) {

    var link_regex = /https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,}/g;
    var isNextPageAvailable = true;

    if ("paging" in response_posts) {
        var nextPage = response_posts.paging.next;
        isNextPageAvailable = true;

    } else {
        isNextPageAvailable = false;
    }

    for (var i = 0; i < response_posts.data.length; i++) {

        var post = response_posts.data[i].message + " ";

        if ("message" in response_posts.data[i]) {
            posts += post.replace(link_regex, "");
        }
    }

    if (nextPage !== undefined) {
        request(nextPage, function (error, response, body) {

            if (!error && response.statusCode === 200) {
                get_user_statuses(JSON.parse(body));

            } else {
                console.log(error);
            }
        });
    }

    if (!isNextPageAvailable){
        //Sending posts to facebook Modal
        console.log(posts);
        res.send(JSON.stringify({posts: posts}));    //res is not defined here
    }
}

router.post('/fbData', function (req, response, next) {

    FB.setAccessToken(req.body.access_token);
    FB.api('/me?fields=posts&posts.limit=1000', function (res) {

        if (!res || res.error) {
            if (!res) {
                response.send(JSON.stringify({error: 'An error occurred. Please try again.'}))
            }
            response.send(JSON.stringify({error: response.error}));
            return;
        }

        get_user_statuses(res.posts, response);   //Passing response object here

    });
});

The issue is that response object passed from express route is not defined in get_user_statuses function. Now I have two question:

Why is response object is not defined?

Is there better approach to achieve this arrangement?


问:
How to fix this fibonacci batch lister?
I've researched about operand and operators, set /a , and setlocal EnableDelayedExpansion from this website but still somehow my code ends up telling
me that my operand is missing.

```<code>@echo off
cls
setlocal EnableDelayedExpansion
color 0a
title Fibonacci Lister
:Fibonacci
cls
set /a n1=1
echo %n1%
set /a n2=1
echo %n2%
set /a j=3
:loopfunction
set /a n%j%=!n%j-1%!+!n%j-2%!
echo !n%j%!
set /a j=%j%+1
goto :loopfunction
</code>```

So I wanted to know what is the problem here. It is probably in line 14 where
the code is complex and hard to understand easily.

答:
<pre class="lang-dos prettyprint-override"><code>@echo off
    setlocal enableextensions disabledelayedexpansion
    set n1=0
    set n2=1
:loop
    echo %n2%
    set /a "n2=n1+n2" & set "n1=%n2%"
    if %n2% gtr 0 goto loop
</code>```

Title: How to fix this fibonacci batch lister?

Body:
I've researched about operand and operators, set /a , and setlocal EnableDelayedExpansion from this website but still somehow my code ends up telling
me that my operand is missing.

@echo off
cls
setlocal EnableDelayedExpansion
color 0a
title Fibonacci Lister
:Fibonacci
cls
set /a n1=1
echo %n1%
set /a n2=1
echo %n2%
set /a j=3
:loopfunction
set /a n%j%=!n%j-1%!+!n%j-2%!
echo !n%j%!
set /a j=%j%+1
goto :loopfunction

So I wanted to know what is the problem here. It is probably in line 14 where
the code is complex and hard to understand easily.


问:
gmock EXPECT_CALL does not invoke the method in tested class
I am new to gmock testing. I have Foo class which has member functions set() and start(). Start() triggers set() and class members member1 set to 1 , member2 is set to 2. When i try to test this in gmock i could not see these members are set.Why and how can i resolve this? Thanks.

test.h file

```<code>#ifndef TEST_H_
#define TEST_H_

#include <gtest/gtest.h>
#include <gmock/gmock.h>

class Foo
{
public:
    Foo();
    virtual~Foo();
    int member1;
    int member2;
    virtual void set();
    virtual void start();
};

class MockFoo:public Foo
{
public:
    MOCK_METHOD0(set, void());

};

#endif /* TEST_H_ */
</code>```

simpleGmock.cpp file

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

using ::testing::AtLeast;
using ::testing::Return;

Foo::Foo(){};
Foo::~Foo(){};
void Foo::set()
{
    member1=1;
    member2=2;
}
void Foo::start()
{
    this->set();
}

TEST(simplesuite, callmethods)
{
    MockFoo mockfoo_obj;

    EXPECT_CALL(mockfoo_obj, set())
          .Times(AtLeast(1))
          .WillOnce(::testing::Return());

    mockfoo_obj.start();

    ASSERT_EQ(mockfoo_obj.member1,1);

}
int main( int argc, char *argv[] ) {
    ::testing::InitGoogleMock( &argc, argv );
    return RUN_ALL_TESTS( );
}
</code>```

and the result is below:

```<code>[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from simplesuite
[ RUN      ] simplesuite.callmethods
simpleGmock.cpp:39: Failure
      Expected: mockfoo_obj.member1
      Which is: -528070912
To be equal to: 1
[  FAILED  ] simplesuite.callmethods (0 ms)
[----------] 1 test from simplesuite (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] simplesuite.callmethods

 1 FAILED TEST
</code>```

答:
Try removing .WillOnce(::testing::Return()) since it will cause Foo::set() not to be called since you are mocking the function.

You might need to manually invoke Foo::set() after EXPECT_CALL since after you mock a method the overridden function is not called anymore. Try adding .WillOnce( Invoke( this, &Foo::set ) )

Body:
I am new to gmock testing. I have Foo class which has member functions set() and start(). Start() triggers set() and class members member1 set to 1 , member2 is set to 2. When i try to test this in gmock i could not see these members are set.Why and how can i resolve this? Thanks.

test.h file

#ifndef TEST_H_
#define TEST_H_

#include <gtest/gtest.h>
#include <gmock/gmock.h>

class Foo
{
public:
    Foo();
    virtual~Foo();
    int member1;
    int member2;
    virtual void set();
    virtual void start();
};

class MockFoo:public Foo
{
public:
    MOCK_METHOD0(set, void());

};

#endif /* TEST_H_ */

simpleGmock.cpp file

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

using ::testing::AtLeast;
using ::testing::Return;

Foo::Foo(){};
Foo::~Foo(){};
void Foo::set()
{
    member1=1;
    member2=2;
}
void Foo::start()
{
    this->set();
}

TEST(simplesuite, callmethods)
{
    MockFoo mockfoo_obj;

    EXPECT_CALL(mockfoo_obj, set())
          .Times(AtLeast(1))
          .WillOnce(::testing::Return());

    mockfoo_obj.start();

    ASSERT_EQ(mockfoo_obj.member1,1);

}
int main( int argc, char *argv[] ) {
    ::testing::InitGoogleMock( &argc, argv );
    return RUN_ALL_TESTS( );
}

and the result is below:

[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from simplesuite
[ RUN      ] simplesuite.callmethods
simpleGmock.cpp:39: Failure
      Expected: mockfoo_obj.member1
      Which is: -528070912
To be equal to: 1
[  FAILED  ] simplesuite.callmethods (0 ms)
[----------] 1 test from simplesuite (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] simplesuite.callmethods

 1 FAILED TEST


问:
Form Submission in Django without Page Refresh using AJAX
I'm a newbie in python so this might be fixed easily.

I'm trying to do a register form using Jquery with Django.
I've been following this tutorial

when I click on the button it shows me the success message in the alert but nothing is inserted in the database.

Here is my code :

register.html

```<code><body>
<form id="add_user_form">

    {% csrf_token %}

    {# label et input du uti_login de la class Form#}
    <label for="UTI_LOGIN">Insérer un surnom d'utilisateur</label>
    <input id="UTI_LOGIN" type="text" name="UTI_LOGIN">
    <br>
        {# label et input du UTI_NOM de la class LoginForm#}
    <label for="UTI_NOM">Insérer un nom d'utilisateur</label>
    <input id="UTI_NOM" type="text" name="UTI_NOM">
    <br>
        {# label et input du UTI_PRENOM de la class LoginForm#}
    <label for="UTI_PRENOM">Insérer un prenom d'utilisateur</label>
    <input id="UTI_PRENOM" type="text" name="UTI_PRENOM">
    <br>
        {# label et input du UTI_CIVILITE de la class LoginForm#}
    <label for="UTI_CIVILITE">Insérer un civilite d'utilisateur</label>
    <input id="UTI_CIVILITE" type="text" name="UTI_CIVILITE">
    <br>
        {# label et input du UTI_EMAIL de la class LoginForm#}
    <label for="UTI_EMAIL">Insérer un email d'utilisateur</label>
    <input id="UTI_EMAIL" type="text" name="UTI_EMAIL">
    <br>
    {# label et input du uti_mdp de la class LoginForm#}
    <label for="UTI_MDP">Insérer mot de passe</label>
    <input id="UTI_MDP" type="password" name="UTI_MDP">
    <br>

    <label for="UTI_SUPPRIME">Hidden label checked</label>
    <input id="UTI_SUPPRIME" type="checkbox" hidden checked>
    <br>
    <br>
    <input value="S'inscrire ! ☺" type="submit">
</form>

</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).on('submit','#add_user_form',function (e) {
{#                    prevent the page getting refreshed#}
            e.preventDefault();

            $.ajax({
                type:'POST',
                url: 'registerSearch',
                data:{
                    username:$('#UTI_LOGIN').val(),
                    mdp:$('#UTI_MDP').val(),
                    nom:$('#UTI_NOM').val(),
                    prenom:$('#UTI_PRENOM').val(),
                    civilite:$('#UTI_CIVILITE').val(),
                    email:$('#UTI_EMAIL').val(),
                    supp:$('#UTI_SUPPRIME').val(),
                    csrfmiddlewaretoken: $('input[name = csrfmiddlewaretoken]').val()
                },
                success:function () {
                    alert("Utilisateur crée !");
                }

            })
        });
    </script>
</html>
</code>```

urls.py

```<code>from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'register', views.register_list, name='register'),
    url(r'registerSearch', views.registersearch_list),
]
</code>```

views.py

```<code>def register_list(request):
    return render(request, 'esigapp/register.html', {})

def registersearch_list(request):
    if request.method == 'POST':
        username = request.POST['username']
        mdp = request.POST['mdp']
        nom = request.POST['nom']
        prenom = request.POST['prenom']
        civil = request.POST['civilite']
        email = request.POST['email']
        supp = request.POST['supp']

        Sie_utilisateur.objects.create(
            UTI_LOGIN=username,
            UTI_MDP=mdp,
            UTI_NOM=nom,
            UTI_PRENOM=prenom,
            UTI_CIVILITE=civil,
            UTI_EMAIL=email,
            UTI_SUPPRIME=supp
        )
    return HttpResponse('')
</code>```

and finally

models.py

```<code>class Sie_utilisateur(models.Model):
    UTI_LOGIN = models.CharField(max_length=50)

    UTI_MDP = models.CharField(max_length=50)

    UTI_NOM = models.CharField(max_length=50)

    UTI_PRENOM = models.CharField(max_length=50)

    UTI_CIVILITE = models.CharField(max_length=1)

    UTI_EMAIL = models.CharField(max_length=50)

    UTI_SUPPRIME = models.BooleanField()

    def __str__(self):
        return self.UTI_NOM
</code>```

Some tips are also useful :)
Thanks

答:
The problem is not Ajax. It's simply that you didn't anchor or terminate your URL patterns; so the URL "/registerSearch" matches the first one, "register".

Make sure you use beginning and end anchors:

```<code>url(r'^register$', views.register_list, name='register'),
url(r'^registerSearch$', views.registersearch_list),
</code>```

You should probably also return something explicit in your registerSearch view so that your Ajax knows that the item has actually been created.

Body:
I'm a newbie in python so this might be fixed easily.

I'm trying to do a register form using Jquery with Django.
I've been following this tutorial

when I click on the button it shows me the success message in the alert but nothing is inserted in the database.

Here is my code :

register.html

<form id="add_user_form">

    {% csrf_token %}

    {# label et input du uti_login de la class Form#}
    Insérer un surnom d'utilisateur
    <input id="UTI_LOGIN" type="text" name="UTI_LOGIN">

        {# label et input du UTI_NOM de la class LoginForm#}
    Insérer un nom d'utilisateur
    <input id="UTI_NOM" type="text" name="UTI_NOM">

        {# label et input du UTI_PRENOM de la class LoginForm#}
    Insérer un prenom d'utilisateur
    <input id="UTI_PRENOM" type="text" name="UTI_PRENOM">

        {# label et input du UTI_CIVILITE de la class LoginForm#}
    Insérer un civilite d'utilisateur
    <input id="UTI_CIVILITE" type="text" name="UTI_CIVILITE">

        {# label et input du UTI_EMAIL de la class LoginForm#}
    Insérer un email d'utilisateur
    <input id="UTI_EMAIL" type="text" name="UTI_EMAIL">

    {# label et input du uti_mdp de la class LoginForm#}
    Insérer mot de passe
    <input id="UTI_MDP" type="password" name="UTI_MDP">

    Hidden label checked
    <input id="UTI_SUPPRIME" type="checkbox" hidden checked>

    <input value="S'inscrire ! ☺" type="submit">
</form>

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'register', views.register_list, name='register'),
    url(r'registerSearch', views.registersearch_list),
]

views.py

def register_list(request):
    return render(request, 'esigapp/register.html', {})

def registersearch_list(request):
    if request.method == 'POST':
        username = request.POST['username']
        mdp = request.POST['mdp']
        nom = request.POST['nom']
        prenom = request.POST['prenom']
        civil = request.POST['civilite']
        email = request.POST['email']
        supp = request.POST['supp']

        Sie_utilisateur.objects.create(
            UTI_LOGIN=username,
            UTI_MDP=mdp,
            UTI_NOM=nom,
            UTI_PRENOM=prenom,
            UTI_CIVILITE=civil,
            UTI_EMAIL=email,
            UTI_SUPPRIME=supp
        )
    return HttpResponse('')

and finally

models.py

class Sie_utilisateur(models.Model):
    UTI_LOGIN = models.CharField(max_length=50)

    UTI_MDP = models.CharField(max_length=50)

    UTI_NOM = models.CharField(max_length=50)

    UTI_PRENOM = models.CharField(max_length=50)

    UTI_CIVILITE = models.CharField(max_length=1)

    UTI_EMAIL = models.CharField(max_length=50)

    UTI_SUPPRIME = models.BooleanField()

    def __str__(self):
        return self.UTI_NOM

Some tips are also useful :)
Thanks

Body:
The problem is not Ajax. It's simply that you didn't anchor or terminate your URL patterns; so the URL "/registerSearch" matches the first one, "register".

Make sure you use beginning and end anchors:

url(r'^register$', views.register_list, name='register'),
url(r'^registerSearch$', views.registersearch_list),

You should probably also return something explicit in your registerSearch view so that your Ajax knows that the item has actually been created.


问:
Function to find maximum of 3 variables isn't returning anything
What is my problem? I run biggest(10,5,6) but it returns nothing.

```<code>def biggest(a,y,z):
    Max=a
    if y>Max:
        Max=y
        if z>Max:
            Max=z
            return Max
</code>```

答:
I'll just paste it here in case some new python student gets here. </p>

```<code>def biggest (a, b, c):
    imax = a
    if (b > imax) and (b > c):
            imax = b
    elif (c > imax):
            imax = c
    return imax

#to test
print (biggest(5,6,7))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What is my problem? I run biggest(10,5,6) but it returns nothing.

def biggest(a,y,z):
    Max=a
    if y>Max:
        Max=y
        if z>Max:
            Max=z
            return Max

Body:
I'll just paste it here in case some new python student gets here.

def biggest (a, b, c):
    imax = a
    if (b > imax) and (b > c):
            imax = b
    elif (c > imax):
            imax = c
    return imax

#to test
print (biggest(5,6,7))


问:
How to solve border overlapping issue in UITableViewCell?
I am adding border to the UITableViewCell. Below is the code:

Try-1:

```<code>cell.layer.borderWidth = 1;
cell.layer.borderColor = [UIColor redColor].CGColor;
</code>```

Try-2:

```<code>cell.contentView.layer.borderWidth = 1;
cell.contentView.layer.borderColor = [UIColor redColor].CGColor;
</code>```

I have tried both these ways, here is the output.

As you can find in image, border is overlapping inbetween two cells, because of this color gets darker then the border cells.

Why I have not added table border?

The problem is, I am using three diff custom cells in single table, according to data, particular cell is loading

Hence I am not able to add border color to entire uitableview or unable to draw cell borders in cellforrowatindexpath. Because in that method only I am checking which type of data it is, and accordingly custom cell has been loaded.

Here is my cellForRowAtIndexPath:

```<code>- (UITableViewCell*) getTableViewCellForTraining:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath withTrainingInfo:(TrainingInfoiOS*)trainingInfo
{
    BeLearnPlatform& ptr = BeLearnPlatform::GetLearnPlatform();

    static NSString *CustomCellIdentifier = @"CustomCell";
    CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier forIndexPath:indexPath];
    cell.courseNameLabel.text = trainingInfo.courseName;
    cell.courseStartButton.sectionID = indexPath.section;
    cell.courseStartButton.rowID = indexPath.row;
    cell.tag=0;
 ...
}
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell* cell = nil;
        NSString* dictionaryKey = [self createKeyWithSection:indexPath.section andRow:indexPath.row];
        NSObject* dataObject = [tableViewMappig objectForKey:dictionaryKey];

        if([dataObject isKindOfClass:[MasterCourse class]])
            {
            UITableViewCell* cell = [self getTableViewCellForTraining:tableView cellForRowAtIndexPath:indexPath withTrainingInfo:(MasterCourse*)dataObject];
            return cell;
            }
        else if([dataObject isKindOfClass:[ParentCourse class]])
            {
            UITableViewCell* cell = [self getTableViewCellForParentCourse:tableView cellForRowAtIndexPath:indexPath withTrainingInfo:(ParentCourse*)dataObject];
            return cell;
            }
</code>```

Please suggest me solution for this.

答:
```<code>@implementation BaseTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    UIView *myBackView = [[UIView alloc] initWithFrame:self.frame];
    self.backgroundColor = [UIColor clearColor];
    myBackView.backgroundColor = [UIColor clearColor];

    self.backgroundView = myBackView;
    self.backgroundView.layer.borderWidth = 2.0;
    self.backgroundView.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor;

    self.borderTop = [CALayer layer]; self.borderBottom = [CALayer layer];
    self.borderTop.borderColor = self.tintColor.CGColor; self.borderBottom.borderColor = self.tintColor.CGColor;
    self.borderTop.frame = CGRectMake(0, 0, self.frame.size.width, 2);
    self.borderTop.frame = CGRectMake(0, self.bounds.size.height, self.frame.size.width, 2);
    self.borderTop.borderWidth = 2.0; self.borderBottom.borderWidth = 2.0;
    [self.contentView.layer addSublayer:self.borderTop];
    [self.contentView.layer addSublayer:self.borderBottom];
    self.borderTop.hidden = YES; self.borderBottom.hidden = YES;
    self.clipsToBounds = NO;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
    // set selection color
    UIView *myBackView = [[UIView alloc] initWithFrame:self.frame];
    self.selectedBackgroundView = myBackView;
    self.borderTop.hidden = selected ? NO : YES;
    self.borderBottom.hidden = selected ? NO : YES;
    self.clipsToBounds = selected ? NO : YES;

    myBackView.backgroundColor = [UIColor clearColor];
    myBackView.layer.borderColor = selected ?  self.tintColor.CGColor : [UIColor groupTableViewBackgroundColor].CGColor;
    myBackView.layer.borderWidth = 2.0;
}

-(void)layoutSubviews {
    [super layoutSubviews];

    CGRect r;
    UIView *defaultAccessoryView = self.subviews.lastObject;
    r = defaultAccessoryView.frame;
    r.origin.x = self.bounds.size.width - 50;
    r.origin.y = - self.bounds.size.height/2 + 50;
    defaultAccessoryView.frame = r;

    CGRect frameBack = self.bounds;
    frameBack.size.height += 2;
    self.backgroundView.frame = frameBack;
    self.selectedBackgroundView.frame = frameBack;
}

@end
</code>```

Body:
I am adding border to the UITableViewCell. Below is the code:

Try-1:

cell.layer.borderWidth = 1;
cell.layer.borderColor = [UIColor redColor].CGColor;

Try-2:

cell.contentView.layer.borderWidth = 1;
cell.contentView.layer.borderColor = [UIColor redColor].CGColor;

I have tried both these ways, here is the output.

As you can find in image, border is overlapping inbetween two cells, because of this color gets darker then the border cells.

Why I have not added table border?

The problem is, I am using three diff custom cells in single table, according to data, particular cell is loading

Hence I am not able to add border color to entire uitableview or unable to draw cell borders in cellforrowatindexpath. Because in that method only I am checking which type of data it is, and accordingly custom cell has been loaded.

Here is my cellForRowAtIndexPath:

- (UITableViewCell*) getTableViewCellForTraining:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath withTrainingInfo:(TrainingInfoiOS*)trainingInfo
{
    BeLearnPlatform& ptr = BeLearnPlatform::GetLearnPlatform();

    static NSString *CustomCellIdentifier = @"CustomCell";
    CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier forIndexPath:indexPath];
    cell.courseNameLabel.text = trainingInfo.courseName;
    cell.courseStartButton.sectionID = indexPath.section;
    cell.courseStartButton.rowID = indexPath.row;
    cell.tag=0;
 ...
}
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell* cell = nil;
        NSString* dictionaryKey = [self createKeyWithSection:indexPath.section andRow:indexPath.row];
        NSObject* dataObject = [tableViewMappig objectForKey:dictionaryKey];

        if([dataObject isKindOfClass:[MasterCourse class]])
            {
            UITableViewCell* cell = [self getTableViewCellForTraining:tableView cellForRowAtIndexPath:indexPath withTrainingInfo:(MasterCourse*)dataObject];
            return cell;
            }
        else if([dataObject isKindOfClass:[ParentCourse class]])
            {
            UITableViewCell* cell = [self getTableViewCellForParentCourse:tableView cellForRowAtIndexPath:indexPath withTrainingInfo:(ParentCourse*)dataObject];
            return cell;
            }

Please suggest me solution for this.


问:
Android RecyclerView: drag and drop over multiple ViewType
I implement drag and drop for a RecyclerView, it works well when have one View type but reset the RecyclerView when have multiple view type, I show the result in this gif:

and this is my code:

```<code>public class RecyclerListAdapter extends RecyclerView.Adapter<ItemViewHolder> {

    private final Integer[] INVOICE_ITEMS_LIST = new Integer[]{
            INVOICE_DESIGN_TITLE,
            INVOICE_DESIGN_TITLE,
            INVOICE_DESIGN_LOGO,
            INVOICE_DESIGN_TITLE
    };

    public RecyclerListAdapter() {
        mItems.addAll(Arrays.asList(INVOICE_ITEMS_LIST));
    }

    @Override
    public int getItemViewType(int position) {
        return INVOICE_ITEMS_LIST[position];
    }

    @Override
    public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        switch (viewType){
            case INVOICE_DESIGN_TITLE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.invoice_design_item_title, parent, false);
                break;
            case INVOICE_DESIGN_LOGO:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.invoice_design_item_logo, parent, false);
                break;
            default:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.invoice_design_item_title, parent, false);
        }

        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ItemViewHolder holder, int position) {

        switch (holder.getItemViewType()) {
            case INVOICE_DESIGN_TITLE:
                break;
            case INVOICE_DESIGN_LOGO:
                // ... some code for setting the image source
                break;

        }

        holder.dragIcon.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (MotionEventCompat.getActionMasked(event) ==
                        MotionEvent.ACTION_DOWN) {
                    itemTouchHelper.startDrag(holder);
                }
                return false;
            }
        });
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

}

public class ItemViewHolder extends RecyclerView.ViewHolder {

    final ImageView dragIcon;
    final ImageView logo;
    ItemViewHolder(View itemView) {
        super(itemView);
        dragIcon = (ImageView) itemView.findViewById(R.id.drag_ic);
        logo = (ImageView) itemView.findViewById(R.id.logo);
    }

}

public void initRecyclerSwipe(final RecyclerView recyclerView){
    ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT ) {

        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFlags = ItemTouchHelper.DOWN | ItemTouchHelper.UP;
            int swipeFlags = ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean isItemViewSwipeEnabled() {
            return true;
        }

        @Override
        public boolean isLongPressDragEnabled() {
            return false;
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            int fromPosition = viewHolder.getAdapterPosition();
            int toPosition = target.getAdapterPosition();

            Collections.swap(mItems, fromPosition, toPosition);

            recyclerView.getAdapter().notifyItemMoved(fromPosition, toPosition);
            return true;
        }

        @Override
        public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
            if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
                float width = (float) viewHolder.itemView.getWidth();
                float alpha = 1.0f - Math.abs(dX) / width;
                viewHolder.itemView.setAlpha(alpha);
                viewHolder.itemView.setTranslationX(dX);
            } else {
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY,
                        actionState, isCurrentlyActive);
            }
        }

        @Override
        public void onChildDrawOver(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
            super.onChildDrawOver(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);

            if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
                View itemView = viewHolder.itemView;
                c.save();
                c.clipRect(itemView.getLeft() + dX, itemView.getTop() + dY, itemView.getRight() + dX, itemView.getBottom() + dY);
                c.translate(itemView.getLeft() + dX, itemView.getTop() + dY);

                // draw the frame
                c.drawColor(0x33000000);

                c.restore();
            }
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
            mItems.remove(viewHolder.getAdapterPosition());
            recyclerView.getAdapter().notifyItemRemoved(viewHolder.getAdapterPosition());

        }

    };

    itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
    itemTouchHelper.attachToRecyclerView(recyclerView);

}
</code>```

How can I swap the children with different view type?

答:
I made a mistake!
the drag and drop mechanism works well.
I swap the mItems

```<code>Collections.swap(mItems, fromPosition, toPosition);
</code>```

but in getViewType:

```<code>@Override
    public int getItemViewType(int position) {
        return INVOICE_ITEMS_LIST[position];
    }
</code>```

and this is the mistake. I should use this:

```<code>@Override
        public int getItemViewType(int position) {
            return mItems.get(position);
        }
</code>```

Body:
I implement drag and drop for a RecyclerView, it works well when have one View type but reset the RecyclerView when have multiple view type, I show the result in this gif:

and this is my code:

public class RecyclerListAdapter extends RecyclerView.Adapter<ItemViewHolder> {

    private final Integer[] INVOICE_ITEMS_LIST = new Integer[]{
            INVOICE_DESIGN_TITLE,
            INVOICE_DESIGN_TITLE,
            INVOICE_DESIGN_LOGO,
            INVOICE_DESIGN_TITLE
    };

    public RecyclerListAdapter() {
        mItems.addAll(Arrays.asList(INVOICE_ITEMS_LIST));
    }

    @Override
    public int getItemViewType(int position) {
        return INVOICE_ITEMS_LIST[position];
    }

    @Override
    public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        switch (viewType){
            case INVOICE_DESIGN_TITLE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.invoice_design_item_title, parent, false);
                break;
            case INVOICE_DESIGN_LOGO:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.invoice_design_item_logo, parent, false);
                break;
            default:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.invoice_design_item_title, parent, false);
        }

        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ItemViewHolder holder, int position) {

        switch (holder.getItemViewType()) {
            case INVOICE_DESIGN_TITLE:
                break;
            case INVOICE_DESIGN_LOGO:
                // ... some code for setting the image source
                break;

        }

        holder.dragIcon.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (MotionEventCompat.getActionMasked(event) ==
                        MotionEvent.ACTION_DOWN) {
                    itemTouchHelper.startDrag(holder);
                }
                return false;
            }
        });
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

}

public class ItemViewHolder extends RecyclerView.ViewHolder {

    final ImageView dragIcon;
    final ImageView logo;
    ItemViewHolder(View itemView) {
        super(itemView);
        dragIcon = (ImageView) itemView.findViewById(R.id.drag_ic);
        logo = (ImageView) itemView.findViewById(R.id.logo);
    }

}

public void initRecyclerSwipe(final RecyclerView recyclerView){
    ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT ) {

        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFlags = ItemTouchHelper.DOWN | ItemTouchHelper.UP;
            int swipeFlags = ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean isItemViewSwipeEnabled() {
            return true;
        }

        @Override
        public boolean isLongPressDragEnabled() {
            return false;
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            int fromPosition = viewHolder.getAdapterPosition();
            int toPosition = target.getAdapterPosition();

            Collections.swap(mItems, fromPosition, toPosition);

            recyclerView.getAdapter().notifyItemMoved(fromPosition, toPosition);
            return true;
        }

        @Override
        public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
            if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
                float width = (float) viewHolder.itemView.getWidth();
                float alpha = 1.0f - Math.abs(dX) / width;
                viewHolder.itemView.setAlpha(alpha);
                viewHolder.itemView.setTranslationX(dX);
            } else {
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY,
                        actionState, isCurrentlyActive);
            }
        }

        @Override
        public void onChildDrawOver(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
            super.onChildDrawOver(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);

            if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
                View itemView = viewHolder.itemView;
                c.save();
                c.clipRect(itemView.getLeft() + dX, itemView.getTop() + dY, itemView.getRight() + dX, itemView.getBottom() + dY);
                c.translate(itemView.getLeft() + dX, itemView.getTop() + dY);

                // draw the frame
                c.drawColor(0x33000000);

                c.restore();
            }
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
            mItems.remove(viewHolder.getAdapterPosition());
            recyclerView.getAdapter().notifyItemRemoved(viewHolder.getAdapterPosition());

        }

    };

    itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
    itemTouchHelper.attachToRecyclerView(recyclerView);

}

How can I swap the children with different view type?

Body:
I made a mistake!
the drag and drop mechanism works well.
I swap the mItems

Collections.swap(mItems, fromPosition, toPosition);

but in getViewType:

@Override
    public int getItemViewType(int position) {
        return INVOICE_ITEMS_LIST[position];
    }

and this is the mistake. I should use this:

@Override
        public int getItemViewType(int position) {
            return mItems.get(position);
        }


问:
How can I execute this sql backup script with JDBC?
How can I execute the following query against my database instance using JDBC, Everything I am trying is returning "no result set" errors.

```<code>com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
</code>```

What do I do when I'm not really looking data back as such?

.sql file

```<code>DECLARE @name VARCHAR(50) -- database name
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(20) -- used for file name
DECLARE @fileFolder VARCHAR(20) -- used for file name

-- specify database backup directory
SET @path = 'C:\SQLBackups\'

-- specify filename format
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)

DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name

WHILE @@FETCH_STATUS = 0
BEGIN
       SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
       BACKUP DATABASE @name TO DISK = @fileName

       FETCH NEXT FROM db_cursor INTO @name
END

CLOSE db_cursor
DEALLOCATE db_cursor
</code>```

My code for executing said query (so far)

```<code>    public static void connect(String instance, String saPassword, String query)  {
    Connection conn = null;
    query = "DECLARE @name VARCHAR(50) -- database name   " +
            "DECLARE @path VARCHAR(256) -- path for backup files   " +
            "DECLARE @fileName VARCHAR(256) -- filename for backup   " +
            "DECLARE @fileDate VARCHAR(20) -- used for file name " +
            "-- specify database backup directory " +
            "SET @path = 'C:\\SQLBackups\\'   " +
            "-- specify filename format " +
            "SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)  " +
            "DECLARE db_cursor CURSOR FOR   " +
            "SELECT name  " +
            "FROM master.dbo.sysdatabases  " +
            "WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases " +
            "OPEN db_cursor    " +
            "FETCH NEXT FROM db_cursor INTO @name    " +
            "WHILE @@FETCH_STATUS = 0    " +
            "BEGIN    " +
            "       SET @fileName = @path + @name + '_' + @fileDate + '.BAK'   " +
            "       BACKUP DATABASE @name TO DISK = @fileName   " +
            "       FETCH NEXT FROM db_cursor INTO @name    " +
            "END    " +
            "CLOSE db_cursor    " +
            "DEALLOCATE db_cursor ";
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        String dbURL = "jdbc:sqlserver://10.0.0.0\\"+ instance;
        String user = "user";
        String pass = saPassword;
        conn = DriverManager.getConnection(dbURL, user, pass);
        Statement stmt = conn.createStatement();
        stmt.executeQuery(query);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
</code>```

I can execute my query just fine in SSMS, is the conversion of the .sql text into the string causing issues here? I'm not too bothered about a result here as it should be creating a lot of .bak files on the server (which does happen when I execute it via SSMS, I changed around the query with grabbing a simple SELECT resultset which works just fine, so I'm a tad lost now.

overwriting the (query) in the method is just for testing purposes, once I get the .bak files landing on the remote server directory I will tidy it up, credentials masked for obvious reasons.

Thanks

答:
In your java code call execute() instead of executeQuery(). The latter supposes that your query needs to return a result set, but the former does not assume that.

So, instead of:

```<code>stmt.executeQuery(query);
</code>```

call:

```<code>stmt.execute(query);
</code>```

Body:
How can I execute the following query against my database instance using JDBC, Everything I am trying is returning "no result set" errors.

com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.

What do I do when I'm not really looking data back as such?

.sql file

DECLARE @name VARCHAR(50) -- database name
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(20) -- used for file name
DECLARE @fileFolder VARCHAR(20) -- used for file name

-- specify database backup directory
SET @path = 'C:\SQLBackups\'

-- specify filename format
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)

DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name

WHILE @@FETCH_STATUS = 0
BEGIN
       SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
       BACKUP DATABASE @name TO DISK = @fileName

       FETCH NEXT FROM db_cursor INTO @name
END

CLOSE db_cursor
DEALLOCATE db_cursor

My code for executing said query (so far)

    public static void connect(String instance, String saPassword, String query)  {
    Connection conn = null;
    query = "DECLARE @name VARCHAR(50) -- database name   " +
            "DECLARE @path VARCHAR(256) -- path for backup files   " +
            "DECLARE @fileName VARCHAR(256) -- filename for backup   " +
            "DECLARE @fileDate VARCHAR(20) -- used for file name " +
            "-- specify database backup directory " +
            "SET @path = 'C:\\SQLBackups\\'   " +
            "-- specify filename format " +
            "SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)  " +
            "DECLARE db_cursor CURSOR FOR   " +
            "SELECT name  " +
            "FROM master.dbo.sysdatabases  " +
            "WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases " +
            "OPEN db_cursor    " +
            "FETCH NEXT FROM db_cursor INTO @name    " +
            "WHILE @@FETCH_STATUS = 0    " +
            "BEGIN    " +
            "       SET @fileName = @path + @name + '_' + @fileDate + '.BAK'   " +
            "       BACKUP DATABASE @name TO DISK = @fileName   " +
            "       FETCH NEXT FROM db_cursor INTO @name    " +
            "END    " +
            "CLOSE db_cursor    " +
            "DEALLOCATE db_cursor ";
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        String dbURL = "jdbc:sqlserver://10.0.0.0\\"+ instance;
        String user = "user";
        String pass = saPassword;
        conn = DriverManager.getConnection(dbURL, user, pass);
        Statement stmt = conn.createStatement();
        stmt.executeQuery(query);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

I can execute my query just fine in SSMS, is the conversion of the .sql text into the string causing issues here? I'm not too bothered about a result here as it should be creating a lot of .bak files on the server (which does happen when I execute it via SSMS, I changed around the query with grabbing a simple SELECT resultset which works just fine, so I'm a tad lost now.

overwriting the (query) in the method is just for testing purposes, once I get the .bak files landing on the remote server directory I will tidy it up, credentials masked for obvious reasons.

Thanks

Body:
In your java code call execute() instead of executeQuery(). The latter supposes that your query needs to return a result set, but the former does not assume that.

So, instead of:

stmt.executeQuery(query);

call:

stmt.execute(query);


问:
html, css, javascript - show/hide divs - one is shown than another should be hidden
I want to create show/hide div's.
It is my code: jsfiddle.net/b60b34h1

But it don't works like I want.
I want that when "press button2" pressed than another div's should hidden.
It should show only one div.

Can You help me?
Thanks

答:
you can try this method

```<code>function unhide(divID) {
    var item = document.getElementById(divID);
    var openDiv = document.getElementsByClassName("unhidden");
    if(openDiv[0]!=undefined){
          openDiv[0].className = 'hidden';
    }

    if (item) {
      item.className='unhidden';
    }
  }
</code>```

Please find working snippet

function unhide(divID,currentLink) {
     var activeLink = document.getElementsByClassName("thick");
       if(activeLink[0]!=undefined){
          activeLink[0].className = 'btn btn-line-black';
    }
    var currentLink = document.getElementById(currentLink);
    currentLink.className = 'thick btn btn-line-black';
    var item = document.getElementById(divID);
    var openDiv = document.getElementsByClassName("unhidden");
    if(openDiv[0]!=undefined){
          openDiv[0].className = 'hidden';
    }
    if (item) {
      item.className=(item.className=='hidden')?'unhidden':'hidden';
    }
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden { display: none; }
.unhidden { display: block; }

.thick{
  font-weight: bold;
   color :red!important;
}

a:after{
font-weight: bold;
}

.btn{
  color :green;
}
.btn-line-black{
  border :1px solid green;
}</code>```

press button1 press button2 press button3

button1

abc

abc

abc

button2

abc

abc

abc

button3

abc

abc

abc

```

Body:
you can try this method

function unhide(divID) {
    var item = document.getElementById(divID);
    var openDiv = document.getElementsByClassName("unhidden");
    if(openDiv[0]!=undefined){
          openDiv[0].className = 'hidden';
    }

    if (item) {
      item.className='unhidden';
    }
  }

Please find working snippet

function unhide(divID,currentLink) {
     var activeLink = document.getElementsByClassName("thick");
       if(activeLink[0]!=undefined){
          activeLink[0].className = 'btn btn-line-black';
    }
    var currentLink = document.getElementById(currentLink);
    currentLink.className = 'thick btn btn-line-black';
    var item = document.getElementById(divID);
    var openDiv = document.getElementsByClassName("unhidden");
    if(openDiv[0]!=undefined){
          openDiv[0].className = 'hidden';
    }
    if (item) {
      item.className=(item.className=='hidden')?'unhidden':'hidden';
    }
  }

.hidden { display: none; }
.unhidden { display: block; }

.thick{
  font-weight: bold;
   color :red!important;
}

a:after{
font-weight: bold;
}

.btn{
  color :green;
}
.btn-line-black{
  border :1px solid green;
}

<script type="text/javascript">

</script>

<div>
  <p><a id="link1" class="btn btn-line-black" href="javascript:unhide('button1','link1');">press button1</a> <a id="link2" class="btn btn-line-black" href="javascript:unhide('button2','link2');">press button2</a> <a id="link3" class="btn btn-line-black" href="javascript:unhide('button3','link3');">press button3</a></p>
  <div class="hidden" id="button1">
    <h3>button1</h3>
    <ul>
      <li>abc</li>
      <li>abc</li>
      <li>abc</li>
    </ul>
  </div>
<div class="hidden" id="button2">
    <h3>button2</h3>
    <ul>
      <li>abc</li>
      <li>abc</li>
      <li>abc</li>
    </ul>
  </div>
<div class="hidden" id="button3">
    <h3>button3</h3>
    <ul>
      <li>abc</li>
      <li>abc</li>
      <li>abc</li>
    </ul>
  </div>
</div>


问:
Insert into a class only selected from a customlistive with checkboxes
I'm using this a custom listview with checkboxes inside.

How can i take the name of each row where checkbox is checked and add it into a class?

Here is my my code:

```<code> SetContentView(Resource.Layout.ExtrasPreviewMain);
        OverridePendingTransition(Resource.Layout.trans_left_in, Resource.Layout.trans_left_out);
        var BackBtn = FindViewById<Button>(Resource.Id.ExtrasBackButton);
        var AcceptBtn = FindViewById<Button>(Resource.Id.ExtrasAcceptButton);
        AcceptBtn.Click += AcceptBtn_Click;

        con.Open();
        SqlCommand sqlCmd = new SqlCommand("SELECT Name from InventoryMaster where MainGroupItemID=" + Connection.CategoryID + "", con);

        mlistview = FindViewById<ListView>(Resource.Id.ExtrasList);
        mItems = new List<ExtrasPreviewClass>();
        SqlDataReader sqlReader = sqlCmd.ExecuteReader();
        while (sqlReader.Read())
        {
            mItems.Add(new ExtrasPreviewClass() { ExtrasName = sqlReader["Name"].ToString() });

        }
        MyListViewAdapterExtras adapter = new MyListViewAdapterExtras(this, mItems);
        mlistview.Adapter = adapter;
        sqlReader.Close();
        con.Close();
    }

    private void AcceptBtn_Click(object sender, EventArgs e)
    {
        var checkbox = FindViewById<CheckBox>(Resource.Id.txtExtrasCheckBox);
        var name = FindViewById<TextView>(Resource.Id.txtExtrasName);

           foreach (var item in mItems)
        {
            if (Convert.ToBoolean(item.ExtrasCheckBox)== true)
            {
                Connection.Extras = Connection.Extras + item.ExtrasName + ",";
            }
        }
</code>```

But it doesnt shows me anything in my last result
Example if will have

Extras      checkbox
Sugar       checked
milk        checked

My result will be empty

And this is my adapter code:

```<code>  class MyListViewAdapterExtras : BaseAdapter<ExtrasPreviewClass>
{
    public List<ExtrasPreviewClass> mitems;
    private Context mContext;
    public MyListViewAdapterExtras(Context context, List<ExtrasPreviewClass> items)
    {
        mitems = items;
        mContext = context;

    }
    public override int Count
    {
        get
        {
            return mitems.Count;
        }
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override ExtrasPreviewClass this[int position]
    {
        get
        {
            return mitems[position];
        }

    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View row = convertView;
        if (row == null)
        {
            row = LayoutInflater.From(mContext).Inflate(Resource.Layout.ExtrasPreview, null, false);

        }

        TextView txtExtrasName = row.FindViewById<TextView>(Resource.Id.txtExtrasName);
        txtExtrasName.Text = mitems[position].ExtrasName;
        CheckBox txtExtrasCheckBox = row.FindViewById<CheckBox>(Resource.Id.txtExtrasCheckBox);
        txtExtrasCheckBox.Text = Convert.ToString(mitems[position].ExtrasCheckBox);

        return row;
    }
</code>```

And my class

```<code>class ExtrasPreviewClass
{
    public string ExtrasName { get; set; }
    public CheckBox ExtrasCheckBox { get; set; }
}
</code>```

答:
In the GetView method from your Adapter, you will have to set an Tag for the CheckBox, with the item information, and register an EventListener for when the CheckBox is CheckedChanged, like this:</p>

```<code>public override View GetView(int position, View convertView, ViewGroup parent)
{
    //Prepare convertView here
    CheckBox itemCheckBox = convertView.FindViewById<CheckBox>(Resource.Id.itemCheckBox);
    if(itemCheckBox.Tag == null)
        itemCheckBox.Tag = new Java.Lang.String(this.items[position].name); //set the checkbox tag with information about your item. The tag object class must inherit from Java.Lang.Object
    itemCheckBox.CheckedChange -= itemCheckBox_CheckedChange; //this is to avoid registering the event more than once when scrolling the listview
    itemCheckBox.CheckedChange += itemCheckBox_CheckedChange;
    return convertView;
}

private void itemCheckBox_CheckedChange(object sender, EventArgs e)
{
    // CheckBox myCheckBox = (CheckBox)sender;
    // Java.Lang.Object myTag = myCheckBox.Tag;
    // String itemName = ((Java.Lang.String)myTag).ToString();
    //save in a variable that your item was checked
    //for example:
    // foreach(Item i in this.items)
    // {
    //     if(i.name.Equals(itemName))
    //     {
    //         i.IsChecked = myCheckBox.Checked;
    //         break;
    //     }
    // }
}
</code>```

Body:
I'm using this a custom listview with checkboxes inside.

How can i take the name of each row where checkbox is checked and add it into a class?

Here is my my code:

 SetContentView(Resource.Layout.ExtrasPreviewMain);
        OverridePendingTransition(Resource.Layout.trans_left_in, Resource.Layout.trans_left_out);
        var BackBtn = FindViewById<Button>(Resource.Id.ExtrasBackButton);
        var AcceptBtn = FindViewById<Button>(Resource.Id.ExtrasAcceptButton);
        AcceptBtn.Click += AcceptBtn_Click;

        con.Open();
        SqlCommand sqlCmd = new SqlCommand("SELECT Name from InventoryMaster where MainGroupItemID=" + Connection.CategoryID + "", con);

        mlistview = FindViewById<ListView>(Resource.Id.ExtrasList);
        mItems = new List<ExtrasPreviewClass>();
        SqlDataReader sqlReader = sqlCmd.ExecuteReader();
        while (sqlReader.Read())
        {
            mItems.Add(new ExtrasPreviewClass() { ExtrasName = sqlReader["Name"].ToString() });

        }
        MyListViewAdapterExtras adapter = new MyListViewAdapterExtras(this, mItems);
        mlistview.Adapter = adapter;
        sqlReader.Close();
        con.Close();
    }

    private void AcceptBtn_Click(object sender, EventArgs e)
    {
        var checkbox = FindViewById<CheckBox>(Resource.Id.txtExtrasCheckBox);
        var name = FindViewById<TextView>(Resource.Id.txtExtrasName);

           foreach (var item in mItems)
        {
            if (Convert.ToBoolean(item.ExtrasCheckBox)== true)
            {
                Connection.Extras = Connection.Extras + item.ExtrasName + ",";
            }
        }

But it doesnt shows me anything in my last result
Example if will have

Extras      checkbox
Sugar       checked
milk        checked

My result will be empty

And this is my adapter code:

  class MyListViewAdapterExtras : BaseAdapter<ExtrasPreviewClass>
{
    public List<ExtrasPreviewClass> mitems;
    private Context mContext;
    public MyListViewAdapterExtras(Context context, List<ExtrasPreviewClass> items)
    {
        mitems = items;
        mContext = context;

    }
    public override int Count
    {
        get
        {
            return mitems.Count;
        }
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override ExtrasPreviewClass this[int position]
    {
        get
        {
            return mitems[position];
        }

    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View row = convertView;
        if (row == null)
        {
            row = LayoutInflater.From(mContext).Inflate(Resource.Layout.ExtrasPreview, null, false);

        }

        TextView txtExtrasName = row.FindViewById<TextView>(Resource.Id.txtExtrasName);
        txtExtrasName.Text = mitems[position].ExtrasName;
        CheckBox txtExtrasCheckBox = row.FindViewById<CheckBox>(Resource.Id.txtExtrasCheckBox);
        txtExtrasCheckBox.Text = Convert.ToString(mitems[position].ExtrasCheckBox);

        return row;
    }

And my class

class ExtrasPreviewClass
{
    public string ExtrasName { get; set; }
    public CheckBox ExtrasCheckBox { get; set; }
}

Body:
In the GetView method from your Adapter, you will have to set an Tag for the CheckBox, with the item information, and register an EventListener for when the CheckBox is CheckedChanged, like this:

public override View GetView(int position, View convertView, ViewGroup parent)
{
    //Prepare convertView here
    CheckBox itemCheckBox = convertView.FindViewById<CheckBox>(Resource.Id.itemCheckBox);
    if(itemCheckBox.Tag == null)
        itemCheckBox.Tag = new Java.Lang.String(this.items[position].name); //set the checkbox tag with information about your item. The tag object class must inherit from Java.Lang.Object
    itemCheckBox.CheckedChange -= itemCheckBox_CheckedChange; //this is to avoid registering the event more than once when scrolling the listview
    itemCheckBox.CheckedChange += itemCheckBox_CheckedChange;
    return convertView;
}

private void itemCheckBox_CheckedChange(object sender, EventArgs e)
{
    // CheckBox myCheckBox = (CheckBox)sender;
    // Java.Lang.Object myTag = myCheckBox.Tag;
    // String itemName = ((Java.Lang.String)myTag).ToString();
    //save in a variable that your item was checked
    //for example:
    // foreach(Item i in this.items)
    // {
    //     if(i.name.Equals(itemName))
    //     {
    //         i.IsChecked = myCheckBox.Checked;
    //         break;
    //     }
    // }
}


问:
Not able to install hadoop using Cloudera Manager
I am trying to setup hadoop cluster in a single VM (for simplicity) using cloudera Manager 5.9. The below are the details of my environment:

```<code>Host OS -> Windows 10
Virtualization software -> Virtual box 5.1.10
Guest OS -> Cent OS 6.8
</code>```

I installed the Cloudera Manager, and as per instruction of Cloudera Manager did follow the steps.

Most of the installation steps went fine, but at the last check it fails.The below is the screen shot of that.

As can be seen in screen shot, it is giving error:

        "Unexpected error. Unable to verify database connection."

I have made the necessary changes in the configuration files of Postgres DB which Cloudera uses by default, that is it should be able to accept the remote connections.

There are no errors in the logs of Cloudera manager. I did online search as well but no success.

Can anyone help me solving this error?

答:
First of all, make sure you started the embedded DB. As the other tests are skipped, maybe your server is down. :

```<code>sudo service cloudera-scm-server-db start
</code>```

I don't think it's your case, as CM seems to be working.

So, if you already started your embedded database, and still have these kind of issues, problems usually came from 2 different sides :

DB problems: It can be obvious, but I don't think it's your case. In my case, I didn't configure pg_hba.conf to make my postgresql be accessed by the incriminated role (here, RMAN). But as I said, you seem to be using the embedded cloudera postgres, so I don't think it's your case.

Python issue: Sometimes, due to a reason I can't control, some symlinks to python libraries are lost during the install process. When you already install your cluster, hue is a great candidate for being impacted, but Cloudera's services are good candidates too, when you're trying to configure your DB. In this case, check your cloudera's agent log (/var/log/cloudera-scm-agent/cloudera-scm-agent.log) and you should see something about psycopg2. If it's the case, you only have to create the following symlink:

sudo ln -s /usr/lib64/python2.7/site-packages/psycopg2 /opt/cloudera/parcels/CDH/lib/hue/build/env/lib/python2.7/site-packages/psycopg2

Anyway, If you're trying to understand how to install CDH, I recommend you to not use the embedded Postgres DB, but Postgres as external DB instead(in the same machine). Cloudera Manager is using some scripts to generate lots of things (passwords, configs, ...) you're going to miss if you use the embedded version of postgres.

On the other hand, if you're only want to access a single-node CDH 5.9+ clúster to make some tests, download the quickstart and follow the cloudera guide to upgrade the cluster to a newer version.

Body:
I am trying to setup hadoop cluster in a single VM (for simplicity) using cloudera Manager 5.9. The below are the details of my environment:

Host OS -> Windows 10
Virtualization software -> Virtual box 5.1.10
Guest OS -> Cent OS 6.8

I installed the Cloudera Manager, and as per instruction of Cloudera Manager did follow the steps.

Most of the installation steps went fine, but at the last check it fails.The below is the screen shot of that.

As can be seen in screen shot, it is giving error:

        "Unexpected error. Unable to verify database connection."

I have made the necessary changes in the configuration files of Postgres DB which Cloudera uses by default, that is it should be able to accept the remote connections.

There are no errors in the logs of Cloudera manager. I did online search as well but no success.

Can anyone help me solving this error?

Body:
First of all, make sure you started the embedded DB. As the other tests are skipped, maybe your server is down. :

sudo service cloudera-scm-server-db start

I don't think it's your case, as CM seems to be working.

So, if you already started your embedded database, and still have these kind of issues, problems usually came from 2 different sides :

DB problems: It can be obvious, but I don't think it's your case. In my case, I didn't configure pg_hba.conf to make my postgresql be accessed by the incriminated role (here, RMAN). But as I said, you seem to be using the embedded cloudera postgres, so I don't think it's your case.

Python issue: Sometimes, due to a reason I can't control, some symlinks to python libraries are lost during the install process. When you already install your cluster, hue is a great candidate for being impacted, but Cloudera's services are good candidates too, when you're trying to configure your DB. In this case, check your cloudera's agent log (/var/log/cloudera-scm-agent/cloudera-scm-agent.log) and you should see something about psycopg2. If it's the case, you only have to create the following symlink:

sudo ln -s /usr/lib64/python2.7/site-packages/psycopg2 /opt/cloudera/parcels/CDH/lib/hue/build/env/lib/python2.7/site-packages/psycopg2

Anyway, If you're trying to understand how to install CDH, I recommend you to not use the embedded Postgres DB, but Postgres as external DB instead(in the same machine). Cloudera Manager is using some scripts to generate lots of things (passwords, configs, ...) you're going to miss if you use the embedded version of postgres.

On the other hand, if you're only want to access a single-node CDH 5.9+ clúster to make some tests, download the quickstart and follow the cloudera guide to upgrade the cluster to a newer version.


问:
output.filename is required webpack
I tried to do the webpack exports in the following way. I tried to convert the async to sync ( regarding fs.readdir) to get the total files within directory.

```<code>const webpack = require('webpack');
const async = require('async');
const path = require('path');
const fs = require('fs');
var fileList = [];

var promiso = new Promise(function(res, rej) {
   fs.readdir(__dirname + "/imports/components", function(err, files)   {
      files.forEach(function(file) {
          console.log("file", file);
          fileList.push(file);
      });

      let config = {
          entry: {
             'myPages': fileList[0]
          },
          module: {
              loaders: [
                  // Javascript: js, jsx
                 {
                    test: /\.jsx?$/,
                    loader: 'babel-loader',
                    query: {
                        presets: ['es2015', 'react']
                    }
                }
            ]
        },
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: './bundler.js'
        },
    }
    res(config)
  })
});

promiso.then(function(mess) {
  console.log("-------------------------mess", mess);
  module.exports = mess;
});
</code>```

I am getting following error

'output.filename' is required, either in config file or as --output-filename

答:
Here you should return promise itself and then use it anywhere else. Because the require cannot work your way. Modules in Node that you load with require() are loaded synchronously and it is not possible for require to return any value that is loaded asynchronously.

```<code>module.exports = promise
</code>```

And in another file use it as follows

```<code>require('path-to-file').then( (mess) => {
    // Use mess
}).then(null, (err) => {
    // Error handling
})
</code>```

Title: output.filename is required webpack

Body:
I tried to do the webpack exports in the following way. I tried to convert the async to sync ( regarding fs.readdir) to get the total files within directory.

const webpack = require('webpack');
const async = require('async');
const path = require('path');
const fs = require('fs');
var fileList = [];

var promiso = new Promise(function(res, rej) {
   fs.readdir(__dirname + "/imports/components", function(err, files)   {
      files.forEach(function(file) {
          console.log("file", file);
          fileList.push(file);
      });

      let config = {
          entry: {
             'myPages': fileList[0]
          },
          module: {
              loaders: [
                  // Javascript: js, jsx
                 {
                    test: /\.jsx?$/,
                    loader: 'babel-loader',
                    query: {
                        presets: ['es2015', 'react']
                    }
                }
            ]
        },
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: './bundler.js'
        },
    }
    res(config)
  })
});

promiso.then(function(mess) {
  console.log("-------------------------mess", mess);
  module.exports = mess;
});

I am getting following error

'output.filename' is required, either in config file or as --output-filename

Body:
Here you should return promise itself and then use it anywhere else. Because the require cannot work your way. Modules in Node that you load with require() are loaded synchronously and it is not possible for require to return any value that is loaded asynchronously.

module.exports = promise

And in another file use it as follows

require('path-to-file').then( (mess) => {
    // Use mess
}).then(null, (err) => {
    // Error handling
})


问:
Checking Mobile Number
I am wanting to send out SMS via an API, however one of the requirements is that i must use the country code, secondly i need to ensure that the length of numbers is correct.

First i need to remove any spaces in the number, check that the character length is 11, check that the number starts with 07 then replace it with +44.

What would be the easiest way to tackle this? I was thinking about

```<code>$number = '07803 556557';
$number = str_replace(' ', '', $number);
if (strlen($number) == '11' && substr($number, 0, 2) == '07') {
    $number = str_replace('07', '+44', $number);
}
</code>```

答:
Summarizing the comments, I would recommend to...

Strip all non-numeric characters from the input. This will not only remove spaces and a + in the beginning, but also typos or characters like (, ) or - that people sometimes add.

Check the length and stop if it doesn't fit your requirement. However, are you sure there can only ever be numbers with a length of 11?

Check if the first two numbers are either 44 or 07, stop otherwise. However, are you sure you don't want to accept other country/region codes?

Change the first two numbers to +44. Remember what ewcz said, however: if you use str_replace(), you might not get what you are looking for. Instead, just replace the first two: $number = substr_replace($number, "+44", 0, 2);

Additional notes:

Never trust or make assumptions about user input. You will have users who enter non-numeric characters, HTML, SQL, PHP, random characters and everything else you would not assume - just for the giggles.

Title: Checking Mobile Number

Body:
I am wanting to send out SMS via an API, however one of the requirements is that i must use the country code, secondly i need to ensure that the length of numbers is correct.

First i need to remove any spaces in the number, check that the character length is 11, check that the number starts with 07 then replace it with +44.

What would be the easiest way to tackle this? I was thinking about

$number = '07803 556557';
$number = str_replace(' ', '', $number);
if (strlen($number) == '11' && substr($number, 0, 2) == '07') {
    $number = str_replace('07', '+44', $number);
}


问:
Creating a small struct in C - have some errors
```<code>#include "stdio.h"
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#define getch() _getch()

struct Clicker {
    int toggle;
    int average;
};

int main()
{
    struct Clicker *clicker;
    printf("Enter your toggle key: ");
    (*clicker).toggle = _getch();
    printf("Enter your average cps: ");
    scanf_s("%d", (*clicker).average);
    printf("\nCurrent settings: \nToggle: %i \nAverage:%i\n", clicker->toggle, clicker->average);
    getchar();
    return 1;
}
</code>```

There is the code.
Errors:

'_getch' undefined, assuming extern returning int
'scanf_s' format string '%d' requires an argument of type 'int *' but variadic arguemnt 1 has type int.
uninitialized local variable 'clicker' used.
```

What am I doing wrong?

答:
You say you are trying to learn C by yourself, so I will actually explain all the mistakes in this program.

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

stdio.h should always be included using the <> form of #include. (The "" form is for headers that are part of your program, and the <> form is for headers that come from system-provided libraries.  In complex programs the distinction can get fuzzy, but don't worry about that right now.)

```<code>#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#define getch() _getch()
</code>```

These three lines all do things that are Windows-specific and should be completely unnecessary in a program like this.  Remove them.

```<code>struct Clicker {
    int toggle;
    int average;
};
</code>```

There is nothing wrong with this structure definition.

```<code>int main()
</code>```

For historical reasons, you need to write int main(void).  This is mostly harmless, but writing empty function parameter lists in C is a bad habit to get into.

```<code>{
    struct Clicker *clicker;
</code>```

Here's your most important mistake: you have declared a pointer to a struct Clicker, when what it appears you wanted was to declare a local variable using the structure.  Write struct Clicker clicker instead.

Pointers are one of the most difficult aspects of the language, especially for people new to programming.  If your book doesn't devote at least a full chapter to pointers and nothing else, it's a bad textbook and you need to get a better one.

```<code>    printf("Enter your toggle key: ");
    (*clicker).toggle = _getch();
</code>```

Consistent with the above change, write clicker.toggle = ... instead of (*clicker).toggle = since you no longer have a pointer.

Do not use the nonstandard function _getch(), use getchar() instead.  (There are programs that actually need to use _getch but this isn't one of them.)

```<code>    printf("Enter your average cps: ");
    scanf_s("%d", (*clicker).average);
</code>```

Here's a place where you have to deal with pointers.  All of the arguments to scanf, after the format string, must be pointers to variables, because that is what makes it possible for scanf to write to the variables.  clicker is no longer a pointer, but what you wrote would be wrong even if we hadn't made that change, because (*clicker).average isn't a pointer even when clicker is.  What you need to write is

```<code>    scanf("%d", &clicker.average);
</code>```

The & operator is said to take the address of the variable clicker.average, producing the pointer that scanf needs.

Similarly to what I said above about _getch, never, ever use the nonstandard function scanf_s.  (All of the functions whose names end in _s come from a well-intentioned but disastrously ineffective attempt by Microsoft to paper over a bunch of design errors in the standard C library.  They don't exist on most operating systems, and they don't fix the problems they were intended to fix.  Don't use any of them.)

When you get more experience you will come to realize that scanf is more trouble than it's worth, but for a trivial program like this it's OK.

```<code>    printf("\nCurrent settings: \nToggle: %i \nAverage:%i\n",
           clicker->toggle, clicker->average);
</code>```

Unlike scanf, printf takes values, not pointers to variables, so this is right except that we have to change clicker->toggle to clicker.toggle and clicker->average to clicker.average because clicker is no longer a pointer.

In text to be printed, do not put spaces immediately before \n.

Even nowadays, code should be no more than 80 columns wide, because that way you can get two files of code side by side on your screen at once and still use a reasonable font size.  This is an absolutely vital thing to be able to do when you are working with a complex program.  (Also, really wide text is harder to read in general.)

```<code>    getchar();
</code>```

It is bad style to put a call to getchar immediately before the end of the program.  When the program is done running it should just exit.  If your IDE refuses to keep the "console" window around after the program exits, get yourself a better IDE.

```<code>    return 1;
</code>```

The program has not failed, so it should return 0, not 1.

Body:
#include "stdio.h"
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#define getch() _getch()

struct Clicker {
    int toggle;
    int average;
};

int main()
{
    struct Clicker *clicker;
    printf("Enter your toggle key: ");
    (*clicker).toggle = _getch();
    printf("Enter your average cps: ");
    scanf_s("%d", (*clicker).average);
    printf("\nCurrent settings: \nToggle: %i \nAverage:%i\n", clicker->toggle, clicker->average);
    getchar();
    return 1;
}

There is the code.
Errors:

'_getch' undefined, assuming extern returning int
'scanf_s' format string '%d' requires an argument of type 'int *' but variadic arguemnt 1 has type int.
uninitialized local variable 'clicker' used.

What am I doing wrong?

Body:
You say you are trying to learn C by yourself, so I will actually explain all the mistakes in this program.

#include "stdio.h"

stdio.h should always be included using the <> form of #include. (The "" form is for headers that are part of your program, and the <> form is for headers that come from system-provided libraries.  In complex programs the distinction can get fuzzy, but don't worry about that right now.)

#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#define getch() _getch()

These three lines all do things that are Windows-specific and should be completely unnecessary in a program like this.  Remove them.

struct Clicker {
    int toggle;
    int average;
};

There is nothing wrong with this structure definition.

int main()

For historical reasons, you need to write int main(void).  This is mostly harmless, but writing empty function parameter lists in C is a bad habit to get into.

{
    struct Clicker *clicker;

Here's your most important mistake: you have declared a pointer to a struct Clicker, when what it appears you wanted was to declare a local variable using the structure.  Write struct Clicker clicker instead.

Pointers are one of the most difficult aspects of the language, especially for people new to programming.  If your book doesn't devote at least a full chapter to pointers and nothing else, it's a bad textbook and you need to get a better one.

    printf("Enter your toggle key: ");
    (*clicker).toggle = _getch();

Consistent with the above change, write clicker.toggle = ... instead of (*clicker).toggle = since you no longer have a pointer.

Do not use the nonstandard function _getch(), use getchar() instead.  (There are programs that actually need to use _getch but this isn't one of them.)

    printf("Enter your average cps: ");
    scanf_s("%d", (*clicker).average);

Here's a place where you have to deal with pointers.  All of the arguments to scanf, after the format string, must be pointers to variables, because that is what makes it possible for scanf to write to the variables.  clicker is no longer a pointer, but what you wrote would be wrong even if we hadn't made that change, because (*clicker).average isn't a pointer even when clicker is.  What you need to write is

    scanf("%d", &clicker.average);

The & operator is said to take the address of the variable clicker.average, producing the pointer that scanf needs.

Similarly to what I said above about _getch, never, ever use the nonstandard function scanf_s.  (All of the functions whose names end in _s come from a well-intentioned but disastrously ineffective attempt by Microsoft to paper over a bunch of design errors in the standard C library.  They don't exist on most operating systems, and they don't fix the problems they were intended to fix.  Don't use any of them.)

When you get more experience you will come to realize that scanf is more trouble than it's worth, but for a trivial program like this it's OK.

    printf("\nCurrent settings: \nToggle: %i \nAverage:%i\n",
           clicker->toggle, clicker->average);

Unlike scanf, printf takes values, not pointers to variables, so this is right except that we have to change clicker->toggle to clicker.toggle and clicker->average to clicker.average because clicker is no longer a pointer.

In text to be printed, do not put spaces immediately before \n.

Even nowadays, code should be no more than 80 columns wide, because that way you can get two files of code side by side on your screen at once and still use a reasonable font size.  This is an absolutely vital thing to be able to do when you are working with a complex program.  (Also, really wide text is harder to read in general.)

    getchar();

It is bad style to put a call to getchar immediately before the end of the program.  When the program is done running it should just exit.  If your IDE refuses to keep the "console" window around after the program exits, get yourself a better IDE.

    return 1;

The program has not failed, so it should return 0, not 1.


问:
Neo4j - Java heap space. Wrong query or settings?
i have a problem with neo4j.
I don't know if problem is my query or something else.

Intro

I have to build an application that store bus/train routes.
This is my schema:

Nodes:

Organizaton: company that have routes/bus etc..

Route: A bus route like: Paris - Berlin.

Vehicle(Bus in this case): Fisical bus with a unique license plate.

Stops: point in a map with latitude and longitude.

Important Relationships:

NEXT: This is a really important relationship.

NEXT relationships contains those properties:

startHour

startMinutes

endHour

endMinutes

dayOfWeek (from 0 to 6 - Sun, Mon etc..)

vehicleId

Problem

My query is:

```<code>MATCH (s1:Stop {id: {departureStopId}}), (s2:Stop {id: {arrivalStopId}})
OPTIONAL MATCH (s1)-[nexts:NEXT*]->(s2)
WHERE ALL(i in nexts WHERE toInt(i.dayOfWeek) = {dayOfWeek} AND toInt(i.startHour) >= {hour})
RETURN nexts
LIMIT 10
</code>```

For example: I wanna found all nexts relationships where dayOfWeek is Sunday (0) and property startHour > 11

After that I usually parse and validate final object on my nodejs backend.

This works when i was at the start.. with 1k relationships..
Now i have 10k relationships and my query have a TIMEOUT problem or queries are solved in 30s.. too much time...
I have no idea how to solve this.
I use neo4j with docker and i tried to read settings docs but i have no idea how Java works.

Can you help me guys?

UPDATE

Thank you all guys!
For now i solved with "allShortestPaths" but I think i will rename all relationships (like Michael Hunger said).

答:
Can you share your profile.

I presume you have a constraint on :Stop(id)

I would use shortest path or dijkstra with costs instead of optional match.
OPTIONAL MATCH will try to find ALL of such paths which are hundreds of millions and filter them as they go.

And it might make sense to group your NEXT relationships by day of week, .e.g :NEXT_MO, :NEXT_THU so you only look at 1/7 th of the data.

Body:
i have a problem with neo4j.
I don't know if problem is my query or something else.

Intro

I have to build an application that store bus/train routes.
This is my schema:

Nodes:

Organizaton: company that have routes/bus etc..

Route: A bus route like: Paris - Berlin.

Vehicle(Bus in this case): Fisical bus with a unique license plate.

Stops: point in a map with latitude and longitude.

Important Relationships:

NEXT: This is a really important relationship.

NEXT relationships contains those properties:

startHour

startMinutes

endHour

endMinutes

dayOfWeek (from 0 to 6 - Sun, Mon etc..)

vehicleId

Problem

My query is:

MATCH (s1:Stop {id: {departureStopId}}), (s2:Stop {id: {arrivalStopId}})
OPTIONAL MATCH (s1)-[nexts:NEXT*]->(s2)
WHERE ALL(i in nexts WHERE toInt(i.dayOfWeek) = {dayOfWeek} AND toInt(i.startHour) >= {hour})
RETURN nexts
LIMIT 10

For example: I wanna found all nexts relationships where dayOfWeek is Sunday (0) and property startHour > 11

After that I usually parse and validate final object on my nodejs backend.

This works when i was at the start.. with 1k relationships..
Now i have 10k relationships and my query have a TIMEOUT problem or queries are solved in 30s.. too much time...
I have no idea how to solve this.
I use neo4j with docker and i tried to read settings docs but i have no idea how Java works.

Can you help me guys?

UPDATE

Thank you all guys!
For now i solved with "allShortestPaths" but I think i will rename all relationships (like Michael Hunger said).


问:
ASP NET - delete row using dataset in SQL
having issues with deleting a datarow using dataset in a sql database

```<code>ds.Tables(0).Rows(i).Delete()
</code>```

Using above code gets me the error: Expression does not produce a value.

I'm using it like this:

```<code>tohtml += "<a role='button' onclick='" + ds.Tables(0).Rows(i).Delete()
</code>```

答:
May be your missing AcceptChanges.
// Delete row

```<code>dTable.Rows[1].Delete();

dTable.AcceptChanges();
</code>```

Here you can check complete CRUD Operation:
http://www.dotnetfunda.com/articles/show/131/datatable-adding-modifying-deleting-filtering-sorting-rows-readingwrit

Body:
having issues with deleting a datarow using dataset in a sql database

ds.Tables(0).Rows(i).Delete()

Using above code gets me the error: Expression does not produce a value.

I'm using it like this:

tohtml += "<a role='button' onclick='" + ds.Tables(0).Rows(i).Delete()

Body:
May be your missing AcceptChanges.
// Delete row

dTable.Rows[1].Delete();

dTable.AcceptChanges();

Here you can check complete CRUD Operation:
http://www.dotnetfunda.com/articles/show/131/datatable-adding-modifying-deleting-filtering-sorting-rows-readingwrit


问:
Objective-C Programming: Will Learning C and/or Smalltalk Help?
Objective-C is an object-oriented programming language that adds Smalltalk-style messaging to the C programming language. I understand that learning Smalltalk might be good in the same way that learning Lisp is good for one's knowledge, but I want to know if learning Smalltalk-specific concepts will help me to understand Objective-C more completely, given Smalltalk's role in its "origin story". If so, what specifically?

Assuming that one already knows C programming, what can we learn from Smalltalk? Obviously, there's a lot of concepts in Objective-C that just aren't in C (ie. messaging, interfaces, protocols, dynamic typing, delegation, reflection; it's object-oriented!) but are derived from Smalltalk.

Edit: I've added the C programming language to the question, as the general consensus is that learning C is a better use of one's time than learning Smalltalk (when it comes to programming in Objective-C).

答:
Smalltalk is an incredibly compact language and remains one of the most pure object oriented languages. Objective-C is a pragmatic compromise between Smalltalk and C, which makes for some very substantial differences. For example, in Smalltalk everything is an object — even simple numbers — and every manipulation of an object is by message sending. Messages are evaluated in the same order irrespective of their name. So e.g. the following:

```<code>8 + 9 / 23 + 16 * 8
</code>```

Is evaluated in strict left-to-right order because the operators '+', '/' and '*' have no special meaning to the language being just messages that are passed on to number objects.

Objective-C adds Smalltalk-style objects to C but is also a strict superset of C that retains C's primitive types and built-in operators. So in Objective-C the normal mathematical order of operations would be applied to the expression above — the division and the multiplication would be done first, the additions afterwards.

Learning C is absolutely essential to a thorough understanding of Objective-C. Objective-C is a strict superset of C and explicitly uses exactly the same syntax and semantics as far as they go. It grafts the concept of objects onto C by virtue of C's ability to retain a pointer to a thing without knowing how to apply any operations to the thing. It then extends the C syntax to provide a means for posting messages to objects and for declaring and implementing the messages an object may receive.

A lot of the general design of the Objective-C runtime, especially when coupled with Cocoa, comes directly from Smalltalk, including the concept of a selector, the use of metaclasses as factories for instances of classes, the hierarchy and system of inheritance, the division of model-view-controller (a Smalltalk original, albeit now almost ubiquitous) and a lot of the messages defined on the standard collections and objects.

Off the top of my head, Smalltalk also differs greatly in its system of flow control and has a similar but subtly different idea of a 'block' (though most newer implementations have brought the two into line). Apple have actually implemented blocks as an extension at the C level which is utilised by a lot of the newer methods on Objective-C objects.

That all being said, the Goldberg Smalltalk-80 book is extremely well written, easy to read and the language is so simple that you can learn the whole language in just two or three chapters. Most of the complexity is swallowed by the objects available in the runtime, and obviously that stuff doesn't transfer. The benefit to you is that the ideological stuff about objects and runtimes ends up very separated from the specifics in print. Conversely, C makes stuff like flow control and arithmetic a language feature, which means more syntax and more to read before you really feel you know what's going on.

So, in conclusion: the Smalltalk-80 book (the purple one) is definitely worth a read and extremely helpful but not necessarily entirely relevant. Learning C is essential in any case; my references to K&R are for comparison.

ContentLicense: CC BY-SA 2.5

Body:
Smalltalk is an incredibly compact language and remains one of the most pure object oriented languages. Objective-C is a pragmatic compromise between Smalltalk and C, which makes for some very substantial differences. For example, in Smalltalk everything is an object — even simple numbers — and every manipulation of an object is by message sending. Messages are evaluated in the same order irrespective of their name. So e.g. the following:

8 + 9 / 23 + 16 * 8

Is evaluated in strict left-to-right order because the operators '+', '/' and '*' have no special meaning to the language being just messages that are passed on to number objects.

Objective-C adds Smalltalk-style objects to C but is also a strict superset of C that retains C's primitive types and built-in operators. So in Objective-C the normal mathematical order of operations would be applied to the expression above — the division and the multiplication would be done first, the additions afterwards.

Learning C is absolutely essential to a thorough understanding of Objective-C. Objective-C is a strict superset of C and explicitly uses exactly the same syntax and semantics as far as they go. It grafts the concept of objects onto C by virtue of C's ability to retain a pointer to a thing without knowing how to apply any operations to the thing. It then extends the C syntax to provide a means for posting messages to objects and for declaring and implementing the messages an object may receive.

A lot of the general design of the Objective-C runtime, especially when coupled with Cocoa, comes directly from Smalltalk, including the concept of a selector, the use of metaclasses as factories for instances of classes, the hierarchy and system of inheritance, the division of model-view-controller (a Smalltalk original, albeit now almost ubiquitous) and a lot of the messages defined on the standard collections and objects.

Off the top of my head, Smalltalk also differs greatly in its system of flow control and has a similar but subtly different idea of a 'block' (though most newer implementations have brought the two into line). Apple have actually implemented blocks as an extension at the C level which is utilised by a lot of the newer methods on Objective-C objects.

That all being said, the Goldberg Smalltalk-80 book is extremely well written, easy to read and the language is so simple that you can learn the whole language in just two or three chapters. Most of the complexity is swallowed by the objects available in the runtime, and obviously that stuff doesn't transfer. The benefit to you is that the ideological stuff about objects and runtimes ends up very separated from the specifics in print. Conversely, C makes stuff like flow control and arithmetic a language feature, which means more syntax and more to read before you really feel you know what's going on.

So, in conclusion: the Smalltalk-80 book (the purple one) is definitely worth a read and extremely helpful but not necessarily entirely relevant. Learning C is essential in any case; my references to K&R are for comparison.


问:
Set user variable from result of query
Is it possible to set a user variable based on the result of a query in MySQL?

What I want to achieve is something like this (we can assume that both USER and GROUP are unique):

```<code>set @user = 123456;
set @group = select GROUP from USER where User = @user;
select * from USER where GROUP = @group;
</code>```

Please note that I know it's possible but I do not wish to do this with nested queries.

答:
Use this way so that result will not be displayed while running stored procedure.

The query:

SELECT a.strUserID
FROM tblUsers a
WHERE a.lngUserID = lngUserID
LIMIT 1
INTO @strUserID;
```

Title: Set user variable from result of query

Body:
Is it possible to set a user variable based on the result of a query in MySQL?

What I want to achieve is something like this (we can assume that both USER and GROUP are unique):

set @user = 123456;
set @group = select GROUP from USER where User = @user;
select * from USER where GROUP = @group;

Please note that I know it's possible but I do not wish to do this with nested queries.