text:
Q: Angular 2, @ngtools/webpack, AOT I'm trying to use AOT in Angular 2 using webpack and @ngtools/webpack.
I don't have any error with the compilation, but when I open the site on the browser I get a console error:
No NgModule metadata found for 'AppModule'
My AotPlugin on webpack configuration is this:
new AotPlugin({
    tsConfigPath: 'tsconfig.json',
    entryModule: helpers.root('src/app/app.module.ts#AppModule')
})

My app.module.ts is:
@NgModule({
bootstrap: [ App ],
imports: [ // import Angular's modules
    BrowserModule,
    RouterModule.forRoot(ROUTES),
    SharedModule
],
declarations: [
    App,
    HomeComponent,
],
providers: providers
})
export class AppModule {}

and my main.browser.ts:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from "./app/app.module";

const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);

My tsconfig.json:
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "noEmitHelpers": true,
    "removeComments": true,
    "lib": ["es6", "dom"],
    "strictNullChecks": false,
    "baseUrl": "./src",
    "paths": [],
    "types": [
      "hammerjs",
      "jasmine",
      "node",
      "protractor",
      "selenium-webdriver",
      "source-map",
      "webpack"
    ]
  },
  "exclude": [
    "node_modules",
    "dist"
  ],
  "awesomeTypescriptLoaderOptions": {
    "forkChecker": true,
    "useWebpackText": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": { "rewriteTsconfig": false },
    "angularCompilerOptions": {
    "genDir": "dist",
    "entryModule": "src/app/app.module#AppModule"
  }
}

Webpack.config.js:
switch (process.env.NODE_ENV) {
  case 'prod':
  case 'production':
    module.exports = require('./config/webpack.prod')({env: 'production'});
    break;
  case 'test':
  case 'testing':
    module.exports = require('./config/webpack.test')({env: 'test'});
    break;
  case 'dev':
  case 'development':
  default:
    module.exports = require('./config/webpack.dev')({env: 'development'});
}

My /config/webpack.prod.js:
const webpack = require('webpack');
const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
    const commonConfig = require('./webpack.common.js').config; // the settings that are common to prod and dev
const hashName = require('./random-hash.js')(); // the settings that are common to prod and dev

    /**
     * Webpack Plugins
     */
    const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const DedupePlugin = require('webpack/lib/optimize/DedupePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');

/**
 * Webpack Constants
 */
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 8080;
const METADATA = webpackMerge(require('./webpack.common.js').metadata, {
    host: HOST,
    port: PORT,
    ENV: ENV
});

module.exports = function (env) {
    return webpackMerge(commonConfig({ env: ENV }), {

        devtool: 'hidden-source-map',

        output:{
            path: helpers.root('dist'),
            filename: '[name].bundle.js?ver='+ hashName,
            sourceMapFilename: '../maps/' + '[name].map?ver='+ hashName,
            chunkFilename: '[id].chunk.js?ver='+ hashName
        },

        plugins: [
            // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
            new DefinePlugin({
                'ENV': JSON.stringify(METADATA.ENV),
                'process.env': {
                    'ENV': JSON.stringify(METADATA.ENV),
                    'NODE_ENV': JSON.stringify(METADATA.ENV)
                }
            }),
            new webpack.LoaderOptionsPlugin({
                optons: {
                    debug: false,
                    htmlLoader: {
                        minimize: true,
                        removeAttributeQuotes: false,
                        caseSensitive: true,
                        customAttrSurround: [
                            [/#/, /(?:)/],
                            [/\*/, /(?:)/],
                            [/\[?\(?/, /(?:)/]
                            ],
                            customAttrAssign: [/\)?\]?=/]
                    },
                    tslint: {
                        emitErrors: true,
                        failOnHint: true,
                        resourcePath: 'src'
                    },
                    postLoaders: [
                        {
                            test: /\.js$/,
                            loader: 'string-replace-loader',
                            query: {
                                search: 'var sourceMappingUrl = extractSourceMappingUrl\\(cssText\\);',
                                    replace: 'var sourceMappingUrl = "";',
                                        flags: 'g'
                            }
                        }
                    ],
                    preLoaders: [
                    {
                        test: /\.ts$/,
                        loader: 'string-replace-loader',
                        query: {
                            search: '(System|SystemJS)(.*[\\n\\r]\\s*\\.|\\.)import\\((.+)\\)',
                            replace: '$1.import($3).then(mod => (mod.__esModule && mod.default) ? mod.default : mod)',
                            flags: 'g'
                        },
                        include: [helpers.root('src')]
                    },
                    {
                        test: /\.ts$/,
                        loader: 'tslint-loader',
                        options: {
                            configFile: 'tslint.json'
                        },
                        exclude: [/\.(spec|e2e)\.ts$/]
                    }

                ]
                }
            })
        ],

        node: {
            global: true,
            crypto: 'empty',
            process: false,
            module: false,
            clearImmediate: false,
            setImmediate: false
        }

    });
};

And config/webpack.common.js:
const webpack = require('webpack');
const helpers = require('./helpers');

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const AssetsPlugin = require('assets-webpack-plugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const AotPlugin = require('@ngtools/webpack').AotPlugin;

/*
 * Webpack Constants
 */
/*
 * Static metadata for index.html
 *
 * See: (custom attribute)
 */
const METADATA = {
    title: '',
    baseUrl: '/',
    isDevServer: helpers.isWebpackDevServer()
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = {
    metadata: METADATA,
    config: function(options) {
        isProd = options.env === 'production';
        return {

            /*
             * Cache generated modules and chunks to improve performance for multiple incremental builds.
             * This is enabled by default in watch mode.
             * You can pass false to disable it.
             *
             * See: http://webpack.github.io/docs/configuration.html#cache
             */
            //cache: false,

            /*
             * The entry point for the bundle
             * Our Angular.js app
             *
             * See: http://webpack.github.io/docs/configuration.html#entry
             */
            entry: {

                'polyfills': './src/polyfills.browser.ts',
                'vendor':    './src/vendor.browser.ts',
                'main':      './src/main.browser.ts'

            },
            // output: {
            //   // Make sure to use [name] or [id] in output.filename
            //   //  when using multiple entry points
            //   //    filename: "[name].bundle.js",
            //   //  chunkFilename: "[id].bundle.js"
            //   publicPath: "https://d3ohoc4mai6ihm.cloudfront.net"
            // },

            /*
             * Options affecting the resolving of modules.
             *
             * See: http://webpack.github.io/docs/configuration.html#resolve
             */
            resolve: {

                /*
                 * An array of extensions that should be used to resolve modules.
                 *
                 * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
                 */
                extensions: ['.ts', '.js', '.json'],

                // An array of directory names to be resolved to the current directory
                modules: [helpers.root('src'), 'node_modules'],

            },

            /*
             * Options affecting the normal modules.
             *
             * See: http://webpack.github.io/docs/configuration.html#module
             */
            module: {

                /*
                 * An array of automatically applied loaders.
                 *
                 * IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
                 * This means they are not resolved relative to the configuration file.
                 *
                 * See: http://webpack.github.io/docs/configuration.html#module-loaders
                 */
                loaders: [

                    /* Ahead of time plugin */
                    {
                        test: /\.ts$/,
                        loader: '@ngtools/webpack',
                    },

                    /*
                     * Json loader support for *.json files.
                     *
                     * See: https://github.com/webpack/json-loader
                     */
                    {
                        test: /\.json$/,
                        loader: 'json-loader'
                    },

                    /*
                     * to string and css loader support for *.css files
                     * Returns file content as string
                     *
                     */
                    {
                        test: /\.css$/,
                        loaders: ['to-string-loader', 'css-loader']
                    },

                    /* Raw loader support for *.html
                     * Returns file content as string
                     *
                     * See: https://github.com/webpack/raw-loader
                     */
                    {
                        test: /\.html$/,
                        loader: 'raw-loader',
                        exclude: [helpers.root('src/index.html')]
                    },

                    /* File loader for supporting images, for example, in CSS files.
                     */
                    {
                        test: /\.(jpg|png|gif)$/,
                        loader: 'url-loader?limit=100000000000'
                    },

                    // Support for SCSS as raw text
                    {
                        test: /\.scss$/,
                        loaders: ['raw-loader', 'sass-loader']
                    },

                    //{ test: /\.scss$/, loaders: ['style', 'css', 'postcss', 'sass'] },

                    {test: /\.(woff2?|ttf|eot|svg)$/, loader: 'url-loader?limit=100000000000'}

                ],

            },

            /*
             * Add additional plugins to the compiler.
             *
             * See: http://webpack.github.io/docs/configuration.html#plugins
             */
            plugins: [
                new AssetsPlugin({
                    path: helpers.root('dist'),
                    filename: 'webpack-assets.json',
                    prettyPrint: true
                }),

                /*
                 * Plugin: ForkCheckerPlugin
                 * Description: Do type checking in a separate process, so webpack don't need to wait.
                 *
                 * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
                 */
                new ForkCheckerPlugin(),
                /*
                 * Plugin: CommonsChunkPlugin
                 * Description: Shares common code between the pages.
                 * It identifies common modules and put them into a commons chunk.
                 *
                 * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
                 * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
                 */
                new webpack.optimize.CommonsChunkPlugin({
                    name: ['polyfills', 'vendor'].reverse()
                }),

                /**
                 * Plugin: ContextReplacementPlugin
                 * Description: Provides context to Angular's use of System.import
                 *
                 * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
                 * See: https://github.com/angular/angular/issues/11580
                 */
                new ContextReplacementPlugin(
                    // The (\\|\/) piece accounts for path separators in *nix and Windows
                    /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
                    helpers.root('src') // location of your src
                ),
                new ContextReplacementPlugin(
                    // The (\\|\/) piece accounts for path separators in *nix and Windows
                    /moment[\/\\]locale$/, /en-gb/
                ),

                /*
                 * Plugin: CopyWebpackPlugin
                 * Description: Copy files and directories in webpack.
                 *
                 * Copies project static assets.
                 *
                 * See: https://www.npmjs.com/package/copy-webpack-plugin
                 */
                new CopyWebpackPlugin([{
                    from: 'src/assets',
                    to: 'assets'
                }]),

                /*
                 * Plugin: HtmlWebpackPlugin
                 * Description: Simplifies creation of HTML files to serve your webpack bundles.
                 * This is especially useful for webpack bundles that include a hash in the filename
                 * which changes every compilation.
                 *
                 * See: https://github.com/ampedandwired/html-webpack-plugin
                 */
                new HtmlWebpackPlugin({
                    template: 'src/index.html',
                    chunksSortMode: 'dependency'
                }),

                /*
                 * Plugin: HtmlHeadConfigPlugin
                 * Description: Generate html tags based on javascript maps.
                 *
                 * If a publicPath is set in the webpack output configuration, it will be automatically added to
                 * href attributes, you can disable that by adding a "=href": false property.
                 * You can also enable it to other attribute by settings "=attName": true.
                 *
                 * The configuration supplied is map between a location (key) and an element definition object (value)
                 * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
                 *
                 * Example:
                 *  Adding this plugin configuration
                 *  new HtmlElementsPlugin({
                     *    headTags: { ... }
                     *  })
                 *
                 *  Means we can use it in the template like this:
                 *  <%= webpackConfig.htmlElements.headTags %>
                 *
                 * Dependencies: HtmlWebpackPlugin
                 */
                new HtmlElementsPlugin({
                    headTags: require('./head-config.common')
                }),

                /* Ahead of time compilation plugin */
                new AotPlugin({
                    tsConfigPath: 'tsconfig.json',
                    entryModule: helpers.root('src', 'app', 'app.module.ts#AppModule')
                })
            ],

            /*
             * Include polyfills or mocks for various node stuff
             * Description: Node configuration
             *
             * See: https://webpack.github.io/docs/configuration.html#node
             */
            node: {
                global: 'window',
                crypto: 'empty',
                process: true,
                module: false,
                clearImmediate: false,
                setImmediate: false
            }

        };
    }
}

Complete error trace:
Uncaught Error: No NgModule metadata found for 'AppModule'.
    at NgModuleResolver.resolve (vendor.bundle.js?ver=d1084b5…:18969) [<root>]
    at CompileMetadataResolver.getNgModuleMetadata (vendor.bundle.js?ver=d1084b5…:18172) [<root>]
    at JitCompiler._loadModules (vendor.bundle.js?ver=d1084b5…:50582) [<root>]
    at JitCompiler._compileModuleAndComponents (vendor.bundle.js?ver=d1084b5…:50542) [<root>]
    at JitCompiler.compileModuleAsync (vendor.bundle.js?ver=d1084b5…:50508) [<root>]
    at PlatformRef_._bootstrapModuleWithZone (vendor.bundle.js?ver=d1084b5…:39236) [<root>]
    at PlatformRef_.bootstrapModule (vendor.bundle.js?ver=d1084b5…:39211) [<root>]
    at Object.<anonymous> (main.bundle.js?ver=d1084b5…:34315) [<root>]
    at __webpack_require__ (polyfills.bundle.js?ver=d1084b5…:53) [<root>]
    at webpackJsonpCallback (polyfills.bundle.js?ver=d1084b5…:24) [<root>]
    at :8080/main.bundle.js?ver=d1084b5dbd73943cc778978401608960:1:1 [<root>]

I don't really know what's going on. I really appreciate your time and you help.

A: I don't really know if it helps, but I had similar problem. I'm guessing you are using some kind of boilerplate because you have this helpers.root function.
First of all try to change this part:
new AotPlugin({
    tsConfigPath: 'tsconfig.json',
    entryModule: helpers.root('src/app/app.module.ts#AppModule')
})

to this (adding helpers.root part to tsconfig.json file):
new AotPlugin({
    tsConfigPath: helpers.root('tsconfig.json'),
    entryModule: helpers.root('src/app/app.module.ts#AppModule')
})

Second of all double check your tsconfig.json to be configured to AoT compilation. This is my tsconfig-aot.json which I',m using in one of my Angular 2 projects:
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es2015", "dom"],
    "noImplicitAny": false,
    "sourceRoot": ".",
    "suppressImplicitAnyIndexErrors": true,
    "typeRoots": [
      "node_modules/@types"
    ]
  },

  "awesomeTypescriptLoaderOptions": {
    "useWebpackText": true,
    "forkChecker": true,
    "useCache": true
  },

  "angularCompilerOptions": {
    "genDir": "aot",
    "skipMetadataEmit" : true
  }
}

Hope this will help!

A: Try rolling back to ngtools/webpack version 1.2.4 there are issues with the path resolution in later versions related to this issue 5329.


text:
Q: Design pattern for waiting for user interaction in iOS? I'm developing a BlackJack game for iOS. Keeping track of the current state and what needs to be done is becoming difficult. For example, I have a C++ class which keeps track of the current Game:
class Game {
  queue<Player> playerQueue;
  void hit();
  void stand();
}

Currently I'm implementing it using events (Method A):
- (void)hitButtonPress:(id)sender {
  game->hit();
}

void Game::hit() {
  dealCard(playerQueue.top());
}

void Game::stand() {
  playerQueue.pop();
  goToNextPlayersTurn();
}

as more and more options are added to the game, creating events for each one is becoming tedious and hard to keep track of.
Another way I thought of implementing it is like so (Method B):
void Game::playersTurn(Player *player) {
  dealCards(player);
  while (true) {
    string choice = waitForUserChoice();
    if (choice == "stand") break;
    if (choice == "hit")
      dealCard(player);
    // etc.
  }
  playerQueue.pop();
  goToNextPlayersTurn();
}

Where waitForUserChoice is a special function that lets the user interact with the UIViewController and once the user presses a button, only then returns control back to the playersTurn function. In other words, it pauses the program until the user clicks on a button.
With method A, I need to split my functions up every time I need user interaction. Method B lets everything stay a bit more in control.
Essentially the difference between method A and B is the following:
A:
function A() {
  initialize();
  // now wait for user interaction by waiting for a call to CompleteA
}

function CompleteA() {
  finalize();
}

B:
function B() {
  initialize();
  waitForUserInteraction();
  finalize();
}

Notice how B keeps the code more organized. Is there even a way to do this with Objective-C? Or is there a different method which I haven't mentioned recommended instead?
A third option I can think of is using a finite state machine. I have heard a little about them, but I'm sure if that will help me in this case or not.
What is the recommended design pattern for my problem?

A: I understand the dilemma you are running into.  When I first started iOS I had a very hard time wrapping my head around relinquishing control to and from the operating system.
In general iOS would encourage you to go with method A.  Usually you have variables in your ViewController which are set in method A(), and then they are checked in CompleteA() to verify that A() ran first etc.
Regarding your question about Finite State Machines, I think that it may help you solve your problem.  The very first thing I wrote in iOS was a FSM (there for this is pretty bad code) however you can take a look here (near the bottom of FlipsideViewController.m:
https://github.com/esromneb/ios-finite-state-machine
The general idea is that you put this in your .h file inside an @interface block
static int state = 0;
static int running = 0;

And in your .m you have this:
- (void) tick {

    switch (state) {
        case 0:
            //this case only runs once for the fsm, so setup one time initializations

            // next state
            state = 1;

            break;
        case 1:
            navBarStatus.topItem.title = @"Connecting...";
            state = 2;
            break;
        case 2:
            // if something happend we move on, if not we wait in the connecting stage
            if( something )
                state = 3;
            else
                state = 1;
            break;
        case 3:
            // respond to something

            // next state
            state = 4;
            break;
        case 4:
            // wait for user interaction
            navBarStatus.topItem.title = @"Press a button!";
            state = 4;

            globalCommand = userInput;

            // if user did something
            if( globalCommand != 0 )
            {
                // go to state to consume user interaction
                state = 5;
            }

            break;

        case 5:
            if( globalCommand == 6 )
            {
                // respond to command #6
            }
            if( globalCommand == 7 )
            {
                // respond to command #7
                }

                        // go back and wait for user input
                        state = 4;
            break;

        default:
            state = 0;
            break;
    }

    if( running )
    {
        [self performSelector:@selector(tick) withObject:nil afterDelay:0.1];
    }
}

In this example (modified from the one on github) globalCommand is an int representing the user's input.  If globalCommand is 0, then the FSM just spins in state 4 until globalCommand is non zero.
To start the FSM, simply set running to 1 and call [self tick] from the viewController.  The FSM will "tick" every 0.1 seconds until running is set to 0.
In my original FSM design I had to respond to user input AND network input from a windows computer running it's own software.  In my design the windows PC was also running a similar but different FSM.  For this design, I built two FIFO queue objects of commands using an NSMutuableArray.  User interactions and network packet would enqueue commands into the queues, while the FSM would dequeue items and respond to them.  I ended up using https://github.com/esromneb/ios-queue-object for the queues.
Please comment if you need any clarification.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best Practice to adjust height of Material UI Icon I put two icons from Material UI Icons in a row. The heights themselves are same: 24px. But the height of path is different. One is 18px and the other is 22px. They don't look cool.
How can I adjust the height? I mean "the height that users see".
import {
  Delete,
  FileCopy
} from "@material-ui/icons";

...

<Box display="flex">
  <FileCopy onClick={handleCopy} />
  <Delete onClick={handleDelete} />
</Box>

I tried setting the the height of SVG, it made vertical align ugly...

A: The icons have a fontSize property - e.g. <HomeIcon fontSize="large" />.
You can also set it explicitly - <DeleteIcon style={{fontSize: "10px"}}/>.

A: It's tough to answer this question without more context of the components and what you can pass to them and what is being returned from them.
Assuming <FileCopy /> is returning an SVG element that you can pass valid svg properties to, the correct way to adjust the size would be to pass it height and width attributes.
<FileCopy height='48' width='48' />

Another way to think about this is the svgs likely have a viewBox that acts as a canvas. The height and width properties of the svg will change the size of the viewBox/canvas with the icon/paths inside it scaling along with it.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" height='24' width='24'><circle fill="#FF4500" cx="10" cy="10" r="10"/><path fill="#FFF" d="M16.67 10a1.46 1.46 0 00-2.47-1 7.12 7.12 0 00-3.85-1.23L11 4.65l2.14.45a1 1 0 10.13-.61L10.82 4a.31.31 0 00-.37.24l-.74 3.47a7.14 7.14 0 00-3.9 1.23 1.46 1.46 0 10-1.61 2.39 2.87 2.87 0 000 .44c0 2.24 2.61 4.06 5.83 4.06s5.83-1.82 5.83-4.06a2.87 2.87 0 000-.44 1.46 1.46 0 00.81-1.33zm-10 1a1 1 0 111 1 1 1 0 01-1-1zm5.81 2.75a3.84 3.84 0 01-2.47.77 3.84 3.84 0 01-2.47-.77.27.27 0 01.38-.38A3.27 3.27 0 0010 14a3.28 3.28 0 002.09-.61.27.27 0 11.39.4zm-.18-1.71a1 1 0 111-1 1 1 0 01-1.01 1.04z"/></svg>

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" height='48' width='48'><circle fill="#FF4500" cx="10" cy="10" r="10"/><path fill="#FFF" d="M16.67 10a1.46 1.46 0 00-2.47-1 7.12 7.12 0 00-3.85-1.23L11 4.65l2.14.45a1 1 0 10.13-.61L10.82 4a.31.31 0 00-.37.24l-.74 3.47a7.14 7.14 0 00-3.9 1.23 1.46 1.46 0 10-1.61 2.39 2.87 2.87 0 000 .44c0 2.24 2.61 4.06 5.83 4.06s5.83-1.82 5.83-4.06a2.87 2.87 0 000-.44 1.46 1.46 0 00.81-1.33zm-10 1a1 1 0 111 1 1 1 0 01-1-1zm5.81 2.75a3.84 3.84 0 01-2.47.77 3.84 3.84 0 01-2.47-.77.27.27 0 01.38-.38A3.27 3.27 0 0010 14a3.28 3.28 0 002.09-.61.27.27 0 11.39.4zm-.18-1.71a1 1 0 111-1 1 1 0 01-1.01 1.04z"/></svg>


text:
Q: Kyokasuigetsu's Kanzen Saimin (Complete Hypnosis) Escape Method During Ichimaru gin's betrayal toward Aizen in Bleach, he mentions that the only way to escape Kyokasuigetsu's power, Kanzen Saimin or Complete Hypnosis, is to touch the tip of the blade before it is released. Now what confuses me is whether you would need to touch the tip of the blade every time before it is released, or just once and Kyokasuigetsu would never be able to affect you?

A: After re-watching Bleach, seeing how Ichimaru Gin keep holding Aizen's sword before he stabbed him, I think one would need to constantly holding the blade to escape Kanzen Saimin, since Gin didn't let go of the blade before stabbing Aizen. Adding to this hypothesis is during Hirako Shinji vs Aizen battle, Aizen asked him since when did he is under the impression that Aizen is not using Kyoka Suigetsu's power, which means that when Aizen decided to release his shikai, you won't even notice it. Should Gin let go of Kyoka Suigetsu's blade, Aizen will release it immediately without Gin noticing it.
And watching early episodes of Bleach where Unohana found about Aizen's fake body who turns out to be Kyoka Suigetsu itself, touching the blade after it's release won't nullify Kanzen Saimin. Therefore to escape Kanzen Saimin, one must touch and keep holding onto the blade before the release.
What a troll Aizen is. Ckckck.


text:
Q: Trigger input validation error with JQuery on materialize? I know it's a pretty lame question, but I couldn't find it in documentation and neither around forums.
I have this HTML

    CEP *
    <input class="validate" id="CEP" name="CEP" required="required" type="text" />

I don't have a form for this field because I will post it via ajax.
Before I send I want to check if it have a value, so I will do something like this
if($("#CEP").val() === '')
{
    //trigger error and return
}

The problem is: I want to trigger the validation error correct using JQuery. but I don't know how.
Thanks in advance.

A:
$("CEP") is not a valid selector for your example as it will select elements having tag as CEP= > <CEP>

To select elements using id attribute, use #
Try this:
if($("#CEP").val() === '')
{
    //trigger error and return
}

A: It's very simple.
Just try:
...
if($("#CEP").val() === '')
{
    $('#CEP').addClass('invalid');
}

And also add the error message on the input when the validation is wrong:

    CEP *
    <input class="validate" id="CEP" name="CEP" required="required" type="text" />


text:
Q: GCD async block & EXC_BAD_ACCESS This crash is fairly rare, but it has happened often enough to convince me I'm doing it wrong.
It's an API call performed using both main-thread async dispatch and barrier dispatch on a custom concurrent queue (the barrier is used because we're modifying data that is read elsewhere, via non-barrier calls to the same queue).
The objective is to make the HTTP request asynchronously, and then fire off a dispatch_barrier_async to handle the resulting data.
The crash is happening when the dispatch_barrier_async call is copying the variables that are used in the passed block. I suppose that the variable has been deallocated before it gets used in the block, but given how I'm declaring it (as a __block variable) I don't see how that could be happening (unless the problem is with the other side of the assignment operator...).
Here's the stack trace:

#0  0x00004f44 in __Block_byref_object_copy_ at /blah/ABEvent.m:156
#1  0x0000582d in __copy_helper_block_ at /blah/ABEvent.m:191
#2  0x02cf3be2 in _Block_call_copy_helper ()
#3  0x02cf3681 in _Block_copy_internal ()
#4  0x02c25526 in _dispatch_Block_copy ()
#5  0x02c26802 in dispatch_barrier_async ()
#6  0x00004e71 in __18+[ABEvent fetch]_block_invoke at /blah/ABEvent.m:159
#7  0x00056e77 in __88-[ABClient get:parameters:success:failure:]_block_invoke_2 at /blah/ABClient.m:375
#8  0x02c2553f in _dispatch_call_block_and_release ()
#9  0x02c37014 in _dispatch_client_callout ()
#10 0x02c277d5 in _dispatch_main_queue_callback_4CF ()
#11 0x02facaf5 in __CFRunLoopRun ()
#12 0x02fabf44 in CFRunLoopRunSpecific ()
#13 0x02fabe1b in CFRunLoopRunInMode ()
#14 0x02f517e3 in GSEventRunModal ()
#15 0x02f51668 in GSEventRun ()
#16 0x01ef1ffc in UIApplicationMain ()
#17 0x0005164d in main at /blah/main.m:3
#18 0x00002db5 in start ()

And the code:

+ (void)fetch {
    ABBlock _success = ^(ABMessage *m) {

        __block NSMutableArray *fetched = [NSMutableArray arrayWithArray:m.params[@"live"]];
        [fetched addObjectsFromArray:m.params[@"soon"]]; // EXC_BAD_ACCESS (top of stack)

        dispatch_barrier_async([ABEvent eventQueue], ^{  // CRASHED IN BLOCK INVOKE (stack line 6)
            NSMutableArray *events = [NSMutableArray array];

            for (NSDictionary *d in fetched) {
                [events addObject:[ABEvent eventWithDictionary:d]];
            }

            AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            appDelegate.events = events;

            events = nil;
        });
    };

    [[ABClient sharedInstance] events:_success failure:nil];
}

Upstream:

-(void)events:(ABBlock)success failure:(ABBlock)failure {
    NSString *params = [NSString stringWithFormat:@"%@",[ABUser loggedInUser]? [ABUser loggedInUser].name : @"no"];
    NSDictionary *dict = @{@"loggedIn": params};

    [self get:@"events/live.json" parameters:dict success:success failure:failure];
}

- (void)get:(NSString *)path
 parameters:(NSDictionary *)parameters
    success:(ABBlock)success
    failure:(ABBlock)failure

    __block ABBlock blockSuccess = success;
    __block ABBlock blockFailure = failure;
    NSString *blockPath = path;
    NSDictionary *blockParameters = parameters;

    AFHTTPSuccessBlock _success = ^(AFHTTPRequestOperation *request, id response) {
        if (blockSuccess) {
            ABMessage *msg = [ABMessage messageWithObject:response];
            dispatch_async(dispatch_get_main_queue(), ^(void) {
                blockSuccess(msg);
            });
        }

    };
}

Elsewhere:

typedef void (^ABBlock) (ABMessage *);

Is there anything obviously wrong with how the variables are being used by the barrier_async block? I'm wondering if I should be copying the message (*m) being passed in as an argument.

A: Try creating a strong reference to it, eg:
        ABMessage *msg = [ABMessage messageWithObject:response];
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            ABMessage *m = msg;
            blockSuccess(m);
        });

A: *

*You don't need the __block specifier on this line:
__block NSMutableArray *fetched = [NSMutableArray arrayWithArray:m.params[@"live"]];

When you specify __block specifier for Obj-C objects, they are not retained automatically. Since you don't need fetched to be mutable inside the block, you don't need to specify __block. (Bonus question: How would you go about this if you wanted to overwrite the value of fetched array?)

*

*You don't need to specify __block on success and failure blocks:
ABBlock blockSuccess = success;
ABBlock blockFailure = failure;

should suffice. When _success block is copied, it will in turn copy the success and failure blocks. I'm not even sure what happens if you specify __block specifier on a block (perhaps it's a no-op - would be a good exercise to find out), but there's no need for it.
Side note: There is no need to copy ABMessage *msg - block will add a strong reference to it.

A: Try copying this block into heap by manually doing:
[[ABClient sharedInstance] events:[_success copy] failure:nil];

Since you are invoking success in another dispatch_async your block that you declared in +fetch must be copied into heap before you dispatch.


text:
Q: Is there a version of matrix rank that can take non-whole values? The rank of a matrix $A$ can be viewed as the number of linearly independent columns of said matrix. For example
$$
A = \begin{bmatrix}
    1 & 1 \\
    2 & 2
\end{bmatrix}
$$
has rank $r=1$ and the column space spans a line contained in $\mathbb{R}^2$.
Numerically speaking matrix $B$ is "almost" the same as $A$:
$$
B = \begin{bmatrix}
    1 & 1.01 \\
    2 & 2
\end{bmatrix}
$$
However, strictly speaking, matrix B has rank $r=2$, as its columns spans the entire $\mathbb{R}^2$ space. Even though its rank is 2, in an informal way we could say that B has  a rank $R$ "almost 1" ($R \approx 1$ or maybe $1<R<2$) due to the fact that its second column is very close to its first column.
Is there some sort of continuous "rank" $R$ (with values that are not necessarily positive integers but are from $\mathbb{R}$) that captures this property?
Another way of restating the question: is there a generalization of the notion of dimension of a vector space that is not necessarily a positive integer? I suspect fractal theory might offer some insight.

A: The non-zero singular values and associated singular vectors of a matrix $A$ determine the dimensions and orthogonal bases for $R(A)$, $R(A^{T})$, $N(A)$, and $N(A^{T})$.  You can set a tolerance below which a singular value should be considered effectively 0 and use that to determine the numerical rank.


text:
Q: NetBeans 13 with Xdebug 3.1.3 I am trying  to configure NetBeans 13 to communicate with Xdebug 3.1.3
I am using PHP 8.1 in a centos-stream 8 with multiple versions of PHP and on a site constructed with Joomla 4.
I have followed all the instructions in the Xdebug installation wizard and a suggestion from NetBeans itself.
My current xdebug.ini file contains the following:
zend_extension=xdebug
xdebug.mode=debug
xdebug.client_host=localhost
xdebug.client_port=9003
xdebug.idekey="netbeans-xdebug"

I have also tried the bellow configuration with no luck either:
zend_extension=/opt/remi/php81/root/usr/lib64/php/modules/xdebug.so
xdebug.mode=debug
xdebug.client_host=localhost
xdebug.client_port=9003
xdebug.idekey="netbeans-xdebug"

My nginx configuration is (only the relevant lines):
upstream fastcgi_backend_php81 {
        server unix:/var/opt/remi/php81/run/php-fpm/xxxxx.sock;
}

location ~ \.php$ {

        try_files $uri =404;
        fastcgi_pass fastcgi_backend_php81;
        fastcgi_buffers 16 32k;
        fastcgi_buffer_size 64k;
        fastcgi_busy_buffers_size 64k;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
}

My general php nginx setup must be correct cause the whole site is working fine. Only problem is that NetBeans is not connecting with Xdebug.
Any help is appreciated.


text:
Q: Javascript floating point addition workaround Ok, so we all know of the floating point number problem, such as:
0.23 - 1 + 1 = 0.22999999999999998

And since in javascript, unlike other languages, all numbers are actually floating points and there's no int/decimal there are all kinds of libraries and workarounds such as BigDecimal to handle this problem. This is best discussed here.
I was creating a "numeric spinner" control that supports floating point numbers, and obviously I wouldn't want the user to click "up" and then "down" and get a different number from what he started with, so I tried writing a workaround - a "addPrecise" method of sorts.
My idea was the following:

*

*Take the two numbers I'm about to add, and figure out their "precision" - how many digits they have after the decimal point.

*Add the two numbers as floats

*Apply toFixed() on the result with the max precision of the two

For example:
float #1: 1.23
float #2: -1

adding them normally would result in 0.22999999999999998 but if I'm taking the maximal number of decimal places, which is #1's 2 digits, and apply toFixed(2) I get 0.23 as I wanted.
I've done this with the following piece of code but I'm not happy with it.
function addPrecise(f1, f2){
    var floatRegex = /[^\d\-]/;
    var f1p =  floatRegex.exec(f1.toString()) ? f1.toString().split(floatRegex.exec(f1.toString()))[1].length : 0;
    var f2p =  floatRegex.exec(f2.toString()) ? f2.toString().split(floatRegex.exec(f2.toString()))[1].length : 0;
    var precision = Math.max(f1p,f2p);
    return parseFloat((parseFloat(f1) + parseFloat(f2)).toFixed(precision));
}

(It's worth noting that I'm using the regex to find the 'floating point' because in other locales it might be a comma instead of a period. I'm also taking into account the possibility that I got an Int (with no point) in which case it's precision is 0.)
Is there a cleaner/simpler/better way to do this?
Edit: I'd also like to point out that finding a reliable way to extract the number of decimal digits is also part of the question. I'm unsure about my method there.

A: An appropriate solution for this problem is:

*

*Determine how many digits, say d, are needed after the decimal point.

*Read inputs from the user and convert them to integers scaled by 10d.

*Do all arithmetic using the integers.

*When displaying values for the user, divide them by 10d for display.

More details:

*

*If all work is in whole units of user-entered data, then the number of digits needed after the decimal point, d, is the same as the number of digits to be accepted from the user. (If one were going to do some arithmetic with fractions of the step size, for example, then more digits might be needed.)

*When the user enters input, it should be converted to the scaled integers. Note that the user enters a string (not a floating-point number; it is just a string when the user types it), and the string should be a numeral (characters that represent a number). One way to process this input is to call library routines to convert this numeral to a floating-point number, then multiply by 10d, then round the floating-point result to the nearest integer (to compensate for floating-point rounding errors). For numbers of reasonable size, this will always produce exactly the desired result; floating-point rounding errors will not be a problem. (Excessively large user input should be rejected.) Another way to process this input is to write your own code to convert the numeral directly to a scaled integer, avoiding floating-point entirely.

*As long as only addition, multiplication, and subtraction are used (e.g., multiplying the step size by a number of steps and adding to a prior value), and the integer range is not exceeded, then all arithmetic is exact; there are no rounding errors. If division is used, this approach must be reconsidered.

*As with reading input, displaying output can be performed either with an assist from floating point and library routines or by writing your own code to convert directly. To use floating-point, convert the integer to floating-point, divide by 10d, and use a library routine to format it with no more than d digits after the decimal place. (Using default format conversions in library routines might result in more than d digits displayed. If only d digits are displayed, and d is a reasonably small number, then floating-point rounding errors that occur during the formatting will not be visible.)

It is possible to implement all of the above using only floating-point, as long as care is taken to ensure that the arithmetic uses entirely integers (or other values that are exactly representable in the floating-point format) within reasonable bounds.


text:
Q: How Visual Studio 2015 Publish Web app and SQL, update DB starting using VS2015 and publishing to azure websites. I'm developing using a local DB for faster interaction. And I'm publishing Web Application and a SQL Database (Project > publish). But I always getting this error.

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web\Microsoft.Web.Publishing.targets(4276,5): Error ERROR_SQL_EXECUTION_FAILURE:
"CREATE TABLE [dbo].[__MigrationHistory]("  There is already an object named '__MigrationHistory' in the database" #ERROR_SQL_EXECUTION_FAILURE.)
Publish failed to deploy.

And it is the same for every table on DB.
How can I somehow just update the tables on the server?
There is another way to work with apps and DB in local machine and later update to the server?
I'm using vs2015, webDeploy 3.6, Windows Azure web app and SQL DB.

A: I got this solved by removing all files from Properties\PublishProfiles. There was lots of old files from my first publishing attempts. After this I created new profile.


text:
Q: Can not print on Single Page dgvprinter c# There are 9 columns in datagridview when I print using dgvprinter it prints 7 columns on 1 page and other 2 on a new page. I want to print on a single page anybody helps me?
Note: There is an image on datagridview.
Here is code:
 DGVPrinter printer = new DGVPrinter();
        printer.Title = "Test";
        printer.SubTitle = "Outgoing Stocks";
        printer.SubTitleFormatFlags = StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
        printer.PageNumbers = true;
        printer.PageNumberInHeader = false;
        printer.PorportionalColumns = true;
        printer.HeaderCellAlignment = StringAlignment.Near;
        printer.Footer = "System generated file";
        printer.FooterSpacing = 15;
        printer.PorportionalColumns = true;
        printer.HeaderCellAlignment = StringAlignment.Near;
        printer.printDocument.DefaultPageSettings.Landscape = true;
        printer.RowHeight = DGVPrinter.RowHeightSetting.CellHeight;
        printer.PrintDataGridView(itemdata_datagridview);


text:
Q: SQL Group By Join I have three tables I need to join in order to tell what documents a product needs.  Not all documents are needed on each product.
There is a Document table, a Product table, and a DocTracking table that tracks the documents associated with products

Product Table
ProdID   ProdName
1        Ball
2        Wheel

DocTracking Table
ProdID     DocID
1          1
1          2
2          2

I want the join to look like this:

ProdID     ProdName   Needs Word Doc?    Needs Excel Doc?
1          Ball       Yes                Yes
2          Wheel      No                 Yes

Any help would be appreciated, if I need to make this into a Stored Procedure, that is fine.

A: If you have only those documents and they are fix you can use this query:
SELECT ProdID, ProdName,
       [Needs Word Doc] = CASE WHEN EXISTS(
           SELECT 1 FROM Document  d INNER JOIN DocTracking dt ON d.DocID=dt.DocID
           WHERE dt.ProdID = p.ProdID AND d.[Doc Name] = 'Word Document'
       ) THEN 'Yes' ELSE 'No' END,
       [Needs Excel Doc] = CASE WHEN EXISTS(
           SELECT 1 FROM Document  d INNER JOIN DocTracking dt ON d.DocID=dt.DocID
           WHERE dt.ProdID = p.ProdID AND d.[Doc Name] = ' Excel Spreadsheet'
       ) THEN 'Yes' ELSE 'No' END
FROM dbo.Product  p

Of course you could also use the DocID, then the query doesn't depend on the name.

A: select P.ProdID, P.ProdName,
       case
          when DW.DocID is null then 'Yes'
          else 'No'
       end as NeedsWordDoc,
       case
          when DE.DocID is null then 'Yes'
          else 'No'
       end as NeedsExcelDoc
from Product P
left join DocTracking DTW on DTW.ProdId = P.ProdId
left join Document DW on DW.DocID = DTW.DocID
                          and DW.Name = 'Word Document'
left join DocTracking DTE on DTE.ProdId = P.ProdId
left join Document DE on DE.DocID = DTE.DocID
                          and DE.Name = 'Excel Spreadsheet'

A: This is a little more complicated than a typical pivot query.  But, the only challenging part is determining which documents are included, and then getting 'Yes' or 'No' out.
The following does this with coalesce() and a conditional that checks for the presence of one type of document:
select pt.ProdId, pt.ProdName,
       coalesce(MAX(case when dt.DocId = 1 then 'Yes' end), 'No') as "Needs Word Doc?",
       coalesce(MAX(case when dt.DocId = 2 then 'Yes' end), 'No') as "Needs Excel Doc?"
from ProductTable pt left outer join
     DocTracking dt
     on dt.ProdId = dt.ProdId
group by pt.ProdId, pt.ProdName;

Note that SQL queries return a fixed number of columns.  So, you cannot have a SQL query that simply returns a different number of columns based on what is present in the documents table.  You can create a SQL query in a string and then use a database-specific command to run it.

A: may be this would help you - using pivot:
select ProdId, ProdName,
case when isnull([Word Document],0)<>0 then 'Yes'
else 'No'
end as  [Needs Word Doc?],
case when isnull([Excel Spreadsheet],0)<>0 then 'Yes'
else 'No'
end as  [Needs Excel Spreadsheet?]
 from
(
select p.ProdId,p.ProdName,d.DocId,d.DocName from
@Prod p left join
@Track t
on p.ProdId=t.ProdId
inner join @Doc d
on t.DocId=d.DocId
)
as temp
pivot
(max(DocID)
For DocName in ([Word Document],[Excel Spreadsheet])
)
as pvt


text:
Q: Is there way to construct frequency dictionary of numbers without cycles('for') and in one line? Suppose we have an array of numbers with repetitions.
Is there way to construct frequency dictionary of numbers without cycles ('for') and in one line? For instance, use list comprehension or map. I attempted but I couldn't come up with better :
d_num = {}
for number in x:
    d_num.update({number : 1} if d_num.get(number) == None else {number : d_num.get(number) + 1})

A: Python follows the philosophy of batteries included and in your case you could simply use collections.Counter:
from collections import Counter
Counter(x)

If you want it as plain dictionary you can convert it back easily. However Counter behaves (almost) like a dictionary so there should be almost no need:
dict(Counter(x))


text:
Q: How to formulate a SQL query to identify sets of matches across a table I have a relation that has airline routes and the airports that these flights go over on such routes. I'm trying to identify what routes skip over the same airports.
I have whittled down the relation into a table that should be possible to manipulate to create my desired result:
SELECT route_id, airport_id
FROM routes_airports
WHERE stops = false
ORDER BY route_id, airport_id;

I would like to match routes to one another when they have the same values for airport_id across their entries in the table while including the routes that exhibit this property.
So, for example, routes 5 and 7 both skip over airports 10,15,20, so they should be matched together, but not with say, route 10 which only skips over airports 10 and 20.
 route_id | skipped_airport_id
----------+------------
        1 |         76
        2 |         21*
        2 |         22*
        4 |         42
        5 |         21*
        5 |         22*
        7 |         15
        7 |         16
        7 |         17
        7 |         18
        7 |         46
        9 |         26
       11 |         19
       14 |         45*
       14 |         46*
       14 |         47*
       15 |         45*
       15 |         46*
       15 |         47*
       17 |         78
       20 |         20

I would like the above example data to result in a table with just the routes that have a match such as below.
 route_id
----------
        2
        5
       14
       15

A: Try something like this:
SELECT route_id, STRING_AGG(airport_id, ',') AS airports
FROM routes_airports
WHERE stops = FALSE
GROUP BY route_id
ORDER BY 2

This will collect the airport_ids into a single column, and ORDER BY that column.

A: WITH
  skips AS
(
  SELECT route_id, STRING_AGG(airport_id, ',' ORDER BY airport_id) AS airport_ids
  FROM routes_airports
  WHERE stops = false
  GROUP BY route_id
)
SELECT airport_ids, STRING_AGG(route_id, ',' ORDER BY route_id) AS route_ids
FROM skips
GROUP BY airport_ids
HAVING COUNT(*) > 1

A: You can do this by aggregating all skipped airports into an array and then find out those routes where those arrays are the same:
with skipped as (
  select route_id, array_agg(skipped_airport_id order by skipped_airport_id) skipped_airports
  from routes_airports
  where stops = false
  group by route_id
)
select s1.*
from skipped s1
where exists (select *
              from skipped s2
              where s1.route_id <> s2.route_id
                and s1.skipped_airports = s2.skipped_airports);

This returns:
route_id | skipped_airports
---------+-----------------
       2 | {21,22}
       5 | {21,22}
      14 | {45,46,47}
      15 | {45,46,47}

Online example: https://rextester.com/MJPJ90714


text:
Q: Weblogic xss vulnerablity : html character entities getting decoded in jsp I am using a filter to prevent xss by encoding html character of my jsp form parameters.
I am resolving them in jsp using ${param} expression.
This is working fine in tomcat as the values are resolved as is, but on weblogic the values are getting decoded, causing the XSS to succeed
I am using this simple code in jsp to test it
<c:set var="testing" value="eb011">47379"/>
<input type="hidden" name="encoding" value="${testing }"/>

Result in tomcat
<input type="hidden" onerror="confirm(1)>47379"/" src="a" >

Result in weblogic
<input type="hidden" value="eb011" name="encoding">47379"/>

Please tell me why is weblogic decoding html codes and what could be done to prevent it.

A: I have never used weblogic in my life, but I do little know about XSS. After some doing some google I found following  method to encode the the html entities in weblogic. I guess that will help you out.

WebLogic Server provides the weblogic.servlet.security.Utils.encodeXSS() method to replace the  special characters in user-supplied data. To use this method, provide the user-supplied data as input.  For example
<%= weblogic.servlet.security.Utils.encodeXSS(
  javax.servlet.ServletRequest.getParameter("userInput"))%>

From:Oracle docs

WebLogic Server provides the weblogic.servlet.security.Utils.encodeXSS() method to replace the special characters in user-supplied data. out.print(defaultGreeting + " " +
  weblogic.security.servlet.encodeXSS(name) + "!");

From: Using a WebLogic Server Utility Method


text:
Q: Intriguing Convergent Series I fell upon this very interesting series in a textbook:
$$ S_n=\sum_{p=1}^n \frac {1}{n+p}$$
Although it resembles harmonic series, this series has a limit.  I managed to prove that the values of $S_n$ must exist in a particular interval for every integer $n$. Here we go:
$$ 1 ≤ p ≤ n $$
$$ 1+n ≤ p+n ≤ 2n $$
$$ \frac 1{2n} ≤\frac 1{n+p} ≤ \frac 1{n+1} $$
$$\sum_{p=1}^n \frac {1}{2n} ≤ \sum_{p=1}^n \frac {1}{n+p} ≤ \sum_{p=1}^n \frac {1}{n+1}$$
$$ \frac {n}{2n} ≤ S_n ≤ \frac {n}{n+1} $$
Finally
$$ \frac {1}{2} ≤ \lim_{n \to \infty} S_n ≤ 1 $$
I also tried computing some values for example:
$ S_{10}= 0.66877... $  ,  $ S_{100}= 0.69065... $   and   $ S_{1000}= 0.69289...$
So it is obvious that the series are slowly converging towards a particular value, but what is it?
I feel like Bernoulli (with all modesty) who found out that the Basel series is less than a number so I'm waiting for the Euler to discover the true limit.
 Please help me and make it as simple as possible.

A: If we define the harmonic numbers
$$H_n=\sum_{k=1}^n\frac1k$$
Your series can be represented by
$$H_{2n}-H_n=\frac1{n+1}+\cdots+\frac1{2n}$$
And since $\lim H_n-\log(n)=\gamma$, we know $\lim H_n-\log(n)-\gamma=0$
$$\lim_{n\to\infty} H_{2n}-H_n=\lim_{n\to\infty} H_{2n}-\log(2n)-\gamma-(H_n-\log(n)-\gamma)+\log(2)=0+0+\log(2)$$
So that your series converges to $\log(2)$.

A: Alternatively, one can proceed as
$$ \sum_{k=1}^{n} \frac{1}{n+k} = \sum_{k=1}^{n} \frac{1}{1+\frac{k}{n}}\frac{1}{n} \xrightarrow[n\to\infty]{} \int_{0}^{1} \frac{dx}{1+x} = \log 2. $$

A: Just as vrugtehagel answered,$$S_n=\sum_{p=1}^n \frac {1}{n+p}=H_{2 n}-H_n$$ Now, if you use the asymptotics $$H_p=\gamma +\log \left({p}\right)+\frac{1}{2 p}-\frac{1}{12
   p^2}+O\left(\frac{1}{p^4}\right)$$you should get $$S_n=\log (2)-\frac{1}{4 n}+\frac{1}{16 n^2}+O\left(\frac{1}{n^4}\right)$$
Similarly, considering $$T_n=\sum_{p=1}^n \frac {1}{an+p}=H_{(a+1) n}-H_{a n}$$ assuming $a \gt 0$, the expansion would be $$T_n=\log\left(1+\frac 1a\right)-\frac{1}{2 a (a+1) n}+\frac{2 a+1}{12 a^2 (a+1)^2
   n^2}+O\left(\frac{1}{n^4}\right)$$


text:
Q: PCRE Regex failes to assert INTL formatter I have the following phpunit assert:
$this->assertRegExp('/^\d.\d{3}$/i', $this->object->transformNumber('3333', 'de_AT'));
// $number = '3333' and $lang = 'de_AT'

and the relevant part of transformNumber:
$formatter = new \NumberFormatter($lang, \NumberFormatter::DECIMAL);
$formatter->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 2);

return $formatter->format($number);

Here intl acts different I've learned that because of the different Intl Versions different outputs can result.
Now my question is why do I get this and the unit test fails:
Failed asserting that '3 333' matches PCRE pattern "/^\d.\d{3}$/i".
As it clear matches the result: regex 101
Info: Runtime:       PHP 7.0.20 with Xdebug 2.5.4
EDIT:
After I rewrote the test to:
    $result = $this->object->transformNumber('3333', 'de_AT');
    printf($result);
    echo "\n";
    foreach (str_split($result) as $char) {
        printf('char: %s => ord: %s', $char, ord($char));
        echo "\n";
    }

I got the follwoing output:
3 333
char: 3 => ord: 51
char: � => ord: 194
char: � => ord: 160
char: 3 => ord: 51
char: 3 => ord: 51
char: 3 => ord: 51

That means that on some machines with different setup (php version/ intl version and so on) I get an extra character (actually 2 Ascii chars instead of space) in the number. Is this an Intl problem?
And I've adjusted the regex to:
$this->assertRegExp('/^\d.(.)?\d{3}$/i', $result);

Now a new question is rising: Why do I get this encoding problem only on some environments?


text:
Q: how to check if a php file is obfuscated? is there any way we can check if a php file has been obfuscated, using php? I was thinking regex maybe (for instance ioncube's encoded file contains a very long alphabet string, etc.

A: One idea is to check for whitespace. The first thing that an obfuscator will do is to remove extra whitespace. Another thing you can look for is the number of characters per line, as obfuscators will put all the code into few (one?) lines.

A: Often, obsfuscators initialize very large arrays to translate variables into less meaningful names (eg. see obsfucator article
One technique may be to search for these super-large arrays, close to the top of the class/file etc. You may be able to hook xdebug up to examine/look for these. The whole thing of course depends on the obsfuscation technique used. Check the source code, there may be patterns they've used that you can search on.

A: I think you can use token_get_all() to parse the file - then compute some statistics. For example check for number of function calls(in calse obfuscator uses some eval() string and nothing else) and calculate average function length - for obfuscators it will usually be about 3-5 chars, for normal PHP code it should be much bigger. You can also use dictionary lookup for function/variable names, check for comments etc. I think if you know all obfuscator formats that you want to detect - it will be easy.


text:
Q: How to pass parameter to REST API? I am using R and have one question on how to pass parameter to the REST API REQUEST.
I already got the token and I am using R, and need to retrieve data from REST API service, by passing some parameters. Here is my code:
library(httr)
r <- POST("https://XXXXXXXX/api/locationhazardInfo",
add_headers("Content-Type"="text/plain; charset=UTF-8",
Accept="text/plain",
"Authorization"=paste("Bearer", tok)),
body = list(
"Latitude":40.738269,
"Longitude":-74.02826,
"CountryCode":"USA",
"HazardLayers":[
{
"LayerId":"18",
"Description":""
},
{
"LayerId":"6",
"Description":""
}
],
"Distances":[
{
"Value":1,
"Unit":"miles"
}
]
)
)

The tok is the token I got from previous step. And I got the systax errors (seem all syntax errors) as shown below,
Any input is greatly appreciated.
here is the screenshot of the error

A: Your body isn't a list. (I don't think!).  I also think you have a rogue ) at the end (second last) which should be a }
A list would look like:
body = list(x = "A simple text string", y="Another String")

Your body is JSON encoded text.
 body = '{"a":1,"b":{}}', encode = "raw")

So your code might look like this:
library(httr)
r <- POST(
    "https://XXXXXXXX/api/locationhazardInfo",
    add_headers(
        "Content-Type"="text/plain; charset=UTF-8",
        Accept="text/plain",
        "Authorization"=paste("Bearer", tok)
    ),
    body = '{
         "Latitude":40.738269,
         "Longitude":-74.02826,
         "CountryCode":"USA",
         "HazardLayers":[
           {
              "LayerId":"18",
              "Description":""
            },
           {
              "LayerId":"6",
              "Description":""
           }
         ],
         "Distances":[
           {
              "Value":1,
              "Unit":"miles"
           }
         ]
       }',
      encode = "raw" )

A: An update, here is the solution at least it fixed my problem:
rg <- POST(url,
           # add_headers("Content-Type"="text/plain; charset=UTF-8",
           add_headers("Content-Type"="application/json",
                       Accept="text/plain",
                       "Authorization"=paste("Bearer", tok)),
           body = '{
         "Latitude":40.738269,
         "Longitude":-74.02826,
         "CountryCode":"USA",
         "HazardLayers":[
           {
              "LayerId":"18",
              "Description":""
            },
           {
              "LayerId":"6",
              "Description":""
           }
         ],
         "Distances":[
           {
              "Value":1,
              "Unit":"miles"
           }
         ]
       }' ,
           encode = "raw"  #### , verbose()
)


text:
Q: A convex quadrilateral with propotion Let P be the intersection of the convex quadrilateral ABCD. Let X,Y,Z be points on AB,BC,CD respectively such that $\frac{AX}{XB}=\frac{BY}{YC}=\frac{CZ}{ZD}=2$. Suppose that XY is tangent to the circumcircle of triangle CYZ and YZ is tangent to the circumcircle of triangle BXY. Prove that $\angle APD=\angle XYZ$

I did not make progress except for proving that $\Delta BXY\sim \Delta CYZ$, using alternate segment theorem.
Any help appreciated.
Thank you in advance.

A: If you proved that $\Delta BXY\sim \Delta CYZ$ then $$\frac{BX}{CY}=\frac{BY}{CZ}$$ or
$$\frac{\frac{1}{3}AB}{\frac{1}{3}BC}=\frac{\frac{2}{3}BC}{\frac{2}{3}DC}$$ or
$$\frac{AB}{BC}=\frac{BC}{DC},$$ which says
$$\Delta ABC\sim\Delta BCD.$$
Id est, $$\measuredangle APD=\measuredangle BDC+\measuredangle PCD=\measuredangle ACB+\measuredangle BCD-\measuredangle ACB=\measuredangle BCD=\measuredangle XYZ.$$


text:
Q: Retrieve specific files in nested subfolder, without run listdir() multiple times I have 42 folders, each contain a file that I need, and a folder, which has a name that is the same of the parent folder, minus a prefix, which contain another file that I need:
XXXXX_foldername
    foldername
        file.abc
    file.xyz

At the moment I am using os.listdir(); although to get to the file.abc, I need to make 2 pass, because in the first pass I get my XXXXX_foldername for each of my 42 folders, so I can acquire my file.xyz. Then I have to make the second pass for the foldername, to retrieve the `file.abc. This repeated N times, for as many folders I have.
def scan_folders(self):
    directory = "/Users/myuser/data"
    # This give me all 42 folders names
    folders_list = os.listdir(directory)
    for item in folders_list:
        # yet another listdir to get the xyz file
        xyz_file = "\n".join(s for s in os.listdir(directory + "/" + item) if "xyz".lower() in s.lower())
        print(xyz_file)
        # this give me the name of the sub-folder
        sub_folder_name = item[6:]
        # And another listdir to get the abc file
        abc_file = "\n".join(s for s in os.listdir(directory + "/" + item + "/" + sub_folder_name) if "abc".lower() in s.lower())
        print(abc_file)

I have to run listdir 2 times to get 2 filenames; is there a better and more efficient way, to find a file, without run the listdir so often? It is not a big deal for 42 folders, but I am planning to scan a folder that contains GB and GB of data, in multiple folders (where the XXXXX is an incremental integer).


text:
Q: MacBook Pro 2021 14" WiFi with lower RSSI than MacBook Pro 2020 13" I don't know if anyone here has noticed this, but in my MacBook Pro the received signal strength (RSSI) on the new 2021 Mac is lower than on my 2020 M1 MacBook Pro. The test was performed with both computers at the exact same spot on my desk, not with the 2 computers side-by-side.
At that specific spot, my work MBP 2020 13" has these values:
RSSI: -24 dBm
Noise: -90 dBm
Tx Rate: 1200Mbps
MCS Index: 11

The new MBP 2021 14" (M1 Max) has these values:
RSSI: -49 dBm
Noise: -83 dBm
Tx Rate: 583-780Mbps
MCS Index: 5-8

Both the MCS Index and the Tx Rate vary wildly on my 2021 MBP. It makes sense that it affects the Tx Rate since the MCS Index changes the modulation, but I don't understand why it changes in the first place, given that the signal values remain the same.
Has anyone ever noticed any changes to your WiFi signals? Has Apple screwed this hardware generation or is this all due to battery savings?
I am not a telecommunications expert so I don't know if, for instance, a receiver antenna could have its signal strength "boosted" by a power amplification. I know the transmitter antenna for sure depends on its power amplification. But what about the receiver? Could this be a software controlling the power on the WiFi antenna?
My laptops are at different macOS versions because the IT department hasn't approved an update on my work computer yet. So:
MBP 2020 13" M1: macOS 11.6.1
MBP 2021 14" M1 Max: macOS 12.0.1
More info:
Both laptops connected to the same WiFi network at 5Ghz 802.11ax (WiFi 6).
However, after a period of inactivity with the lid shut (such as overnight), the Monterey 2021 MBP will not reconnect as WiFi 6 automatically. I need to click on the WiFi logo and turn it off/on to reconnect as WiFi 6.
I appreciate any insights you might have. Thank you.


text:
Q: Golang SQL package jsonb operator In sql package for postgresql jsonb how can I use the @> operator with a string query for example

*

*WHERE data @> '{"stringdata": $1}' or

*WHERE data @> '{"stringdata": "$1"}' doesn't work

The alternative is data->>'string_data' = $1 which I don't prefer for multiple statements
Error is:
    "Message": "invalid input syntax for type json",
    "Detail": "Token \"$\" is invalid.",
    "Where": "JSON data, line 1: $...",
    "Routine": "report_invalid_token"

A: AFAIK, you can't interpolate inside strings, but you can build a JSON object using json_build_object or json_object:
SELECT data FROM test
WHERE data @> json_build_object('stringdata', $1::text, 'foo', $2::int)::jsonb;

This is basically an equivalent of
SELECT data FROM test
WHERE data @> '{"stringdata":"$1","foo":$2}';


text:
Q: Orderby month and year using linq I'm fetching distinct months from database but the month values are in the form of month and year. ie, Jan-15,Feb-15. How do I get it in Ascending order of both month and year?
Right now I'm getting result as: Apr-15 Feb-15 Jan-15 Mar-15. But I want the result like this: Jan-15 Feb-15 Mar-15 Apr-15.
 var months = ((from mnths in context.Table
                       orderby mnths.Month
                       select mnths.Month).Distinct()).ToList();

        return months;

Thanks.

A: You can use DateTime.TryParseExact like this:
var months = ((from mnths in context.Table
                   orderby mnths.Month
                   select mnths.Month).Distinct()).ToList().OrderBy(m =>
                   {
                        DateTime month;
                        return DateTime.TryParseExact(m, new[] {"MMM-yy"}, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out month)
                            ? month
                            : DateTime.MinValue;
                   }).ToList();

You need to call ToList before OrderBy so the original query is executed and you get an IEnumerable<string> instead of an IQueryable.

A: Just use .NET Sort Method.
First Get All dates from DB
var dates = ((from dts in context.Table
                         select dts).Distinct().ToList();

            return dates;

And then Do
dates.Sort();
dates.Reverse();

And you'll get the result as yo want. (And Store Datetime in Db with type datetime not nvarchar or other).


text:
Q: I can't found my mistake in my simple C-loop,the printf doesnt work Down there is my code,when i try to compile it the printf doesnt work,what do you think?Why?
#include <stdio.h>
int main(){
    float i;
    for(i=0.0f; i < 1.0f; i+=0.05f){
        if(i == 0.5f)
            printf("Die Hälfte ist erreicht\n");
    }
    return 0;
}

A: Floating-point arithmetic is designed to approximate real-number arithmetic. The 0.05f in source code is converted from that decimal numeral to a binary format that approximates it. Further, each time i += 0.05f is executed, the real-number sum is rounded to fit in the float format. The rounding errors that causes may either compound or cancel, moving the current value of i further from or nearer to what you would have if real-number arithmetic were used.
To iterate with an arithmetic sequence of floating-point values, you can use integer values for a counter and then scale the counter as desired:
for (float iteration = 0; iteration < 20; iteration += 1)
{
    float i = iteration / 20;
    if (i == 0.5f)
        printf("Die Hälfte ist erreicht\n");
}

However, there may be additional subtleties involved in any code more complicated than this, so it is necessary to learn about floating-point arithmetic in order to use it correctly.

A: Floating point numbers are based on binary numbers. It may not be possible to exactly represent the value of a decimal number but only a value that is very close.
That means you should avoid comparisons == or != for floating point numbers.
One option is to convert your program to count using integer numbers.
#include <stdio.h>
int main(){
    float f;
    for(int i=0; i < 100; i+=5){
        if(i == 50)
            printf("Die Hälfte ist erreicht\n");
        f = (float)i / 100f;
    }
    return 0;
}

Another option is to compare the difference between floating point numbers with a small number.
#include <stdio.h>
int main(){
    float i;
    for(i=0.0f; i < 1.0f; i+=0.05f){
        float diff = i - 0.5f;
        if(diff < 0) diff = (-diff);
        if(diff < 0.01)
            printf("Die Hälfte ist erreicht\n");
    }
    return 0;
}


text:
Q: How do I search a text file for anagrams of a given word I have to search through a text file for anagrams of a given word. The text file has one word per line. So far I've managed to write a function, that makes a dictionary from a given word, with the key being a letter in the word, and it's value being the number of times the letter is in the word. The second function loops through each line of the text file, creates a second dictionary of the same keys and values, and compares the two. if the two are equal to each other, the function will add that word to a list. Once the function finishes looping through the text file, it should print the list of anagrams, but it's printing a blank list. Here is my code, I have no clue where it's going wrong.
this is for creating the dictionary of the given word.
word= input("Enter a word: ")
letterdict = {}

def count_letters(word,letterdict):
    for letter in word:
        letterdict[letter] = letterdict.get(letter,0) + 1
    return letterdict

print(count_letters(word,letterdict))

this is for looping through the text file and comparing
def search():
    count_letters(word,letterdict)
    anagrams = []
    letterdict2={}
    f = open('EnglishWords.txt', 'r')
    for letter in f:
        letterdict2[letter] = letterdict2.get(letter,0) + 1
        if letterdict == letterdict2:
            anagrams.append[f]
        letterdict2.clear()
    f.close()
    anagrams.sort() #put list in alphabetical order

    return print(anagrams)

search()

A: Much faster algorithm (inside the loop, anyway): go through your entire dictionary just once, creating a new file with two words on each line; the first is the word with its letters alphabetized, and then the word itself, for example:
aaadkrrv aardvark
aabcsu abacus
. . .

Then, sort that file. Now, looking for all the anagrams of a word is a simple direct lookup into a sorted list.

A: This looks like a problem of not using the global keyword to access (and write to) the letterdict you create. Declare your variables locally and pass them through your program using function parameters. Python doesn't provide strong global variable support (it's there, but takes a lot of attention to detail to use).
Consider rewriting your functions:
def count_letters(word):
    letterdict = dict()
    for letter in word:
        letterdict[letter] = letterdict.get(letter,0) + 1
    return letterdict

def search(word):
    letterdict = count_letters(word)
    anagrams = []
    letterdict2={}
    with open('EnglishWords.txt', 'r') as f:
        for line in f:
            for letter in line:
                letterdict2[letter] = letterdict2.get(letter,0) + 1
                if letterdict == letterdict2:
                    anagrams.append[line]
                letterdict2.clear()
    anagrams.sort() #put list in alphabetical order

return anagrams

A few notes about the original code:

*

*return print(anagrams) probably doesn't do anything and seems like a syntax error in your code.

*for letter in f: loads lines of the file to letter

*count_letters(word,letterdict) does nothing with the calculated value

*You may/may not want to include spaces and numbers in your letterdict


text:
Q: Is Stream.findAny a short-circuit operation? Consider this code
Object found = collection.stream()
    .filter( s -> myPredicate1(s))
    .filter( s -> myPredicate2(s))
    .findAny()

Will it process entire stream, and call both myPredicate1 and myPredicate2 for all elements of the collection? Or will as many predicates be called as are needed to actually find the value?

A: Yes it is, as the Stream.findAny() documentation states:

This is a short-circuiting terminal operation.

It's a common misconception that objects in stream are "pushed" towards consuming operation. It's actually the other way around - the consuming operation pulls each element.
For sequential streams only as many predicates will be called as are needed to find matching value.
Parallel streams may execute more predicates, but will also stop execution as soon as an element is found.
public class StreamFilterLazyTest {

  static int stI = 0;

  static class T {

    public T() {
      super();
      this.i = ++stI;
    }

    int i;

    int getI() {
      System.err.println("getI: "+i);
      return i;
    }
  }

  public static void main(String[] args) {
    T[] arr = {new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T()};
    Optional<T> found = Arrays.stream(arr).filter(t -> t.getI() == 3).findAny();
    System.out.println("Found: "+found.get().getI());
  }
}

will print:
getI: 1
getI: 2
getI: 3
Found: 3

A: The javadoc for findAny() states:

"This is a short-circuiting terminal operation."
"The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations ..."

This means that findAny() on a sequential stream will only "pull" enough elements to find the first one.  On a parallel stream, it could pull more than enough, depending on the implementation.
The package javadoc also states:

"Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed."

This means that the filter() predicates only occur when the findAny() terminal pulls them.
In short:

Q: Is filter + findAny still a short-circuit operation?

A: Yes.

A: Well it does not matter if sequential or parallel streams are used, they are still going to traverse as many elements as are required to find the first that matches. It might be different if you use findFirst and you have a Stream made of an ordered collection.
findFirst in this case has to preserver the order.
In this case, due to parallelism, the second, then third elements might be processed before the first, but still only the first will be returned.

A: Stream#findAny is a short-circuiting terminal operation. it will visit Predicates to matching & short-circuited one by one since Stream#filter return a new stream each time.

Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.

As @Holger mentioned in comment that it can makes filters be short-circuited as below:
if(predicate1.test(value) && predicate2.test(value)){
 ....
}

Test
Iterator<Predicate<Integer>> predicates = Stream.<Predicate<Integer>>of(
        it -> false,
        it -> {
            throw new AssertionError("Can't be short-circuited!");
        }
).iterator();

Predicate<Integer> expectsToBeShortCircuited = it -> predicates.next().test(it);

Stream.of(1).filter(expectsToBeShortCircuited).filter(expectsToBeShortCircuited)
      //                                       |
      //                                       |
      //                      here is short-circuited since the stream is empty now
      .findAny();

A: You can use peek to verify this

== Sequential ==
Alpha1 Alpha2 Beta1 Beta2 Gamma1 Gamma2 Dolphin1 Fargo1 Fargo2  Found:
  Fargo Applications: 9
== Parallel ==
  Arnold1 Jim1 Loke1 Alpha1 Mustard1 Lenny1 Mustard2 Mark1 Alpha2 Mark2
  Beta1 Beta2 Gamma1 Fargo1 Gamma2 Dolphin1 Fargo2  Found: Fargo
  Applications: 17

YMMV depending on number of cores etc.
Produced by below
package test.test;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

public class Snippet {

    static AtomicInteger predicateApplications;

    public static void main(String arr[]) {
        System.out.println("== Sequential == \n");
        sequential();
        System.out.println(" == Parallel == \n");
        parallel();
    }

    private static void sequential() {
        Stream<String> stream = Stream.of("Alpha", "Beta", "Gamma", "Dolphin", "Fargo", "Mustard", "Lenny", "Mark",
                "Jim", "Arnold", "Loke");
        execute(stream);
    }

    private static void parallel() {
        Stream<String> parallelStream = Stream
                .of("Alpha", "Beta", "Gamma", "Dolphin", "Fargo", "Mustard", "Lenny", "Mark", "Jim", "Arnold", "Loke")
                .parallel();
        execute(parallelStream);
    }

    private static void execute(Stream<String> stream) {
        predicateApplications = new AtomicInteger(0);

        Optional<String> findAny = stream.peek(s -> print(s + "1")).filter(s -> s.contains("a"))
                .peek(s -> print(s + "2")).filter(s -> s.startsWith("F")).findAny();

        String found = findAny.orElse("NONE");
        System.out.println("\nFound: " + found);
        System.out.println("Applications: " + predicateApplications.get());
    }

    private static void print(String s) {
        System.out.print(s + " ");
        predicateApplications.incrementAndGet();
    }

}


text:
Q: Is there any flutter packages that support Bluetooth on windows Currently I am working on a project that needs to have Bluetooth features in Desktop
But I didn't find any working packages.
Can any one suggest me the good packages ??

A: Try those BLE packages,they are supported to windows.
https://pub.dev/packages/quick_blue
https://pub.dev/packages/flutter_blue_plugin
From quick_ble package have following features

*

*Scan BLE peripheral

*Connect BLE peripheral

*Discover services of BLE peripheral

*Transfer data between BLE central & peripheral

A: check out this link.
https://www.tldevtech.com/best-bluetooth-packages-for-flutter/
From the link, quick_blue(https://pub.dev/packages/quick_blue) library supports Bluetooth features in Desktop from Flutter.

A: You can use win_ble package.
This is specifically developed to work for Flutter for Windows. Also it's up to date.
Current version of it is 0.04

A: You can use win_ble package.
This is specifically developed to work for Flutter for Windows. Also it's up to date.
Check it out here
win_ble


text:
Q: Builds stuck in pending state drone I'm using drone:0.8 with the following configuration but the only two first jobs are succeeded in building. The rest of jobs are stuck in the pending state.
I'm deploying drone using Docker Swarm stack deploy. Here is my configuration file:
version: '3'
services:
  server:
    image: drone/drone:0.8
    ports:
    - 8000
    - 9000
    volumes:
    - /data/local/drone:/var/lib/drone/
    environment:
    - DRONE_OPEN=true
    - DRONE_HOST=http://example.com
    - DRONE_GITHUB=true
    - DRONE_ORGS=my_fake_company
    - DRONE_ADMIN=my_github
    - DRONE_GITHUB_CLIENT=my_secret
    - DRONE_GITHUB_SECRET=my_client
    - DRONE_SECRET=my_drone_secret
    - VIRTUAL_HOST=virtual_host.nginx.com
    - VIRTUAL_PORT=8000
    networks:
    - edge
  agent:
    image: drone/agent:0.8
    command: agent
    depends_on:
    - drone-server
    volumes:
    - /var/run/docker.sock:/var/run/docker.sock
    environment:
    - DRONE_SERVER=drone_server:9000
    - DRONE_SECRET=my_secret
    networks:
    - edge
networks:
  - edge
  external: true

It's running behind nginx-proxy by jwlinder.


text:
Q: Issue using DLookUp function in Access Ok so I have a text box on my main form and I want it to show the quantity of a product chosen from a drop down list.
Now there is a complication, there are 3 stock locations for each product, but this is simplified as I have 3 different levels stored on the same record for a product, with different column names.
So what I need to do is search for the name of the correct column to find the right stock location (again from a drop down).
My stock level column heading is stored in the variable "Branch" which is a string.
Here is my code.
Me.txtSourceDescQty.Value = DLookup(Branch, "[products/stock]", "[Product Code] = " & Me.cmbSource.Value)

This is the error I get. 'Stock Level' is the column header for one of the stock locations, which is stored under the variable "Branch" in the line of code.
cmbSource is the combo box where the product code is selected.

A: I think Me.cmbSource.Value needs to appear in quotes:
Me.txtSourceDescQty.Value = DLookup(Branch, "[products/stock]", "[Product Code] = '" & Me.cmbSource.Value & "'")


text:
Q: Displaying suggested results in magento search with solr I want to be able to display the results for the suggested search terms when a search on magento returns with no results but there are results for the suggested terms.
I want to be able to display the products for these search terms as if they were results of the original query.
This is using solr 3.6 and magento ee 1.13.0.2

A: To make sure you have an idea how search works in Magento.
Once the keyword or phrase you submit gets processed by Magento, there will be two updates happening on the DB level; one on the search query table. And another on the search results table.

catalogsearch_query
catalogsearch_result

The idea is for Magento not to search again for the same term if that keyword or phrase was submitted by another customer to make the process faster in the future.
Solr:
Since you are already using it, there is two ways to go:

*

*Make Solr be the search engine for the whole process, so you will be responsible for filling up the table with product IDs results, and if no products found then fill it up with suggested Products instead.

*Let Magento handle the search with its mechanism,  and you can handle the case of no results by filling up the results table and updating the query table also from Solr.
In both cases, you will need to extend the functionality of the Magento catalog search module for this to work.


text:
Q: c++: Initialize struct with one array containing all arguments I am currently working on a small tokenizer template function which also casts the tokens to different objects. this works really nice aslong as all the strucs I cast to have the same number of items. what I would like to do know is to make the function cast to structs with any number of items. The bottleneck of the function for me right now is this:
When it was a fixed number(in this case three) of items I did this:
mystruct holder = {items[i], items[i+1], items[i+2]};

Now my idea to be able to cast to structs with different items was to put all items into one array (all the struct items will be of the same type) and simply initialize it like this:
float values[numItems];
for(int j=0; j<numItems; j++) values[j] = items[i+j]
mystruct holder = {values};

But unfortunatelly you cant initialize a struct like this. Does anybody have an idea about how to achieve this?
Thanks!

A: You can just use a constructor which takes the array as its argument. Structs are basically classes but with a default member visibility of public rather than private.


text:
Q: Using a WITH as an aggregate value I am querying a Presto table where I want to calculate what percentage of the total a certain subset of the rows account for.
Consider a table like this:

id
m

1
5

1
7

2
9

3
8

I want to query to report how much of the total measure (m) is contributed by each id.  In this example, the total of the measure column is 29 can I find it with a query like...
SELECT SUM("m") FROM t;

output:
sqlite> SELECT SUM("m") FROM t;
29

Then I want to subtotal by id for some of the ids like
SELECT "id", SUM("m") AS "sub_total" FROM t WHERE "id" IN ('1','3') GROUP BY id;

output:
sqlite> SELECT "id", SUM("m") AS "sub_total" FROM t WHERE "id" IN ('1','3') GROUP BY id;
1|12
3|8

Now I want to add a third column where the subtotals are divided by the grand total (29) to get the percentage for each selected id.
I tried:
sqlite>
WITH a AS (
 SELECT SUM("m") AS g FROM t )
SELECT "id", SUM("m") AS "sub_total", SUM(m)*100/"a"."g"
FROM a, t
  WHERE "t"."id" IN ('1','3') GROUP BY "t"."id";

output:
1|12|41
3|8|27

Which is all good in SQLLite3!  But when I translate this to my actual Presto DB (and the right tables and columns), I get this error:
presto error: line 10:5: 'a.g' must be an aggregate expression or appear in GROUP BY clause

I can't understand what I'm missing here or why this would be different in Presto.

A: When you have a GROUP BY in your query, all expressions that the query is returning must be either:

*

*the expression you are grouping by

*or aggregate function

For example if you do GROUP BY id, the resulting query will return one row per id - you cannot just use m, because with id = 1 there are two values: 5 and 7 - so what should be returned? First value, last, sum, average? You need to tell it using aggregate function like sum(m).
Same with a.g - you need to add it to GROUP BY.
WITH a AS (
 SELECT SUM("m") AS g FROM t )
SELECT "id", SUM("m") AS "sub_total", SUM(m)*100/"a"."g"
FROM a, t
  WHERE "t"."id" IN ('1','3') GROUP BY "t"."id", "a"."g";

There's nothing special about PrestoDB here, it's more SQLite that's less strict, actually most other database engines would complain about your case.


text:
Q: An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the @RequestBody or the @RequestPart arguments I am teaching myself Spring by dissecting example applications and then adding code here and there to test theories that I develop during the dissection.  I am getting the following error message when testing some code that I added to a Spring application:
An Errors/BindingResult argument is expected to be declared immediately after the
model attribute, the @RequestBody or the @RequestPart arguments to which they apply

The method to which the error message refers is:
@RequestMapping(value = "/catowners", method = RequestMethod.GET)
public String findOwnersOfPetType(Integer typeID, BindingResult result, Map<String, Object> model) {
    // find owners of a specific type of pet
    typeID = 1;//this is just a placeholder
    Collection<Owner> results = this.clinicService.findOwnerByPetType(typeID);
    model.put("selections", results);
    return "owners/catowners";
}

This error message was triggered when I tried to load the /catowners url pattern in the web browser. I have reviewed this page and this posting, but the explanation does not seem clear.
Can anyone show me how to fix this error, and also explain what it means?
EDIT:
Based on Biju Kunjummen's response, I changed the syntax to the following:
@RequestMapping(value = "/catowners", method = RequestMethod.GET)
public String findOwnersOfPetType(@Valid Integer typeID, BindingResult result, Map<String, Object> model)

I am still getting the same error message.  Is ther something I am not understanding?
SECOND EDIT:
Based on Sotirios's comment, I changed the code to the following:
@RequestMapping(value = "/catowners", method = RequestMethod.GET)
public String findOwnersOfPetType(BindingResult result, Map<String, Object> model) {
    // find owners of a specific type of pet
    Integer typeID = 1;//this is just a placeholder
    Collection<Owner> results = this.clinicService.findOwnerByPetType(typeID);
    model.put("selections", results);
    return "owners/catowners";
 }

I am still getting the same error message after telling eclipse to run as...run on server again.
Is there something that I am not understanding?

A: If you have a parameter of type BindingResult it is essentially to hold any errors when binding http request parameters to a variable declared directly preceding the BindingResult method parameter.
So all of these is acceptable:
@RequestMapping(value = "/catowners", method = RequestMethod.GET)
public String findOwnersOfPetType(@Valid MyType type, BindingResult result, ...)

@RequestMapping(value = "/catowners", method = RequestMethod.GET)
public String findOwnersOfPetType(@ModelAttribute MyType type, BindingResult result, ...)

@RequestMapping(value = "/catowners", method = RequestMethod.GET)
public String findOwnersOfPetType(@RequestBody @Valid MyType type, BindingResult result, ...)

A: Spring uses an interface called HandlerMethodArgumentResolver to resolve the parameter in your handler methods and construct an object to pass as an argument.
If it doesn't find one, it passes null (I have to verify this).
The BindingResult is a result object that holds errors that may have come up validating a @ModelAttribute, @Valid, @RequestBody or @RequestPart, so you can only use it with parameters that are annotated as such. There are HandlerMethodArgumentResolver for each of those annotations.
EDIT (response to comment)
Your example seems to show that the user should provide a pet type (as an integer). I would change the method to
@RequestMapping(value = "/catowners", method = RequestMethod.GET)
public String findOwnersOfPetType(@RequestParam("type") Integer typeID, Map<String, Object> model)

And you would make your request (depending on your config) as
localhost:8080/yourcontext/catowners?type=1

Here too there is nothing to validate so you don't want or need a BindingResult. It would fail if you tried to add it anyway.


text:
Q: jquery / javascript hide everything expect div and its children How do I hide everything that is outside the class application? I want to hide everything that is within the body tag, but outside the
 with class application. Is it possible? However, all children of the
should still be visible.

title

Prompta habemus dissentiet quo no. Sit electram partiendo eu, civibus probatus euripidis at sea, usu admodum detracto te. No has dicta aliquid probatus, diam sanctus id mel, ne vocent animal eam. Cum an graeco aperiam concludaturque, ea posidonium contentiones sed, sed iriure admodum imperdiet ei.

title

A: There are no elements to hide in your example, but if there was you could do something like
$('body').children(':not(.application)').hide();

FIDDLE
That would get all direct children of the body tag except .application and hide them.

EDIT:
If you have textNodes directly in the body, those can't be hidden as they are not styleable, you have to wrap those nodes in elements first doing something like this
$('body').contents().filter(function() {
    return this.nodeType === 3;
}).wrap('');

FIDDLE
only then can you apply styles to those textNodes.

A: just use css for this
div.application ~ *{
  display:none !important;
}


text:
Q: How to set type for createApp(App) function in vuejs 3? I am using vue3 with firebase, on typescript.
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import { auth } from './firebase'

// eslint-disable-next-line
let app: any

auth.onAuthStateChanged(() => {
  if (!app) {
    app = createApp(App)
      .use(store)
      .use(router)
      .mount('#app')
  }
})

What type should I set to 'app' variable? I tried App, typeof App but it failed.

A: createApp returns an App instance. Since you already have an App imported, you need to rename the type while importing. But notice app.mount returns a different type, you can't chain it after createApp without changing the type:
import { createApp, App as Application } from 'vue'
import App from './App.vue'
// other imports

let app: Application

auth.onAuthStateChanged(() => {
  if (!app) {
    app = createApp(App)
    app.use(store)
    app.use(router)
    app.mount('#app')
  }
})


text:
Q: Disk acting full when it isn't I have just reinstalled Windows 10 on my laptop.
I tried to install Chrome, but got error 112 (which seems to mean disk full).
I tried to install Steam, and it installed fine, but when it tries to update it downloads, then says it needs to be online, the end of the log looks like this:
[2018-05-25 16:46:04] Downloading update (70,591 of 166,320 KB)...
[2018-05-25 16:46:17] Error: Saving package (tenfoot_images_all) failed.
[2018-05-25 16:46:17] Error: Steam needs to be online to update.     Please confirm your network connection and try again.
[2018-05-25 16:46:21] Shutdown

I checked, and I'm only using 20GB out of 900 on the C drive (the only drive at the moment).
I can download files, the issue seems to only affect installers, I have tried turning off Windows Firewall, but it made no difference.
Is there anything I can do to try to fix this?
Screenshots
Steam

Chrome

Edit
I tried to use the Windows USB Creator to re-install, but I got this error:

A: Two things to check:
1) If you just reinstalled Windows 10 onto your laptop I would make sure all your network drivers are installed. Go into device manager and make sure you see no yellow exclamation triangles.  Go to the laptop manufacturer's website, get to the drivers section, and you can go through there to double check.
2) With new installations or re-installations, Windows 10 tries to download the latest updates.  When this happens it can screw with your bandwidth when trying to download other things.  Temporarily disable and updates Windows is doing.  You should then have a smoother network connection.


text:
Q: "digits=2" doesn't work for one of arguments A script from R Cookbook:
q <- seq(from=0,to=3,by=0.5)
tbl <- data.frame(Quant=q, Lower=pnorm(-q), Upper=pnorm(q))
print(tbl,digits=2)

results in:
  Quant Lower Upper
1 0.0 0.5000 0.50
2 0.5 0.3085 0.69
3 1.0 0.1587 0.84
4 1.5 0.0668 0.93
5 2.0 0.0228 0.98
6 2.5 0.0062 0.99
7 3.0 0.0013 1.00

Why is "Lower" different from others?

A: The option "digits=2" makes sure that the output of each columns contains at least two significant digits. In the example above the last entry of Lower is 0.0013, with two significant (non-zero) digits.
As an example, we can modify the option to digits=3:
> print(tbl,digits=3)
#   Quant  Lower Upper
#1   0.0 0.50000 0.500
#2   0.5 0.30854 0.691
#3   1.0 0.15866 0.841
#4   1.5 0.06681 0.933
#5   2.0 0.02275 0.977
#6   2.5 0.00621 0.994
#7   3.0 0.00135 0.999

Note that Lower in row 7 now has three significant digits. The other entries in that column are adapted accordingly.
If want to have an output that contains not more than two decimal digits for any number in the table, irrespective of the significance of the digits, you could use the round() function:
> round(tbl, digits=2)
#  Quant Lower Upper
#1   0.0  0.50  0.50
#2   0.5  0.31  0.69
#3   1.0  0.16  0.84
#4   1.5  0.07  0.93
#5   2.0  0.02  0.98
#6   2.5  0.01  0.99
#7   3.0  0.00  1.00