问:
Query that creates 1000 rows in Oracle SQL
I am trying to write a query to generates 1000 rows, I have a table called CCHOMEWORK with 2 columns, ID integer (PK) and StudentID varchar which contains the value for all the 1000 rows.

I tried this, but I keep getting errors and does not work

```<code>SET @MyCounter = 1

WHILE @MyCounter < 1000

BEGIN

INSERT INTO CCHOMEWORK
    (ID)
VALUES
    @MyCounter)

    set @MyCounter = @MyCounter + 1;

END
</code>```

答:
This will create 1000 rows:

```<code>SELECT LEVEL
FROM   DUAL
CONNECT BY LEVEL <= 1000
</code>```

You can include it in your insert with:

```<code>INSERT INTO CCHOMEWORK (ID)
SELECT LEVEL
FROM   DUAL
CONNECT BY LEVEL <= 1000
</code>```

However, if you want to insert multiple sequential IDs you might be better using a sequence:

```<code>CREATE SEQUENCE CCHOMEWORK__ID__SEQ
/
</code>```

Then:

```<code>INSERT INTO CCHOMEWORK (ID)
SELECT CC_HOMEWORK__ID__SEQ.NEXTVAL
FROM DUAL
CONNECT BY LEVEL <= 1000;
</code>```

Or:

```<code>BEGIN
  FOR i IN 1 .. 1000 LOOP
    INSERT INTO CCHOMEWORK (ID) VALUES ( CC_HOMEWORK__ID__SEQ.NEXTVAL );
  END LOOP;
END;
/
</code>```

Body:
I am trying to write a query to generates 1000 rows, I have a table called CCHOMEWORK with 2 columns, ID integer (PK) and StudentID varchar which contains the value for all the 1000 rows.

I tried this, but I keep getting errors and does not work

SET @MyCounter = 1

WHILE @MyCounter < 1000

BEGIN

INSERT INTO CCHOMEWORK
    (ID)
VALUES
    @MyCounter)

    set @MyCounter = @MyCounter + 1;

END

Body:
This will create 1000 rows:

SELECT LEVEL
FROM   DUAL
CONNECT BY LEVEL <= 1000

You can include it in your insert with:

INSERT INTO CCHOMEWORK (ID)
SELECT LEVEL
FROM   DUAL
CONNECT BY LEVEL <= 1000

However, if you want to insert multiple sequential IDs you might be better using a sequence:

CREATE SEQUENCE CCHOMEWORK__ID__SEQ
/

Then:

INSERT INTO CCHOMEWORK (ID)
SELECT CC_HOMEWORK__ID__SEQ.NEXTVAL
FROM DUAL
CONNECT BY LEVEL <= 1000;

Or:

BEGIN
  FOR i IN 1 .. 1000 LOOP
    INSERT INTO CCHOMEWORK (ID) VALUES ( CC_HOMEWORK__ID__SEQ.NEXTVAL );
  END LOOP;
END;
/


来源: stackexchange

问:
Cant put Query inside Create sequence sql
The Below query is failing. How to correct it I need to put max id from TBL_PLANNING_REPOSITORY in the create sequence start with.

```<code>CREATE sequence auto_id_planning_repo
start with (select MAX(ID) from TBL_PLANNING_REPOSITORY) increment by 1;
</code>```

答:
Use dynamic sql.</p>

```<code>DECLARE
   v_startwith   NUMBER;
BEGIN
   SELECT MAX (ID) INTO v_startwith FROM TBL_PLANNING_REPOSITORY;

   EXECUTE IMMEDIATE
      'create sequence auto_id_planning_repo  start with ' || v_startwith || ' increment by 1';
END;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The Below query is failing. How to correct it I need to put max id from TBL_PLANNING_REPOSITORY in the create sequence start with.

CREATE sequence auto_id_planning_repo
start with (select MAX(ID) from TBL_PLANNING_REPOSITORY) increment by 1;

Body:
Use dynamic sql.

DECLARE
   v_startwith   NUMBER;
BEGIN
   SELECT MAX (ID) INTO v_startwith FROM TBL_PLANNING_REPOSITORY;

   EXECUTE IMMEDIATE
      'create sequence auto_id_planning_repo  start with ' || v_startwith || ' increment by 1';
END;


问:
PHP if a table table row exists
In PHP, is there a way of making the following statement to check if a row exists?

If "the table cases has a "passenger" field with the value of 4 WHERE case= '$case' {
code...
}

答:
```<code>$query ='SELECT 1 FROM cases WHERE passenger = 4 AND case ="$case"';
$result = mysql_query($query);

if(mysql_num_rows($result)){
   //exists
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: PHP if a table table row exists


问:
Configure IntersectionObserver to change value of *.isIntersecting based on X pixels
I have intersection observer object it works, but I want it to notify my once some element is 100pixels over or at bottom of intersection point.

With default config it just changes value of .isIntersection once the element is exactly in view. But I want to do some stuff when elements are 100pixels above or below the viewport.

This is my code:

```<code>var iObserver = new IntersectionObserver(function(element) {
  console.log('elementi', element); // I want to trigger here when elementi is 100px or less of distance to the viewport.
});

var el;
for (var i = 0; i < elements.length; i++) {
  el = elements[i];
  console.log('eli', el);
  iObserver.observe(el);
}
</code>```

UPDATE

Thanks to user for answer I used this and it worked:

```<code>var iObserver = new IntersectionObserver(function(entryEvent) {
 //...
}, {'rootMargin': '100px 0px 100px 0px'});
</code>```

答:
You can define the rootMargin top and bottom in the options you pass to the observer.

In the demo, hover the red rectangle, when it reaches a distance of 10px from the .container the observer is called:

const options = {
  root: document.querySelector('.container'),
  rootMargin: '10px 0px 10px 0px',
};

let i = 0;

const iObserver = new IntersectionObserver((entries) => console.log(`intersection ${i++}`), options);

iObserver.observe(document.querySelector('.element'));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  position: relative;
  height: 20px;
  background: lightblue;
}

.element {
  position: absolute;
  top: calc(100% + 30px);
  height: 100px;
  width: 100px;
  background: red;
  margin-bottom: 20px;
  transition: top 5s;
}

.element:hover {
  top: calc(100% - 30px);
}

.as-console-wrapper {
  height: 50px;
}</code>```

1

```

Body:
I have intersection observer object it works, but I want it to notify my once some element is 100pixels over or at bottom of intersection point.

With default config it just changes value of .isIntersection once the element is exactly in view. But I want to do some stuff when elements are 100pixels above or below the viewport.

This is my code:

var iObserver = new IntersectionObserver(function(element) {
  console.log('elementi', element); // I want to trigger here when elementi is 100px or less of distance to the viewport.
});

var el;
for (var i = 0; i < elements.length; i++) {
  el = elements[i];
  console.log('eli', el);
  iObserver.observe(el);
}

UPDATE

Thanks to user for answer I used this and it worked:

var iObserver = new IntersectionObserver(function(entryEvent) {
 //...
}, {'rootMargin': '100px 0px 100px 0px'});

Body:
You can define the rootMargin top and bottom in the options you pass to the observer.

In the demo, hover the red rectangle, when it reaches a distance of 10px from the .container the observer is called:

const options = {
  root: document.querySelector('.container'),
  rootMargin: '10px 0px 10px 0px',
};

let i = 0;

const iObserver = new IntersectionObserver((entries) => console.log(`intersection ${i++}`), options);

iObserver.observe(document.querySelector('.element'));

.container {
  position: relative;
  height: 20px;
  background: lightblue;
}

.element {
  position: absolute;
  top: calc(100% + 30px);
  height: 100px;
  width: 100px;
  background: red;
  margin-bottom: 20px;
  transition: top 5s;
}

.element:hover {
  top: calc(100% - 30px);
}

.as-console-wrapper {
  height: 50px;
}

<div class="container">
  <div class="element">1</div>
</div>


问:
Background subtraction when background brightness is unknown
I'm currently working on a computer vision project, and got most of my algorithm working. However I'm currently doing background subtraction manually on every image. This is because the most common background subtraction algorithms that I can find make use of thresholding, and my project should deal with backgrounds both brighter and darker than the object I want to extract.

This is the way I am subtracting the background currently (using python and the scikit stack):

```<code>val = filters.threshold_otsu(image)
return image > val
</code>```

Of course, this only works with backgrounds darker than the subject.
I had the idea of finding whether or not the background is bright, and then depending on that change the sign of the inequality, but could not find a way to do that.

Is there a background subtraction algorithm which is able to handle both bright and dark backgrounds, or is there another way to solve this problem?

答:
There are several automatic thresholding techiques available. One of them is Otsu.

http://www.labbookpages.co.uk/software/imgProc/otsuThreshold.html

It is implemented in opencv (https://docs.opencv.org/trunk/d7/d4d/tutorial_py_thresholding.html)

```<code>import cv2
img = cv2.imread('noisy2.png',0)
ret2,th2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
</code>```

Body:
I'm currently working on a computer vision project, and got most of my algorithm working. However I'm currently doing background subtraction manually on every image. This is because the most common background subtraction algorithms that I can find make use of thresholding, and my project should deal with backgrounds both brighter and darker than the object I want to extract.

This is the way I am subtracting the background currently (using python and the scikit stack):

val = filters.threshold_otsu(image)
return image > val

Of course, this only works with backgrounds darker than the subject.
I had the idea of finding whether or not the background is bright, and then depending on that change the sign of the inequality, but could not find a way to do that.

Is there a background subtraction algorithm which is able to handle both bright and dark backgrounds, or is there another way to solve this problem?

Body:
There are several automatic thresholding techiques available. One of them is Otsu.

http://www.labbookpages.co.uk/software/imgProc/otsuThreshold.html

It is implemented in opencv (https://docs.opencv.org/trunk/d7/d4d/tutorial_py_thresholding.html)

import cv2
img = cv2.imread('noisy2.png',0)
ret2,th2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)


问:
Java caching system with spring
I already have a system which uses spring's caching abstraction + EhCache Implementation for caching solution. But now, I need to switch EhCache for other solution that gives me distributed features. I found JCS ( java Caching System ) suitable for my problem. However, I haven't managed to find a way to use spring caching abstraction with JCS. Does anyone of you know how if it's possible to use spring caching abstraction with JCS? If so, how do I do it?

```<code>@Bean(destroyMethod = "shutdown")
public net.sf.ehcache.CacheManager ehCacheManager() {
    net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();

    DiskStoreConfiguration store = new DiskStoreConfiguration();
    store.setPath(
            diskDirectory);
    config.addDiskStore(store);
    CacheConfiguration cacheConfiguration = new CacheConfiguration();
    cacheConfiguration.setName("disk");
    cacheConfiguration.maxEntriesLocalHeap(1);
    cacheConfiguration.setTimeToLiveSeconds(Integer.parseInt(cacheTime));
    cacheConfiguration.setMemoryStoreEvictionPolicy("LRU");

    cacheConfiguration.maxBytesLocalDisk(Long.parseLong(diskSize), MemoryUnit.GIGABYTES);
    PersistenceConfiguration perCache = new PersistenceConfiguration();
    perCache.strategy(Strategy.LOCALTEMPSWAP);

    cacheConfiguration.addPersistence(perCache);
    config.addCache(cacheConfiguration);

    return net.sf.ehcache.CacheManager.newInstance(config);
}
</code>```

My goal is to find a CacheManager class that works like the one above, and Therefore, be able to use the anottations @cacheble, @key and etc.

Thanks!!

答:
Have you considered Infinispan? It provides distributed features and it has a good spring integration. It also supports JSR 107 api.

An example extracted from the official site:

```<code>/**
 * This example shows how to configure Spring's {@link CacheManager} with
  Infinispan implementation.
 */
public class SpringAnnotationConfiguration {

    @Configuration
    public static class ApplicationConfiguration {

        @Bean
        public SpringEmbeddedCacheManagerFactoryBean springCache() {
            return new SpringEmbeddedCacheManagerFactoryBean();
        }

        @Bean
        public CachePlayground playground() {
            return new CachePlayground();
        }
    }

    public static class CachePlayground {

        @Autowired
        private CacheManager cacheManager;

        public void add(String key, String value) {
            cacheManager.getCache("default").put(key, value);
        }

        public String getContent(String key) {
            return cacheManager.getCache("default").get(key).get().toString();
        }
    }

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);

        CachePlayground cachePlayground = applicationContext.getBean(CachePlayground.class);

        cachePlayground.add("Infinispan", "Is cool!");
        System.out.println(cachePlayground.getContent("Infinispan"));
    }
}
</code>```

Title: Java caching system with spring

Body:
I already have a system which uses spring's caching abstraction + EhCache Implementation for caching solution. But now, I need to switch EhCache for other solution that gives me distributed features. I found JCS ( java Caching System ) suitable for my problem. However, I haven't managed to find a way to use spring caching abstraction with JCS. Does anyone of you know how if it's possible to use spring caching abstraction with JCS? If so, how do I do it?

@Bean(destroyMethod = "shutdown")
public net.sf.ehcache.CacheManager ehCacheManager() {
    net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();

    DiskStoreConfiguration store = new DiskStoreConfiguration();
    store.setPath(
            diskDirectory);
    config.addDiskStore(store);
    CacheConfiguration cacheConfiguration = new CacheConfiguration();
    cacheConfiguration.setName("disk");
    cacheConfiguration.maxEntriesLocalHeap(1);
    cacheConfiguration.setTimeToLiveSeconds(Integer.parseInt(cacheTime));
    cacheConfiguration.setMemoryStoreEvictionPolicy("LRU");

    cacheConfiguration.maxBytesLocalDisk(Long.parseLong(diskSize), MemoryUnit.GIGABYTES);
    PersistenceConfiguration perCache = new PersistenceConfiguration();
    perCache.strategy(Strategy.LOCALTEMPSWAP);

    cacheConfiguration.addPersistence(perCache);
    config.addCache(cacheConfiguration);

    return net.sf.ehcache.CacheManager.newInstance(config);
}

My goal is to find a CacheManager class that works like the one above, and Therefore, be able to use the anottations @cacheble, @key and etc.

Thanks!!

Body:
Have you considered Infinispan? It provides distributed features and it has a good spring integration. It also supports JSR 107 api.

An example extracted from the official site:

/**
 * This example shows how to configure Spring's {@link CacheManager} with
  Infinispan implementation.
 */
public class SpringAnnotationConfiguration {

    @Configuration
    public static class ApplicationConfiguration {

        @Bean
        public SpringEmbeddedCacheManagerFactoryBean springCache() {
            return new SpringEmbeddedCacheManagerFactoryBean();
        }

        @Bean
        public CachePlayground playground() {
            return new CachePlayground();
        }
    }

    public static class CachePlayground {

        @Autowired
        private CacheManager cacheManager;

        public void add(String key, String value) {
            cacheManager.getCache("default").put(key, value);
        }

        public String getContent(String key) {
            return cacheManager.getCache("default").get(key).get().toString();
        }
    }

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);

        CachePlayground cachePlayground = applicationContext.getBean(CachePlayground.class);

        cachePlayground.add("Infinispan", "Is cool!");
        System.out.println(cachePlayground.getContent("Infinispan"));
    }
}


问:
WooCommerce Custom Template Adding Only Last Product in the row to the cart
I want to show specific products in a table list view with their own custom field for specific user; couldn't achieve this with any plugins so started to code my own. Only this user/wholesaler will view this page.

But before going that far in the code I got stuck on "ADD TO CART" Button submission. Whichever product I try to add only the last product in the row gets submitted.
Here's the code:

```<code>    <h1> PRODUCT TABLE LIST </h1>
            <table>

            <thead>
              <tr>
                <th></th>
                <th>Product</th>
                <th>Note Box</th>
                <th>Price</th>
                <th>Choose Quantiy</th>
                <th>Product Total Quantity</th>
                <th></th>
              </tr>
              </thead>

              <tbody class="products">
    <?php
        $args = array(
        'post_type' => 'product',
        'posts_per_page' => 15,
        'product_cat' => '',
        'post__in' => array( 481, 478, 934 ),
        'orderby' => 'title' );
        $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>

                <tr class="product-<?php echo esc_attr( $product->id ); ?>">

                    <a href="<?php echo get_permalink( $loop->post->ID ) ?>" title="<?php echo esc_attr($loop->post->post_title ? $loop->post->post_title : $loop->post->ID); ?>">

<td>
                        <?php woocommerce_show_product_sale_flash( $post, $product ); ?>

                        <?php if (has_post_thumbnail( $loop->post->ID )) echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); else echo '<img src="'.woocommerce_placeholder_img_src().'" alt="Placeholder" width="300px" height="300px" />'; ?>

</td>

<td>
<h3><?php the_title(); ?></h3>
</td>

<td>
<input type="text" placeholder="Choose up to 16 letters or Numbers" />
</td>

<td>
<span class="price">
<?php echo $product->get_price_html(); ?>
</span>
</td>

</a>

    <td>

<table>
    <tr>
        <th>SC1</th>
            <td><input type="number" name="quantity" min="1" max="100"></td>
    </tr>

    <tr>
        <th>KW1</th>
        <td><input type="number" name="quantity" min="1" max="100"></td>
    </tr>
</table>

</td>

<td><input name="quantity" data-min="1" data-max="0" value="1" size="4" title="Qty" class="input-text qty text" maxlength="12" type="number"></td>

<td>
                    <input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $product->id ); ?>" />

<button type="submit" class="single_add_to_cart_button button alt"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>
</td>

</tr>

    <?php endwhile; ?>
    <?php wp_reset_query(); ?>

            </tbody>
            </table>
</code>```

I have tried to use woocommerce_template_loop_add_to_cart( $loop->post, $product) but it doesn't submit the quantity value.

答:
there is no need to create different tempalte for woo commerce cart. woocommerce give you to chnage this its own templates.

copy the files under templates folder from woocommerce plugin and paste these files to you theme folder under the "woocommerce" folder. (you have to create woocommerce folder in your theme). now you can modify woocommerce templates.

Body:
I want to show specific products in a table list view with their own custom field for specific user; couldn't achieve this with any plugins so started to code my own. Only this user/wholesaler will view this page.

But before going that far in the code I got stuck on "ADD TO CART" Button submission. Whichever product I try to add only the last product in the row gets submitted.
Here's the code:

 PRODUCT TABLE LIST

                Product
                Note Box
                Price
                Choose Quantiy
                Product Total Quantity

    <?php
        $args = array(
        'post_type' => 'product',
        'posts_per_page' => 15,
        'product_cat' => '',
        'post__in' => array( 481, 478, 934 ),
        'orderby' => 'title' );
        $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>

                <tr class="product-<?php echo esc_attr( $product->id ); ?>">

                    <a href="<?php echo get_permalink( $loop->post->ID ) ?>" title="<?php echo esc_attr($loop->post->post_title ? $loop->post->post_title : $loop->post->ID); ?>">

                        <?php woocommerce_show_product_sale_flash( $post, $product ); ?>

                        <?php if (has_post_thumbnail( $loop->post->ID )) echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); else echo ''; ?>

<?php the_title(); ?>

<input type="text" placeholder="Choose up to 16 letters or Numbers" />

<?php echo $product->get_price_html(); ?>

        SC1
            <input type="number" name="quantity" min="1" max="100">

        KW1
        <input type="number" name="quantity" min="1" max="100">

<input name="quantity" data-min="1" data-max="0" value="1" size="4" title="Qty" class="input-text qty text" maxlength="12" type="number">

                    <input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $product->id ); ?>" />

<button type="submit" class="single_add_to_cart_button button alt"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>

    <?php endwhile; ?>
    <?php wp_reset_query(); ?>

I have tried to use woocommerce_template_loop_add_to_cart( $loop->post, $product) but it doesn't submit the quantity value.


问:
Nativescript Default child route
How can I navigate to /account/dashboard, when the the router is '/account' ?
Here are my routes, which are currently not working.
The component that is being loaded is AccountPage, rather than AccountDashboardPage ?</p>

```<code>export const routes = [
    { path: "", redirectTo: "home", pathMatch: "full" },
    { path: "home", component: HomePage },
    { path: "settings", component: SettingsPage },
    { path: "checkout", component: CheckoutPage },
    { path: "login", component: LoginPage },
    { path: "categories", component: CategoriesPage },
    { path: "category/subcategories/:id", component: SubcategoryList, pathMatch: "full" },
    { path: "category/:id", component: CategoryProducts, pathMatch: "full" },
    { path: "product/:id", component: ProductPage },
    {
        path: 'account',
        component: AccountPage,
        canActivateChild: [AuthGuardService],
        children: [
            { path: "", redirectTo: 'dashboard', pathMatch: 'full' },
            { path: 'dashboard', component: AccountDashboardPage}
        ]
    }
];
</code>```

答:
When I removed

```<code>component: AccountPage,
</code>```

it all worked out!

Title: Nativescript Default child route

Body:
How can I navigate to /account/dashboard, when the the router is '/account' ?
Here are my routes, which are currently not working.
The component that is being loaded is AccountPage, rather than AccountDashboardPage ?

export const routes = [
    { path: "", redirectTo: "home", pathMatch: "full" },
    { path: "home", component: HomePage },
    { path: "settings", component: SettingsPage },
    { path: "checkout", component: CheckoutPage },
    { path: "login", component: LoginPage },
    { path: "categories", component: CategoriesPage },
    { path: "category/subcategories/:id", component: SubcategoryList, pathMatch: "full" },
    { path: "category/:id", component: CategoryProducts, pathMatch: "full" },
    { path: "product/:id", component: ProductPage },
    {
        path: 'account',
        component: AccountPage,
        canActivateChild: [AuthGuardService],
        children: [
            { path: "", redirectTo: 'dashboard', pathMatch: 'full' },
            { path: 'dashboard', component: AccountDashboardPage}
        ]
    }
];

Body:
When I removed

component: AccountPage,

it all worked out!


问:
How to call a method with a variable parameter from the main method?
I would like to call the isATens method from my main method but im only able to do that when isATens has no parameter. I'v tried putting the same parameter in the caller, but that does't seem to recognize that either.</p>

```<code>public class P1L4 {

    public static void main(String[] args) {
        P1L4 main = new P1L4();
        main.run();
        isATens(userInput); //<--- this is what I've tried doing.
    }

    public void run() {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Name a tens and i'll test if it's one under 100.");
        int userInput = scanner.nextInt();
    }

    public boolean isATens(int userInput) {
        System.out.println(userInput);
        switch (userInput) {
            case 10 : case 20 : case 30 : case 40 : case 50 : case 60: case 70: case 80: case 90 :
                isUnderOneHundred(continued);
            default :
                System.out.println("Not under one hundred");
        }
        return true;
    }

    public boolean isUnderOneHundred(int continued) {
        return true;
    }
}
</code>```

答:
There are some Java concepts that you apparently haven't learned yet: Scope and Instance vs. static methods. Read the appropriate chapters of your Java textbook if you have difficulties understanding my following comments.

int userInput = scanner.nextInt(); is declared inside the scope of the run() method, and therefore not visible in the main() method. If you want to see userInput outside of the run() method, I'd make it the return value of that method:

```<code>public int run() {
    ...
    int userInput = scanner.nextInt();
    return userInput;
}
</code>```

You're mixing instance and static methods without any visible concept when to use which kind. When you want to call an instance method from a static one, you need to name the instance before the dot, so at least it has to be main.isATens(userInput); instead of isATens(userInput); (after you've solved the userInput issue).

Your program logic is strange, e.g. I'd expect a method like isUnderOneHundred(int continued) to return true if the parameter is under 100, but that method doesn't even have any look at its parameter and returns true for any number you pass in.

Body:
I would like to call the isATens method from my main method but im only able to do that when isATens has no parameter. I'v tried putting the same parameter in the caller, but that does't seem to recognize that either.

public class P1L4 {

    public static void main(String[] args) {
        P1L4 main = new P1L4();
        main.run();
        isATens(userInput); //<--- this is what I've tried doing.
    }

    public void run() {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Name a tens and i'll test if it's one under 100.");
        int userInput = scanner.nextInt();
    }

    public boolean isATens(int userInput) {
        System.out.println(userInput);
        switch (userInput) {
            case 10 : case 20 : case 30 : case 40 : case 50 : case 60: case 70: case 80: case 90 :
                isUnderOneHundred(continued);
            default :
                System.out.println("Not under one hundred");
        }
        return true;
    }

    public boolean isUnderOneHundred(int continued) {
        return true;
    }
}

Body:
There are some Java concepts that you apparently haven't learned yet: Scope and Instance vs. static methods. Read the appropriate chapters of your Java textbook if you have difficulties understanding my following comments.

int userInput = scanner.nextInt(); is declared inside the scope of the run() method, and therefore not visible in the main() method. If you want to see userInput outside of the run() method, I'd make it the return value of that method:

public int run() {
    ...
    int userInput = scanner.nextInt();
    return userInput;
}

You're mixing instance and static methods without any visible concept when to use which kind. When you want to call an instance method from a static one, you need to name the instance before the dot, so at least it has to be main.isATens(userInput); instead of isATens(userInput); (after you've solved the userInput issue).

Your program logic is strange, e.g. I'd expect a method like isUnderOneHundred(int continued) to return true if the parameter is under 100, but that method doesn't even have any look at its parameter and returns true for any number you pass in.


问:
Change color of text in dynamic table AngularJS/JavaScript
I am working on a web application in which I maintain a favorites table. How can I change color of values in HTML table? For example if for a particular column value is less than 0 then display in red and if value id more than 0, display in green. This is the snippet of my code:

```<code><table class="table table-striped" style="margin-top: 10px;" id="favoritesTable">
    <tr>
        <th>Symbol</th>
        <th>Stock Price</th>
        <th>Change (Change Percent)</th>
        <th>Volume</th>
        <th></th>
    </tr>
    <tr ng-repeat="x in mylist">
        <td><a ng-click="changeValue(x[0]);getStockDetails()" style="color: blue; cursor: pointer;" data-slide="prev" href="#myCarousel">{{x[0]}}</a></td>
        <td>{{x[1]}}</td>
        <td id="changeAndPercent">{{x[2]}} ({{x[3]}}%)</td>
        <td>{{x[4]}}</td>
        <td><button class="btn btn-default btn-sm" ng-click="removeFromTable(x[0])"><span class="glyphicon glyphicon-trash"></span></button></td>
    </tr>
</table>
</code>```

I am storing data in mylist variable in angularJS. I want to check if x[2] is greater than 0 then display it in green color and if it is less than 0 display it in red color.

Things I tried were adding script tag inside table and creating table in JavaScript. When I created table in a JavaScript function then ng-click functions did not work. Please help!

Thanks in advance!

EDIT: I have also attached an image of my table -->

答:
Simple use ng-class set to show red color if value is zero

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {
$scope.data=[{value:0},{value:-1},{value:1}]
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.text-red{
  color:red
}

.arrow-green{
  width: 0;
  height: 0;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;

  border-left: 20px solid green;
}
.arrow-red{
  width: 0;
  height: 0;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;

  border-left: 20px solid red;
}
  .text-green{
  color:green
}</code>```

  <td ng-class="{'text-red': item.value <=0,'text-green': item.value >0}">
   My value is {{item.value}}
 <div  ng-class="{'arrow-red': item.value <=0,'arrow-green': item.value >0}">

```

Body:
I am working on a web application in which I maintain a favorites table. How can I change color of values in HTML table? For example if for a particular column value is less than 0 then display in red and if value id more than 0, display in green. This is the snippet of my code:

        Symbol
        Stock Price
        Change (Change Percent)
        Volume

        {{x[0]}}
        {{x[1]}}
        {{x[2]}} ({{x[3]}}%)
        {{x[4]}}
        <button class="btn btn-default btn-sm" ng-click="removeFromTable(x[0])"></button>

I am storing data in mylist variable in angularJS. I want to check if x[2] is greater than 0 then display it in green color and if it is less than 0 display it in red color.

Things I tried were adding script tag inside table and creating table in JavaScript. When I created table in a JavaScript function then ng-click functions did not work. Please help!

Thanks in advance!

EDIT: I have also attached an image of my table -->

Body:
Simple use ng-class set to show red color if value is zero

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {
$scope.data=[{value:0},{value:-1},{value:1}]
});

.text-red{
  color:red
}

.arrow-green{
  width: 0;
  height: 0;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;

  border-left: 20px solid green;
}
.arrow-red{
  width: 0;
  height: 0;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;

  border-left: 20px solid red;
}
  .text-green{
  color:green
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<table>

<tr ng-repeat="item in data">
  <td ng-class="{'text-red': item.value <=0,'text-green': item.value >0}">
   My value is {{item.value}}
 <div  ng-class="{'arrow-red': item.value <=0,'arrow-green': item.value >0}"></div>
  </td>
</tr>
</table>
</div>


问:
How to handle requests that includes forward slashes (/)?
I need to handle requests as following:

```<code>www.example.com/show/abcd/efg?name=alex&family=moore   (does not work)
www.example.com/show/abcdefg?name=alex&family=moore   (works)
www.example.com/show/abcd-efg?name=alex&family=moore   (works)
</code>```

It should accept any sort of character from the value that is located between www.example.com/show/ and ?. Please note the value that would be located there would be a single value not name of an action.

For example: /show/abcd/efg and /show/lkikf?name=Jack in which the first request should redirect user to the page abcd/efg (because thats a name) and the second one should redirect user to the page lkikf along with value of parameter name.

I have following controller to handle it but the issue is when I have / in the address the controller is unable to handle it.

```<code>@RequestMapping(value = "/{mystring:.*}", method = RequestMethod.GET)
public String handleReqShow(
            @PathVariable String mystring,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String family, Model model)     {
</code>```

I used following regex which did not work.

```<code> /^[ A-Za-z0-9_@./#&+-]*$/
</code>```

答:
You could encode slashes on UI with %2f: http://www.example.com/show/abcd%2fefg?name=alex&family=moore.
Now you should configure Spring to handle slashes. Simple config example:

```<code>@RestController
public class TestController {

    @GetMapping("{testId:.+}")
    public String test(@PathVariable String testId) {
        return testId;
    }

    @GetMapping("{testId:.+}/test/{messageId}")
    public String test2(@PathVariable String testId, @PathVariable String messageId) {
        return testId + " " + messageId;
    }

    //Only if using Spring Security
    @Configuration
    public static class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
        @Bean
        public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
            DefaultHttpFirewall firewall = new DefaultHttpFirewall();
            firewall.setAllowUrlEncodedSlash(true);
            return firewall;
        }
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
        }
    }

    @Configuration
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public static class SpringMvcConfig extends WebMvcConfigurerAdapter {
        @Override
        public void configurePathMatch(PathMatchConfigurer configurer) {
            UrlPathHelper urlPathHelper = new UrlPathHelper();
            urlPathHelper.setUrlDecode(false);
            configurer.setUrlPathHelper(urlPathHelper);
        }
    }

}
</code>```

Body:
I need to handle requests as following:

www.example.com/show/abcd/efg?name=alex&family=moore   (does not work)
www.example.com/show/abcdefg?name=alex&family=moore   (works)
www.example.com/show/abcd-efg?name=alex&family=moore   (works)

It should accept any sort of character from the value that is located between www.example.com/show/ and ?. Please note the value that would be located there would be a single value not name of an action.

For example: /show/abcd/efg and /show/lkikf?name=Jack in which the first request should redirect user to the page abcd/efg (because thats a name) and the second one should redirect user to the page lkikf along with value of parameter name.

I have following controller to handle it but the issue is when I have / in the address the controller is unable to handle it.

@RequestMapping(value = "/{mystring:.*}", method = RequestMethod.GET)
public String handleReqShow(
            @PathVariable String mystring,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String family, Model model)     {

I used following regex which did not work.

 /^[ A-Za-z0-9_@./#&+-]*$/

Body:
You could encode slashes on UI with %2f: http://www.example.com/show/abcd%2fefg?name=alex&family=moore.
Now you should configure Spring to handle slashes. Simple config example:

@RestController
public class TestController {

    @GetMapping("{testId:.+}")
    public String test(@PathVariable String testId) {
        return testId;
    }

    @GetMapping("{testId:.+}/test/{messageId}")
    public String test2(@PathVariable String testId, @PathVariable String messageId) {
        return testId + " " + messageId;
    }

    //Only if using Spring Security
    @Configuration
    public static class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
        @Bean
        public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
            DefaultHttpFirewall firewall = new DefaultHttpFirewall();
            firewall.setAllowUrlEncodedSlash(true);
            return firewall;
        }
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
        }
    }

    @Configuration
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public static class SpringMvcConfig extends WebMvcConfigurerAdapter {
        @Override
        public void configurePathMatch(PathMatchConfigurer configurer) {
            UrlPathHelper urlPathHelper = new UrlPathHelper();
            urlPathHelper.setUrlDecode(false);
            configurer.setUrlPathHelper(urlPathHelper);
        }
    }

}


问:
Beginner Prolog Stack Overflow
I am working on my very first Prolog assignment, and on recursive problems, I cannot seem to stop overflowing the stack. It's like an addiction; I don't know how to stop.

Let me give you an example. I want to create a function that determines if an object, Y, is a part of another object, X. Here is the database I am working with:

```<code>% Parts Database
has(bicycle,wheel,2).
has(bicycle,handlebar,1).
has(bicycle,brake,2).
has(wheel,hub,1).
has(wheel,spoke,32).
has(bicycle,frame,1).

has(car,steering_wheel,1).
has(car,stereo,1).
has(car,tires,4).
</code>```

From here, I want to write a function partof(X,Y) that returns true if Y is a part of X. This is what I currently have:

```<code>% Determines if Y is a part of X
partof(X,Y) :-
    has(X,Y,_).
partof(X,Y) :-
    partof(X,Z),
    partof(Z,Y).
</code>```

This works for all true queries, but overflows the stack instead of returning false. For example:

```<code>?- partof(wheel, spoke).
true ;
ERROR: Out of local stack

?- partof(bicycle, spoke).
true ;
ERROR: Out of local stack

?- partof(wheel, X).
X = hub ;
X = spoke ;
ERROR: Out of local stack
</code>```

I know you are all thinking to yourselves, "This dumb idiot, doesn't know what a base case is. Doesn't know how to pull out of recursion." Well, I don't blame you. I feel dumb. Some patient guidance would be very helpful, though. Thanks in advance!

答:
Recursion in Prolog kind-of works as in other programming languages, but it is much more complex in Prolog since there are two independent control flows intertwined within the same run. In traditional imperative languages, either recursion works (and yields a result) or doesn't and thus loops thereby maybe overflowing some stack.

But in Prolog, we may get many interesting answers first, and only after a while we are stuck in an infinite loop. You had quite some luck with your query, you found loops immediately after the first solution/answer. Imagine you would have taken the following query:

```<code>?- partof(X, Y).
   X = bicycle, Y = wheel
;  X = bicycle, Y = handlebar
;  X = bicycle, Y = brake
;  X = wheel, Y = hub
;  X = wheel, Y = spoke
;  X = bicycle, Y = frame
;  X = car, Y = steering_wheel
;  X = car, Y = stereo
;  X = car, Y = tires
;  X = bicycle, Y = hub
;  X = bicycle, Y = spoke
;  loops. % ERROR: Out of local stack
</code>```

Note that the solutions are not really interesting to us. We were only after this last message.  How many times shall we hit space until we say that a query terminates?  Fortunately, there is a cheaper way out.  We simply add false (a condition that is never true) as an additional goal. Clearly, the query must never have a solution. The only interesting thing that remains is whether or not the query terminates:

```
?- partof(X, Y), <b>false</b>.
   loops. % ERROR: Out of local stack
```

This trick can be extended to your whole program1. Simply add false where you like. The remaining program called a failure slice shares still a lot with your original one: It needs less (or equal) many inferences to execute. Thus, if the failure slice loops, also the original program loops. Here is the minimal looping failure slice for your program:

```
<s>partof(X,Y) :- <b>false</b></s>,
    <s>has(X,Y,_)</s>.
partof(X,Y) :-
    partof(X,Z), <b>false</b>,
    <s>partof(Z,Y)</s>.
```

Note that has/3 has been completely eliminated. In other words, modifying has/3 no matter how will not stop this loop! Never! You need to modify something in the visible part first. There is not much left!

Experienced Prolog programmers see such problems immediately. With the help of a failure-slice you can learn to identify these parts for yourself. And, trust me, for very complex programs, it is very useful to always have the option to check if your intuition is right or not.

And here is another way to define transitive closure using closure/3 and library(lambda):

```<code>partof(X, Y) :-
   closure(\A^B^has(A, B,_), X, Y).
</code>```

1 actually, this only works for pure monotonic programs

Title: Beginner Prolog Stack Overflow

Body:
I am working on my very first Prolog assignment, and on recursive problems, I cannot seem to stop overflowing the stack. It's like an addiction; I don't know how to stop.

Let me give you an example. I want to create a function that determines if an object, Y, is a part of another object, X. Here is the database I am working with:

% Parts Database
has(bicycle,wheel,2).
has(bicycle,handlebar,1).
has(bicycle,brake,2).
has(wheel,hub,1).
has(wheel,spoke,32).
has(bicycle,frame,1).

has(car,steering_wheel,1).
has(car,stereo,1).
has(car,tires,4).

From here, I want to write a function partof(X,Y) that returns true if Y is a part of X. This is what I currently have:

% Determines if Y is a part of X
partof(X,Y) :-
    has(X,Y,_).
partof(X,Y) :-
    partof(X,Z),
    partof(Z,Y).

This works for all true queries, but overflows the stack instead of returning false. For example:

?- partof(wheel, spoke).
true ;
ERROR: Out of local stack

?- partof(bicycle, spoke).
true ;
ERROR: Out of local stack

?- partof(wheel, X).
X = hub ;
X = spoke ;
ERROR: Out of local stack

I know you are all thinking to yourselves, "This dumb idiot, doesn't know what a base case is. Doesn't know how to pull out of recursion." Well, I don't blame you. I feel dumb. Some patient guidance would be very helpful, though. Thanks in advance!

Body:
Recursion in Prolog kind-of works as in other programming languages, but it is much more complex in Prolog since there are two independent control flows intertwined within the same run. In traditional imperative languages, either recursion works (and yields a result) or doesn't and thus loops thereby maybe overflowing some stack.

But in Prolog, we may get many interesting answers first, and only after a while we are stuck in an infinite loop. You had quite some luck with your query, you found loops immediately after the first solution/answer. Imagine you would have taken the following query:

?- partof(X, Y).
   X = bicycle, Y = wheel
;  X = bicycle, Y = handlebar
;  X = bicycle, Y = brake
;  X = wheel, Y = hub
;  X = wheel, Y = spoke
;  X = bicycle, Y = frame
;  X = car, Y = steering_wheel
;  X = car, Y = stereo
;  X = car, Y = tires
;  X = bicycle, Y = hub
;  X = bicycle, Y = spoke
;  loops. % ERROR: Out of local stack

Note that the solutions are not really interesting to us. We were only after this last message.  How many times shall we hit space until we say that a query terminates?  Fortunately, there is a cheaper way out.  We simply add false (a condition that is never true) as an additional goal. Clearly, the query must never have a solution. The only interesting thing that remains is whether or not the query terminates:

?- partof(X, Y), false.
   loops. % ERROR: Out of local stack

This trick can be extended to your whole program1. Simply add false where you like. The remaining program called a failure slice shares still a lot with your original one: It needs less (or equal) many inferences to execute. Thus, if the failure slice loops, also the original program loops. Here is the minimal looping failure slice for your program:

<s>partof(X,Y) :- false</s>,
    <s>has(X,Y,_)</s>.
partof(X,Y) :-
    partof(X,Z), false,
    <s>partof(Z,Y)</s>.

Note that has/3 has been completely eliminated. In other words, modifying has/3 no matter how will not stop this loop! Never! You need to modify something in the visible part first. There is not much left!

Experienced Prolog programmers see such problems immediately. With the help of a failure-slice you can learn to identify these parts for yourself. And, trust me, for very complex programs, it is very useful to always have the option to check if your intuition is right or not.

And here is another way to define transitive closure using closure/3 and library(lambda):

partof(X, Y) :-
   closure(\A^B^has(A, B,_), X, Y).

1 actually, this only works for pure monotonic programs

ContentLicense: CC BY-SA 4.0


问:
Scala dynamic String interpolation - Read from properties file
I tried to get the log message from message.properties and did string interpolation with that log message.In this time,The log message is not interpolated with original message.

I am not able to get string interpolated result and am getting the output as log message what i have specified in properties file

Here I dont want to hard code any log message in scala file,Instead of this,I want to get all message from properties file and redirected into application log after interpolating string value.

```<code>import com.typesafe.config.ConfigFactory
import grizzled.slf4j.Logging
object Test extends Logging {
  def main(args: Array[String]){
    val subjectArea="Member"
    val  messageProp = ConfigFactory.load("message.properties")
    val log=messageProp.getString("log.subject.area")
    debug(s"$log")
  }
}

message.properties
log.subject.area=The Subject Area : $subjectArea
</code>```

Console Output: The Subject Area : $subjectArea
i want this output : The Subject Area : Member

Thanks in advance!!!
Test.scala
message.propeties

答:
This is not a string interpolation problem. You want a lightweight templating engine (e.g. http://jtwig.org/documentation/quick-start/application or something else). I feel that most of them would be an overkill if your problem is as simple as in the snippet you've provided.

If you want to do something more or less complex, then sure, go with template engines.

Otherwise, I'd just go with string substitution.

Body:
I tried to get the log message from message.properties and did string interpolation with that log message.In this time,The log message is not interpolated with original message.

I am not able to get string interpolated result and am getting the output as log message what i have specified in properties file

Here I dont want to hard code any log message in scala file,Instead of this,I want to get all message from properties file and redirected into application log after interpolating string value.

import com.typesafe.config.ConfigFactory
import grizzled.slf4j.Logging
object Test extends Logging {
  def main(args: Array[String]){
    val subjectArea="Member"
    val  messageProp = ConfigFactory.load("message.properties")
    val log=messageProp.getString("log.subject.area")
    debug(s"$log")
  }
}

message.properties
log.subject.area=The Subject Area : $subjectArea

Console Output: The Subject Area : $subjectArea
i want this output : The Subject Area : Member

Thanks in advance!!!
Test.scala
message.propeties


问:
How can I override the max heap size (Xmx) for junit tests in Intellij? (setting in the Edit Configuration dialog just prepends it)
I want to set the max heap size for a junit test in intellij, and the value that I enter into the VM Options field is merely prepended. Without attempting to override Xmx, the run command shown by ps aux is the following:

```<code>/usr/lib/jvm/java-8-oracle/bin/java -ea -javaagent:/home/ubuntu/.m2/repository/org/jmockit/jmockit/1.8/jmockit-1.8.jar -Xmx1024m -Didea.test.cyclic.buffer.size=1048576 ...
</code>```

If I add the custom Xmx config, it shows up, but the later value of 1024m is still appended to the run command:

```<code>/usr/lib/jvm/java-8-oracle/bin/java -ea -Xmx4G -javaagent:/home/ubuntu/.m2/repository/org/jmockit/jmockit/1.8/jmockit-1.8.jar -Xmx1024m -Didea.test.cyclic.buffer.size=1048576 ...
</code>```

How do I correctly set or override Xmx here? I searched in ~/idea-IC-172.3317.76/bin/idea.properties and in ~/.IdeaIC2017.2/config/ but couldn't find anything.

答: Check your pom.xml files, Maven options defined for the tests override IDEA defaults, it's by design.</p>

Body:
I want to set the max heap size for a junit test in intellij, and the value that I enter into the VM Options field is merely prepended. Without attempting to override Xmx, the run command shown by ps aux is the following:

/usr/lib/jvm/java-8-oracle/bin/java -ea -javaagent:/home/ubuntu/.m2/repository/org/jmockit/jmockit/1.8/jmockit-1.8.jar -Xmx1024m -Didea.test.cyclic.buffer.size=1048576 ...

If I add the custom Xmx config, it shows up, but the later value of 1024m is still appended to the run command:

/usr/lib/jvm/java-8-oracle/bin/java -ea -Xmx4G -javaagent:/home/ubuntu/.m2/repository/org/jmockit/jmockit/1.8/jmockit-1.8.jar -Xmx1024m -Didea.test.cyclic.buffer.size=1048576 ...

How do I correctly set or override Xmx here? I searched in ~/idea-IC-172.3317.76/bin/idea.properties and in ~/.IdeaIC2017.2/config/ but couldn't find anything.


问:
How to checkout from PTC Integrity in Jenkins Pipeline SCM Step Plugin
I want to add a process step in my pipeline, that checks out a project from PTC Integrity. There is a example in the Snippet Generator for a checkin but it is not built correctly, so I can not take this for orientation.

As PTC Integrity is not properly documented for the use with SCM Step Plugin (although supported according to their compability list) I have no idea how to do this.

My first step was to Find out what if there is a Integrity SCM class with this pipeline script:

```<code>node {
   checkout scm: [$class: 'IntegritySCM']
}
</code>```

This throws as expected an IllegalArgumentException:

```<code>java.lang.IllegalStateException: cannot call getRootUrlFromRequest from outside a request handling thread
at jenkins.model.Jenkins.getRootUrlFromRequest(Jenkins.java:2366)
at hudson.scm.IntegritySCM.<init>(IntegritySCM.java:113)
Caused: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.jenkinsci.plugins.structs.describable.DescribableModel.instantiate(DescribableModel.java:260)
Caused: java.lang.IllegalArgumentException: Could not instantiate {serverConfig=d917f329-9826-4ffa-8bbd-de68271c4abd}
for IntegritySCM(browser: IntegrityRepositoryBrowser{IntegrityWebUI(url: String)}, serverConfig: String, userName: String, password: String, configPath: String, includeList: String,
excludeList: String, cleanCopy: boolean, lineTerminator: String, validCheckpoint: boolean, freezeMembers: boolean, noCheckout: boolean,
restoreTimestamp: boolean, skipAuthorInfo: boolean, checkpointBeforeBuild: boolean, checkpointLabel: String,
alternateWorkspace: String, fetchChangedWorkspaceFiles: boolean, deleteNonMembers: boolean, checkoutThreadPoolSize: int, configurationName: String)
</code>```

From this I can conclude which arguments can be given for the checkout command.
Now my question is, how can I build the checkout command in the pipeline script?

I saw an example on the github page of the scm step plugin but for mercurial which does it like this:

```<code>checkout scm: [$class: 'MercurialSCM', 'source': '....', clean: true...]
</code>```

But I can't apply this to Integrity. E.g. I don't know how to tell the command the path of the project I want to checkout.

答:
The pipeline snippet generator tool can be used to generate a pipeline syntax for any SCM classes supported by Pipeline. You can take a look here: https://jenkins.io/blog/2016/05/31/pipeline-snippetizer/

A sample pipeline snippet is something like this:

```<code>checkout([$class: 'IntegritySCM', checkpointBeforeBuild: false, configPath: '\integrity project configuration path\', configurationName: '7fc7dc75-f94e-4cc7-ab57-558f611d0fb8', deleteNonMembers: false, fetchChangedWorkspaceFiles: false, localClient: true, password: '{AQAAABAAAAAQ7YBJmtuzpndmmu/eUEL3v80g/oF3g+lzpM1S1JHkk5E=}', restoreTimestamp: false, serverConfig: '836d9a67-b82d-4cf3-ba06-c4557a18306b', skipAuthorInfo: false])
</code>```

Body:
I want to add a process step in my pipeline, that checks out a project from PTC Integrity. There is a example in the Snippet Generator for a checkin but it is not built correctly, so I can not take this for orientation.

As PTC Integrity is not properly documented for the use with SCM Step Plugin (although supported according to their compability list) I have no idea how to do this.

My first step was to Find out what if there is a Integrity SCM class with this pipeline script:

node {
   checkout scm: [$class: 'IntegritySCM']
}

This throws as expected an IllegalArgumentException:

java.lang.IllegalStateException: cannot call getRootUrlFromRequest from outside a request handling thread
at jenkins.model.Jenkins.getRootUrlFromRequest(Jenkins.java:2366)
at hudson.scm.IntegritySCM.<init>(IntegritySCM.java:113)
Caused: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.jenkinsci.plugins.structs.describable.DescribableModel.instantiate(DescribableModel.java:260)
Caused: java.lang.IllegalArgumentException: Could not instantiate {serverConfig=d917f329-9826-4ffa-8bbd-de68271c4abd}
for IntegritySCM(browser: IntegrityRepositoryBrowser{IntegrityWebUI(url: String)}, serverConfig: String, userName: String, password: String, configPath: String, includeList: String,
excludeList: String, cleanCopy: boolean, lineTerminator: String, validCheckpoint: boolean, freezeMembers: boolean, noCheckout: boolean,
restoreTimestamp: boolean, skipAuthorInfo: boolean, checkpointBeforeBuild: boolean, checkpointLabel: String,
alternateWorkspace: String, fetchChangedWorkspaceFiles: boolean, deleteNonMembers: boolean, checkoutThreadPoolSize: int, configurationName: String)

From this I can conclude which arguments can be given for the checkout command.
Now my question is, how can I build the checkout command in the pipeline script?

I saw an example on the github page of the scm step plugin but for mercurial which does it like this:

checkout scm: [$class: 'MercurialSCM', 'source': '....', clean: true...]

But I can't apply this to Integrity. E.g. I don't know how to tell the command the path of the project I want to checkout.

Body:
The pipeline snippet generator tool can be used to generate a pipeline syntax for any SCM classes supported by Pipeline. You can take a look here: https://jenkins.io/blog/2016/05/31/pipeline-snippetizer/

A sample pipeline snippet is something like this:

checkout([$class: 'IntegritySCM', checkpointBeforeBuild: false, configPath: '\integrity project configuration path\', configurationName: '7fc7dc75-f94e-4cc7-ab57-558f611d0fb8', deleteNonMembers: false, fetchChangedWorkspaceFiles: false, localClient: true, password: '{AQAAABAAAAAQ7YBJmtuzpndmmu/eUEL3v80g/oF3g+lzpM1S1JHkk5E=}', restoreTimestamp: false, serverConfig: '836d9a67-b82d-4cf3-ba06-c4557a18306b', skipAuthorInfo: false])


问:
Why should I learn Lisp?
I really feel that I should learn Lisp and there are plenty of good resources out there to help me do it.

I'm not put off by the complicated syntax, but where in "traditional commercial programming" would I find places it would make sense to use it instead of a procedural language.

Is there a commercial killer-app out there that's been written in Lisp ?

答:
Complicated syntax? The beauty of lisp is that it has a ridiculously simple syntax. It's just a list, where each element of the list can be either another list or an elementary data type.

It's worth learning because of the way it enhances your coding ability to think about and use functions as just another data type. This will improve upon the way you code in an imperative and/or object-oriented language because it will allow you to be more mentally flexible with how your code is structured.

Title: Why should I learn Lisp?

LastEditorDisplayName: Mark Biek


问:
Trouble Layering in CSS
I'm trying to layer some elements using z-index and it's not working at all.

Here's the CSS:

```<code>    ul.ui-tabs-nav {list-style:none; float:left; display:block;padding:0; margin:6px 0px 0px 0px; width:85px;  }
    ul.ui-tabs-nav li {padding:0px 7px; height:64px; background:url(/templates/gspm_home/images/tab_bak.gif) top left no-repeat;}
    ul.ui-tabs-nav li.ui-tabs-selected {z-index:100; display:block; background:url(/templates/gspm_home/images/tab_bak_current.gif) top left no-repeat; overflow:visible;  }
.ui-tabs-panel { z-index:1; width:360px; height:256px; padding:0;background:#fff; float:right; margin-top:6px;}
</code>```

When the ui-tabs-selected class is invoked, there is supposed to be a background image that layer above the ui-tabs-panel. But nothing happens.

Here is the html markup:

```<code><ul class="ui-tabs-nav">
    <li class=""> <a href="#1" class="blue">
    Link</a></li>
    <li class="ui-tabs-selected"> <a href="#2" class="blue">Link</a></li>
    <li class=""> <a href="#3" class="blue"></a></li>
    <li class=""> <a href="#4" class="blue">Link</a></li></ul>

                <div style="" class="leading ui-tabs-panel ui-tabs-hide" id="1">
                Content
                </div>
                <div style="" class="leading ui-tabs-panel" id="2">
                Content
                </div>
                <div style="" class="leading ui-tabs-panel ui-tabs-hide" id="3">
                Content
                        </div>
                <div style="" class="leading ui-tabs-panel ui-tabs-hide" id="4">
                Content
                </div>
</code>```

What am I missing?

www.gspm.org - site's under construction. The section in question are the rotating tabs. Uses jQuery UI Tabs plugin.

答:
You need to use:

```<code>ul.ui-tabs-nav
{
    list-style:none;
    padding:0;
    margin:6px 0px 0px 0px;
    width:85px;
    position: absolute;
    z-index: 100;
}

ul.ui-tabs-nav li.ui-tabs-selected
{
    display:block;
    background: url(/templates/gspm_home/images/tab_bak_current.gif) top left no-repeat;
    width: 100px
}
</code>```

z-index won't take effect unless the element has position absolute or relative iirc.
You also need to set a width on the selected li - a background image won't "escape" even with overflow: visible; (which you can now remove).

This worked for me in FireBug - hopefully it will work when you put it in code.

OwnerDisplayName: Jared

Title: Trouble Layering in CSS

Body:
I'm trying to layer some elements using z-index and it's not working at all.

Here's the CSS:

    ul.ui-tabs-nav {list-style:none; float:left; display:block;padding:0; margin:6px 0px 0px 0px; width:85px;  }
    ul.ui-tabs-nav li {padding:0px 7px; height:64px; background:url(/templates/gspm_home/images/tab_bak.gif) top left no-repeat;}
    ul.ui-tabs-nav li.ui-tabs-selected {z-index:100; display:block; background:url(/templates/gspm_home/images/tab_bak_current.gif) top left no-repeat; overflow:visible;  }
.ui-tabs-panel { z-index:1; width:360px; height:256px; padding:0;background:#fff; float:right; margin-top:6px;}

When the ui-tabs-selected class is invoked, there is supposed to be a background image that layer above the ui-tabs-panel. But nothing happens.

Here is the html markup:

    Link

 Link

 Link

                Content

                Content

                Content

                Content

What am I missing?

www.gspm.org - site's under construction. The section in question are the rotating tabs. Uses jQuery UI Tabs plugin.

LastEditorDisplayName: Jared

Body:
You need to use:

ul.ui-tabs-nav
{
    list-style:none;
    padding:0;
    margin:6px 0px 0px 0px;
    width:85px;
    position: absolute;
    z-index: 100;
}

ul.ui-tabs-nav li.ui-tabs-selected
{
    display:block;
    background: url(/templates/gspm_home/images/tab_bak_current.gif) top left no-repeat;
    width: 100px
}

z-index won't take effect unless the element has position absolute or relative iirc.
You also need to set a width on the selected li - a background image won't "escape" even with overflow: visible; (which you can now remove).

This worked for me in FireBug - hopefully it will work when you put it in code.

OwnerDisplayName: RoBorg


问:
loading multiple beans in spring boot using soap web service
I  am trying to write soap webservice using spring boot.I have 2 xsd's. REL-6-MM7-1-4.xsd which is dependent on SoapEnvelope.xsd.

Can anyone help me in resolving it.

```<code>import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.validation.XmlValidator;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
import org.springframework.xml.xsd.XsdSchemaCollection;

@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
    @Bean
    public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        servlet.setTransformWsdlLocations(true);
        return new ServletRegistrationBean(servlet, "/ws/*");
    }

    @Bean(name = "REL-6-MM7-1-4")
    public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchemaCollection xsdSchemaCollection) {
        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
        wsdl11Definition.setPortTypeName("MMSPort");
        wsdl11Definition.setLocationUri("/ws");
        wsdl11Definition.setTargetNamespace("http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4");
        wsdl11Definition.setSchemaCollection(xsdSchemaCollection);
        return wsdl11Definition;
    }

    @Bean
    public XsdSchemaCollection getXsdCollection() {
        return new XsdSchemaCollection() {

            public XsdSchema[] getXsdSchemas() {
                return new XsdSchema[]{new SimpleXsdSchema(new ClassPathResource("REL-6-MM7-1-4.xsd")), new SimpleXsdSchema(new ClassPathResource("SoapEnvelope.xsd"))};
            }

            public XmlValidator createValidator() {
                throw new UnsupportedOperationException();
            }
        };
    }
</code>```

I have tried to expose 2 beans but when i startup the application i get following error.

Error creating bean with name 'REL-6-MM7-1-4' defined in class path resource [hello/WebServiceConfig.class]: Invocation of init method failed; nested exception is java.lang.NullPointerException

答:
Try to modify your method as below it should work.</p>

```<code>    @Bean
    public XsdSchema studentSchema() {
        return new SimpleXsdSchema(new ClassPathResource("school.xsd"));
    }

    @Bean
    public XsdSchema employeeSchema() {
        return new SimpleXsdSchema(new ClassPathResource("employee.xsd"));
    }

     @Bean
        public XsdSchemaCollection getXsdCollection() {

        return  new XsdSchemaCollection() {

        @Override
        public XmlValidator createValidator() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public XsdSchema[] getXsdSchemas() {
            return new XsdSchema[]{studentSchema(),employeeSchema()};
        }};
</code>```

Body:
I  am trying to write soap webservice using spring boot.I have 2 xsd's. REL-6-MM7-1-4.xsd which is dependent on SoapEnvelope.xsd.

Can anyone help me in resolving it.

import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.validation.XmlValidator;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
import org.springframework.xml.xsd.XsdSchemaCollection;

@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
    @Bean
    public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        servlet.setTransformWsdlLocations(true);
        return new ServletRegistrationBean(servlet, "/ws/*");
    }

    @Bean(name = "REL-6-MM7-1-4")
    public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchemaCollection xsdSchemaCollection) {
        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
        wsdl11Definition.setPortTypeName("MMSPort");
        wsdl11Definition.setLocationUri("/ws");
        wsdl11Definition.setTargetNamespace("http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4");
        wsdl11Definition.setSchemaCollection(xsdSchemaCollection);
        return wsdl11Definition;
    }

    @Bean
    public XsdSchemaCollection getXsdCollection() {
        return new XsdSchemaCollection() {

            public XsdSchema[] getXsdSchemas() {
                return new XsdSchema[]{new SimpleXsdSchema(new ClassPathResource("REL-6-MM7-1-4.xsd")), new SimpleXsdSchema(new ClassPathResource("SoapEnvelope.xsd"))};
            }

            public XmlValidator createValidator() {
                throw new UnsupportedOperationException();
            }
        };
    }

I have tried to expose 2 beans but when i startup the application i get following error.

Error creating bean with name 'REL-6-MM7-1-4' defined in class path resource [hello/WebServiceConfig.class]: Invocation of init method failed; nested exception is java.lang.NullPointerException

Body:
Try to modify your method as below it should work.

    @Bean
    public XsdSchema studentSchema() {
        return new SimpleXsdSchema(new ClassPathResource("school.xsd"));
    }

    @Bean
    public XsdSchema employeeSchema() {
        return new SimpleXsdSchema(new ClassPathResource("employee.xsd"));
    }

     @Bean
        public XsdSchemaCollection getXsdCollection() {

        return  new XsdSchemaCollection() {

        @Override
        public XmlValidator createValidator() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public XsdSchema[] getXsdSchemas() {
            return new XsdSchema[]{studentSchema(),employeeSchema()};
        }};


问:
Twilio TwiML app XML error
I have a TwiML app with this code in the Connect action of the CallController. This code is taken straight from the Twilio demos.

```<code>[HttpPost]
public virtual ActionResult Connect(string phoneNumber, string called)
{
    var response = new VoiceResponse();

    var dial = new Dial(callerId: "+6138595????");
    if (phoneNumber != null)
    {
        dial.Number(phoneNumber);
    }
    else
    {
        dial.Client("support_agent");
    }
    response.Dial(dial);

    return TwiML(response);
}
</code>```

When this is called it raises the error "Data at the root level is invalid. Line 1, position 1."

The XML this generates is

```<code><?xml version="1.0" encoding="utf-8"?>
<Response>
  <Dial callerId="+6138595????">
    <Client>support_agent</Client>
  </Dial>
</Response>
</code>```

答:
I had the same problem we solved it in our WebApi by skipping the Twilio sdk and generating the xml by ourselves.

I hope this will work for you too:

```<code>[HttpPost]
public virtual HttpResponseMessage Connect(string phoneNumber, string called)
{
            string twiml = $"<?xml version=\"1.0\" encoding=\"utf-8\"?><Response><Dial callerId=\"{phoneNumber}\"><Client>support_agent</Client></Dial></Response>";
            var xmlResponse = new HttpResponseMessage();
            xmlResponse.Content = new StringContent(twiml, Encoding.UTF8, "text/xml");

            return xmlResponse;
}
</code>```

Please notice that there are no end of lines - "\n", \r", etc.

Title: Twilio TwiML app XML error

Body:
I have a TwiML app with this code in the Connect action of the CallController. This code is taken straight from the Twilio demos.

[HttpPost]
public virtual ActionResult Connect(string phoneNumber, string called)
{
    var response = new VoiceResponse();

    var dial = new Dial(callerId: "+6138595????");
    if (phoneNumber != null)
    {
        dial.Number(phoneNumber);
    }
    else
    {
        dial.Client("support_agent");
    }
    response.Dial(dial);

    return TwiML(response);
}

When this is called it raises the error "Data at the root level is invalid. Line 1, position 1."

The XML this generates is

<?xml version="1.0" encoding="utf-8"?>
<Response>
  <Dial callerId="+6138595????">
    <Client>support_agent</Client>
  </Dial>
</Response>

Body:
I had the same problem we solved it in our WebApi by skipping the Twilio sdk and generating the xml by ourselves.

I hope this will work for you too:

[HttpPost]
public virtual HttpResponseMessage Connect(string phoneNumber, string called)
{
            string twiml = $"<?xml version=\"1.0\" encoding=\"utf-8\"?><Response><Dial callerId=\"{phoneNumber}\"><Client>support_agent</Client></Dial></Response>";
            var xmlResponse = new HttpResponseMessage();
            xmlResponse.Content = new StringContent(twiml, Encoding.UTF8, "text/xml");

            return xmlResponse;
}

Please notice that there are no end of lines - "\n", \r", etc.


问:
Core Data 'File "Contents" couldn't be opened'
I made the silly mistake and I accidentially touch my current Core Data model instead the new version one I just created. So I went to source control and reverted the changes inside the **.xcdatamodeld group. However I have now a zombie entry in the project structure inside this group (its the new version **.xcdatamodel I have created) that I can't open (message like in the title). Probably because reverting deleting the files but somehow the reference is still there.

Just a little bit annoying. Tried cleaning, closing & reopening.

答:
I had two files with the same name, but only one showed in Xcode. This fixed it:

Locate the **.xcdatamodeld file in your project

Right click and select 'Show Package Contents'

Locate the two files with the same name

Delete the one that is Zero bytes in size

Rebuild and smile


问:
UITapGesture in UITableview header
I trying to use expandable tableview in swift. So I added Gesture to header in  tableview, but it does not recognising. Kindly guide me. Just cross check my coding.

MY CODING IS BELOW:

```<code>func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let vvv = tableView.headerViewForSection(section)

        let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        tap.delegate = self
        vvv?.addGestureRecognizer(tap)
        return vvv
    }

    func handleTap(gestureRecognizer: UITapGestureRecognizer)
    {
        if(gestureRecognizer.state == .Ended)
        {
            println("SECTION PRESSED") //NOT ENTERING TO THIS BLOCK
        }
    }
</code>```

答:
In Swift 4 you can add a UITapGestureRecognizer to the header view:</p>

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let headerView = UIView()

    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(headerTap))
    headerView.addGestureRecognizer(tapRecognizer)

    return headerView
}

@objc func headerTap() {
    // Tap action
}
</code>```

Title: UITapGesture in UITableview header

Body:
I trying to use expandable tableview in swift. So I added Gesture to header in  tableview, but it does not recognising. Kindly guide me. Just cross check my coding.

MY CODING IS BELOW:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let vvv = tableView.headerViewForSection(section)

        let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        tap.delegate = self
        vvv?.addGestureRecognizer(tap)
        return vvv
    }

    func handleTap(gestureRecognizer: UITapGestureRecognizer)
    {
        if(gestureRecognizer.state == .Ended)
        {
            println("SECTION PRESSED") //NOT ENTERING TO THIS BLOCK
        }
    }

Body:
In Swift 4 you can add a UITapGestureRecognizer to the header view:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let headerView = UIView()

    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(headerTap))
    headerView.addGestureRecognizer(tapRecognizer)

    return headerView
}

@objc func headerTap() {
    // Tap action
}


问:
Print out all subsets in an array that equal an given sum recursively
I have a weird homework that I have to write a program with a method that takes an array of non-negative integers (array elements can have repeated values) and a value sum as parameters. The method then prints out all the combinations of the elements in array whose sum is equal to sum. The weird part is, the teacher forces us to strictly follow the below structure:

```<code>public class Combinations {

    public static void printCombinations(int[] arr, int sum) {
       // Body of the method
    }

    public static void main(String[] args) {
       // Create 2-3 arrays of integers and 2-3 sums here then call the above
       // method with these arrays and sums to test the correctness of your method
    }

}
</code>```

We are not allow to add neither more methods nor more parameters for the current program. I have researched and understood several ways to do this recursively, but with this restriction, I don't really know how to do it. Therefore, I appreciate if you guys help me out.

EDIT: The array can have repeated elements. Here's an example run of the program.

```<code>arr = {1, 3, 2, 2, 25} and sum = 3
</code>```

Outputs:

(1, 2)  // 1st and 3rd element

(1, 2) // 1st and 4th element

(3) // 2nd element

答:
As the printCombinations() method accepts the integer array as parameter and you are not allowed to add any additional methods. I couldn't think of Recursion without adding an additional method.

Here is a solution, let me know if this helps. And this is not the best way!

```<code>public static void main( String[] args ) throws Exception {
    int arr[] = {1, 3, 2, 2, 25, 1, 1};
    int sum = 8;
    printCombinations(arr, sum);
}

public static void printCombinations(int arr[], int sum){
    int count = 0;
    int actualSum = sum;
    while (count < arr.length) {
        int j = 0;
        int arrCollection[] = new int[arr.length];
        for (int k = 0; k < arrCollection.length; k++){
            arrCollection[k] = -99; // as the array can contain only +ve integers
        }
        for (int i = count; i < arr.length; i++) {
            sum = sum - arr[i];
            if (sum < 0){
                sum = sum + arr[i];
            } else if (sum > 0){
                arrCollection[j++] = arr[i];
            } else if (sum == 0){
                System.out.println("");
                arrCollection[j++] = arr[i];
                int countElements = 0;
                for (int k = 0; k < arrCollection.length; k++){
                    if (arrCollection[k] != -99) {
                        countElements++;
                        System.out.print(arrCollection[k] + " ");
                    }
                }
                if (countElements == 1){
                    i = arr.length -1;
                }
                sum = sum + arr[i];
                j--;
            }
        }
        count++;
        sum = actualSum;
    }
}
</code>```

Body:
I have a weird homework that I have to write a program with a method that takes an array of non-negative integers (array elements can have repeated values) and a value sum as parameters. The method then prints out all the combinations of the elements in array whose sum is equal to sum. The weird part is, the teacher forces us to strictly follow the below structure:

public class Combinations {

    public static void printCombinations(int[] arr, int sum) {
       // Body of the method
    }

    public static void main(String[] args) {
       // Create 2-3 arrays of integers and 2-3 sums here then call the above
       // method with these arrays and sums to test the correctness of your method
    }

}

We are not allow to add neither more methods nor more parameters for the current program. I have researched and understood several ways to do this recursively, but with this restriction, I don't really know how to do it. Therefore, I appreciate if you guys help me out.

EDIT: The array can have repeated elements. Here's an example run of the program.

arr = {1, 3, 2, 2, 25} and sum = 3

Outputs:

(1, 2)  // 1st and 3rd element

(1, 2) // 1st and 4th element

(3) // 2nd element

Body:
As the printCombinations() method accepts the integer array as parameter and you are not allowed to add any additional methods. I couldn't think of Recursion without adding an additional method.

Here is a solution, let me know if this helps. And this is not the best way!

public static void main( String[] args ) throws Exception {
    int arr[] = {1, 3, 2, 2, 25, 1, 1};
    int sum = 8;
    printCombinations(arr, sum);
}

public static void printCombinations(int arr[], int sum){
    int count = 0;
    int actualSum = sum;
    while (count < arr.length) {
        int j = 0;
        int arrCollection[] = new int[arr.length];
        for (int k = 0; k < arrCollection.length; k++){
            arrCollection[k] = -99; // as the array can contain only +ve integers
        }
        for (int i = count; i < arr.length; i++) {
            sum = sum - arr[i];
            if (sum < 0){
                sum = sum + arr[i];
            } else if (sum > 0){
                arrCollection[j++] = arr[i];
            } else if (sum == 0){
                System.out.println("");
                arrCollection[j++] = arr[i];
                int countElements = 0;
                for (int k = 0; k < arrCollection.length; k++){
                    if (arrCollection[k] != -99) {
                        countElements++;
                        System.out.print(arrCollection[k] + " ");
                    }
                }
                if (countElements == 1){
                    i = arr.length -1;
                }
                sum = sum + arr[i];
                j--;
            }
        }
        count++;
        sum = actualSum;
    }
}


问:
What is an efficient SQL query to join to a double maximum in a sub query?
Sorry the title is crap - I could not think of a better way to phrase it. This is my data structure:

```<code>Widget   WidgetTransition
------   ----------------
Id,      WidgetId,
...      TransitionTypeId,
         Cost,
         ...
</code>```

I want a query that will give me a list of details for each widget along with the details of the most expensive (max WidgetTransition.Cost) transition. If a widget has two or more transitions that are 'tied' for the most expensive transition, the details of the most recent transition (max WidgetTransition.WidgetId) should be used. If the widget has no transitions, it should not appear in the results. This is the best that I could come up with:

```<code>SELECT *
FROM   Widget
JOIN   WidgetTransition
ON     WidgetTransition.WidgetId = Widget.Id
AND    WidgetTransition.Cost = (
       SELECT Max(MostExpensiveTransition.Cost)
       FROM   WidgetTransition MostExpensiveTransition
       WHERE  MostExpensiveTransition.WidgetId = Widget.Id
       )
</code>```

This almost works, but has two problems.

Doesn't deal with tied transitions properly. If a widget has two or more tied transitions, each transition will appear in the results, instead of the most recent.

With large data sets, the query is sloooow. The Sybase database that I am running it on will do two table scans (WidgetTransition.Cost is not in the index) on WidgetTransition for each widget. Presumably one is for the join and one to find the max cost.

Is there a better way to write this query that fixes the tied problem and/or runs more efficiently? I want to avoid using T-SQL or a stored procedure.

答:
If I understand you correctly this will do what you want.
Don't know about performance. You have to test that and try to figure out what indexes is helpful.</p>

```<code>declare @Widget table (ID int)
declare @WidgetTransition table (WidgetID int, TransitionTypeID int, Cost int)

insert into @Widget values (1)
insert into @Widget values (2)
insert into @Widget values (3)

insert into @WidgetTransition values (1, 1, 1)
insert into @WidgetTransition values (1, 2, 2)
insert into @WidgetTransition values (2, 1, 2)
insert into @WidgetTransition values (2, 2, 12)
insert into @WidgetTransition values (2, 3, 12)

select *
from @Widget as Widget
  inner join @WidgetTransition as WidgetTransition
    on Widget.ID = WidgetTransition.WidgetID
  inner join
    ( select Widget.ID, max(WT.TransitionTypeID) as TrasitionTypeID
      from @Widget as Widget
        inner join
          ( select WidgetID, max(Cost) as Cost
            from @WidgetTransition
            group by WidgetID
          ) as MaxCost
          on Widget.ID = MaxCost.WidgetID
        inner join @WidgetTransition as WT
          on Widget.ID = WT.WidgetID and
             MaxCost.Cost = WT.Cost
        group by Widget.ID
    ) as MaxTransitionTypeID
    on Widget.ID = MaxTransitionTypeID.ID and
       WidgetTransition.TransitionTypeID = MaxTransitionTypeID.TrasitionTypeID
</code>```

Body:
Sorry the title is crap - I could not think of a better way to phrase it. This is my data structure:

Widget   WidgetTransition
------   ----------------
Id,      WidgetId,
...      TransitionTypeId,
         Cost,
         ...

I want a query that will give me a list of details for each widget along with the details of the most expensive (max WidgetTransition.Cost) transition. If a widget has two or more transitions that are 'tied' for the most expensive transition, the details of the most recent transition (max WidgetTransition.WidgetId) should be used. If the widget has no transitions, it should not appear in the results. This is the best that I could come up with:

SELECT *
FROM   Widget
JOIN   WidgetTransition
ON     WidgetTransition.WidgetId = Widget.Id
AND    WidgetTransition.Cost = (
       SELECT Max(MostExpensiveTransition.Cost)
       FROM   WidgetTransition MostExpensiveTransition
       WHERE  MostExpensiveTransition.WidgetId = Widget.Id
       )

This almost works, but has two problems.

Doesn't deal with tied transitions properly. If a widget has two or more tied transitions, each transition will appear in the results, instead of the most recent.

With large data sets, the query is sloooow. The Sybase database that I am running it on will do two table scans (WidgetTransition.Cost is not in the index) on WidgetTransition for each widget. Presumably one is for the join and one to find the max cost.

Is there a better way to write this query that fixes the tied problem and/or runs more efficiently? I want to avoid using T-SQL or a stored procedure.

Body:
If I understand you correctly this will do what you want.
Don't know about performance. You have to test that and try to figure out what indexes is helpful.

declare @Widget table (ID int)
declare @WidgetTransition table (WidgetID int, TransitionTypeID int, Cost int)

insert into @Widget values (1)
insert into @Widget values (2)
insert into @Widget values (3)

insert into @WidgetTransition values (1, 1, 1)
insert into @WidgetTransition values (1, 2, 2)
insert into @WidgetTransition values (2, 1, 2)
insert into @WidgetTransition values (2, 2, 12)
insert into @WidgetTransition values (2, 3, 12)

select *
from @Widget as Widget
  inner join @WidgetTransition as WidgetTransition
    on Widget.ID = WidgetTransition.WidgetID
  inner join
    ( select Widget.ID, max(WT.TransitionTypeID) as TrasitionTypeID
      from @Widget as Widget
        inner join
          ( select WidgetID, max(Cost) as Cost
            from @WidgetTransition
            group by WidgetID
          ) as MaxCost
          on Widget.ID = MaxCost.WidgetID
        inner join @WidgetTransition as WT
          on Widget.ID = WT.WidgetID and
             MaxCost.Cost = WT.Cost
        group by Widget.ID
    ) as MaxTransitionTypeID
    on Widget.ID = MaxTransitionTypeID.ID and
       WidgetTransition.TransitionTypeID = MaxTransitionTypeID.TrasitionTypeID


问:
Any simple php lib to auth with Google, FB, Twitter
Is there something like Hybridauth3, Loginza, or uLogin (but not those as I understand they are not supported by the teams anymore)? Hybridauth is too complex for me for simple auth.</p>

答:
Have you looked at thephpleague's package. Their pakages are always well maintained.

https://github.com/thephpleague/oauth2-client

and even specifics for:

Google (https://github.com/thephpleague/oauth2-google) and

Facebook (https://github.com/thephpleague/oauth2-facebook)


问:
how to highlight the selected menu in angular 4
I am trying to highlight the selected menu but unable to get an idea.

Below code is menu with sub-menus, menus come from JSON.

HTML

```<code><div *ngFor="let values of val">
    <mat-expansion-panel class="mat-ripple" mat-button routerLink=".">
        <mat-expansion-panel-header expandedHeight="48px" collapsedHeight="48px">
            <mat-panel-title>
                <md-icon class="mat-icon mat-list-icon material-icons">
                    {{values.titleImage}}
                </md-icon>
                <div class="menu-list-text">
                    {{values.titleName}}
                </div>
            </mat-panel-title>
        </mat-expansion-panel-header>
        <a class="sidenav-link mat-list-item mat-ripple"
           mat-button
           routerLink="."
           *ngFor="let subTitleVal of values.subTitle">
            <div class="mat-list-item-content">
                <span md-line="">{{subTitleVal.titleName}}</span>
            </div>
        </a>
    </mat-expansion-panel>
</div>
</code>```

JSON

```<code>val: any;
val = [{
    'titleKey': 'AAA',
    'titleName': ' Menu1',
    'titleImage': 'Icon1',
    'subTitle': [{
        'titleKey': 'AAA',
        'titleName': 'SubMenu1',
        'action': 'ACC',
    }]
}, {
    'titleKey': 'BBB',
    'titleName': 'Menu2',
    'titleImage': 'Icon2',
    'subTitle': [{
        'titleKey': 'BBB',
        'titleName': 'SubMenu2',
        'action': 'FT',
    }]
}, {
    'titleKey': 'CCC',
    'titleName': 'Menu3',
    'titleImage': 'Icon3',
    'subTitle': [{
        'titleKey': 'CCC',
        'titleName': 'SubMenu3',
        'action': 'BP',
    }]
}];
</code>```

How to add the class when user selects a particular sub-menu?

答: You can use routerLinkActive attribute on a element to specify css class to be used for the link that corresponds to the selected route.

Body:
I am trying to highlight the selected menu but unable to get an idea.

Below code is menu with sub-menus, menus come from JSON.

HTML

    <mat-expansion-panel class="mat-ripple" mat-button routerLink=".">
        <mat-expansion-panel-header expandedHeight="48px" collapsedHeight="48px">
            <mat-panel-title>
                <md-icon class="mat-icon mat-list-icon material-icons">
                    {{values.titleImage}}
                </md-icon>

                    {{values.titleName}}

            </mat-panel-title>
        </mat-expansion-panel-header>

                {{subTitleVal.titleName}}

    </mat-expansion-panel>

JSON

val: any;
val = [{
    'titleKey': 'AAA',
    'titleName': ' Menu1',
    'titleImage': 'Icon1',
    'subTitle': [{
        'titleKey': 'AAA',
        'titleName': 'SubMenu1',
        'action': 'ACC',
    }]
}, {
    'titleKey': 'BBB',
    'titleName': 'Menu2',
    'titleImage': 'Icon2',
    'subTitle': [{
        'titleKey': 'BBB',
        'titleName': 'SubMenu2',
        'action': 'FT',
    }]
}, {
    'titleKey': 'CCC',
    'titleName': 'Menu3',
    'titleImage': 'Icon3',
    'subTitle': [{
        'titleKey': 'CCC',
        'titleName': 'SubMenu3',
        'action': 'BP',
    }]
}];

How to add the class when user selects a particular sub-menu?


问:
Firebase not displaying rich push notification
I am using firebase notification in my application. I want to send rich notification but firebase console don't have UI for same. So I am trying to send the payload using postman.

I have created Notification Service Extension for handling content but it never gets called.

Deployment target in xCode is iOS 10.0 and iPad has iOS 11

Json payload(Not Working):

```<code>  {
    "to":"/topics/dev_news",
   "mutable_content": true,
   "data":
   {
        "attachment-url":"my image url",
        "media_type":"image"

   }

}
</code>```

FYI:
I am able to receive push if I add "notification" key-value in payload.

Json payload(Working but without media):

```<code>{
    "to":"/topics/dev_news",
   "mutable_content": true,
   "data":
   {
        "attachment-url":"my image url",
        "media_type":"image"

   },
   "notification" : {
    "title" : "demo push",
    "body" : "this is push body"
   }

}
</code>```

Any idea about this??

答:
Answering to my own question, I was searching for attachment-url in data dictionary (which I was passing in the payload) in service extension class. But attachment-url comes directly in the content.userInfo (It is not wrapped inside the data dictionary) in extension class.

Wondering how I can make such a silly mistake..!! :D

Body:
I am using firebase notification in my application. I want to send rich notification but firebase console don't have UI for same. So I am trying to send the payload using postman.

I have created Notification Service Extension for handling content but it never gets called.

Deployment target in xCode is iOS 10.0 and iPad has iOS 11

Json payload(Not Working):

  {
    "to":"/topics/dev_news",
   "mutable_content": true,
   "data":
   {
        "attachment-url":"my image url",
        "media_type":"image"

   }

}

FYI:
I am able to receive push if I add "notification" key-value in payload.

Json payload(Working but without media):

{
    "to":"/topics/dev_news",
   "mutable_content": true,
   "data":
   {
        "attachment-url":"my image url",
        "media_type":"image"

   },
   "notification" : {
    "title" : "demo push",
    "body" : "this is push body"
   }

}

Any idea about this??


问:
Glide crash because of context 4.3.1
In the new version of the Glide 4.3 I'm trying to use it but it crash whenever I use it and whatever context I passed to it.

this is the error showed to me

```<code>   java.lang.AbstractMethodError: abstract method "void com.bumptech.glide.module.RegistersComponents.registerComponents(android.content.Context, com.bumptech.glide.Glide, com.bumptech.glide.Registry)"
</code>```

this is my code I tried:

```<code>Glide.with(getApplicationContext()).
            load(url)
            .into(imageView);
</code>```

and

```<code>   Glide.with(getContext()).
            load(url)
            .into(imageView);
</code>```

and it give me that warning

```<code>W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
</code>```

and the code in lib in gradle

```<code>compile 'com.github.bumptech.glide:glide:4.3.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'
</code>```

Update1 :
Waring Solved By Adding a class that extends AppGlideModule

```<code>import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;

@GlideModule
public final class MyAppGlideModule extends AppGlideModule {}
</code>```

but the same error still exist

答:
Please Add The Following Method on Your AppGlideModule class

```<code>@Override
public boolean isManifestParsingEnabled() {
  return false;
}
</code>```

To maintain backward compatibility with Glide v3’s GlideModules, Glide still parses AndroidManifest.xml files from both the application and any included libraries and will include any legacy GlideModules listed in the manifest. Although this functionality will be removed in a future version, we’ve retained the behavior for now to ease the transition.
  If you’ve already migrated to the Glide v4 AppGlideModule and LibraryGlideModule, you can disable manifest parsing entirely. Doing so can improve the initial startup time of Glide and avoid some potential problems with trying to parse metadata. To disable manifest parsing, override the isManifestParsingEnabled() method in your AppGlideModule implementation

Check : http://bumptech.github.io/glide/doc/configuration.html

Title: Glide crash because of context 4.3.1

Body:
In the new version of the Glide 4.3 I'm trying to use it but it crash whenever I use it and whatever context I passed to it.

this is the error showed to me

   java.lang.AbstractMethodError: abstract method "void com.bumptech.glide.module.RegistersComponents.registerComponents(android.content.Context, com.bumptech.glide.Glide, com.bumptech.glide.Registry)"

this is my code I tried:

Glide.with(getApplicationContext()).
            load(url)
            .into(imageView);

and

   Glide.with(getContext()).
            load(url)
            .into(imageView);

and it give me that warning

W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored

and the code in lib in gradle

compile 'com.github.bumptech.glide:glide:4.3.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'

Update1 :
Waring Solved By Adding a class that extends AppGlideModule

import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;

@GlideModule
public final class MyAppGlideModule extends AppGlideModule {}

but the same error still exist

Body:
Please Add The Following Method on Your AppGlideModule class

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

To maintain backward compatibility with Glide v3’s GlideModules, Glide still parses AndroidManifest.xml files from both the application and any included libraries and will include any legacy GlideModules listed in the manifest. Although this functionality will be removed in a future version, we’ve retained the behavior for now to ease the transition.
  If you’ve already migrated to the Glide v4 AppGlideModule and LibraryGlideModule, you can disable manifest parsing entirely. Doing so can improve the initial startup time of Glide and avoid some potential problems with trying to parse metadata. To disable manifest parsing, override the isManifestParsingEnabled() method in your AppGlideModule implementation

Check : http://bumptech.github.io/glide/doc/configuration.html