问:
Python program: a tool to convert binary numbers to decimal, and decimal numbers to binary, and a simple text-only menu to add or subtract numbers
Python program: a tool to convert binary numbers to decimal, and decimal numbers to binary, and a simple text-only menu to add or subtract numbers.

To the creator could you please adjust the code so it looks like the code you have in your editor? I cannot read this.

```<code> import sys
</code>```

Binary To Decimal

```<code>def bintodec(binnum):
     l = len(binnum)
     s = binnum
     dec = 0
     for i in range(0,l):
         b = s[l-i-1]
         dec = dec + int(b)*(2**i)
         return dec
</code>```

Decimal To Binary

```<code> def dectobin(decnum):
     if decnum==0:
         return "00000000"
     bin=""
     while decnum>0:
         bin = str(decnum%2) + bin
         decnum = decnum/2

     if len(bin)%8 != 0:
         n = 8*(len(bin)/8 + 1) - len(bin)
         bin = "0" + bin
         return bin

 def show_menu():
     print ("What do you want to do?")
     print ("1. Enter the first number")
     print ("2. Enter the second number")
     print ("3. Add the two numbers together")
     print ("4. Subtract the second number from the first")
     print ("5. Exit the program\n")
     show_menu()
      inp = input()
      n1 = ""
      n2 = ""
      while inp !=5:
     if inp=="1":
         n1 = str(input("Enter the first number\n"))
         print ("The first number chosen is: " + str(n1) + "\n")
         show_menu()
     if inp=="2":
         n2= str(input("Enter the second number\n"))
         print ("The first number chosen is: " + str(n1))
         print ("The second number chosen is: " + str(n2) +"\n")
         show_menu()
     if inp=="3":
         print ("The sum of the two numbers is: " + dectobin(bintodec(n1) + bintodec(n2)) + "\n")
     exit()
     if inp=="4":
         if bintodec(n2)<bintodec(n1):
             print ("For this selection second number should be greater than or equal to first")
         else:
             print ("The difference beween the two numbers is: " + dectobin(bintodec(n2) - bintodec(n1)) + "\n")
         exit()
     inp = input()
</code>```

答:
Through much confusion as to what you were trying to do this is what i could come up with:

```<code># Binary To Decimal
def bintodec(binnum):
    return int(str(binnum), 2)

#Decimal To Binary
def dectobin(x):
    return int(bin(x)[2:])

def ask_for_numbers():
    number_list = 0
    while True:
        ask_for_operand = input('Would you like to add or sub')
        ask_for_number = input('Please enter a number: ')
        try:
            if ask_for_operand == 'add':
                try:
                    number_list += bintodec(ask_for_number)
                except:
                    number_list += int(ask_for_number)
                print(number_list)
            elif ask_for_operand == 'sub':
                try:
                    number_list -= bintodec(ask_for_number)
                except:
                    number_list -= int(ask_for_number)
                print(number_list)
            else:
                return number_list
        except ValueError:
            print("Not Int or Bin")

def main():
    print(ask_for_numbers())

if __name__ == '__main__':
    main()
</code>```

Clearly I had to start again, the decimal to binary function was not needed. The issue with doing it this way is that if i want to add the decimal '10' the function ask_for_numbers() will want to convert that into a binary value. Maybe you can edit this code to figure it out.

I hope this helps :)

Body:
Python program: a tool to convert binary numbers to decimal, and decimal numbers to binary, and a simple text-only menu to add or subtract numbers.

To the creator could you please adjust the code so it looks like the code you have in your editor? I cannot read this.

 import sys

Binary To Decimal

def bintodec(binnum):
     l = len(binnum)
     s = binnum
     dec = 0
     for i in range(0,l):
         b = s[l-i-1]
         dec = dec + int(b)*(2**i)
         return dec

Decimal To Binary

 def dectobin(decnum):
     if decnum==0:
         return "00000000"
     bin=""
     while decnum>0:
         bin = str(decnum%2) + bin
         decnum = decnum/2

     if len(bin)%8 != 0:
         n = 8*(len(bin)/8 + 1) - len(bin)
         bin = "0" + bin
         return bin

 def show_menu():
     print ("What do you want to do?")
     print ("1. Enter the first number")
     print ("2. Enter the second number")
     print ("3. Add the two numbers together")
     print ("4. Subtract the second number from the first")
     print ("5. Exit the program\n")
     show_menu()
      inp = input()
      n1 = ""
      n2 = ""
      while inp !=5:
     if inp=="1":
         n1 = str(input("Enter the first number\n"))
         print ("The first number chosen is: " + str(n1) + "\n")
         show_menu()
     if inp=="2":
         n2= str(input("Enter the second number\n"))
         print ("The first number chosen is: " + str(n1))
         print ("The second number chosen is: " + str(n2) +"\n")
         show_menu()
     if inp=="3":
         print ("The sum of the two numbers is: " + dectobin(bintodec(n1) + bintodec(n2)) + "\n")
     exit()
     if inp=="4":
         if bintodec(n2)<bintodec(n1):
             print ("For this selection second number should be greater than or equal to first")
         else:
             print ("The difference beween the two numbers is: " + dectobin(bintodec(n2) - bintodec(n1)) + "\n")
         exit()
     inp = input()

Body:
Through much confusion as to what you were trying to do this is what i could come up with:

# Binary To Decimal
def bintodec(binnum):
    return int(str(binnum), 2)

#Decimal To Binary
def dectobin(x):
    return int(bin(x)[2:])

def ask_for_numbers():
    number_list = 0
    while True:
        ask_for_operand = input('Would you like to add or sub')
        ask_for_number = input('Please enter a number: ')
        try:
            if ask_for_operand == 'add':
                try:
                    number_list += bintodec(ask_for_number)
                except:
                    number_list += int(ask_for_number)
                print(number_list)
            elif ask_for_operand == 'sub':
                try:
                    number_list -= bintodec(ask_for_number)
                except:
                    number_list -= int(ask_for_number)
                print(number_list)
            else:
                return number_list
        except ValueError:
            print("Not Int or Bin")

def main():
    print(ask_for_numbers())

if __name__ == '__main__':
    main()

Clearly I had to start again, the decimal to binary function was not needed. The issue with doing it this way is that if i want to add the decimal '10' the function ask_for_numbers() will want to convert that into a binary value. Maybe you can edit this code to figure it out.

I hope this helps :)


来源: stackexchange

问:
Azure Machine Learning Write output to Azure SQL Database
I am using Azure Machine Learning to clustering data.

The input data is from an Azure SQL Database, and it works fine.
At the end of everything I want to write the output to a table in the same Azure SQL Database, but I get this error:

```<code>Error: Error 1000: AFx Library library exception:
Sql encountered an error: Login failed for user
</code>```

Anyone any idea?
Thank you very much!

答:
Find the issue!

I needed to create an specific user with this SQL code:

```<code>CREATE USER AMLApplicationUser WITH PASSWORD = '************';
</code>```

and then add the user to these roles on the database I want to write.

```<code>ALTER ROLE db_datareader ADD MEMBER AMLApplicationUser;
ALTER ROLE db_datawriter ADD MEMBER AMLApplicationUser;
</code>```

I guess only the datawriter role is enough, but I needed datareader too.

So in conclusion, seems that database admin role can be used to read data, but not to write data from AML.

Thank you for your help!

ContentLicense: CC BY-SA 3.0

Body:
I am using Azure Machine Learning to clustering data.

The input data is from an Azure SQL Database, and it works fine.
At the end of everything I want to write the output to a table in the same Azure SQL Database, but I get this error:

Error: Error 1000: AFx Library library exception:
Sql encountered an error: Login failed for user

Anyone any idea?
Thank you very much!

Body:
Find the issue!

I needed to create an specific user with this SQL code:

CREATE USER AMLApplicationUser WITH PASSWORD = '************';

and then add the user to these roles on the database I want to write.

ALTER ROLE db_datareader ADD MEMBER AMLApplicationUser;
ALTER ROLE db_datawriter ADD MEMBER AMLApplicationUser;

I guess only the datawriter role is enough, but I needed datareader too.

So in conclusion, seems that database admin role can be used to read data, but not to write data from AML.

Thank you for your help!


问:
How do I delay/defer/control when an A-Frame scene initializes/loads?
I want to have an A-Frame scene start loading only when I tell it to. Currently if I put  in an HTML file, it will start initializing immediately.

```<code><a-scene></a-scene>
</code>```

答:
An A-Frame scene waits for all of its children to initialize before it itself initializes. So it waits for every  from the bottom up. Under the hood,  is based on  which handles load order. When  emits loaded, then the parent nodes can begin loading.  emits loaded when it attaches + initializes all of its components.

Therefore, you start a scene on demand:

```<code><a-scene>
  <a-node id="waitOnMe"></a-node>
</a-scene>

document.getElementById('waitOnMe').emit('loaded');  // When you are ready.
</code>```

Body:
An A-Frame scene waits for all of its children to initialize before it itself initializes. So it waits for every <a-entity> from the bottom up. Under the hood, <a-entity> is based on <a-node> which handles load order. When <a-node> emits loaded, then the parent nodes can begin loading. <a-entity> emits loaded when it attaches + initializes all of its components.

Therefore, you start a scene on demand:

<a-scene>
  <a-node id="waitOnMe"></a-node>
</a-scene>

document.getElementById('waitOnMe').emit('loaded');  // When you are ready.


问:
Backslash is printing while writing id to mongoDb
I am passing id from angular js to nodejs server in the following manner:

formData.append("proId", JSON.stringify($scope.pid));

I am also able to retrieve id on the server-side, but when I am posting that to MongoDB, it adding back-shlahes to id.

For example:

"\"5a0fc8ad4a9a9c2cd81a8853\"", it shoulnot contain \  & extra " commas.

Why this is hapening?

答:
That's what JSON.stringify does to a string:

```<code>→ node -pe 'JSON.stringify("5a0fc8ad4a9a9c2cd81a8853")'
"5a0fc8ad4a9a9c2cd81a8853"
</code>```

You probably need to JSON.parse it on the server side.

```<code>→ node -pe 'JSON.parse("\"5a0fc8ad4a9a9c2cd81a8853\"")'
5a0fc8ad4a9a9c2cd81a8853
</code>```

Or don't JSON encode the variable in the first place.

Body:
That's what JSON.stringify does to a string:

→ node -pe 'JSON.stringify("5a0fc8ad4a9a9c2cd81a8853")'
"5a0fc8ad4a9a9c2cd81a8853"

You probably need to JSON.parse it on the server side.

→ node -pe 'JSON.parse("\"5a0fc8ad4a9a9c2cd81a8853\"")'
5a0fc8ad4a9a9c2cd81a8853

Or don't JSON encode the variable in the first place.


问:
Beautiful Soup find_all wraps together instead of individually
Long story short, I'm trying to use Beautiful Soup to replace b tags with strong tags.
Soup takes some input that includes

```<code><b>Words:</b> attributes
<b>Other Words:</b> other attributes
</code>```

I have the following python3 code:

```<code>strong_tag = soup.new_tag("strong")
if(soup.find('b')):
    for b_tag in soup.find_all('b'):
        b_tag.wrap(strong_tag)
</code>```

This outputs

```<code>attributes
<strong><b>Words:</b><b>Other Words:</b></strong> other attributes
</code>```

instead of

```<code><strong><b>Words:</b></strong> attributes
<strong><b>Other Words:</b></strong> other attributes
</code>```

How do I fix this?

I'm assuming that once I can fix this, I can extract() the contents from the b tags, leaving just the strong tags behind.

答:
You just need:

```<code>from bs4 import BeautifulSoup
div_test="""
<b>Words:</b> attributes
<b>Other Words:</b> other attributes
"""
soup = BeautifulSoup(div_test,'html.parser')
for b_tag in soup.find_all('b'):
    b_tag.wrap(soup.new_tag("strong"))
print(soup)
</code>```

this will print:

```<code><strong><b>Words:</b></strong> attributes
<strong><b>Other Words:</b></strong> other attributes
</code>```

Body:
Long story short, I'm trying to use Beautiful Soup to replace b tags with strong tags.
Soup takes some input that includes

Words: attributes
Other Words: other attributes

I have the following python3 code:

strong_tag = soup.new_tag("strong")
if(soup.find('b')):
    for b_tag in soup.find_all('b'):
        b_tag.wrap(strong_tag)

This outputs

attributes
Words:Other Words: other attributes

instead of

Words: attributes
Other Words: other attributes

How do I fix this?

I'm assuming that once I can fix this, I can extract() the contents from the b tags, leaving just the strong tags behind.

Body:
You just need:

from bs4 import BeautifulSoup
div_test="""
<b>Words:</b> attributes
<b>Other Words:</b> other attributes
"""
soup = BeautifulSoup(div_test,'html.parser')
for b_tag in soup.find_all('b'):
    b_tag.wrap(soup.new_tag("strong"))
print(soup)

this will print:

<strong><b>Words:</b></strong> attributes
<strong><b>Other Words:</b></strong> other attributes


问:
yowsup installation on windows
I am following these procedures for installation:
https://github.com/tgalal/yowsup/blob/master/README.md

and completed yowsup2 installation successfully with this command

```<code>pip install yowsup2
</code>```

and now I am trying to register my phone number in yowsup
as suggested here

but when I tried following command (yowsup is imported) it gives error

```<code>>>> yowsup-cli
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'cli' is not defined
</code>```

I am new to python

Please help me to solve this error :/

答:
this problem occured because your cmd can not find the yowsup-cli or can not find python. check your environment variables ,that you have set your python path or not,if not then see some videos and set it. Or type

```<code>python yowsup-cli
</code>```

and that will mostly run it.

Title: yowsup installation on windows

Body:
I am following these procedures for installation:
https://github.com/tgalal/yowsup/blob/master/README.md

and completed yowsup2 installation successfully with this command

pip install yowsup2

and now I am trying to register my phone number in yowsup
as suggested here

but when I tried following command (yowsup is imported) it gives error

>>> yowsup-cli
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'cli' is not defined

I am new to python

Please help me to solve this error :/

Body:
this problem occured because your cmd can not find the yowsup-cli or can not find python. check your environment variables ,that you have set your python path or not,if not then see some videos and set it. Or type

python yowsup-cli

and that will mostly run it.


问:
Save image from webview never save to local mobile phone
i already create a code to save image from webview. the code works but there are some problem, here is the code

```<code>public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

        final WebView.HitTestResult result = mWebView.getHitTestResult();
        if (result.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {

            //menu.setHeaderTitle(result.getExtra());
            menu.add(0, 1, 0, "Save Image")
                    .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {

                            String DownloadImageURL = result.getExtra();

                            if(URLUtil.isValidUrl(DownloadImageURL)){

                                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL));
                                request.allowScanningByMediaScanner();
                                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                DownloadManager downloadManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
                                downloadManager.enqueue(request);

                                Toast.makeText(getContext(),"Image save successfully.",Toast.LENGTH_SHORT).show();
                            }
                            else {
                                Toast.makeText(getContext(),"Error to save image.",Toast.LENGTH_SHORT).show();
                            }
                            return false;
                        }
                    });
        }
    }
</code>```

when i try to long click the image it will show dialog message to save the image, when i click on it, it will show toast message that says the image have been save succesfully and yes there a notification in my stat bar

the problem is, when i try to open my gallery and search for the image, i never find the image because it's not save to my local storage.

can you help me to fix the code?
thanks

答:
Tested your code and i got many error, but i already solved my problem

The gallery never show the downloaded images because storage scanner never scan them, in fact they are there in our manager. So what i did is to send a broadcast to tell storage that new images is come to storage

Body:
i already create a code to save image from webview. the code works but there are some problem, here is the code

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

        final WebView.HitTestResult result = mWebView.getHitTestResult();
        if (result.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {

            //menu.setHeaderTitle(result.getExtra());
            menu.add(0, 1, 0, "Save Image")
                    .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {

                            String DownloadImageURL = result.getExtra();

                            if(URLUtil.isValidUrl(DownloadImageURL)){

                                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL));
                                request.allowScanningByMediaScanner();
                                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                DownloadManager downloadManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
                                downloadManager.enqueue(request);

                                Toast.makeText(getContext(),"Image save successfully.",Toast.LENGTH_SHORT).show();
                            }
                            else {
                                Toast.makeText(getContext(),"Error to save image.",Toast.LENGTH_SHORT).show();
                            }
                            return false;
                        }
                    });
        }
    }

when i try to long click the image it will show dialog message to save the image, when i click on it, it will show toast message that says the image have been save succesfully and yes there a notification in my stat bar

the problem is, when i try to open my gallery and search for the image, i never find the image because it's not save to my local storage.

can you help me to fix the code?
thanks


问:
Requesting administrator privileges in C program?
I'm trying to make a C program that modifies my host file, but I can't just straight up open the file with the program, because Windows blocks it. Is there any way that I can make the program request administrative privileges within the code, or any script I can use to start the program in admin mode? </p>

答: Shoot, okay, seconds after posting this question, I found a solution. It turns out that you can right click the executable, click properties, and on the compatibility tab, select "Run this program as administrator". Just in case anyone else needed this information. </p>


问:
How to search address book with a phone number?
I just want to search my IPhone's address book by a received call's phone number. How can I proceed further in this case? Suppose my received call is in the format of (ISD code) xxxxxxxxxx, like (+1 1234567890) or (001 1234567890) or (+11234567890) or (+1 (123) 456-7890) or (1234567890 without ISD code) or something else. So how can I search the entire address book data base to get the contacts info by using only (ISD CODE)1234567890? Can somebody help me please?

Regards,
Prathap.

答:
Here's an interesting thing i learned about how Android handles caller id (how they quickly and easily get the name for an incoming call)

Instead of storing the phone numbers internally in an address book database as +1 (555) 666-1234, store them in reverse order such as 43216665551. That way when a call comes, in reverse the incoming phone number (43216665551), take just the first 10 digits (4321666555), and have your SQL look something like "WHERE phone_number LIKE "4321666555%"

This doesn't really answer your question, but someone may find this useful

ContentLicense: CC BY-SA 2.5


问:
using an input variable in multiple functions in python
I would like to know how to use the 'name' variable in the entername() function in the hello() function.

It is an input variable, does anyone know how to use it across multiple functions?

```<code>def entername():
    name = input("Please enter your name: ")
    return

def hello():
    text = "Hello " + name + ", welcome to the simulator..."
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        char, time.sleep(0.1)
    print(char)
    return
</code>```

答:
```<code>def entername():
    name = input("Please enter your name: ")
    return name

name = entername()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to know how to use the 'name' variable in the entername() function in the hello() function.

It is an input variable, does anyone know how to use it across multiple functions?

def entername():
    name = input("Please enter your name: ")
    return

def hello():
    text = "Hello " + name + ", welcome to the simulator..."
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        char, time.sleep(0.1)
    print(char)
    return


问:
Angular 4 router reload view when url queryParams change
I have a component who shows a list of item than can be filtered using url queryParams, thos items are paginated from the api, and if a filter is set, i need to call the first page again, this first call is in the resolver of the router, so what I need is that the router reload in the same way as if I came from other URL.

app.routes.ts

```<code>const appRoutes: Routes = [
    {
        path: 'applications',
        component: AppComponent,
        resolve: {
            data: AppResolve
        }
    },
]
</code>```

app.resolver.ts

```<code>@Injectable()
export class AppResolve implements Resolve<any> {
    constructor() {}
   resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
           // call to the api and the first 50 applications filtered by the url queryParams
    }
}
</code>```

app.component.ts

```<code>@Component({
    // ...
})
export class AppComponent {
    constructor(private route: ActivatedRoute,
              private appService: AppService) {
        this.route.data.subscribe((data: any) => {
            // recive the first 50 applications
        })
    }

    loadMoreApps(): void {
        // call to the api for the next 50 applications filtered by the url queryParams
    }
}
</code>```

app.service.ts

```<code>@Injectable()
export class AppService {
    constructor(private router: Router,
              private route: ActivatedRoute) {}
    navigate(urlQueryParams: any): void {
        this.router.navigate(['/applications'], {queryParams: urlQueryParams});
    }
}
</code>```

other.component.ts

```<code>@Component({
    // ...
})
export class OtherComponent {
    constructor(private appService: AppService) {}
    filterApps(): void {
        const filters = {
            'category': 'game',
            'author': 'username'
        }
        this.appService.navigate(filters)
    }
}
</code>```

答:
In the route set the property runGuardsAndResolvers to 'always' this way:

```<code>const appRoutes: Routes = [
{
    path: 'applications',
    component: AppComponent,
    resolve: {
        data: AppResolve
    },
    runGuardsAndResolvers: 'always' // <----- This line
}
</code>```

]

This will execute the resolve every time you access to the route.

Regards

Body:
I have a component who shows a list of item than can be filtered using url queryParams, thos items are paginated from the api, and if a filter is set, i need to call the first page again, this first call is in the resolver of the router, so what I need is that the router reload in the same way as if I came from other URL.

app.routes.ts

const appRoutes: Routes = [
    {
        path: 'applications',
        component: AppComponent,
        resolve: {
            data: AppResolve
        }
    },
]

app.resolver.ts

@Injectable()
export class AppResolve implements Resolve<any> {
    constructor() {}
   resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
           // call to the api and the first 50 applications filtered by the url queryParams
    }
}

app.component.ts

@Component({
    // ...
})
export class AppComponent {
    constructor(private route: ActivatedRoute,
              private appService: AppService) {
        this.route.data.subscribe((data: any) => {
            // recive the first 50 applications
        })
    }

    loadMoreApps(): void {
        // call to the api for the next 50 applications filtered by the url queryParams
    }
}

app.service.ts

@Injectable()
export class AppService {
    constructor(private router: Router,
              private route: ActivatedRoute) {}
    navigate(urlQueryParams: any): void {
        this.router.navigate(['/applications'], {queryParams: urlQueryParams});
    }
}

other.component.ts

@Component({
    // ...
})
export class OtherComponent {
    constructor(private appService: AppService) {}
    filterApps(): void {
        const filters = {
            'category': 'game',
            'author': 'username'
        }
        this.appService.navigate(filters)
    }
}

Body:
In the route set the property runGuardsAndResolvers to 'always' this way:

const appRoutes: Routes = [
{
    path: 'applications',
    component: AppComponent,
    resolve: {
        data: AppResolve
    },
    runGuardsAndResolvers: 'always' // <----- This line
}

]

This will execute the resolve every time you access to the route.

Regards


问:
How to convert \xXY encoded characters to UTF-8 in Python?
I have a text which contains characters such as "\xaf", "\xbe", which, as I understand it from this question, are ASCII encoded characters.

I want to convert them in Python to their UTF-8 equivalents. The usual string.encode("utf-8") throws UnicodeDecodeError. Is there some better way, e.g., with the codecs standard library?

Sample 200 characters here.

答:
It's not ASCII (ASCII codes only go up to 127; \xaf is 175). You first need to find out the correct encoding, decode that, and then re-encode in UTF-8.

Could you provide an actual string sample? Then we can probably guess the current encoding.


问:
How do you compute the mean of integers entered by the user that are evenly divisible by a number?
So far.. I have coded this:

```<code>While True:
    div_5 = []
    x = float(input("Please input an integer(negative if you want to stop: "))
    x = int(x)
    length = len(div_5)
    total_sum = sum(div_5)
    average = total_sum/length
    if x % 5:
        div_5.append(x)
    if x < 0:
        break
print(average)
</code>```

When I run the code, It says that line 7 has a ZeroDivisionError. What am I doing wrong? I am adding x if it is divisible by 5 to the list, why is saying this?
Any tips will be helpful for I am new to python.

This is what I need to do

I have been working on this for a week, hours at a time. I can't seem to get it correct.

答:
As I said in the comments:

You need to create the div_5 list before the start of the while loop.

You're supposed to read integer input, so that float call is useless.

Test if x is negative immediately after you read it.

Don't compute the average until you break out of the loop, and don't compute it if there's no data in the list.

Also, your test for divisibility is backwards: x % 5 is zero if x is divisible by 5, and zero is considered False.

Here's a repaired version of your code.

```<code>div_5 = []
while True:
    x = int(input("Please input an integer (negative if you want to stop): "))
    if x < 0:
        break
    if x % 5 == 0:
        div_5.append(x)

if div_5:
    average = sum(div_5) / len(div_5)
else:
    average = 0
print(average)
</code>```

Demo

Please input an integer (negative if you want to stop): 1
Please input an integer (negative if you want to stop): 5
Please input an integer (negative if you want to stop): 6
Please input an integer (negative if you want to stop): 10
Please input an integer (negative if you want to stop): -4
7.5
```

When we break out of the main loop the test if div_5 test if there are any numbers in the div_5 list and only performs the division if there are. If there are no numbers in the list, then the average is zero.

Body:
So far.. I have coded this:

While True:
    div_5 = []
    x = float(input("Please input an integer(negative if you want to stop: "))
    x = int(x)
    length = len(div_5)
    total_sum = sum(div_5)
    average = total_sum/length
    if x % 5:
        div_5.append(x)
    if x < 0:
        break
print(average)

When I run the code, It says that line 7 has a ZeroDivisionError. What am I doing wrong? I am adding x if it is divisible by 5 to the list, why is saying this?
Any tips will be helpful for I am new to python.

This is what I need to do

I have been working on this for a week, hours at a time. I can't seem to get it correct.

Body:
As I said in the comments:

You need to create the div_5 list before the start of the while loop.

You're supposed to read integer input, so that float call is useless.

Test if x is negative immediately after you read it.

Don't compute the average until you break out of the loop, and don't compute it if there's no data in the list.

Also, your test for divisibility is backwards: x % 5 is zero if x is divisible by 5, and zero is considered False.

Here's a repaired version of your code.

div_5 = []
while True:
    x = int(input("Please input an integer (negative if you want to stop): "))
    if x < 0:
        break
    if x % 5 == 0:
        div_5.append(x)

if div_5:
    average = sum(div_5) / len(div_5)
else:
    average = 0
print(average)

Demo

Please input an integer (negative if you want to stop): 1
Please input an integer (negative if you want to stop): 5
Please input an integer (negative if you want to stop): 6
Please input an integer (negative if you want to stop): 10
Please input an integer (negative if you want to stop): -4
7.5

When we break out of the main loop the test if div_5 test if there are any numbers in the div_5 list and only performs the division if there are. If there are no numbers in the list, then the average is zero.


问:
Jmeter - Is it possible to pass query through variable
Is it possible to pass query through variable? What I need is:
1. Get multiple queries from csv file.
2. Execute them one by one.
3. Store results

答:
Yes you can do it by using CSV Data Set config and Bean shell post processor.

Step 1: Need to read queries from CSV file.

Step 2: Use JDBC request to query the database. I'm assuming that you already created database JDBC pool with the help of JDBC Connection Configuration

Step 3: Use Bean Shell post processor to save the results into a file.


问:
Having trouble with discord.py bot repeating itself with on_message() and modifying user messages
I'm trying to use the on_message() command to get the bot to recognize a specific kind of message, and return a modified version of that message; Here's an example:

```<code>import discord
import asyncio
from discord.ext.commands import Bot
from discord.ext import commands
import platform
import logging

logging.basicConfig(level=logging.INFO)

client = Bot(description="Basic Bot by Habchy#1665", command_prefix="!",     pm_help = True)

@client.command()
async def ping(*args):

    await client.say(":ping_pong: Pong!")
    await asyncio.sleep(3)

@client.event
async def on_message(message):

    if message.content.startswith('ABDD'):

        newMessage = message.content[:]

        newMessage.replace("D","C",1)

        await client.send_message(message.channel, "Fixed!")
        await client.send_message(message.channel, newMessage)

    await client.process_commands(message)

client.run('my auth code')
</code>```

The first problem I'm experiencing is that my bot repeats the messages "Fixed!" and "ABDD" constantly until I shut it down.

The second problem I have is that it doesn't seem to be changing "ABDD" to "ABCD"

I'm fairly new to the whole bot making thing, and I would love some help on this problem. Thanks!

I'm using Habchy's BasicBot as a framework for my bot.

答:
I cannot tell you what is causing the repeated messages, but the reason that it doesn't change ABDD to ABCD is because str.replace() returns a new string instead of edits an old one.

Change newMessage.replace("D","C",1) to newMessage =  newMessage.replace("D","C",1)

Body:
I'm trying to use the on_message() command to get the bot to recognize a specific kind of message, and return a modified version of that message; Here's an example:

import discord
import asyncio
from discord.ext.commands import Bot
from discord.ext import commands
import platform
import logging

logging.basicConfig(level=logging.INFO)

client = Bot(description="Basic Bot by Habchy#1665", command_prefix="!",     pm_help = True)

@client.command()
async def ping(*args):

    await client.say(":ping_pong: Pong!")
    await asyncio.sleep(3)

@client.event
async def on_message(message):

    if message.content.startswith('ABDD'):

        newMessage = message.content[:]

        newMessage.replace("D","C",1)

        await client.send_message(message.channel, "Fixed!")
        await client.send_message(message.channel, newMessage)

    await client.process_commands(message)

client.run('my auth code')

The first problem I'm experiencing is that my bot repeats the messages "Fixed!" and "ABDD" constantly until I shut it down.

The second problem I have is that it doesn't seem to be changing "ABDD" to "ABCD"

I'm fairly new to the whole bot making thing, and I would love some help on this problem. Thanks!

I'm using Habchy's BasicBot as a framework for my bot.


问:
My DatePickerDialog not showing the current date. How to get Current date in DatePickerDialog?
I used TimepickerDialog and DatePicker Dialog to get the Time and Date.
But when open the Date Picker Dialog it showing different date click to view

Here is my code.

```<code>         final Calendar calendar = Calendar.getInstance();

            dt_day = calendar.get(Calendar.DAY_OF_MONTH);
            dt_month =calendar.get(Calendar.MONTH);
            dt_year = calendar.get(Calendar.YEAR);
           final DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                 //     datePickerDialog.updateDate(12,12,1993);
                date.setText(dayOfMonth + "/" + (month+1) + "/" + year);
                str_date = String.valueOf(dayOfMonth + "/" + (month+1) + "/" + year);
            }
        },dt_day, dt_month,dt_year);

        datePickerDialog.show();
</code>```

答: You have given wrong values in parameter, the third parameter should be dt_year and the fifth parameter should be dt_day</p>

Body:
I used TimepickerDialog and DatePicker Dialog to get the Time and Date.
But when open the Date Picker Dialog it showing different date click to view

Here is my code.

         final Calendar calendar = Calendar.getInstance();

            dt_day = calendar.get(Calendar.DAY_OF_MONTH);
            dt_month =calendar.get(Calendar.MONTH);
            dt_year = calendar.get(Calendar.YEAR);
           final DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                 //     datePickerDialog.updateDate(12,12,1993);
                date.setText(dayOfMonth + "/" + (month+1) + "/" + year);
                str_date = String.valueOf(dayOfMonth + "/" + (month+1) + "/" + year);
            }
        },dt_day, dt_month,dt_year);

        datePickerDialog.show();


问:
Vista 64-bit Development Caveats
I'm migrating my development workstation from 32-bit Vista to 64-bit Vista.

The production platform is 32-bit Windows Server and SQL Server 2008.

Does anyone know of any issues with migrating the code base?

EDIT:

the system consists of web forms, c# code, stored procedures.

there is also ajax.net, ssrs, ssis, and dynamic reports/graphs from dundas.

however, i think other users might appreciate any lessons learned or feedback in general regarding this move.

FINDINGS:

As of Jan 24, 2009

Checkpoint VPN does not support Vista 64 (actually it seems that very few do)

Cropper utility required special download and rebuild to work on Vista 64 (Cropper looks very nice, but it lacks scrollable window capture)

The lack of support for Vista 64 made it not worth while for me.  I wish someone would have mentioned the lack of VPN support, but there is currently no vpn vendor that supports 64 bit clients....  So be forwarned - as of 1/28/2009 - using Vista 64 is not a good option for those of us who need vpn.

答:
I have done exactly this - migrated my workstation to Vista 64 whilst still deploying code to 32-bit Win2008 servers.

Generally, your biggest problem will be the WOW64 emulation layer - which means that 32-bit processes and 64-bit processes see different versions of the same resources (registry keys, system folders, and so on.) In .NET, there's an enumeration System.Environment.SpecialFolder which will give you safely abstracted access to Program Files, Application Data and other potentially risky system folders. You'll also need to force IIS to run in 32-bit compatibility mode (it can't run 64-bit and 32-bit web apps simultaneously) - instructions at http://support.microsoft.com/kb/894435

There's nothing insurmountable, though - I'm successfully compiling COM-visible .NET assemblies on Vista x64 (setting the compiler to target x86 CPUs), and then deploying them alongside ASP.NET and legacy ASP code running 32-bit COM objects on a 32-bit server, and it's all working very well. There's some notes you might find useful posted on my blog; biggest headache I encountered personally was that 32-bit applications (including my favourite text editor) can't see C:\Windows\System32 any more... but even that's easy enough to work around.

OwnerDisplayName: mson

Title: Vista 64-bit Development Caveats

LastEditorDisplayName: mson

OwnerDisplayName: Dylan Beattie


问:
Encoding error PostgreSQL 8.4
I am importing data from a CSV file. One of the fields has an accent(Telefónica O2 UK Limited). The application throws en error while inserting the data to the table.

```<code>PGError: ERROR:  invalid byte sequence for encoding "UTF8": 0xf36e6963
HINT:  This error can also happen if the byte sequence does not match the
encoding expected by the server, which is controlled by "client_encoding".
: INSERT INTO "companies" ("name", "validated")
    VALUES(E'Telef?nica O2 UK Limited', 't')
</code>```

The data entry through the forms works when I enter names with accents and umlaut.
How do I workaround this issue?

Edit

I addressed the issue by converting the file encoding. I uploaded the CSV file to Google docs and exported the file to CSV.

答:
I think you can try to use the Ruby gem rchardet, which may be a better solution. Example code:

```<code>require ‘rchardet’

cd = CharDet.detect(string_of_unknown_encoding)
encoding = cd['encoding']
converted_string = Iconv.conv(‘UTF-8′, encoding, str_of_unknown_encoding)
</code>```

Here are some related links:

https://github.com/jmhodges/rchardet

http://www.meeho.net/blog/2010/03/ruby-how-to-detect-the-encoding-of-a-string/

Title: Encoding error PostgreSQL 8.4

Body:
I am importing data from a CSV file. One of the fields has an accent(Telefónica O2 UK Limited). The application throws en error while inserting the data to the table.

PGError: ERROR:  invalid byte sequence for encoding "UTF8": 0xf36e6963
HINT:  This error can also happen if the byte sequence does not match the
encoding expected by the server, which is controlled by "client_encoding".
: INSERT INTO "companies" ("name", "validated")
    VALUES(E'Telef?nica O2 UK Limited', 't')

The data entry through the forms works when I enter names with accents and umlaut.
How do I workaround this issue?

Edit

I addressed the issue by converting the file encoding. I uploaded the CSV file to Google docs and exported the file to CSV.

Body:
I think you can try to use the Ruby gem rchardet, which may be a better solution. Example code:

require ‘rchardet’

cd = CharDet.detect(string_of_unknown_encoding)
encoding = cd['encoding']
converted_string = Iconv.conv(‘UTF-8′, encoding, str_of_unknown_encoding)

Here are some related links:

https://github.com/jmhodges/rchardet

http://www.meeho.net/blog/2010/03/ruby-how-to-detect-the-encoding-of-a-string/


问:
How can I effectively save a value in the OnPropertyChangedEvent?
I'm implementing MVVM and trying to save a value from my Xaml page's Switch. I would like to have this value stored into the Application's properties. Currently, saving the value where I am triggers OnPropertyChanged again, and the value is never updated.

I have a BaseViewModel class:

```<code>public class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected void SetValue<T>(ref T backingField, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(backingField, value))
            return;

        backingField = value;

        OnPropertyChanged(propertyName);
    }
}
</code>```

In my ViewModel:

```<code>private bool _sizeToggled;
public bool SizeToggled
{
    get { return _sizeToggled; }
    set
    {
      SetValue(ref _sizeToggled, value);
      OnPropertyChanged(nameof(SizeToggled));
      SaveValue();
    }
}

private void SaveValue(){
Application.Current.Properties["SizeToggled"] = SizeToggled;
}
</code>```

And my Xaml code:

```<code><StackLayout Orientation="Horizontal" Padding="10,0,0,0">
    <Label Text="Size:" FontAttributes="Bold"/>
    <Switch IsToggled="{Binding SizeToggled}"
                       HorizontalOptions="EndAndExpand"/>
</StackLayout>
</code>```

How can I implement my SaveValue() Method so that the Application's Properties will be stored/updated when the value is updated?

答: have you checked that the vm is really your datacontext? </p>

Body:
I'm implementing MVVM and trying to save a value from my Xaml page's Switch. I would like to have this value stored into the Application's properties. Currently, saving the value where I am triggers OnPropertyChanged again, and the value is never updated.

I have a BaseViewModel class:

public class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected void SetValue<T>(ref T backingField, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(backingField, value))
            return;

        backingField = value;

        OnPropertyChanged(propertyName);
    }
}

In my ViewModel:

private bool _sizeToggled;
public bool SizeToggled
{
    get { return _sizeToggled; }
    set
    {
      SetValue(ref _sizeToggled, value);
      OnPropertyChanged(nameof(SizeToggled));
      SaveValue();
    }
}

private void SaveValue(){
Application.Current.Properties["SizeToggled"] = SizeToggled;
}

And my Xaml code:

<StackLayout Orientation="Horizontal" Padding="10,0,0,0">

    <Switch IsToggled="{Binding SizeToggled}"
                       HorizontalOptions="EndAndExpand"/>
</StackLayout>

How can I implement my SaveValue() Method so that the Application's Properties will be stored/updated when the value is updated?


问:
Valgrind: Definitely Lost Memory Leak in C Program
I'm writing a maze problem program. I can get the direction of the path successfully. However, I get definitely lost and errors from valgrind report. What's problem in my code?

The following is my code:

```<code>002: #include <stdio.h>
003: #include <stdlib.h>
004: #include <string.h>
005:
006: struct each_path {
007:     int step_nums, coin_nums;
008:     char **step_dir;
009: };
010:
011: void initial_value();
012: void *readFile(char *fileName);
013: void maze_1Dto2D(char *array);
014: void visit(int, int);
015: void display_direction();
016: struct each_path *epath;
017: int path_assume_num;
018: char *maze1D, **maze2D, **maze2D_tmp;
019: int maze_height, maze_width;
020: int startI = 1, startJ = 1, endI, endJ;  // entrance & exit
021: int path_nums, coin_nums, min_step_num, min_path_num;
022:
023:
024: int main(void) {
025:     char *maze_txtfile;
026:     int i, j;
027:
028:     // the first maze
029:     initial_value();
030:     maze_txtfile = readFile("maze2.txt");
031:     maze2D_tmp = malloc( maze_height * sizeof(*maze2D_tmp));
032:     for ( i = 0; i < maze_height; ++i ) {
033:         maze2D_tmp[i] = malloc(maze_width + 1);
034:         memcpy(maze2D_tmp[i], maze2D[i], maze_width + 1);
035:     }
036:     epath = malloc(path_assume_num * sizeof(*epath));
037:     for ( i = 0; i < path_assume_num; ++i) {
038:         epath[i].step_dir = malloc(10 * sizeof(*epath[i].step_dir));
039:         for ( j = 0; j < 10; ++j)
040:             epath[i].step_dir[j] = malloc(6);
041:     }
042:
043:     endI = maze_height - 2;
044:     endJ = maze_width - 2;
045:     visit(startI, startJ);
046:     display_direction();
047:
048:     for ( i = 0; i < path_nums; ++i) {
049:         for ( j = 0; j < epath[i].step_nums; ++j)
050:             free(epath[i].step_dir[j]);
051:         free(epath[i].step_dir);
052:     }
053:     for ( i = 0; i < maze_height; ++i) {
054:         free(maze2D[i]);
055:         free(maze2D_tmp[i]);
056:     }
057:     free(maze1D);
058:     free(maze2D);
059:     free(maze2D_tmp);
060:     free(epath);
061:
062:     exit(0);
063: }
064:
065: void initial_value() {
066:     path_assume_num = 1;
067:     maze_height = 0;
068:     maze_width = 0;
069:     path_nums = 0;
070:     coin_nums = 0;
071:     min_step_num = 100000;
072: }
073:
074:
075: void *readFile(char *fileName) {
076:     FILE *file = fopen(fileName, "r");
077:     size_t maze_unit_num = 0, maze_assume_size = 100;
078:     int maze_unit;
079:
080:     if (file == NULL)
081:         return NULL; //could not open file
082:
083:     maze1D = malloc(maze_assume_size);
084:
085:     while ((maze_unit = fgetc(file)) != EOF)
086:     {
087:         if (maze_unit_num >= maze_assume_size)
088:         {
089:             maze_assume_size *= 2;
090:             maze1D = realloc(maze1D, maze_assume_size);
091:         }
092:         maze1D[maze_unit_num] = (char) maze_unit;
093:
094:         if (maze1D[maze_unit_num] == '\n')
095:         {
096:             if (maze_height == 0)
097:                 maze_width = maze_unit_num - 1;
098:             maze_height++;
099:         }
100:         maze_unit_num++;
101:     }
102:     maze1D = realloc(maze1D, maze_unit_num + 1);
103:     maze1D[maze_unit_num] = '\0';
104:     maze_1Dto2D(maze1D);
105: }
106:
107: void maze_1Dto2D(char *array) {
108:     size_t i = 0, j = 0, num = 0;
109:     maze2D = malloc( maze_height * sizeof(*maze2D));
110:
111:     for ( i = 0; i < maze_height ; ++i)
112:     {
113:         maze2D[i] = malloc(maze_width + 1);
114:         for ( j = 0; j < maze_width + 1; ++j, ++num)
115:         {
116:             maze2D[i][j] = array[num];
117:
118:             if (array[num] == '\r')
119:                 --j;
120:             else if (array[num] == '\n')
121:                 maze2D[i][j] = '\0';
122:             else
123:                 maze2D[i][j] = array[num];
124:         }
125:     }
126: }
127:
128: void visit(int i, int j) {
129:     int preI, preJ, curI = 1, curJ = 1;
130:     int step_nums = 0, step_assume_num = 10; // entrance is not included
131:     char dir[6];
132:     int m, n;
133:
134:     if (maze2D_tmp[i][j] == '2')
135:         coin_nums++;
136:     maze2D_tmp[i][j] = '3';
137:     if (i == endI && j == endJ) {
138:         if (path_nums >= path_assume_num) {
139:             path_assume_num *= 2;
140:             epath = realloc(epath, path_assume_num * sizeof(*epath));
141:             for ( m = path_assume_num / 2; m < path_assume_num; ++m) {
142:                 epath[m].step_dir = malloc(10 * sizeof(*epath[m].step_dir));
143:                 for ( n = 0; n < 10; ++n)
144:                     epath[m].step_dir[n] = malloc(6);
145:             }
146:         }
147:         while (curI != endI || curJ != endJ)
148:         {
149:             if (step_nums >= step_assume_num) {
150:                 step_assume_num *= 2;
151:                 epath[path_nums].step_dir = realloc(epath[path_nums].step_dir, step_assume_num * sizeof(*epath[path_nums].step_dir));
152:                 for ( m = step_assume_num / 2; m < step_assume_num; ++m)
153:                     epath[path_nums].step_dir[m] = malloc(6);
154:             }
155:
156:             if ( maze2D_tmp[curI][curJ + 1] == '3' && preJ != (curJ + 1) ) {
157:                 preI = curI;
158:                 preJ = curJ;
159:                 curJ++;
160:                 strcpy(dir, "right");
161:
162:             }
163:             else if ( maze2D_tmp[curI + 1][curJ] == '3' && preI != (curI + 1) ) {
164:                 preI = curI;
165:                 preJ = curJ;
166:                 curI++;
167:                 strcpy(dir, "down");
168:             }
169:             else if ( maze2D_tmp[curI - 1][curJ] == '3' && preI != (curI - 1) ) {
170:                 preI = curI;
171:                 preJ = curJ;
172:                 curI--;
173:                 strcpy(dir, "up");
174:             }
175:             else if ( maze2D_tmp[curI][curJ - 1] == '3' && preJ != (curJ - 1)) {
176:                 preI = curI;
177:                 preJ = curJ;
178:                 curJ--;
179:                 strcpy(dir, "left");
180:             }
181:             strcpy(epath[path_nums].step_dir[step_nums], dir);
182:             step_nums++;
183:         }
184:         epath[path_nums].step_dir = realloc(epath[path_nums].step_dir, step_nums * sizeof(*epath[path_nums].step_dir));
185:         epath[path_nums].step_nums = step_nums;
186:         epath[path_nums].coin_nums = coin_nums;
187:         path_nums++;
188:         if (step_nums < min_step_num)
189:         {
190:             min_step_num = step_nums;
191:             min_path_num = path_nums;
192:         }
193:     }
194:
195:     if (maze2D_tmp[i][j + 1] == '1' || maze2D_tmp[i][j + 1] == '2') visit(i, j + 1);
196:     if (maze2D_tmp[i + 1][j] == '1' || maze2D_tmp[i + 1][j] == '2') visit(i + 1, j);
197:     if (maze2D_tmp[i][j - 1] == '1' || maze2D_tmp[i][j - 1] == '2') visit(i, j - 1);
198:     if (maze2D_tmp[i - 1][j] == '1' || maze2D_tmp[i - 1][j] == '2') visit(i - 1, j);
199:
200:     if (maze2D[i][j] == '2')
201:     {
202:         maze2D_tmp[i][j] = '2';
203:         coin_nums--;
204:     }
205:     else
206:         maze2D_tmp[i][j] = '1';
207: }
208:
209: void display_direction() {
210:     int i;
211:     for ( i = 0; i < min_step_num; ++i)
212:         printf("%s\n", epath[min_path_num - 1].step_dir[i]);
213:     printf("coin numbers:%d\n", epath[min_path_num - 1].coin_nums);
214: }
</code>```

Valgrind report:

I get "definitely lost: 1,908 bytes in 318 blocks" from leak summary and
4 errors from 4 contexts (suppressed: 0 from 0) from error summary.
What might contribute to these error messages?

```<code>==3410== HEAP SUMMARY:
==3410==     in use at exit: 2,460 bytes in 319 blocks
==3410==   total heap usage: 742 allocs, 423 frees, 37,249 bytes allocated
==3410==
==3410== 954 bytes in 159 blocks are definitely lost in loss record 2 of 3
==3410==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3410==    by 0x401007: visit (4thesecondmaze.c:153)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x4012EC: visit (4thesecondmaze.c:195)
==3410==    by 0x4012EC: visit (4thesecondmaze.c:195)
==3410==    by 0x4012EC: visit (4thesecondmaze.c:195)
==3410==
==3410== 954 bytes in 159 blocks are definitely lost in loss record 3 of 3
==3410==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3410==    by 0x401007: visit (4thesecondmaze.c:153)
==3410==    by 0x4012EC: visit (4thesecondmaze.c:195)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x4013BA: visit (4thesecondmaze.c:197)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x4012EC: visit (4thesecondmaze.c:195)
==3410==
==3410== LEAK SUMMARY:
==3410==    definitely lost: 1,908 bytes in 318 blocks
==3410==    indirectly lost: 0 bytes in 0 blocks
==3410==      possibly lost: 0 bytes in 0 blocks
==3410==    still reachable: 552 bytes in 1 blocks
==3410==         suppressed: 0 bytes in 0 blocks
==3410== Reachable blocks (those to which a pointer was found) are not shown.
==3410== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 0 from 0)
</code>```

答:
On line 153, you are allocating a bunch of memory blocks into step_dir, and end up with step_assume_num allocated blocks.

Later, on line 184, you call realloc to reduce the allocated memory for step_dir to the amount actually used, step_num blocks.  The blocks allocated but not used (from step_num + 1 to step_assume_num) have not been freed.  You need to free these blocks before reducing the array size.

Body:
I'm writing a maze problem program. I can get the direction of the path successfully. However, I get definitely lost and errors from valgrind report. What's problem in my code?

The following is my code:

002: #include <stdio.h>
003: #include <stdlib.h>
004: #include <string.h>
005:
006: struct each_path {
007:     int step_nums, coin_nums;
008:     char **step_dir;
009: };
010:
011: void initial_value();
012: void *readFile(char *fileName);
013: void maze_1Dto2D(char *array);
014: void visit(int, int);
015: void display_direction();
016: struct each_path *epath;
017: int path_assume_num;
018: char *maze1D, **maze2D, **maze2D_tmp;
019: int maze_height, maze_width;
020: int startI = 1, startJ = 1, endI, endJ;  // entrance & exit
021: int path_nums, coin_nums, min_step_num, min_path_num;
022:
023:
024: int main(void) {
025:     char *maze_txtfile;
026:     int i, j;
027:
028:     // the first maze
029:     initial_value();
030:     maze_txtfile = readFile("maze2.txt");
031:     maze2D_tmp = malloc( maze_height * sizeof(*maze2D_tmp));
032:     for ( i = 0; i < maze_height; ++i ) {
033:         maze2D_tmp[i] = malloc(maze_width + 1);
034:         memcpy(maze2D_tmp[i], maze2D[i], maze_width + 1);
035:     }
036:     epath = malloc(path_assume_num * sizeof(*epath));
037:     for ( i = 0; i < path_assume_num; ++i) {
038:         epath[i].step_dir = malloc(10 * sizeof(*epath[i].step_dir));
039:         for ( j = 0; j < 10; ++j)
040:             epath[i].step_dir[j] = malloc(6);
041:     }
042:
043:     endI = maze_height - 2;
044:     endJ = maze_width - 2;
045:     visit(startI, startJ);
046:     display_direction();
047:
048:     for ( i = 0; i < path_nums; ++i) {
049:         for ( j = 0; j < epath[i].step_nums; ++j)
050:             free(epath[i].step_dir[j]);
051:         free(epath[i].step_dir);
052:     }
053:     for ( i = 0; i < maze_height; ++i) {
054:         free(maze2D[i]);
055:         free(maze2D_tmp[i]);
056:     }
057:     free(maze1D);
058:     free(maze2D);
059:     free(maze2D_tmp);
060:     free(epath);
061:
062:     exit(0);
063: }
064:
065: void initial_value() {
066:     path_assume_num = 1;
067:     maze_height = 0;
068:     maze_width = 0;
069:     path_nums = 0;
070:     coin_nums = 0;
071:     min_step_num = 100000;
072: }
073:
074:
075: void *readFile(char *fileName) {
076:     FILE *file = fopen(fileName, "r");
077:     size_t maze_unit_num = 0, maze_assume_size = 100;
078:     int maze_unit;
079:
080:     if (file == NULL)
081:         return NULL; //could not open file
082:
083:     maze1D = malloc(maze_assume_size);
084:
085:     while ((maze_unit = fgetc(file)) != EOF)
086:     {
087:         if (maze_unit_num >= maze_assume_size)
088:         {
089:             maze_assume_size *= 2;
090:             maze1D = realloc(maze1D, maze_assume_size);
091:         }
092:         maze1D[maze_unit_num] = (char) maze_unit;
093:
094:         if (maze1D[maze_unit_num] == '\n')
095:         {
096:             if (maze_height == 0)
097:                 maze_width = maze_unit_num - 1;
098:             maze_height++;
099:         }
100:         maze_unit_num++;
101:     }
102:     maze1D = realloc(maze1D, maze_unit_num + 1);
103:     maze1D[maze_unit_num] = '\0';
104:     maze_1Dto2D(maze1D);
105: }
106:
107: void maze_1Dto2D(char *array) {
108:     size_t i = 0, j = 0, num = 0;
109:     maze2D = malloc( maze_height * sizeof(*maze2D));
110:
111:     for ( i = 0; i < maze_height ; ++i)
112:     {
113:         maze2D[i] = malloc(maze_width + 1);
114:         for ( j = 0; j < maze_width + 1; ++j, ++num)
115:         {
116:             maze2D[i][j] = array[num];
117:
118:             if (array[num] == '\r')
119:                 --j;
120:             else if (array[num] == '\n')
121:                 maze2D[i][j] = '\0';
122:             else
123:                 maze2D[i][j] = array[num];
124:         }
125:     }
126: }
127:
128: void visit(int i, int j) {
129:     int preI, preJ, curI = 1, curJ = 1;
130:     int step_nums = 0, step_assume_num = 10; // entrance is not included
131:     char dir[6];
132:     int m, n;
133:
134:     if (maze2D_tmp[i][j] == '2')
135:         coin_nums++;
136:     maze2D_tmp[i][j] = '3';
137:     if (i == endI && j == endJ) {
138:         if (path_nums >= path_assume_num) {
139:             path_assume_num *= 2;
140:             epath = realloc(epath, path_assume_num * sizeof(*epath));
141:             for ( m = path_assume_num / 2; m < path_assume_num; ++m) {
142:                 epath[m].step_dir = malloc(10 * sizeof(*epath[m].step_dir));
143:                 for ( n = 0; n < 10; ++n)
144:                     epath[m].step_dir[n] = malloc(6);
145:             }
146:         }
147:         while (curI != endI || curJ != endJ)
148:         {
149:             if (step_nums >= step_assume_num) {
150:                 step_assume_num *= 2;
151:                 epath[path_nums].step_dir = realloc(epath[path_nums].step_dir, step_assume_num * sizeof(*epath[path_nums].step_dir));
152:                 for ( m = step_assume_num / 2; m < step_assume_num; ++m)
153:                     epath[path_nums].step_dir[m] = malloc(6);
154:             }
155:
156:             if ( maze2D_tmp[curI][curJ + 1] == '3' && preJ != (curJ + 1) ) {
157:                 preI = curI;
158:                 preJ = curJ;
159:                 curJ++;
160:                 strcpy(dir, "right");
161:
162:             }
163:             else if ( maze2D_tmp[curI + 1][curJ] == '3' && preI != (curI + 1) ) {
164:                 preI = curI;
165:                 preJ = curJ;
166:                 curI++;
167:                 strcpy(dir, "down");
168:             }
169:             else if ( maze2D_tmp[curI - 1][curJ] == '3' && preI != (curI - 1) ) {
170:                 preI = curI;
171:                 preJ = curJ;
172:                 curI--;
173:                 strcpy(dir, "up");
174:             }
175:             else if ( maze2D_tmp[curI][curJ - 1] == '3' && preJ != (curJ - 1)) {
176:                 preI = curI;
177:                 preJ = curJ;
178:                 curJ--;
179:                 strcpy(dir, "left");
180:             }
181:             strcpy(epath[path_nums].step_dir[step_nums], dir);
182:             step_nums++;
183:         }
184:         epath[path_nums].step_dir = realloc(epath[path_nums].step_dir, step_nums * sizeof(*epath[path_nums].step_dir));
185:         epath[path_nums].step_nums = step_nums;
186:         epath[path_nums].coin_nums = coin_nums;
187:         path_nums++;
188:         if (step_nums < min_step_num)
189:         {
190:             min_step_num = step_nums;
191:             min_path_num = path_nums;
192:         }
193:     }
194:
195:     if (maze2D_tmp[i][j + 1] == '1' || maze2D_tmp[i][j + 1] == '2') visit(i, j + 1);
196:     if (maze2D_tmp[i + 1][j] == '1' || maze2D_tmp[i + 1][j] == '2') visit(i + 1, j);
197:     if (maze2D_tmp[i][j - 1] == '1' || maze2D_tmp[i][j - 1] == '2') visit(i, j - 1);
198:     if (maze2D_tmp[i - 1][j] == '1' || maze2D_tmp[i - 1][j] == '2') visit(i - 1, j);
199:
200:     if (maze2D[i][j] == '2')
201:     {
202:         maze2D_tmp[i][j] = '2';
203:         coin_nums--;
204:     }
205:     else
206:         maze2D_tmp[i][j] = '1';
207: }
208:
209: void display_direction() {
210:     int i;
211:     for ( i = 0; i < min_step_num; ++i)
212:         printf("%s\n", epath[min_path_num - 1].step_dir[i]);
213:     printf("coin numbers:%d\n", epath[min_path_num - 1].coin_nums);
214: }

Valgrind report:

I get "definitely lost: 1,908 bytes in 318 blocks" from leak summary and
4 errors from 4 contexts (suppressed: 0 from 0) from error summary.
What might contribute to these error messages?

==3410== HEAP SUMMARY:
==3410==     in use at exit: 2,460 bytes in 319 blocks
==3410==   total heap usage: 742 allocs, 423 frees, 37,249 bytes allocated
==3410==
==3410== 954 bytes in 159 blocks are definitely lost in loss record 2 of 3
==3410==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3410==    by 0x401007: visit (4thesecondmaze.c:153)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x4012EC: visit (4thesecondmaze.c:195)
==3410==    by 0x4012EC: visit (4thesecondmaze.c:195)
==3410==    by 0x4012EC: visit (4thesecondmaze.c:195)
==3410==
==3410== 954 bytes in 159 blocks are definitely lost in loss record 3 of 3
==3410==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3410==    by 0x401007: visit (4thesecondmaze.c:153)
==3410==    by 0x4012EC: visit (4thesecondmaze.c:195)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x4013BA: visit (4thesecondmaze.c:197)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x401352: visit (4thesecondmaze.c:196)
==3410==    by 0x4012EC: visit (4thesecondmaze.c:195)
==3410==
==3410== LEAK SUMMARY:
==3410==    definitely lost: 1,908 bytes in 318 blocks
==3410==    indirectly lost: 0 bytes in 0 blocks
==3410==      possibly lost: 0 bytes in 0 blocks
==3410==    still reachable: 552 bytes in 1 blocks
==3410==         suppressed: 0 bytes in 0 blocks
==3410== Reachable blocks (those to which a pointer was found) are not shown.
==3410== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 0 from 0)


问:
Datepicker does not display the calendar
I have in my application a form where I can chose a date from a datepicker calendar. When I refresh my page, the datepicker calendar appears when clicking the form. This is the correct behaviour.

However when I reach the same page from another page using a link, the calendar does not appear after clicking the form. I have to refresh the page in order to make the calendar visible.

Here is my form page:

```<code># app/views/reservations/_form.html.erb
...

      <div class="row reservations">
        <div class="span2 field">
          <%= f.label :mydate %><br />
          <%= f.text_field :mydate, class: "input-append date datepicker", value: Date.today.strftime('%d-%m-%Y') %>
        </div>
...
</code>```

My javascript code:

```<code># app/assets/javascripts/reservations.js.coffee
$ -> $('.date').datepicker({
    format: 'dd-mm-yyyy'
    autoclose: true
    todayHighlight: true
    language: 'fr'
});
</code>```

And the Gemfile:

```<code>source 'https://rubygems.org'

ruby "2.0.0"

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.0.beta1'
gem 'bootstrap-sass', '2.3.1.0'
gem 'bcrypt-ruby', '3.0.1'
gem 'protected_attributes'
gem 'will_paginate'
gem 'bootstrap-will_paginate'
gem 'bootstrap-datepicker-rails'
gem 'rails-i18n'

gem 'pg'

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 4.0.0.beta1'
  gem 'coffee-rails', '~> 4.0.0.beta1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer', platforms: :ruby

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.0.1'
</code>```

答:
The simplest solution for this is use the method: :get in the link_to

```<code><%= link_to "Create New Form", sampleform_path, method: :get %>
</code>```

Body:
I have in my application a form where I can chose a date from a datepicker calendar. When I refresh my page, the datepicker calendar appears when clicking the form. This is the correct behaviour.

However when I reach the same page from another page using a link, the calendar does not appear after clicking the form. I have to refresh the page in order to make the calendar visible.

Here is my form page:

# app/views/reservations/_form.html.erb
...

          <%= f.label :mydate %>

          <%= f.text_field :mydate, class: "input-append date datepicker", value: Date.today.strftime('%d-%m-%Y') %>

...

My javascript code:

# app/assets/javascripts/reservations.js.coffee
$ -> $('.date').datepicker({
    format: 'dd-mm-yyyy'
    autoclose: true
    todayHighlight: true
    language: 'fr'
});

And the Gemfile:

source 'https://rubygems.org'

ruby "2.0.0"

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.0.beta1'
gem 'bootstrap-sass', '2.3.1.0'
gem 'bcrypt-ruby', '3.0.1'
gem 'protected_attributes'
gem 'will_paginate'
gem 'bootstrap-will_paginate'
gem 'bootstrap-datepicker-rails'
gem 'rails-i18n'

gem 'pg'

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 4.0.0.beta1'
  gem 'coffee-rails', '~> 4.0.0.beta1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer', platforms: :ruby

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.0.1'

Body:
The simplest solution for this is use the method: :get in the link_to

<%= link_to "Create New Form", sampleform_path, method: :get %>


问:
syntax error in YOWSUP
i am following this tutorial : http://xebee.xebia.in/index.php/2013/11/25/yowsup-the-whatsapp-api/

in step 3
when i execute this on my terminal :

```<code>$ python yowsup-cli -c config.example -r sms
</code>```

i get a syntax error saying

```<code>  File "yowsup-cli", line 98
    unistr = str if sys.version_info >= (3, 0) else unicode
                  ^
SyntaxError: invalid syntax
</code>```

can any body help how can i remove this error

i m a newbie to python

答: yeah that was an old version error. anyway if you get any problem with the regitration process then you can try this guide yowsup registration guide.</p>

Title: syntax error in YOWSUP

Body:
i am following this tutorial : http://xebee.xebia.in/index.php/2013/11/25/yowsup-the-whatsapp-api/

in step 3
when i execute this on my terminal :

$ python yowsup-cli -c config.example -r sms

i get a syntax error saying

  File "yowsup-cli", line 98
    unistr = str if sys.version_info >= (3, 0) else unicode
                  ^
SyntaxError: invalid syntax

can any body help how can i remove this error

i m a newbie to python


问:
How to populate DropDownList with an IEnumerable returned from GET method in Api Controller?
I am new to web apps in MVC. The past 2 days I have researched and tried many things, but none applied to me; I am using an ApiController, not a Controller, so I cannot do things like "return View(model)".

If you can help me understand how to link these things together or show where my problem is that would be VERY appreciated!

Situation:
I want to make a web app that has cascading drop down lists; first list for selecting car makes, and second list that shows the car models for the selected make. The lists and a submit button will be within an AJAX form.

Question:
I just want to know, how can I populate the first drop down list on page load, using a GET method in my ApiController that returns an IEnumerable of car makes?
Then I can go from there. Keep in mind that later I will have a second drop down list that populates/updates based on the first, so I want the population of the drop down lists to be done client-side.

What I tried:

Using HTML.DropDownListFor to create a list, but
HTML.DropDownListFor always get "Object reference not set to an
instance of an object". I also use Ajax.BeginForm, but not sure if that can
actually call the GET method that returns an IEnumerable and add it to the
list.

Using $(document).ready() to use a getJSON to GET the car makes from my
ApiController method, but the getJSON would not fire.

I probably have something hugely wrong somewhere, since I cannot get anything to populate my list, and I am still learning. Thank you SO much for any help! I will now show my code, and some alternative code I tried after.

First are my Model classes:

```<code>    public class Make
    {
        public int MakeId { get; set; }
        public string MakeName { get; set; }
    }

    public class Model
    {
        public int ModelId { get; set; }
        public string ModelName { get; set; }
        public int MakeId { get; set; }
    }

    public class MakeViewModel
    {
        public int SelectedMakeId { get; set; }
        public IEnumerable<Make> MakesList { get; set; }
    }
</code>```

Here is my Vehicle ApiController with two GET methods, Makes() and Models(int makeID), each returns IEnumerable. They will eventually consume from a local xml, but right now for simplicity I removed it and each just returns a List of one Make or Model item.

```<code>public class VehicleController : ApiController
{
    [System.Web.Http.HttpGet]
    public IEnumerable<Make> Makes()
    {
        List<Make> makesList = new List<Make>();

        //Code for consuming from xml file will go here

        //For now, add one test make to the list
        Make maketest = new Make();
        maketest.MakeId = 1;
        maketest.MakeName = "MakeTest";
        makesList.Add(maketest);

        //return List of the one test make
        return makesList;
    }

    [System.Web.Http.HttpGet]
    public IEnumerable<Model> Models(int id)
    {
        List<Model> modelsList = new List<Model>();

        //Code for consuming from xml file will go here

        //For now, add one test model to the list
        Model modeltest = new Model();
        modeltest.ModelId = 1;
        modeltest.ModelName = "ModelTest";
        modeltest.MakeId = 1;
        modelsList.Add(modeltest);

        //return List of the one test model
        return modelsList;
    }
}
</code>```

This is my Index.cshtml, which loads a partial view _Form.cshtml

```<code><h2>Vehicle Selector</h2>
@{
    ViewBag.Title = "Home Page";
    @Html.Partial("_Form");
}
</code>```

Finally is my partial view _Form.cshtml; I will show just the first half of the file for the first drop down list.
At the top, I include the model MakeViewModel which is where we can find our list of car makes..

```<code>@model VehicleMVC.Models.MakeViewModel
<script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")"
    type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"
    type="text/javascript"></script>
</code>```

I use Ajax.BeginForm() to call the GET method Makes() from my VehicleController to update my makes_DDL, because I want the list to be populated when page is loaded. Honestly the problem might be here, as I'm not confident it's right.

```<code>@using (Ajax.BeginForm("Makes", "Vehicle", new AjaxOptions
    {
        HttpMethod = "GET",
        UpdateTargetId = "makes_DDL"
    }))
</code>```

I use Html.DropDownListFor() to create the makes_DDL list, though it always gives me "Object reference not set to an instance of an object" error.

```<code>@Html.DropDownListFor(model => model.SelectedMakeId,
    (SelectList)Model.MakesList, new { @class = "makes_DDL" })
</code>```

Thank you so much in advance!

Some things I tried:
I tried using new SelectList, but no luck:

```<code>@Html.DropDownListFor(model => model.SelectedMakeId, new
    SelectList(Model.MakesList, "MakeId", "MakeName"))
</code>```

Then I tried to hardcode a test list of makes, but same "Object reference not set to an instance of an object" error.

```<code>@Html.DropDownListFor(model => model.SelectedMakeId,
    new SelectList( new List<VehicleMVC.Models.Make>
    {
        new VehicleMVC.Models.Make { MakeId = 0, MakeName = "SmallCar"},
        new VehicleMVC.Models.Make { MakeId = 1, MakeName = "BigCar"}
    },
    "value", "text", 0), new { @class = "makes_DDL" })
</code>```

Since I was pretty sure that the Ajax.BeginForm was not doing what I want (calling GET Makes() method from my VehicleController to populate the makes_DDL list), I tried to use $(document).ready() to use a getJSON to use the route "api/vehicle" which should call Makes(), but it seems to not fire the getJSON since the alert I put inside doesn't fire.

```<code><script type="text/javascript">
    function getMakes() {
        $.getJSON("api/vehicle",
            function (data) {
                //This alert doesn't fire, so it seems getJSON is not firing?
                 window.alert(1);
                //Code would later go here for appending the makes from the
                  returned IEnumerable to the makes_DDL list
            });
    }

$(document).ready(getMakes);
</script>
</code>```

答:
Instead of using @Html.DropDownListFor you can use  <select> tag as follows,

```<code> <select id="SelectedMakeId" name="SelectedMakeId"></select>
</code>```

Then you can populate it with getJson as

```<code> $(document).ready(function (e) {
     $.getJSON("http://localhost:2390/api/vehicle", function (data) {
        $.each(data, function (index, value) {
             $("#SelectedMakeId").append("<option value=" + value.MakeId + ">" + value.MakeName + "</option>");
        });
    });
});
</code>```

Note that you have to give correct api method url. Instead of giving this url http://localhost:2390/api/vehicle you have to give your path.

YOU CAN TRY THIS ONE ALSO

You can use ViewBag as well. For that do the following,

1. Set the route to api method Makes() as

```<code>     [System.Web.Http.Route("api/Vehicle/MakersList")]
     [System.Web.Http.HttpGet]
     public IEnumerable<Make> Makes()
     {
        ...
     }
</code>```

2. Change the Index method

Add the GetMakers() method that consume api method. Use this GetMakers() to initialize ViewBag.listMakers

```<code>     private string MAKER_URL = "http://localhost:2390/api/vehicle";
     public ActionResult Index()
     {
            ViewBag.listMakers = new SelectList(GetMakers(), "MakeId","MakeName");
            return View();
     }

     public IEnumerable<Make> GetMakers()
     {
       try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(MAKER_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.GetAsync("vehicle/MakersList").Result;
                if (response.IsSuccessStatusCode)
                    return response.Content.ReadAsAsync<IEnumerable<Make>>().Result;
                return null;
            }
            catch
            {
                return null;
            }

     }
</code>```

3. Rewrite the @Html.DropDownListFor as

```<code>@Html.DropDownListFor(model => model.SelectedMakeId, (IEnumerable<SelectListItem>)ViewBag.listMakers, "---Select---", new { @class = "makes_DDL" })
</code>```

Body:
I am new to web apps in MVC. The past 2 days I have researched and tried many things, but none applied to me; I am using an ApiController, not a Controller, so I cannot do things like "return View(model)".

If you can help me understand how to link these things together or show where my problem is that would be VERY appreciated!

Situation:
I want to make a web app that has cascading drop down lists; first list for selecting car makes, and second list that shows the car models for the selected make. The lists and a submit button will be within an AJAX form.

Question:
I just want to know, how can I populate the first drop down list on page load, using a GET method in my ApiController that returns an IEnumerable of car makes?
Then I can go from there. Keep in mind that later I will have a second drop down list that populates/updates based on the first, so I want the population of the drop down lists to be done client-side.

What I tried:

Using HTML.DropDownListFor to create a list, but
HTML.DropDownListFor always get "Object reference not set to an
instance of an object". I also use Ajax.BeginForm, but not sure if that can
actually call the GET method that returns an IEnumerable and add it to the
list.

Using $(document).ready() to use a getJSON to GET the car makes from my
ApiController method, but the getJSON would not fire.

I probably have something hugely wrong somewhere, since I cannot get anything to populate my list, and I am still learning. Thank you SO much for any help! I will now show my code, and some alternative code I tried after.

First are my Model classes:

    public class Make
    {
        public int MakeId { get; set; }
        public string MakeName { get; set; }
    }

    public class Model
    {
        public int ModelId { get; set; }
        public string ModelName { get; set; }
        public int MakeId { get; set; }
    }

    public class MakeViewModel
    {
        public int SelectedMakeId { get; set; }
        public IEnumerable<Make> MakesList { get; set; }
    }

Here is my Vehicle ApiController with two GET methods, Makes() and Models(int makeID), each returns IEnumerable. They will eventually consume from a local xml, but right now for simplicity I removed it and each just returns a List of one Make or Model item.

public class VehicleController : ApiController
{
    [System.Web.Http.HttpGet]
    public IEnumerable<Make> Makes()
    {
        List<Make> makesList = new List<Make>();

        //Code for consuming from xml file will go here

        //For now, add one test make to the list
        Make maketest = new Make();
        maketest.MakeId = 1;
        maketest.MakeName = "MakeTest";
        makesList.Add(maketest);

        //return List of the one test make
        return makesList;
    }

    [System.Web.Http.HttpGet]
    public IEnumerable<Model> Models(int id)
    {
        List<Model> modelsList = new List<Model>();

        //Code for consuming from xml file will go here

        //For now, add one test model to the list
        Model modeltest = new Model();
        modeltest.ModelId = 1;
        modeltest.ModelName = "ModelTest";
        modeltest.MakeId = 1;
        modelsList.Add(modeltest);

        //return List of the one test model
        return modelsList;
    }
}

This is my Index.cshtml, which loads a partial view _Form.cshtml

Vehicle Selector

@{
    ViewBag.Title = "Home Page";
    @Html.Partial("_Form");
}

Finally is my partial view _Form.cshtml; I will show just the first half of the file for the first drop down list.
At the top, I include the model MakeViewModel which is where we can find our list of car makes..

@model VehicleMVC.Models.MakeViewModel

I use Ajax.BeginForm() to call the GET method Makes() from my VehicleController to update my makes_DDL, because I want the list to be populated when page is loaded. Honestly the problem might be here, as I'm not confident it's right.

@using (Ajax.BeginForm("Makes", "Vehicle", new AjaxOptions
    {
        HttpMethod = "GET",
        UpdateTargetId = "makes_DDL"
    }))

I use Html.DropDownListFor() to create the makes_DDL list, though it always gives me "Object reference not set to an instance of an object" error.

@Html.DropDownListFor(model => model.SelectedMakeId,
    (SelectList)Model.MakesList, new { @class = "makes_DDL" })

Thank you so much in advance!

Some things I tried:
I tried using new SelectList, but no luck:

@Html.DropDownListFor(model => model.SelectedMakeId, new
    SelectList(Model.MakesList, "MakeId", "MakeName"))

Then I tried to hardcode a test list of makes, but same "Object reference not set to an instance of an object" error.

@Html.DropDownListFor(model => model.SelectedMakeId,
    new SelectList( new List<VehicleMVC.Models.Make>
    {
        new VehicleMVC.Models.Make { MakeId = 0, MakeName = "SmallCar"},
        new VehicleMVC.Models.Make { MakeId = 1, MakeName = "BigCar"}
    },
    "value", "text", 0), new { @class = "makes_DDL" })

Since I was pretty sure that the Ajax.BeginForm was not doing what I want (calling GET Makes() method from my VehicleController to populate the makes_DDL list), I tried to use $(document).ready() to use a getJSON to use the route "api/vehicle" which should call Makes(), but it seems to not fire the getJSON since the alert I put inside doesn't fire.

Body:
Instead of using @Html.DropDownListFor you can use  <select> tag as follows,

 <select id="SelectedMakeId" name="SelectedMakeId"></select>

Then you can populate it with getJson as

 $(document).ready(function (e) {
     $.getJSON("http://localhost:2390/api/vehicle", function (data) {
        $.each(data, function (index, value) {
             $("#SelectedMakeId").append("<option value=" + value.MakeId + ">" + value.MakeName + "</option>");
        });
    });
});

Note that you have to give correct api method url. Instead of giving this url http://localhost:2390/api/vehicle you have to give your path.

YOU CAN TRY THIS ONE ALSO

You can use ViewBag as well. For that do the following,

1. Set the route to api method Makes() as

     [System.Web.Http.Route("api/Vehicle/MakersList")]
     [System.Web.Http.HttpGet]
     public IEnumerable<Make> Makes()
     {
        ...
     }

2. Change the Index method

Add the GetMakers() method that consume api method. Use this GetMakers() to initialize ViewBag.listMakers

     private string MAKER_URL = "http://localhost:2390/api/vehicle";
     public ActionResult Index()
     {
            ViewBag.listMakers = new SelectList(GetMakers(), "MakeId","MakeName");
            return View();
     }

     public IEnumerable<Make> GetMakers()
     {
       try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(MAKER_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.GetAsync("vehicle/MakersList").Result;
                if (response.IsSuccessStatusCode)
                    return response.Content.ReadAsAsync<IEnumerable<Make>>().Result;
                return null;
            }
            catch
            {
                return null;
            }

     }

3. Rewrite the @Html.DropDownListFor as

@Html.DropDownListFor(model => model.SelectedMakeId, (IEnumerable<SelectListItem>)ViewBag.listMakers, "---Select---", new { @class = "makes_DDL" })


问:
Sightly (HTL) List iteration
How do I iterate over an arrayList of String values in Sightly?

Using my backend java class I get an ArrayList returned to Sightly. How do I iterate over and display them?

答:
data-sly-list use the container such as  Please see the example for the better understanding.

I have below List

```<code>test1
test2
test3
test4

<div data-sly-list="${ currentPage.listChildren }">
      ${item.name}
</div>
</code>```

Output will be generated as –

```<code>test1 test2 test3 test4
</code>```

And when you view the HTML element structure in you debugger then it will be –

```<code><div>
   Test1
   Test2
   Test3
   Test4
<div>
</code>```

Now use data-sly-repeat–

```<code><div data-sly-repeat="${ currentPage.listChildren }">
      ${item.name}
</div>
</code>```

Output will be –
    XHTML

```<code>test1
test2
test3
test4
</code>```

Title: Sightly (HTL) List iteration

Body:
data-sly-list use the container such as  Please see the example for the better understanding.

I have below List

test1
test2
test3
test4

<div data-sly-list="${ currentPage.listChildren }">
      ${item.name}
</div>

Output will be generated as –

test1 test2 test3 test4

And when you view the HTML element structure in you debugger then it will be –

<div>
   Test1
   Test2
   Test3
   Test4
<div>

Now use data-sly-repeat–

<div data-sly-repeat="${ currentPage.listChildren }">
      ${item.name}
</div>

Output will be –
    XHTML

test1
test2
test3
test4


问:
How to Set An HTML SELECT element value to php variable ONSELECT
I am Using an HTML dropdown on a page, my requirement is to when i select any value from dropdown, it want to be store in an PHP variable on the same page without submitting form or without refreshing the page.

my code is:

Script:

```<code>    <script type="text/javascript">
    $("#bank_name").change(function(){

    var data=$(this).val();
    alert(data);

    $.ajax({
        url:"transaction.php",
        type:"POST",
        data: ({"bank_code": data}),
        sucess: function(response){
        console.log("Success");
        alert(data);
    },

    error: function(response){
        console.log("Error");
        alert(data);
    }
    });
    <script>
</code>```

PHP Code:

```<code>    $bank_code=$_POST["bank_code"];
    echo "Bank Code is:",$bank_code;
</code>```

it gets the value of selected option and also alerts the value but after alert it doesn't echo the value in PHP.

答:
You have type error in success ,You should remove those () brackets in data field to access $_POST in php like below,

```<code><script type="text/javascript">
    $("#bank_name").change(function(){

    var data=$(this).val();
    alert(data);

    $.ajax({
        url:"transaction.php",
        type:"POST",
        data: {bank_code: data),
        success: function(response){
        console.log("Success");
        alert(response);
    },

    error: function(response){
        console.log("Error");
        alert(data);
    }
    });
    <script>
</code>```

Body:
You have type error in success ,You should remove those () brackets in data field to access $_POST in php like below,

<script type="text/javascript">
    $("#bank_name").change(function(){

    var data=$(this).val();
    alert(data);

    $.ajax({
        url:"transaction.php",
        type:"POST",
        data: {bank_code: data),
        success: function(response){
        console.log("Success");
        alert(response);
    },

    error: function(response){
        console.log("Error");
        alert(data);
    }
    });
    <script>


问:
How to get the Intersection and Union of two Series in Pandas with non-unique values?
If I have 2 Series objects, like so: [0,0,1] [1,0,0]
How would I get the intersection and union of the two?
They only contain booleans which means they are non-unique values.

I have a large Boolean matrix. I've minhashed it and now I'm trying to find the false positives and negatives which I think means that I have to get the Jaccard similarity for each original pair.

答:
Since you say they are booleans use logical_and and logical_or of numpy or & and | on series i.e

```<code>y1 = pd.Series([1,0,1,0])
y2 = pd.Series([1,0,0,1])

# Numpy approach
intersection = np.logical_and(y1.values, y2.values)
union = np.logical_or(y1.values, y2.values)
intersection.sum() / union.sum()
# 0.33333333333333331

# Pandas approach
sum(y1 & y2) / sum(y1 | y2)
# 0.33333333333333331
</code>```

Body:
Since you say they are booleans use logical_and and logical_or of numpy or & and | on series i.e

y1 = pd.Series([1,0,1,0])
y2 = pd.Series([1,0,0,1])

# Numpy approach
intersection = np.logical_and(y1.values, y2.values)
union = np.logical_or(y1.values, y2.values)
intersection.sum() / union.sum()
# 0.33333333333333331

# Pandas approach
sum(y1 & y2) / sum(y1 | y2)
# 0.33333333333333331


问:
SQL to show 1 for unique and 0 for reapeat
looking for a quick solution on SQL...

I used to have a clunky formula in excel: =IF(COUNTIF($C$2:C2,C2)>1,0,COUNTIF($C$2:C2,C2)) to print 1 for unique item and 0 for a repeat.

Then moved to =1-(C1-C2) and that kinda did the job... Not an accurate one Now looking for an SQL that could do a similar job... The example below for result needed:

```<code>NUMBER         UNIQUE
6573455300000  1
6573455300000  0
6573455300000  0
6573455300000  0
6573411981080  1
6573411981080  0
6573411981080  0
6573411981080  0
</code>```

Does anyone know any kind of code to achieve this?

答:
```<code>select  t.Number,case when t.num=1 then t.num else 0 end [Unique] from(
select Number,row_number() over (partition by number order by number) num from MyTbl)t
order by t.Number
</code>```

Body:
looking for a quick solution on SQL...

I used to have a clunky formula in excel: =IF(COUNTIF($C$2:C2,C2)>1,0,COUNTIF($C$2:C2,C2)) to print 1 for unique item and 0 for a repeat.

Then moved to =1-(C1-C2) and that kinda did the job... Not an accurate one Now looking for an SQL that could do a similar job... The example below for result needed:

NUMBER         UNIQUE
6573455300000  1
6573455300000  0
6573455300000  0
6573455300000  0
6573411981080  1
6573411981080  0
6573411981080  0
6573411981080  0

Does anyone know any kind of code to achieve this?


问:
C# and ActiveSync communication / open and read files
I have a device connected to a host computer through cradle usb. Now, I'm just wondering if I could use C# sockets to communicate with the device (ie device sending data, host computer processing it then replying back to the device). How can I accomplish this? by that, what ip address etc etc.. do I have to change so that it would connect cause I have the sockets working on wireless. If not, then is there a way to connect to the device, open and read a file (a text document to be more specific) from the device to my host application.. any ideas?

Thanks! :)

答:
Depending on your target device, when you connect via ActiveSync it likely makes a local RNDIS network connection between teh two devices.  You can resolve "ppp_peer" as the partner's network name instead of trying to use a hard-coded IP address (IIRC the IP is different on XP than on Vista).

Be aware that it's not a full connection.  TCP packets gets passed through, but things like ICMP do not.

Of course, this just gives you a socket connection, just like if you were to connect between two PCs.  It's not going to allow you to do file system operations unless you have an app on the other side listening for commands.  If you want that type of thing, Microsoft provides the Remote API (RAPI) interface (wrapped in managed code here)for a lot of basic commands, and it can be extended (with C) to do anything you'd like.


问:
Python socket listen on all ports
Basically, I want to listen to all ports using the socket module. How do I make it so that port is = to all the open ports on the server? Any guides and or resources are highly appreciated Here is my current code.

```<code>import socket

def Main():
    host = '127.0.0.1'
    port = 5000

    s = socket.socket()
    s.bind((host, port))

    s.listen(1)
    c, addr = s.accept()
    print('Connection from: ' + str(addr))
    while True:
        data = c.recv(1024)
        if not data:
            break
        print('from connected user: ' + str(data))
        data = str(data).upper()
        print('sending: ' + str(data))
        c.send(data)
    c.close()

if __name__ == '__main__':
    Main()
</code>```

答:
You may try all possible ports and store them in a list. Remember ports below 1024 are reserved and some of the ports may be in use. So,  you will get some errors and you need to handle those if you cannot bind to that port. Also, you need a socket for each port since a socket can only listen at one port. Create a function create_socket which returns socket, then store them is a list. If you get error while trying to connect, just pass those errors. This may not be a good approach but it will work for you.

```<code>def create_socket(port_number):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(('127.0.0.1', port_number))
    server_socket.listen(1)

    return server_socket

socket_list = []

for port_number in range(1025,65536):
    try:
        socket_list.append(create_socket(port_number))
    except Exception:
        pass
</code>```

Title: Python socket listen on all ports

Body:
Basically, I want to listen to all ports using the socket module. How do I make it so that port is = to all the open ports on the server? Any guides and or resources are highly appreciated Here is my current code.

import socket

def Main():
    host = '127.0.0.1'
    port = 5000

    s = socket.socket()
    s.bind((host, port))

    s.listen(1)
    c, addr = s.accept()
    print('Connection from: ' + str(addr))
    while True:
        data = c.recv(1024)
        if not data:
            break
        print('from connected user: ' + str(data))
        data = str(data).upper()
        print('sending: ' + str(data))
        c.send(data)
    c.close()

if __name__ == '__main__':
    Main()

Body:
You may try all possible ports and store them in a list. Remember ports below 1024 are reserved and some of the ports may be in use. So,  you will get some errors and you need to handle those if you cannot bind to that port. Also, you need a socket for each port since a socket can only listen at one port. Create a function create_socket which returns socket, then store them is a list. If you get error while trying to connect, just pass those errors. This may not be a good approach but it will work for you.

def create_socket(port_number):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(('127.0.0.1', port_number))
    server_socket.listen(1)

    return server_socket

socket_list = []

for port_number in range(1025,65536):
    try:
        socket_list.append(create_socket(port_number))
    except Exception:
        pass