问:
Loops and Collatz Conjecture
I have a problem with loops and declaring variables. currently I am making a program about Collatz Conjecture, the program should check what is the biggest steps to reach one from certain amount of Collatz Sequence. here's my code :

```<code>start_num = int(input("insert a starting Number > "))
how_many = int(input("how many times you want to check? >"))

def even_or_odd(number):
    if number % 2 == 0:
        return 'isEven'
    else:
        return 'notEven'

def collatz(n):
    z = n
    counter = 0
    while True:
        if n != 1:
            if even_or_odd(n) == 'isEven':
                n = n/2
                counter += 1
                continue
            if even_or_odd(n) == 'notEven':
                n = (n*3)+1
                counter += 1
                continue
        else:
            print('number ' + str(z) + ' reached 1 with : ' + str(counter) + ' steps')
            return counter
            break

def check_biggest_steps(steps_before, steps_after):
    if steps_before > steps_after:
        return steps_before
    if steps_after > steps_before:
        return steps_after
    if steps_after == steps_before:
        return steps_after

def compute_collatz(n_times, collatz_number):
    for _ in range(n_times):
        before = collatz(collatz_number)
        collatz_number += 1
        after = collatz(collatz_number)
        collatz_number += 1
        biggest_steps = check_biggest_steps(before, after)

    print('Biggest Steps is :' + str(biggest_steps))

compute_collatz(how_many, start_num)
</code>```

this biggest_steps variable always return the last 2 steps. I know what causing this problem is that biggest_step variable located inside the loop but I can't get it working anywhere don't know what to do. Thanks

答:
Don't read my code until you have tried it yourself.

Try to make a list that appends every change to a list, then to get the number of moves at the end, just get the length of the list.

.

```<code>def collatz(x):
    while x != 1:
        if x % 2 > 0:
             x =((3 * x) + 1)
             list_.append(x)
        else:
            x = (x / 2)
            list_.append(x)
    return list_

print('Please enter a number: ', end='')
while True:
    try:
        x = int(input())
        list_ = [x]
        break
    except ValueError:
        print('Invaid selection, try again: ', end='')

l = collatz(x)

print('\nList:', l, sep=' ')
print('Number of steps required:', len(l) - 1)
</code>```

Title: Loops and Collatz Conjecture

Body:
I have a problem with loops and declaring variables. currently I am making a program about Collatz Conjecture, the program should check what is the biggest steps to reach one from certain amount of Collatz Sequence. here's my code :

start_num = int(input("insert a starting Number > "))
how_many = int(input("how many times you want to check? >"))

def even_or_odd(number):
    if number % 2 == 0:
        return 'isEven'
    else:
        return 'notEven'

def collatz(n):
    z = n
    counter = 0
    while True:
        if n != 1:
            if even_or_odd(n) == 'isEven':
                n = n/2
                counter += 1
                continue
            if even_or_odd(n) == 'notEven':
                n = (n*3)+1
                counter += 1
                continue
        else:
            print('number ' + str(z) + ' reached 1 with : ' + str(counter) + ' steps')
            return counter
            break

def check_biggest_steps(steps_before, steps_after):
    if steps_before > steps_after:
        return steps_before
    if steps_after > steps_before:
        return steps_after
    if steps_after == steps_before:
        return steps_after

def compute_collatz(n_times, collatz_number):
    for _ in range(n_times):
        before = collatz(collatz_number)
        collatz_number += 1
        after = collatz(collatz_number)
        collatz_number += 1
        biggest_steps = check_biggest_steps(before, after)

    print('Biggest Steps is :' + str(biggest_steps))

compute_collatz(how_many, start_num)

this biggest_steps variable always return the last 2 steps. I know what causing this problem is that biggest_step variable located inside the loop but I can't get it working anywhere don't know what to do. Thanks

Body:
Don't read my code until you have tried it yourself.

Try to make a list that appends every change to a list, then to get the number of moves at the end, just get the length of the list.

.

def collatz(x):
    while x != 1:
        if x % 2 > 0:
             x =((3 * x) + 1)
             list_.append(x)
        else:
            x = (x / 2)
            list_.append(x)
    return list_

print('Please enter a number: ', end='')
while True:
    try:
        x = int(input())
        list_ = [x]
        break
    except ValueError:
        print('Invaid selection, try again: ', end='')

l = collatz(x)

print('\nList:', l, sep=' ')
print('Number of steps required:', len(l) - 1)


来源: stackexchange

问:
Android Studio 3.0 Canary 2: attribute 'android:versionCode' not found
I've updated Android Studio to the latest canary build and now I can't run my app.

Every time when I try to build the project I get the following error:

```<code>Error:F:\...\**app_name**\app\build\intermediates\instant-run-support\debug\slice_0\AndroidManifest.xml:2 attribute 'android:versionCode' not found
</code>```

I tried to manually open the file and the attribute is clearly there:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="****"
      android:versionCode="1"
      android:versionName="1.0"
      split="lib_slice_0_apk">
</manifest>
</code>```

I've tried to clean the project, invalidate cache, restart android studio but nothing helped.

This is my build.gradle (app) file:

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "****"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
}
</code>```

答: After cleaning and rebulding I disabled instant run and re-enabled it and the error is gone.</p>

ContentLicense: CC BY-SA 3.0

Body:
I've updated Android Studio to the latest canary build and now I can't run my app.

Every time when I try to build the project I get the following error:

Error:F:\...\**app_name**\app\build\intermediates\instant-run-support\debug\slice_0\AndroidManifest.xml:2 attribute 'android:versionCode' not found

I tried to manually open the file and the attribute is clearly there:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="****"
      android:versionCode="1"
      android:versionName="1.0"
      split="lib_slice_0_apk">
</manifest>

I've tried to clean the project, invalidate cache, restart android studio but nothing helped.

This is my build.gradle (app) file:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "****"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
}


问:
How to use espresso to press a setPositiveButton type AlertDialog button
If I want to press ADD button, I tried:

onView(withText("ADD")).perform(click())

as well as

```<code>onView(withText("ADD"))
                .inRoot(isDialog())
                .check(matches(isDisplayed()))
                .perform(click());
</code>```

But none of them work well

答:
I will offer you to use uiautomator for this case, more info

Try to do this

```<code>Thread.sleep(TimeUnit.SECONDS.toMillis(1));
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject obj = device.findObject(new UiSelector().textContains("ADD").clickable(true));
obj.click();
</code>```

Body:
If I want to press ADD button, I tried:

onView(withText("ADD")).perform(click())

as well as

onView(withText("ADD"))
                .inRoot(isDialog())
                .check(matches(isDisplayed()))
                .perform(click());

But none of them work well

Body:
I will offer you to use uiautomator for this case, more info

Try to do this

Thread.sleep(TimeUnit.SECONDS.toMillis(1));
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject obj = device.findObject(new UiSelector().textContains("ADD").clickable(true));
obj.click();


问:
How can I change the size of icons in the Tree control in Flex?
I embed SVG graphics in my Flex application using

```<code>package MyUI
{
    public class Assets
    {
        [Embed(source="/assets/pic.svg"]
        [Bindable]
        public static var svgPic:Class;
    }
}
</code>```

and then extending the Tree class with some of my own code, setting the icon upon adding a node to the data provider:

```<code>public class MyTree extends Tree
{
    public function MyTree()
    {
        // ...
        this.iconField = "svgIcon";
        // ...
        this.dataProvider = new ArrayCollection;
        this.dataProvider.addItem({ /* ... */ svgIcon: MyUI.Assets.svgPic /* ... */ });
        // ...
    }
}
</code>```

Now I have two things I want to do:

use the SVG graphics in multiple places in the app, scaling them to the appropriate size for each appearance, i. e. scale them to a proper icon size when using them in the tree

change the size of the icon at runtime, e. g. display a slightly larger icon for selected items or let an icon "pulse" as a response to some event

I read the Flex documentation on the 9-slice scaling properties in the Embed tag, but I think that's not what I want.

Edit:

I unsuccessfully checked the "similar questions" suggested by SO, among others this one:

Flex: Modify an embedded icon and use it in a button?

答:
Subclass mx.controls.treeClasses.TreeItemRenderer and make it resize the icon to your desired dimensions, or create your own item renderer implementation by using the same interfaces as TreeItemRenderer. Set a custom item renderer with the itemRenderer property:

```<code>exampleTree.itemRenderer = new ClassFactory( ExampleCustomItemRendererClass );
</code>```

OwnerDisplayName: Hanno

ContentLicense: CC BY-SA 2.5

Body:
I embed SVG graphics in my Flex application using

package MyUI
{
    public class Assets
    {
        [Embed(source="/assets/pic.svg"]
        [Bindable]
        public static var svgPic:Class;
    }
}

and then extending the Tree class with some of my own code, setting the icon upon adding a node to the data provider:

public class MyTree extends Tree
{
    public function MyTree()
    {
        // ...
        this.iconField = "svgIcon";
        // ...
        this.dataProvider = new ArrayCollection;
        this.dataProvider.addItem({ /* ... */ svgIcon: MyUI.Assets.svgPic /* ... */ });
        // ...
    }
}

Now I have two things I want to do:

use the SVG graphics in multiple places in the app, scaling them to the appropriate size for each appearance, i. e. scale them to a proper icon size when using them in the tree

change the size of the icon at runtime, e. g. display a slightly larger icon for selected items or let an icon "pulse" as a response to some event

I read the Flex documentation on the 9-slice scaling properties in the Embed tag, but I think that's not what I want.

Edit:

I unsuccessfully checked the "similar questions" suggested by SO, among others this one:

Flex: Modify an embedded icon and use it in a button?

LastEditorDisplayName: Hanno

Body:
Subclass mx.controls.treeClasses.TreeItemRenderer and make it resize the icon to your desired dimensions, or create your own item renderer implementation by using the same interfaces as TreeItemRenderer. Set a custom item renderer with the itemRenderer property:

exampleTree.itemRenderer = new ClassFactory( ExampleCustomItemRendererClass );

OwnerDisplayName: joshtynjala


问:
In Python, is there an elegant way to print a list in a custom format without explicit looping?
I know you can do

```<code>print str(myList)
</code>```

to get

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

and you can do

```<code>i = 0
for entry in myList:
  print str(i) + ":", entry
  i += 1
</code>```

to get

```<code>0: 1
1: 2
2: 3
</code>```

But is there a way similar to the first to get a result similar to the last?

With my limited knowledge of Python (and some help from the documentation), my best is:

```<code>print '\n'.join([str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList)])
</code>```

It's not much less verbose, but at least I get a custom string in one (compound) statement.
Can you do better?

答:
Another:

```<code>>>> lst=[10,11,12]
>>> fmt="%i: %i"
>>> for d in enumerate(lst):
...    print(fmt%d)
...
0: 10
1: 11
2: 12
</code>```

Yet another form:

```<code>>>> for i,j in enumerate(lst): print "%i: %i"%(i,j)
</code>```

That method is nice since the individual elements in tuples produced by enumerate can be modified such as:

```<code>>>> for i,j in enumerate([3,4,5],1): print "%i^%i: %i "%(i,j,i**j)
...
1^3: 1
2^4: 16
3^5: 243
</code>```

Of course, don't forget you can get a slice from this like so:

```<code>>>> for i,j in list(enumerate(lst))[1:2]: print "%i: %i"%(i,j)
...
1: 11
</code>```

Body:
I know you can do

print str(myList)

to get

[1, 2, 3]

and you can do

i = 0
for entry in myList:
  print str(i) + ":", entry
  i += 1

to get

0: 1
1: 2
2: 3

But is there a way similar to the first to get a result similar to the last?

With my limited knowledge of Python (and some help from the documentation), my best is:

print '\n'.join([str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList)])

It's not much less verbose, but at least I get a custom string in one (compound) statement.
Can you do better?

Body:
Another:

>>> lst=[10,11,12]
>>> fmt="%i: %i"
>>> for d in enumerate(lst):
...    print(fmt%d)
...
0: 10
1: 11
2: 12

Yet another form:

>>> for i,j in enumerate(lst): print "%i: %i"%(i,j)

That method is nice since the individual elements in tuples produced by enumerate can be modified such as:

>>> for i,j in enumerate([3,4,5],1): print "%i^%i: %i "%(i,j,i**j)
...
1^3: 1
2^4: 16
3^5: 243

Of course, don't forget you can get a slice from this like so:

>>> for i,j in list(enumerate(lst))[1:2]: print "%i: %i"%(i,j)
...
1: 11


问:
Using archive file for compiled object seems to break compilation
I have a large project with a custom Makefile building everything. This is for an ARM Cortex-M0.

One of the steps is to compile a Newlib syscalls.c into syscalls.c.o. That gets dumped into an archive file newlib.a which in turn is linked to the final output.elf for loading onto my device's flash.

```<code>$ arm-none-eabi-gcc -o output.elf .bld/*.c.o .bld/*.cpp.o .bld/libs/*.a -nostartfiles -mcpu=cortex-m0 -mthumb -Tlinker.ld -Wl,-Map=output.map --specs=nano.specs
</code>```

If I follow the above procedure, sometimes the "Archive has no index":

```<code>.bld/libs/newlib.a: error adding symbols: Archive has no index; run ranlib to add one
</code>```

And sometimes (I have not figured out how to deterministically make one or the other happen) I get an undefined reference even though _init() is defined, as an empty function, in syscalls.c.

```<code>c:/progra~2/gnutoo~1/50a5a~1.420/bin/../lib/gcc/arm-none-eabi/5.4.1/../../../../arm-none-eabi/lib/armv6-m\libc_nano.a(lib_a-init.o): In function `__libc_init_array':
init.c:(.text.__libc_init_array+0x1c): undefined reference to `_init'
</code>```

However, if I skip the newlib.a file and just directly link syscalls.c.o into the final .elf, it works as expected.

What about using an archive could be causing this issue? I've also tried reordering the arguments to the linker to no avail.

Note (edit)

I did notice the run ranlib to add one instruction. However, this does not apply because:

This is not necessary on other archives that I'm building, why is it needed here?

That error doesn't happen anymore (after some fiddling. not sure what changed). The main issue is that _init is undefined.

Reference

I'm compiling other archive files in this build with no issues. The unique things here are that this archive only has one file in it and it's the only C-only archive. However, I don't see how this could affect things.

This is basically how I'm compiling syscalls.c and archiving the .o file:

```<code>$ arm-none-eabi-gcc newlib/syscalls.c -o .bld/newlib/syscalls.c.o -c -std=gnu11 -Wstrict-prototypes -nostartfiles -mcpu=cortex-m0 -mthumb -O2 -pipe -ffreestanding -funsigned-bitfields -Wall -Wfatal-errors -ffunction-sections -fdata-sections -MMD -MP -MF .bld/.dep/newlib/syscalls.c.o.d
$ arm-none-eabi-ar rcs .bld/libs/newlib.a .bld/newlib/syscalls.c.o
</code>```

gcc version

```<code>arm-none-eabi-g++ (GNU Tools for ARM Embedded Processors) 5.4.1 20160919 (release) [ARM/embedded-5-branch revision 240496]
</code>```

Simplified syscalls.c

```<code>caddr_t _sbrk(int nbytes) __attribute__((externally_visible));
void _init(void) __attribute__((externally_visible));

/* c++ destructor dynamic shared object needed if -fuse-cxa-atexit is used*/
void *__dso_handle __attribute__ ((weak));

// defined in linker script
extern caddr_t Heap_Bank1_Start;
extern caddr_t Heap_Bank1_End;

caddr_t _sbrk(int nbytes) { /* ... */ }
void _init(void) {}
</code>```

答:
Hope this hint can help you: https://github.com/ap4y/modbus.js/issues/1

Hi, you have this error because static library (libmodbus.a) have been
  precompiled for other platform. Actually, it my mistake to leave it in
  repository. In order to resolve this error you should compile library
  for your platform and replace it in lib directory.

Body:
I have a large project with a custom Makefile building everything. This is for an ARM Cortex-M0.

One of the steps is to compile a Newlib syscalls.c into syscalls.c.o. That gets dumped into an archive file newlib.a which in turn is linked to the final output.elf for loading onto my device's flash.

$ arm-none-eabi-gcc -o output.elf .bld/*.c.o .bld/*.cpp.o .bld/libs/*.a -nostartfiles -mcpu=cortex-m0 -mthumb -Tlinker.ld -Wl,-Map=output.map --specs=nano.specs

If I follow the above procedure, sometimes the "Archive has no index":

.bld/libs/newlib.a: error adding symbols: Archive has no index; run ranlib to add one

And sometimes (I have not figured out how to deterministically make one or the other happen) I get an undefined reference even though _init() is defined, as an empty function, in syscalls.c.

c:/progra~2/gnutoo~1/50a5a~1.420/bin/../lib/gcc/arm-none-eabi/5.4.1/../../../../arm-none-eabi/lib/armv6-m\libc_nano.a(lib_a-init.o): In function `__libc_init_array':
init.c:(.text.__libc_init_array+0x1c): undefined reference to `_init'

However, if I skip the newlib.a file and just directly link syscalls.c.o into the final .elf, it works as expected.

What about using an archive could be causing this issue? I've also tried reordering the arguments to the linker to no avail.

Note (edit)

I did notice the run ranlib to add one instruction. However, this does not apply because:

This is not necessary on other archives that I'm building, why is it needed here?

That error doesn't happen anymore (after some fiddling. not sure what changed). The main issue is that _init is undefined.

Reference

I'm compiling other archive files in this build with no issues. The unique things here are that this archive only has one file in it and it's the only C-only archive. However, I don't see how this could affect things.

This is basically how I'm compiling syscalls.c and archiving the .o file:

$ arm-none-eabi-gcc newlib/syscalls.c -o .bld/newlib/syscalls.c.o -c -std=gnu11 -Wstrict-prototypes -nostartfiles -mcpu=cortex-m0 -mthumb -O2 -pipe -ffreestanding -funsigned-bitfields -Wall -Wfatal-errors -ffunction-sections -fdata-sections -MMD -MP -MF .bld/.dep/newlib/syscalls.c.o.d
$ arm-none-eabi-ar rcs .bld/libs/newlib.a .bld/newlib/syscalls.c.o

gcc version

arm-none-eabi-g++ (GNU Tools for ARM Embedded Processors) 5.4.1 20160919 (release) [ARM/embedded-5-branch revision 240496]

Simplified syscalls.c

caddr_t _sbrk(int nbytes) __attribute__((externally_visible));
void _init(void) __attribute__((externally_visible));

/* c++ destructor dynamic shared object needed if -fuse-cxa-atexit is used*/
void *__dso_handle __attribute__ ((weak));

// defined in linker script
extern caddr_t Heap_Bank1_Start;
extern caddr_t Heap_Bank1_End;

caddr_t _sbrk(int nbytes) { /* ... */ }
void _init(void) {}


问:
Java byte type in enum constructor
```<code>public enum Rank {
    TEN("Ten",1),
    NINE("Nine",2),
    EIGHT("Eight",0),
    SEVEN("Seven",0);

    private final String name;
    private final int point;

    /*
     * @param rank should be byte
     */
    private Rank(String name,int point)
    {
        this.name=name;
        this.point=point;
    }
</code>```

How to replace int to byte in point. One way i can think of is using TEN("Ten",Byte.parseByte("1"));

Is there any better or/and shorter approach?

答:
Just a style suggestion, move the cast in the constructor, so it looks cleaner:</p>

```<code>public enum Rank {
    TEN("Ten", 1),
    NINE("Nine", 2),
    EIGHT("Eight", 0),
    SEVEN("Seven", 0);

    private final String name;
    private final byte point;

    private Rank(String name, int point)
    {
        this.name = name;
        this.point = (byte)point;
    }
</code>```

Title: Java byte type in enum constructor

Body:
public enum Rank {
    TEN("Ten",1),
    NINE("Nine",2),
    EIGHT("Eight",0),
    SEVEN("Seven",0);

    private final String name;
    private final int point;

    /*
     * @param rank should be byte
     */
    private Rank(String name,int point)
    {
        this.name=name;
        this.point=point;
    }

How to replace int to byte in point. One way i can think of is using TEN("Ten",Byte.parseByte("1"));

Is there any better or/and shorter approach?

Body:
Just a style suggestion, move the cast in the constructor, so it looks cleaner:

public enum Rank {
    TEN("Ten", 1),
    NINE("Nine", 2),
    EIGHT("Eight", 0),
    SEVEN("Seven", 0);

    private final String name;
    private final byte point;

    private Rank(String name, int point)
    {
        this.name = name;
        this.point = (byte)point;
    }


问:
Join PDFs calling join.py OSX script from another python script and passing parameters
Please keep in mind i am very new to python.

I have been trying to write a python script that among other things, uses the join.py Python script already present in OSX (see https://apple.stackexchange.com/a/99218) to merge pdf files from a specific folder.

The way this script is supposed to work is by providing the following arguments:
join.py -o OutputDir/Outputfilename InputDir/*.pdf when in shell.
This will take all the pdfs of the input filenames and merge them. I have successfully done this with a shell script but trying to run it with python i have not managed to make it grab all the pdfs, with any way i've tried. It always refuses to process a list of files, just wants a string.

My latest script:

```<code>import sys
sys.path.insert(0, '/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/')
pdfInputDir = os.path.join (sortsdir, expTitle, "PDFs")
print(pdfInputDir)
pdfstomerge = []
for root, dirs, files in os.walk(pdfInputDir):
    pdfstomerge += glob.glob(os.path.join(root, '*.pdf'))
print(pdfstomerge) #i verify the pdfs are the ones i want
from subprocess import call
call(["/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/join.py", "-o", os.path.join(pdfInputDir, "output.pdf"), ''.join(map(str, pdfstomerge))])
###
###
</code>```

Every time i run it i get an output.pdf correctly produced which is empty. To verify that what i am doing is working, i have switched *.pdf with one of the pdf filenames i have in the directory and it has produced an output.pdf with that file, meaning i am on the right track, i just can't figure out a way to provide it with all the necessary pdfs instead of one.

I am not sure what i am doing wrong anymore, especially since the above "command" works in terminal. I've tried different approaches including os.path.join(pdfInputDir, "*.pdf") , re'match and fnmatch but none of them worked - i usually get an error along these lines:
TypeError: Can't convert 'list' object to str implicitly
 (could be i wrote them wrong).

Also, i am pretty sure that i could perhaps run it as a python module, instead of calling it with subprocess but then i failed to find a way to "push" all the required arguments in it, so i stuck with the subprocess.call way.

Any ideas on how to properly provide those parameters for my script would be more than appreciated.

答:
Could you please try join(str(i) for i in pdfstomerge) instead of join(map(str, pdfstomerge).

This should solve your query :-) (hopefully) Have a nice day!

```<code>try:
   liststr = ','join(str(i) for i in pdfstomerge)
   print(liststr)
except TypeError:
   print(pdfstomerge) # to check what you have in the list of pdfs
</code>```

In addition I am not sure if you have to pass the value in a string like:

```<code>stringToCall = '[' + liststr + ']'
</code>```

Hope you will find soon a solution.

Body:
Please keep in mind i am very new to python.

I have been trying to write a python script that among other things, uses the join.py Python script already present in OSX (see https://apple.stackexchange.com/a/99218) to merge pdf files from a specific folder.

The way this script is supposed to work is by providing the following arguments:
join.py -o OutputDir/Outputfilename InputDir/*.pdf when in shell.
This will take all the pdfs of the input filenames and merge them. I have successfully done this with a shell script but trying to run it with python i have not managed to make it grab all the pdfs, with any way i've tried. It always refuses to process a list of files, just wants a string.

My latest script:

import sys
sys.path.insert(0, '/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/')
pdfInputDir = os.path.join (sortsdir, expTitle, "PDFs")
print(pdfInputDir)
pdfstomerge = []
for root, dirs, files in os.walk(pdfInputDir):
    pdfstomerge += glob.glob(os.path.join(root, '*.pdf'))
print(pdfstomerge) #i verify the pdfs are the ones i want
from subprocess import call
call(["/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/join.py", "-o", os.path.join(pdfInputDir, "output.pdf"), ''.join(map(str, pdfstomerge))])
###
###

Every time i run it i get an output.pdf correctly produced which is empty. To verify that what i am doing is working, i have switched *.pdf with one of the pdf filenames i have in the directory and it has produced an output.pdf with that file, meaning i am on the right track, i just can't figure out a way to provide it with all the necessary pdfs instead of one.

I am not sure what i am doing wrong anymore, especially since the above "command" works in terminal. I've tried different approaches including os.path.join(pdfInputDir, "*.pdf") , re'match and fnmatch but none of them worked - i usually get an error along these lines:
TypeError: Can't convert 'list' object to str implicitly
 (could be i wrote them wrong).

Also, i am pretty sure that i could perhaps run it as a python module, instead of calling it with subprocess but then i failed to find a way to "push" all the required arguments in it, so i stuck with the subprocess.call way.

Any ideas on how to properly provide those parameters for my script would be more than appreciated.

Body:
Could you please try join(str(i) for i in pdfstomerge) instead of join(map(str, pdfstomerge).

This should solve your query :-) (hopefully) Have a nice day!

try:
   liststr = ','join(str(i) for i in pdfstomerge)
   print(liststr)
except TypeError:
   print(pdfstomerge) # to check what you have in the list of pdfs

In addition I am not sure if you have to pass the value in a string like:

stringToCall = '[' + liststr + ']'

Hope you will find soon a solution.


问:
Dragging a TButton from form to form
I have a Delphi GUI app (with RAD studio 2010) and I want the user to be able to rearrange his workspace. I know how to make TButtons draggable around in the same form, but not how to make the user able to drag a button from one form to another form. When you click and attempt to drag a TButton, I don't think it treats it like a drag-and-drop operation. How do you get a TButton to be drag-and-drop capable across multiple forms?</p>

答: First, set DragMode of the button to dmAutomatic, or manually call BeginDrag when a mouse down occurs on the button. Then use the OnDragOver + OnDragDrop events of the form you're going to drag to.</p>

Title: Dragging a TButton from form to form


问:
gsub R extracting string
I am trying to extract a string between two commas with gsub. If I have the following

```<code>xz<- "1620 Honeylocust Drive, 60210 IL, USA"
</code>```

and I want to extract everything between the two commas, (60120 IL), is it possible to use gsub?

I have tried

```<code>gsub(".*,","",xz)
</code>```

The result is USA. How can I do it?

答:
You could also do this using strsplit and grep (here I did it in 2 lines for readability):

```<code>xz1 <- "1620, Honeylocust Drive, 60210 IL, USA"
a1 <- strsplit(xz1, "[ ]*,[ ]*")[[1]]
grep("^[0-9]+[ ]+[A-Z]+", a1, value=TRUE)
#[1] "60210 IL"
</code>```

It's not using gsub, and in the present case it is not better, but maybe it is easier to adapt to other situations.

Title: gsub R extracting string

Body:
I am trying to extract a string between two commas with gsub. If I have the following

xz<- "1620 Honeylocust Drive, 60210 IL, USA"

and I want to extract everything between the two commas, (60120 IL), is it possible to use gsub?

I have tried

gsub(".*,","",xz)

The result is USA. How can I do it?

Body:
You could also do this using strsplit and grep (here I did it in 2 lines for readability):

xz1 <- "1620, Honeylocust Drive, 60210 IL, USA"
a1 <- strsplit(xz1, "[ ]*,[ ]*")[[1]]
grep("^[0-9]+[ ]+[A-Z]+", a1, value=TRUE)
#[1] "60210 IL"

It's not using gsub, and in the present case it is not better, but maybe it is easier to adapt to other situations.


问:
I'm trying to echo an image in a PHP variable in CodeIgniter
Hello I'm trying to echo an image on a view page in CodeIgniter but nothing is displayed on the page.

Here I'm making the variable:

```<code><?php $image = "<img src='../../images/stoel.jpg' alt='img' />";  ?>
</code>```

And here I'm trying to echo the image:

```<code><img src="<?php echo $image;?>">
</code>```

答:
You are already assign full image code in variable so you just need to print your variable:

```<code><img src="<?php echo $image;?>">
</code>```

To

```<code><?php echo $image;?>
</code>```

Body:
Hello I'm trying to echo an image on a view page in CodeIgniter but nothing is displayed on the page.

Here I'm making the variable:

<?php $image = "";  ?>

And here I'm trying to echo the image:

<img src="<?php echo $image;?>">

Body:
You are already assign full image code in variable so you just need to print your variable:

<img src="<?php echo $image;?>">

To

<?php echo $image;?>


问:
Event Handler Namespace in Vanilla JavaScript
I'm familiar with namespaces in jQuery's event handlers. I can add an event handler in a specific namespace:

```<code>$('#id').on('click.namespace', _handlerFunction);
</code>```

And then I can remove all event handlers in that namespace:

```<code>$('#id').off('.namespace');
</code>```

The advantage here is that I can remove only the events in this namespace, not any user-added/additional events that should be maintained.

Does anyone have any tips on how I can not use jQuery, but achieve a similar result?

答:
In this solution I've extended the DOM to have on and off methods with the ability to use events namespacing:

var events = {
  on(event, cb, opts){
    if( !this.namespaces ) // save the namespaces on the DOM element itself
      this.namespaces = {};

    this.namespaces[event] = cb;
    var options = opts || false;

    this.addEventListener(event.split('.')[0], cb, options);
    return this;
  },
  off(event) {
    this.removeEventListener(event.split('.')[0], this.namespaces[event]);
    delete this.namespaces[event];
    return this;
  }
}

// Extend the DOM with these above custom methods
window.on = Element.prototype.on = events.on;
window.off = Element.prototype.off = events.off;

window
  .on('mousedown.foo', ()=> console.log("namespaced event will be removed after 3s"))
  .on('mousedown.bar', ()=> console.log("event will NOT be removed"))
  .on('mousedown.baz', ()=> console.log("event will fire once"), {once: true});

// after 3 seconds remove the event with `foo` namespace
setTimeout(function(){
    window.off('mousedown.foo')
}, 3000)```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Click anywhere </code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm familiar with namespaces in jQuery's event handlers. I can add an event handler in a specific namespace:

$('#id').on('click.namespace', _handlerFunction);

And then I can remove all event handlers in that namespace:

$('#id').off('.namespace');

The advantage here is that I can remove only the events in this namespace, not any user-added/additional events that should be maintained.

Does anyone have any tips on how I can not use jQuery, but achieve a similar result?

Body:
In this solution I've extended the DOM to have on and off methods with the ability to use events namespacing:

var events = {
  on(event, cb, opts){
    if( !this.namespaces ) // save the namespaces on the DOM element itself
      this.namespaces = {};

    this.namespaces[event] = cb;
    var options = opts || false;

    this.addEventListener(event.split('.')[0], cb, options);
    return this;
  },
  off(event) {
    this.removeEventListener(event.split('.')[0], this.namespaces[event]);
    delete this.namespaces[event];
    return this;
  }
}

// Extend the DOM with these above custom methods
window.on = Element.prototype.on = events.on;
window.off = Element.prototype.off = events.off;

window
  .on('mousedown.foo', ()=> console.log("namespaced event will be removed after 3s"))
  .on('mousedown.bar', ()=> console.log("event will NOT be removed"))
  .on('mousedown.baz', ()=> console.log("event will fire once"), {once: true});

// after 3 seconds remove the event with `foo` namespace
setTimeout(function(){
    window.off('mousedown.foo')
}, 3000)

Click anywhere


问:
Expand outer nested div to 100%
I have this code

.outer {
  background-color: #ff00ff;
  width: 100%;
}

.outer div {
  float: left;
  background-color: #0000ff;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div>
    test1    <br/> test1
  </div>
  <div>
    test2    <br/> test2
  </div>
</div></code>```

https://jsfiddle.net/jcb5mdqa/

It looks like

but I want the outer to have a width of 100% like in .css written.

Expected result

What do I need to change?

答:
Method 1: use

.outer {
  background-color: #ff00ff;
  width: 100%;
}

.outer div {
  float: left;
  background-color: #0000ff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div>
    test1    <br/> test1
  </div>
  <div>
    test2    <br/> test2
  </div>
  <br style="clear: both">
</div> </code>```

Method 2 :use overflow:hidden

```<code>.outer {
  background-color: #ff00ff;
  width: 100%;
  overflow: hidden;/*/<=========new/*/
}
</code>```

Mehod 3: use of :after

```<code>.outer:after {
    content: '';
    clear: both;
    display: block;
}
</code>```

Title: Expand outer nested div to 100%

Body:
I have this code

.outer {
  background-color: #ff00ff;
  width: 100%;
}

.outer div {
  float: left;
  background-color: #0000ff;

}

    test1
 test1

    test2
 test2

https://jsfiddle.net/jcb5mdqa/

It looks like

but I want the outer to have a width of 100% like in .css written.

Expected result

What do I need to change?

Body:
Method 1: use <br style="clear: both">

.outer {
  background-color: #ff00ff;
  width: 100%;
}

.outer div {
  float: left;
  background-color: #0000ff;
}

<div class="outer">
  <div>
    test1    <br/> test1
  </div>
  <div>
    test2    <br/> test2
  </div>
  <br style="clear: both">
</div>

Method 2 :use overflow:hidden

.outer {
  background-color: #ff00ff;
  width: 100%;
  overflow: hidden;/*/<=========new/*/
}

Mehod 3: use of :after

.outer:after {
    content: '';
    clear: both;
    display: block;
}


问:
SendMessage send attachment that is locked
I am using a standard SendMessage command to send an email in a PowerShell script. I want to attach a log file but unfortunatly the log file is locked by a parent script.

Is there a way to send the file anyways as an attachment (I don't want to delete it or write it)?

I know I can read the file with Get-Content, should I pipe this output to a new temporary file that is then attached? If that would work how would I go about doing this.

答:
Copy-Item should work if you can read the content with Get-Content.

Copy it as a temporary file, send it, then delete it.

```<code>Copy-Item C:\My_log.log $env:TEMP
</code>```

PowerShell 2.0 and above

```<code>Send-MailMessage -Attachments $env:TEMP\My_log.log .......
</code>```

PowerShell 1.0 -> PowerShell Send Email

```<code>Remove-Item $env:TEMP\My_log.log
</code>```

Body:
Copy-Item should work if you can read the content with Get-Content.

Copy it as a temporary file, send it, then delete it.

Copy-Item C:\My_log.log $env:TEMP

PowerShell 2.0 and above

Send-MailMessage -Attachments $env:TEMP\My_log.log .......

PowerShell 1.0 -> PowerShell Send Email

Remove-Item $env:TEMP\My_log.log


问:
Database does not accept decimal values in live
I am using the following bit of code to insert some data into a database:

```<code>internal int InsertSample(Sample sample)
{
    using (var db = new OleDbConnection(connectionString))
    {
        var query = Constants.InsertNewSample;
        return db.Execute(query, sample);
    }
}
</code>```

And it works fine when I run it locally through Visual Studio.

However, when I publish the site and try inserting, I get an error:

Data type mismatch in criteria expression.

Stack trace

```<code>[OleDbException (0x80040e07): Data type mismatch in criteria expression.]
   System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) +1138392
   System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) +247
   System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) +208
   System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) +58
   System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) +162
   System.Data.OleDb.OleDbCommand.ExecuteNonQuery() +107
   Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action`2 paramReader) +93
   Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command) +758
   MVCQCPage.Helpers.Access.InsertSample(Sample sample) +208
</code>```

But this only happens if the value of Sample.MassOff is in decimal format (e.g. 1.6).

If this value is passed as an integer (e.g. 5), it works without any issue when debugging and after publishing.

How is this possible????

The data type in the database is numeric, and the data type of Sample.MassOff is string.

Let me know if I can provide any more details.

答:
I was able to resolve this by doing the following:

Changing the data type of MassOff to double

Adding the line <globalization uiCulture="en" culture="en-US" /> to web.config

Body:
I am using the following bit of code to insert some data into a database:

internal int InsertSample(Sample sample)
{
    using (var db = new OleDbConnection(connectionString))
    {
        var query = Constants.InsertNewSample;
        return db.Execute(query, sample);
    }
}

And it works fine when I run it locally through Visual Studio.

However, when I publish the site and try inserting, I get an error:

Data type mismatch in criteria expression.

Stack trace

[OleDbException (0x80040e07): Data type mismatch in criteria expression.]
   System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) +1138392
   System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) +247
   System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) +208
   System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) +58
   System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) +162
   System.Data.OleDb.OleDbCommand.ExecuteNonQuery() +107
   Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action`2 paramReader) +93
   Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command) +758
   MVCQCPage.Helpers.Access.InsertSample(Sample sample) +208

But this only happens if the value of Sample.MassOff is in decimal format (e.g. 1.6).

If this value is passed as an integer (e.g. 5), it works without any issue when debugging and after publishing.

How is this possible????

The data type in the database is numeric, and the data type of Sample.MassOff is string.

Let me know if I can provide any more details.


问:
How to highlight a menu item after it is routed to its particular menu?
How to highlight a (in side-nav) menu item (on selected) after it is routed to its particular menu in angular material? It will be useful if anyone got the solution.

<md-sidenav layout="column" class="md-sidenav-left md-whiteframe-z2"
  md-component-id="left" md-is-locked-open="$mdMedia('gt-sm')">
    <menu-link section="page" class="ng-isolate-scope">
        test1
    </menu-link>
    <menu-link section="page" class="ng-isolate-scope">
        test2
    </menu-link>
    <menu-link section="page" class="ng-isolate-scope">
        test3
    </menu-link>
    <menu-link section="page" class="ng-isolate-scope">
        test6
    </menu-link>
    <menu-link section="page" class="ng-isolate-scope">
        test8
    </menu-link>
    <menu-link section="page" class="ng-isolate-scope">
        test10
    </menu-link>
    <menu-link section="page" class="ng-isolate-scope">
        test78
    </menu-link>
    <menu-link section="page" class="ng-isolate-scope">
        test89
    </menu-link>
</md-sidenav>
```

答:
Add ui-sref-active="active" to every link. See the example below.

```<code><menu-link section="page" class="ng-isolate-scope">
    <a class="md-button md-ink-ripple" ui-sref="customer" ui-sref-active="active">
        test1
    </a>
</menu-link>
</code>```

The link will have an active class when the user is on the route specified in ui-sref or its child route. You can use that class to style the active item in any way you want.

Body:
Add ui-sref-active="active" to every link. See the example below.

<menu-link section="page" class="ng-isolate-scope">
    <a class="md-button md-ink-ripple" ui-sref="customer" ui-sref-active="active">
        test1
    </a>
</menu-link>

The link will have an active class when the user is on the route specified in ui-sref or its child route. You can use that class to style the active item in any way you want.


问:
Spring Batch - Rerun Job with same Job Parameter
Spring Batch new guy here,so, expect anything.

I have a job that runs successfully to completion with given job parameters paymentPeriod=1. Though the requirement expects the job to be able to rerun with same job parameters paymentPeriod=1 .

I can run job first time with parameter paymentPeriod=1 with following endpoint from postman

```<code>@RestController
@RequestMapping(value = "api/jobs")
public class JobController {
    @Autowired
    private JobOperator jobOperator;

    @RequestMapping(value = "/pay/{paymentPeriod}", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.ACCEPTED)
    public void launchPaymentJob(@PathVariable Integer paymentPeriod) throws Exception {
        this.jobOperator.start("paymentJob", String.format("paymentPeriod=%s", paymentPeriod));
    }
}
</code>```

Though when i rerun with same parameters i get JobInstanceAlreadyExistsException cannot start a job instance that already exists with name paymentJob and parameters=paymentPeriod=1

答:
Going by the concept of Job Instances and Job Executions in Spring Batch, you can't start a COMPLETED job instance again though you can launch same instance of job again & again till its not COMPLETE ( and few more job statuses ).

Job instance uniqueness is achieved by jobId & job parameters.

So if you don't vary your parameters, you can't start a completed job with same instance.

If your REST End Point is restricted to take same value again and again, you need to add a unique parameter within that method and that can very well be - java.lang.System.currentTimeMillis().

You can use any other unique value though current system time is very convenient.

Convert java.lang.System.currentTimeMillis() to String and append to your parameters with something like , String.format("paymentPeriod=%s", paymentPeriod+java.lang.System.currentTimeMillis()) instead of what you are currently.

Hope you get the idea.

Body:
Spring Batch new guy here,so, expect anything.

I have a job that runs successfully to completion with given job parameters paymentPeriod=1. Though the requirement expects the job to be able to rerun with same job parameters paymentPeriod=1 .

I can run job first time with parameter paymentPeriod=1 with following endpoint from postman

@RestController
@RequestMapping(value = "api/jobs")
public class JobController {
    @Autowired
    private JobOperator jobOperator;

    @RequestMapping(value = "/pay/{paymentPeriod}", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.ACCEPTED)
    public void launchPaymentJob(@PathVariable Integer paymentPeriod) throws Exception {
        this.jobOperator.start("paymentJob", String.format("paymentPeriod=%s", paymentPeriod));
    }
}

Though when i rerun with same parameters i get JobInstanceAlreadyExistsException cannot start a job instance that already exists with name paymentJob and parameters=paymentPeriod=1


问:
Checking row for duplicates in Sudoku
When i tried to check the rows of the Sudoku for duplicate elements, nothing is returned as result. Don't know whether the code is right or not. If the duplicate element found in a row, then need to print repetition found. Help me to reach the solution with using the method checkRow().

```<code>public class Sudoku {
 public static void main(String... args) throws Exception
{
    Scanner scanner = new Scanner(System.in);
    int[][] sudokuPuzzle = {
                         {8, 1, 0, 0, 0, 0, 0, 3, 9},
                         {0, 0, 0, 9, 0, 1, 0, 0, 0},
                         {3, 0, 5, 0, 0, 0, 4, 0, 1},
                         {0, 0, 9, 8, 0, 2, 7, 0, 0},
                         {0, 0, 0, 5, 0, 6, 0, 0, 0},
                         {0, 0, 4, 3, 0, 7, 1, 0, 0},
                         {1, 0, 8, 0, 0, 0, 9, 0, 2},
                         {0, 0, 0, 6, 0, 4, 0, 0, 0},
                         {2, 4, 0, 0, 0, 0, 0, 6, 5}
                    };
    printSudoku(sudokuPuzzle);
int count = countCellsToFill(sudokuPuzzle);
System.out.println("Number of cells have to filled: " + count);
}
 public static void printSudoku(int[][] sudokuPuzzle)
 {
  for (int i = 0; i < sudokuPuzzle.length; i++)
    {
        if (i == 3 || i == 6)
            System.out.println("------------------------");
        for (int j = 0; j < sudokuPuzzle[i].length; j++)
        {
            System.out.format("%-2s", sudokuPuzzle[i][j]);
            if (j == 2 || j == 5 )
                System.out.print(" | ");
        }
        System.out.println();
    }
}

 public static int countCellsToFill(int[][] sudokuPuzzle){
int count=0;
for(int[] sudokuPuzzle1 : sudokuPuzzle){
    for(int a: sudokuPuzzle1){
        if(a == 0){
            count++;
        }
    }
}
return count;
}
 public boolean checkRow(int[] sudokuPuzzle){
for (int row = 0; row < sudokuPuzzle.length; row++)
{
        int num = sudokuPuzzle[row];
            if (num == sudokuPuzzle[row])
            {
                return true;
            }
}
return false;
}
}
</code>```

答:
Take a moment and read your code:

```<code> public boolean checkRow(int[] sudokuPuzzle){
    for (int row = 0; row < sudokuPuzzle.length; row++)
    {
       int num = sudokuPuzzle[row];
       if (num == sudokuPuzzle[row])
       {
          return true;
       }
    }
       return false;
 }
</code>```

What you are doing here is picking up the first number, "8" in this case, because it is on your position "0". Then, you check if that "8" is on your position "0", which of course, will be always true.

If you wanna check numbers per row, I suggest you to analize it with, maybe, a double for. So you can do your 9 lines, 9 numbers per line, and gotta have in mind don't compare the number you just read with himself.

By the way, if you are doing a Sudoku, you should check if that number appears in the first square as well. Sodukus are composed by 9 squares, you can not repeat numbers in rows, nor in columns, nor in squares.

That is an easy problem, struggle a bit!

Title: Checking row for duplicates in Sudoku

Body:
When i tried to check the rows of the Sudoku for duplicate elements, nothing is returned as result. Don't know whether the code is right or not. If the duplicate element found in a row, then need to print repetition found. Help me to reach the solution with using the method checkRow().

public class Sudoku {
 public static void main(String... args) throws Exception
{
    Scanner scanner = new Scanner(System.in);
    int[][] sudokuPuzzle = {
                         {8, 1, 0, 0, 0, 0, 0, 3, 9},
                         {0, 0, 0, 9, 0, 1, 0, 0, 0},
                         {3, 0, 5, 0, 0, 0, 4, 0, 1},
                         {0, 0, 9, 8, 0, 2, 7, 0, 0},
                         {0, 0, 0, 5, 0, 6, 0, 0, 0},
                         {0, 0, 4, 3, 0, 7, 1, 0, 0},
                         {1, 0, 8, 0, 0, 0, 9, 0, 2},
                         {0, 0, 0, 6, 0, 4, 0, 0, 0},
                         {2, 4, 0, 0, 0, 0, 0, 6, 5}
                    };
    printSudoku(sudokuPuzzle);
int count = countCellsToFill(sudokuPuzzle);
System.out.println("Number of cells have to filled: " + count);
}
 public static void printSudoku(int[][] sudokuPuzzle)
 {
  for (int i = 0; i < sudokuPuzzle.length; i++)
    {
        if (i == 3 || i == 6)
            System.out.println("------------------------");
        for (int j = 0; j < sudokuPuzzle[i].length; j++)
        {
            System.out.format("%-2s", sudokuPuzzle[i][j]);
            if (j == 2 || j == 5 )
                System.out.print(" | ");
        }
        System.out.println();
    }
}

 public static int countCellsToFill(int[][] sudokuPuzzle){
int count=0;
for(int[] sudokuPuzzle1 : sudokuPuzzle){
    for(int a: sudokuPuzzle1){
        if(a == 0){
            count++;
        }
    }
}
return count;
}
 public boolean checkRow(int[] sudokuPuzzle){
for (int row = 0; row < sudokuPuzzle.length; row++)
{
        int num = sudokuPuzzle[row];
            if (num == sudokuPuzzle[row])
            {
                return true;
            }
}
return false;
}
}

Body:
Take a moment and read your code:

 public boolean checkRow(int[] sudokuPuzzle){
    for (int row = 0; row < sudokuPuzzle.length; row++)
    {
       int num = sudokuPuzzle[row];
       if (num == sudokuPuzzle[row])
       {
          return true;
       }
    }
       return false;
 }

What you are doing here is picking up the first number, "8" in this case, because it is on your position "0". Then, you check if that "8" is on your position "0", which of course, will be always true.

If you wanna check numbers per row, I suggest you to analize it with, maybe, a double for. So you can do your 9 lines, 9 numbers per line, and gotta have in mind don't compare the number you just read with himself.

By the way, if you are doing a Sudoku, you should check if that number appears in the first square as well. Sodukus are composed by 9 squares, you can not repeat numbers in rows, nor in columns, nor in squares.

That is an easy problem, struggle a bit!


问:
override delete_selected to check for records that exist in other tables in django 1.10
I am using the default admin dashboard of django. Basically, i want to override the delete_selected method on a model by model basis so I can check for records before allowing the deletion to take place.

My models.py is:

```<code>class Kind(models.Model):

    name = models.CharField(max_length=50, unique=True)
    addedby = models.ForeignKey(User,related_name='admin_kind')
    createdon = models.DateTimeField(auto_now_add=True)
    updatedon = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name',)

class Item(models.Model):

    name = models.CharField(max_length=50)
    kind = models.ForeignKey(Kind,related_name="item_kind")
    createdon = models.DateTimeField(auto_now_add=True)
    updatedon = models.DateTimeField(auto_now=True)

    def __str__(self):
        return ' , '.join([self.kind.name, self.name])

    class Meta:
        ordering = ('kind', 'name',)
        unique_together = (('name','kind'))
</code>```

Now what I want is before a kind could be deleted, I want to check if there is a related record in items. If there is, do not delete it.

But i am stuck at how to go about overriding delete_selected method in admin.py.

```<code>def delete_selected(self, request, obj):
    '''
    Delete Kind only if there are no items under it.
    '''
    for o in obj.all():
        featuredItems = Item.objects.filter(kind=o).count()
        if featuredItems == 0:
            o.delete()
</code>```

However, django shows the warning and when i click yes, it deletes the kind even though there are records for it. I want to absolutely block the deletion.

答:
Function code is correct, but you need to explicitly tell django to use your own function to delete that model's objects. You can do that by declaring a list in your admin.py,

```<code>actions = ['delete_selected']
</code>```

Where "delete_selected" is your function name.

Body:
I am using the default admin dashboard of django. Basically, i want to override the delete_selected method on a model by model basis so I can check for records before allowing the deletion to take place.

My models.py is:

class Kind(models.Model):

    name = models.CharField(max_length=50, unique=True)
    addedby = models.ForeignKey(User,related_name='admin_kind')
    createdon = models.DateTimeField(auto_now_add=True)
    updatedon = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name',)

class Item(models.Model):

    name = models.CharField(max_length=50)
    kind = models.ForeignKey(Kind,related_name="item_kind")
    createdon = models.DateTimeField(auto_now_add=True)
    updatedon = models.DateTimeField(auto_now=True)

    def __str__(self):
        return ' , '.join([self.kind.name, self.name])

    class Meta:
        ordering = ('kind', 'name',)
        unique_together = (('name','kind'))

Now what I want is before a kind could be deleted, I want to check if there is a related record in items. If there is, do not delete it.

But i am stuck at how to go about overriding delete_selected method in admin.py.

def delete_selected(self, request, obj):
    '''
    Delete Kind only if there are no items under it.
    '''
    for o in obj.all():
        featuredItems = Item.objects.filter(kind=o).count()
        if featuredItems == 0:
            o.delete()

However, django shows the warning and when i click yes, it deletes the kind even though there are records for it. I want to absolutely block the deletion.

Body:
Function code is correct, but you need to explicitly tell django to use your own function to delete that model's objects. You can do that by declaring a list in your admin.py,

actions = ['delete_selected']

Where "delete_selected" is your function name.


问:
Make UITableView Header "stickier", harder to pull down
I have added header with custom view to my TableView. It is used as a search bar, I set contentOffset so it is hidden in beginning.

Everything works as expected but I am wondering if there is any way to make it harder to pull down? (should be stickier) Now it opens with just regular scrolling which is too easy.

EDIT: ScrollViewDidScroll Code

```<code>if tableView.contentOffset.y < 80 && tableView.contentOffset.y > 40 {
            subscriptionsTableView.contentOffset.y += 0.23

            print("Content offset")
            print(tableView.contentOffset.y)
}
</code>```

答:
I had a similiar problem and solved in quite easily in the end. I set the table view top inset to the height of the header

```<code>tableView.contentInset.top = -1 * headerView.frame.size.height
</code>```

This makes the header be shown "off screen", the user is now not being able to scroll to it. I added a code to change the top inset to 0, showing the header, when the user scrolls to the top over the header

```<code>func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.y < 0 {
        UIView.animate(withDuration: 0.25, animations: {
            self.tableView.contentInset.top = 0
        })
    } else if scrollView.contentOffset.y > headerView.frame.size.height {
        UIView.animate(withDuration: 0.25, animations: {
            self.searchBar.resignFirstResponder()
            self.tableView.contentInset.top = -1 * self.headerView.frame.size.height
        })
    }
}
</code>```

I also set the top inset back when the user scrolls the table view.

Body:
I have added header with custom view to my TableView. It is used as a search bar, I set contentOffset so it is hidden in beginning.

Everything works as expected but I am wondering if there is any way to make it harder to pull down? (should be stickier) Now it opens with just regular scrolling which is too easy.

EDIT: ScrollViewDidScroll Code

if tableView.contentOffset.y < 80 && tableView.contentOffset.y > 40 {
            subscriptionsTableView.contentOffset.y += 0.23

            print("Content offset")
            print(tableView.contentOffset.y)
}

Body:
I had a similiar problem and solved in quite easily in the end. I set the table view top inset to the height of the header

tableView.contentInset.top = -1 * headerView.frame.size.height

This makes the header be shown "off screen", the user is now not being able to scroll to it. I added a code to change the top inset to 0, showing the header, when the user scrolls to the top over the header

func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.y < 0 {
        UIView.animate(withDuration: 0.25, animations: {
            self.tableView.contentInset.top = 0
        })
    } else if scrollView.contentOffset.y > headerView.frame.size.height {
        UIView.animate(withDuration: 0.25, animations: {
            self.searchBar.resignFirstResponder()
            self.tableView.contentInset.top = -1 * self.headerView.frame.size.height
        })
    }
}

I also set the top inset back when the user scrolls the table view.


问:
Qt: Does a QReadWriteLock work as shown?
I have four threads that need to be syncronized. In order to achieve this, I am looking to pass each thread the same bool array. Each thread will change the 'corresponding' value to true once it has reached a certain point in the thread, then constantly check to see if the rest of the values are true. If so, enter the loop... An example

```<code>//above thread init stuff
oLock->lockForWrite();
abSync[iThreadNum] = true;  //iThreadNum = {0...3} depending on whats set
oLock->unlock();

bool bSynced = false;
while (!bSynced)
{
    oLock->lockForRead();
    if (abSync[0] && abSync[1] && abSync[2] && abSync[3])
        bSynced = true;
    oLock->unlock();
}

//below thread run and finish
</code>```

Does the QReadWriteLock work as described above? Will it in fact lock the variable for the write (as each thread goes through) but not for the read? A quick look at the documentation suggests that QReadWriteLock will only block at lockForRead() if there is a write lock but not a read lock which is what I want above.

Also, I understand the above will suck down CPU cycles as its going through the loop and that is the wanted behavior. Using a Sleep is not good enough for our needs.

答: No the QReadWriteLock doesn't do exactly what you want to do, after reading your comment above you really dont need any lock for writting data, you just need to assure that the reads are volative on your array. If you need the threads to run at the same time why not a count down latch? That ensures that all threads (possibly) start at the same time.</p>

Body:
I have four threads that need to be syncronized. In order to achieve this, I am looking to pass each thread the same bool array. Each thread will change the 'corresponding' value to true once it has reached a certain point in the thread, then constantly check to see if the rest of the values are true. If so, enter the loop... An example

//above thread init stuff
oLock->lockForWrite();
abSync[iThreadNum] = true;  //iThreadNum = {0...3} depending on whats set
oLock->unlock();

bool bSynced = false;
while (!bSynced)
{
    oLock->lockForRead();
    if (abSync[0] && abSync[1] && abSync[2] && abSync[3])
        bSynced = true;
    oLock->unlock();
}

//below thread run and finish

Does the QReadWriteLock work as described above? Will it in fact lock the variable for the write (as each thread goes through) but not for the read? A quick look at the documentation suggests that QReadWriteLock will only block at lockForRead() if there is a write lock but not a read lock which is what I want above.

Also, I understand the above will suck down CPU cycles as its going through the loop and that is the wanted behavior. Using a Sleep is not good enough for our needs.


问:
VS2010 "Could not write lines to file".........."Network path not found"
does anybody know what this error in VS2010 means (i did try google but not much came up for this case on ATI stream)

```<code>Error   9   error MSB3491: Could not write lines to file "\\samples\\opencl\\bin\\debug\\x86_64\\MatrixMulDoubleVS10.exe.embed.manifest". The network path was not found.   C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets   673
</code>```

Im trying to run the ATI Stream SDK examples

答: I had a same error in my downloaded sample which was from VC6++. There were errors because output directory and intermediate directory were not given properly. I corrected them and problem was solved. </p>

Body:
does anybody know what this error in VS2010 means (i did try google but not much came up for this case on ATI stream)

Error   9   error MSB3491: Could not write lines to file "\\samples\\opencl\\bin\\debug\\x86_64\\MatrixMulDoubleVS10.exe.embed.manifest". The network path was not found.   C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets   673

Im trying to run the ATI Stream SDK examples


问:
Android cordova push icon missing
Recieving push notes works, yet the icon for my app remains empty

Tried the below and a path to one of the images in my asset folder. Neither works...

```<code>   let push = Push.init({
        android: {
          senderID: "XYZ",
          "icon": "drawable-ldpi-icon",
              "iconColor": "blue"
        },...
</code>```

Suggestions anyone?

答:
First of all you should crop your logo to white transparent png :

platforms/android/res/drawable-hdpi/ic_notify.png (24 × 24 )

platforms/android/res/drawable-mdpi/ic_notify.png (36 × 36)

platforms/android/res/drawable-xhdpi/ic_notify.png (48 × 48)

platforms/android/res/drawable-xxhdpi/ic_notify.png (72 × 72)

platforms/android/res/drawable-xxxhdpi/ic_notify.png (96 × 96)

or just go to this link

to automaticly generate all format

put all four file on

```<code>\platforms\android\res\drawable-hdpi\ic_stat_ac_unit.png
\platforms\android\res\drawable-mdpi\ic_stat_ac_unit.png
\platforms\android\res\drawable-xhdpi\ic_stat_ac_unit.png
\platforms\android\res\drawable-xxhdpi\ic_stat_ac_unit.png
\platforms\android\res\drawable-xxxhdpi\ic_stat_ac_unit.png
</code>```

And make shourt that you specify

```<code> Push.init({
         android: {
           senderID: "XYZ",
           "icon": "ic_stat_ac_unit",
               "iconColor": "blue"
         }....
</code>```

In final case you will also specify

```<code>    var DATA = {
        "to": "fple.....",
        "data": {
              "title":"", // Title notification
              "message": "\u270C Peace, Love \u2764",
              "color":"#cccccc", // color title notification
              "icon":"ic_stat_ac_unit",
              "smallIcon": "ic_stat_ac_unit",
              "largeIcon": "ic_stat_ac_unit"
        }};
</code>```

Title: Android cordova push icon missing

Body:
Recieving push notes works, yet the icon for my app remains empty

Tried the below and a path to one of the images in my asset folder. Neither works...

   let push = Push.init({
        android: {
          senderID: "XYZ",
          "icon": "drawable-ldpi-icon",
              "iconColor": "blue"
        },...

Suggestions anyone?

Body:
First of all you should crop your logo to white transparent png :

platforms/android/res/drawable-hdpi/ic_notify.png (24 × 24 )

platforms/android/res/drawable-mdpi/ic_notify.png (36 × 36)

platforms/android/res/drawable-xhdpi/ic_notify.png (48 × 48)

platforms/android/res/drawable-xxhdpi/ic_notify.png (72 × 72)

platforms/android/res/drawable-xxxhdpi/ic_notify.png (96 × 96)

or just go to this link

to automaticly generate all format

put all four file on

\platforms\android\res\drawable-hdpi\ic_stat_ac_unit.png
\platforms\android\res\drawable-mdpi\ic_stat_ac_unit.png
\platforms\android\res\drawable-xhdpi\ic_stat_ac_unit.png
\platforms\android\res\drawable-xxhdpi\ic_stat_ac_unit.png
\platforms\android\res\drawable-xxxhdpi\ic_stat_ac_unit.png

And make shourt that you specify

 Push.init({
         android: {
           senderID: "XYZ",
           "icon": "ic_stat_ac_unit",
               "iconColor": "blue"
         }....

In final case you will also specify

    var DATA = {
        "to": "fple.....",
        "data": {
              "title":"", // Title notification
              "message": "\u270C Peace, Love \u2764",
              "color":"#cccccc", // color title notification
              "icon":"ic_stat_ac_unit",
              "smallIcon": "ic_stat_ac_unit",
              "largeIcon": "ic_stat_ac_unit"
        }};


问:
PHP - How to search an associative array by matching the key against a regexp
I am currently working on a small script to convert data coming from an external source. Depending on the content I need to map this data to something that makes sense to my application.

A sample input could be:

```<code>$input = 'We need to buy paper towels.'
</code>```

Currently I have the following approach:

```<code>// Setup an assoc_array what regexp match should be mapped to which itemId
private $itemIdMap = [ '/paper\stowels/' => '3746473294' ];

// Match the $input ($key) against the $map and return the first match
private function getValueByRegexp($key, $map) {
  $match = preg_grep($key, $map);
  if (count($match) > 0) {
    return $match[0];
  } else {
    return '';
  }
}
</code>```

This raises the following error on execution:

Warning: preg_grep(): Delimiter must not be alphanumeric or backslash

What am I doing wrong and how could this be solved?

答:
In preg_grep manual order of arguments is:

```<code>string $pattern , array $input
</code>```

In your code $match = preg_grep($key, $map); - $key is input string, $map is a pattern.

So, your call is

```<code>$match = preg_grep(
    'We need to buy paper towels.',
    [ '/paper\stowels/' => '3746473294' ]
);
</code>```

So, do you really try to find string We need to buy paper towels in a number 3746473294?

So first fix can be - swap'em and cast second argument to array:

```<code>$match = preg_grep($map, array($key));
</code>```

But here comes second error - $itemIdMap is array. You can't use array as regexp. Only scalar values (more strictly - strings) can be used. This leads you to:

```<code>$match = preg_grep($map['/paper\stowels/'], $key);
</code>```

Which is definitely not what you want, right?

The solution:

```<code>$input = 'We need to buy paper towels.';
$itemIdMap = [
    '/paper\stowels/' => '3746473294',
    '/other\sstuff/' => '234432',
    '/to\sbuy/' => '111222',
];

foreach ($itemIdMap as $k => $v) {
    if (preg_match($k, $input)) {
        echo $v . PHP_EOL;
    }
}
</code>```

Your wrong assumption is that you think you can find any item from array of regexps in a single string with preg_grep, but it's not right. Instead, preg_grep searches elements of array, which fit one single regexp. So, you just used the wrong function.

Body:
I am currently working on a small script to convert data coming from an external source. Depending on the content I need to map this data to something that makes sense to my application.

A sample input could be:

$input = 'We need to buy paper towels.'

Currently I have the following approach:

// Setup an assoc_array what regexp match should be mapped to which itemId
private $itemIdMap = [ '/paper\stowels/' => '3746473294' ];

// Match the $input ($key) against the $map and return the first match
private function getValueByRegexp($key, $map) {
  $match = preg_grep($key, $map);
  if (count($match) > 0) {
    return $match[0];
  } else {
    return '';
  }
}

This raises the following error on execution:

Warning: preg_grep(): Delimiter must not be alphanumeric or backslash

What am I doing wrong and how could this be solved?

Body:
In preg_grep manual order of arguments is:

string $pattern , array $input

In your code $match = preg_grep($key, $map); - $key is input string, $map is a pattern.

So, your call is

$match = preg_grep(
    'We need to buy paper towels.',
    [ '/paper\stowels/' => '3746473294' ]
);

So, do you really try to find string We need to buy paper towels in a number 3746473294?

So first fix can be - swap'em and cast second argument to array:

$match = preg_grep($map, array($key));

But here comes second error - $itemIdMap is array. You can't use array as regexp. Only scalar values (more strictly - strings) can be used. This leads you to:

$match = preg_grep($map['/paper\stowels/'], $key);

Which is definitely not what you want, right?

The solution:

$input = 'We need to buy paper towels.';
$itemIdMap = [
    '/paper\stowels/' => '3746473294',
    '/other\sstuff/' => '234432',
    '/to\sbuy/' => '111222',
];

foreach ($itemIdMap as $k => $v) {
    if (preg_match($k, $input)) {
        echo $v . PHP_EOL;
    }
}

Your wrong assumption is that you think you can find any item from array of regexps in a single string with preg_grep, but it's not right. Instead, preg_grep searches elements of array, which fit one single regexp. So, you just used the wrong function.


问:
converting the bitmap to imageview
I have written my own custom view, in the custom view i have done free hand drawing using canvas.. After that i've added the custom view to linear layout.. how to add the custom view to  image view.. please help me out...Thanks in advance...</p>

答:
In this case, you can convert your custom view to Bitmap image by using the following snippet:

```<code>public static Bitmap getBitmapFromView(View view) {
        //Define a bitmap with the same size as the view
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
        //Bind a canvas to it
        Canvas canvas = new Canvas(returnedBitmap);
        //Get the view's background
        Drawable bgDrawable =view.getBackground();
        if (bgDrawable!=null)
            //has background drawable, then draw it on the canvas
            bgDrawable.draw(canvas);
        else
            //does not have background drawable, then draw white background on the canvas
            canvas.drawColor(Color.WHITE);
        // draw the view on the canvas
        view.draw(canvas);
        //return the bitmap
        return returnedBitmap;
}
</code>```

Then you can add bitmap to image view by using the following method:

```<code>imageview.setBitmapImage(returnedBitmap);
</code>```

Title: converting the bitmap to imageview

Body:
In this case, you can convert your custom view to Bitmap image by using the following snippet:

public static Bitmap getBitmapFromView(View view) {
        //Define a bitmap with the same size as the view
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
        //Bind a canvas to it
        Canvas canvas = new Canvas(returnedBitmap);
        //Get the view's background
        Drawable bgDrawable =view.getBackground();
        if (bgDrawable!=null)
            //has background drawable, then draw it on the canvas
            bgDrawable.draw(canvas);
        else
            //does not have background drawable, then draw white background on the canvas
            canvas.drawColor(Color.WHITE);
        // draw the view on the canvas
        view.draw(canvas);
        //return the bitmap
        return returnedBitmap;
}

Then you can add bitmap to image view by using the following method:

imageview.setBitmapImage(returnedBitmap);


问:
Visual Studio Deployment Project: Allow User to Select Configuration file at runtime
I have a Windows service I built with VS2008. The service is installed on the target machine via and MSI, which I built using a Setup and Deployment project in Visual Studio. When the MSI is run, it copies the binaries needed to the target directory and installs the service in the service control manager.

I have the projects set up so that they create a "Configs" directory in the target directory. There is one configuration file for each type of environment (Dev, QA, Prod).

As it currently stands, when the installation is complete, the user must go to the Configs directory and copy the desired configuration to the base target directory. This is a source of confusion and a few errors.

I would like the MSI file to prompt the user for the

答:
I've accomplished the same need functionality in setup projects for my service deployments successfully.

First, you'll need add your "Configs" directory under the Application Folder in "File System" of your setup project.

Second, view the "User Interface" designer. Here you will need to add a new dialog. What I did was add a dialog with two radio buttons (choices being development or production). I placed mine after the "Welcome" dialog in the setup menu sequence.

Select your new dialog and add what you need in the Properties window. In my body text, I tell the user to "Select a deployment option". From there you set values for each choice. My Button1Label property reads as "Development" with a Button1Value of 1. Button 2 is "Production" with a value of 2. I named the ButtonProperty "DEPLOY".

Finally, add each config file to the File System under "Application Folder" -> "Configs".
The key action here is tying each config file to a deployment option. For a development config file it's Condition property would be:

```<code>DEPLOY=1
</code>```

Similarily the production config Condition property would be:

```<code>DEPLOY=2
</code>```

It's simple but it does exactly what you need it to do. Which is hard to do with setup projects. They lack a whole lot of functionality.

Body:
I've accomplished the same need functionality in setup projects for my service deployments successfully.

First, you'll need add your "Configs" directory under the Application Folder in "File System" of your setup project.

Second, view the "User Interface" designer. Here you will need to add a new dialog. What I did was add a dialog with two radio buttons (choices being development or production). I placed mine after the "Welcome" dialog in the setup menu sequence.

Select your new dialog and add what you need in the Properties window. In my body text, I tell the user to "Select a deployment option". From there you set values for each choice. My Button1Label property reads as "Development" with a Button1Value of 1. Button 2 is "Production" with a value of 2. I named the ButtonProperty "DEPLOY".

Finally, add each config file to the File System under "Application Folder" -> "Configs".
The key action here is tying each config file to a deployment option. For a development config file it's Condition property would be:

DEPLOY=1

Similarily the production config Condition property would be:

DEPLOY=2

It's simple but it does exactly what you need it to do. Which is hard to do with setup projects. They lack a whole lot of functionality.


问:
Download data from http using Python Spark streaming
I am new for PySpark and I installed Kafka single node and single broker on my Ubuntu 14.04.

After installation I tested the Kafka that sending and receiving data by using kafka-console-producer and kafka-console-consume.

Below are the steps I followed
Starting a consumer to consuming messages.

```<code> bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic kafkatopic --from-beginning
</code>```

Starting a producer to sending messages in a new terminal window.

```<code>bin/kafka-console-producer.sh --broker-list localhost:9092 --topic kafkatopic
[2016-09-25 7:26:58,179] WARN Property topic is not valid (kafka.utils.VerifiableProperties)
Good morning
Future big data
this is test message
</code>```

In the consumer terminal

```<code>bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic kafkatopic --from-beginning
Good morning
Future big data
this is test message
</code>```

The below link from meetup.com produce streaming data

http://stream.meetup.com/2/rsvps

My requirement is how to collect the streaming data from http site to spark using Kafka. What is the transformation command to download streamin data?

After downloading the data I can find the count by city and other analysis for a particular time interval.

答: There are different ways to process realtime streaming. The one i am considering is like below one.

Body:
I am new for PySpark and I installed Kafka single node and single broker on my Ubuntu 14.04.

After installation I tested the Kafka that sending and receiving data by using kafka-console-producer and kafka-console-consume.

Below are the steps I followed
Starting a consumer to consuming messages.

 bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic kafkatopic --from-beginning

Starting a producer to sending messages in a new terminal window.

bin/kafka-console-producer.sh --broker-list localhost:9092 --topic kafkatopic
[2016-09-25 7:26:58,179] WARN Property topic is not valid (kafka.utils.VerifiableProperties)
Good morning
Future big data
this is test message

In the consumer terminal

bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic kafkatopic --from-beginning
Good morning
Future big data
this is test message

The below link from meetup.com produce streaming data

http://stream.meetup.com/2/rsvps

My requirement is how to collect the streaming data from http site to spark using Kafka. What is the transformation command to download streamin data?

After downloading the data I can find the count by city and other analysis for a particular time interval.


问:
Can't login to heroku using CLI
I try to login to heroku on Windows. Using cmd.exe

```<code>C:\Users\Komp_1\OneDrive\PHP_projects\chatbot>heroku auth:login
Enter your Heroku credentials:
Email: sergiuszxxxi@gmail.com
Password: **********
Enter your Heroku credentials:
Email: sergiuszxxxi@gmail.com
Password: **********
Enter your Heroku credentials:
Email:
</code>```

It looks like a never ending loop. But when I try use a git-bash to login than:

```<code>$ heroku login
Enter your Heroku credentials:
Email: Sergiusxxxi@gmail.com
 !    Login is currently incompatible with git bash/Cygwin/MinGW
</code>```

What can be wrong? I can't find solution.

答:
Ok so probably that was problem from Heroku. Simple steps to repair this:
1. Go to heroku
2. Log out
3. Reset password
4. Go to your email and set up new password
5. Login to your heroku :-)

PS. My password was correct and I used this same in cmd and on heroku. On heroku worked but in cmd not :-)

Title: Can't login to heroku using CLI

Body:
I try to login to heroku on Windows. Using cmd.exe

C:\Users\Komp_1\OneDrive\PHP_projects\chatbot>heroku auth:login
Enter your Heroku credentials:
Email: sergiuszxxxi@gmail.com
Password: **********
Enter your Heroku credentials:
Email: sergiuszxxxi@gmail.com
Password: **********
Enter your Heroku credentials:
Email:

It looks like a never ending loop. But when I try use a git-bash to login than:

$ heroku login
Enter your Heroku credentials:
Email: Sergiusxxxi@gmail.com
 !    Login is currently incompatible with git bash/Cygwin/MinGW

What can be wrong? I can't find solution.


问:
Scan C disk and copy files
I would appreciate some help here.

The Powershell script should close Outlook process which works.

Aswell as scan C disk for .pst files which works.

Copy these files to "\fileserver01\temp\test\"

Export to csv/excel list where these files where located and last write time.

Possible hide error messages for the user when running the script since it complains about not full access on a few folders when running the scan.

Code:

```<code>Get-Process outlook | Foreach-Object { $_.CloseMainWindow() }

Get-ChildItem -path c:\ -recurse -include *.pst | `
Copy-Item -destination "\\fileserver01\temp\test\" | `
Select-object fullname,lastwritetime|export-csv "\\fileserver01\temp\test\"
</code>```

How should I fix the last couple of things on my list?
Thanks

答:
This doesn't directly answer the question you've asked, as @Adamar's answer appears to do just that.

however, your issue could also be resolved by querying ost/pst files from registry using a snippet like this:

```<code>(Get-ChildItem HKCU:\Software\Microsoft\Office\16.0\Outlook\Search).Property | ? {$_ -match "(o|p)st$"}
</code>```

which will return all of the ost/pst files the logged in user has open in outlook.

a snippet like this will then copy them all to a network share and print the logs to a file.

```<code>$FilesToCopy = (Get-ChildItem HKCU:\Software\Microsoft\Office\16.0\Outlook\Search).Property | ? {$_ -match "(o|p)st$"}
$FilesToCopy | ForEach { Copy-Item -Path $_ -Destination "\\network\share" ; $_ | Out-File "\\network\share\log.txt" -Append }
</code>```

This saves a LOT of time over indexing through all of the C: drive - there's also an issue where very long directory names (greater than 260 char length) are not indexed properly by Get-ChildItem - making this method a bit more reliable and appealing for a production script.

Title: Scan C disk and copy files

Body:
I would appreciate some help here.

The Powershell script should close Outlook process which works.

Aswell as scan C disk for .pst files which works.

Copy these files to "\fileserver01\temp\test\"

Export to csv/excel list where these files where located and last write time.

Possible hide error messages for the user when running the script since it complains about not full access on a few folders when running the scan.

Code:

Get-Process outlook | Foreach-Object { $_.CloseMainWindow() }

Get-ChildItem -path c:\ -recurse -include *.pst | `
Copy-Item -destination "\\fileserver01\temp\test\" | `
Select-object fullname,lastwritetime|export-csv "\\fileserver01\temp\test\"

How should I fix the last couple of things on my list?
Thanks

Body:
This doesn't directly answer the question you've asked, as @Adamar's answer appears to do just that.

however, your issue could also be resolved by querying ost/pst files from registry using a snippet like this:

(Get-ChildItem HKCU:\Software\Microsoft\Office\16.0\Outlook\Search).Property | ? {$_ -match "(o|p)st$"}

which will return all of the ost/pst files the logged in user has open in outlook.

a snippet like this will then copy them all to a network share and print the logs to a file.

$FilesToCopy = (Get-ChildItem HKCU:\Software\Microsoft\Office\16.0\Outlook\Search).Property | ? {$_ -match "(o|p)st$"}
$FilesToCopy | ForEach { Copy-Item -Path $_ -Destination "\\network\share" ; $_ | Out-File "\\network\share\log.txt" -Append }

This saves a LOT of time over indexing through all of the C: drive - there's also an issue where very long directory names (greater than 260 char length) are not indexed properly by Get-ChildItem - making this method a bit more reliable and appealing for a production script.


问:
Remove particular string from url Jquery
I need to remove size i.e. resolution of image path from url. Take following example:

```<code>http://raudevlocal.com/wp/wp-content/uploads/2017/05/0000362_chocolate-layer-cake-1024x682.jpeg
</code>```

I need to remove -1024x682

```<code>http://raudevlocal.com/wp/wp-content/uploads/2017/05/rohit-300x118.jpg
</code>```

Need to remove -300x118

答:
```<code>str = "http://raudevlocal.com/wp/wp-content/uploads/2017/05/0000362_chocolate-layer-cake-1024x682.jpeg";
str.replace(/-(\d+x\d+)/, "");
output will be
http://raudevlocal.com/wp/wp-content/uploads/2017/05/0000362_chocolate-layer-cake.jpeg
</code>```

Body:
I need to remove size i.e. resolution of image path from url. Take following example:

http://raudevlocal.com/wp/wp-content/uploads/2017/05/0000362_chocolate-layer-cake-1024x682.jpeg

I need to remove -1024x682

http://raudevlocal.com/wp/wp-content/uploads/2017/05/rohit-300x118.jpg

Need to remove -300x118


问:
Unable to click the element. Error: no such element: Unable to locate element:
I am practicing on flipkart.com. i am unable to click the product after the search result. The xpath is correct. I tried using scroll function,visible, find by partial linktext, wait, sleep still i am unable to do. Please find the below code.</p>

```<code>package Flipkart;

import org.openqa.selenium.By; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class TC2
{
    public static void main(String[] args) throws InterruptedException
    {
        System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.flipkart.com/");
        driver.findElement(By.name("q")).sendKeys("Bag");
        driver.findElement(By.xpath("html/body/div[1]/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[2]/button")).click();
        driver.findElement(By.xpath(".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]")).click();
    }
}

  Error:
    Starting ChromeDriver 2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed) on port 17575
    Only local connections are allowed.
    Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]"}
      (Session info: chrome=58.0.3029.81)
      (Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 76 milliseconds
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
    System info: host: 'D90T0CQ1', ip: '192.168.162.83', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_102'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed), userDataDir=C:\Users\SALUNK~1\AppData\Local\Temp\scoped_dir12552_16506}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=58.0.3029.81, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
    Session ID: a8c3432c9b1e8cce3365db9407fc310f
    *** Element info: {Using=xpath, value=.//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
        at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
        at Flipkart.TC2.main(TC2.java:15)
</code>```

答:
I have tried the same lines of code which you have mentioned and things work for me. Maybe you should try again.

Please try to use small xpath:

Suggestion:

Replace Xpath: html/body/div[1]/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[2]/button with the different Xpath:
                                        //form[@action="/search"]/div/div[2]/button

You should use relative path instead of absolute path because if there are any changes made in the path of the element then that XPath gets failed.

Body:
I am practicing on flipkart.com. i am unable to click the product after the search result. The xpath is correct. I tried using scroll function,visible, find by partial linktext, wait, sleep still i am unable to do. Please find the below code.

package Flipkart;

import org.openqa.selenium.By; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class TC2
{
    public static void main(String[] args) throws InterruptedException
    {
        System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.flipkart.com/");
        driver.findElement(By.name("q")).sendKeys("Bag");
        driver.findElement(By.xpath("html/body/div[1]/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[2]/button")).click();
        driver.findElement(By.xpath(".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]")).click();
    }
}

  Error:
    Starting ChromeDriver 2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed) on port 17575
    Only local connections are allowed.
    Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]"}
      (Session info: chrome=58.0.3029.81)
      (Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 76 milliseconds
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
    System info: host: 'D90T0CQ1', ip: '192.168.162.83', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_102'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed), userDataDir=C:\Users\SALUNK~1\AppData\Local\Temp\scoped_dir12552_16506}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=58.0.3029.81, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
    Session ID: a8c3432c9b1e8cce3365db9407fc310f
    *** Element info: {Using=xpath, value=.//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
        at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
        at Flipkart.TC2.main(TC2.java:15)


问:
How to compare 2 images in Android programatically?
I am making an app in which i need to show all duplicate photos and delete them .I want to know which is the best way to identify duplicate images from device.Please help me. </p>

答:
As in the comments mentioned, there is different ways to compare images, such as if both images have same file, id, size, resolution or more advanced through openCV, which has numerous image manipulation functions and you can easily integrate it with android.

Otherwise, you could also look at Bitmap class has method "sameAs" you can use that method to compare two bitmaps. But you need to convert the image to bitmap.