问:
How can I call a Supplier-based constructor for a recursive set of classes based on generic container?
I have seen advice that a Supplier can be used to create an instance of a parametrized class.

E.g. Here: "Instantiating object of type parameter" or here: "Create instance of generic type in Java?"

How to create the Supplier seems clear from the linked answers:

```<code>// Example of creating objects in linked answers
MyClass<StringBuilder> it = new MyClass<>(StringBuilder::new);
SomeContainer<String> stringContainer = new SomeContainer<>(String::new);
</code>```

but how to use it for a recursive set of classes based on generic container doesn't seem to be clear.

My problem is that this Supplier methods itself has to be called as a parameter of the constructor for each recursive class. Example:

```<code>class SetOf<E> {
    // Supplier-based code from SO Q #75175
    private Supplier<E> supplier;
    SetOf(Supplier<E> supplier) { this.supplier = supplier; }
    createE() { return supplier.get(); }

    addToContainer(key) {
        E value = createE(); // I assume that's how it's used?
        this.add(key, value);
    }
}
</code>```

The problem here is that if we are building container of containers thusly:

```<code>class SetOfThings extends SetOf<Thing> {}
class SetOfSetsOfThings extends SetOf<SetOfThings> {}
class SetOfSetOfSetsOfThings extends SetOf<SetOfSetOfThings> {}
SetOf<SetOfSetOfSetOfThings> root = new SetOf<>(SetOfSetOfThings::new);
</code>```

So, what we are passing to the Supplier of outer class (SetOfSetOfSetOfThings) is the reference to constructor of inner class (SetOfSetOfThings) - BUT, when that SetOfSetOfThings() constructor will be called, it will be called with no parameters, meaning that there will be NO supplier for SetOfThings set in the SetOfSetOfThings object! (which means we can never create SetOfThings objects).

I suppose we can fix this 3-level chain somehow, by using Lambda syntax and passing a parameter (with value of SetOfThings::new) to SetOfSetOfThings::new in turn. But this only works because our chain is 3 levels deep - what if we have to instantiate 4-level deep chain with root class being SetOfSetOfSetsOfSetsOfThings?

This question is a very narrow Function/Supplier specific version of my more generic earlier question here (where comments pointed to both Supplier as an idea, and the linked answer showing how to use a supplier in general - neither of which work easily in case of recursive class hierarchy).

答:
You're going to need some kind of supplier passed to the constructor at any level, since the Thing at the base level ultimately has to come from somewhere. However, you can use Supplier<Thing> at every level like so:

```<code>class SetOfThings extends SetOf<Thing> {
    SetOfThings(Supplier<Thing> supplier) {
        super(supplier);
    }
}

class SetOfSetOfThings extends SetOf<SetOfThings> {
    SetOfSetOfThings(Supplier<Thing> supplier) {
        super(() -> new SetOfThings(supplier));
    }
}

class SetOfSetOfSetOfThings extends SetOf<SetOfSetOfThings> {
    SetOfSetOfSetOfThings(Supplier<Thing> supplier) {
        super(() -> new SetOfSetOfThings(supplier));
    }
}
</code>```

Then you can do:

```<code>SetOf<SetOfSetOfSetOfThings> root = new SetOf<>(() -> new SetOfSetOfSetOfThings(Thing::new));

SetOfSetOfSetOfThings ssst = root.createE();
SetOfSetOfThings sst = ssst.createE();
SetOfThings st = sst.createE();
Thing t = st.createE();
</code>```

EDIT: If you're just trying to create an instance of recursive SetOf type, you don't need subclasses:

```<code>SetOf<SetOf<SetOf<SetOf<Thing>>>> root = new SetOf<>(
        () -> new SetOf<>(
                () -> new SetOf<>(
                        () -> new SetOf<>(
                                Thing::new))));
</code>```

And with a helper method to make it look nicer:

```<code>public static <E> Supplier<SetOf<E>> setsOf(Supplier<E> supplier) {
    return () -> new SetOf<>(supplier);
}

SetOf<SetOf<SetOf<SetOf<Thing>>>> root = new SetOf<>(setsOf(setsOf(setsOf(Thing::new))));
</code>```

Body:
I have seen advice that a Supplier can be used to create an instance of a parametrized class.

E.g. Here: "Instantiating object of type parameter" or here: "Create instance of generic type in Java?"

How to create the Supplier seems clear from the linked answers:

// Example of creating objects in linked answers
MyClass<StringBuilder> it = new MyClass<>(StringBuilder::new);
SomeContainer<String> stringContainer = new SomeContainer<>(String::new);

but how to use it for a recursive set of classes based on generic container doesn't seem to be clear.

My problem is that this Supplier methods itself has to be called as a parameter of the constructor for each recursive class. Example:

class SetOf<E> {
    // Supplier-based code from SO Q #75175
    private Supplier<E> supplier;
    SetOf(Supplier<E> supplier) { this.supplier = supplier; }
    createE() { return supplier.get(); }

    addToContainer(key) {
        E value = createE(); // I assume that's how it's used?
        this.add(key, value);
    }
}

The problem here is that if we are building container of containers thusly:

class SetOfThings extends SetOf<Thing> {}
class SetOfSetsOfThings extends SetOf<SetOfThings> {}
class SetOfSetOfSetsOfThings extends SetOf<SetOfSetOfThings> {}
SetOf<SetOfSetOfSetOfThings> root = new SetOf<>(SetOfSetOfThings::new);

So, what we are passing to the Supplier of outer class (SetOfSetOfSetOfThings) is the reference to constructor of inner class (SetOfSetOfThings) - BUT, when that SetOfSetOfThings() constructor will be called, it will be called with no parameters, meaning that there will be NO supplier for SetOfThings set in the SetOfSetOfThings object! (which means we can never create SetOfThings objects).

I suppose we can fix this 3-level chain somehow, by using Lambda syntax and passing a parameter (with value of SetOfThings::new) to SetOfSetOfThings::new in turn. But this only works because our chain is 3 levels deep - what if we have to instantiate 4-level deep chain with root class being SetOfSetOfSetsOfSetsOfThings?

This question is a very narrow Function/Supplier specific version of my more generic earlier question here (where comments pointed to both Supplier as an idea, and the linked answer showing how to use a supplier in general - neither of which work easily in case of recursive class hierarchy).

Body:
You're going to need some kind of supplier passed to the constructor at any level, since the Thing at the base level ultimately has to come from somewhere. However, you can use Supplier<Thing> at every level like so:

class SetOfThings extends SetOf<Thing> {
    SetOfThings(Supplier<Thing> supplier) {
        super(supplier);
    }
}

class SetOfSetOfThings extends SetOf<SetOfThings> {
    SetOfSetOfThings(Supplier<Thing> supplier) {
        super(() -> new SetOfThings(supplier));
    }
}

class SetOfSetOfSetOfThings extends SetOf<SetOfSetOfThings> {
    SetOfSetOfSetOfThings(Supplier<Thing> supplier) {
        super(() -> new SetOfSetOfThings(supplier));
    }
}

Then you can do:

SetOf<SetOfSetOfSetOfThings> root = new SetOf<>(() -> new SetOfSetOfSetOfThings(Thing::new));

SetOfSetOfSetOfThings ssst = root.createE();
SetOfSetOfThings sst = ssst.createE();
SetOfThings st = sst.createE();
Thing t = st.createE();

EDIT: If you're just trying to create an instance of recursive SetOf type, you don't need subclasses:

SetOf<SetOf<SetOf<SetOf<Thing>>>> root = new SetOf<>(
        () -> new SetOf<>(
                () -> new SetOf<>(
                        () -> new SetOf<>(
                                Thing::new))));

And with a helper method to make it look nicer:

public static <E> Supplier<SetOf<E>> setsOf(Supplier<E> supplier) {
    return () -> new SetOf<>(supplier);
}

SetOf<SetOf<SetOf<SetOf<Thing>>>> root = new SetOf<>(setsOf(setsOf(setsOf(Thing::new))));


来源: stackexchange

问:
Using TFRecords for images
I want to use TFRecords to serialized a bunch of PNG files. for I took a look into inception repository. the give example is for RGB JPEG files, since my files are in grayscale,  I had to change  the code.
but I've managed to  generate the records files.
The problem is when I try to read them:

```<code>def getImage(filename):
with tf.device('/cpu:0'):
    # convert filenames to a queue for an input pipeline.
    filenameQ = tf.train.string_input_producer([filename],num_epochs=None)

    # object to read records
    recordReader = tf.TFRecordReader()

    # read the full set of features for a single example
    key, fullExample = recordReader.read(filenameQ)

    # parse the full example into its' component features.
    features = tf.parse_single_example(
        fullExample,
        features={
            'image/height': tf.FixedLenFeature([], tf.int64),
            'image/width': tf.FixedLenFeature([], tf.int64),
            'image/colorspace': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/channels':  tf.FixedLenFeature([], tf.int64),
            'image/class/label': tf.FixedLenFeature([],tf.int64),
            'image/class/text': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/format': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/filename': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/encoded': tf.FixedLenFeature([], dtype=tf.string, default_value='')
        })

    # now we are going to manipulate the label and image features
    label = features['image/class/label']
    image_buffer = features['image/encoded']
    # Decode the PNG
    with tf.name_scope('decode_img',[image_buffer], None):
        # decode
        image = tf.image.decode_png( image_buffer, channels=1)

        # and convert to single precision data type
        image = tf.image.convert_image_dtype(image, dtype=tf.float32)
    # cast image into a single array, where each element corresponds to the greyscale
    # value of a single pixel.

    image =tf.reshape([None, img_height*img_width])# here is the problem

    label=tf.stack(tf.one_hot(label-1, numberOFclasses))
    return label, image
</code>```

the problem is  the  reshape line,the program crashes when I try it this .
this how it's been used:

```<code>with tf.name_scope('decode_img',[image_buffer], None):
            # decode
            image = tf.image.decode_jpeg(image_buffer, channels=3)

            # and convert to single precision data type
            image = tf.image.convert_image_dtype(image, dtype=tf.float32)
        # cast image into a single array, where each element corresponds to the greyscale
        # value of a single pixel.
        # the "1-.." part inverts the image, so that the background is black.
        image=tf.reshape(1-tf.image.rgb_to_grayscale(image),[img_height*img_width])
</code>```

which make sens since, when the file are RGB. but I have only 1 channel so the file are already grayscale.

答:
You use tf.reshape([None, img_height*img_width]). First of all there is no first parameter (what exactly you are trying to reshape). It should be your image. Also most probably you want to reshape it in this way: tf.reshape(image, [img_height, img_width]).

Not related to your problem, but why do you need so many features in your TFRecord file?

ContentLicense: CC BY-SA 3.0

Title: Using TFRecords for images

Body:
I want to use TFRecords to serialized a bunch of PNG files. for I took a look into inception repository. the give example is for RGB JPEG files, since my files are in grayscale,  I had to change  the code.
but I've managed to  generate the records files.
The problem is when I try to read them:

def getImage(filename):
with tf.device('/cpu:0'):
    # convert filenames to a queue for an input pipeline.
    filenameQ = tf.train.string_input_producer([filename],num_epochs=None)

    # object to read records
    recordReader = tf.TFRecordReader()

    # read the full set of features for a single example
    key, fullExample = recordReader.read(filenameQ)

    # parse the full example into its' component features.
    features = tf.parse_single_example(
        fullExample,
        features={
            'image/height': tf.FixedLenFeature([], tf.int64),
            'image/width': tf.FixedLenFeature([], tf.int64),
            'image/colorspace': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/channels':  tf.FixedLenFeature([], tf.int64),
            'image/class/label': tf.FixedLenFeature([],tf.int64),
            'image/class/text': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/format': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/filename': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/encoded': tf.FixedLenFeature([], dtype=tf.string, default_value='')
        })

    # now we are going to manipulate the label and image features
    label = features['image/class/label']
    image_buffer = features['image/encoded']
    # Decode the PNG
    with tf.name_scope('decode_img',[image_buffer], None):
        # decode
        image = tf.image.decode_png( image_buffer, channels=1)

        # and convert to single precision data type
        image = tf.image.convert_image_dtype(image, dtype=tf.float32)
    # cast image into a single array, where each element corresponds to the greyscale
    # value of a single pixel.

    image =tf.reshape([None, img_height*img_width])# here is the problem

    label=tf.stack(tf.one_hot(label-1, numberOFclasses))
    return label, image

the problem is  the  reshape line,the program crashes when I try it this .
this how it's been used:

with tf.name_scope('decode_img',[image_buffer], None):
            # decode
            image = tf.image.decode_jpeg(image_buffer, channels=3)

            # and convert to single precision data type
            image = tf.image.convert_image_dtype(image, dtype=tf.float32)
        # cast image into a single array, where each element corresponds to the greyscale
        # value of a single pixel.
        # the "1-.." part inverts the image, so that the background is black.
        image=tf.reshape(1-tf.image.rgb_to_grayscale(image),[img_height*img_width])

which make sens since, when the file are RGB. but I have only 1 channel so the file are already grayscale.


问:
In perl, what is the difference between $DB::single = 1 and 2?
What is the difference between putting $DB::single=1 and $DB::single=2 in your code? Both seem to have the identical effect of halting execution at the statement following the assignment when I do a 'c' on the perl debugger command line.

perldebug says that a value of 1 is equivalent to having just pressed 's' to get to the next statement, and 2 is the same as 'n', but what difference does it make how you got to the statement?

答:
From perldebug:

If you set $DB::single to 2, it's equivalent to having just typed the n command (which executes over subroutine calls), whereas a value of 1 means the s command (which enters subroutine calls).

That much you know already.

From a user point of view, I'm pretty sure there is no difference. I base this on an examination of the actual DB.pm source code.

Let's follow this logically. You may want to refer to the source code. I've simplified some of the code to remove unnecessary detail but you should be able to get the idea from my descriptions.

When you are executing code in the debugger, there are (at least) two important variables, running and single. The combination of these is what decides whether code is run:

```<code>running  single  description
-------  ------  -----------
   0       ?     not running
   1       0     running flat-out
   1       1     single stepping, execute into function
   1       2     single stepping, execute over function
</code>```

The DB() function is executed for every single line, and it contains the following snippet which will stop the running if single has been set (it always executes the current line regardless):

```<code>if ($DB::single) {
    $DB::single = 0;
    $running = 0;
}
</code>```

That's why, if you set the variable in your Perl code, it will break (by break, I mean "stop running the code", not "damage somehow")  the debugger at the next line.

When running is 0, the DB() function enters this little loop:

```<code># Now sit in an event loop until something sets $running
do {
    $c->idle;          # call client event loop; must not block
} until $running;
</code>```

In other words, it waits on a user command which sets running back to 1. This can be done by one of the following three functions:

```<code>sub next {
    $DB::single = 2;
    $running = 1;
}

sub step {
    $DB::single = 1;
    $running = 1;
}

sub cont {
    $DB::single = 0;
    $running = 1;
}
</code>```

You can see that these three commands set up a different combination of single and running which will be used while executing the next Perl line (see the earlier table to see what these combinations mean).

The ability to use either 1 or 2 in your Perl code is a direct result of the fact that you're using a sneaky but clever trick to break execution from your Perl code itself, by setting a variable that would normally be set by a debugger command.

That's why it's not the value that matters so much as the fact you're forcing the debugger into a particular state.

Body:
From perldebug:

If you set $DB::single to 2, it's equivalent to having just typed the n command (which executes over subroutine calls), whereas a value of 1 means the s command (which enters subroutine calls).

That much you know already.

From a user point of view, I'm pretty sure there is no difference. I base this on an examination of the actual DB.pm source code.

Let's follow this logically. You may want to refer to the source code. I've simplified some of the code to remove unnecessary detail but you should be able to get the idea from my descriptions.

When you are executing code in the debugger, there are (at least) two important variables, running and single. The combination of these is what decides whether code is run:

running  single  description
-------  ------  -----------
   0       ?     not running
   1       0     running flat-out
   1       1     single stepping, execute into function
   1       2     single stepping, execute over function

The DB() function is executed for every single line, and it contains the following snippet which will stop the running if single has been set (it always executes the current line regardless):

if ($DB::single) {
    $DB::single = 0;
    $running = 0;
}

That's why, if you set the variable in your Perl code, it will break (by break, I mean "stop running the code", not "damage somehow")  the debugger at the next line.

When running is 0, the DB() function enters this little loop:

# Now sit in an event loop until something sets $running
do {
    $c->idle;          # call client event loop; must not block
} until $running;

In other words, it waits on a user command which sets running back to 1. This can be done by one of the following three functions:

sub next {
    $DB::single = 2;
    $running = 1;
}

sub step {
    $DB::single = 1;
    $running = 1;
}

sub cont {
    $DB::single = 0;
    $running = 1;
}

You can see that these three commands set up a different combination of single and running which will be used while executing the next Perl line (see the earlier table to see what these combinations mean).

The ability to use either 1 or 2 in your Perl code is a direct result of the fact that you're using a sneaky but clever trick to break execution from your Perl code itself, by setting a variable that would normally be set by a debugger command.

That's why it's not the value that matters so much as the fact you're forcing the debugger into a particular state.

ContentLicense: CC BY-SA 2.5


问:
Redirecting folders to their corresponding subdomains
Trying to configure apache via .htaccess so any folder will be redirected to the corresponding subdomain:

Example:

Original URL: http://zipcode.is/ro/010011
  redirects to: http://ro.zipcode.direct/010011

Moving the folder from zipcode.is/ro/010011 to a subdirectory on the new domain: ro.zipcode.direct/010011 (note that the domain is different as well). Now this is working but as soon as I change the country ISO code, it won't work any more e.g. zipcode.is/us/10128

答:
```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z]+)/(\d+)$ http://$1.zipcode.direct/$2 [R=301,L]
</code>```

the above was the best and shortest solution (thanks Ruslan G.!), the first method by Alexey S. doesn't check types and was less elegant, left it in case someone wants to further tweak:

```<code>RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*)$ http://$1.zipcode.direct/$2 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^.]*)$ http://$1.zipcode.direct [R=301,L]
</code>```

Body:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z]+)/(\d+)$ http://$1.zipcode.direct/$2 [R=301,L]

the above was the best and shortest solution (thanks Ruslan G.!), the first method by Alexey S. doesn't check types and was less elegant, left it in case someone wants to further tweak:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*)$ http://$1.zipcode.direct/$2 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^.]*)$ http://$1.zipcode.direct [R=301,L]


问:
Django select inherited model in a single query
Let's Assume I have a parent and a child tables which are implemented via inheritance in django.

models.py

```<code>class A(models.Model)
 a = CharField()

class B(A):
 b = CharField()
</code>```

Now I want to select column b from table B I execute:

```<code>B.objects.only('b').get(id=4)
</code>```

But this statement queries database 2 times:

SELECT `b`.`a_ptr_id`, `b`.`b` FROM `b` WHERE `b`.`a_ptr_id` = 4; args=(4,)
SELECT `a`.`a`, `b`.`a_id` FROM `b` INNER JOIN `a` ON (`b`.`a_ptr_id` = `b`.`id`) WHERE `b`.`a_ptr_id` = 4; args=(4,)
```

How do I generate SINGLE query like select b from b where a_ptr_id = ? using django models?

I want to query database one single time!

答:
It turns out that only 1 query was generated.  The 2nd query was caused because I checked all of this in debug mode. My IDE evaluated the object automatically which led to querying the database with </p>

```<code>SELECT `a`.`a`, `b`.`a_id` FROM `b` INNER JOIN `a` ON (`b`.`a_ptr_id` = `b`.`id`) WHERE `b`.`a_ptr_id` = 4;
</code>```

Body:
Let's Assume I have a parent and a child tables which are implemented via inheritance in django.

models.py

class A(models.Model)
 a = CharField()

class B(A):
 b = CharField()

Now I want to select column b from table B I execute:

B.objects.only('b').get(id=4)

But this statement queries database 2 times:

SELECT `b`.`a_ptr_id`, `b`.`b` FROM `b` WHERE `b`.`a_ptr_id` = 4; args=(4,)
SELECT `a`.`a`, `b`.`a_id` FROM `b` INNER JOIN `a` ON (`b`.`a_ptr_id` = `b`.`id`) WHERE `b`.`a_ptr_id` = 4; args=(4,)

How do I generate SINGLE query like select b from b where a_ptr_id = ? using django models?

I want to query database one single time!

Body:
It turns out that only 1 query was generated.  The 2nd query was caused because I checked all of this in debug mode. My IDE evaluated the object automatically which led to querying the database with

SELECT `a`.`a`, `b`.`a_id` FROM `b` INNER JOIN `a` ON (`b`.`a_ptr_id` = `b`.`id`) WHERE `b`.`a_ptr_id` = 4;


问:
Operator that skips the next emission from the source whenever another Observable emits
I have a use case where I need an Observable to skip its next emission whenever another notifier Observable emits.

```<code>source:    |---X---X---X---X---X---X---X---X---X---X--|>
notifier:  |-------------X---------X----------X-------|>
result:    |---X---X---X-------X---X-------X-------X--|>
</code>```

Basically, I want an operator called skipNextWhen that takes in the notifier observable and skips the next emission from the source.

I tried using an implementation that uses the pausable operator (re-implemented using switchMap), but couldn't get it to work.

pausable.ts

```<code>import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/observable/never';
import 'rxjs/add/operator/startWith';

declare module 'rxjs/Observable' {
    interface Observable<T> {
        pausable: typeof pausable;
    }
}

function pausable<T>(notifier: Observable<boolean>): Observable<T> {
    return notifier.startWith(false).switchMap((paused) => {
        if (paused) {
            return Observable.never();
        } else {
            const source = new Subject();
            this.subscribe(source);
            return source;
        }
    });
}

Observable.prototype.pausable = pausable;
</code>```

skipNextWhen.ts

```<code>import { Observable } from 'rxjs/Observable';
import './pausable';

declare module 'rxjs/Observable' {
    interface Observable<T> {
        skipNextWhen: typeof skipNextWhen;
    }
}

function skipNextWhen<T, R>(other: Observable<T>): Observable<R> {
    const notifier = Observable.merge(this.map(() => false),
                                      other.map(() => true));
    return this.pausable(notifier);
}

Observable.prototype.skipNextWhen = skipNextWhen;
</code>```

Is there a more suitable operator that I should consider using instead? The behavior I'm seeing with my current implementation is that the result Observable emits once, and then never again - even if the notifier Observable never emits.

答:
I can think of two solutions to this:

Using .filter(), .do() and a few side-effects.

This is mayne easier to understand solution even though it's not that "Rx" way:

```<code>function skipNextWhen(other) {
    let skipNext = false;

    return this.merge(other.do(() => skipNext = true).filter(() => false))
        .filter(val => {
            const doSkip = skipNext;
            skipNext = false;
            return !doSkip;
        });
}
</code>```

I'm using merge() just to update skipNext, other's value is always ignored.

Using .scan():

This solution is without any state variables and side-effects.

```<code>function skipNextWhen(other) {
    const SKIP = 'skip';

    return this.merge(other.mapTo(SKIP))
        .scan((acc, val) => {
            if (acc === SKIP) {
                return null;
            } else if (val === SKIP) {
                return SKIP;
            } else {
                return val;
            }
        }, [])
        .filter(val => Boolean(val) && val !== SKIP);
}
</code>```

Basically, when SKIP arrives I return it right away because it's going to be passed again in acc parameter by the scan() operator and later ignored by filter().

If I receive a normal value but the previous value was SKIP I ignore it and return just null which is later filter away.

Both solutions give the same result:

```<code>Observable.prototype.skipNextWhen = skipNextWhen;

const source = Observable.range(1, 10)
    .concatMap(val => Observable.of(val).delay(100));

source
    .skipNextWhen(Observable.interval(350))
    .subscribe(console.log);
</code>```

This prints the following:

```<code>1
2
3
5
6
8
9
10
</code>```

Just be aware that you're not in fact creating new operator. You just have a shortcut for an operator chain. This for example doesn't let you unsubscribe from other when the source completes.

Body:
I have a use case where I need an Observable to skip its next emission whenever another notifier Observable emits.

source:    |---X---X---X---X---X---X---X---X---X---X--|>
notifier:  |-------------X---------X----------X-------|>
result:    |---X---X---X-------X---X-------X-------X--|>

Basically, I want an operator called skipNextWhen that takes in the notifier observable and skips the next emission from the source.

I tried using an implementation that uses the pausable operator (re-implemented using switchMap), but couldn't get it to work.

pausable.ts

import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/observable/never';
import 'rxjs/add/operator/startWith';

declare module 'rxjs/Observable' {
    interface Observable<T> {
        pausable: typeof pausable;
    }
}

function pausable<T>(notifier: Observable<boolean>): Observable<T> {
    return notifier.startWith(false).switchMap((paused) => {
        if (paused) {
            return Observable.never();
        } else {
            const source = new Subject();
            this.subscribe(source);
            return source;
        }
    });
}

Observable.prototype.pausable = pausable;

skipNextWhen.ts

import { Observable } from 'rxjs/Observable';
import './pausable';

declare module 'rxjs/Observable' {
    interface Observable<T> {
        skipNextWhen: typeof skipNextWhen;
    }
}

function skipNextWhen<T, R>(other: Observable<T>): Observable<R> {
    const notifier = Observable.merge(this.map(() => false),
                                      other.map(() => true));
    return this.pausable(notifier);
}

Observable.prototype.skipNextWhen = skipNextWhen;

Is there a more suitable operator that I should consider using instead? The behavior I'm seeing with my current implementation is that the result Observable emits once, and then never again - even if the notifier Observable never emits.

Body:
I can think of two solutions to this:

Using .filter(), .do() and a few side-effects.

This is mayne easier to understand solution even though it's not that "Rx" way:

function skipNextWhen(other) {
    let skipNext = false;

    return this.merge(other.do(() => skipNext = true).filter(() => false))
        .filter(val => {
            const doSkip = skipNext;
            skipNext = false;
            return !doSkip;
        });
}

I'm using merge() just to update skipNext, other's value is always ignored.

Using .scan():

This solution is without any state variables and side-effects.

function skipNextWhen(other) {
    const SKIP = 'skip';

    return this.merge(other.mapTo(SKIP))
        .scan((acc, val) => {
            if (acc === SKIP) {
                return null;
            } else if (val === SKIP) {
                return SKIP;
            } else {
                return val;
            }
        }, [])
        .filter(val => Boolean(val) && val !== SKIP);
}

Basically, when SKIP arrives I return it right away because it's going to be passed again in acc parameter by the scan() operator and later ignored by filter().

If I receive a normal value but the previous value was SKIP I ignore it and return just null which is later filter away.

Both solutions give the same result:

Observable.prototype.skipNextWhen = skipNextWhen;

const source = Observable.range(1, 10)
    .concatMap(val => Observable.of(val).delay(100));

source
    .skipNextWhen(Observable.interval(350))
    .subscribe(console.log);

This prints the following:

1
2
3
5
6
8
9
10

Just be aware that you're not in fact creating new operator. You just have a shortcut for an operator chain. This for example doesn't let you unsubscribe from other when the source completes.


问:
core-0.13.0.job.jar is missing and i need it
I need to use this core folder in my example

hadoop jar $MAHOUT_HOME/core/target/mahout-core-xyz.job.jar

org.apache.mahout.classifier.df.tools.Describe

-p /user/hue/KDDTrain/KDDTrain+_20Percent.arff -f /user/hue/KDDTrain/KDDTrain+.info -d N 3 C 2 N C 4 N C 8 N 2 C 19 N L
but i have Mahout-0.13.0 and there is no core folder. Can any one help me please?

答:
There is no mahout-core-xyz.jar in Mahout 0.13.0. As of Mahout 0.10.0 This module (core) and it's corresponding jar (mahout-core-xyz.jar) has been renamed to Map Reduce Legacy and the jar: mahout-mr-0.13.x.jar.

As well while this code  is no longer supported and having been deprecated in 2014.


问:
Springboot and Transaction
I have one method that have a lot of access in my DB (saves something, find another things, update and more)  It`s possible to log how transaction each process are using and trace if that connection have ben being closed or not?
My DB are Postgresql</p>

答:
I'm assuming you are using @Transactional — or any of its "flavors".

Let's also say you are using Log4J 1.x (.properties configuration), you can place this line:

```<code>log4j.logger.org.springframework.transaction = DEBUG
</code>```

...for the appropriate location/appender.

This will log everything that logs out debug statements within that package level (and "onwards").

Similarly you can configure Log4J 2.x, Logback, etc.; the point is to configure an appender for the org.springframework.transaction package.

Title: Springboot and Transaction

Body:
I'm assuming you are using @Transactional — or any of its "flavors".

Let's also say you are using Log4J 1.x (.properties configuration), you can place this line:

log4j.logger.org.springframework.transaction = DEBUG

...for the appropriate location/appender.

This will log everything that logs out debug statements within that package level (and "onwards").

Similarly you can configure Log4J 2.x, Logback, etc.; the point is to configure an appender for the org.springframework.transaction package.


问:
how does GitHub support oembed?
how does GitHub support oembed?

According to this old gist
https://gist.github.com/skabber/54099

```<code>// URL scheme: http://gist.github.com/*
// API endpoint: http://gist.github.com/services/oembed/
// Example call: http://gist.github.com/services/oembed/?url=http%3A//gist.github.com/54099
</code>```

But that unfortunately does not work. (I get http 404)

Now I know GitHub allows oembed because I can embed snippets in articles on  medium.com

can somebody show me the URLs that I need to access GitHub Oembed services ?

p.s.
Just to help: had I asked the question for Flick instead of GitHub this URL would have been just the correct answer:
http://www.flickr.com/services/oembed/?format=json&url=http%3A//www.flickr.com/photos/bees/2341623661/

p.s. II
if somebody wonders why I am after this, it's because I want to see the JSON response provided by GitHub

答:
GitHub does not provide oEmbed support for it's url. You can test with this oEmbed tester which tells you that the site is not oEmbed supported.

Medium doesn't unfurls its content with the help of oEmbed meta. It just takes the snapshot of the content (which would be displayed when opening the same url content in browser). Try the same by embedding a google doc content. You could get a clear picture of what medium does.

Medium uses embed.ly which is a api provider which provides embed content which could be easily added to your site.

Title: how does GitHub support oembed?

Body:
how does GitHub support oembed?

According to this old gist
https://gist.github.com/skabber/54099

// URL scheme: http://gist.github.com/*
// API endpoint: http://gist.github.com/services/oembed/
// Example call: http://gist.github.com/services/oembed/?url=http%3A//gist.github.com/54099

But that unfortunately does not work. (I get http 404)

Now I know GitHub allows oembed because I can embed snippets in articles on  medium.com

can somebody show me the URLs that I need to access GitHub Oembed services ?

p.s.
Just to help: had I asked the question for Flick instead of GitHub this URL would have been just the correct answer:
http://www.flickr.com/services/oembed/?format=json&url=http%3A//www.flickr.com/photos/bees/2341623661/

p.s. II
if somebody wonders why I am after this, it's because I want to see the JSON response provided by GitHub


问:
Android TV Application
I have an android application for phones and tablets. Now I want to create suitable TV application of my app with leanback support library widgets and I read different tutorials for TV apps.
Now I want to know if I should add new package for tv to my current project or create new project and release different apk for tv? which one is better? does adding package to my current project have effects on apk size?</p>

答:
From Android TV best practice :

In most cases, we recommend delivering your TV experience as part of
  your existing app for phones, tablets, and other devices, using the
  same package name and store listing. This approach lets users upgrade
  to your TV experience seamlessly and also lets you take advantage of
  the reviews and ratings you’ve earned in your app for phones and
  tablets.

You can use a single apk :

You can bundle your TV intents, leanback library, and TV-specific code
  and resources as part of a single APK solution for all supported
  devices

Or you can use multiple apk support :

If necessary, you can use Multiple APK Support to deliver a
  custom binary to Android TV devices under the same package name and
  store listing that you use for phones and tablets.

Title: Android TV Application


问:
Scrolling through Visual Studio Intellisense list without mouse or keyboard arrows
I'm a heavy user of Intellisense in Visual Studio. I'm also a "keep your hands on the keyboard" and "keep them in home position" aficionado, so I'm always looking for ways to keep my hands centered on the ASDF   JKL; keys as much as possible.

Whenever the Intellisense list pops up in Visual Studio, if there are many words in the list that start with the same letters as the word I'm trying to select, typing the first few letters to hone in on my selection doesn't help, since the list won't jump down to my preferred selection until I type enough characters to finally reach the first unique character in the word. It's usually faster to take my right hand off the JKL; keys and reach for the up/down arrow keys to manually scroll through the list.

I'd rather keep my hands centered in home position, and ideally use something like the J and K keys to move up and down in the Intellisense list (similar to how J and K move up and down in Vim...and especially since I use VsVim inside Visual Studio).

The MSDN Intellisense documentation only lists the up/down arrow keys and scrolling (mouse wheel, PgUp/PgDn keys, etc.) as options for doing this:

So here are my questions (in order of preference):

Are there any existing keyboard shortcuts in Visual Studio that allow keeping your hands in home position while scrolling the Intellisense list?

Is there any way to custom map keyboard keys (such as J and K) to do the up/down scrolling in the Intellisense list?

Are there any plugins that enable this functionality?

Is there any other way to accomplish this?

答:
I was looking to accomplish the same that Doktorn suggested in Visual Studio Code, so I will put the solution here just in case someone needs the same.

You have to add two new Key bindings in keybindings.json:

```<code>[
    { "key": "alt+j",                    "command": "selectPrevSuggestion",
                                         "when": "suggestWidgetVisible" },
    { "key": "alt+k",                    "command": "selectNextSuggestion",
                                         "when": "suggestWidgetVisible" }
]
</code>```

Body:
I was looking to accomplish the same that Doktorn suggested in Visual Studio Code, so I will put the solution here just in case someone needs the same.

You have to add two new Key bindings in keybindings.json:

[
    { "key": "alt+j",                    "command": "selectPrevSuggestion",
                                         "when": "suggestWidgetVisible" },
    { "key": "alt+k",                    "command": "selectNextSuggestion",
                                         "when": "suggestWidgetVisible" }
]


问:
How to prove that the boolean inequality of a type with itself is uninhabited in Idris?
I was wondering how to prove that (So (not (y == y))) is an instance of Uninhabited, and I'm not sure how to go about it. Is it provable in Idris, or is not provable due to the possibility of a weird Eq implementation for y?

答:
The Eq interface does not require an implementation to follow the normal laws of equality. But, we can define an extended LawfulEq interface which does:

```<code>%default total

is_reflexive : (t -> t -> Bool) -> Type
is_reflexive {t} rel = (x : t) -> rel x x = True

is_symmetric : (t -> t -> Bool) -> Type
is_symmetric {t} rel = (x : t) -> (y : t) -> rel x y = rel y x

is_transitive : (t -> t -> Bool) -> Type
is_transitive {t} rel = (x : t) -> (y : t) -> (z : t) -> rel x y = True -> rel x z = rel y z

interface Eq t => LawfulEq t where
  eq_is_reflexive : is_reflexive {t} (==)
  eq_is_symmetric : is_symmetric {t} (==)
  eq_is_transitive : is_transitive {t} (==)
</code>```

The result asked for in the question can be proved for type Bool:

```<code>so_false_is_void : So False -> Void
so_false_is_void Oh impossible

so_not_y_eq_y_is_void : (y : Bool) -> So (not (y == y)) -> Void
so_not_y_eq_y_is_void False = so_false_is_void
so_not_y_eq_y_is_void True = so_false_is_void
</code>```

The result can be proved not true for the following Weird type:

```<code>data Weird = W

Eq Weird where
  W == W = False

weird_so_not_y_eq_y : (y : Weird) -> So (not (y == y))
weird_so_not_y_eq_y W = Oh
</code>```

The Weird (==) can be shown to be not reflexive, so an implementation of LawfulEq Weird is not possible:

```<code>weird_eq_not_reflexive : is_reflexive {t=Weird} (==) -> Void
weird_eq_not_reflexive is_reflexive_eq =
  let w_eq_w_is_true = is_reflexive_eq W in
    trueNotFalse $ trans (sym w_eq_w_is_true) (the (W == W = False) Refl)
</code>```

Body:
The Eq interface does not require an implementation to follow the normal laws of equality. But, we can define an extended LawfulEq interface which does:

%default total

is_reflexive : (t -> t -> Bool) -> Type
is_reflexive {t} rel = (x : t) -> rel x x = True

is_symmetric : (t -> t -> Bool) -> Type
is_symmetric {t} rel = (x : t) -> (y : t) -> rel x y = rel y x

is_transitive : (t -> t -> Bool) -> Type
is_transitive {t} rel = (x : t) -> (y : t) -> (z : t) -> rel x y = True -> rel x z = rel y z

interface Eq t => LawfulEq t where
  eq_is_reflexive : is_reflexive {t} (==)
  eq_is_symmetric : is_symmetric {t} (==)
  eq_is_transitive : is_transitive {t} (==)

The result asked for in the question can be proved for type Bool:

so_false_is_void : So False -> Void
so_false_is_void Oh impossible

so_not_y_eq_y_is_void : (y : Bool) -> So (not (y == y)) -> Void
so_not_y_eq_y_is_void False = so_false_is_void
so_not_y_eq_y_is_void True = so_false_is_void

The result can be proved not true for the following Weird type:

data Weird = W

Eq Weird where
  W == W = False

weird_so_not_y_eq_y : (y : Weird) -> So (not (y == y))
weird_so_not_y_eq_y W = Oh

The Weird (==) can be shown to be not reflexive, so an implementation of LawfulEq Weird is not possible:

weird_eq_not_reflexive : is_reflexive {t=Weird} (==) -> Void
weird_eq_not_reflexive is_reflexive_eq =
  let w_eq_w_is_true = is_reflexive_eq W in
    trueNotFalse $ trans (sym w_eq_w_is_true) (the (W == W = False) Refl)


问:
What do promise generators return?
I'm working with a modified version of this example for writing a helper for vaguely async/await syntax. Here's the code in TypeScript:

```<code>export class Async {
  public static do(makeGenerator) {
    let generator = makeGenerator.apply(this, arguments);

    try {
      return handle(generator.next());
    } catch (error) {
      return Promise.reject(error);
    }

    function handle(result) {
      if (result.done) {
        return Promise.resolve(result.value);
      }

      return Promise.resolve(result.value)
        .then(nextResult => {
          return handle(generator.next(nextResult));
        })
        .catch(error => {
          return handle(generator.throw(error));
        });
    }
  }
}
</code>```

The usage is meant to be like:

```<code>Async.do(function* () {
  let someResult = yield somePromise();
  // Don't continue until the promise resolves
  someDependentOperation(someResult);
});
</code>```

That all works just fine.

Where it falls down is if I try to return Async.do(...). I'd thought from inspecting the code that this should return a Promise object, but this apparently isn't the case. Async.do returns immediately, and the result is undefined. Is there something I'm missing about the way generators work?

答: I can confirm that this was a problem elsewhere in my code (I'd missed a return off one of my intermediate functions that should have returned a Promise).

Title: What do promise generators return?

Body:
I'm working with a modified version of this example for writing a helper for vaguely async/await syntax. Here's the code in TypeScript:

export class Async {
  public static do(makeGenerator) {
    let generator = makeGenerator.apply(this, arguments);

    try {
      return handle(generator.next());
    } catch (error) {
      return Promise.reject(error);
    }

    function handle(result) {
      if (result.done) {
        return Promise.resolve(result.value);
      }

      return Promise.resolve(result.value)
        .then(nextResult => {
          return handle(generator.next(nextResult));
        })
        .catch(error => {
          return handle(generator.throw(error));
        });
    }
  }
}

The usage is meant to be like:

Async.do(function* () {
  let someResult = yield somePromise();
  // Don't continue until the promise resolves
  someDependentOperation(someResult);
});

That all works just fine.

Where it falls down is if I try to return Async.do(...). I'd thought from inspecting the code that this should return a Promise object, but this apparently isn't the case. Async.do returns immediately, and the result is undefined. Is there something I'm missing about the way generators work?


问:
Delete data from Cassandra with part of the partition key
Let's say that I have the following table in Cassandra:

```<code>customer_bought_product (
    store_id uuid,
    product_id text,
    order_time timestamp,
    email text,
    first_name text,
    last_name text,
    PRIMARY KEY ((store_id, product_id), order_time, email)
</code>```

The partition keys are store_id and order_id and it is used in order to store time series data.

The data does not have a TTL, as it should be accessible at all times.

In some cases we may require to delete all of the data for a given store_id.
What is the best practice to do it?

So far I have thought of the following solutions:

Write a program, that will select all of the data from the table and delete the records with the given store_id. - The downside is that this will take more and more time as we insert more data in the table.

Leave the data in the table. - The only problem with doing this, is that we will have useless data.

Store the table name with the available partition keys in a different table, that can be queried by store_id, get the keys from it and create a delete statement for each or those keys. - I do not like this concept, because I have to maintain the records.

Has anyone encountered this problem? What is the best practice to clear unused records from Cassandra (excluding TTL)?

答:
Create a materialized view to store the product_ids that belong to a corresponding store_ids. This way you can query the MV for a given store_id and then delete the corresponding rows from the main table. This way additional application code could be avoided to maintain two different tables.</p>

```<code>create materialized view mv_customer_bought_product
as select product_id, store_id, order_time, email
from customer_bought_product
where order_time is not null
and email is not null
and product_id is not null
and store_id is not null
primary key (store_id, product_id, order_time, email) ;
</code>```

Body:
Let's say that I have the following table in Cassandra:

customer_bought_product (
    store_id uuid,
    product_id text,
    order_time timestamp,
    email text,
    first_name text,
    last_name text,
    PRIMARY KEY ((store_id, product_id), order_time, email)

The partition keys are store_id and order_id and it is used in order to store time series data.

The data does not have a TTL, as it should be accessible at all times.

In some cases we may require to delete all of the data for a given store_id.
What is the best practice to do it?

So far I have thought of the following solutions:

Write a program, that will select all of the data from the table and delete the records with the given store_id. - The downside is that this will take more and more time as we insert more data in the table.

Leave the data in the table. - The only problem with doing this, is that we will have useless data.

Store the table name with the available partition keys in a different table, that can be queried by store_id, get the keys from it and create a delete statement for each or those keys. - I do not like this concept, because I have to maintain the records.

Has anyone encountered this problem? What is the best practice to clear unused records from Cassandra (excluding TTL)?

Body:
Create a materialized view to store the product_ids that belong to a corresponding store_ids. This way you can query the MV for a given store_id and then delete the corresponding rows from the main table. This way additional application code could be avoided to maintain two different tables.

create materialized view mv_customer_bought_product
as select product_id, store_id, order_time, email
from customer_bought_product
where order_time is not null
and email is not null
and product_id is not null
and store_id is not null
primary key (store_id, product_id, order_time, email) ;


问:
Ecto funny behavior in datetime?
I just found a funny behavior on Ecto when creating inserted_at and updated_at.

Before passed midnight, my app behaves normal.. but after passed midnight it behaves like below log

```<code>[info] >>> RUNTIME DATETIME {{2017, 7, 4}, {2, 38, 43}}
[info] >>> CHAT NEW = %Portal.DailyChat{__meta__:
#Ecto.Schema.Metadata<:loaded, "daily_chats">, id: 17, inserted_at: ~N[2017-07-03 19:38:43.315000], messages:
 "{\"chats\":[{\"time\":\"2:38:43\",\"message\":\"Test\",\"from\":\"bi***@gmail.com\"}]}", read: true, updated_at: ~N[2017-07-03 19:38:43.315000], user_a: %Po
rtal.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">, id: 3, inserted_at: ~N[2017-06-16 20:08:05.000000], name: "Indra", password: nil, password_
hash: "AF41E68E1309FA29A5044CBDC36B90A3821D8807E68C7675A6C495112BC8A55F", updated_at: ~N[2017-06-16 20:08:05.000000], username: "bi****@gmail.com"}, user_a_id:
 3, user_b: %Portal.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">, id: 1, inserted_at: ~N[2017-06-16 16:18:25.000000], name: "Bromo", passw
ord: nil, password_hash: "AF41E68E1309FA29A5044CBDC36B90A3821D8807E68C7675A6C495112BC8A55F", updated_at: ~N[2017-06-16 16:18:25.000000], username: "bro***@gm
ail.com"}, user_b_id: 1}
</code>```

Value for >>> RUNTIME DATETIME is generated using :calendar.local_time, which produces a correct time.

For >>> CHAT NEW values is what Ecto generates after persisting data to DB, both updated_at and inserted_at are wrong time!

Does anybody knows how to fixed this issue?

Thanks

答:
The times aren't wrong, they're in UTC while :calendar.local_time returns the time in your system's timezone. Since there's a 7 hour difference, you probably live in one of these places.

If you run :calendar.universal_time, you should get the current UTC time, which will match the one Ecto used.

You can also convert the universal time to local time using :calendar.universal_time_to_local_time/1 and the reverse using :calendar.local_time_to_universal_time/1.

Title: Ecto funny behavior in datetime?

Body:
I just found a funny behavior on Ecto when creating inserted_at and updated_at.

Before passed midnight, my app behaves normal.. but after passed midnight it behaves like below log

[info] >>> RUNTIME DATETIME {{2017, 7, 4}, {2, 38, 43}}
[info] >>> CHAT NEW = %Portal.DailyChat{__meta__:
#Ecto.Schema.Metadata<:loaded, "daily_chats">, id: 17, inserted_at: ~N[2017-07-03 19:38:43.315000], messages:
 "{\"chats\":[{\"time\":\"2:38:43\",\"message\":\"Test\",\"from\":\"bi***@gmail.com\"}]}", read: true, updated_at: ~N[2017-07-03 19:38:43.315000], user_a: %Po
rtal.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">, id: 3, inserted_at: ~N[2017-06-16 20:08:05.000000], name: "Indra", password: nil, password_
hash: "AF41E68E1309FA29A5044CBDC36B90A3821D8807E68C7675A6C495112BC8A55F", updated_at: ~N[2017-06-16 20:08:05.000000], username: "bi****@gmail.com"}, user_a_id:
 3, user_b: %Portal.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">, id: 1, inserted_at: ~N[2017-06-16 16:18:25.000000], name: "Bromo", passw
ord: nil, password_hash: "AF41E68E1309FA29A5044CBDC36B90A3821D8807E68C7675A6C495112BC8A55F", updated_at: ~N[2017-06-16 16:18:25.000000], username: "bro***@gm
ail.com"}, user_b_id: 1}

Value for >>> RUNTIME DATETIME is generated using :calendar.local_time, which produces a correct time.

For >>> CHAT NEW values is what Ecto generates after persisting data to DB, both updated_at and inserted_at are wrong time!

Does anybody knows how to fixed this issue?

Thanks


问:
Passing a input value from one method to another
The following code is for a lab for the java course I'm taking for which just started the chapter on parameters and objects. I've hit a major choke-point past which I can't get past.

The issue I'm having is that I need to get the input assigned to destinationAmount, in the method GetAmountOfDestinations, to the method GetItinerary so I can use it in the for loop. I can't have any code within the main method other than the calls to the other methods. I cannot change the nature of the methods as the instructions say they must be made in a certain way.

Just how would I get the input to the other method? Do I create a third method to route the value through? I've looked for hours on this website and youtube and I haven't seen anything like this situation. I'd appreciate the help.

```<code>import java.util.*;
public class TripPlanner
{
  public static final Scanner CONSOLE = new Scanner ( System.in );
  public static void main(String [] args)
  {
    GetAmountOfDestinations();
    GetItinerary();
  }
  public static int GetAmountOfDestinations()
  {
    System.out.println( "Please enter the amount of destinations." );
    int destinationAmount = CONSOLE.nextInt();
    System.out.println( "You entered " + destinationAmount + "." );
  }
  public static void GetItinerary()
  {

    System.out.println( "Your starting airport is SAT." );

    int amountOfDestinations = ??????;
    System.out.println(amountOfDestinations);

    double currentDestinationLatitude = Airports.getAirportLatitude( "SAT" );
    double currentDestinationLongitude = Airports.getAirportLongitude( "SAT" );
    for( int x = 0; x <  amountOfDestinations; x = x + 1 )
    {
      System.out.println( "Please enter the next destination." );
      String nextDestination = CONSOLE.next();

      double nextDestinationLatitude = Airports.getAirportLatitude( nextDestination );
      double nextDestinationLongitude = Airports.getAirportLongitude( nextDestination );

      System.out.println( nextDestinationLatitude + " " + nextDestinationLongitude );
    }
  }
}
</code>```

答:
You need to add a return on your GetAmountOfDestinations then call the method when you're trying t get the amountOfDestinations:

```<code>public static int GetAmountOfDestinations()
  {
    System.out.println( "Please enter the amount of destinations." );
    int destinationAmount = CONSOLE.nextInt();
    System.out.println( "You entered " + destinationAmount + "." );
    return destinationAmount;
  }
</code>```

In the GetItinerary you assign the value:

```<code>int amountOfDestinations = GetAmountOfDestinations();
</code>```

Body:
The following code is for a lab for the java course I'm taking for which just started the chapter on parameters and objects. I've hit a major choke-point past which I can't get past.

The issue I'm having is that I need to get the input assigned to destinationAmount, in the method GetAmountOfDestinations, to the method GetItinerary so I can use it in the for loop. I can't have any code within the main method other than the calls to the other methods. I cannot change the nature of the methods as the instructions say they must be made in a certain way.

Just how would I get the input to the other method? Do I create a third method to route the value through? I've looked for hours on this website and youtube and I haven't seen anything like this situation. I'd appreciate the help.

import java.util.*;
public class TripPlanner
{
  public static final Scanner CONSOLE = new Scanner ( System.in );
  public static void main(String [] args)
  {
    GetAmountOfDestinations();
    GetItinerary();
  }
  public static int GetAmountOfDestinations()
  {
    System.out.println( "Please enter the amount of destinations." );
    int destinationAmount = CONSOLE.nextInt();
    System.out.println( "You entered " + destinationAmount + "." );
  }
  public static void GetItinerary()
  {

    System.out.println( "Your starting airport is SAT." );

    int amountOfDestinations = ??????;
    System.out.println(amountOfDestinations);

    double currentDestinationLatitude = Airports.getAirportLatitude( "SAT" );
    double currentDestinationLongitude = Airports.getAirportLongitude( "SAT" );
    for( int x = 0; x <  amountOfDestinations; x = x + 1 )
    {
      System.out.println( "Please enter the next destination." );
      String nextDestination = CONSOLE.next();

      double nextDestinationLatitude = Airports.getAirportLatitude( nextDestination );
      double nextDestinationLongitude = Airports.getAirportLongitude( nextDestination );

      System.out.println( nextDestinationLatitude + " " + nextDestinationLongitude );
    }
  }
}

Body:
You need to add a return on your GetAmountOfDestinations then call the method when you're trying t get the amountOfDestinations:

public static int GetAmountOfDestinations()
  {
    System.out.println( "Please enter the amount of destinations." );
    int destinationAmount = CONSOLE.nextInt();
    System.out.println( "You entered " + destinationAmount + "." );
    return destinationAmount;
  }

In the GetItinerary you assign the value:

int amountOfDestinations = GetAmountOfDestinations();


问:
session_write_close symfony 2 and 3
php/symfony experts!

This question especially for you.

try this code example

```<code>/**
 * @Route("/your-route", name="your-route")
 */
public function indexAction()
{

    $this->get('session')->save();

    sleep(10);

    return $this->render('template.html.twig');
}
</code>```

requests are performing in parallel in different browsers as expected, but why sequentially in the same browser?

答:
Different browsers start different sessions, so there is no session lock, but different tabs of one browser try to open the same session.

That's why you will have session lock as default behavior.

When you do $session->save() -- you call session_write_close() function and save your session in its file. And by default Symfony redefines session.save_path value from your php.ini.

So it seems you need to check permissions on path "/your_project_path/app/../var/sessions/dev"
See this issue: Warning: session_write_close(): Failed to write session data.... #17845.

Title: session_write_close symfony 2 and 3

Body:
php/symfony experts!

This question especially for you.

try this code example

/**
 * @Route("/your-route", name="your-route")
 */
public function indexAction()
{

    $this->get('session')->save();

    sleep(10);

    return $this->render('template.html.twig');
}

requests are performing in parallel in different browsers as expected, but why sequentially in the same browser?


问:
React Native - Async storage information is extracted after componentWillMount()
I am storing if a checkbox is checked or not using AsyncStorage. When I reload the app, I see from logs that inside the asynchronous variable the correct information is stored. But, it is loaded after componentWillMount. Because of that, the checkbox does not appear checked, as it should be.

I think a good workaround will be to change the checkbox properties inside the asynchronous function. Do you think that would be a good solution? Do you have other suggestions for showing the correct checkbox value?

My code:

```<code>constructor(props) {
    super(props)
    this.state = {isChecked: false}
    this.switchStatus = this.switchStatus.bind(this)
  }

  async getCache(key) {
    try {
      const status = await AsyncStorage.getItem(key);
      if (status == null)
        status = false
      console.log("my async status is " + status)
      return status
    } catch(error) {
      console.log("error", e)
    }
  }

  componentWillMount(){
    // key string depends on the object selected to be checked
    const key = "status_" + this.props.data.id.toString()
    this.getCache = this.getCache.bind(this)
    this.setState({isChecked: (this.getCache(key) == 'true')})
    console.log("my state is" + this.state.isChecked)
  }

  switchStatus () {
    const newStatus = this.state.isChecked == false ? true : false
    AsyncStorage.setItem("status_" + this.props.data.id.toString(), newStatus.toString());
    console.log("hi my status is " + newStatus)
    this.setState({isChecked: newStatus})
  }

  render({ data, onPress} = this.props) {
    const {id, title, checked} = data
    return (
      <ListItem button onPress={onPress}>
        <CheckBox
          style={{padding: 1}}
          onPress={(this.switchStatus}
          checked={this.state.isChecked}
        />
        <Body>
          <Text>{title}</Text>
        </Body>
        <Right>
          <Icon name="arrow-forward" />
        </Right>
      </ListItem>
    )
  }
</code>```

There is no difference if I put everything in componentWillMount in the constructor.

答:
you make use of the async - await, but you are not waiting for your method in componentWillMount(). Try this:</p>

```<code>componentWillMount(){
    // key string depends on the object selected to be checked
    const key = "status_" + this.props.data.id.toString()
    this.getCache =  await this.getCache.bind(this)   // <-- Missed await
    this.setState({isChecked: (this.getCache(key) == 'true')})
    console.log("my state is" + this.state.isChecked)
  }
</code>```

Body:
I am storing if a checkbox is checked or not using AsyncStorage. When I reload the app, I see from logs that inside the asynchronous variable the correct information is stored. But, it is loaded after componentWillMount. Because of that, the checkbox does not appear checked, as it should be.

I think a good workaround will be to change the checkbox properties inside the asynchronous function. Do you think that would be a good solution? Do you have other suggestions for showing the correct checkbox value?

My code:

constructor(props) {
    super(props)
    this.state = {isChecked: false}
    this.switchStatus = this.switchStatus.bind(this)
  }

  async getCache(key) {
    try {
      const status = await AsyncStorage.getItem(key);
      if (status == null)
        status = false
      console.log("my async status is " + status)
      return status
    } catch(error) {
      console.log("error", e)
    }
  }

  componentWillMount(){
    // key string depends on the object selected to be checked
    const key = "status_" + this.props.data.id.toString()
    this.getCache = this.getCache.bind(this)
    this.setState({isChecked: (this.getCache(key) == 'true')})
    console.log("my state is" + this.state.isChecked)
  }

  switchStatus () {
    const newStatus = this.state.isChecked == false ? true : false
    AsyncStorage.setItem("status_" + this.props.data.id.toString(), newStatus.toString());
    console.log("hi my status is " + newStatus)
    this.setState({isChecked: newStatus})
  }

  render({ data, onPress} = this.props) {
    const {id, title, checked} = data
    return (
      <ListItem button onPress={onPress}>
        <CheckBox
          style={{padding: 1}}
          onPress={(this.switchStatus}
          checked={this.state.isChecked}
        />

          <Text>{title}</Text>

        <Right>
          <Icon name="arrow-forward" />
        </Right>
      </ListItem>
    )
  }

There is no difference if I put everything in componentWillMount in the constructor.

Body:
you make use of the async - await, but you are not waiting for your method in componentWillMount(). Try this:

componentWillMount(){
    // key string depends on the object selected to be checked
    const key = "status_" + this.props.data.id.toString()
    this.getCache =  await this.getCache.bind(this)   // <-- Missed await
    this.setState({isChecked: (this.getCache(key) == 'true')})
    console.log("my state is" + this.state.isChecked)
  }


问:
oembed with multiple urls
Is there a possibility to access oembed or a similar service like noembed with multiple urls like:

```<code>http://noembed.com/embed?url=[url1],[url2]
</code>```

Thanks for your response

答:
The answer is NO.

oEmbed spec does not allow such options

Title: oembed with multiple urls

Body:
Is there a possibility to access oembed or a similar service like noembed with multiple urls like:

http://noembed.com/embed?url=[url1],[url2]

Thanks for your response


问:
Typical network socket timeout
I'm interested to know, what is the typical network socket timeout value, used in production today.

I'm currently using 30 seconds in our Java application, but would like to hear what other using, especially for Internet communications.

Thanks.

答:
There is no such thing as a "typical" socket timeout.  Rather you should chose the timeout(s) according to the application requirements.  Issues such as:

Is there a user waiting for the response?

Is a timeout a likely event?

Does setting a "too long" timeout tie down lots of resources, or delay processing?

Does setting a "too short" timeout result in wasted processing when waiting a bit longer would have given results?

Is there a keep-alive mechanism ... so that you can distinguish between (say) network failure and the remote server taking a long time?

The best strategy is probably to pick some intuitively sensible values, and then tune them.

Title: Typical network socket timeout

ContentLicense: CC BY-SA 4.0


问:
Spring Secutiry retrieve Principal Object
I need to retrieve exactly Principal Object in non default Spring chain (not in controller with Principle injection). I'm implementing some interceptor with my spring-websocket and client to set user Principal from oauth header token value.

Main problem now is that I can't just directrly fetch Principal object instead I'm getting username String.

I've created this method but it returns String (getting ClassCastException):

```<code>public Principal setApplicationAuthentication(String username) {
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    Authentication auth = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
            userDetails.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(auth);
    return (Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
</code>```

答:
I've figured it out with invoking only this method:

```<code>SecurityContextHolder.getContext().getAuthentication()
</code>```

Authentication is already Principal (superclass) with class hierarchy

Body:
I need to retrieve exactly Principal Object in non default Spring chain (not in controller with Principle injection). I'm implementing some interceptor with my spring-websocket and client to set user Principal from oauth header token value.

Main problem now is that I can't just directrly fetch Principal object instead I'm getting username String.

I've created this method but it returns String (getting ClassCastException):

public Principal setApplicationAuthentication(String username) {
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    Authentication auth = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
            userDetails.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(auth);
    return (Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}

Body:
I've figured it out with invoking only this method:

SecurityContextHolder.getContext().getAuthentication()

Authentication is already Principal (superclass) with class hierarchy


答:
First, note that GetAmountOfDestinations() is declared to return an int. You need to add a return statement to this method in order for it to compile.

Second, you will then need to assign the returned value to a variable. There are two different ways to do this:

Assign the returned value to a variable in main() and then pass it to GetItinerary():

```<code>public static void main(String [] args)
{
  int dest = GetAmountOfDestinations();
  GetItinerary(dest);
}
</code>```

This requires you to change GetItinerary() to accept an int parameter, rather than have a local variable:

```<code>public static void GetItinerary(int amountOfDestinations)
</code>```

Now remove the local variable declaration.

Another solution is to call GetAmountOfDestinations() directly from GetItinerary():

int amountOfDestinations = GetAmountOfDestinations();

Then remove the call to GetAmountOfDestinations() from main().

Title: Passing a input value from one method to another

Body:
First, note that GetAmountOfDestinations() is declared to return an int. You need to add a return statement to this method in order for it to compile.

Second, you will then need to assign the returned value to a variable. There are two different ways to do this:

Assign the returned value to a variable in main() and then pass it to GetItinerary():

public static void main(String [] args)
{
  int dest = GetAmountOfDestinations();
  GetItinerary(dest);
}

This requires you to change GetItinerary() to accept an int parameter, rather than have a local variable:

public static void GetItinerary(int amountOfDestinations)

Now remove the local variable declaration.

Another solution is to call GetAmountOfDestinations() directly from GetItinerary():

int amountOfDestinations = GetAmountOfDestinations();

Then remove the call to GetAmountOfDestinations() from main().


问:
Angular 2 - Viewing a Single Record of Data
I am new to Angular so I am having trouble figuring out how to form my questions for what I am trying to accomplish, but here it goes.

I have a component that is fetching a single user record from a service. I then want to display those user details on my UI. In other parts of my code, they have always been multiple records so I have used *ngFor and looped over the array of data. However, since this is just a single result, I am not too sure how to accomplish this.

Component:

```<code>import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { UserRecord } from '../shared/user-record.interface';
import { UserService } from '../shared/user.service';

@Component({
    selector: 'app-view-record',
    templateUrl: './view-record.component.html',
    styleUrls: ['./view-record.component.css']
})
export class ViewRecordComponent implements OnInit {

    private record: UserRecord[];
    private errorMessage: any = '';
    private loaded = false;
    private RecordID: number; // User ID of who we are looking at

    constructor(private _crudService: UserService,
        private activatedRoute: ActivatedRoute) { }

    ngOnInit() {

        // Get the userID from the activated route
        this.activatedRoute.params.subscribe((params: Params) => {
            this.RecordID = params['id'];
        });

        // Call our service and pass the userID
        this._crudService.getRecord(this.RecordID)
            .then(res => {
                this.record = this._crudService.record;
                return this._crudService.getRecord(this.RecordID);
            })
            .then(res => {
                console.log(this.record)
                this.loaded = true;
            })
            .catch(err => { console.error(err); });
    }

}
</code>```

Service:

```<code>getRecord(userID: number) {

        const headers: Headers = new Headers({
            "Authorization": this._frameworkService.getSessionInfo().token
        });
        return new Promise((resolve, rejects) => {
            this._http.post(this.baseUrl + '/fetchRecord', { "userID": userID }, { "headers": headers })
                .map(res => res.json())
                .subscribe((data) => {
                    if (data) {
                        this.record = data;
                    }
                    resolve(true);
                });
        });
    }
</code>```

Interface:

```<code>export interface UserRecord {
    RecordID: number;
    QID: string;
    FavoriteColor?: string;
    FavoriteNumber?: number;
    FavoriteActor?: string;
    MetaInsertUTC: string;
    MetaUpdateUTC: string;
    FirstName: string;
    LastName: string;
    NTID: string;
}
</code>```

Service Result:

```<code>[
   {
      "RecordID":"55",
      "QID":"Q00019204",
      "FavoriteColor":"Blue",
      "FavoriteNumber":"6",
      "FavoriteActor":"Bob",
      "MetaInsertUTC":"2017-06-29 18:47:01.750",
      "MetaUpdateUTC":null,
      "FirstName":"Jim",
      "LastName":"Bobs",
      "NTID":"bobby"
   }
]
</code>```

In my Component HTML, I have tried {{record.FirstName}} but receive the error of ViewRecordComponent.html:16 ERROR TypeError: Cannot read property 'FirstName' of undefined.

Since this isn't a set of data results, I don't see how *ngFor would be applicable in the use case.

I assumed that since my component is storing the data in the record object, I should be able to access that from the UI? The console.log shows all of the correct data points.

How would I reference the users FirstName in my component HTML? Hopefully I'm on the right path at least.

答:
Your response seems to be an array with an object, so record.FirstName doesn't exist, but record[0].FirstName does.

And when it comes to the view, remember to use either the safe navigation operator or *ngIf so that you do not run into undefined issues like mentioned by DeborahK. Observable type error: cannot read property of undefined

Furthermore just some suggestion on how to handle http in Angular... I would do something like the following...

```<code>getRecord(userID: number) {
    const headers: Headers = new Headers({
        "Authorization": this._frameworkService.getSessionInfo().token
    });
    return this._http.post(this.baseUrl + '/fetchRecord', { "userID": userID }, { "headers": headers })
       .toPromise()
       .then(res => res.json()[0]) // get the object only
       .catch(err => { console.error(err); });
}
</code>```

and component:

```<code>this._crudService.getRecord(this.RecordID)
   .then(res => {
       this.record = res;
   });
</code>```

But that's totally up to you :)

Body:
I am new to Angular so I am having trouble figuring out how to form my questions for what I am trying to accomplish, but here it goes.

I have a component that is fetching a single user record from a service. I then want to display those user details on my UI. In other parts of my code, they have always been multiple records so I have used *ngFor and looped over the array of data. However, since this is just a single result, I am not too sure how to accomplish this.

Component:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { UserRecord } from '../shared/user-record.interface';
import { UserService } from '../shared/user.service';

@Component({
    selector: 'app-view-record',
    templateUrl: './view-record.component.html',
    styleUrls: ['./view-record.component.css']
})
export class ViewRecordComponent implements OnInit {

    private record: UserRecord[];
    private errorMessage: any = '';
    private loaded = false;
    private RecordID: number; // User ID of who we are looking at

    constructor(private _crudService: UserService,
        private activatedRoute: ActivatedRoute) { }

    ngOnInit() {

        // Get the userID from the activated route
        this.activatedRoute.params.subscribe((params: Params) => {
            this.RecordID = params['id'];
        });

        // Call our service and pass the userID
        this._crudService.getRecord(this.RecordID)
            .then(res => {
                this.record = this._crudService.record;
                return this._crudService.getRecord(this.RecordID);
            })
            .then(res => {
                console.log(this.record)
                this.loaded = true;
            })
            .catch(err => { console.error(err); });
    }

}

Service:

getRecord(userID: number) {

        const headers: Headers = new Headers({
            "Authorization": this._frameworkService.getSessionInfo().token
        });
        return new Promise((resolve, rejects) => {
            this._http.post(this.baseUrl + '/fetchRecord', { "userID": userID }, { "headers": headers })
                .map(res => res.json())
                .subscribe((data) => {
                    if (data) {
                        this.record = data;
                    }
                    resolve(true);
                });
        });
    }

Interface:

export interface UserRecord {
    RecordID: number;
    QID: string;
    FavoriteColor?: string;
    FavoriteNumber?: number;
    FavoriteActor?: string;
    MetaInsertUTC: string;
    MetaUpdateUTC: string;
    FirstName: string;
    LastName: string;
    NTID: string;
}

Service Result:

[
   {
      "RecordID":"55",
      "QID":"Q00019204",
      "FavoriteColor":"Blue",
      "FavoriteNumber":"6",
      "FavoriteActor":"Bob",
      "MetaInsertUTC":"2017-06-29 18:47:01.750",
      "MetaUpdateUTC":null,
      "FirstName":"Jim",
      "LastName":"Bobs",
      "NTID":"bobby"
   }
]

In my Component HTML, I have tried {{record.FirstName}} but receive the error of ViewRecordComponent.html:16 ERROR TypeError: Cannot read property 'FirstName' of undefined.

Since this isn't a set of data results, I don't see how *ngFor would be applicable in the use case.

I assumed that since my component is storing the data in the record object, I should be able to access that from the UI? The console.log shows all of the correct data points.

How would I reference the users FirstName in my component HTML? Hopefully I'm on the right path at least.

Body:
Your response seems to be an array with an object, so record.FirstName doesn't exist, but record[0].FirstName does.

And when it comes to the view, remember to use either the safe navigation operator or *ngIf so that you do not run into undefined issues like mentioned by DeborahK. Observable type error: cannot read property of undefined

Furthermore just some suggestion on how to handle http in Angular... I would do something like the following...

getRecord(userID: number) {
    const headers: Headers = new Headers({
        "Authorization": this._frameworkService.getSessionInfo().token
    });
    return this._http.post(this.baseUrl + '/fetchRecord', { "userID": userID }, { "headers": headers })
       .toPromise()
       .then(res => res.json()[0]) // get the object only
       .catch(err => { console.error(err); });
}

and component:

this._crudService.getRecord(this.RecordID)
   .then(res => {
       this.record = res;
   });

But that's totally up to you :)


问:
How do I implement long-term single sign-on with Firebase and a custom server?
I have a server-side rendered app that also communicates with Firebase. When a user logs in, the client gets an ID Token from firebase that I then share with my server as described in the documentation. My server stores the ID Token in a cookie, so that the client will include the token in all requests and my server can check whether the user is logged in.

The problem is that when Firebase refreshes the token after an hour, my server can't verify the token id and redirects them to the login page. Then the client loads, gets the refreshed token from Firebase and stores it in the server cookie, after which requests are authenticated correctly by my server again.

I can make the client refresh the token on every request, but the problem still occurs when the user leaves my site and then returns after one hour.

How can I setup my app so that my server will correctly authenticate users after the firebase token expires?

答:
If I understand you correctly, you want to programmatically keep the user "logged in" until he/she either exits the session or logs out - without the token signing him/her out.

I am facing the same problem. I think the best approach is to use Firebase.auth.onAuthStateChanged.

You have that function on the front end client side.

Let's look at the following example:

Suppose the user is on the page www.domain.com/myaccount. He/she is actively on that url. An hour has passed since he/she used the site (and he/she is still actively using it). What you want is to have firebase.auth.onAuthStateChanged in the front end of user side. Once that hour passes, the function is immediately triggered, you can then (inside that function) request a new token from your server and sends it back immediately,  all while the user never knew that the token was switched. (I recommend doing this via AJAX).

I hope this answers your question. If onAuthStateChanged doesnt work with your application for some reason, you can try onIdTokenChanged. See links below.

https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged

https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onIdTokenChanged


问:
How to use Dropbox as Django media files storage?
Is there a clean way of using Dropbox as storage for django media files?. Like you would do with s3boto and AmazonS3 described here: How to set-up a Django project with django-storages and Amazon S3

Thanks

答:
django-storages has a dropbox implementation ready to go, just:

```<code>pip install dropbox django-storages
</code>```

and in your settings file:

```<code>INSTALLED_APPS += (
    'storages',
)

DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage'
</code>```

From: http://django-storages.readthedocs.io/en/latest/backends/dropbox.html

Body:
django-storages has a dropbox implementation ready to go, just:

pip install dropbox django-storages

and in your settings file:

INSTALLED_APPS += (
    'storages',
)

DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage'

From: http://django-storages.readthedocs.io/en/latest/backends/dropbox.html


问:
TortoiseSVN "tree conflict" on file when merging
I have a directory in my trunk (trunk/gray/catalog/web/app_code/), and my branch (branches/125/gray/catalog/web/app_code/). The trunk and branch contain 8 files common to both, but the branch has 20 files not found in trunk. These files were SVN added to the branch. Both directories only contain files as children (no children directories). gray/catalog/web/app_code/ was made in the branch and trunk separately with SVN Add.

When I attempt to Test merge branches/125/gray/catalog/web/app_code/ to trunk/gray/catalog/web/app_code/ using Tortoise SVN all of the common files show tree conflict errors, and the files in branch but not in trunk are not added to trunk.

If I attempt the test merge to/from at the gray/catalog/web/ level then no conflicts are shown. The 8 files which are common are shown as being SVN adds, and the 20 files in branch but not in trunk are not added or mentioned at all.

What might cause this?

答:
Don't know if this is beyond stating the obvious, but most of my tree conflicts stem from having renamed things and SVN gets riled up.

Were these files renamed multiple times? or possibly all copy pasted?

Typically these are highly annoying, but fixable by tricking SVN. Either using a switch command, or creating the files anew.

Resolving tree conflict
Why am I getting tree conflicts in Subversion?


问:
How to Disable UAC for my application
Well , when ever I am trying to run my application as administrator I am getting the following
error, and whether to allow or not.

If I am running the app directly and not as an administrator then this seems to work. Is there Some thing I need to do to get rid of the UAC , no I dont want user to manually change the UAC settings.

Do I need to tweak registry settings only for my programe or any certificate I need to sign with.

答: Your process needs to elevate its privileges. There are couple of articles about this in CodeProject but have a look at this one first.</p>

Title: How to Disable UAC for my application


问:
Client_secret and client_id values for posting to blogger
I'm trying to build an app that posts sentences to Blogger. However I'm stuck at the oAuth part which requires a client ID and client secret. I don't know where to find these values.

The values are required in the following line:

```<code>GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jacksonFactory,
                        CLIENT_ID, CLIENT_SECRET, scopes).setAccessType("online").setApprovalPrompt("auto").build();
</code>```

How do I find the proper CLIENT_ID and CLIENT_SECRET values?

答: All right, I found it. It involves going to https://console.developers.google.com/apis/api/blogger.googleapis.com/ and then I can create tokens by clicking on the left hand menu.</p>

Body:
I'm trying to build an app that posts sentences to Blogger. However I'm stuck at the oAuth part which requires a client ID and client secret. I don't know where to find these values.

The values are required in the following line:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jacksonFactory,
                        CLIENT_ID, CLIENT_SECRET, scopes).setAccessType("online").setApprovalPrompt("auto").build();

How do I find the proper CLIENT_ID and CLIENT_SECRET values?


问:
Select last duplicate row with different id Oracle 11g
I have a table that look like this:

The problem is I need to get the last record with duplicates in the column "NRODENUNCIA".

答:
There are a number of solutions for your problem. One is to use row_number.

Note that I've ordered by DENUNCIID in the OVER clause. This defines the "Last Record" as the one that has the largest DENUNCIID. If you want to define it differently you'd need to change the field that is being ordered.

```<code>with dupes as (

SELECT
        ROW_NUMBER() OVER (Partition by NRODENUNCIA ORDER BY DENUNCIID DESC) RN,
        *
FROM
     YourTable
)
SELECT * FROM dupes where rn = 1
</code>```

This only get's the last record per dupe.

If you want to only include records that have dupes then you change the where clause to

```<code>WHERE  rn =1
  and NRODENUNCIA  in (select NRODENUNCIA from dupes where rn > 1)
</code>```

Body:
There are a number of solutions for your problem. One is to use row_number.

Note that I've ordered by DENUNCIID in the OVER clause. This defines the "Last Record" as the one that has the largest DENUNCIID. If you want to define it differently you'd need to change the field that is being ordered.

with dupes as (

SELECT
        ROW_NUMBER() OVER (Partition by NRODENUNCIA ORDER BY DENUNCIID DESC) RN,
        *
FROM
     YourTable
)
SELECT * FROM dupes where rn = 1

This only get's the last record per dupe.

If you want to only include records that have dupes then you change the where clause to

WHERE  rn =1
  and NRODENUNCIA  in (select NRODENUNCIA from dupes where rn > 1)


问:
Drop down menu breaking footer
I have an html file with really big drop down menus and a small page. When I'm just using the page and not touching the menu, the footer is at the bottom and there's no problem. When I use the drop down menu, the footer stays at the same place as before and there is a huge white space under it. I don't want it fixed (it's not for all pages so it will be ugly) but I want it to stay at the bottom always even if I open the drop downmenu and scroll. How can I do that? Here is the footer's css if that helps.</p>

```<code>footer {
    margin-top: 10%;
    text-align: center;
    background: rgb(200,200,200);
    padding: 1%;
    font-size: 18px;
}
</code>```

答:
As footer should be in bottom, so it should not have margin-top property instead it should have bottom:0.

Also, dropdown should have max-height css property, it should not be too long.

Title: Drop down menu breaking footer

Body:
I have an html file with really big drop down menus and a small page. When I'm just using the page and not touching the menu, the footer is at the bottom and there's no problem. When I use the drop down menu, the footer stays at the same place as before and there is a huge white space under it. I don't want it fixed (it's not for all pages so it will be ugly) but I want it to stay at the bottom always even if I open the drop downmenu and scroll. How can I do that? Here is the footer's css if that helps.

footer {
    margin-top: 10%;
    text-align: center;
    background: rgb(200,200,200);
    padding: 1%;
    font-size: 18px;
}


问:
ScrapingHub: ImportError: No module named firebase
I'm trying to put my scraped data on my firebase account on cloud , but i'm getting this ImportError when i run the spider. I tried making new project and even reinstalling the firebase and shub on specific version of Python but no help.

the spider runs perfectly on my machine , and doesn't show any ImportErrors.
here is the error log.

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/scrapy/utils/defer.py", line 102, in iter_errback
    yield next(it)
  File "/usr/local/lib/python2.7/site-packages/sh_scrapy/middlewares.py", line 30, in process_spider_output
    for x in result:
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/offsite.py", line 29, in process_spider_output
    for x in result:
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/referer.py", line 339, in <genexpr>
    return (_set_referer(r) for r in result or ())
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/urllength.py", line 37, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/depth.py", line 58, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/app/__main__.egg/Terminator/spiders/IcyTermination.py", line 18, in parse
    from firebase import firebase
ImportError: No module named firebase
</code>```

any help?

答:
I couldn't comment due to reputation. But have you created your requirements.txt?

Here you will find how to deploy your own dependencies to scrapinghub.

Basically you create a requirements.txt file at the root of your project with one dependency per line and add

requirements_file: requirements.txt

to your scrapinghub.yml file

Body:
I'm trying to put my scraped data on my firebase account on cloud , but i'm getting this ImportError when i run the spider. I tried making new project and even reinstalling the firebase and shub on specific version of Python but no help.

the spider runs perfectly on my machine , and doesn't show any ImportErrors.
here is the error log.

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/scrapy/utils/defer.py", line 102, in iter_errback
    yield next(it)
  File "/usr/local/lib/python2.7/site-packages/sh_scrapy/middlewares.py", line 30, in process_spider_output
    for x in result:
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/offsite.py", line 29, in process_spider_output
    for x in result:
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/referer.py", line 339, in <genexpr>
    return (_set_referer(r) for r in result or ())
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/urllength.py", line 37, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/depth.py", line 58, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/app/__main__.egg/Terminator/spiders/IcyTermination.py", line 18, in parse
    from firebase import firebase
ImportError: No module named firebase

any help?


问:
analytics.js net::ERR_CONNECTION_REFUSED
Could anyone help me understand why this happens with google analytics code?

This is the error which then gives me to load the tracking code:

https://www.google-analytics.com/analytics.js Failed to load resource: net::ERR_CONNECTION_REFUSED

Is there any solution to this? I was trying to fix it all morning.

My situation:

If this error occurs, the tracking code does not work.
So if events are monitored and callback functions specified in hitCallback property are never executed. When the causes a deficiency in the functionality of the website and also in tracking statistics.

Types of events that have failed me: behavioral events, events advanced electronic commerce (step forward cart).

My attempts:

I have disabled antivirus, antivirus firewall, Windows firewall and defend unsuccessfully thinking that could be.
I installed the extention to debug google analytics. Googled for hours. I tried loading the code directly in the browser and on any pc I can get it. I could only get https://www.google-analytics.com/analytics.js making a wget from my server console.
It could be a problem with the ISP?

Thank you very much!

Update:

Confirmed is the ISP.
Although they have not solved in my case because the technician went on vacation.

If someone would come to have this problem, it occurs to me as a solution, edit the code tracking Analitycs to call a url eg "mydomain.com/analytics.js" it processor by modrewrite, and direct this request php file to download the actual file Js www.google-analytics.com/analytics.js and return in the response. As a proxy php. It's just an idea I have not tested.
Thank you all, and may close this question if you want.

答:
It can be that you are using a VPN(Virtual private network) which analytics blocks. Try loading https://www.google-analytics.com/analytics.js
If it does not work, try disabling the VPN and try again </p>


问:
how to Add a Button on the home screen in android?
I want to add a button on the home screen and want to code in the click event of that button.
I have an application which has an activate button,As soon as this activate button is clicked i want that a Button gets created on the home screen and i want to code some database queries in its click event.I have already created that application,Now i want to place the button on the home screen.How do i do that.

Thanks in Anticipation.

答: I don't think you can create a button on the Home Screen on-the-fly by coding.  In my book, the only way to get a button on the Home Screen is if the user adds it as a widget.</p>


问:
Finding child fragment by Tag inside another Fragment
I hava a fragment that is the parent of another fragment. I am adding the fragment child like this:

```<code>@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.add(R.id.list_container, new SwipeableFragment(), FRAGMENT_LIST_VIEW).commit();
        transaction.addToBackStack(FRAGMENT_LIST_VIEW);

 return view;
}
</code>```

Later, I have a method in my parent fragment that needs to find the child. So I'm doing like this:

```<code>final Fragment fragment = getFragmentManager().findFragmentByTag(FRAGMENT_LIST_VIEW);
</code>```

But always returns null. What am I doing wrong?

答:
Change this code with the code given below:

```<code>// Your Code:
final Fragment fragment = getFragmentManager().findFragmentByTag(FRAGMENT_LIST_VIEW);

// Replace with this:
final Fragment fragment = getChildFragmentManager().findFragmentByTag(FRAGMENT_LIST_VIEW);
</code>```

Hopefully it will work!

Body:
I hava a fragment that is the parent of another fragment. I am adding the fragment child like this:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.add(R.id.list_container, new SwipeableFragment(), FRAGMENT_LIST_VIEW).commit();
        transaction.addToBackStack(FRAGMENT_LIST_VIEW);

 return view;
}

Later, I have a method in my parent fragment that needs to find the child. So I'm doing like this:

final Fragment fragment = getFragmentManager().findFragmentByTag(FRAGMENT_LIST_VIEW);

But always returns null. What am I doing wrong?

Body:
Change this code with the code given below:

// Your Code:
final Fragment fragment = getFragmentManager().findFragmentByTag(FRAGMENT_LIST_VIEW);

// Replace with this:
final Fragment fragment = getChildFragmentManager().findFragmentByTag(FRAGMENT_LIST_VIEW);

Hopefully it will work!