问:
VSCode Extension: How to debug "Activating extension 'undefined_publisher.extension-name' failed: Unexpected token {."
I have created a vscode extension using typescript. Normally, I'd reduce the problem to the smallest possible piece of code, but whenever I try to do that, the problem disappears.

Whenever I try to run the extension (by pressing Ctrl+Shift+P and selecting my extension's command), I get the error: (name changed)

```<code>Activating extension 'undefined_publisher.extension-name' failed: Unexpected token {.
</code>```

Or, in previous versions of the code when I first encountered the error, ...Unexpected token ,.

The error gives no indication of which line or even which file contains the unexpected token. I have tried to run the debugger on the code that loads the extension (vscode devtools), but I couldn't find any obvious "current file" or some such in the call stack.

How do I even begin to debug this?

package.json: (name changed)

```<code>{
    "name": "extension-name",
    "displayName": "Extension Name",
    "description": "Extension Descripton",
    "version": "0.0.1",
    "engines": {
        "vscode": "^1.41.0"
    },
    "categories": [
        "Other"
    ],
    "activationEvents": [
        "onCommand:extension-name.start"
    ],
    "main": "./out/extension.js",
    "contributes": {
        "commands": [
            {
                "command": "extension-name.start",
                "title": "Open a Extension Name window"
            }
        ]
    },
    "scripts": {
        "vscode:prepublish": "npm run compile",
        "compile": "tsc -p ./",
        "watch": "tsc -watch -p ./",
        "pretest": "npm run compile",
        "test": "node ./out/test/runTest.js"
    },
    "devDependencies": {
        "@types/glob": "^7.1.1",
        "@types/mocha": "^5.2.7",
        "@types/node": "^12.11.7",
        "@types/vscode": "^1.41.0",
        "awesome-typescript-loader": "^5.2.1",
        "glob": "^7.1.5",
        "html-loader": "^0.5.5",
        "mocha": "^6.2.2",
        "tslint": "^5.20.0",
        "typescript": "^3.6.4",
        "vscode-test": "^1.2.2",
        "webpack": "^4.41.2",
        "webpack-cli": "^3.3.9"
    },
    "dependencies": {
        "cerialize": "^0.1.18",
        "ts_common": "file:../ts_common"
    },
    "private": true
}
</code>```

tsconfig.json:

```<code>{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es2016",
        "outDir": "out",
        "lib": [
            "es2018",
            "dom"
        ],
        "sourceMap": true,
        //"rootDir": "src",
        "typeRoots": ["node_modules/@types"],
        "strict": true,   /* enable all strict type-checking options */
        /* Additional Checks */
        "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
        "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
        // "noUnusedParameters": true,  /* Report errors on unused parameters. */
    },
    "awesomeTypescriptLoaderOptions": {
      "useCache": true,
      "isolatedModules": true,
      //"transpileOnly": true, // This is about a 2x speedup to compilation but disable type errors/warnings
      "reportFiles": [
        "src/**/*.{ts,tsx}"
      ]
    },
    "include": [
      "./src/"
    ]/*,
    "exclude": [
        "node_modules",
        "../ts_common",
        "./dist",
        ".vscode-test"
    ]*/
}
</code>```

答:
Are you using "export" in an embedded script?

From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export
You can't do that.

Body:
I have created a vscode extension using typescript. Normally, I'd reduce the problem to the smallest possible piece of code, but whenever I try to do that, the problem disappears.

Whenever I try to run the extension (by pressing Ctrl+Shift+P and selecting my extension's command), I get the error: (name changed)

Activating extension 'undefined_publisher.extension-name' failed: Unexpected token {.

Or, in previous versions of the code when I first encountered the error, ...Unexpected token ,.

The error gives no indication of which line or even which file contains the unexpected token. I have tried to run the debugger on the code that loads the extension (vscode devtools), but I couldn't find any obvious "current file" or some such in the call stack.

How do I even begin to debug this?

package.json: (name changed)

{
    "name": "extension-name",
    "displayName": "Extension Name",
    "description": "Extension Descripton",
    "version": "0.0.1",
    "engines": {
        "vscode": "^1.41.0"
    },
    "categories": [
        "Other"
    ],
    "activationEvents": [
        "onCommand:extension-name.start"
    ],
    "main": "./out/extension.js",
    "contributes": {
        "commands": [
            {
                "command": "extension-name.start",
                "title": "Open a Extension Name window"
            }
        ]
    },
    "scripts": {
        "vscode:prepublish": "npm run compile",
        "compile": "tsc -p ./",
        "watch": "tsc -watch -p ./",
        "pretest": "npm run compile",
        "test": "node ./out/test/runTest.js"
    },
    "devDependencies": {
        "@types/glob": "^7.1.1",
        "@types/mocha": "^5.2.7",
        "@types/node": "^12.11.7",
        "@types/vscode": "^1.41.0",
        "awesome-typescript-loader": "^5.2.1",
        "glob": "^7.1.5",
        "html-loader": "^0.5.5",
        "mocha": "^6.2.2",
        "tslint": "^5.20.0",
        "typescript": "^3.6.4",
        "vscode-test": "^1.2.2",
        "webpack": "^4.41.2",
        "webpack-cli": "^3.3.9"
    },
    "dependencies": {
        "cerialize": "^0.1.18",
        "ts_common": "file:../ts_common"
    },
    "private": true
}

tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es2016",
        "outDir": "out",
        "lib": [
            "es2018",
            "dom"
        ],
        "sourceMap": true,
        //"rootDir": "src",
        "typeRoots": ["node_modules/@types"],
        "strict": true,   /* enable all strict type-checking options */
        /* Additional Checks */
        "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
        "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
        // "noUnusedParameters": true,  /* Report errors on unused parameters. */
    },
    "awesomeTypescriptLoaderOptions": {
      "useCache": true,
      "isolatedModules": true,
      //"transpileOnly": true, // This is about a 2x speedup to compilation but disable type errors/warnings
      "reportFiles": [
        "src/**/*.{ts,tsx}"
      ]
    },
    "include": [
      "./src/"
    ]/*,
    "exclude": [
        "node_modules",
        "../ts_common",
        "./dist",
        ".vscode-test"
    ]*/
}


来源: stackexchange

问:
jframe send back when close the second jframe in netbeans
I am creating a Java application with NetBeans, a main JFrame containing menus. When I click a menu item and open another JFrame, and then close the second JFrame to return to the main JFrame, main JFrame was sent back and NetBeans IDE appears.

I must click ALT+TAB to show the main JFrame again and then when I reopen the second JFrame, everything goes OK.

I tested JFrame.ToFront(). Following screenshots describe the problem in steps:

step 1

step 2

step 3

step 4

step 5

step 6

step 7

答:
It is not very difficult. You just need to use

```<code>JFrame.requestFocus();
</code>```

I hope that I could help you!

ContentLicense: CC BY-SA 3.0

Body:
It is not very difficult. You just need to use

JFrame.requestFocus();

I hope that I could help you!

ContentLicense: CC BY-SA 4.0


问:
Remove all packages that do not come with R
How can I remove all installed packages except base and recommended?

答:
Accepted answer no longer works (R 3.6.X), but this one does:

```<code>update.packages(checkBuilt = T, ask = F)
</code>```

We use checkBuilt=T because this checks whether packages were built under an older version and need to be rebuilt (sometimes).

We use ask=F because otherwise we get a prompt for each package which is annoying.

Body:
Accepted answer no longer works (R 3.6.X), but this one does:

update.packages(checkBuilt = T, ask = F)

We use checkBuilt=T because this checks whether packages were built under an older version and need to be rebuilt (sometimes).

We use ask=F because otherwise we get a prompt for each package which is annoying.


问:
creating forms in zend with ini file
I know Zend_Form gets a lot of hate from many developers, I've even heard that for many it was the main turn-off to switching from [insert random php framework name here] to ZF, but just a little time ago I found out that creating forms with an .ini file is the way around this and the best way of doing it. I haven't found any useful info googling around it, can anyone point me the right path to it?

Thanks a lot.

答:
Check this out. It's stated in the official manual at this page:
http://framework.zend.com/manual/1.12/en/zend.form.quickstart.html

Scroll down to the section called "Using a Zend_Config Object". There you got some examples.

As mentioned in the doc, the Zend_Config factory will ingest the .ini file describing your form. After that, you can build a Zend_Form using that Zend_Config instance.

```<code>$config = new Zend_Config_Ini($configFile, 'development');
$form   = new Zend_Form($config->user->login);
</code>```

Title: creating forms in zend with ini file

Body:
Check this out. It's stated in the official manual at this page:
http://framework.zend.com/manual/1.12/en/zend.form.quickstart.html

Scroll down to the section called "Using a Zend_Config Object". There you got some examples.

As mentioned in the doc, the Zend_Config factory will ingest the .ini file describing your form. After that, you can build a Zend_Form using that Zend_Config instance.

$config = new Zend_Config_Ini($configFile, 'development');
$form   = new Zend_Form($config->user->login);


问:
forEach loop assigns the same random number
In typescript, I am trying to assign a random number to a property of each object in an array.  I have tried the following code

```<code>uniqueItems.forEach(unique => {
  unique.humanCode = Math.floor(1000 + Math.random() * 9000).toString();
});
</code>```

If I console.log inside the forEach loop, I get a different number but when I console.log the array of objects after the forEach, all of the random numbers are the same.

Edit: I had originally created my array of objects by using

```<code>for (let i = 0; i < this.quantity; i++) {
  this.uniqueItems.push(uniqueItem);
}
</code>```

This made an array of the same object.  This meant that my array was being assigned the last random number.  I fixed this by using the spread operator when I created my array.

```<code>for (let i = 0; i < this.quantity; i++) {
  this.uniqueItems.push({ ...this.uniqueItem });
}
</code>```

答:
You can use map to iterate over your items and return a new object for each item in the array. This will also ensure you are no updating the object by reference. You should read about mutability in JavaScript. It's an important concept in JS</p>

```<code>uniqueItems.map(unique => ({
  ...unique,
  humanCode: Math.floor(1000 + Math.random() * 9000).toString(),
}));
</code>```

Body:
In typescript, I am trying to assign a random number to a property of each object in an array.  I have tried the following code

uniqueItems.forEach(unique => {
  unique.humanCode = Math.floor(1000 + Math.random() * 9000).toString();
});

If I console.log inside the forEach loop, I get a different number but when I console.log the array of objects after the forEach, all of the random numbers are the same.

Edit: I had originally created my array of objects by using

for (let i = 0; i < this.quantity; i++) {
  this.uniqueItems.push(uniqueItem);
}

This made an array of the same object.  This meant that my array was being assigned the last random number.  I fixed this by using the spread operator when I created my array.

for (let i = 0; i < this.quantity; i++) {
  this.uniqueItems.push({ ...this.uniqueItem });
}

Body:
You can use map to iterate over your items and return a new object for each item in the array. This will also ensure you are no updating the object by reference. You should read about mutability in JavaScript. It's an important concept in JS

uniqueItems.map(unique => ({
  ...unique,
  humanCode: Math.floor(1000 + Math.random() * 9000).toString(),
}));


问:
What's the difference between ViewData and ViewBag?
I saw the ViewBag in MVC 3. How's that different than ViewData in MVC 2?

答:
Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary.

Note: in most pre-release versions of MVC 3, the ViewBag property was named the ViewModel as noted in this snippet from MVC 3 release notes:

(edited 10-8-12) It was suggested I post the source of this info I posted, here is the source:
http://www.asp.net/whitepapers/mvc3-release-notes#_Toc2_4

MVC 2 controllers support a ViewData
  property that enables you to pass data
  to a view template using a late-bound
  dictionary API. In MVC 3, you can also
  use somewhat simpler syntax with the
  ViewBag property to accomplish the
  same purpose. For example, instead of
  writing ViewData["Message"]="text",
  you can write ViewBag.Message="text".
  You do not need to define any
  strongly-typed classes to use the
  ViewBag property. Because it is a
  dynamic property, you can instead just
  get or set properties and it will
  resolve them dynamically at run time.
  Internally, ViewBag properties are
  stored as name/value pairs in the
  ViewData dictionary. (Note: in most
  pre-release versions of MVC 3, the
  ViewBag property was named the
  ViewModel property.)


问:
Recent Azure Function Upgrade Broke WebP Decode back to bitmap using libwebp.dll
I recently discovered that a call to this

[DllImport("libwebp.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "WebPGetInfo")]
  public static extern int WebPGetInfo(IntPtr data, uint dataSize, out int width, out int height);

is broken, the call should have return width and height, but with the new azure function upgrade the width and height are always zero from the azure function call when running both locally and in Azure cloud.

However the same WebP wrapper code works perfectly fine for a dotnet core web api project.  I noticed that the recent Azure function upgrade changed func.exe from 32bit to 64bit.  I am not sure if this has anything to do with it, because the dotnet core web api project works in both 32 and 64 bit, but the azure function app are broken for both 32bit and 64bit.

Anyone encounter similar issue like this?

答: Update.  My bad, I accidentally changed the code to get the posted file in the azure function project.</p>


问:
AMP for article pages only?
My boss wants to add AMP to our new site, we already have a responsive website and have added PWA.

The site is a blog/news site, so does AMP need to be on each article page only? Or do we need to have a AMP for every page?

答:
that's a good questions. The answers depends on multiple things:

is amp possible for the whole page?

what do you wan't to achieve?

It is no problem to mix amp-pages with non-amp pages.
If you use amp your are very limited in css and own javascript.

An mean idea is to deliver only what the user realy need.
Use safe cdn, webfonts and some special amp-elements.

All pages witch uses amp are cached by google, your users can load the content extremly fast.

If you use amp for your articles you can great cool things:
It's possible to present your news in some special formats.

https://amp.dev/documentation/examples/news-publishing/news_article/?format=websites

more informations you can find also here: https://amp.dev/documentation/templates/

Title: AMP for article pages only?


问:
Can't install PyQt5 using pip
I have tried to install PyQt5 using

```<code>pip install PyQt5
</code>```

and

```<code>sudo -H pip install PyQt5
</code>```

both of them give me the errors

```<code>ERROR: Could not find a version that satisfies the requirement PyQt5 (from versions: none)
ERROR: No matching distribution found for PyQt5
</code>```

I use Ubuntu 18.04.

My python version is: Python 2.7.15rc1

I have already installed python3-pip and tried to install PyQt5 using

```<code>pip3 install PyQt5
</code>```

I get the error

```<code>Traceback (most recent call last):
  File "/usr/local/bin/pip3", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 3241, in <module>
    @_call_aside
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 3225, in _call_aside
    f(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 3254, in _initialize_master_working_set
    working_set = WorkingSet._build_master()
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 585, in _build_master
    return cls._build_from_requirements(__requires__)
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 598, in _build_from_requirements
    dists = ws.resolve(reqs, Environment())
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 786, in resolve
    raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'pip==9.0.1' distribution was not found and is required by the application
</code>```

My python3 version is: Python3.6.7.

答:
You need to upgrade your pip

```<code>pip install --user --upgrade pip
</code>```

Then do a fresh install

```<code>pip install PyQt5
</code>```

or

```<code>pip3 install PyQt5
</code>```

Title: Can't install PyQt5 using pip

Body:
I have tried to install PyQt5 using

pip install PyQt5

and

sudo -H pip install PyQt5

both of them give me the errors

ERROR: Could not find a version that satisfies the requirement PyQt5 (from versions: none)
ERROR: No matching distribution found for PyQt5

I use Ubuntu 18.04.

My python version is: Python 2.7.15rc1

I have already installed python3-pip and tried to install PyQt5 using

pip3 install PyQt5

I get the error

Traceback (most recent call last):
  File "/usr/local/bin/pip3", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 3241, in <module>
    @_call_aside
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 3225, in _call_aside
    f(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 3254, in _initialize_master_working_set
    working_set = WorkingSet._build_master()
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 585, in _build_master
    return cls._build_from_requirements(__requires__)
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 598, in _build_from_requirements
    dists = ws.resolve(reqs, Environment())
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 786, in resolve
    raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'pip==9.0.1' distribution was not found and is required by the application

My python3 version is: Python3.6.7.

Body:
You need to upgrade your pip

pip install --user --upgrade pip

Then do a fresh install

pip install PyQt5

or

pip3 install PyQt5


问:
How can I turn this jquery into a function?
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the href> tag somewhere.

html code

```<code><img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
    <li><a href="linkpage.htm" class="newslink1">Link 1</a></li>
    <li><a href="linkpage.htm" class="newslink2">Link 2</a></li>
    <li><a href="linkpage.htm" class="newslink3">Link 3</a></li>
</ul>
</code>```

jquery

```<code>$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});
</code>```

答:
Could give this a try:  </p>

```<code>$('a.newslink').bind('mouseover', function(){
              var imgname = $(this).attr("src");
              $('img#storyimg').attr("src", imgname);

});
</code>```

Body:
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the  tag somewhere.

html code

Link 1

Link 2

Link 3

jquery

$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});

Body:
Could give this a try:

$('a.newslink').bind('mouseover', function(){
              var imgname = $(this).attr("src");
              $('img#storyimg').attr("src", imgname);

});


问:
active state adding to parent link on one, but not another
I'm using this script to add an "active" class to my menu items. One of my parent menu items is /path/library/. The class is added just fine there. And then on the pagination of that page (i.e., /path/library/?page-2) the class stays added to the parent just fine. For the parent link /path/signage/, the active link is applied just fine. But when I have a non-paginated child (i.e., /path/signage/posters/) no active link is applied anywhere. I'm lost. No idea why I can't get it to work properly when it does it right for one but not the other.

Here's my script...

```<code>    jQuery(document).ready(function($) {
       $('.persist-header a').each(function () {
          var $this = $(this);
          if ($this.attr('href').indexOf(window.location.pathname) !== -1) {
             $this.addClass('active');
          }
       });
    });
</code>```

EDIT
Ok, here's my header code (this is a WP site. And since I'm pulling images from specific taxonomies, I'm not using the WP menu system - I'm using ACF for selecting the items that go in the menu).

```<code>    <div class="d-flex align-items-end">
        <div class="content container-fluid" style="padding: 0 !important;">

            <style>
                        .bordercolor0 {
                            border-color: #26b59c;
                        }
                        .bordercolor1 {
                            border-color: #f99d3f;
                        }
                        .bordercolor2 {
                            border-color: #d52352;
                        }
                        .bordercolor3 {
                            border-color: #ef453b;
                        }
                        .bordercolor4 {
                            border-color: #000000;
                        }
                        .bordercolorhome {
                            border-color: #000000;
                        }
                    </style>

            <!-- MAIN NAV -->
            <nav role="navigation" class="cblNavMenu persist-area">

                <?php  ?>

                <div class="cblNavMenu--wrap static persist-header ">

                    <?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

                        if( have_rows('choose_top_level_category', 'option') ):

                        $c = 0;

                        while( have_rows('choose_top_level_category', 'option') ): the_row();

                        // vars
                        $term = get_sub_field('category', 'option');
                        $cat_label = get_sub_field('category_label', 'option');
                        $current_term_id = $term->term_id;
                         ?>

                    <a class="cblNavMenu--link navBtn max  <?php echo int_to_words($c); ?> " href="<?php echo esc_url( get_term_link( $term ) ); ?>" role="button">
                        <div class="cblNavMenu--link__content block">
                            <div class="cblNavMenu--icon">

                                <?php $args = array(
                                    'post_type' => 'attachment',
                                    'post_mime_type' => 'image',
                                    'posts_per_page' => 1,
                                    'tax_query' => array(
                                        array(
                                            'taxonomy' => 'mediacat',
                                            'terms' => $term->term_id,
                                        )
                                    ),
                                    'orderby' => 'rand',
                                    'post_status' => 'inherit',
                                    //'fields' => 'ids'
                                );
                                $loop = new WP_Query( $args );

                                while ( $loop->have_posts() ) :

                                    $loop->the_post();

                                    $item = get_the_id();

                                    $attachment_image = wp_get_attachment_image_url( $item, 'square' );
                                ?>

                                <figure class="cblNavMenu--icon__imgwrap">
                                    <img class="cblNavMenu--icon__img" src="<?php echo $attachment_image; ?>" alt="<?php echo $term->name;?>"/>
                                </figure>
                                <?php endwhile;
                                wp_reset_postdata(); ?>
                            </div>
                            <span class="cblNavMenu--label"><?php if($cat_label) { echo $cat_label; } else { echo $term->name; } ?></span>
                        </div>
                    </a>

                        <?php $c++; endwhile;
                    endif; ?>

                    <script>
                        jQuery(document).ready(function($) {
                            $('.persist-header a').each(function () {
                                var $this = $(this);
                                if ($this.attr('href').indexOf(window.location.pathname) !== -1) {
                                    $this.addClass('active');
                                }
                            });
                        });
                    </script>

                    <script>
                        jQuery(function($) {
                            if ($('.zero.active').length > 0) {
                                $('.cblNavMenu--wrap').addClass('bordercolor0');
                            }
                            if ($('.one.active').length > 0) {
                                $('.cblNavMenu--wrap').addClass('bordercolor1');
                            }
                            if ($('.two.active').length > 0) {
                                $('.cblNavMenu--wrap').addClass('bordercolor2');
                            }
                            if ($('.three.active').length > 0) {
                                $('.cblNavMenu--wrap').addClass('bordercolor3');
                            }
                            if ($('.four.active').length > 0) {
                                $('.cblNavMenu--wrap').addClass('bordercolor4');
                            }
                            if ($('.zero.active').length > 0) {
                                $('footer').addClass('bordercolor0');
                            }
                            if ($('.one.active').length > 0) {
                                $('footer').addClass('bordercolor1');
                            }
                            if ($('.two.active').length > 0) {
                                $('footer').addClass('bordercolor2');
                            }
                            if ($('.three.active').length > 0) {
                                $('footer').addClass('bordercolor3');
                            }
                            if ($('.four.active').length > 0) {
                                $('footer').addClass('bordercolor4');
                            }
                            if ($('body.home').length > 0) {
                                $('footer').addClass('bordercolorhome');
                            }
                        });
                    </script>

                    <div class="clearfix"></div>
                </div>

                <div class="clearfix"></div>
            </nav>

        </div>
    </div>
</code>```

And my taxonomy page, which is working great for paginated children, but not regular children (of course the get_header and get_footer codes are in there as well. Seemed superfluous to include them here though)...

```<code>    <div id="post-<?php the_ID(); ?>" <?php post_class(''); ?>>
        <div class="content container-fluid" style="padding: 0 !important;">
            <div class="row justify-content-center">
                <div class="col-md-9">
                    <?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

                    $paged = (get_query_var('page')) ? get_query_var('page') : 1;

                    $current_term_id = $term->term_id;
                    $current_name = $term->name;
                    $current_taxonomy = $term->taxonomy;
                    $current_parent = $term->parent;
                    ?>

                    <h1 class="header__title">
                        <i class="fas fa-map-marker-alt"></i>
                        <?php echo $current_name; ?>
                    </h1>

                    <?php $sub_terms = get_terms( array(
                        'taxonomy' => $current_taxonomy,
                        'child_of' => $current_term_id,
                        'hide_empty' => true,
                    ) );

                    if ($sub_terms) {
                    ?>
                    <ul class="sub-terms">
                        <?php foreach ($sub_terms as $sub_term) { ?>
                        <li><a href="<?php echo get_term_link( $sub_term ) ?>" class="sub"><?php echo $sub_term->name?></a></li>
                        <?php }// END foreach ?>
                    </ul><!-- END .sub-terms -->
                    <?php }// END if ?>

                    <main>
                        Search Form Here

                        <div class="container-fluid">
                            <div class="row justify-content-center">
                                <div class="pagination_links" style="clear: both;">
                                    <?php $args = array(
                                            'post_type' => 'attachment',
                                            'post_mime_type' => 'image',
                                            'tax_query'       => array(
                                                array(
                                                    'taxonomy' => $term->taxonomy,
                                                    'field' => 'term_id',
                                                    'terms' => $current_term_id
                                                )
                                            ),
                                            'orderby' => 'title',
                                            'order' => 'asc',
                                            'posts_per_page' => '20',
                                            'paged' => $paged,
                                            'post_status' => 'inherit'
                                        );

                                        $loop = new WP_Query( $args );

                                        $c = 0;

                                    ?>
                                    <?php $big = 999999999; // need an unlikely integer

                                        for ($i=1;$i<=$loop->max_num_pages;$i++) { ?>
                                            <a href="<?php str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ) ?>?page=<?php echo $i; ?>" class="page-numbers current" aria-current="page">Page <?php echo $i; ?></a>

                                        <?php }
                                    ?>
                                </div>
                            </div>

                            <div class="row justify-content-center">
                                <form class="wpsp-page-nav-form" action="<?php echo $_SERVER['REQUEST_URI'];?>" method="get" style="text-align: center;">
                                    <div class="col-6 offset-3">
                                        <label for="sortby" class="wpsp-label wpsp-hidden" style="display: inline-block;"><?php _e('Jump to', 'wp-smart-pagination'); ?></label>
                                        <input class="wpsp-input-number" type="text" placeholder="page..."  size="15" name="page" style="display: inline-block; width: auto; background-color: #fff;"/>
                                        <button class="btn" type="submit" style="display: inline-block;"><i class="fa fa-arrow-right" aria-hidden="true"></i></button>
                                    </div>
                                </form>
                            </div>

                            <div class="row justify-content-center">
                                <div class="container-fluid">

                                    <div class="grid">
                                        <div class="grid-sizer"></div>
                                        <?php $c = 0;
                                            if ( $loop->have_posts() ) {

                                            while ( $loop->have_posts() ) {
                                                $loop->the_post();

                                                $item = get_the_id();
                                                $atts = wp_get_attachment_image_src($item, 'large');
                                                $image_all = wp_prepare_attachment_for_js($item);
                                                $attachment_page = wp_get_attachment_url( $item );
                                                $title = wp_prepare_attachment_for_js($item);
                                                $image_title = wp_prepare_attachment_for_js($item);
                                        ?>

                                        <div class="grid-item">

                                            <div class="entry-title-box">
                                                <h3 class="entry-title"><?php echo $image_title['title']; ?></h3>
                                            </div>
                                            <img src="<?php echo $atts[0]; ?>" alt="<?php echo $image_all['alt']; ?>">
                                            <div class="entry-content-box">
                                                <p>keywords: <em><?php if (empty($image_all['alt'])) { echo $image_all['caption']; } else { echo $image_all['alt']; } ?></em></p>
                                                <div id="fileName<?php echo $loop->current_post +1; ?>" style="display: none;"><?php echo $image_title['title']; ?></div>
                                                <div class="btn-group">
                                                    <button class="btn btn-primary btn2 js-tooltip" id="btnCopy" rel="fileName<?php echo $loop->current_post +1; ?>" type="button" data-toggle="popover" title="copied">Copy Filename</button>
                                                    <button type="button" class="btn btn-default btn2 js-tooltip" id="btnCopy" rel="fileName" type="button" data-toggle="popover" title="copied">
                                                        <!-- icon from google's material design library -->
                                                        <svg class="icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="24" height="24" viewBox="0 0 24 24">
                                                            <path d="M17,9H7V7H17M17,13H7V11H17M14,17H7V15H14M12,3A1,1 0 0,1 13,4A1,1 0 0,1 12,5A1,1 0 0,1 11,4A1,1 0 0,1 12,3M19,3H14.82C14.4,1.84 13.3,1 12,1C10.7,1 9.6,1.84 9.18,3H5A2,2 0 0,0 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5A2,2 0 0,0 19,3Z" />
                                                        </svg>
                                                    </button>
                                                </div>
                                                <button id="btn_link" class="btn btn-secondary" type="button" href="#" data-toggle="modal" data-target="#galleryModal<?php echo $loop->current_post +1; ?>" data-backdrop="static" data-keyboard="false" style="margin-top: 5px;">Suggest keywords</button>
                                            </div>
                                        </div>

                                        <!-- Modal -->
                                        <div class="modal fade" id="galleryModal<?php echo $loop->current_post +1; ?>" tabindex="-1" role="dialog" aria-labelledby="galleryModalLabel<?php echo $loop->current_post +1; ?>" aria-hidden="true">
                                            <div class="modal-dialog modal-lg modal-dialog-centered">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                                                    </div>
                                                    <div class="modal-body d-flex h-100">
                                                        <div class="row justify-content-center align-self-center">
                                                            <div class="col-md-6" style="text-align: center;">
                                                                <img src="<?php echo $atts[0]; ?>" class="img-fluid img-thumbnail">
                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="row">
                                                                    <h2 class="modal-title" id="galleryModalLabel<?php echo $loop->current_post +1; ?>"><span id="copyit"><?php echo $image_title['title']; ?></span></h2>
                                                                </div>
                                                                <div class="row">
                                                                    <p>keywords: <em><?php if (empty($image_all['alt'])) { echo $image_all['caption']; } else { echo $image_all['alt']; } ?></em></p>
                                                                </div>
                                                                <div class="row" id="message">
                                                                    <?php echo do_shortcode( '[gravityform id="1" field_values="filename='. $image_title['title'] .'" ajax="true"]' ); ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                                <?php } $c++; } wp_reset_postdata(); ?>
                                    </div>

                                    <script type="text/javascript">
                                        jQuery(document).ready(function($) {
                                            // init Masonry
                                            var $grid = $('.grid').masonry({
                                            itemSelector: '.grid-item',
                                            percentPosition: true,
                                            columnWidth: '.grid-sizer'
                                        });

                                        // layout Masonry after each image loads
                                        $grid.imagesLoaded().progress( function() {
                                            $grid.masonry();
                                        });
                                    });

                                    jQuery(document).on("click", "#btnCopy", function(ev) {
                                        var $body = document.getElementsByTagName('body')[0];
                                        var rel = jQuery(this).attr("rel");
                                        var text = jQuery("#"+rel).text();
                                        var $tempInput = document.createElement('INPUT');
                                        $body.appendChild($tempInput);
                                        $tempInput.setAttribute('value',  text)
                                        $tempInput.select();
                                        document.execCommand('copy');
                                        $body.removeChild($tempInput);
                                    });

                                    jQuery(function () {
                                        jQuery('[data-toggle="popover"]').popover().click(function () {
                                            setTimeout(function () {
                                                jQuery('[data-toggle="popover"]').popover('hide');
                                            }, 2000);
                                        });
                                    });
                                </script>
                            </div>

                            <div class="row justify-content-center">
                                <div class="pagination_links" style="clear: both;">
                                    <?php $big = 999999999; // need an unlikely integer

                                        for ($i=1;$i<=$loop->max_num_pages;$i++) { ?>
                                            <a href="<?php str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ) ?>?page=<?php echo $i; ?>" class="page-numbers current" aria-current="page">Page <?php echo $i; ?></a><?php }
                                    ?>
                                </div>
                            </div>

                            <div class="row justify-content-center">
                                <form class="wpsp-page-nav-form" action="<?php echo $_SERVER['REQUEST_URI'];?>" method="get" style="text-align: center;">
                                    <div class="col-6 offset-3">
                                        <label for="sortby" class="wpsp-label wpsp-hidden" style="display: inline-block;"><?php _e('Jump to', 'wp-smart-pagination'); ?></label>
                                        <input class="wpsp-input-number" type="text" placeholder="page..."  size="15" name="page" style="display: inline-block; width: auto; background-color: #fff;"/>
                                        <button class="btn" type="submit" style="display: inline-block;"><i class="fa fa-arrow-right" aria-hidden="true"></i></button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </main>
            </div>
        </div>
    </div>
</code>```

答:
I found a solution by posing a different version of the question here since my original problem changed when I got my pagination issue resolved so it was no longer doing "path/term/?page=2", but had changed to "path/term/page/2", and I was also still having difficulty with applying the style when I was on child pages like "path/term/sub-term".

```<code>    $('.persist-header a[href*="/<?php echo $term2->slug; ?>/"]').addClass('active');
</code>```

It works great!

Body:
I'm using this script to add an "active" class to my menu items. One of my parent menu items is /path/library/. The class is added just fine there. And then on the pagination of that page (i.e., /path/library/?page-2) the class stays added to the parent just fine. For the parent link /path/signage/, the active link is applied just fine. But when I have a non-paginated child (i.e., /path/signage/posters/) no active link is applied anywhere. I'm lost. No idea why I can't get it to work properly when it does it right for one but not the other.

Here's my script...

    jQuery(document).ready(function($) {
       $('.persist-header a').each(function () {
          var $this = $(this);
          if ($this.attr('href').indexOf(window.location.pathname) !== -1) {
             $this.addClass('active');
          }
       });
    });

EDIT
Ok, here's my header code (this is a WP site. And since I'm pulling images from specific taxonomies, I'm not using the WP menu system - I'm using ACF for selecting the items that go in the menu).

                <?php  ?>

                    <?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

                        if( have_rows('choose_top_level_category', 'option') ):

                        $c = 0;

                        while( have_rows('choose_top_level_category', 'option') ): the_row();

                        // vars
                        $term = get_sub_field('category', 'option');
                        $cat_label = get_sub_field('category_label', 'option');
                        $current_term_id = $term->term_id;
                         ?>

                    <a class="cblNavMenu--link navBtn max  <?php echo int_to_words($c); ?> " href="<?php echo esc_url( get_term_link( $term ) ); ?>" role="button">

                                <?php $args = array(
                                    'post_type' => 'attachment',
                                    'post_mime_type' => 'image',
                                    'posts_per_page' => 1,
                                    'tax_query' => array(
                                        array(
                                            'taxonomy' => 'mediacat',
                                            'terms' => $term->term_id,
                                        )
                                    ),
                                    'orderby' => 'rand',
                                    'post_status' => 'inherit',
                                    //'fields' => 'ids'
                                );
                                $loop = new WP_Query( $args );

                                while ( $loop->have_posts() ) :

                                    $loop->the_post();

                                    $item = get_the_id();

                                    $attachment_image = wp_get_attachment_image_url( $item, 'square' );
                                ?>

                                    <img class="cblNavMenu--icon__img" src="<?php echo $attachment_image; ?>" alt="<?php echo $term->name;?>"/>

                                <?php endwhile;
                                wp_reset_postdata(); ?>

                            <?php if($cat_label) { echo $cat_label; } else { echo $term->name; } ?>

                        <?php $c++; endwhile;
                    endif; ?>

And my taxonomy page, which is working great for paginated children, but not regular children (of course the get_header and get_footer codes are in there as well. Seemed superfluous to include them here though)...

    <div id="post-<?php the_ID(); ?>" <?php post_class(''); ?>>

                    <?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

                    $paged = (get_query_var('page')) ? get_query_var('page') : 1;

                    $current_term_id = $term->term_id;
                    $current_name = $term->name;
                    $current_taxonomy = $term->taxonomy;
                    $current_parent = $term->parent;
                    ?>

                        <?php echo $current_name; ?>

                    <?php $sub_terms = get_terms( array(
                        'taxonomy' => $current_taxonomy,
                        'child_of' => $current_term_id,
                        'hide_empty' => true,
                    ) );

                    if ($sub_terms) {
                    ?>

                        <?php foreach ($sub_terms as $sub_term) { ?>

<a href="<?php echo get_term_link( $sub_term ) ?>" class="sub"><?php echo $sub_term->name?>

                        <?php }// END foreach ?>

                    <?php }// END if ?>

                        Search Form Here

                                    <?php $args = array(
                                            'post_type' => 'attachment',
                                            'post_mime_type' => 'image',
                                            'tax_query'       => array(
                                                array(
                                                    'taxonomy' => $term->taxonomy,
                                                    'field' => 'term_id',
                                                    'terms' => $current_term_id
                                                )
                                            ),
                                            'orderby' => 'title',
                                            'order' => 'asc',
                                            'posts_per_page' => '20',
                                            'paged' => $paged,
                                            'post_status' => 'inherit'
                                        );

                                        $loop = new WP_Query( $args );

                                        $c = 0;

                                    ?>
                                    <?php $big = 999999999; // need an unlikely integer

                                        for ($i=1;$i<=$loop->max_num_pages;$i++) { ?>
                                            <a href="<?php str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ) ?>?page=<?php echo $i; ?>" class="page-numbers current" aria-current="page">Page <?php echo $i; ?>

                                        <?php }
                                    ?>

                                <form class="wpsp-page-nav-form" action="<?php echo $_SERVER['REQUEST_URI'];?>" method="get" style="text-align: center;">

                                        <?php _e('Jump to', 'wp-smart-pagination'); ?>
                                        <input class="wpsp-input-number" type="text" placeholder="page..."  size="15" name="page" style="display: inline-block; width: auto; background-color: #fff;"/>
                                        <button class="btn" type="submit" style="display: inline-block;"></button>

                                </form>

                                        <?php $c = 0;
                                            if ( $loop->have_posts() ) {

                                            while ( $loop->have_posts() ) {
                                                $loop->the_post();

                                                $item = get_the_id();
                                                $atts = wp_get_attachment_image_src($item, 'large');
                                                $image_all = wp_prepare_attachment_for_js($item);
                                                $attachment_page = wp_get_attachment_url( $item );
                                                $title = wp_prepare_attachment_for_js($item);
                                                $image_title = wp_prepare_attachment_for_js($item);
                                        ?>

<?php echo $image_title['title']; ?>

                                            <img src="<?php echo $atts[0]; ?>" alt="<?php echo $image_all['alt']; ?>">

keywords: <?php if (empty($image_all['alt'])) { echo $image_all['caption']; } else { echo $image_all['alt']; } ?>

                                                <div id="fileName<?php echo $loop->current_post +1; ?>" style="display: none;"><?php echo $image_title['title']; ?>

                                                    <button class="btn btn-primary btn2 js-tooltip" id="btnCopy" rel="fileName<?php echo $loop->current_post +1; ?>" type="button" data-toggle="popover" title="copied">Copy Filename</button>
                                                    <button type="button" class="btn btn-default btn2 js-tooltip" id="btnCopy" rel="fileName" type="button" data-toggle="popover" title="copied">

                                                        <svg class="icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="24" height="24" viewBox="0 0 24 24">
                                                            <path d="M17,9H7V7H17M17,13H7V11H17M14,17H7V15H14M12,3A1,1 0 0,1 13,4A1,1 0 0,1 12,5A1,1 0 0,1 11,4A1,1 0 0,1 12,3M19,3H14.82C14.4,1.84 13.3,1 12,1C10.7,1 9.6,1.84 9.18,3H5A2,2 0 0,0 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5A2,2 0 0,0 19,3Z" />
                                                        </svg>
                                                    </button>

                                                <button id="btn_link" class="btn btn-secondary" type="button" href="#" data-toggle="modal" data-target="#galleryModal<?php echo $loop->current_post +1; ?>" data-backdrop="static" data-keyboard="false" style="margin-top: 5px;">Suggest keywords</button>

                                        <div class="modal fade" id="galleryModal<?php echo $loop->current_post +1; ?>" tabindex="-1" role="dialog" aria-labelledby="galleryModalLabel<?php echo $loop->current_post +1; ?>" aria-hidden="true">

                                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

                                                                <img src="<?php echo $atts[0]; ?>" class="img-fluid img-thumbnail">

                                                                    <h2 class="modal-title" id="galleryModalLabel<?php echo $loop->current_post +1; ?>"><?php echo $image_title['title']; ?>

keywords: <?php if (empty($image_all['alt'])) { echo $image_all['caption']; } else { echo $image_all['alt']; } ?>

                                                                    <?php echo do_shortcode( '[gravityform id="1" field_values="filename='. $image_title['title'] .'" ajax="true"]' ); ?>

                                                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                                                <?php } $c++; } wp_reset_postdata(); ?>

                                    <?php $big = 999999999; // need an unlikely integer

                                        for ($i=1;$i<=$loop->max_num_pages;$i++) { ?>
                                            <a href="<?php str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ) ?>?page=<?php echo $i; ?>" class="page-numbers current" aria-current="page">Page <?php echo $i; ?><?php }
                                    ?>

                                <form class="wpsp-page-nav-form" action="<?php echo $_SERVER['REQUEST_URI'];?>" method="get" style="text-align: center;">

                                        <?php _e('Jump to', 'wp-smart-pagination'); ?>
                                        <input class="wpsp-input-number" type="text" placeholder="page..."  size="15" name="page" style="display: inline-block; width: auto; background-color: #fff;"/>
                                        <button class="btn" type="submit" style="display: inline-block;"></button>

                                </form>

Body:
I found a solution by posing a different version of the question here since my original problem changed when I got my pagination issue resolved so it was no longer doing "path/term/?page=2", but had changed to "path/term/page/2", and I was also still having difficulty with applying the style when I was on child pages like "path/term/sub-term".

    $('.persist-header a[href*="/<?php echo $term2->slug; ?>/"]').addClass('active');

It works great!


问:
Python pandas explode (one to many relationship)
Suppose I have a the following dataframe with columns name, preference, fruits:

```<code>name   preference   fruits
adam    likes       apples
mike   dislikes     orange
</code>```

If the dataframe above had a one to many relationship like column name would have have multiple relationship with column preference, fruits. For example the output dataframe I am looking for is:

```<code>name   preference   fruits
adam    likes       apples
adam    likes       orange
adam    dislikes    apple
adam    dislikes    orange
mike    likes       apples
mike    likes       orange
mike    dislikes    apple
mike    dislikes    orange
</code>```

Wondering if it is possible. From my knowledge about pandas so far I believe I will have to use groupby?
Any help is appreciated!
Thanks!

答:
Is it just cross product:

```<code>(pd.MultiIndex.from_product([df[col] for col in df],
                           names=df.columns)
   .to_frame().reset_index(drop=True)
)
</code>```

Output:

```<code>   name preference  fruits
0  adam      likes  apples
1  adam      likes  orange
2  adam   dislikes  apples
3  adam   dislikes  orange
4  mike      likes  apples
5  mike      likes  orange
6  mike   dislikes  apples
7  mike   dislikes  orange
</code>```

Body:
Suppose I have a the following dataframe with columns name, preference, fruits:

name   preference   fruits
adam    likes       apples
mike   dislikes     orange

If the dataframe above had a one to many relationship like column name would have have multiple relationship with column preference, fruits. For example the output dataframe I am looking for is:

name   preference   fruits
adam    likes       apples
adam    likes       orange
adam    dislikes    apple
adam    dislikes    orange
mike    likes       apples
mike    likes       orange
mike    dislikes    apple
mike    dislikes    orange

Wondering if it is possible. From my knowledge about pandas so far I believe I will have to use groupby?
Any help is appreciated!
Thanks!

Body:
Is it just cross product:

(pd.MultiIndex.from_product([df[col] for col in df],
                           names=df.columns)
   .to_frame().reset_index(drop=True)
)

Output:

   name preference  fruits
0  adam      likes  apples
1  adam      likes  orange
2  adam   dislikes  apples
3  adam   dislikes  orange
4  mike      likes  apples
5  mike      likes  orange
6  mike   dislikes  apples
7  mike   dislikes  orange


问:
What is Frontend Architecture?
I know that there are many takes on the subject, some more code-related and some more conceptual.

What is the ideal definition? And why?

答:
Front-end Architecture is a specialization of Software Architecture. It goes beyond low-level coding concerns and takes into consideration multiple criteria, such as internal and external forces, the past & forecasting of technologies, inferences regarding the growth-direction of applications, their alignment with internal and vendors' systems, and more, in order to provide educated and adapted recommendations to front-end development.

An opposing understanding comes from a popular use of the word "architecture", which refers to the structure of the internal pieces of a given application, including the organization of its modules, the tech-stack used, its data-flow, and so forth. That is not necessarily wrong (conceptually). However, academically speaking those responsibilities belong to another area called "System Design", which is an engineering discipline. By using the proper terminology we are free to reserve the word “architecture” for higher-level concerns which are essential for the success of front-end development and front-end products, especially for big organizations and for the long run. Here are some examples of those architectural concerns:

Converting Non-functional Requirements into comprehensive technical directives relevant to front-end development;

Forecasting of the growth-direction of multiple applications and subsequent recommendations for the adjustments on their System Design;

Study of the current status and forecasting of technologies - what is coming and what will be deprecated;

Organization of Front-end Shops and definition of technical standards;

Documentation and maintenance of Architectural Decision Records (ADR);

Creation and optimization of dev-environments;

Identification of reusability opportunities across multiple departments;

Team composition and management;

Strategic representation/communication of architectural decisions to the various stakeholders;

Benchmark and R&D to favor continued innovation and increase of competitive advantage;

Quality assurance to maximize maintainability and longevity of front-end projects.

This is not a normative list. In fact, these items might change depending on each person and/or organization. The goal here is to exemplify possible concerns related to Front-end Architecture.

In years past, concerns like these were covered by Software Architects. However, the immense range of IT-related knowledge nowadays (Cloud, AI, IoT, AR, VR, Frontend, Backend, Security, DevOps, and so on) has rendered their contributions much less realistic and relevant. Even front-end developers have difficulty keeping up with the intense changes in the field. So while Software Architects and Managers don't have adequate knowledge to give technical recommendations to front-end development, programmers are too busy with their deliverables to monitor the multi-departmental efforts within their companies. Therefore, Front-end Architecture is an essential specialization to permit the strategic direction of front-end development work.

Title: What is Frontend Architecture?


问:
change background color in another blade using variable in laravel blade
I'm working with Laravel right now and can't figure out how I can apply different background colors on page that i want ..

Actually, I want to change the background of my page which I convert to PDF

here is my route

```<code>Route::get('/form/{slug}/pdf/{id}/{color?}', ['as' => 'generate.pdfColor', 'uses' => 'OriginController@changeColor']);
</code>```

here is my function of the controller

```<code>public function changeColor(Request $request, $slug, $id = null, $myColor){
    $colors=[
        1=> ['color'=>'#1e90ff'],
        2=> ['color'=>'#2ecc71'],
        3=> ['color'=>'#e84118'],
        4=> ['color'=>'#222D32'],
        5=> ['color'=>'#ffcccc'],
        6=> ['color'=>'#910000']
    ];
    return  view('layouts.modules.student_pdf',['data'=>$colors[$myColor]]);
}
</code>```

here is my link to sending parameter of the color
in this example  1 is (#1e90ff)

```<code><a  target="_blank" href='<?php echo e(route('generate.pdfColor', ['slug' => 'student', 'id' => '56', 'color' => '1'])); ?>'>
    <i class='fa fa-file-pdf-o 2x avatar'></i>
     change color
</a>
</code>```

and this my page cv_pdf.blade.php that i want to change the bg

```<code> <!-- left -->
    <div class="left" id="left_pdf" style="background:{{data['color']}}  ; " >
     ..............
    </div>
</code>```

答:
You just missed the $ sign for $data variable

```<code>//Fix
<div class="left" id="left_pdf" style="background:{{$data['color']}}  ; " >
</code>```

Body:
I'm working with Laravel right now and can't figure out how I can apply different background colors on page that i want ..

Actually, I want to change the background of my page which I convert to PDF

here is my route

Route::get('/form/{slug}/pdf/{id}/{color?}', ['as' => 'generate.pdfColor', 'uses' => 'OriginController@changeColor']);

here is my function of the controller

public function changeColor(Request $request, $slug, $id = null, $myColor){
    $colors=[
        1=> ['color'=>'#1e90ff'],
        2=> ['color'=>'#2ecc71'],
        3=> ['color'=>'#e84118'],
        4=> ['color'=>'#222D32'],
        5=> ['color'=>'#ffcccc'],
        6=> ['color'=>'#910000']
    ];
    return  view('layouts.modules.student_pdf',['data'=>$colors[$myColor]]);
}

here is my link to sending parameter of the color
in this example  1 is (#1e90ff)

<a  target="_blank" href='<?php echo e(route('generate.pdfColor', ['slug' => 'student', 'id' => '56', 'color' => '1'])); ?>'>

     change color

and this my page cv_pdf.blade.php that i want to change the bg

     ..............

Body:
You just missed the $ sign for $data variable

//Fix
<div class="left" id="left_pdf" style="background:{{$data['color']}}  ; " >


问:
logback java - log.error works but log.info doesn't
I have a web application on java spring mvc 4. I'm using logback 1.2.3 for logging. It happens:

private static final Logger LOG = LoggerFactory.getLogger(ExampleController.class);

On controller method:

```<code>LOG.info("The info"); // Prints nothing
LOG.error("The error"); // It prints on log file
</code>```

I'm giving you logback.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <property name="LOG_PATH" value="${catalina.base}/logs/app" />
  <property name="LOG_NAME" value="app" />

  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_PATH}/${LOG_NAME}.log</file>

    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
        <fileNamePattern>${LOG_PATH}/archived/${LOG_NAME}.%i.log.zip</fileNamePattern>
        <minIndex>1</minIndex>
        <maxIndex>5</maxIndex>
    </rollingPolicy>

    <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
        <maxFileSize>5MB</maxFileSize>
    </triggeringPolicy>

    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %d{dd-MM-yyyy HH:mm:ss} %-5p %t %c:%L - %m%n
        </Pattern>
    </encoder>
  </appender>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %d{dd-MM-yyyy HH:mm:ss} %-5p %t %c:%L - %m%n
        </Pattern>
    </encoder>
  </appender>
  <root level="INFO">
    <appender-ref ref="FILE" />
    <appender-ref ref="STDOUT" />
  </root>
  <root level="ERROR">
    <appender-ref ref="FILE" />
    <appender-ref ref="STDOUT" />
  </root>
</configuration>
</code>```

What is it missing?

答:
You just need to add one block

```<code><root level="INFO">
  <appender-ref ref="FILE"/>
  <appender-ref ref="STDOUT"/>
</root>
</code>```

for your ref="STDOUT". level="INFO" means that you print all log with level >= INFO

So can you try to remove the second one because it probably overrides the first one

```<code><root level="ERROR">
  <appender-ref ref="FILE"/>
  <appender-ref ref="STDOUT"/>
</root>
</code>```

Body:
I have a web application on java spring mvc 4. I'm using logback 1.2.3 for logging. It happens:

private static final Logger LOG = LoggerFactory.getLogger(ExampleController.class);

On controller method:

LOG.info("The info"); // Prints nothing
LOG.error("The error"); // It prints on log file

I'm giving you logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <property name="LOG_PATH" value="${catalina.base}/logs/app" />
  <property name="LOG_NAME" value="app" />

  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_PATH}/${LOG_NAME}.log</file>

    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
        <fileNamePattern>${LOG_PATH}/archived/${LOG_NAME}.%i.log.zip</fileNamePattern>
        <minIndex>1</minIndex>
        <maxIndex>5</maxIndex>
    </rollingPolicy>

    <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
        <maxFileSize>5MB</maxFileSize>
    </triggeringPolicy>

    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %d{dd-MM-yyyy HH:mm:ss} %-5p %t %c:%L - %m%n
        </Pattern>
    </encoder>
  </appender>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %d{dd-MM-yyyy HH:mm:ss} %-5p %t %c:%L - %m%n
        </Pattern>
    </encoder>
  </appender>
  <root level="INFO">
    <appender-ref ref="FILE" />
    <appender-ref ref="STDOUT" />
  </root>
  <root level="ERROR">
    <appender-ref ref="FILE" />
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

What is it missing?

Body:
You just need to add one block

<root level="INFO">
  <appender-ref ref="FILE"/>
  <appender-ref ref="STDOUT"/>
</root>

for your ref="STDOUT". level="INFO" means that you print all log with level >= INFO

So can you try to remove the second one because it probably overrides the first one

<root level="ERROR">
  <appender-ref ref="FILE"/>
  <appender-ref ref="STDOUT"/>
</root>


问:
C# : Currency Rendering Solution
i have to find a solution for this task :

"Supermarkets are increasingly equipped with automatic cash registers. Most of these funds only accept payment by credit card, although a significant proportion of consumers still pay cash (with banknotes and coins).

One of the problems encountered with the cash payment is the rendering of money: how to make a given sum optimally, ie with the minimum number of coins and notes? This is a problem for every one of us every day, let alone the automatic cash registers.

In this exercise, i m asked to try to find an optimal solution to make change in a specific case: when an automatic cash register contains only 2 € coins, 5 € and 10 € banknotes.

To simplify the problem, we will consider that all these coins and bills are available in unlimited quantities.

Here are some examples of currency:

The return of money is expressed by a Currency object. This item has 3 properties: piece2, billet5 and billet10 which respectively store the number of coins of 2 €, 5 € tickets and 10 € tickets.

For example, if we take example 2 of the table (6 €), we should get a Money object with:

Piece2 worth 3 (3 pieces of 2 €)

Ticket5 is worth 0 (no ticket of 5 €)

Ticket10 is worth 0 (no ticket of 10 €)

Task : Implement the MonnaieOptimale(int s) method that returns a Currency object containing the coins and notes whose sum is s. If it is impossible to return the currency (as in example 1), return null.

To get it best the solution will always have to make change when possible and with the minimum number of coins and tickets."

Data: s is always a strictly positive integer (long) less than or equal to 9223372036854775807

the general structure of the solution is the following:

Suggestions ??

答:
```<code>using System;
public class Program {
public static void Main() {
int re10 = 0, re5 = 0, re2 = 0, s = 197;
while (s / 2 != 0) {
    while (s / 5 != 0) {
        while (s / 10 != 0) {
             if (s % 10 % 5 == 0) {
                  re10 = s / 10;
                  s = s % 10;
                     }
              else {
              if (s / 10 > 1) {
               re10 = s / 10 - 1;
               s = s % 10 + 10;
              }
              break;
             }
           }
        if (s % 5 % 2 == 0) {
             re5 = s / 5;
             s = s % 5;
            } else
        if (s / 5 > 1) {
         re5 = s / 5 - 1;
         s = s % 5 + 5;
        }
        break;
       }
  re2 = s / 2;
   s = s % 2;
  }
if(re5==3){re10+=1;re5-=2;}
 Console.WriteLine("billet 10 :" + re10);
 Console.WriteLine("billet 5 :" + re5);
 Console.WriteLine("billet 2 :" + re2);
 Console.WriteLine("Total : "re2 * 2 + re10 * 10 + re5 * 5);
 }
}

billet 10 :18
billet 5 :3
billet 2 :1
Total :  197
</code>```

Title: C# : Currency Rendering Solution


问:
Collapse / concatenate / aggregate multiple columns to a single comma separated string within each group
This is an extension to post Collapse / concatenate / aggregate a column to a single comma separated string within each group

Goal: aggregate multiple columns according to one grouping variable and separate individual values by separator of choice.

Reproducible example:

```<code>data <- data.frame(A = c(rep(111, 3), rep(222, 3)), B = c(rep(c(100), 3), rep(200,3)), C = rep(c(1,2,NA),2), D = c(15:20), E = rep(c(1,NA,NA),2))
data
    A   B  C  D  E
1 111 100  1 15  1
2 111 100  2 16 NA
3 111 100 NA 17 NA
4 222 200  1 18  1
5 222 200  2 19 NA
6 222 200 NA 20 NA
</code>```

A is the grouping variable but B is still displayed in overall result (B depends on A in my application) and C, D and E are the variables to be collapsed into separated character strings.

Desired Output

```<code>    A   B  C    D         E
1 111 100  1,2  15,16,17  1
2 222 100  1,2  18,19,20  1
</code>```

I don't have a ton of experience with R. I did try to expand upon the solutions posted by G. Grothendieck to the linked post to meet my requirements but can't quite get it right for multiple columns.

What would be a proper implementation to get the desired output?

I focused specifically on group_by and summarise_all and aggregate in my attempts. They are a complete mess so I don't believe it would even be helpful to display.

EDIT:
Solutions posted work great at displaying desired result!
To continue improving the value in this post for those that find it.

How would it be possible for users to select their own separation characters.
e.g. '-', '\n'
The current solutions by @akrun and @tmfmnk both  result in lists instead of a concatenated character string. Please correct me if I said this incorrectly.

```<code>data$D
[1] 15 16 17 18 19 20
> data$A
[1] 111 111 111 222 222 222
> data$B
[1] 100 100 100 200 200 200
> data$C
[1]  1  2 NA  1  2 NA
> data$D
[1] 15 16 17 18 19 20
> data$E
[1]  1 NA NA  1 NA NA
</code>```

答:
With dplyr, you can do:

```<code>data %>%
 group_by(A, B) %>%
 summarise_all(~ toString(na.omit(.)))

      A     B C     D          E
  <dbl> <dbl> <chr> <chr>      <chr>
1   111   100 1, 2  15, 16, 17 1
2   222   200 1, 2  18, 19, 20 1
</code>```

Body:
This is an extension to post Collapse / concatenate / aggregate a column to a single comma separated string within each group

Goal: aggregate multiple columns according to one grouping variable and separate individual values by separator of choice.

Reproducible example:

data <- data.frame(A = c(rep(111, 3), rep(222, 3)), B = c(rep(c(100), 3), rep(200,3)), C = rep(c(1,2,NA),2), D = c(15:20), E = rep(c(1,NA,NA),2))
data
    A   B  C  D  E
1 111 100  1 15  1
2 111 100  2 16 NA
3 111 100 NA 17 NA
4 222 200  1 18  1
5 222 200  2 19 NA
6 222 200 NA 20 NA

A is the grouping variable but B is still displayed in overall result (B depends on A in my application) and C, D and E are the variables to be collapsed into separated character strings.

Desired Output

    A   B  C    D         E
1 111 100  1,2  15,16,17  1
2 222 100  1,2  18,19,20  1

I don't have a ton of experience with R. I did try to expand upon the solutions posted by G. Grothendieck to the linked post to meet my requirements but can't quite get it right for multiple columns.

What would be a proper implementation to get the desired output?

I focused specifically on group_by and summarise_all and aggregate in my attempts. They are a complete mess so I don't believe it would even be helpful to display.

EDIT:
Solutions posted work great at displaying desired result!
To continue improving the value in this post for those that find it.

How would it be possible for users to select their own separation characters.
e.g. '-', '\n'
The current solutions by @akrun and @tmfmnk both  result in lists instead of a concatenated character string. Please correct me if I said this incorrectly.

data$D
[1] 15 16 17 18 19 20
> data$A
[1] 111 111 111 222 222 222
> data$B
[1] 100 100 100 200 200 200
> data$C
[1]  1  2 NA  1  2 NA
> data$D
[1] 15 16 17 18 19 20
> data$E
[1]  1 NA NA  1 NA NA

Body:
With dplyr, you can do:

data %>%
 group_by(A, B) %>%
 summarise_all(~ toString(na.omit(.)))

      A     B C     D          E
  <dbl> <dbl> <chr> <chr>      <chr>
1   111   100 1, 2  15, 16, 17 1
2   222   200 1, 2  18, 19, 20 1


答:
We can group by 'A', 'B', and use summarise_at to paste all the non-NA elements

```<code>library(dplyr)
data %>%
    group_by(A, B) %>%
    summarise_at(vars(-group_cols()), ~ toString(.[!is.na(.)]))
# A tibble: 2 x 5
# Groups:   A [2]
#      A     B C     D          E
#  <dbl> <dbl> <chr> <chr>      <chr>
#1   111   100 1, 2  15, 16, 17 1
#2   222   200 1, 2  18, 19, 20 1
</code>```

If we need to pass custom delimiter, use paste or str_c

```<code>library(stringr)
data %>%
    group_by(A, B) %>%
    summarise_at(vars(-group_cols()), ~ str_c(.[!is.na(.)], collapse="_"))
</code>```

Or using base R with aggregate

```<code>aggregate(. ~ A + B, data, FUN = function(x)
      toString(x[!is.na(x)]), na.action = NULL)
</code>```

Title: Collapse / concatenate / aggregate multiple columns to a single comma separated string within each group

Body:
We can group by 'A', 'B', and use summarise_at to paste all the non-NA elements

library(dplyr)
data %>%
    group_by(A, B) %>%
    summarise_at(vars(-group_cols()), ~ toString(.[!is.na(.)]))
# A tibble: 2 x 5
# Groups:   A [2]
#      A     B C     D          E
#  <dbl> <dbl> <chr> <chr>      <chr>
#1   111   100 1, 2  15, 16, 17 1
#2   222   200 1, 2  18, 19, 20 1

If we need to pass custom delimiter, use paste or str_c

library(stringr)
data %>%
    group_by(A, B) %>%
    summarise_at(vars(-group_cols()), ~ str_c(.[!is.na(.)], collapse="_"))

Or using base R with aggregate

aggregate(. ~ A + B, data, FUN = function(x)
      toString(x[!is.na(x)]), na.action = NULL)


问:
Minimum time quantum needed in nanosleep(), usleep() to yield the CPU
In concurrent code in my workplace, there are several occurrences of nanosleep() or usleep() with a non-zero constant to free up the CPU without relying on futex(), or a sleeping synchronization primitive to put the thread to sleep (for instance, when waiting for an element from a concurrent queue). The code claims to prevent pathological cases where threads consume CPU without doing any actual work when other threads are available to get scheduled on that CPU. This sounds reasonable by itself assuming the cooperation between the sleep functions and the kernel thread scheduler is correct.

Is there a concept in linux where a minimum duration passed to nanosleep(), usleep(), et al. is known to put the calling thread to sleep and run another thread in it's place on the same core when cores are oversubscribed? And if the duration is smaller than that, then the thread does not actually yield the CPU but continue spinning? This forms the basis of the constant passed to the sleep() functions in order to make it behave like a coarse-yield.

I realize that a sched_yield() is probably better suited for what the code is doing; but I just wanted to educate myself on the behavior of the linux sleep() functions before benchmarking a replacement or improvement on the existing code.

Thanks!

答: @stark has answered your question as written, but to elaborate, don't do that. If you're waiting for an event to happen, perform an operation that waits for the event, like pthread_cond_wait, sem_wait, poll, read, etc. rather than sleeping and retrying. This will avoid wasting lots of cpu time, and it also discourages erroneous programming models full of data races (because normally the same primitive that waits also ensures exclusive access/synchronization).


问:
Why am getting an "elif" syntax error showing invalid syntax in python
Whts wrong in this statement??
and why am getting this error.

```<code>a = 200
b = 33
c = 500
if a < b:
  print("Both conditions are True")
  elif a>b and True :
  print("f")
</code>```

Error:

```<code>elif a>b and True :
       ^
SyntaxError: invalid syntax
</code>```

答:
The identation is incorrect and causing the error. Also, the and true does not serve anything there. You can try the following code:

```<code>a = 200
b = 33
c = 500
if a < b:
  print("Both conditions are True")
elif a > b:
  print("f")
</code>```

Body:
Whts wrong in this statement??
and why am getting this error.

a = 200
b = 33
c = 500
if a b and True :
  print("f")

Error:

elif a>b and True :
       ^
SyntaxError: invalid syntax

Body:
The identation is incorrect and causing the error. Also, the and true does not serve anything there. You can try the following code:

a = 200
b = 33
c = 500
if a < b:
  print("Both conditions are True")
elif a > b:
  print("f")


问:
Sitecore OMS - achieving a goal on a form submission
I inherited a Sitecore solution that has a sublayout that contains a complex ASP.NET ascx form which handles both payments and integration with 3rd party web services.

This sublayout uses parameters templates to provide some level of control on the way the form looks like.

The .ascx control contains multiple views:

In the first view the user fills the
form and click NEXT.

In the second view the user can review the entered data before
clicking the SUBMIT button.

The third view is the thank you page of the form.

If I want to create a goal for the submission of this form, am I supposed to set the goal as "achieved" via API on submission of the form itself? Should I add, maybe, the name of the goal as one of the parameter templates so that the marketing editors will be able to change it, if needed?

Thanks

答:
You have several possibilities:

Most forms have a confirmation page, when everything is submitted and approved. You can attach an event to this page through the normal user interface. There are no special code required for this and it is out of the box.

As you say you can do it by code. This is fairly easy and should look something like this:

public void RegisterEvent(){
  if (!AnalyticsTracker.IsActive)
    return;

AnalyticsTracker tracker = AnalyticsTracker.Current;

if (tracker == null || tracker.CurrentPage == null)
    return;

AnalyticsPageEvent pageEvent = new AnalyticsPageEvent()
  {
    Name = "TheNameOfYourEvent",
    Key = "TheKeyOfTheEvent",
    Text = "SomeText",
    Data = "Event data can contain all the entered information if you like",
  };

tracker.CurrentPage.TriggerEvent(pageEvent);
  tracker.Submit();
}

Whether you hardcode the event or you make it variable depends on whether you need to change the event frequent.

The first option is the most simple, but if you also want to integrate to a CRM and store user input, you might want to go with option 2 as you can store the profile data as well.

Hope that helps!


答:
elif goes on the same level of indentation as if. It's after the if statement, not inside it:

```<code>if a < b:
  print("Both conditions are True")
elif a>b and True :
  print("f")
</code>```

Title: Why am getting an "elif" syntax error showing invalid syntax in python

Body:
elif goes on the same level of indentation as if. It's after the if statement, not inside it:

if a < b:
  print("Both conditions are True")
elif a>b and True :
  print("f")


问:
SQL query that displays the current date and count of days between two specific dates
I am trying to write a SQL query that shows the count of the days and date depending upon the financial period it falls in. The financial period starts 5 days before the month end eg march 27th to 26th April

For the above mentioned period if the day is 29th march, the count of the day should be 3 and the date should be 2020-04. The date should adjust depending upon the period it falls in.

I tried to adress the second part of this query by writing the below script but it does not bring any result

```<code>declare @date datetime
set @date = getdate()
SELECT format (date,'yyyy-MM-dd') as date

where @date

between dateadd(day,-5,EOMONTH(getdate(),-1)) and dateadd(day,-5,EOMONTH(getdate()))
</code>```

答:
The following code will calculate what you need. Please read the comments in the code itself.

```<code>-- First, lets declare all the variables we need.
-- I tried to name them so they are selfexplanatory.
declare @inputdate DateTime,
            @financialPeriodStartDate DateTime,
            @EndOfTheMonth DateTime,
            @nextFinantialMonthYear DateTime,
            @previousFinancialPeriodStartDate DateTime
-- Now we calculate some of the values
    set @inputdate = GETDATE() -- Let's use Today's date, but you can change this to any date.
    set @EndOfTheMonth = EOMONTH(@inputdate) -- This is the end of the month for the input date
    set @financialPeriodStartDate = DATEADD(DAY,-5,EOMONTH(@inputdate)) -- This is you Financial Period Start Date for the giving input date.
    set @previousFinancialPeriodStartDate = DATEADD(DAY,-5,EOMONTH(DATEADD(MONTH, -1, @inputdate))) -- Also calculates the Start Date of the precious financial period.
    set @nextFinantialMonthYear = DATEADD(MONTH, 1,@financialPeriodStartDate) -- This is the start date of the next financial period.

-- In the following Select, it calculates the values you need, based in the previous variables.
    select
    @inputdate as Today,
    @EndOfTheMonth as EndOfMonth,
    @previousFinancialPeriodStartDate as PreviousFinancialPeriodStartDate,
    @financialPeriodStartDate as FinacialPeriodStartDate,
    CASE WHEN DATEDIFF(DAY , @financialPeriodStartDate, @inputdate + 1  ) < 0
         THEN DATEDIFF(DAY , @previousFinancialPeriodStartDate, @inputdate + 1  )
         WHEN DATEDIFF(DAY , @financialPeriodStartDate, @inputdate + 1  ) >=0
         THEN DATEDIFF(DAY , @financialPeriodStartDate, @inputdate + 1  )
    END as DaysFromFPStartDate,
    STR(YEAR(@nextFinantialMonthYear)) +'-'+LTRIM(RTRIM(STR(MONTH(@nextFinantialMonthYear)))) as NextFinantialPeriodMonthAndYear
</code>```

I hope it helps.

Body:
I am trying to write a SQL query that shows the count of the days and date depending upon the financial period it falls in. The financial period starts 5 days before the month end eg march 27th to 26th April

For the above mentioned period if the day is 29th march, the count of the day should be 3 and the date should be 2020-04. The date should adjust depending upon the period it falls in.

I tried to adress the second part of this query by writing the below script but it does not bring any result

declare @date datetime
set @date = getdate()
SELECT format (date,'yyyy-MM-dd') as date

where @date

between dateadd(day,-5,EOMONTH(getdate(),-1)) and dateadd(day,-5,EOMONTH(getdate()))

Body:
The following code will calculate what you need. Please read the comments in the code itself.

-- First, lets declare all the variables we need.
-- I tried to name them so they are selfexplanatory.
declare @inputdate DateTime,
            @financialPeriodStartDate DateTime,
            @EndOfTheMonth DateTime,
            @nextFinantialMonthYear DateTime,
            @previousFinancialPeriodStartDate DateTime
-- Now we calculate some of the values
    set @inputdate = GETDATE() -- Let's use Today's date, but you can change this to any date.
    set @EndOfTheMonth = EOMONTH(@inputdate) -- This is the end of the month for the input date
    set @financialPeriodStartDate = DATEADD(DAY,-5,EOMONTH(@inputdate)) -- This is you Financial Period Start Date for the giving input date.
    set @previousFinancialPeriodStartDate = DATEADD(DAY,-5,EOMONTH(DATEADD(MONTH, -1, @inputdate))) -- Also calculates the Start Date of the precious financial period.
    set @nextFinantialMonthYear = DATEADD(MONTH, 1,@financialPeriodStartDate) -- This is the start date of the next financial period.

-- In the following Select, it calculates the values you need, based in the previous variables.
    select
    @inputdate as Today,
    @EndOfTheMonth as EndOfMonth,
    @previousFinancialPeriodStartDate as PreviousFinancialPeriodStartDate,
    @financialPeriodStartDate as FinacialPeriodStartDate,
    CASE WHEN DATEDIFF(DAY , @financialPeriodStartDate, @inputdate + 1  ) < 0
         THEN DATEDIFF(DAY , @previousFinancialPeriodStartDate, @inputdate + 1  )
         WHEN DATEDIFF(DAY , @financialPeriodStartDate, @inputdate + 1  ) >=0
         THEN DATEDIFF(DAY , @financialPeriodStartDate, @inputdate + 1  )
    END as DaysFromFPStartDate,
    STR(YEAR(@nextFinantialMonthYear)) +'-'+LTRIM(RTRIM(STR(MONTH(@nextFinantialMonthYear)))) as NextFinantialPeriodMonthAndYear

I hope it helps.


问:
Extending/Inheriting Tomcat Projects
We are developing webapps with Eclipse + Tomcat plugin. We recently started a new app which will run on Facebook and StudiVZ (FB competitor in Germany). Since the functionality of the app will be 95% the same we split the code into separate Eclipse projects (app-core, app-facebook, app-vz). The -core project is source-linked into the -facebook and -vz projects in Eclipse. We are also using Hudson for CI and made ant scripts that import the code from the -core project before building. So basically we tried to inherit on a project level.

The described method has some flaws:

Versioning is complicated

The -core project does not run standalone, which makes automatic testing partly impossible

We need to modify some models where the -core projects classes depend on

Other problems that make me think this is not the best solution

Does anyone have suggestions for a better solution?

答:
I don't use/hate Eclipse[1], but can point to how we deal with a similar problem.

We use Maven with IntelliJ. In particular, both of these support modules which have defined internal dependencies. In your case it could be -fb and -vz modules depending on core, or you can split core into smaller parts (such as DAO, business logic, etc.).

When compiling, deliverables of "upper" modules would be used to build "lower" modules.

Let's go over points/flaws you have raised:

versioning is no longer a problem as everything sits under the same root of Subversion/GIT/VCS of your choice

Why is that a problem? Certainly this shouldn't be an issue for unit tests as how I understand TDD, these should not require complex environments. For automated tests, you would have to test the core API (as this is the interface between core and everything else, right?) hence this shouldn't require any fronted stuff?

you need to explain your other points to tell why you don't like it

It is against Geneva convention to ask a developer to use anything other than IDE of his/her choice.

Title: Extending/Inheriting Tomcat Projects