text:
package org.drip.spaces.cover;

/*
 * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 */

/*!
 * Copyright (C) 2017 Lakshmi Krishnamurthy
 * Copyright (C) 2016 Lakshmi Krishnamurthy
 * Copyright (C) 2015 Lakshmi Krishnamurthy
 *
 *  This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
 *  	libraries targeting analysts and developers
 *  	https://lakshmidrip.github.io/DRIP/
 *
 *  DRIP is composed of four main libraries:
 *
 *  - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
 *  - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
 *  - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
 *  - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
 *
 *  - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
 *  	Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
 *  	Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
 *  	Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
 *  	Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
 *
 *  - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
 *  	Incorporator, Holdings Constraint, and Transaction Costs.
 *
 *  - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
 *
 *  - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *   	you may not use this file except in compliance with the License.
 *
 *  You may obtain a copy of the License at
 *  	http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  	distributed under the License is distributed on an "AS IS" BASIS,
 *  	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 *  See the License for the specific language governing permissions and
 *  	limitations under the License.
 */

/**
 * FunctionClassCoveringBounds implements the estimate Lower/Upper Bounds and/or Absolute Values of the
 * 	Covering Number for the Function Class. The Main References are:
 *
 * 	1) Carl, B., and I. Stephani (1990): Entropy, Compactness, and Approximation of Operators, Cambridge
 * 		University Press, Cambridge UK.
 *
 * 	2) Bartlett, P. L., S. R. Kulkarni, and S. E. Posner (1997): Covering Numbers for Real-valued Function
 * 		Classes, IEEE Transactions on Information Theory 43 (5) 1721-1724.
 *
 * @author Lakshmi Krishnamurthy
 */

public interface FunctionClassCoveringBounds {

	/**
	 * Log of the Lower Bound of the Function Covering Number
	 *
	 * @param dblCover The Size of the Cover
	 *
	 * @return Log of the Lower Bound of the Function Covering Number
	 *
	 * @throws java.lang.Exception Thrown if the Inputs are Invalid
	 */

	public abstract double logLowerBound (
		final double dblCover)
		throws java.lang.Exception;

	/**
	 * Log of the Upper Bound of the Function Covering Number
	 *
	 * @param dblCover The Size of the Cover
	 *
	 * @return Log of the Upper Bound of the Function Covering Number
	 *
	 * @throws java.lang.Exception Thrown if the Inputs are Invalid
	 */

	public abstract double logUpperBound (
		final double dblCover)
		throws java.lang.Exception;
}

redpajama_set_name: RedPajamaGithub


text:
namespace Apache.Ignite.Core.Events
{
    using System;
    using System.Globalization;
    using Apache.Ignite.Core.Binary;
    using Apache.Ignite.Core.Common;

    /// <summary>
    /// Ignite task event.
    /// </summary>
    public sealed class TaskEvent : EventBase
	{
        /** */
        private readonly string _taskName;

        /** */
        private readonly string _taskClassName;

        /** */
        private readonly IgniteGuid? _taskSessionId;

        /** */
        private readonly bool _internal;

        /** */
        private readonly Guid? _subjectId;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="r">The reader to read data from.</param>
        internal TaskEvent(IBinaryRawReader r) : base(r)
        {
            _taskName = r.ReadString();
            _taskClassName = r.ReadString();
            _taskSessionId = IgniteGuid.Read(r);
            _internal = r.ReadBoolean();
            _subjectId = r.ReadGuid();
        }

        /// <summary>
        /// Gets name of the task that triggered the event.
        /// </summary>
        public string TaskName { get { return _taskName; } }

        /// <summary>
        /// Gets name of task class that triggered this event.
        /// </summary>
        public string TaskClassName { get { return _taskClassName; } }

        /// <summary>
        /// Gets session ID of the task that triggered the event.
        /// </summary>
        public IgniteGuid? TaskSessionId { get { return _taskSessionId; } }

        /// <summary>
        /// Returns true if task is created by Ignite and is used for system needs.
        /// </summary>
        public bool Internal { get { return _internal; } }

        /// <summary>
        /// Gets security subject ID initiated this task event, if available. This property is not available for
        /// <see cref="EventType.EventTaskSessionAttrSet" /> task event.
        /// Subject ID will be set either to node ID or client ID initiated task execution.
        /// </summary>
        public Guid? SubjectId { get { return _subjectId; } }

        /** <inheritDoc /> */
	    public override string ToShortString()
	    {
	        return string.Format(CultureInfo.InvariantCulture,
	            "{0}: TaskName={1}, TaskClassName={2}, TaskSessionId={3}, Internal={4}, " +
	            "SubjectId={5}", Name, TaskName, TaskClassName, TaskSessionId, Internal, SubjectId);
	    }
    }
}


text:
@implementation TKDAppCollectionView

- (NSCollectionViewItem *)newItemForRepresentedObject:(id)object {
    TKDAppViewItem *appIcon = (TKDAppViewItem *)[super newItemForRepresentedObject:object];
    TKDAppViewItem *prototype = (TKDAppViewItem *)self.itemPrototype;

    appIcon.tokaidoController = prototype.tokaidoController;
    [appIcon view];

    appIcon.tokenField.delegate = appIcon;
    appIcon.appIcon.delegate = appIcon;

    [appIcon.appIcon configureForRepresentedObject];
    [appIcon.tokenField configureForRepresentedObject];

    return  appIcon;
}

@end


text:
package org.gradle.tests2;

import org.junit.Test;

public class Test2_1 {
    @Test
    public void myTest() throws Exception {
        Thread.sleep(5);
    }
}


text:
import {mixin, fromMixin} from '../../mixin';

export let grid = mixin('grid', function({nospacing}) {
	this.class.push('mdl-grid');

	if (nospacing) this.class.push('mdl-grid--no-spacing');
});

export let Grid = fromMixin(grid);


text:
<?php

namespace AppBundle\Tests\Controller;

use AppBundle\Tests\TestBase;

class CountryControllerTest extends TestBase
{
    public function testIndex()
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/Northern_Ireland/Northern_Ireland');
        echo $crawler->filter('')->text();

//        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertContains('Northern Ireland', $crawler->filter('')->text());
        $this->assertContains('Country: ', $crawler->filter('')->text());
        $this->assertContains('Summary: ', $crawler->filter('')->text());
    }
}


text:
from players.player_DDPG_1 import *
import tensorflow as tf
import numpy as np

# PLAYER DDPG
class player_DDPG_1A( player_DDPG_1 ):

    EXPERIENCES_LEN    = 1e6
    BATCH_SIZE         = 128
    STEPS_BEFORE_TRAIN = 5000
    NUM_FRAMES         = 1
    C_LEARNING_RATE    = 1e-3
    A_LEARNING_RATE    = 1e-4
    TAU                = 0.01
    REWARD_DISCOUNT    = 0.99

    ### __INIT__
    def __init__( self ):

        player_DDPG_1.__init__( self )

    # PROCESS OBSERVATION
    def process(self, obsv):

        return np.stack( tuple(self.obsv_list[i] for i in range(self.NUM_FRAMES)), axis = 1 )

    # PREPARE NETWORK
    def network( self ):

        # Critic

        NormalCritic = self.brain.addBlock( 'NormalCritic' )

        NormalCritic.addInput( shape = [ None, self.obsv_shape[0], self.NUM_FRAMES ], name  = 'Observation' )
        NormalCritic.addInput( shape = [ None, self.num_actions ], name  = 'Actions' )

        NormalCritic.setLayerDefaults( type       = tb.layers.hlfully,
                                       activation = tb.activs.relu,
                                       bias       = False)

        NormalCritic.addLayer( input = 'Observation',out_channels = 128, name = 'Hidden1' )

        H1 = NormalCritic.tensor( 'Hidden1' )
        H2 = NormalCritic.tensor( 'Actions' )
        H3 = tf.concat( [H1,H2], 1 )
        NormalCritic.addInput( tensor = H3, name = 'Hidden3' )

        NormalCritic.addLayer( input = 'Hidden3', out_channels = 200, name = 'Hidden4' )
        NormalCritic.addLayer( input = 'Hidden4', out_channels = 1, activation = None , name = 'Value' )

        # Target Critic

        TargetCritic = self.brain.addBlock( 'TargetCritic' )

        TargetCritic.addInput( shape = [ None, self.obsv_shape[0], self.NUM_FRAMES ], name  = 'Observation')
        TargetCritic.addInput( shape = [ None, self.num_actions ], name  = 'Actions' )

        TargetCritic.setLayerDefaults( type       = tb.layers.hlfully,
                                       activation = tb.activs.relu,
                                       bias       = False )

        TargetCritic.addLayer( input = 'Observation', out_channels = 128, name = 'Hidden1', copy_weights = '../NormalCritic/W_Hidden1' )

        H1 = TargetCritic.tensor ('Hidden1' )
        H2 = TargetCritic.tensor( 'Actions' )
        H3 = tf.concat( [H1,H2],1 )
        TargetCritic.addInput( tensor = H3, name = 'Hidden3')

        TargetCritic.addLayer( input = 'Hidden3', out_channels = 200, name = 'Hidden4', copy_weights = '../NormalCritic/W_Hidden4' )
        TargetCritic.addLayer( input = 'Hidden4', out_channels = 1, activation = None , name = 'Value', copy_weights = '../NormalCritic/W_Value' )

        # Actor

        NormalActor = self.brain.addBlock( 'NormalActor' )

        NormalActor.addInput( shape=[ None, self.obsv_shape[0], self.NUM_FRAMES ], name='Observation' )

        NormalActor.setLayerDefaults( type       = tb.layers.hlfully,
                                      activation = tb.activs.relu,
                                      bias       = False )

        NormalActor.addLayer( input = 'Observation', out_channels = 128, name = 'Hidden1' )
        NormalActor.addLayer( input = 'Hidden1',     out_channels = 200, name = 'Hidden2' )
        NormalActor.addLayer( input = 'Hidden2',     out_channels = self.num_actions,
                              activation = tb.activs.tanh, name = 'Out', min = -0.003, max = 0.003)

        out = NormalActor.tensor('Out')
        out = tf.multiply( out, self.range_actions )
        NormalActor.addInput( tensor = out, name = 'Output')

        # Target Actor

        TargetActor = self.brain.addBlock( 'TargetActor' )

        TargetActor.addInput( shape=[ None, self.obsv_shape[0], self.NUM_FRAMES ], name='Observation' )

        TargetActor.setLayerDefaults( type       = tb.layers.hlfully,
                                      activation = tb.activs.relu,
                                      bias       = False )

        TargetActor.addLayer( input = 'Observation', out_channels = 128, name = 'Hidden1', copy_weights = '../NormalActor/W_Hidden1')
        TargetActor.addLayer( input = 'Hidden1',     out_channels = 200, name = 'Hidden2', copy_weights = '../NormalActor/W_Hidden2')
        TargetActor.addLayer( input = 'Hidden2',     out_channels = self.num_actions, name = 'Out',
                              activation = tb.activs.tanh, min = -0.003, max = 0.003, copy_weights = '../NormalActor/W_Out')

        out = TargetActor.tensor('Out')
        out = tf.multiply( out, self.range_actions )
        TargetActor.addInput( tensor = out, name = 'Output')


text:
from {{project_name}}.settings.base import *  # noqa
from {{project_name}}.settings.secret import *  # noqa

HOST = f'alpha.{BASE_HOST_URL}'
ALLOWED_HOSTS = (HOST,)

# Database
# https://docs.djangoproject.com/en/{{docs_version}}/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': DATABASES_DEFAULT_NAME or '{{project_name}}_alpha',
        'USER': DATABASES_DEFAULT_USER or '{{project_name}}',
        'PASSWORD': DATABASES_DEFAULT_PASSWORD or '',
        'HOST': DATABASES_DEFAULT_HOST or '127.0.0.1',
        'PORT': DATABASES_DEFAULT_PORT or '5432',
    }
}

# Email Settings
# https://docs.djangoproject.com/en/{{docs_version}}/topics/email/

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = EMAIL_HOST or ''

# Debug

DEBUG = True
TEMPLATES[0]['OPTIONS']['debug'] = DEBUG  # noqa

# Assets

# STATIC_DEBUG = True

# Sites
# https://docs.djangoproject.com/en/{{docs_version}}/ref/contrib/sites/

# SITE_ID = 3

# Invoke commands configuration

WORKING_DIR = 'www/{{project_name}}_alpha'
HOST_USER = ''
HOST_IP = ''
HOST_PORT = '22'


text:
'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    /*
      Add altering commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.createTable('users', { id: Sequelize.INTEGER });
    */
    return queryInterface.addColumn('Recipes', 'ingredients', {
      type: Sequelize.TEXT,
      defaultValue: ''
    });
  },

  down: (queryInterface, Sequelize) => {
    /*
      Add reverting commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.dropTable('users');
    */
  }
};


text:
DZNEmptyDataSet
=================

[![Pod Version](http://img.shields.io/cocoapods/v/DZNEmptyDataSet.svg)](http://cocoadocs.org/docsets/DZNEmptyDataSet/)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![License](http://img.shields.io/badge/license-MIT-blue.svg)](http://opensource.org/licenses/MIT)

### Projects using this library

[Add your project to the list here](https://github.com/dzenbot/DZNEmptyDataSet/wiki/Projects-using-DZNEmptyDataSet) and provide a (320px wide) render of the result.

### The Empty Data Set Pattern
Also known as *[Empty State](http://emptystat.es/)* or *[Blank Slate](http://patternry.com/p=blank-slate/)*.

Most applications show lists of content (data sets), which many turn out to be empty at one point, specially for new users with blank accounts. Empty screens create confusion by not being clear about what's going on, if there is an error/bug or if the user is supposed to do something within your app to be able to consume the content.

Please read this very interesting article about [*Designing For The Empty States*](http://tympanus.net/codrops/2013/01/09/designing-for-the-empty-states/).

![Screenshots_Row1](https://raw.githubusercontent.com/dzenbot/UITableView-DataSet/master/Examples/Applications/Screenshots/Screenshots_row1.png)
![Screenshots_Row2](https://raw.githubusercontent.com/dzenbot/UITableView-DataSet/master/Examples/Applications/Screenshots/Screenshots_row2.png)
(*These are real life examples, available in the 'Applications' sample project*)

**[Empty Data Sets](http://pttrns.com/?did=1&scid=30)** are helpful for:
* Avoiding white-screens and communicating to your users why the screen is empty.
* Calling to action (particularly as an onboarding process).
* Avoiding other interruptive mechanisms like showing error alerts.
* Beeing consistent and improving the user experience.
* Delivering a brand presence.

### Features
* Compatible with UITableView and UICollectionView. Also compatible with UISearchDisplayController and UIScrollView.
* Gives multiple possibilities of layout and appearance, by showing an image and/or title label and/or description label and/or button.
* Uses NSAttributedString for easier appearance customisation.
* Uses auto-layout to automagically center the content to the tableview, with auto-rotation support. Also accepts custom vertical and horizontal alignment.
* Background color customisation.
* Allows tap gesture on the whole tableview rectangle (useful for resigning first responder or similar actions).
* For more advanced customisation, it allows a custom view.
* Compatible with Storyboard.
* Compatible with iOS 6 or later.
* Compatible with iPhone and iPad.
* **App Store ready**

This library has been designed in a way where you won't need to extend UITableView or UICollectionView class. It will still work when using UITableViewController or UICollectionViewController.
By just conforming to DZNEmptyDataSetSource & DZNEmptyDataSetDelegate, you will be able to fully customize the content and appearance of the empty states for your application.

## Installation

Available in [Cocoa Pods](http://cocoapods.org/?q=DZNEmptyDataSet)
```ruby
pod 'DZNEmptyDataSet'
```
To integrate DZNEmptyDataSet into your Xcode project using Carthage, specify it in your `Cartfile`:

```ogdl
github "dzenbot/DZNEmptyDataSet"
```

## How to use
For complete documentation, [visit CocoaPods' auto-generated doc](http://cocoadocs.org/docsets/DZNEmptyDataSet/)

### Import
```objc
#import "UIScrollView+EmptyDataSet.h"
```

### Protocol Conformance
Conform to datasource and/or delegate.
```objc
@interface MainViewController : UITableViewController <DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;

    // A little trick for removing the cell separators
    self.tableView.tableFooterView = [UIView new];
}
```

### Dealloc
~~You MUST disable the datasource and/or delegate in your view controller's `dealloc` method.
This will unregister internal observers and invalidate private states.~~

Disabling the datasource and/or delegate in your the controller's `dealloc` method is no longer needed. Take a look at [#91](https://github.com/dzenbot/DZNEmptyDataSet/issues/91) for more information.

### Data Source Implementation
Return the content you want to show on the empty state, and take advantage of NSAttributedString features to customise the text appearance.

The image for the empty state:
```objc
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIImage imageNamed:@"empty_placeholder"];
}
```

The attributed string for the title of the empty state:
```objc
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = @"Please Allow Photo Access";

    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:18.0],
                                 NSForegroundColorAttributeName: [UIColor darkGrayColor]};

    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}
```

The attributed string for the description of the empty state:
```objc
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = @"This allows you to share photos from your library and save photos to your camera roll.";

    NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    paragraph.alignment = NSTextAlignmentCenter;

    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0],
                                 NSForegroundColorAttributeName: [UIColor lightGrayColor],
                                 NSParagraphStyleAttributeName: paragraph};

    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}
```

The attributed string to be used for the specified button state:
```objc
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
{
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:17.0]};

    return [[NSAttributedString alloc] initWithString:@"Continue" attributes:attributes];
}
```

or the image to be used for the specified button state:
```objc
- (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
{
    return [UIImage imageNamed:@"button_image"];
}
```

The background color for the empty state:
```objc
- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIColor whiteColor];
}
```

If you need a more complex layout, you can return a custom view instead:
```objc
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
{
    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [activityView startAnimating];
    return activityView;
}
```

Additionally, you can modify the horizontal and/or vertical alignments (as when using a tableHeaderView):
```objc
- (CGPoint)offsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return CGPointMake(0, -self.tableView.tableHeaderView.frame.size.height/2);
}
```

### Delegate Implementation
Return the behaviours you would expect from the empty states, and receive the user events.

Asks to know if the empty state should be rendered and displayed (Default is YES) :
```objc
- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
{
    return YES;
}
```

Asks for interaction permission (Default is YES) :
```objc
- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView
{
    return YES;
}
```

Asks for scrolling permission (Default is NO) :
```objc
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}
```

Notifies when the dataset view was tapped:
```objc
- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView
{
    // Do something
}
```

Notifies when the data set call to action button was tapped:
```objc
- (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView
{
    // Do something
}
```

### Refresh layout
If you need to refresh the empty state layout, simply call:

```objc
[self.tableView reloadData];
```
or
```objc
[self.collectionView reloadData];
```
depending of which you are using.

### Force layout update
You can also call `[self.tableView reloadEmptyDataSet]` to invalidate the current empty state layout and trigger a layout update, bypassing `-reloadData`. This might be useful if you have a lot of logic on your data source that you want to avoid calling, when not needed. `[self.tableView reloadEmptyDataSet]` is the only way to refresh content when using with UIScrollView.

## Sample projects

#### Applications
This project replicates several popular application's empty states (~20) with their exact content and appearance, such as Airbnb, Dropbox, Facebook, Foursquare, and many others. See how easy and flexible it is to customize the appearance of your empty states. You can also use this project as a playground to test things.

#### Countries
This project shows a list of the world countries loaded from CoreData. It uses NSFecthedResultController for filtering search. When searching and no content is matched, a simple empty state is shown. See how to interact between the UITableViewDataSource and the DZNEmptyDataSetSource protocols, while using a typical CoreData stack.

#### Colors
This project is a simple example of how this library also works with UICollectionView and UISearchDisplayController, while using Storyboards.

## Collaboration
Feel free to collaborate with ideas, issues and/or pull requests.

## License
(The MIT License)

Copyright (c) 2015 Ignacio Romero Zurbuchen <iromero@dzen.cl>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace P008_String_to_Integer
{
    class Program
    {
        static void Main(string[] args)
        {
            var solution = new Solution();
            Console.WriteLine(solution.MyAtoi("1024"));
            Console.WriteLine(solution.MyAtoi("-1024"));
            Console.WriteLine(solution.MyAtoi(uint.MaxValue.ToString()));
            Console.WriteLine(solution.MyAtoi("-" + uint.MaxValue.ToString()));
            Console.WriteLine(solution.MyAtoi("+1"));
            Console.ReadLine();
        }
    }
}


text: Service samples.


text:
`sphep` is a tiny C++ tool for generating evenly distributed points on a d-dimensional sphere. It works by generating random points on the sphere and redistributing them by a constrained n-body simulation.
Requirements:
- Eigen3 library

### test
The generator can be tested using the spheptest inside of the test subfolder.
The output points can be visualized using `gnuplot`:
```splot "points.txt" pointtype 7```
### license
The code (except `FindEigen3.cmake`) is licensed under the MIT-license. See the LICENSE file. The cmake module `FindEigen3.cmake` is licensed under BSD 2-clause license (see the top of that file)


text:
#import <Foundation/Foundation.h>
#import "SWGObject.h"

@protocol SWGLocation
@end

@interface SWGLocation : SWGObject

@property(nonatomic) NSString<Optional>* street;

@property(nonatomic) NSString<Optional>* zip;

@property(nonatomic) NSString<Optional>* city;

@property(nonatomic) NSString<Optional>* country;

/* demo for java.math.BigDecimal [optional]
 */
@property(nonatomic) NSNumber<Optional>* latitude;

/* demo for java.lang.Double [optional]
 */
@property(nonatomic) NSNumber<Optional>* longitude;

@end


text:
#include "KubernetesControllerService.h"

#include <vector>

extern "C" {
#include "api/CoreV1API.h"
}

#include "core/PropertyBuilder.h"
#include "core/Resource.h"
#include "core/logging/LoggerConfiguration.h"
#include "Exception.h"
#include "utils/gsl.h"
#include "utils/StringUtils.h"

namespace org::apache::nifi::minifi::controllers {

const core::Property KubernetesControllerService::NamespaceFilter{
    core::PropertyBuilder::createProperty("Namespace Filter")
        ->withDescription("Limit the output to pods in namespaces which match this regular expression")
        ->withDefaultValue<std::string>("default")
        ->build()};
const core::Property KubernetesControllerService::PodNameFilter{
    core::PropertyBuilder::createProperty("Pod Name Filter")
        ->withDescription("If present, limit the output to pods the name of which matches this regular expression")
        ->build()};
const core::Property KubernetesControllerService::ContainerNameFilter{
    core::PropertyBuilder::createProperty("Container Name Filter")
        ->withDescription("If present, limit the output to containers the name of which matches this regular expression")
        ->build()};

KubernetesControllerService::KubernetesControllerService(const std::string& name, const utils::Identifier& uuid)
  : AttributeProviderService(name, uuid),
    logger_{core::logging::LoggerFactory<KubernetesControllerService>::getLogger()} {
}

KubernetesControllerService::KubernetesControllerService(const std::string& name, const std::shared_ptr<Configure>& configuration)
  : KubernetesControllerService{name} {
    setConfiguration(configuration);
    initialize();
}

void KubernetesControllerService::initialize() {
  std::lock_guard<std::mutex> lock(initialization_mutex_);
  if (initialized_) { return; }

  ControllerService::initialize();
  setSupportedProperties(properties());
  initialized_ = true;
}

void KubernetesControllerService::onEnable() {
  try {
    api_client_ = std::make_unique<kubernetes::ApiClient>();
  } catch (const std::runtime_error& ex) {
    logger_->log_error("Could not create the API client in the Kubernetes Controller Service: %s", ex.what());
  }

  std::string namespace_filter;
  if (getProperty(NamespaceFilter.getName(), namespace_filter) && !namespace_filter.empty()) {
    namespace_filter_ = utils::Regex{namespace_filter};
  }

  std::string pod_name_filter;
  if (getProperty(PodNameFilter.getName(), pod_name_filter) && !pod_name_filter.empty()) {
    pod_name_filter_ = utils::Regex{pod_name_filter};
  }

  std::string container_name_filter;
  if (getProperty(ContainerNameFilter.getName(), container_name_filter) && !container_name_filter.empty()) {
    container_name_filter_ = utils::Regex{container_name_filter};
  }
}

namespace {

struct v1_pod_list_t_deleter {
  void operator()(v1_pod_list_t* ptr) const noexcept { v1_pod_list_free(ptr); }
};
using v1_pod_list_unique_ptr = std::unique_ptr<v1_pod_list_t, v1_pod_list_t_deleter>;

v1_pod_list_unique_ptr getPods(gsl::not_null<apiClient_t*> api_client, core::logging::Logger& logger) {
  logger.log_info("Calling Kubernetes API listPodForAllNamespaces...");
  v1_pod_list_unique_ptr pod_list{CoreV1API_listPodForAllNamespaces(api_client,
                                                                    0,  // allowWatchBookmarks
                                                                    nullptr,  // continue
                                                                    nullptr,  // fieldSelector
                                                                    nullptr,  // labelSelector
                                                                    0,  // limit
                                                                    nullptr,  // pretty
                                                                    nullptr,  // resourceVersion
                                                                    nullptr,  // resourceVersionMatch
                                                                    0,  // timeoutSeconds
                                                                    0)};  // watch
  logger.log_info("The return code of the Kubernetes API listPodForAllNamespaces call: %ld", api_client->response_code);
  return pod_list;
}

}  // namespace

std::optional<std::vector<KubernetesControllerService::AttributeMap>> KubernetesControllerService::getAttributes() {
  if (!api_client_) {
    logger_->log_warn("The Kubernetes client is not valid, unable to call the Kubernetes API");
    return std::nullopt;
  }

  const auto pod_list = getPods(api_client_->getClient(), *logger_);
  if (!pod_list) {
    logger_->log_warn("Could not find any Kubernetes pods");
    return std::nullopt;
  }

  std::vector<AttributeMap> container_attribute_maps;

  listEntry_t* pod_entry = nullptr;
  list_ForEach(pod_entry, pod_list->items) {
    const auto pod = static_cast<v1_pod_t*>(pod_entry->data);

    std::string name_space{pod->metadata->_namespace};
    std::string pod_name{pod->metadata->name};
    std::string uid{pod->metadata->uid};

    listEntry_t* container_entry = nullptr;
    list_ForEach(container_entry, pod->spec->containers) {
      auto container = static_cast<v1_container_t*>(container_entry->data);

      std::string container_name{container->name};

      if (matchesRegexFilters(name_space, pod_name, container_name)) {
        container_attribute_maps.push_back(AttributeMap{
            {"namespace", name_space},
            {"pod", pod_name},
            {"uid", uid},
            {"container", container_name}});
      }
    }
  }

  logger_->log_info("Found %zu containers (after regex filtering) in %ld Kubernetes pods (unfiltered)", container_attribute_maps.size(), pod_list->items->count);
  return container_attribute_maps;
}

bool KubernetesControllerService::matchesRegexFilters(const kubernetes::ContainerInfo& container_info) const {
  return matchesRegexFilters(container_info.name_space, container_info.pod_name, container_info.container_name);
}

bool KubernetesControllerService::matchesRegexFilters(const std::string& name_space, const std::string& pod_name, const std::string& container_name) const {
  static constexpr auto matchesFilter = [](const std::string& target, const std::optional<utils::Regex>& filter) {
    return !filter || utils::regexMatch(target, *filter);
  };
  return matchesFilter(name_space, namespace_filter_) &&
      matchesFilter(pod_name, pod_name_filter_) &&
      matchesFilter(container_name, container_name_filter_);
}

REGISTER_RESOURCE(KubernetesControllerService, ControllerService);

}  // namespace org::apache::nifi::minifi::controllers


text:
import json
import Tkinter as tk
from Queue import Queue, Empty
import sys

from Threads import TelemetryThread

class TelemetryWidget(tk.Frame):
    """
    Shows structured output from valmar.

    Args:
        parent: parent window
    """
    def __init__(self, parent):
        tk.Frame.__init__(self, parent, bd=2, relief='groove')
        self.parent = parent

        #contains all pretty views
        self.translationKeys = self.load_keys('../gui/telemetryTranslation.json')
        self.labels = {}
        self.values = {}
        self.telemetry_data = {}

        #instantiate ui
        self.set_telemetry_ui()

        #start grabbing data
        self.update_telemetry_loop()

    def set_telemetry_ui(self, json_object = None):
        """ Initialize visual elements of widget. """
        index = 0
        for key, val in self.translationKeys.iteritems():
            # label
            if val['display']:
                if key not in self.labels:
                    #update label row
                    self.labels[key] = tk.Label(self, text=val['friendly_name']+ ' (' + val['unit'] + ')', padx=5, pady=5, bd=2, justify='left', relief='ridge', width=18)
                    self.labels[key].grid(row=val['display_order'], column=0, sticky='nsew')
                    #update value column
                    self.values[key] = tk.Label(self, padx=5, pady=5, width=18, anchor='w')
                    self.values[key].grid(row=val['display_order'],column=1, sticky='nsew')
                    self.telemetry_data[key] = ''
                    #make expandable
                    self.grid_rowconfigure(index, weight=1)
                    index += 1

        self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=1)
        self.parent.grid_columnconfigure(0, weight=1)
        self.parent.grid_rowconfigure(0, weight=1)
        self.grid()
        self.update()

    def set_telemetry_data(self, telemetryData):
        self.telemetry_data = telemetryData

    def update_telemetry_loop(self):
        for key, val in self.translationKeys.iteritems():
            if val['display']:
                #print 'Telemetry Data:'
                #print self.telemetry_data
                self.values[key]
                self.values[key]['text'] = self.telemetry_data[key]
        self.after(500, self.update_telemetry_loop)

    def load_keys(self, config_file):
        with open(config_file) as f:
            configuration = \
                json.load(f)#.replace('\n', '').replace(' ', '').replace('\r', '')
        return configuration

if __name__=='__main__':
    from Queue import Queue
    root = tk.Tk()
    t = TelemetryWidget(root, Queue())
    t.grid()
    root.update()
    print t.winfo_height(), t.winfo_width()
    root.mainloop()
    sys.exit()


text:
<?xml version="1.0"?>
<form xmlns="http://www.demandware.com/xml/form/2008-04-19">
	<action formid="selectvariation" valid-form="false"/>
	<action formid="selectoption" valid-form="false"/>
	<action formid="addtocart" valid-form="false"/>
	<action formid="compare" valid-form="false"/>
	<action formid="variation" valid-form="false"/>
	<action formid="addtowishlist" valid-form="false"/>
	<action formid="addtogiftregistry" valid-form="false"/>
</form>


text:
from django.core.management.base import BaseCommand
from django.core.paginator import Paginator
from rois_manager.models import Slice

from csv import DictWriter

import logging

logger = logging.getLogger('promort_commands')

class Command(BaseCommand):
    help = """
    Export existing Slices data to CSV (ROIs data only)
    """

    def add_arguments(self, parser):
        parser.add_argument('--output_file', dest='output', type=str, required=True,
                            help='path of the output CSV file')
        parser.add_argument('--page_size', dest='page_size', type=int, default=0,
                            help='the number of records retrieved for each page (this will enable pagination)')

    def _dump_data(self, page_size, csv_writer):
        if page_size > 0:
            logger.info('Pagination enabled (%d records for page)', page_size)
            s_qs = Slice.objects.get_queryset().defer('roi_json').order_by('creation_date')
            paginator = Paginator(s_qs, page_size)
            for x in paginator.page_range:
                logger.info('-- page %d --', x)
                page = paginator.page(x)
                for s in page.object_list:
                    self._dump_row(s, csv_writer)
        else:
            logger.info('Loading full batch')
            slices = Slice.objects.all()
            for s in slices:
                self._dump_row(s, csv_writer)

    def _dump_row(self, slice, csv_writer):
        try:
            action_start_time = slice.action_start_time.strftime('%Y-%m-%d %H:%M:%S')
        except AttributeError:
            action_start_time = None
        try:
            action_complete_time = slice.action_complete_time.strftime('%Y-%m-%d %H:%M:%S')
        except AttributeError:
            action_complete_time = None
        csv_writer.writerow(
            {
                'case_id': slice.slide.case.id,
                'slide_id': slice.slide.id,
                'rois_review_step_id': slice.annotation_step.label,
                'slice_label': slice.label,
                'slice_id': slice.id,
                'action_start_time': action_start_time,
                'action_complete_time': action_complete_time,
                'creation_date': slice.creation_date.strftime('%Y-%m-%d %H:%M:%S'),
                'reviewer': slice.author.username,
                'positive_slice': slice.is_positive(),
                'total_cores': slice.total_cores,
                'positive_cores': slice.get_positive_cores_count()
            }
        )

    def _export_data(self, out_file, page_size):
        header = ['case_id', 'slide_id', 'rois_review_step_id', 'slice_label', 'slice_id', 'action_start_time',
                  'action_complete_time', 'creation_date', 'reviewer', 'positive_slice',
                  'positive_cores', 'total_cores']
        with open(out_file, 'w') as ofile:
            writer = DictWriter(ofile, delimiter=',', fieldnames=header)
            writer.writeheader()
            self._dump_data(page_size, writer)

    def handle(self, *args, **opts):
        logger.info('=== Starting export job ===')
        self._export_data(opts['output'], opts['page_size'])
        logger.info('=== Data saved to %s ===', opts['output'])


text:
<!DOCTYPE html>

    <title>Layer order example</title>
    <meta charset="utf-8">
    <meta name="viewport"
          content="initial-scale=1.0, user-scalable=no, width=device-width">
    <meta name="mobile-web-app-capable" content="yes">

      Change order of layers on the map by changing the order of items in the
      list below.

      Hint: drag-drop elements using the handle.

        {{layer.get('name')}}

      Add/remove the "Roads" layer:
      <input type="checkbox" ng-model="ctrl.toggleRoadsLayer" ng-model-options="{getterSetter: true}"/>

This example shows how to use the ngeo-sortable directive and the ngeo.misc.syncArrays function to create a list of layers where the order of layers can be changed using drag-and-drop.


text:
#import "NSViewController.h"

#import "IDEVariablesViewQuickLookProvider-Protocol.h"

@class DBGDataValue, DBGRectView, NSLayoutConstraint, NSString, NSTextField, NSURL, NSView;

@interface DBGRectQuickLookProvider : NSViewController <IDEVariablesViewQuickLookProvider>
{
    DBGDataValue *_dataValue;
    int _loadedState;
    DBGRectView *_rectView;
    NSLayoutConstraint *_widthConstraint;
    NSLayoutConstraint *_heightConstraint;
    NSView *_xyContainerView;
    NSTextField *_xyLabel;
    NSTextField *_widthLabel;
    NSTextField *_heightLabel;
}

@property __weak NSTextField *heightLabel; // @synthesize heightLabel=_heightLabel;
@property __weak NSTextField *widthLabel; // @synthesize widthLabel=_widthLabel;
@property __weak NSTextField *xyLabel; // @synthesize xyLabel=_xyLabel;
@property __weak NSView *xyContainerView; // @synthesize xyContainerView=_xyContainerView;
@property __weak NSLayoutConstraint *heightConstraint; // @synthesize heightConstraint=_heightConstraint;
@property __weak NSLayoutConstraint *widthConstraint; // @synthesize widthConstraint=_widthConstraint;
@property __weak DBGRectView *rectView; // @synthesize rectView=_rectView;
@property int loadedState; // @synthesize loadedState=_loadedState;
- (void).cxx_destruct;
- (id)blockStartAddress;
- (void)cancelLoading;
@property(readonly) NSView *quickLookView;
- (void)_updateRectWithX:(id)arg1 y:(id)arg2 width:(id)arg3 height:(id)arg4;
- (void)_startRetrieval;
- (void)loadView;
- (id)initWithDataValue:(id)arg1 options:(id)arg2;

// Remaining properties
@property(readonly) NSURL *existingURLToOpen;
@property(readonly) NSString *extensionForTemporaryFile;

@end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="../../../../../../../webapp/css/ticket-stylesheet.css">

                <button id="buttonTable">Table</button>
                <button id="buttonForm">Form</button>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_height="match_parent"
	android:layout_width="match_parent"
	android:orientation="vertical">

	<EditText
		android:layout_height="wrap_content"
		android:inputType="textMultiLine"
		android:layout_width="match_parent"
		android:ems="12"
		android:gravity="top|start"
		android:layout_weight="100.0"
		android:singleLine="false"
		android:textIsSelectable="true"
		android:typeface="monospace"
    android:fontFamily="monospace"
		android:id="@+id/editor"/>

	<LinearLayout
		style="?android:attr/buttonBarStyle"
		android:layout_height="wrap_content"
		android:layout_width="match_parent"
		android:orientation="horizontal">

		<Button
			style="?android:attr/buttonStyleSmall"
			android:layout_height="wrap_content"
			android:layout_width="wrap_content"
			android:text="Load"
			android:id="@+id/button_load"/>

		<View
			android:background="?android:attr/dividerHorizontal"
			android:layout_height="match_parent"
			android:layout_width="1dp"/>

		<LinearLayout
			android:layout_height="match_parent"
			android:layout_width="wrap_content"
			android:orientation="horizontal"
			android:layout_weight="100"/>

		<View
			android:background="?android:attr/dividerHorizontal"
			android:layout_height="match_parent"
			android:layout_width="1dp"/>

		<Button
			style="?android:attr/buttonStyleSmall"
			android:layout_height="wrap_content"
			android:layout_width="wrap_content"
			android:text="Save"
			android:id="@+id/button_save"/>

	</LinearLayout>

</LinearLayout>


text:
import Ember from 'ember';

export default Ember.Component.extend({

  lightGallery: null,

  didInsertElement(){
    var _this = this;

    this._super();

    Ember.run.scheduleOnce('afterRender', this, function(){
      var lightGallery = Ember.$("#imageGallery").lightGallery({
        thumbnail: false,
        hideControlOnEnd: true,
        closable: false,
        counter: true,
        swipeThreshold : 50,
        enableTouch : true,
        selector: '.preview_image'
      });

      _this.set("lightGallery", lightGallery);

    });
  },

  willDestroyElement() {
    this.get("lightGallery").destroy();
  }

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE section PUBLIC "-//Boost//DTD BoostBook XML V1.1//EN"
"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">

  <title>Tutorial and Motivating Examples</title>

    <title>Arithmetic Expressions Can Yield Incorrect Results</title>

    <para>When some operation on signed integer types results in a result
    which exceeds the capacity of a data variable to hold it, the result is
    undefined. In the case of unsigned integer types a similar situation
    results in a value wrap as per modulo arithmetic. In either case the
    result is different than in integer number arithmetic in the mathematical
    sense. This is called "overflow". Since word size can differ between
    machines, code which produces mathematically correct results in one set of
    circumstances may fail when re-compiled on a machine with different
    hardware. When this occurs, most C++ programs will continue to execute
    with no indication that the results are wrong. It is the programmer's
    responsibility to ensure such undefined behavior is avoided.</para>

    <para>This program demonstrates this problem. The solution is to replace
    instances of built in integer types with corresponding safe types.</para>

    <programlisting><xi:include href="../../example/example1.cpp" parse="text"
        xmlns:xi="http://www.w3.org/2001/XInclude"/></programlisting>

    <screen>example 1:undetected erroneous expression evaluation
Not using safe numerics
error NOT detected!
-127 != 127 + 2
Using safe numerics
error detected:converted signed value too large: positive overflow error
Program ended with exit code: 0</screen>

    <title>Arithmetic Operations Can Overflow Silently</title>

    <para>A variation of the above is when a value is incremented/decremented
    beyond its domain.</para>

    <programlisting><xi:include href="../../example/example2.cpp" parse="text"
        xmlns:xi="http://www.w3.org/2001/XInclude"/></programlisting>

    <screen>example 2:undetected overflow in data type
Not using safe numerics
-2147483648 != 2147483647 + 1
error NOT detected!
Using safe numerics
addition result too large
error detected!</screen>

    <para>When variables of unsigned integer type are decremented below zero,
    they "roll over" to the highest possible unsigned version of that integer
    type. This is a common problem which is generally never detected.</para>

    <title>Arithmetic on Unsigned Integers Can Yield Incorrect Results</title>

    <para>Subtracting two unsigned values of the same size will result in an
    unsigned value. If the first operand is less than the second the result
    will be arithmetically in correct. But if the size of the unsigned types
    is less than that of an unsigned int, C/C++ will promote the
    types to signed int before subtracting resulting in an
    correct result. In either case, there is no indication of an error.
    Somehow, the programmer is expected to avoid this behavior. Advice usually
    takes the form of "Don't use unsigned integers for arithmetic". This is
    well and good, but often not practical. C/C++ itself uses unsigned for
    sizeof(T) which is then used by users in arithmetic.</para>

    <para>This program demonstrates this problem. The solution is to replace
    instances of built in integer types with corresponding safe types.</para>

    <programlisting><para><xi:include href="../../example/example8.cpp"
          parse="text" xmlns:xi="http://www.w3.org/2001/XInclude"/></para></programlisting>

    <screen>example 8:undetected erroneous expression evaluation
Not using safe numerics
error NOT detected!
4294967171 != 2 - 127
Using safe numerics
error detected:subtraction result cannot be negative: negative overflow error
Program ended with exit code: 0</screen>

    <title>Implicit Conversions Can Lead to Erroneous Results</title>

    <para>At CPPCon 2016 Jon Kalb gave a very entertaining (and disturbing)
    <ulink url="https://www.youtube.com/watch?v=wvtFGa6XJDU">lightning
    talk</ulink> related to C++ expressions.</para>

    <para>The talk included a very, very simple example similar to the
    following:</para>

    <para><programlisting><xi:include href="../../example/example4.cpp"
          parse="text" xmlns:xi="http://www.w3.org/2001/XInclude"/></programlisting><screen>example 3: implicit conversions change data values
Not using safe numerics
a is -1 b is 1
b is less than a
error NOT detected!
Using safe numerics
a is -1 b is 1
converted negative value to unsigned: domain error
error detected!
</screen></para>

    <para>A normal person reads the above code and has to be dumbfounded by
    this. The code doesn't do what the text - according to the rules of
    algebra - says it does. But C++ doesn't follow the rules of algebra - it
    has its own rules. There is generally no compile time error. You can get a
    compile time warning if you set some specific compile time switches. The
    explanation lies in reviewing how C++ reconciles binary expressions
    (a < b is an expression here) where operands are different
    types. In processing this expression, the compiler:</para>

    <para><itemizedlist>
        <listitem>
          <para>Determines the "best" common type for the two operands. In
          this case, application of the rules in the C++ standard dictate that
          this type will be an unsigned int.</para>
        </listitem>

        <listitem>
          <para>Converts each operand to this common type. The signed value of
          -1 is converted to an unsigned value with the same bit-wise
          contents, 0xFFFFFFFF, on a machine with 32 bit integers. This
          corresponds to a decimal value of 4294967295.</para>
        </listitem>

        <listitem>
          <para>Performs the calculation - in this case it's
          <, the "less than" operation. Since 1 is less than
          4294967295 the program prints "b is less than a".</para>
        </listitem>
      </itemizedlist></para>

    <para>In order for a programmer to detect and understand this error he
    should be pretty familiar with the implicit conversion rules of the C++
    standard. These are available in a copy of the standard and also in the
    canonical reference book <citetitle><link linkend="stroustrup">The C++
    Programming Language</link></citetitle> (both are over 1200 pages long!).
    Even experienced programmers won't spot this issue and know to take
    precautions to avoid it. And this is a relatively easy one to spot. In the
    more general case this will use integers which don't correspond to easily
    recognizable numbers and/or will be buried as a part of some more complex
    expression.</para>

    <para>This example generated a good amount of web traffic along with
    everyone's pet suggestions. See for example <ulink
    url="https://bulldozer00.com/2016/10/16/the-unsigned-conundrum/">a blog
    post with everyone's favorite "solution"</ulink>. All the proposed
    "solutions" have disadvantages and attempts to agree on how handle this
    are ultimately fruitless in spite of, or maybe because of, the <ulink
    url="https://twitter.com/robertramey1/status/795742870045016065">emotional
    content</ulink>. Our solution is by far the simplest: just use the safe
    numerics library as shown in the example above.</para>

    <para>Note that in this particular case, usage of the safe types results
    in no runtime overhead in using the safe integer library. Code generated
    will either equal or exceed the efficiency of using primitive integer
    types.</para>

    <title>Mixing Data Types Can Create Subtle Errors</title>

    <para>C++ contains signed and unsigned integer types. In spite of their
    names, they function differently which often produces surprising results
    for some operands. Program errors from this behavior can be exceedingly
    difficult to find. This has lead to recommendations of various ad hoc
    "rules" to avoid these problems. It's not always easy to apply these
    "rules" to existing code without creating even more bugs. Here is a
    typical example of this problem:</para>

    <para><programlisting><xi:include href="../../example/example10.cpp"
          parse="text" xmlns:xi="http://www.w3.org/2001/XInclude"/></programlisting>Here
    is the output of the above program:<screen>example 4: mixing types produces surprising results
Not using safe numerics
10000
4294957296
error NOT detected!
Using safe numerics
10000
error detected!converted negative value to unsigned: domain error
</screen>This solution is simple, just replace instances of int
    with safe<int>.</para>

    <title>Array Index Value Can Exceed Array Limits</title>

    <para>Using an intrinsic C++ array, it's very easy to exceed array limits.
    This can fail to be detected when it occurs and create bugs which are hard
    to find. There are several ways to address this, but one of the simplest
    would be to use safe_unsigned_range;</para>

    <para><programlisting><xi:include href="../../example/example5.cpp"
          parse="text" xmlns:xi="http://www.w3.org/2001/XInclude"/></programlisting><screen>example 5: array index values can exceed array bounds
Not using safe numerics
error NOT detected!
Using safe numerics
error detected:Value out of range for this safe type: domain error
</screen></para>

    <para>Collections like standard arrays and vectors do array index checking
    in some function calls and not in others so this may not be the best
    example. However it does illustrate the usage of
    safe_range<T> for assigning legal ranges to variables.
    This will guarantee that under no circumstances will the variable contain
    a value outside of the specified range.</para>

    <title>Checking of Input Values Can Be Easily Overlooked</title>

    <para>It's way too easy to overlook the checking of parameters received
    from outside the current program.<programlisting><xi:include
          href="../../example/example6.cpp" parse="text"
          xmlns:xi="http://www.w3.org/2001/XInclude"/></programlisting><screen>example 6: checking of externally produced value can be overlooked
Not using safe numerics
2147483647 0
error NOT detected!
Using safe numerics
error detected:error in file input: domain error
</screen>Without safe integer, one will have to insert new code every time an
    integer variable is retrieved. This is a tedious and error prone
    procedure. Here we have used program input. But in fact this problem can
    occur with any externally produced input.</para>

    <title>Cannot Recover From Arithmetic Errors</title>

    <para>If a divide by zero error occurs in a program, it's detected by
    hardware. The way this manifests itself to the program can and will depend
    upon</para>

    <para><itemizedlist>
        <listitem>
          <para>data type - int, float, etc</para>
        </listitem>

        <listitem>
          <para>setting of compile time command line switches</para>
        </listitem>

        <listitem>
          <para>invocation of some configuration functions which convert these
          hardware events into C++ exceptions</para>
        </listitem>
      </itemizedlist>It's not all that clear how one would detect and recover
    from a divide by zero error in a simple portable way. Usually, users just
    ignore the issue which usually results in immediate program termination
    when this situation occurs.</para>

    <para>This library will detect divide by zero errors before the operation
    is invoked. Any errors of this nature are handled according to the <link
    linkend="safe_numeric.exception_policies">exception_policy</link> selected
    by the library user.</para>

    <para><programlisting><xi:include href="../../example/example13.cpp"
          parse="text" xmlns:xi="http://www.w3.org/2001/XInclude"/></programlisting><screen>example 7: cannot recover from arithmetic errors
Not using safe numerics
error NOT detectable!
Using safe numerics
error detected:divide by zero: domain error
</screen></para>

    <title>Compile Time Arithmetic is Not Always Correct</title>

    <para>If a divide by zero error occurs while a program is being compiled,
    there is not guarantee that it will be detected. This example shows a real
    example compiled with a recent version of CLang.</para>

    <itemizedlist>
      <listitem>
        <para>Source code includes a constant expression containing a simple
        arithmetic error.</para>
      </listitem>

      <listitem>
        <para>The compiler emits a warning but otherwise calculates the wrong
        result.</para>
      </listitem>

      <listitem>
        <para>Replacing int with safe<int> will guarantee that the error
        is detected at runtime</para>
      </listitem>

      <listitem>
        <para>Operations using safe types are marked constexpr. So we can
        force the operations to occur at runtime by marking the results as
        constexpr. This will result in an error at compile time if the
        operations cannot be correctly calculated.</para>
      </listitem>
    </itemizedlist>

    <para><programlisting><xi:include href="../../example/example14.cpp"
          parse="text" xmlns:xi="http://www.w3.org/2001/XInclude"/></programlisting><screen>example 8: cannot detect compile time arithmetic errors
Not using safe numerics
0error NOT detected!
Using safe numerics
error detected:positive overflow error
Program ended with exit code: 0</screen></para>

    <title>Programming by Contract is Too Slow</title>

    <para>Programming by Contract is a highly regarded technique. There has
    been much written about it and it has been proposed as an addition to the
    C++ language <citation><xref linkend="garcia"/></citation><citation><xref
    linkend="crowl2"/></citation> It (mostly) depends upon runtime checking of
    parameter and object values upon entry to and exit from every function.
    This can slow the program down considerably which in turn undermines the
    main motivation for using C++ in the first place! One popular scheme for
    addressing this issue is to enable parameter checking only during
    debugging and testing which defeats the guarantee of correctness which we
    are seeking here! Programming by Contract will never be accepted by
    programmers as long as it is associated with significant additional
    runtime cost.</para>

    <para>The Safe Numerics Library has facilities which, in many cases, can
    check guaranteed parameter requirements with little or no runtime
    overhead. Consider the following example:</para>

    <para><programlisting><xi:include href="../../example/example7.cpp"
          parse="text" xmlns:xi="http://www.w3.org/2001/XInclude"/></programlisting><screen>example 7:
enforce contracts with zero runtime cost
parameter error detected</screen></para>

    <para>In the example above, the function convert incurs
    significant runtime cost every time the function is called. By using
    "safe" types, this cost is moved to the moment when the parameters are
    constructed. Depending on how the program is constructed, this may totally
    eliminate extraneous computations for parameter requirement type checking.
    In this scenario, there is no reason to suppress the checking for release
    mode and our program can be guaranteed to be always arithmetically
    correct.</para>


text:
package com.elixlogic.tifoon.domain.model.object;

import lombok.NonNull;
import org.apache.commons.lang3.reflect.FieldUtils;

import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class ReflectionObjectTreeAware implements ObjectTreeAware {
    @Override
    @Nullable
    public final List<ObjectTreeAware> traceObjectPath(@NonNull final Object _objectToFind) {
        for (final Field field : FieldUtils.getAllFieldsList(getClass())) {
            try {
                final List<ObjectTreeAware> result = findValue(FieldUtils.readField(this, field.getName(), true), _objectToFind);

                if (result != null) {
                    return result;
                }
           } catch (IllegalAccessException _e) {
                // safe to ignore
            }
        }

        return null;
    }

    @Nullable
    private List<ObjectTreeAware> findValue(@NonNull final Object _value, @NonNull final Object _objectToFind) {
        List<ObjectTreeAware> result = null;

        if (_value == _objectToFind) {
            result = new ArrayList<>();
            result.add(this);
        } else if (_value instanceof ObjectTreeAware) {
            // recurse
            result = ((ObjectTreeAware) _value).traceObjectPath(_objectToFind);

            if (result != null) {
                result.add(this);
            }
        } else if (_value instanceof Collection) {
            // iterate collection
            for (final Object objectFromCollection : (Collection) _value) {
                result = findValue(objectFromCollection, _objectToFind);

                if (result != null) {
                    break;
                }
            }
        } else if (_value instanceof Map) {
            // iterate values in map
            for (final Object objectFromCollection : ((Map) _value).values()) {
                result = findValue(objectFromCollection, _objectToFind);

                if (result != null) {
                    break;
                }
            }
        }

        return result;
    }
}


text:
<?php

namespace Doctrine\ORM\Persisters;

use Doctrine\ORM\PersistentCollection,
    Doctrine\ORM\UnitOfWork;

/**
 * Persister for one-to-many collections.
 *
 * IMPORTANT:
 * This persister is only used for uni-directional one-to-many mappings on a foreign key
 * (which are not yet supported). So currently this persister is not used.
 *
 * @since 2.0
 * @author Roman Borschel <roman@code-factory.org>
 * @todo Remove
 */
class OneToManyPersister extends AbstractCollectionPersister
{
    /**
     * Generates the SQL UPDATE that updates a particular row's foreign
     * key to null.
     *
     * @param PersistentCollection $coll
     * @return string
     * @override
     */
    protected function _getDeleteRowSQL(PersistentCollection $coll)
    {
        $mapping = $coll->getMapping();
        $targetClass = $this->_em->getClassMetadata($mapping->getTargetEntityName());
        $table = $targetClass->getTableName();

        $ownerMapping = $targetClass->getAssociationMapping($mapping['mappedBy']);

        $setClause = '';
        foreach ($ownerMapping->sourceToTargetKeyColumns as $sourceCol => $targetCol) {
            if ($setClause != '') $setClause .= ', ';
            $setClause .= "$sourceCol = NULL";
        }

        $whereClause = '';
        foreach ($targetClass->getIdentifierColumnNames() as $idColumn) {
            if ($whereClause != '') $whereClause .= ' AND ';
            $whereClause .= "$idColumn = ?";
        }

        return array("UPDATE $table SET $setClause WHERE $whereClause", $this->_uow->getEntityIdentifier($element));
    }

    protected function _getInsertRowSQL(PersistentCollection $coll)
    {
        return "UPDATE xxx SET foreign_key = yyy WHERE foreign_key = zzz";
    }

    /* Not used for OneToManyPersister */
    protected function _getUpdateRowSQL(PersistentCollection $coll)
    {
        return;
    }

    /**
     * Generates the SQL UPDATE that updates all the foreign keys to null.
     *
     * @param PersistentCollection $coll
     */
    protected function _getDeleteSQL(PersistentCollection $coll)
    {

    }

    /**
     * Gets the SQL parameters for the corresponding SQL statement to delete
     * the given collection.
     *
     * @param PersistentCollection $coll
     */
    protected function _getDeleteSQLParameters(PersistentCollection $coll)
    {}

    /**
     * Gets the SQL parameters for the corresponding SQL statement to insert the given
     * element of the given collection into the database.
     *
     * @param PersistentCollection $coll
     * @param mixed $element
     */
    protected function _getInsertRowSQLParameters(PersistentCollection $coll, $element)
    {}

    /**
     * Gets the SQL parameters for the corresponding SQL statement to delete the given
     * element from the given collection.
     *
     * @param PersistentCollection $coll
     * @param mixed $element
     */
    protected function _getDeleteRowSQLParameters(PersistentCollection $coll, $element)
    {}

    /**
     * {@inheritdoc}
     */
    public function count(PersistentCollection $coll)
    {
        $mapping = $coll->getMapping();
        $class = $this->_em->getClassMetadata($mapping['targetEntity']);
        $params = array();
        $id = $this->_em->getUnitOfWork()->getEntityIdentifier($coll->getOwner());

        $where = '';
        foreach ($class->associationMappings[$mapping['mappedBy']]['joinColumns'] AS $joinColumn) {
            if ($where != '') {
                $where .= ' AND ';
            }
            $where .= $joinColumn['name'] . " = ?";
            if ($class->containsForeignIdentifier) {
                $params[] = $id[$class->getFieldForColumn($joinColumn['referencedColumnName'])];
            } else {
                $params[] = $id[$class->fieldNames[$joinColumn['referencedColumnName']]];
            }
        }

        $sql = "SELECT count(*) FROM " . $class->getQuotedTableName($this->_conn->getDatabasePlatform()) . " WHERE " . $where;
        return $this->_conn->fetchColumn($sql, $params);
    }

    /**
     * @param PersistentCollection $coll
     * @param int $offset
     * @param int $length
     * @return \Doctrine\Common\Collections\ArrayCollection
     */
    public function slice(PersistentCollection $coll, $offset, $length = null)
    {
        $mapping = $coll->getMapping();
        return $this->_em->getUnitOfWork()
                  ->getEntityPersister($mapping['targetEntity'])
                  ->getOneToManyCollection($mapping, $coll->getOwner(), $offset, $length);
    }

    /**
     * @param PersistentCollection $coll
     * @param object $element
     */
    public function contains(PersistentCollection $coll, $element)
    {
        $mapping = $coll->getMapping();
        $uow = $this->_em->getUnitOfWork();

        // shortcut for new entities
        if ($uow->getEntityState($element, UnitOfWork::STATE_NEW) == UnitOfWork::STATE_NEW) {
            return false;
        }

        // only works with single id identifier entities. Will throw an exception in Entity Persisters
        // if that is not the case for the 'mappedBy' field.
        $id = current( $uow->getEntityIdentifier($coll->getOwner()) );

        return $uow->getEntityPersister($mapping['targetEntity'])
                   ->exists($element, array($mapping['mappedBy'] => $id));
    }
}


text:
<?php

declare(strict_types=1);

namespace PH7;

defined('PH7') or exit('Restricted access');

use PH7\Framework\Cache\Cache;
use PH7\Framework\Config\Config;
use PH7\Framework\Core\Kernel;
use PH7\Framework\File as F;
use PH7\Framework\File\Permission\Chmod;
use PH7\Framework\Layout\Gzip\Gzip;
use PH7\Framework\Layout\Tpl\Engine\PH7Tpl\PH7Tpl;
use PH7\Framework\Mvc\Model\DbConfig;
use PH7\Framework\Mvc\Request\Http;
use PH7\Framework\Security\Version;

@set_time_limit(0);
@ini_set('max_execution_time', '0'); // Infinite time of execution
@ini_set('memory_limit', '528M');

class UpgradeCore
{
    /**
     * Remote update URL.
     */
    private const REMOTE_URL = 'https://update.ph7builder.com/';
    private const ARCHIVE_EXT = '.zip';
    private const MIN_SQL_FILE_SIZE = 12; // Size in bytes

    /**
     * Internal update folders.
     *
     * @internal For better compatibility with Windows, we didn't put a slash at the end of the directory constants.
     */
    private const DIR = 'upgrade';
    private const FILE_DIR = 'file';
    private const DATA_DIR = 'data';
    private const SQL_DIR = 'sql';
    private const INFO_DIR = 'info';

    private const INST_INTRO_FILE = 'introduction';
    private const INST_CONCL_FILE = 'conclusion';
    private const UPGRADE_FILE = 'upgrade.sql';
    private const VERSION_LIST_FILE = 'all_versions.txt';
    private const VERSION_FILE = 'Version.class.php';

    // Use UNIX wildcard to be able to select only the sub-directories present in "public/"
    private const PUBLIC_DIR = 'public/*';
    // Use UNIX wildcard to be able to select only the sub-directories present in "protected/"
    private const PROTECTED_DIR = 'protected/*';

    private Http $oHttpRequest;

    private F\File $oFile;

    private Config $oConfig;

    private string $sHtml;

    private string $sUpgradesDirUpgradeFolder;

    private string $sVerName;

    private string $sVerNumber;

    private string $sVerBuild;

    private bool $bAutoRemoveUpgradeDir = false;

    private bool $bUpgradePatchAvailable = false;

    private array $aErrors = [];

    public function __construct()
    {
        $this->oHttpRequest = new Http;
        $this->oFile = new F\File;
        $this->oConfig = Config::getInstance();

        $this->sHtml = ''; // Default HTML contents
        $this->sVerNumber = '...'; // Default value of the version number upgrade

        $this->prepare(); // Preparation and verification for software upgrade
    }

    /**
     * Output the HTML layout of the upgrade wizard.
     */
    public function display(): void
    {
        echo '<!DOCTYPE html><meta charset="utf-8"><title>', t('Upgrade %software_name% | Version %0%', $this->sVerNumber), '</title><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta name="robots" content="noindex">
';
        echo $this->sHtml;
        echo '
' . t('Psst! Do not forget to read the documentation page before proceeding with the update.', Version::UPGRADE_DOC_URL) . '
';
        echo '
';
    }

    /**
     * @return array Returns all version numbers.
     */
    public function getVersions(): array
    {
        return (array)file(static::REMOTE_URL . static::VERSION_LIST_FILE);
    }

    /**
     * Checks and returns the correct needed version for the current pH7Builder installation.
     * It will look at the next release version after the one currently installed.
     *
     * @return string The needed version number for the current pH7Builder installation.
     */
    public function getNextVersion(): string
    {
        $aVersions = $this->getVersions();

        if ($iKey = array_search(Kernel::SOFTWARE_VERSION, $aVersions, true)) {
            return (string)$aVersions[$iKey + 1];
        }

        // If no next version is found, just returns the current one
        return Kernel::SOFTWARE_VERSION;
    }

    private function prepare(): void
    {
        // Checking if the administrator is logged in
        if (AdminCore::auth()) {
            // Download the next upgrade patch to "~/_repository/" folder
            $sNextVersion = $this->getNextVersion();

            if (!$this->download($sNextVersion)) {
                $this->aErrors[] = t("Couldn't properly download the patch zip archive. Please try again later on.");
            }
        } else {
            $this->aErrors[] = t('You must be logged in as administrator to upgrade your site.');
        }

        if (!$this->hasErrors()) {
            $aAvailableUpgrades = $this->getAvailableUpgrades();
            if (empty($aAvailableUpgrades)) {
                $this->sHtml .= '
' . t('No upgrade patches available for %software_name%.') . '
';
            } else {
                $this->sHtml .= '
' . t('Upgrade available for %software_name%:') . '
';
                $this->sHtml .= '<form method="post">';

                rsort($aAvailableUpgrades, SORT_NUMERIC);
                foreach ($aAvailableUpgrades as $sFolder) {
                    $this->sUpgradesDirUpgradeFolder = $this->oFile->checkExtDir($sFolder);

                    $this->readConfig();

                    $sVerName = (string)$this->oConfig->values['upgrade.version']['name'];
                    $sVerNumber = (string)$this->oConfig->values['upgrade.version']['number'];
                    $sVerBuild = (string)$this->oConfig->values['upgrade.version']['build'];
                    $sDesc = $this->oConfig->values['upgrade.information']['description'];

                    if ($this->isValidUpgradeFolder($this->sUpgradesDirUpgradeFolder)) {
                        $bIsValidVer = $this->isValidVersion($sVerName, $sVerNumber, $sVerBuild);
                        if ($bIsValidVer) {
                            $this->bUpgradePatchAvailable = true;

                            $this->sHtml .= '
' . t('Version Name: %0%, Version Number: %1%, Version Build: %2%', $sVerName, $sVerNumber, $sVerBuild) . '
';

                            $sMsg = t('Upgrade %software_version_name% %software_version% Build %software_build% to version %0%', '' . $sVerName . ' ' . $sVerNumber . ' Build ' . $sVerBuild . '');
                            $this->sHtml .= '<button type="submit" class="success" name="submit_upgrade" value="' . $this->sUpgradesDirUpgradeFolder . '" onclick="return confirm(\'' . t('Have you made a backup of your website files, folders and database?') . '\');">' . $sMsg . '</button>';

                            $this->sHtml .= '
' . t('Description of the upgrade patch:') . '
';
                            $this->sHtml .= $sDesc;

                            $this->sHtml .= '
' . t('Instruction:') . '
';
                            $this->sHtml .= $this->readInstruction(static::INST_INTRO_FILE);

                            $this->sHtml .= '

';
                        }
                    } else {
                        $sMsg = t('Upgrade patch is not valid!');
                        $this->sHtml .= '<button type="submit" class="error" disabled="disabled">' . $sMsg . '</button>';
                    }
                }

                $this->sHtml .= '</form>';

                if (!$this->bUpgradePatchAvailable) {
                    $this->sHtml .= '
' . t('No upgrade patches available for your current version: %software_version%, build %software_build%') . '
';
                }

                if ($this->isUpgradeRequested() && $this->isValidUpgradeFolder($this->oHttpRequest->post('submit_upgrade'))) {
                    $this->sUpgradesDirUpgradeFolder = $this->oHttpRequest->post('submit_upgrade');

                    $this->readConfig();

                    $this->sVerName = (string)$this->oConfig->values['upgrade.version']['name']; // Version name upgrade
                    $this->sVerNumber = (string)$this->oConfig->values['upgrade.version']['number']; // Version number upgrade
                    $this->sVerBuild = (string)$this->oConfig->values['upgrade.version']['build']; // Version build upgrade

                    DbConfig::setSiteMode(DbConfig::MAINTENANCE_SITE);
                    $this->oConfig->setDevelopmentMode();
                    usleep(100000);

                    $this->check();

                    if (!$this->hasErrors()) {
                        $this->run(); // Run the upgrade patch!

                        if (!$this->hasErrors()) {
                            /**
                             * It resets the HTML variable ($this->sHtml) to not display versions upgrade available.
                             * The user can refresh the page to réaficher the upgrade available.
                             */
                            $this->sHtml = '
' . t('Your update ran successfully!') . '
';

                            if ($this->bAutoRemoveUpgradeDir) {
                                if ($this->removeUpgradeDir()) {
                                    $this->sHtml .= '
' . t('The upgrade directory (~%0%) has been deleted!', PH7_PATH_REPOSITORY . static::DIR . PH7_DS . $this->sUpgradesDirUpgradeFolder) . '
';
                                    $this->sHtml .= '
' . t('Status... OK!') . '
';
                                } else {
                                    $this->sHtml .= '
' . t('The upgrade directory (~%0%) could not be deleted, please delete it manually using an FTP client or SSH.', PH7_PATH_REPOSITORY . static::DIR . PH7_DS . $this->sUpgradesDirUpgradeFolder) . '
';
                                    $this->sHtml .= '
' . t('Status... Failure!') . '
';
                                }
                            } else {
                                $this->sHtml .= '
' . t('Please delete the upgrade folder using an FTP client or SSH.') . '
';
                            }

                            $this->sHtml .= '
' . t('Conclusion Message:') . '
';
                            $this->sHtml .= $this->readInstruction(static::INST_CONCL_FILE);
                        } else {
                            $this->addErrorMessagesToLayout();
                        }
                    } else {
                        $this->addErrorMessagesToLayout();
                    }

                    $this->oConfig->setProductionMode();
                    DbConfig::setSiteMode(DbConfig::ENABLED_SITE);
                    usleep(100000);
                }
            }
        } else {
            $this->addErrorMessagesToLayout();
        }
    }

    private function run(): void
    {
        $this->file();
        $this->sql();
        $this->setNewVersionToKernel();
        $this->clearAllCacheFolders();
    }

    private function file(): void
    {
        $this->copyPublicPathToRoot();
        $this->copyProtectedPathToRoot();
    }

    private function copyPublicPathToRoot(): void
    {
        $sPathPublicDir = PH7_PATH_REPOSITORY . static::DIR . PH7_DS . $this->sUpgradesDirUpgradeFolder . static::DATA_DIR . PH7_DS . static::FILE_DIR . PH7_DS . static::PUBLIC_DIR;

        if (is_dir($this->oFile->removeWildcards($sPathPublicDir))) {
            $this->oFile->systemCopy($sPathPublicDir, PH7_PATH_ROOT);
            $this->oFile->chmod(PH7_PATH_ROOT, Chmod::MODE_ALL_EXEC);
        }
    }

    private function copyProtectedPathToRoot(): void
    {
        $sPathProtectedDir = PH7_PATH_REPOSITORY . static::DIR . PH7_DS . $this->sUpgradesDirUpgradeFolder . static::DATA_DIR . PH7_DS . static::FILE_DIR . PH7_DS . static::PROTECTED_DIR;

        if (is_dir($this->oFile->removeWildcards($sPathProtectedDir))) {
            $this->oFile->systemCopy($sPathProtectedDir, PH7_PATH_PROTECTED);
            $this->oFile->chmod(PH7_PATH_PROTECTED, Chmod::MODE_ALL_EXEC);
        }
    }

    private function sql(): void
    {
        $sFullPath = PH7_PATH_REPOSITORY . static::DIR . PH7_DS . $this->sUpgradesDirUpgradeFolder . static::DATA_DIR . PH7_DS . static::SQL_DIR . PH7_DS . $this->oConfig->values['database']['type_name'] . PH7_DS . static::UPGRADE_FILE;

        if (is_file($sFullPath) && filesize($sFullPath) > static::MIN_SQL_FILE_SIZE) {
            $mQuery = (new UpgradeCoreModel)->run($sFullPath);

            if ($mQuery !== true) {
                $this->aErrors[] = t('Unable to execute the upgrade of the database SQL.
Error Message: %0%', '
' . print_r($mQuery) . '
');
            }
        }
    }

    private function check(): void
    {
        if (!AdminCore::auth()) {
            // Recheck if the administrator is still logged in
            $this->aErrors[] = t('You must be logged in as administrator to upgrade your site.');
        }

        if (DbConfig::getSetting('siteStatus') !== DbConfig::MAINTENANCE_SITE) {
            $this->aErrors[] = t('Your site must be in maintenance mode to begin the upgrade.');
        }

        if (!isDebug()) {
            $this->aErrors[] = t('You must put your site in development mode in order to launch the upgrade of your site!') . '
' .
                t('1) Please change the permission of the ~%0% file for writing for all groups (0666 in octal).', PH7_PATH_APP_CONFIG . PH7_CONFIG_FILE) . '
' .
                t('2) Edit ~%0% file and find the code:', PH7_PATH_APP_CONFIG . PH7_CONFIG_FILE) . '
' .
                '"environment = production ; production or development"
' .
                t('and replace it with the code:') . '
' .
                '"environment = development ; production or development"
' .
                t('3) After installation, please edit ~%0% file and find the code:', PH7_PATH_APP_CONFIG . PH7_CONFIG_FILE) . '
' .
                '"environment = development ; production or development"
' .
                t('and replace it with the code:') . '
' .
                '"environment = production ; production or development"
' .
                t('4) Change the permission of the file to write only for users and reading for the other groups (0644 in octal).');
        }
    }

    /**
     * Download the new version patches from pH7Builder remote server to the client server.
     * Then, extract the file to "_repository/upgrade/" directory to set it as available for the next update.
     * Then, remove zip archive file, as we don't need it anymore.
     */
    private function download(string $sNewVersion): bool
    {
        $sZipFileName = $sNewVersion . self::ARCHIVE_EXT;
        $sDestinationPath = PH7_PATH_REPOSITORY . static::DIR . PH7_DS;

        $rFile = $this->oFile->getUrlContents(self::REMOTE_URL . $sZipFileName);
        $this->oFile->putFile(PH7_PATH_REPOSITORY . PH7_TMP . $sZipFileName, $rFile);

        // TODO Need to retrieve the valid checksum of each release from the remote server, where it gives these details
        $sRemoveChecksumPatch = md5_file(PH7_PATH_REPOSITORY . PH7_TMP . $sZipFileName);

        if (!$this->isPatchChecksumMatch(PH7_PATH_REPOSITORY . PH7_TMP . $sZipFileName, $sRemoveChecksumPatch)) {
            $bStatus = false;
        } else {
            // Extract zip archive
            $bStatus = $this->oFile->zipExtract(PH7_PATH_REPOSITORY . PH7_TMP . $sZipFileName, $sDestinationPath);
        }

        // Delete zip archive
        $this->oFile->deleteFile(PH7_PATH_REPOSITORY . PH7_TMP . $sZipFileName);

        return $bStatus;
    }

    /**
     * Check if error is found.
     */
    private function hasErrors(): bool
    {
        return !empty($this->aErrors);
    }

    /**
     * Assign the error messages to the current HTML code.
     */
    private function addErrorMessagesToLayout(): void
    {
        $iErrors = count($this->aErrors);

        $this->sHtml .= '
' . t('You have %0% error(s):', $iErrors) . '
';

        for ($iKey = 0; $iKey < $iErrors; $iKey++) {
            $this->sHtml .= '
' . t('%0%) %1%', $iKey + 1, $this->aErrors[$iKey]) . '
';
        }
    }

    /**
     * Checks if the file upgrade is valid.
     *
     * @param string $sFolder The folder.
     *
     * @return bool Returns TRUE if it is correct, FALSE otherwise.
     */
    private function isValidUpgradeFolder(string $sFolder): bool
    {
        $sFullPath = PH7_PATH_REPOSITORY . static::DIR . PH7_DS . $sFolder;

        return !preg_match('#^' . Version::VERSION_PATTERN . '\-' . Version::VERSION_PATTERN . '#', $sFolder) || !is_file($sFullPath . static::INFO_DIR . PH7_DS . PH7_CONFIG_FILE) ? false : true;
    }

    /**
     * Read the upgrade folders.
     *
     * @return array Returns the upgrade folders.
     */
    private function readUpgrades(): array
    {
        return (array)$this->oFile->readDirs(PH7_PATH_REPOSITORY . static::DIR . PH7_DS);
    }

    /**
     * Remove the upgrade folder.
     *
     * @return bool Returns TRUE If the folder has been deleted, FALSE otherwise.
     */
    private function removeUpgradeDir(): bool
    {
        return $this->oFile->deleteDir(PH7_PATH_REPOSITORY . static::DIR . PH7_DS . $this->sUpgradesDirUpgradeFolder);
    }

    private function getAvailableUpgrades(): array
    {
        $aFolders = [];

        foreach ($this->readUpgrades() as $sFolder) {
            $aFolders[$sFolder] = $sFolder;
        }

        return $aFolders;
    }

    /**
     * Set new version to the Version, kernel constants.
     */
    private function setNewVersionToKernel(): void
    {
        $sVersionPathFile = PH7_PATH_FRAMEWORK . 'Security/' . self::VERSION_FILE;
        $sContents = $this->oFile->getFile($sVersionPathFile);

        if ($this->sVerName != Version::KERNEL_VERSION_NAME) {
            $sContents = str_replace('KERNEL_VERSION_NAME = \'' . Version::KERNEL_VERSION_NAME . '\'', 'KERNEL_VERSION_NAME = \'' . $this->sVerName . '\'', $sContents);
        }

        if ($this->sVerNumber != Version::KERNEL_VERSION) {
            $sContents = str_replace('KERNEL_VERSION = \'' . Version::KERNEL_VERSION . '\'', 'KERNEL_VERSION = \'' . $this->sVerNumber . '\'', $sContents);
        }

        if ($this->sVerBuild !== Version::KERNEL_BUILD) {
            $sContents = str_replace('KERNEL_BUILD = \'' . Version::KERNEL_BUILD . '\'', 'KERNEL_BUILD = \'' . $this->sVerBuild . '\'', $sContents);
        }

        $this->oFile->putFile($sVersionPathFile, $sContents);
    }

    /**
     * Check if the version name, number and build they are correct.
     *
     * @param string $sName Name of the version. e.g., pOH
     * @param string $sNumber Number of the version. e.g., 2.1.4
     * @param string $sBuild Number of the version build. e.g., 1
     *
     * @return bool Returns TRUE if the version name is correct, FALSE otherwise.
     */
    private function isValidVersion(string $sName, string $sNumber, string $sBuild): bool
    {
        if (!is_string($sName) || !preg_match('#^' . Version::VERSION_PATTERN . '$#', $sNumber)) {
            return false;
        }

        if (version_compare($sNumber, Kernel::SOFTWARE_VERSION, '<')) {
            return false;
        }

        if (version_compare($sNumber, Kernel::SOFTWARE_VERSION, '==')) {
            return version_compare($sBuild, Kernel::SOFTWARE_BUILD, '>');
        }

        if (version_compare($sNumber, Kernel::SOFTWARE_VERSION, '>')) {
            return true;
        }

        return false;
    }

    /**
     * Get the version upgrade in the config.ini file.
     */
    private function readConfig(): bool
    {
        return $this->oConfig->load(PH7_PATH_REPOSITORY . static::DIR . PH7_DS . $this->sUpgradesDirUpgradeFolder . static::INFO_DIR . PH7_DS . PH7_CONFIG_FILE);
    }

    /**
     * Get the instructions.
     *
     * @param string $sInstFile Instruction file.
     *
     * @return string|bool Returns "false" if the file does not exist or if it fails, otherwise returns the "file contents"
     */
    private function readInstruction(string $sInstFile)
    {
        try {
            return F\Import::file(
                PH7_PATH_REPOSITORY . static::DIR . PH7_DS . $this->sUpgradesDirUpgradeFolder . static::INFO_DIR . PH7_DS . $sInstFile
            );
        } catch (F\IOException $oExcept) {
            return '
' . t('Instruction file not found!') . '
';
        }
    }

    /**
     * Clear all cache folders.
     *
     * Quite often, the changes from newer versions can break the website if older data are still saved in cache.
     */
    private function clearAllCacheFolders(): void
    {
        $aCacheFolders = [
            PH7_PATH_CACHE . Cache::CACHE_DIR,
            PH7_PATH_CACHE . PH7Tpl::COMPILE_DIR,
            PH7_PATH_CACHE . PH7Tpl::CACHE_DIR,
            PH7_PATH_CACHE . Gzip::CACHE_DIR
        ];

        foreach ($aCacheFolders as $sFolder) {
            $this->oFile->deleteDir($sFolder);
        }
    }

    private function isUpgradeRequested(): bool
    {
        return $this->oHttpRequest->postExists('submit_upgrade');
    }

    /**
     * Checks the checksum of the downloaded zip archive to be sure of its integrity and authenticity before proceeding to the upgrade with the patch file.
     */
    private function isPatchChecksumMatch(string $sZipFilePath, string $sValidChecksum): bool
    {
        return md5_file($sZipFilePath) === $sValidChecksum;
    }
}

(new UpgradeCore)->display();


text:
Работа с видепамятью.

Вывод заданного файла как есть в видеопамять текстового режиме 0B800H, и вывод в видеопамять в графическом режиме: эффект полосок на телевизоре.

В DOSBox работает некорректно.


text:
"""A module containing optimization routines."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# pylint: disable=wildcard-import
from tensorflow.contrib.opt.python.training.adamax import *
from tensorflow.contrib.opt.python.training.addsign import *
from tensorflow.contrib.opt.python.training.agn_optimizer import *
from tensorflow.contrib.opt.python.training.drop_stale_gradient_optimizer import *
from tensorflow.contrib.opt.python.training.elastic_average_optimizer import *
from tensorflow.contrib.opt.python.training.external_optimizer import *
from tensorflow.contrib.opt.python.training.lars_optimizer import *
from tensorflow.contrib.opt.python.training.ggt import *
from tensorflow.contrib.opt.python.training.lazy_adam_optimizer import *
from tensorflow.contrib.opt.python.training.model_average_optimizer import *
from tensorflow.contrib.opt.python.training.moving_average_optimizer import *
from tensorflow.contrib.opt.python.training.multitask_optimizer_wrapper import *
from tensorflow.contrib.opt.python.training.nadam_optimizer import *
from tensorflow.contrib.opt.python.training.reg_adagrad_optimizer import *
from tensorflow.contrib.opt.python.training.shampoo import *
from tensorflow.contrib.opt.python.training.weight_decay_optimizers import *
from tensorflow.contrib.opt.python.training.powersign import *
from tensorflow.contrib.opt.python.training.variable_clipping_optimizer import *
# pylint: enable=wildcard-import

from tensorflow.python.util.all_util import remove_undocumented

_allowed_symbols = [
    'AdaMaxOptimizer',
    'PowerSignOptimizer',
    'AddSignOptimizer',
    'DelayCompensatedGradientDescentOptimizer',
    'DropStaleGradientOptimizer',
    'ExternalOptimizerInterface',
    'LARSOptimizer',
    'LazyAdamOptimizer',
    'NadamOptimizer',
    'MovingAverageOptimizer',
    'MomentumWOptimizer',
    'AdamWOptimizer',
    'DecoupledWeightDecayExtension',
    'extend_with_decoupled_weight_decay',
    'ScipyOptimizerInterface',
    'VariableClippingOptimizer',
    'MultitaskOptimizerWrapper',
    'clip_gradients_by_global_norm',
    'AGNOptimizer',
    'AGNCustomGetter',
    'ElasticAverageOptimizer',
    'ElasticAverageCustomGetter',
    'ModelAverageOptimizer',
    'ModelAverageCustomGetter',
    'GGTOptimizer',
    'ShampooOptimizer',
    'RegAdagradOptimizer',
]

remove_undocumented(__name__, _allowed_symbols)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>The Messaging API Sign In</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">

    <link href="/public/styles/ie10-viewport-bug-workaround.css" rel="stylesheet">

    <link href="/public/styles/signin.css" rel="stylesheet">

      <form id="signinForm" class="form-signin" ng-submit="signIn()">

Sign in

        Username
        <input type="text" id="inputUsername"  class="form-control" placeholder="Username" required autofocus ng-model="username">
        Password
        <input type="password" id="inputPassword" class="form-control" placeholder="Password" required ng-model="password">

          Error! Invalid username/password.

        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>

version: {{version}}

      </form>