text:
angular.module('ot.view.buildSearch', [
    'ui.router',
    'ot.service.core',
    'ot.service.form',
    'ot.service.structure'
])
    .config(function ($stateProvider) {
        $stateProvider.state('build-search', {
            url: '/build-search/{projectId}',
            templateUrl: 'app/view/view.buildSearch.tpl.html',
            controller: 'BuildSearchCtrl'
        });
    })
    .controller('BuildSearchCtrl', function ($location, $scope, $stateParams, $state, $http, ot, otStructureService, otFormService, otNotificationService) {
        var view = ot.view();
        // Project's id
        var projectId = $stateParams.projectId;

        // Loading the project
        function loadProject() {
            otStructureService.getProject(projectId).then(function (projectResource) {
                $scope.project = projectResource;
                // View settings
                view.breadcrumbs = ot.projectBreadcrumbs(projectResource);
                view.title = "Build search";
                // View commands
                view.commands = [
                    ot.viewApiCommand(projectResource._buildSearch),
                    ot.viewCloseCommand('/project/' + projectResource.id)
                ];
                return ot.pageCall($http.get(projectResource._buildDiffActions));
            }).then(function (diffActionResources) {
                $scope.buildDiffActions = diffActionResources.resources;
                return ot.pageCall($http.get($scope.project._buildSearch));
            }).then(function (searchForm) {
                $scope.searchForm = searchForm;

                // Extracts the list of properties
                $scope.propertyField = otFormService.getField(searchForm, "property");

                $scope.data = {
                    maximumCount: 10
                };
                try {
                    // Permalink
                    var jsonLink = $location.hash();
                    if (jsonLink) {
                        // Parsing the JSON
                        $scope.data = JSON.parse(jsonLink);
                        // Removes the hash after use
                        $location.hash('');
                        // Launches the search automatically
                        $scope.submitSearch();
                    } else {
                        // Locally saved criteria
                        var json = localStorage.getItem('build_search_' + projectId);
                        if (json) {
                            $scope.data = JSON.parse(json);
                        }
                    }
                } catch (e) {
                    otNotificationService.error("Cannot get the filter from the permalink.");
                }
            });
        }

        // Initialization
        loadProject();

        // Selected builds
        $scope.selectedBuilds = [];
        $scope.selectedBuild = {
            from: '',
            to: ''
        };

        // Search
        $scope.searched = false;
        $scope.searching = false;
        $scope.submitSearch = function () {
            $scope.searching = true;
            ot.pageCall($http.get($scope.searchForm._search, {params: $scope.data})).then(function (result) {
                $scope.buildViews = result.resources;
                // Stores
                localStorage.setItem(
                    'build_search_' + projectId,
                    JSON.stringify($scope.data)
                );
            }).finally(function () {
                $scope.searching = false;
                $scope.searched = true;
            });
        };

        // Toggle advanced search
        $scope.toggleAdvancedSearch = function () {
            $scope.advancedSearch = !$scope.advancedSearch;
        };

        // Displays the permalink
        $scope.displayPermalink = function () {
            var jsonFilter = JSON.stringify($scope.data);
            $location.hash(jsonFilter);
        };

        // Selects a build
        $scope.selectBuild = function (buildView) {
            if ($scope.selectedBuilds.indexOf(buildView) < 0) {
                $scope.selectedBuilds.push(buildView);
                // Auto selection
                if ($scope.selectedBuilds.length == 2) {
                    $scope.selectedBuild.from = $scope.selectedBuilds[0].build.id;
                    $scope.selectedBuild.to = $scope.selectedBuilds[1].build.id;
                }
                // Removes from the list of results
                var pos = $scope.buildViews.indexOf(buildView);
                if (pos >= 0) {
                    $scope.buildViews.splice(pos, 1);
                }
            }
        };

        // Unselects a build
        $scope.unselectBuild = function (buildView) {
            var pos = $scope.selectedBuilds.indexOf(buildView);
            if (pos >= 0) {
                $scope.selectedBuilds.splice(pos, 1);
                if ($scope.selectedBuilds.length == 1) {
                    $scope.selectedBuild.from = '';
                    $scope.selectedBuild.to = '';
                }
            }
        };

        // Change log between two builds
        $scope.buildDiff = function (buildDiffAction) {
            if ($scope.selectedBuild.from && $scope.selectedBuild.from && $scope.selectedBuild.from != $scope.selectedBuild.to) {
                $state.go(buildDiffAction.id, {
                    from: $scope.selectedBuild.from,
                    to: $scope.selectedBuild.to
                });
            }
        };

        // Clearing the search options
        $scope.resetForm = function () {
            $scope.data = {
                maximumCount: 10
            };
            $scope.advancedSearch = false;
        };

    })
;


text:
<?xml version="1.0" ?>
<Simulation verbosity="debug" profile="jobs">
  <TestInfo>
    <name>doc/workshop/optimizer/GeneticAlgorithms/inputs.GA_MaxwoRepConstrained</name>
    <author>Mohammad Abdo (@Jimmy-INL)</author>
    <created>2022-07-21</created>
    <classesTested/>
    <description>Workshop test: GA maximization without replacement Constrained</description>
  </TestInfo>

  <RunInfo>
    <WorkingDir>MaxwoReplacementConstrained</WorkingDir>
    <Sequence>optimize,print</Sequence>
    <batchSize>1</batchSize>
  </RunInfo>

  <Steps>
    <MultiRun name="optimize" re-seeding="2286">
      <Input class="DataObjects" type="PointSet">placeholder</Input>
      <Model class="Models" type="ExternalModel">myLocalSum</Model>
      <Optimizer class="Optimizers" type="GeneticAlgorithm">GAopt</Optimizer>
      <SolutionExport class="DataObjects" type="PointSet">opt_export</SolutionExport>
      <Output class="DataObjects" type="PointSet">optOut</Output>
      <Output class="OutStreams" type="Print">opt_export</Output>
    </MultiRun>
    <IOStep name="print">
      <Input class="DataObjects" type="PointSet">opt_export</Input>
      <Input class="DataObjects" type="PointSet">optOut</Input>
      <Output class="OutStreams" type="Print">opt_export</Output>
      <Output class="OutStreams" type="Print">optOut</Output>
      <Output class="OutStreams" type="Plot">opt_path</Output>
      <Output class="OutStreams" type="Plot">population</Output>
    </IOStep>
  </Steps>

  <Models>
    <ExternalModel ModuleToLoad="../myLocalSum.py" name="myLocalSum" subType="">
      <variables>x1,x2,x3,x4,x5,x6,obj</variables>
    </ExternalModel>
  </Models>

  <Functions>
    <External file="../myConstraints.py" name="expConstr1">
      <variables>x1,x2,x3,x4,x5,x6</variables>
    </External>
    <External file="../myConstraints.py" name="impConstr1">
      <variables>x1,x2,x3,x4,x5,x6,obj</variables>
    </External>
  </Functions>

  <Distributions>
    <UniformDiscrete name='woRep_dist'>
      <lowerBound>2</lowerBound>
      <upperBound>7</upperBound>
      <strategy>withoutReplacement</strategy>
    </UniformDiscrete>
    <UniformDiscrete name='wRep_dist'>
      <lowerBound>2</lowerBound>
      <upperBound>7</upperBound>
      <strategy>withReplacement</strategy>
    </UniformDiscrete>
  </Distributions>

  <Optimizers>
    <GeneticAlgorithm name="GAopt">
      <samplerInit>
        <limit>25</limit>
        <initialSeed>42</initialSeed>
        <writeSteps>every</writeSteps>
        <type>max</type>
      </samplerInit>

      <GAparams>
        <populationSize>20</populationSize>
        <parentSelection>rouletteWheel</parentSelection>
        <reproduction>
          <crossover type="onePointCrossover">
            <crossoverProb>0.8</crossoverProb>
          </crossover>
          <mutation type="swapMutator">
            <mutationProb>0.9</mutationProb>
          </mutation>
        </reproduction>
        <fitness type="invLinear">
          1.0

        </fitness>
        <survivorSelection>fitnessBased</survivorSelection>
      </GAparams>

      <convergence>
        <objective>-1</objective>
      </convergence>

      <variable name="x1">
        <distribution>woRep_dist</distribution>
      </variable>

      <variable name="x2">
        <distribution>woRep_dist</distribution>
      </variable>

      <variable name="x3">
        <distribution>woRep_dist</distribution>
      </variable>

      <variable name="x4">
        <distribution>woRep_dist</distribution>
      </variable>

      <variable name="x5">
        <distribution>woRep_dist</distribution>
      </variable>

      <variable name="x6">
        <distribution>woRep_dist</distribution>
      </variable>

      <objective>obj</objective>
      <TargetEvaluation class="DataObjects" type="PointSet">optOut</TargetEvaluation>
      <Sampler class="Samplers" type="MonteCarlo">MC_samp</Sampler>
      <Constraint class='Functions' type='External'>expConstr1</Constraint>

    </GeneticAlgorithm>
  </Optimizers>

  <Samplers>
    <MonteCarlo name="MC_samp">
      <samplerInit>
        <limit>20</limit>
        <initialSeed>050877</initialSeed>
      </samplerInit>
      <variable name="x1">
        <distribution>woRep_dist</distribution>
      </variable>

      <variable name="x2">
        <distribution>woRep_dist</distribution>
      </variable>

      <variable name="x3">
        <distribution>woRep_dist</distribution>
      </variable>

      <variable name="x4">
        <distribution>woRep_dist</distribution>
      </variable>

      <variable name="x5">
        <distribution>woRep_dist</distribution>
      </variable>

      <variable name="x6">
        <distribution>woRep_dist</distribution>
      </variable>

    </MonteCarlo>
  </Samplers>

  <DataObjects>
    <PointSet name="placeholder"/>
    <PointSet name="optOut">
      <Input>x1,x2,x3,x4,x5,x6</Input>
      <Output>obj</Output>
    </PointSet>
    <PointSet name="opt_export">
      <Input>trajID</Input>
      <Output>x1,x2,x3,x4,x5,x6,obj,age,batchId,fitness,iteration,accepted,conv_objective</Output>
    </PointSet>
  </DataObjects>

  <OutStreams>
    <Print name="optOut">
      <type>csv</type>
      <source>optOut</source>
    </Print>
    <Print name="opt_export">
      <type>csv</type>
      <source>opt_export</source>
      <clusterLabel>trajID</clusterLabel>
    </Print>
    <Plot name="opt_path" subType="OptPath">
      <source>opt_export</source>
      <vars>x1,x2,x3,x4,x5,x6,obj</vars>
    </Plot>
    <Plot name="population" subType="PopulationPlot">
      <source>opt_export</source>
      <vars>x1,x2,x3,x4,x5,x6,obj</vars>
      <logVars>obj</logVars>
      <index>batchId</index>
      <how>png</how>
    </Plot>
  </OutStreams>
</Simulation>

redpajama_set_name: RedPajamaGithub


text:
from webhelpers.html import literal
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
from pylons import tmpl_context as c

# Global string whitelist that we find commonly helpul
string_whitespaces = " \a\b\f\n\r\t\v"
string_whitelist = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-@."
string_whitelist_password = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~!@#$%^&*()_-+=\\|[]{};':\",./<>?"

# Whitelist characters string check
# Returns true if the given string only contains characters
# of the second given string
def string_check_whitelist(source, whitelist):

	valid_string = True

	for source_char in source:
		# Not found - thus it is not in the whitelist
		if whitelist.find(source_char) < 0:
			valid_string = False
			break

	return valid_string

# Given source code, and a language, convert it into HTML that can render out
# directly onto the browser screen. Returns the original source code upon failure
# Note, as degined in the "lib/Challenges.py" source file, we map out languages by the
# following names:
# p, py, python -> Python
# c, c89, c99 -> GCC C
# cp, cpp, c++ -> C++
# j, java -> Java
def code_to_html(SourceCode, SourceLanguage):

	# To lower the source language
	SourceLanguage = SourceLanguage.lower()

	# Convert language directly to python
	if SourceLanguage == "python":

		# Generate the required CSS header
		Formatter = HtmlFormatter(linenos=True, cssclass="source")

		# Generate the formatted code
		FormattedCode = highlight(SourceCode, PythonLexer(), Formatter)

		# Force the block of source code "pre" tag tage the page width
		FormattedCode = FormattedCode.replace('', '')

		# Return a web-friendly string
		return literal(FormattedCode)

	# Unsupported language
	else:
		c.pygments_css_header = ""
		return literal("
") + SourceCode + literal("
")


text:
package com.ntobjectives.hackazon.network;

import android.net.http.AndroidHttpClient;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import retrofit.client.Client;
import retrofit.client.Header;
import retrofit.client.Request;
import retrofit.client.Response;
import retrofit.mime.TypedByteArray;
import retrofit.mime.TypedInput;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA by Nick Chervyakov.
 * User: Nikolay Chervyakov
 * Date: 07.12.2014
 * Time: 15:11
 */
public class AndroidClient implements Client {
    public static final String TAG = AndroidClient.class.getSimpleName();
    protected AndroidHttpClient client;

    public AndroidClient() {

    }

    @Override
    public Response execute(Request req) throws IOException {
        client = AndroidHttpClient.newInstance("Hackazon");
        HttpUriRequest request = convertRequest(req);

        String result;
        try {
            HttpResponse response = client.execute(request);
            int status = response.getStatusLine().getStatusCode();

            if (status != HttpStatus.SC_OK) {
                Log.d(TAG, "FAIL: Bad status from url "
                        + status + ": "
                        + response.getStatusLine().getReasonPhrase());
            }

            HttpEntity entity = response.getEntity();
            TypedInput res;

            if (entity == null) {
                Log.d(TAG, "FAIL: Null entity in response");
                res = new TypedByteArray("application/unknown", new byte[0]);

            } else {
                result = EntityUtils.toString(entity, "UTF-8");
                res = new TypedByteArray(response.getEntity().getContentType().getValue(), result.getBytes());
            }

            return new Response(req.getUrl(), status, response.getStatusLine().getReasonPhrase(), convertHeadersFromApacheToRetrofit(response.getAllHeaders()), res);
        } catch (Exception e) {
          Log.d(TAG, "Exception: " + e);

        } finally {
            client.close();
        }

        throw new IOException("");
    }

    /**
     * Convert header collection from apache one to retrofit one
     * @param apacheHeaders Apache headers
     * @return Converted collection of headers
     */
    protected List<Header> convertHeadersFromApacheToRetrofit(org.apache.http.Header[] apacheHeaders) {
        List<Header> headers = new ArrayList<Header>();

        for (org.apache.http.Header h : apacheHeaders) {
            headers.add(new Header(h.getName(), h.getValue()));
        }

        return headers;
    }

    protected HttpUriRequest convertRequest(Request source) {
        HttpUriRequest result;

        String method = source.getMethod();

        if (method.equals("GET")) {
            result = new HttpGet(source.getUrl());

        } else if (method.equals("POST")) {
            result = new HttpPost(source.getUrl());

        } else if (method.equals("PUT")) {
            result = new HttpPut(source.getUrl());

        } else if (method.equals("DELETE")) {
            result = new HttpDelete(source.getUrl());

        } else if (method.equals("HEAD")) {
            result = new HttpHead(source.getUrl());

        } else if (method.equals("OPTIONS")) {
            result = new HttpOptions(source.getUrl());

        } else if (method.equals("TRACE")) {
            result = new HttpTrace(source.getUrl());

        } else {
            throw new RuntimeException("Invalid HTTP request method: '" + method + "'");
        }

        for (Header h : source.getHeaders()) {
            result.addHeader(new BasicHeader(h.getName(), h.getValue()));
        }

        if (result instanceof HttpPost && source.getBody() != null) {
            HttpEntity entity;

            try {
                ByteArrayOutputStream bodyOut = new ByteArrayOutputStream();
                source.getBody().writeTo(bodyOut);
                entity = new ByteArrayEntity(bodyOut.toByteArray());

            } catch (IOException e) {
                entity = new ByteArrayEntity(new byte[0]);
            }

            //((HttpPost) result).setEntity(entity);
        }

        return result;
    }
}


text:
/**
 *              Textbook Exercise Program
 * Class:       RandomPlus.java
 * Purpose:
 *
 * @author:    Tyler Lucas
 * Student ID: 3305203, Athabasca University
 * Date:       25-Jun-2017
 * Version     1.0
 *
 * Based on and References:
 *
 */

package Chapter07E06;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.Random;

public class RandomPlus extends Random
{
    /**
     * Returns {@link Rectangle} with random dimensions within the input
     * Rectangle. Returned Rectangle has a minimum height and width of 1, and
     * lies on or inside the input Rectangle bounds, including on the border.
     *
     * @param bounds Rectangle of minimum width and height of 1, defining the
     * inclusive maximum bounds of the desired random Rectangle.
     *
     * @return Rectangle with minimum height and width of 1, defined at a
     * random location and of random dimensions within the input Rectangle,
     * while being completely contained within the input Rectangle.
     */
    public Rectangle nextRectWithin(Rectangle bounds)
    {
        int rectW = 1 + nextInt(bounds.width - 1);
        int rectH = 1 + nextInt(bounds.height - 1);
        int rectX = nextInt(bounds.width - rectW);
        int rectY = nextInt(bounds.height - rectH);
        return new Rectangle(rectX, rectY, rectW, rectH);
    }

    /**
     * Returns {@link Rectangle} with random dimensions within the input
     * {@link Dimension}. Returned Rectangle has a minimum height and width of
     * 1, and lies on or inside the input Rectangle bounds, including on the
     * border.
     *
     * @param bounds Dimension of minimum width and height of 1, defining the
     * inclusive maximum bounds of the desired random Rectangle.
     *
     * @return Rectangle at location (0,0) with minimum height and width of 1,
     * maximum equal to input Dimension height and width.
     */
    public Rectangle nextRectWithin(Dimension bounds)
    {
        return nextRectWithin(new Rectangle(0, 0, bounds.width, bounds.height));
    }

    public Point nextPointWithin(Rectangle bounds)
    {
        return new Point(
                bounds.x + nextInt(bounds.width),
                bounds.y + nextInt(bounds.height)
        );
    }

    public Point nextPointWithin(Dimension bounds)
    {
        return nextPointWithin(new Rectangle(0, 0, bounds.width, bounds.height));
    }

    public Color nextColor()
    {
        return Color.getHSBColor(nextFloat(), 1.0f, 1.0f);
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>About NF Drapery</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" href="images/bannerlogo.png" type="image/x-icon"/>

    <link rel="stylesheet" href="css/bootstrap.css" type="text/css">
    <link rel="stylesheet" href="css/jpreloader.css" type="text/css">
    <link rel="stylesheet" href="css/animate.css" type="text/css">
    <link rel="stylesheet" href="css/plugin.css" type="text/css">
    <link rel="stylesheet" href="css/owl.carousel.css" type="text/css">
    <link rel="stylesheet" href="css/owl.theme.css" type="text/css">
    <link rel="stylesheet" href="css/owl.transitions.css" type="text/css">
    <link rel="stylesheet" href="css/style.css" type="text/css">

    <link rel="stylesheet" href="css/bg.css" type="text/css">

    <link rel="stylesheet" href="css/color.css" type="text/css" id="colors">

    <link rel="stylesheet" href="rs-plugin/css/settings.css" type="text/css">
    <link rel="stylesheet" href="css/rev-settings.css" type="text/css">

    <link rel="stylesheet" href="fonts/font-awesome/css/font-awesome.css" type="text/css">
    <link rel="stylesheet" href="fonts/elegant_font/HTML_CSS/style.css" type="text/css">
    <link rel="stylesheet" href="fonts/elegant_font/HTML_CSS/lte-ie7.js" type="text/css">

Working Hours Monday - Friday 08:00-16:00

Toll Free 1800.899.900

Home

Portfolio

Services

About Us

Contact

Store

About Us

Home

/

About Us

Our Story

Quality workmanship and customer service have always been the cornerstone of our philosophy at NFDrapery. From our humble beginnings to the industry wide scale of our business today, our founders, Ilman and Malrae Kim distinguished themselves in the design industry by their industrious work ethic, attention to detail, and creative offerings.

We are a full product and service workroom dedicated to our clients by providing the best window treatment or design solutions. From the initial consultation to the finished product, NFDrapery works closely with designers to create innovative designs and beautiful products.

While our business has grown and expanded over the years, our culture and message remain the same: We will always strive for perfection and become an innovative workroom that our designers could be proud to call their own.

                Talk With Us

                        We are an exclusive workroom for talented designers in metro Atlanta. Our expertise and high quality work make us Atlanta's most premium workroom.

Contact Us

                            <address>
                                6021 Live Oak Pkwy
                                Norcross, GA 30093
                                Phone:(678) 502 7450
                                Email:info@nfdrapery.com
                                Web:http://nfdrapery.com
                            </address>

Visit our online store

                            © Copyright 2017 - NFDrapery || Template by Designesia


text:
package org.lirazs.robolayout.core.view;

import org.lirazs.robolayout.core.util.UIViewLayoutBridgeUtil;
import org.lirazs.robolayout.core.util.UIViewLayoutUtil;
import org.lirazs.robolayout.core.util.UIViewViewGroupUtil;
import org.lirazs.robolayout.core.view.inflater.LayoutInflater;
import org.apache.commons.io.FilenameUtils;
import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.coregraphics.CGSize;
import org.robovm.apple.foundation.*;
import org.robovm.apple.uikit.*;
import org.robovm.objc.Selector;
import org.robovm.objc.annotation.Method;

import java.util.Map;

/**
 * Created on 8/4/2015.
 */
public class LayoutBridge extends ViewGroup implements LayoutViewDelegate, LayoutParamsDelegate {

    private boolean resizeOnKeyboard;
    private boolean scrollToTextField;

    private CGRect lastFrame;

    public LayoutBridge(CGRect frame) {
        super(frame);
    }

    @Override
    public CGSize getSizeThatFits(CGSize cgSize) {
        UIView lastChild = getSubviews().last();

        MarginLayoutParams layoutParams = (MarginLayoutParams) UIViewLayoutUtil.getLayoutParams(lastChild);
        LayoutMeasureSpec widthSpec = new LayoutMeasureSpec(cgSize.getWidth(), LayoutMeasureSpecMode.Unspecified);
        LayoutMeasureSpec heightSpec = new LayoutMeasureSpec(cgSize.getHeight(), LayoutMeasureSpecMode.Unspecified);

        if(layoutParams.getWidth() == LayoutParamsSize.MatchParent.getValue()) {
            widthSpec.setMode(LayoutMeasureSpecMode.Exactly);
        }
        if(layoutParams.getHeight() == LayoutParamsSize.MatchParent.getValue()) {
            heightSpec.setMode(LayoutMeasureSpecMode.Exactly);
        }

        onMeasure(widthSpec, heightSpec);
        return getMeasuredSize();
    }

    public void addSubview(UIView view) {
        for (UIView subView : getSubviews()) {
            subView.removeFromSuperview();
        }
        super.addSubview(view);
    }

    public boolean isResizeOnKeyboard() {
        return resizeOnKeyboard;
    }

    public void setResizeOnKeyboard(boolean resizeOnKeyboard) {
        if(resizeOnKeyboard && !this.resizeOnKeyboard) {
            NSNotificationCenter center = NSNotificationCenter.getDefaultCenter();

            center.addObserver(this, Selector.register("willShowKeyboard:"), UIWindow.KeyboardWillShowNotification(), null);
            center.addObserver(this, Selector.register("didShowKeyboard:"), UIWindow.KeyboardDidShowNotification(), null);
            center.addObserver(this, Selector.register("willHideKeyboard:"), UIWindow.KeyboardWillHideNotification(), null);

        } else if(!resizeOnKeyboard && this.resizeOnKeyboard) {
            NSNotificationCenter center = NSNotificationCenter.getDefaultCenter();

            center.removeObserver(this, UIWindow.KeyboardWillShowNotification(), null);
            center.removeObserver(this, UIWindow.KeyboardDidShowNotification(), null);
            center.removeObserver(this, UIWindow.KeyboardWillHideNotification(), null);
        }
        this.resizeOnKeyboard = resizeOnKeyboard;
    }

    public boolean isScrollToTextField() {
        return scrollToTextField;
    }

    public void setScrollToTextField(boolean scrollToTextField) {
        if(scrollToTextField && !this.scrollToTextField) {
            NSNotificationCenter center = NSNotificationCenter.getDefaultCenter();

            center.addObserver(this, Selector.register("didBeginEditing:"), UITextField.DidBeginEditingNotification(), null);
            center.addObserver(this, Selector.register("didEndEditing:"), UITextField.DidEndEditingNotification(), null);
            center.addObserver(this, Selector.register("didBeginEditing:"), UITextView.DidBeginEditingNotification(), null);
            center.addObserver(this, Selector.register("didEndEditing:"), UITextView.DidEndEditingNotification(), null);

        } else if(!scrollToTextField && this.scrollToTextField) {
            NSNotificationCenter center = NSNotificationCenter.getDefaultCenter();

            center.removeObserver(this, UITextField.DidBeginEditingNotification(), null);
            center.removeObserver(this, UITextField.DidEndEditingNotification(), null);
            center.removeObserver(this, UITextView.DidBeginEditingNotification(), null);
            center.removeObserver(this, UITextView.DidEndEditingNotification(), null);
        }
        this.scrollToTextField = scrollToTextField;
    }

    //TODO: For some reason this method does not exist in RoboVM - so cannot call super!!
    public void setValue(Object value, String key) {
        if(key.equals("layouts")) {
            String stringValue = String.valueOf(value);

            String extension = FilenameUtils.getExtension(stringValue);
            if(extension.isEmpty()) {
                extension = "xml";
            }
            NSBundle bundle = NSBundle.getMainBundle();
            NSURL url = bundle.findResourceURL(stringValue.substring(0, stringValue.indexOf('.')), extension);
            if(url != null) {
                LayoutInflater inflater = new LayoutInflater();
                inflater.inflate(url, this, true);
            }
        } else {
            //[super setValue:value forUndefinedKey:key];
        }
    }

    @Override
    public void onLayout(CGRect frame, boolean changed) {
        UIView firstChild = getSubviews().last();
        if(firstChild != null) {
            CGSize size = UIViewLayoutUtil.getMeasuredSize(firstChild);
            MarginLayoutParams lp = (MarginLayoutParams) UIViewLayoutUtil.getLayoutParams(firstChild);
            UIEdgeInsets margin = lp.getMargin();

            UIViewLayoutUtil.layout(firstChild,
                    new CGRect(margin.getLeft(), margin.getTop(), size.getWidth(), size.getHeight()));
        }
    }

    @Override
    public void onMeasure(LayoutMeasureSpec widthMeasureSpec, LayoutMeasureSpec heightMeasureSpec) {
        /*for (UIView subView : getSubviews()) {
            if(UIViewLayoutUtil.getVisibility(subView) != ViewVisibility.Gone) {
                UIViewViewGroupUtil.measureChild(this, subView, widthMeasureSpec, 0, heightMeasureSpec, 0);
            }
        }*/

        CGSize lastChildSize = CGSize.Zero();
        UIView lastChild = getSubviews().last();

        if(UIViewLayoutUtil.getVisibility(lastChild) != ViewVisibility.Gone) {
            UIViewViewGroupUtil.measureChild(this, lastChild, widthMeasureSpec, 0, heightMeasureSpec, 0);

            lastChildSize = UIViewLayoutUtil.getMeasuredSize(lastChild);
            LayoutParams layoutParams = UIViewLayoutUtil.getLayoutParams(lastChild);

            if(layoutParams instanceof MarginLayoutParams) {
                MarginLayoutParams marginParams = (MarginLayoutParams) layoutParams;
                lastChildSize.setWidth(lastChildSize.getWidth() + marginParams.getMargin().getLeft() + marginParams.getMargin().getRight());
                lastChildSize.setHeight(lastChildSize.getHeight() + marginParams.getMargin().getTop() + marginParams.getMargin().getBottom());
            }
        }

        double widthSize = lastChildSize.getWidth() + getPadding().getLeft() + getPadding().getRight();
        double heightSize = lastChildSize.getHeight() + getPadding().getTop() + getPadding().getBottom();

        LayoutMeasuredDimension width = new LayoutMeasuredDimension(widthSize, LayoutMeasuredState.None);
        LayoutMeasuredDimension height = new LayoutMeasuredDimension(heightSize, LayoutMeasuredState.None);

        setMeasuredDimensionSize(new LayoutMeasuredSize(width, height));
    }

    @Override
    public boolean checkLayoutParams(LayoutParams layoutParams) {
        return layoutParams != null;
    }

    @Override
    public LayoutParams generateDefaultLayoutParams() {
        LayoutBridgeLayoutParams lp = new LayoutBridgeLayoutParams(LayoutParamsSize.MatchParent, LayoutParamsSize.MatchParent);
        lp.setWidth(LayoutParamsSize.MatchParent.getValue());
        lp.setHeight(LayoutParamsSize.MatchParent.getValue());
        return lp;
    }

    @Override
    public LayoutParams generateLayoutParams(LayoutParams params) {
        return new LayoutBridgeLayoutParams(params);
    }

    @Override
    public LayoutParams generateLayoutParams(Map<String, String> attrs) {
        return new LayoutBridgeLayoutParams(attrs);
    }

    @Override
    public boolean isViewGroup() {
        //return false;
        return true;
    }

    @Override
    public void onViewRemoved(UIView view) {

    }

    @Override
    public void layoutSubviews() {
        super.layoutSubviews();

        if(lastFrame == null || !getFrame().equalsTo(lastFrame) || UIViewLayoutUtil.isLayoutRequested(this)) {
            NSDate methodStart = NSDate.now();

            lastFrame = this.getFrame();

            final LayoutMeasureSpec widthMeasureSpec = new LayoutMeasureSpec();
            final LayoutMeasureSpec heightMeasureSpec = new LayoutMeasureSpec();

            widthMeasureSpec.setSize(getFrame().getSize().getWidth());
            heightMeasureSpec.setSize(getFrame().getSize().getHeight());

            widthMeasureSpec.setMode(LayoutMeasureSpecMode.Exactly);
            heightMeasureSpec.setMode(LayoutMeasureSpecMode.Exactly);

            UIViewLayoutUtil.measure(this, widthMeasureSpec, heightMeasureSpec);
            UIViewLayoutUtil.layout(this, getFrame());

            NSDate methodFinish = NSDate.now();
            double timeIntervalSince = methodFinish.getTimeIntervalSince(methodStart);

            Foundation.log(String.format("Relayout took %.2fms", timeIntervalSince * 1000));
        }
    }

    @Method(selector = "willShowKeyboard:")
    public void willShowKeyboard(NSNotification notification) {
        NSValue uiKeyboardFrameEndUserInfoKey = (NSValue) notification.getUserInfo().get(new NSString("UIKeyboardFrameEndUserInfoKey"));
        CGRect keyboardFrame = uiKeyboardFrameEndUserInfoKey.rectValue();
        CGRect kbLocalFrame = convertRectFromView(keyboardFrame, getWindow());

        Foundation.log(String.format("Show: %s", kbLocalFrame.toString()));

        CGRect f = this.getFrame();
        f.getSize().setHeight(kbLocalFrame.getOrigin().getY());
        setFrame(f);

        double duration = notification.getUserInfo().getDouble(new NSString("UIKeyboardAnimationDurationUserInfoKey"));
        UIView.animate(duration, new Runnable() {
            @Override
            public void run() {
                layoutIfNeeded();
            }
        });
    }
    @Method(selector = "didShowKeyboard:")
    public void didShowKeyboard(NSNotification notification) {

    }
    @Method(selector = "willHideKeyboard:")
    public void willHideKeyboard(NSNotification notification) {
        NSValue uiKeyboardFrameEndUserInfoKey = (NSValue) notification.getUserInfo().get(new NSString("UIKeyboardFrameEndUserInfoKey"));
        CGRect keyboardFrame = uiKeyboardFrameEndUserInfoKey.rectValue();
        CGRect kbLocalFrame = convertRectFromView(keyboardFrame, getWindow());

        Foundation.log(String.format("Hide: %s", kbLocalFrame.toString()));

        CGRect f = this.getFrame();
        f.getSize().setHeight(kbLocalFrame.getOrigin().getY());
        setFrame(f);

        double duration = notification.getUserInfo().getDouble(new NSString("UIKeyboardAnimationDurationUserInfoKey"));
        UIView.animate(duration, new Runnable() {
            @Override
            public void run() {
                layoutIfNeeded();
            }
        });
    }

    @Method(selector = "didBeginEditing:")
    public void didBeginEditing(NSNotification notification) {
        UIView.animate(0.3, new Runnable() {
            @Override
            public void run() {
                UIViewLayoutBridgeUtil.findAndScrollToFirstResponder(LayoutBridge.this);
            }
        });
    }

    @Method(selector = "didEndEditing:")
    public void didEndEditing(NSNotification notification) {

    }
}


text:
#include <linux/mm.h>
#include <linux/mmzone.h>
#include <linux/bootmem.h>
#include <linux/bit_spinlock.h>
#include <linux/page_cgroup.h>
#include <linux/hash.h>
#include <linux/slab.h>
#include <linux/memory.h>
#include <linux/vmalloc.h>
#include <linux/cgroup.h>
#include <linux/swapops.h>
#include <linux/kmemleak.h>

static void __meminit init_page_cgroup(struct page_cgroup *pc, unsigned long id)
{
	pc->flags = 0;
	set_page_cgroup_array_id(pc, id);
	pc->mem_cgroup = NULL;
	INIT_LIST_HEAD(&pc->lru);
}
static unsigned long total_usage;

#if !defined(CONFIG_SPARSEMEM)

void __meminit pgdat_page_cgroup_init(struct pglist_data *pgdat)
{
	pgdat->node_page_cgroup = NULL;
}

struct page_cgroup *lookup_page_cgroup(struct page *page)
{
	unsigned long pfn = page_to_pfn(page);
	unsigned long offset;
	struct page_cgroup *base;

	base = NODE_DATA(page_to_nid(page))->node_page_cgroup;
	if (unlikely(!base))
		return NULL;

	offset = pfn - NODE_DATA(page_to_nid(page))->node_start_pfn;
	return base + offset;
}

struct page *lookup_cgroup_page(struct page_cgroup *pc)
{
	unsigned long pfn;
	struct page *page;
	pg_data_t *pgdat;

	pgdat = NODE_DATA(page_cgroup_array_id(pc));
	pfn = pc - pgdat->node_page_cgroup + pgdat->node_start_pfn;
	page = pfn_to_page(pfn);
	VM_BUG_ON(pc != lookup_page_cgroup(page));
	return page;
}

static int __init alloc_node_page_cgroup(int nid)
{
	struct page_cgroup *base, *pc;
	unsigned long table_size;
	unsigned long start_pfn, nr_pages, index;

	start_pfn = NODE_DATA(nid)->node_start_pfn;
	nr_pages = NODE_DATA(nid)->node_spanned_pages;

	if (!nr_pages)
		return 0;

	table_size = sizeof(struct page_cgroup) * nr_pages;

	base = __alloc_bootmem_node_nopanic(NODE_DATA(nid),
			table_size, PAGE_SIZE, __pa(MAX_DMA_ADDRESS));
	if (!base)
		return -ENOMEM;
	for (index = 0; index < nr_pages; index++) {
		pc = base + index;
		init_page_cgroup(pc, nid);
	}
	NODE_DATA(nid)->node_page_cgroup = base;
	total_usage += table_size;
	return 0;
}

void __init page_cgroup_init_flatmem(void)
{

	int nid, fail;

	if (mem_cgroup_disabled())
		return;

	for_each_online_node(nid)  {
		fail = alloc_node_page_cgroup(nid);
		if (fail)
			goto fail;
	}
	printk(KERN_INFO "allocated %ld bytes of page_cgroup\n", total_usage);
	printk(KERN_INFO "please try 'cgroup_disable=memory' option if you"
	" don't want memory cgroups\n");
	return;
fail:
	printk(KERN_CRIT "allocation of page_cgroup failed.\n");
	printk(KERN_CRIT "please try 'cgroup_disable=memory' boot option\n");
	panic("Out of memory");
}

#else /* CONFIG_FLAT_NODE_MEM_MAP */

struct page_cgroup *lookup_page_cgroup(struct page *page)
{
	unsigned long pfn = page_to_pfn(page);
	struct mem_section *section = __pfn_to_section(pfn);

	if (!section->page_cgroup)
		return NULL;
	return section->page_cgroup + pfn;
}

struct page *lookup_cgroup_page(struct page_cgroup *pc)
{
	struct mem_section *section;
	struct page *page;
	unsigned long nr;

	nr = page_cgroup_array_id(pc);
	section = __nr_to_section(nr);
	page = pfn_to_page(pc - section->page_cgroup);
	VM_BUG_ON(pc != lookup_page_cgroup(page));
	return page;
}

static void *__meminit alloc_page_cgroup(size_t size, int nid)
{
	void *addr = NULL;

	addr = alloc_pages_exact_nid(nid, size, GFP_KERNEL | __GFP_NOWARN);
	if (addr)
		return addr;

	if (node_state(nid, N_HIGH_MEMORY))
		addr = vmalloc_node(size, nid);
	else
		addr = vmalloc(size);

	return addr;
}

#ifdef CONFIG_MEMORY_HOTPLUG
static void free_page_cgroup(void *addr)
{
	if (is_vmalloc_addr(addr)) {
		vfree(addr);
	} else {
		struct page *page = virt_to_page(addr);
		size_t table_size =
			sizeof(struct page_cgroup) * PAGES_PER_SECTION;

		BUG_ON(PageReserved(page));
		free_pages_exact(addr, table_size);
	}
}
#endif

static int __meminit init_section_page_cgroup(unsigned long pfn, int nid)
{
	struct page_cgroup *base, *pc;
	struct mem_section *section;
	unsigned long table_size;
	unsigned long nr;
	int index;

	nr = pfn_to_section_nr(pfn);
	section = __nr_to_section(nr);

	if (section->page_cgroup)
		return 0;

	table_size = sizeof(struct page_cgroup) * PAGES_PER_SECTION;
	base = alloc_page_cgroup(table_size, nid);

	/*
	 * The value stored in section->page_cgroup is (base - pfn)
	 * and it does not point to the memory block allocated above,
	 * causing kmemleak false positives.
	 */
	kmemleak_not_leak(base);

	if (!base) {
		printk(KERN_ERR "page cgroup allocation failure\n");
		return -ENOMEM;
	}

	for (index = 0; index < PAGES_PER_SECTION; index++) {
		pc = base + index;
		init_page_cgroup(pc, nr);
	}
	/*
	 * The passed "pfn" may not be aligned to SECTION.  For the calculation
	 * we need to apply a mask.
	 */
	pfn &= PAGE_SECTION_MASK;
	section->page_cgroup = base - pfn;
	total_usage += table_size;
	return 0;
}
#ifdef CONFIG_MEMORY_HOTPLUG
void __free_page_cgroup(unsigned long pfn)
{
	struct mem_section *ms;
	struct page_cgroup *base;

	ms = __pfn_to_section(pfn);
	if (!ms || !ms->page_cgroup)
		return;
	base = ms->page_cgroup + pfn;
	free_page_cgroup(base);
	ms->page_cgroup = NULL;
}

int __meminit online_page_cgroup(unsigned long start_pfn,
			unsigned long nr_pages,
			int nid)
{
	unsigned long start, end, pfn;
	int fail = 0;

	start = SECTION_ALIGN_DOWN(start_pfn);
	end = SECTION_ALIGN_UP(start_pfn + nr_pages);

	if (nid == -1) {
		/*
		 * In this case, "nid" already exists and contains valid memory.
		 * "start_pfn" passed to us is a pfn which is an arg for
		 * online__pages(), and start_pfn should exist.
		 */
		nid = pfn_to_nid(start_pfn);
		VM_BUG_ON(!node_state(nid, N_ONLINE));
	}

	for (pfn = start; !fail && pfn < end; pfn += PAGES_PER_SECTION) {
		if (!pfn_present(pfn))
			continue;
		fail = init_section_page_cgroup(pfn, nid);
	}
	if (!fail)
		return 0;

	/* rollback */
	for (pfn = start; pfn < end; pfn += PAGES_PER_SECTION)
		__free_page_cgroup(pfn);

	return -ENOMEM;
}

int __meminit offline_page_cgroup(unsigned long start_pfn,
		unsigned long nr_pages, int nid)
{
	unsigned long start, end, pfn;

	start = SECTION_ALIGN_DOWN(start_pfn);
	end = SECTION_ALIGN_UP(start_pfn + nr_pages);

	for (pfn = start; pfn < end; pfn += PAGES_PER_SECTION)
		__free_page_cgroup(pfn);
	return 0;

}

static int __meminit page_cgroup_callback(struct notifier_block *self,
			       unsigned long action, void *arg)
{
	struct memory_notify *mn = arg;
	int ret = 0;
	switch (action) {
	case MEM_GOING_ONLINE:
		ret = online_page_cgroup(mn->start_pfn,
				   mn->nr_pages, mn->status_change_nid);
		break;
	case MEM_OFFLINE:
		offline_page_cgroup(mn->start_pfn,
				mn->nr_pages, mn->status_change_nid);
		break;
	case MEM_CANCEL_ONLINE:
	case MEM_GOING_OFFLINE:
		break;
	case MEM_ONLINE:
	case MEM_CANCEL_OFFLINE:
		break;
	}

	return notifier_from_errno(ret);
}

#endif

void __init page_cgroup_init(void)
{
	unsigned long pfn;
	int nid;

	if (mem_cgroup_disabled())
		return;

	for_each_node_state(nid, N_HIGH_MEMORY) {
		unsigned long start_pfn, end_pfn;

		start_pfn = node_start_pfn(nid);
		end_pfn = node_end_pfn(nid);
		/*
		 * start_pfn and end_pfn may not be aligned to SECTION and the
		 * page->flags of out of node pages are not initialized.  So we
		 * scan [start_pfn, the biggest section's pfn < end_pfn) here.
		 */
		for (pfn = start_pfn;
		     pfn < end_pfn;
                     pfn = ALIGN(pfn + 1, PAGES_PER_SECTION)) {

			if (!pfn_valid(pfn))
				continue;
			/*
			 * Nodes's pfns can be overlapping.
			 * We know some arch can have a nodes layout such as
			 * -------------pfn-------------->
			 * N0 | N1 | N2 | N0 | N1 | N2|....
			 */
			if (pfn_to_nid(pfn) != nid)
				continue;
			if (init_section_page_cgroup(pfn, nid))
				goto oom;
		}
	}
	hotplug_memory_notifier(page_cgroup_callback, 0);
	printk(KERN_INFO "allocated %ld bytes of page_cgroup\n", total_usage);
	printk(KERN_INFO "please try 'cgroup_disable=memory' option if you "
			 "don't want memory cgroups\n");
	return;
oom:
	printk(KERN_CRIT "try 'cgroup_disable=memory' boot option\n");
	panic("Out of memory");
}

void __meminit pgdat_page_cgroup_init(struct pglist_data *pgdat)
{
	return;
}

#endif

#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP

static DEFINE_MUTEX(swap_cgroup_mutex);
struct swap_cgroup_ctrl {
	struct page **map;
	unsigned long length;
	spinlock_t	lock;
};

struct swap_cgroup_ctrl swap_cgroup_ctrl[MAX_SWAPFILES];

struct swap_cgroup {
	unsigned short		id;
};
#define SC_PER_PAGE	(PAGE_SIZE/sizeof(struct swap_cgroup))
#define SC_POS_MASK	(SC_PER_PAGE - 1)

/*
 * SwapCgroup implements "lookup" and "exchange" operations.
 * In typical usage, this swap_cgroup is accessed via memcg's charge/uncharge
 * against SwapCache. At swap_free(), this is accessed directly from swap.
 *
 * This means,
 *  - we have no race in "exchange" when we're accessed via SwapCache because
 *    SwapCache(and its swp_entry) is under lock.
 *  - When called via swap_free(), there is no user of this entry and no race.
 * Then, we don't need lock around "exchange".
 *
 * TODO: we can push these buffers out to HIGHMEM.
 */

/*
 * allocate buffer for swap_cgroup.
 */
static int swap_cgroup_prepare(int type)
{
	struct page *page;
	struct swap_cgroup_ctrl *ctrl;
	unsigned long idx, max;

	ctrl = &swap_cgroup_ctrl[type];

	for (idx = 0; idx < ctrl->length; idx++) {
		page = alloc_page(GFP_KERNEL | __GFP_ZERO);
		if (!page)
			goto not_enough_page;
		ctrl->map[idx] = page;
	}
	return 0;
not_enough_page:
	max = idx;
	for (idx = 0; idx < max; idx++)
		__free_page(ctrl->map[idx]);

	return -ENOMEM;
}

/**
 * swap_cgroup_cmpxchg - cmpxchg mem_cgroup's id for this swp_entry.
 * @end: swap entry to be cmpxchged
 * @old: old id
 * @new: new id
 *
 * Returns old id at success, 0 at failure.
 * (There is no mem_cgroup using 0 as its id)
 */
unsigned short swap_cgroup_cmpxchg(swp_entry_t ent,
					unsigned short old, unsigned short new)
{
	int type = swp_type(ent);
	unsigned long offset = swp_offset(ent);
	unsigned long idx = offset / SC_PER_PAGE;
	unsigned long pos = offset & SC_POS_MASK;
	struct swap_cgroup_ctrl *ctrl;
	struct page *mappage;
	struct swap_cgroup *sc;
	unsigned long flags;
	unsigned short retval;

	ctrl = &swap_cgroup_ctrl[type];

	mappage = ctrl->map[idx];
	sc = page_address(mappage);
	sc += pos;
	spin_lock_irqsave(&ctrl->lock, flags);
	retval = sc->id;
	if (retval == old)
		sc->id = new;
	else
		retval = 0;
	spin_unlock_irqrestore(&ctrl->lock, flags);
	return retval;
}

/**
 * swap_cgroup_record - record mem_cgroup for this swp_entry.
 * @ent: swap entry to be recorded into
 * @mem: mem_cgroup to be recorded
 *
 * Returns old value at success, 0 at failure.
 * (Of course, old value can be 0.)
 */
unsigned short swap_cgroup_record(swp_entry_t ent, unsigned short id)
{
	int type = swp_type(ent);
	unsigned long offset = swp_offset(ent);
	unsigned long idx = offset / SC_PER_PAGE;
	unsigned long pos = offset & SC_POS_MASK;
	struct swap_cgroup_ctrl *ctrl;
	struct page *mappage;
	struct swap_cgroup *sc;
	unsigned short old;
	unsigned long flags;

	ctrl = &swap_cgroup_ctrl[type];

	mappage = ctrl->map[idx];
	sc = page_address(mappage);
	sc += pos;
	spin_lock_irqsave(&ctrl->lock, flags);
	old = sc->id;
	sc->id = id;
	spin_unlock_irqrestore(&ctrl->lock, flags);

	return old;
}

/**
 * lookup_swap_cgroup - lookup mem_cgroup tied to swap entry
 * @ent: swap entry to be looked up.
 *
 * Returns CSS ID of mem_cgroup at success. 0 at failure. (0 is invalid ID)
 */
unsigned short lookup_swap_cgroup(swp_entry_t ent)
{
	int type = swp_type(ent);
	unsigned long offset = swp_offset(ent);
	unsigned long idx = offset / SC_PER_PAGE;
	unsigned long pos = offset & SC_POS_MASK;
	struct swap_cgroup_ctrl *ctrl;
	struct page *mappage;
	struct swap_cgroup *sc;
	unsigned short ret;

	ctrl = &swap_cgroup_ctrl[type];
	mappage = ctrl->map[idx];
	sc = page_address(mappage);
	sc += pos;
	ret = sc->id;
	return ret;
}

int swap_cgroup_swapon(int type, unsigned long max_pages)
{
	void *array;
	unsigned long array_size;
	unsigned long length;
	struct swap_cgroup_ctrl *ctrl;

	if (!do_swap_account)
		return 0;

	length = DIV_ROUND_UP(max_pages, SC_PER_PAGE);
	array_size = length * sizeof(void *);

	array = vmalloc(array_size);
	if (!array)
		goto nomem;

	memset(array, 0, array_size);
	ctrl = &swap_cgroup_ctrl[type];
	mutex_lock(&swap_cgroup_mutex);
	ctrl->length = length;
	ctrl->map = array;
	spin_lock_init(&ctrl->lock);
	if (swap_cgroup_prepare(type)) {
		/* memory shortage */
		ctrl->map = NULL;
		ctrl->length = 0;
		mutex_unlock(&swap_cgroup_mutex);
		vfree(array);
		goto nomem;
	}
	mutex_unlock(&swap_cgroup_mutex);

	return 0;
nomem:
	printk(KERN_INFO "couldn't allocate enough memory for swap_cgroup.\n");
	printk(KERN_INFO
		"swap_cgroup can be disabled by swapaccount=0 boot option\n");
	return -ENOMEM;
}

void swap_cgroup_swapoff(int type)
{
	struct page **map;
	unsigned long i, length;
	struct swap_cgroup_ctrl *ctrl;

	if (!do_swap_account)
		return;

	mutex_lock(&swap_cgroup_mutex);
	ctrl = &swap_cgroup_ctrl[type];
	map = ctrl->map;
	length = ctrl->length;
	ctrl->map = NULL;
	ctrl->length = 0;
	mutex_unlock(&swap_cgroup_mutex);

	if (map) {
		for (i = 0; i < length; i++) {
			struct page *page = map[i];
			if (page)
				__free_page(page);
		}
		vfree(map);
	}
}

#endif


text:
module Locomotive
  module SitesHelper

    # forms

    def ordered_current_site_locales
      current_site.locales + (Locomotive.config.site_locales - current_site.locales)
    end

    def options_for_site_locales
      Rails.cache.fetch('views/helpers/site_locales') do
        Locomotive.config.site_locales.map do |locale|
          text          = I18n.t("locomotive.locales.#{locale}")
          flag_url      = path_to_image "locomotive/icons/flags/#{locale}.png"
          nice_display  = h("<img class='flag' src='#{flag_url}' width='24px' />" + text)

          [
            text,
            locale,
            { :"data-display" => nice_display }
          ]
        end
      end
    end

    def options_for_site_timezones
      Rails.cache.fetch('views/helpers/timezones') do
        ActiveSupport::TimeZone.all.map do |tz|
          [tz.to_s, tz.name]
        end
      end
    end

  end
end


text:
// Declare app level module which depends on filters, and services
angular.module('myAngularApp.config', [])

// from package.json
.constant("appName","clo")
.constant("appVersion","15.6.7")
.constant("appServerUrlLocal","http://localhost:9000/todoc")
.constant("appServerUrlRemote", "https://xxxx.com/todoc")

.constant("appGAID","UA-63329886-5")

.config(function($routeProvider, $logProvider, $locationProvider, $httpProvider) {
  'use strict';
  //$routeProvider.otherwise({redirectTo: '/user'});

  //$logProvider.debugEnabled(true);
  //$httpProvider.responseInterceptors.push('httpInterceptor');

  //$routeProvider
  //    .when('/', { templateUrl: 'views/dashboard.html', controller: 'dashboard' })
  //    .when('/login', { templateUrl: 'views/auth.html', controller: 'auth' });
  //    .otherwise({ redirectTo: '/' });
  //$routeProvider
  //.otherwise({ redirectTo: '/' });

  //$locationProvider.html5Mode(true);
  //$locationProvider.html5Mode({
  //  enabled: true,
  //  requireBase: false
  //});
})

.run(function($route, gettextCatalog){
    gettextCatalog.currentLanguage = 'en';
    gettextCatalog.debug = true;

    //ie https://github.com/angular/angular.js/issues/1213
    $route.reload();
});

  // double check that the app has been configured before running it and blowing up space and time
  // .run(['WS_URL', '$timeout', '$document', function(WS_URL, $timeout, $document) {
  //   if( WS_URL.match('//INSTANCE.firebaseio.com') ) {
  //     angular.element($document.body).html('
Please configure app/js/config.js before running!
');
  //     $timeout(function() {
  //       angular.element($document.body).removeClass('hide');
  //     }, 250);
  //   }
  // }])

  //
  // .config(function($translateProvider) {
  //
  //   //$translateProvider.useLocalStorage();
  //   //$translateProvider.useStaticFilesLoader({
  //   //  prefix: '/languages/',
  //   //  suffix: '.json'
  //   //});
  //
  //    $translateProvider.translations('en', {
  //     HEADLINE: 'Hello there, This is my awesome app!',
  //     INTRO_TEXT: 'And it has i18n support!',
  //     BUTTON_TEXT_EN: 'english',
  //     BUTTON_TEXT_DE: 'german'
  //   })
  //   .translations('de', {
  //     HEADLINE: 'Hey, das ist meine großartige App!',
  //     INTRO_TEXT: 'Und sie untersützt mehrere Sprachen!',
  //     BUTTON_TEXT_EN: 'englisch',
  //     BUTTON_TEXT_DE: 'deutsch'
  //   });
  //   $translateProvider.preferredLanguage('en');
  // })

  /** samples

  // decorator on $log service
  .config(['$provide', function ($provide) {
      $provide.decorator('$log', ['$delegate', function ($delegate) {
          // Keep track of the original debug method, we'll need it later.
          var origDebug = $delegate.debug;

          //Intercept the call to $log.debug() so we can add on
          //our enhancement. We're going to add on a date and
          //time stamp to the message that will be logged.
          $delegate.debug = function () {
              var args = [].slice.call(arguments);
              args[0] = [new Date().toString(), ': ', args[0]].join('');

              // Send on our enhanced message to the original debug method.
              origDebug.apply(null, args)
          };

          return $delegate;
      }]);
  }])

  */


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>$title ($projectnumber)</title>
<link href="/style/style.css" rel="stylesheet" type="text/css">

Home --> Documentations --> PJNATH Reference


text:
require 'rails_helper'
require "#{Rails.root}/lib/alerts/discretionary_sanctions_monitor"

def mock_mailer
  OpenStruct.new(deliver_now: true)
end

describe DiscretionarySanctionsMonitor do
  describe '.create_alerts_for_course_articles' do
    let(:course) { create(:course, start: 1.month.ago, end: 1.month.after) }
    let(:student) { create(:user, username: 'student') }
    let!(:courses_user) do
      create(:courses_user, user_id: student.id,
                            course_id: course.id,
                            role: CoursesUsers::Roles::STUDENT_ROLE)
    end
    let(:content_expert) { create(:user, greeter: true) }

    # Article that hasn't been edited by students
    let!(:article2) { create(:article, title: '1948_war', namespace: 0) }

    # Article that has been edited by a student
    let(:article) { create(:article, title: 'Ahmed_Mohamed_clock_incident', namespace: 0) }
    let!(:revision) do
      create(:revision, article_id: article.id,
                        user_id: student.id,
                        date: course.start + 1.day)
    end
    let!(:articles_course) do
      create(:articles_course, article_id: article.id,
                               course_id: course.id)
    end

    let!(:assignment) do
      create(:assignment, article_title: article.title,
                          article_id: article.id,
                          course_id: course.id,
                          user_id: student.id)
    end

    before do
      allow_any_instance_of(CategoryImporter).to receive(:page_titles_for_category)
        .with('Category:Wikipedia pages under discretionary sanctions', 1)
        .and_return(['Talk:1948 war',
                     'Talk:Ahmed Mohamed clock incident',
                     'Talk:Armenian Genocide denial'])
    end

    it 'creates Alert records for assignments and edited articles under discretionary sanctions' do
      described_class.create_alerts_for_course_articles
      expect(DiscretionarySanctionsEditAlert.count).to eq(1)
      expect(DiscretionarySanctionsAssignmentAlert.count).to eq(1)
      alerted_edit_article_ids = DiscretionarySanctionsEditAlert.all.pluck(:article_id)
      expect(alerted_edit_article_ids).to include(article.id)
      alerted_assignment_article_ids = DiscretionarySanctionsAssignmentAlert.all.pluck(:article_id)
      expect(alerted_assignment_article_ids).to include(article.id)
    end

    it 'emails a greeter' do
      create(:courses_user, user_id: content_expert.id, course_id: course.id, role: 4)
      allow_any_instance_of(AlertMailer).to receive(:alert).and_return(mock_mailer)
      described_class.create_alerts_for_course_articles
      expect(Alert.last.email_sent_at).not_to be_nil
    end

    it 'does not create a second Alert for the same assignments, if the first is not resolved' do
      Alert.create(type: 'DiscretionarySanctionsAssignmentAlert', article_id: assignment.article_id,
                   course_id: assignment.course_id, user_id: assignment.user_id)
      expect(DiscretionarySanctionsAssignmentAlert.count).to eq(1)
      described_class.create_alerts_for_course_articles
      expect(DiscretionarySanctionsAssignmentAlert.count).to eq(1)
    end

    it 'does not create a second Alert for the same articles, if the first is not resolved' do
      Alert.create(type: 'DiscretionarySanctionsEditAlert',
                   article_id: article.id, course_id: course.id)
      expect(DiscretionarySanctionsEditAlert.count).to eq(1)
      described_class.create_alerts_for_course_articles
      expect(DiscretionarySanctionsEditAlert.count).to eq(1)
    end

    it 'does not create second Alert if the first alert is resolved but there are no new edits' do
      Alert.create(type: 'DiscretionarySanctionsEditAlert', article_id: article.id,
                   course_id: course.id, resolved: true, created_at: revision.date + 1.hour)
      expect(DiscretionarySanctionsEditAlert.count).to eq(1)
      described_class.create_alerts_for_course_articles
      expect(DiscretionarySanctionsEditAlert.count).to eq(1)
    end

    it 'does create second Alert if the first alert is resolved and there are later edits' do
      Alert.create(type: 'DiscretionarySanctionsEditAlert', article_id: article.id,
                   course_id: course.id, resolved: true, created_at: revision.date - 1.hour)
      expect(DiscretionarySanctionsEditAlert.count).to eq(1)
      described_class.create_alerts_for_course_articles
      expect(DiscretionarySanctionsEditAlert.count).to eq(2)
    end

    it 'does create second Alert if the first alert is resolved and there are later assignments' do
      Alert.create(type: 'DiscretionarySanctionsAssignmentAlert', article_id: assignment.article_id,
                   course_id: assignment.course_id, user_id: assignment.user_id, resolved: true)
      expect(DiscretionarySanctionsAssignmentAlert.count).to eq(1)
      described_class.create_alerts_for_course_articles
      expect(DiscretionarySanctionsAssignmentAlert.count).to eq(2)
    end
  end
end


text:
Quality

Logging, Tracing...

License

                <form class="form-horizontal" name="generalForm" ng-submit="$ctrl.onSubmit()">

                        File Path

                            <input type="text" class="form-control" id="filePath" placeholder="" ng-model="$ctrl.formData.filePath">

                            <electron-dialog-button class="col-xs-12" dialog-type="'file'" on-path-selected="$ctrl.filePathSelected($event)"></electron-dialog-button>

                                    <input type="radio" name="test" id="test1" value="all" ng-model="$ctrl.formData.test" checked> Test all

                                    <input type="radio" name="test" id="test2" value="following" ng-model="$ctrl.formData.test"> Test the following

                            <input type="text" class="form-control" id="following" placeholder="" ng-model="$ctrl.formData.following">

                                    <input type="radio" name="test" id="test3" value="random" ng-model="$ctrl.formData.test"> Test

                            <input type="text" class="form-control" id="random" placeholder="2" ng-model="$ctrl.formData.random">

                             random

                            <button type="button" class="btn btn-flat btn-default" ng-click="$ctrl.showConfirmModal()"> Do</button>
                            <button type="button" class="btn btn-flat btn-default"> View Output</button>

                </form>

                    <ui-view></ui-view>

Est id sit ad laborum et ea irure nisi veniam occaecat anim irure exercitation. Consequat reprehenderit qui anim veniam proident pariatur in non qui velit culpa cupidatat irure. Quis voluptate occaecat consectetur enim laboris enim
                            id et eu.


text:
require 'test_helper'

class Api::FindingControllerTest < ActionController::TestCase

  def finding_ids
    ids = []
    findings.each { |finding| ids << finding.id }
    return ids
  end

  def all_findings
    results = {'count' => Finding.count }
    results['results'] = []
    Finding.all.each do |finding|
      results['results'] << finding.as_json
    end
    return results.as_json
  end

  test "index lists all findings" do
    get :index

    assert_response :success
    assert_equal all_findings, JSON.parse(@response.body), "index doesn't list all findings"
  end

  test "sorts by pretty name and orders" do
    get(:index, {:sort_by => 'repo_name', :order => 'asc'})

    assert_response :success
    assert_equal findings(:one).as_json, JSON.parse(@response.body)['results'][0], "wrong finding is first"
  end

  test "searches by filtered_by" do
    get(:index, {:filtered_by => filters(:one).id})

    assert_response :success
    assert_equal findings(:one).as_json, JSON.parse(@response.body)['results'][0], "not searching by filtered_by"
  end

  test "shows a single finding" do
    get(:show, {:id => findings(:one).id})

    assert_response :success
    assert_equal findings(:one).as_json, JSON.parse(@response.body), "finding isn't shown correctly"
  end

  test "throws a 404 on showing unknown finding" do
    get(:show, {:id => ([1...1000] - finding_ids).sample})

    assert_response :missing, "matching finding not found, response not 404"
  end

  test "updates finding status" do
    put(:update, {:id => findings(:one).id, :status => 3})

    assert_response :success
    assert_equal 3, Finding.find(findings(:one).id).status, "finding status didn't change"
  end

  test "throws a 404 on updating unknown finding" do
    put(:update, {:id => ([1...1000] - finding_ids).sample})

    assert_response :missing, "update sent for unknown finding, response not 404"
  end

  test "fails publishing to jira with no project" do
    put(:publish, {:id => findings(:one).id, :method => 'jira'})
    assert_response 400
  end

  test "fails publishing with unsupported method" do
    put(:publish, {:id => findings(:one).id, :method => 'FOOBAR'})
    assert_response 400
  end

  test "throws a 404 publishing unknown finding" do
    put(:publish, {:id => ([1...1000] - finding_ids).sample, :method => 'github'})

    assert_response :missing, "publish sent for unknown finding, response not 404"
  end

  # test "throws a 500 on publishing failure" do
  #   github_result = mock('github_result')
  #   github_result.expects(:number).returns(nil).once
  #   github_result.expects(:html_url).returns(nil).once
  #   @controller.expects(:publish_to_github).returns(github_result).once
  #
  #   put(:publish, {:id => findings(:one).id, :method => 'github'})
  #   assert_response 500
  # end

  # test "publishes to github" do
  #   github_result = mock('github_result')
  #   github_result.expects(:number).returns('1').once
  #   github_result.expects(:html_url).returns('http://test.url').once
  #   CodeburnerUtil.expects(:strip_github_path).returns('TestTeam/TestProject').once
  #
  #   # publish_to_github call
  #   CodeburnerUtil.expects(:severity_to_text).returns('High').once
  #   user_github = mock('user_github')
  #   Octokit::Client.expects(:new).returns(user_github)
  #   user_github.expects(:create_issue).returns(github_result).once
  #
  #   put(:publish, {:id => findings(:one).id, :method => 'github'})
  #   assert_response :success
  #   assert_equal 2, Finding.find(findings(:one).id).status, "finding status didn't change to published"
  # end

  # test "publishes to jira" do
  #   jira_result = {'key' => '1234'}
  #
  #   #publish_to_jira call
  #   issue = mock('mock_issue')
  #   issue.expects(:build).returns(issue).once
  #   issue.expects(:save).returns(:true)
  #   issue.expects(:attrs).returns(jira_result)
  #   CodeburnerUtil.expects(:severity_to_text).returns('High').once
  #   $jira.expects(:Issue).returns(issue).once
  #
  #   put(:publish, {:id => findings(:one).id, :method => 'jira', :project => 'TEST'})
  #   assert_response :success
  #   assert_equal 2, Finding.find(findings(:one).id).status, "finding status didn't change to published"
  # end
end


text:
package otlphttpexporter // import "go.opentelemetry.io/collector/exporter/otlphttpexporter"

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"runtime"
	"strconv"
	"time"

	"go.uber.org/zap"
	"google.golang.org/genproto/googleapis/rpc/status"
	"google.golang.org/protobuf/proto"

	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/consumer/consumererror"
	"go.opentelemetry.io/collector/exporter/exporterhelper"
	"go.opentelemetry.io/collector/pdata/plog"
	"go.opentelemetry.io/collector/pdata/plog/plogotlp"
	"go.opentelemetry.io/collector/pdata/pmetric"
	"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp"
	"go.opentelemetry.io/collector/pdata/ptrace"
	"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp"
)

type exporter struct {
	// Input configuration.
	config     *Config
	client     *http.Client
	tracesURL  string
	metricsURL string
	logsURL    string
	logger     *zap.Logger
	settings   component.TelemetrySettings
	// Default user-agent header.
	userAgent string
}

const (
	headerRetryAfter         = "Retry-After"
	maxHTTPResponseReadBytes = 64 * 1024
)

// Create new exporter.
func newExporter(cfg component.Config, set component.ExporterCreateSettings) (*exporter, error) {
	oCfg := cfg.(*Config)

	if oCfg.Endpoint != "" {
		_, err := url.Parse(oCfg.Endpoint)
		if err != nil {
			return nil, errors.New("endpoint must be a valid URL")
		}
	}

	userAgent := fmt.Sprintf("%s/%s (%s/%s)",
		set.BuildInfo.Description, set.BuildInfo.Version, runtime.GOOS, runtime.GOARCH)

	// client construction is deferred to start
	return &exporter{
		config:    oCfg,
		logger:    set.Logger,
		userAgent: userAgent,
		settings:  set.TelemetrySettings,
	}, nil
}

// start actually creates the HTTP client. The client construction is deferred till this point as this
// is the only place we get hold of Extensions which are required to construct auth round tripper.
func (e *exporter) start(_ context.Context, host component.Host) error {
	client, err := e.config.HTTPClientSettings.ToClient(host, e.settings)
	if err != nil {
		return err
	}
	e.client = client
	return nil
}

func (e *exporter) pushTraces(ctx context.Context, td ptrace.Traces) error {
	tr := ptraceotlp.NewExportRequestFromTraces(td)
	request, err := tr.MarshalProto()
	if err != nil {
		return consumererror.NewPermanent(err)
	}

	return e.export(ctx, e.tracesURL, request)
}

func (e *exporter) pushMetrics(ctx context.Context, md pmetric.Metrics) error {
	tr := pmetricotlp.NewExportRequestFromMetrics(md)
	request, err := tr.MarshalProto()
	if err != nil {
		return consumererror.NewPermanent(err)
	}
	return e.export(ctx, e.metricsURL, request)
}

func (e *exporter) pushLogs(ctx context.Context, ld plog.Logs) error {
	tr := plogotlp.NewExportRequestFromLogs(ld)
	request, err := tr.MarshalProto()
	if err != nil {
		return consumererror.NewPermanent(err)
	}

	return e.export(ctx, e.logsURL, request)
}

func (e *exporter) export(ctx context.Context, url string, request []byte) error {
	e.logger.Debug("Preparing to make HTTP request", zap.String("url", url))
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(request))
	if err != nil {
		return consumererror.NewPermanent(err)
	}
	req.Header.Set("Content-Type", "application/x-protobuf")
	req.Header.Set("User-Agent", e.userAgent)

	resp, err := e.client.Do(req)
	if err != nil {
		return fmt.Errorf("failed to make an HTTP request: %w", err)
	}

	defer func() {
		// Discard any remaining response body when we are done reading.
		io.CopyN(io.Discard, resp.Body, maxHTTPResponseReadBytes) // nolint:errcheck
		resp.Body.Close()
	}()

	if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
		// Request is successful.
		return nil
	}

	respStatus := readResponse(resp)

	// Format the error message. Use the status if it is present in the response.
	var formattedErr error
	if respStatus != nil {
		formattedErr = fmt.Errorf(
			"error exporting items, request to %s responded with HTTP Status Code %d, Message=%s, Details=%v",
			url, resp.StatusCode, respStatus.Message, respStatus.Details)
	} else {
		formattedErr = fmt.Errorf(
			"error exporting items, request to %s responded with HTTP Status Code %d",
			url, resp.StatusCode)
	}

	// Check if the server is overwhelmed.
	// See spec https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md#throttling-1
	if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable {
		// Fallback to 0 if the Retry-After header is not present. This will trigger the
		// default backoff policy by our caller (retry handler).
		retryAfter := 0
		if val := resp.Header.Get(headerRetryAfter); val != "" {
			if seconds, err2 := strconv.Atoi(val); err2 == nil {
				retryAfter = seconds
			}
		}
		// Indicate to our caller to pause for the specified number of seconds.
		return exporterhelper.NewThrottleRetry(formattedErr, time.Duration(retryAfter)*time.Second)
	}

	if isPermanentClientFailure(resp.StatusCode) {
		// Do not retry; report the failure as permanent if the server thinks the request is malformed.
		return consumererror.NewPermanent(formattedErr)
	}

	// All other errors are retryable, so don't wrap them in consumererror.NewPermanent().
	return formattedErr
}

// Does the 'code' indicate a permanent error
func isPermanentClientFailure(code int) bool {
	switch code {
	case http.StatusBadRequest:
		return true
	case http.StatusPaymentRequired:
		// 402 - payment required typically means that an auth token isn't valid anymore and as such, we deem it as permanent
		return true
	case http.StatusRequestEntityTooLarge:
		return true
	case http.StatusRequestURITooLong:
		return true
	case http.StatusRequestHeaderFieldsTooLarge:
		return true
	case http.StatusNotFound:
		return true
	case http.StatusMethodNotAllowed:
		return true
	default:
		return false
	}
}

// Read the response and decode the status.Status from the body.
// Returns nil if the response is empty or cannot be decoded.
func readResponse(resp *http.Response) *status.Status {
	var respStatus *status.Status
	if resp.StatusCode >= 400 && resp.StatusCode <= 599 {
		// Request failed. Read the body. OTLP spec says:
		// "Response body for all HTTP 4xx and HTTP 5xx responses MUST be a
		// Protobuf-encoded Status message that describes the problem."
		maxRead := resp.ContentLength
		if maxRead == -1 || maxRead > maxHTTPResponseReadBytes {
			maxRead = maxHTTPResponseReadBytes
		}
		respBytes := make([]byte, maxRead)
		n, err := io.ReadFull(resp.Body, respBytes)
		if err == nil && n > 0 {
			// Decode it as Status struct. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md#failures
			respStatus = &status.Status{}
			err = proto.Unmarshal(respBytes, respStatus)
			if err != nil {
				respStatus = nil
			}
		}
	}

	return respStatus
}


text:
<?php

namespace Drupal\Tests\locale\Kernel;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Language\Language;
use Drupal\language\Entity\ConfigurableLanguage;

/**
 * Tests default configuration handling with a foreign default language.
 *
 * @group locale
 */
class LocaleConfigSubscriberForeignTest extends LocaleConfigSubscriberTest {

  /**
   * {@inheritdoc}
   */
  public function register(ContainerBuilder $container) {
    parent::register($container);

    $language = Language::$defaultValues;
    $language['id'] = 'hu';
    $language['name'] = 'Hungarian';
    $container->setParameter('language.default_values', $language);
  }

  /**
   * {@inheritdoc}
   */
  protected function setUpLanguages() {
    parent::setUpLanguages();
    ConfigurableLanguage::createFromLangcode('hu')->save();
  }

  /**
   * {@inheritdoc}
   */
  protected function setUpLocale() {
    parent::setUpLocale();
    $this->setUpTranslation('locale_test.translation', 'test', 'English test', 'Hungarian test', 'hu', TRUE);
  }

  /**
   * Tests that the language of default configuration was updated.
   */
  public function testDefaultConfigLanguage() {
    $this->assertEqual('hu', $this->configFactory->getEditable('locale_test.no_translation')->get('langcode'));
    $this->assertEqual('hu', $this->configFactory->getEditable('locale_test.translation')->get('langcode'));
    $this->assertEqual($this->configFactory->getEditable('locale_test.translation')->get('test'), 'Hungarian test');
  }

  /**
   * Tests creating translations of shipped configuration.
   */
  public function testCreateActiveTranslation() {
    $config_name = 'locale_test.no_translation';
    $this->saveLanguageActive($config_name, 'test', 'Test (Hungarian)', 'hu');
    $this->assertTranslation($config_name, 'Test (Hungarian)', 'hu');
  }

  /**
   * Tests importing community translations of shipped configuration.
   */
  public function testLocaleCreateActiveTranslation() {
    $config_name = 'locale_test.no_translation';
    $this->saveLocaleTranslationData($config_name, 'test', 'Test', 'Test (Hungarian)', 'hu', TRUE);
    $this->assertTranslation($config_name, 'Test (Hungarian)', 'hu', FALSE);
  }

  /**
   * Tests updating translations of shipped configuration.
   */
  public function testUpdateActiveTranslation() {
    $config_name = 'locale_test.translation';
    $this->saveLanguageActive($config_name, 'test', 'Updated Hungarian test', 'hu');
    $this->assertTranslation($config_name, 'Updated Hungarian test', 'hu');
  }

  /**
   * Tests updating community translations of shipped configuration.
   */
  public function testLocaleUpdateActiveTranslation() {
    $config_name = 'locale_test.translation';
    $this->saveLocaleTranslationData($config_name, 'test', 'English test', 'Updated Hungarian test', 'hu', TRUE);
    $this->assertTranslation($config_name, 'Updated Hungarian test', 'hu', FALSE);
  }

  /**
   * Tests deleting a translation override.
   */
  public function testDeleteTranslation() {
    $config_name = 'locale_test.translation';
    $this->deleteLanguageOverride($config_name, 'test', 'English test', 'de');
    // The German translation in this case will be forced to the Hungarian
    // source so its not overwritten with locale data later.
    $this->assertTranslation($config_name, 'Hungarian test', 'de');
  }

  /**
   * Tests deleting translations of shipped configuration.
   */
  public function testDeleteActiveTranslation() {
    $config_name = 'locale_test.translation';
    $this->configFactory->getEditable($config_name)->delete();
    // Deleting active configuration should not change the locale translation.
    $this->assertTranslation($config_name, 'Hungarian test', 'hu', FALSE);
  }

  /**
   * Tests deleting community translations of shipped configuration.
   */
  public function testLocaleDeleteActiveTranslation() {
    $config_name = 'locale_test.translation';
    $this->deleteLocaleTranslationData($config_name, 'test', 'English test', 'hu');
    // Deleting the locale translation should not change active config.
    $this->assertEqual($this->configFactory->getEditable($config_name)->get('test'), 'Hungarian test');
  }

  /**
   * Tests that adding English creates a translation override.
   */
  public function testEnglish() {
    $config_name = 'locale_test.translation';
    ConfigurableLanguage::createFromLangcode('en')->save();
    // Adding a language on the UI would normally call updateConfigTranslations.
    $this->localeConfigManager->updateConfigTranslations([$config_name], ['en']);
    $this->assertConfigOverride($config_name, 'test', 'English test', 'en');

    $this->configFactory->getEditable('locale.settings')->set('translate_english', TRUE)->save();
    $this->saveLocaleTranslationData($config_name, 'test', 'English test', 'Updated English test', 'en');
    $this->assertTranslation($config_name, 'Updated English test', 'en', FALSE);

    $this->saveLanguageOverride($config_name, 'test', 'Updated English', 'en');
    $this->assertTranslation($config_name, 'Updated English', 'en');

    $this->deleteLocaleTranslationData($config_name, 'test', 'English test', 'en');
    $this->assertNoConfigOverride($config_name, 'en');
  }

  /**
   * Saves a language override.
   *
   * This will invoke LocaleConfigSubscriber through the event dispatcher. To
   * make sure the configuration was persisted correctly, the configuration
   * value is checked. Because LocaleConfigSubscriber temporarily disables the
   * override state of the configuration factory we check that the correct value
   * is restored afterwards.
   *
   * @param string $config_name
   *   The configuration name.
   * @param string $key
   *   The configuration key.
   * @param string $value
   *   The configuration value to save.
   * @param string $langcode
   *   The language code.
   */
  protected function saveLanguageActive($config_name, $key, $value, $langcode) {
    $this
      ->configFactory
      ->getEditable($config_name)
      ->set($key, $value)
      ->save();
    $this->assertActiveConfig($config_name, $key, $value, $langcode);
  }

}


text:
typedef void  (^ZCBtnDownloadCompletedBlock)(UIImage *image,UIButton *btn ,NSError *error);

@interface UIButton (ZCDownload)
- (void)zcSetImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(ZCBtnDownloadCompletedBlock)completedBlock;
@end


text:
namespace PageAccessCap.Models
{
    public class ErrorViewModel
    {
        public int PageHitCount { get; set; }
        public string Message { get; set; }

        public ErrorViewModel() { }
        public ErrorViewModel(string message)
            : this()
        {
            this.Message = message;
        }
    }
}


text:
using System;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using System.Threading.Tasks;
using Raven.Client.Documents;
using Raven.Client.Documents.Operations;
using Raven.Client.Documents.Queries;
using System.Threading;

namespace WorkflowCore.Persistence.RavenDB.Services
{
	public class WorkflowPurger : IWorkflowPurger
	{
		private readonly IDocumentStore _database;

		public WorkflowPurger(IDocumentStore database)
		{
			_database = database;
		}

		public async Task PurgeWorkflows(WorkflowStatus status, DateTime olderThan, CancellationToken cancellationToken = default)
		{
			await DeleteWorkflowInstances(status, olderThan, cancellationToken);
		}

		/// <summary>
		/// Delete all Workflow Documents
		/// </summary>
		/// <returns></returns>
		private Task<Operation> DeleteWorkflowInstances(WorkflowStatus status, DateTime olderThan, CancellationToken cancellationToken = default)
		{
			var utcTime = olderThan.ToUniversalTime();
			var queryToDelete = new IndexQuery { Query = $"FROM {nameof(WorkflowInstance)} where status = '{status}' and CompleteTime < '{olderThan}'" };
			return _database.Operations.SendAsync(new DeleteByQueryOperation(queryToDelete, new QueryOperationOptions { AllowStale = false }), token: cancellationToken);
		}
	}
}


text:
<?php

namespace Symfony\Component\DependencyInjection;

use Symfony\Component\DependencyInjection\Argument\BoundArgument;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\OutOfBoundsException;

/**
 * Definition represents a service definition.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class Definition
{
    private const DEFAULT_DEPRECATION_TEMPLATE = 'The "%service_id%" service is deprecated. You should stop using it, as it will be removed in the future.';

    private ?string $class = null;
    private ?string $file = null;
    private string|array|null $factory = null;
    private bool $shared = true;
    private array $deprecation = [];
    private array $properties = [];
    private array $calls = [];
    private array $instanceof = [];
    private bool $autoconfigured = false;
    private string|array|null $configurator = null;
    private array $tags = [];
    private bool $public = false;
    private bool $synthetic = false;
    private bool $abstract = false;
    private bool $lazy = false;
    private ?array $decoratedService = null;
    private bool $autowired = false;
    private array $changes = [];
    private array $bindings = [];
    private array $errors = [];

    protected $arguments = [];

    /**
     * @internal
     *
     * Used to store the name of the inner id when using service decoration together with autowiring
     */
    public ?string $innerServiceId = null;

    /**
     * @internal
     *
     * Used to store the behavior to follow when using service decoration and the decorated service is invalid
     */
    public ?int $decorationOnInvalid = null;

    public function __construct(string $class = null, array $arguments = [])
    {
        if (null !== $class) {
            $this->setClass($class);
        }
        $this->arguments = $arguments;
    }

    /**
     * Returns all changes tracked for the Definition object.
     */
    public function getChanges(): array
    {
        return $this->changes;
    }

    /**
     * Sets the tracked changes for the Definition object.
     *
     * @param array $changes An array of changes for this Definition
     *
     * @return $this
     */
    public function setChanges(array $changes): static
    {
        $this->changes = $changes;

        return $this;
    }

    /**
     * Sets a factory.
     *
     * @param string|array|Reference|null $factory A PHP function, reference or an array containing a class/Reference and a method to call
     *
     * @return $this
     */
    public function setFactory(string|array|Reference|null $factory): static
    {
        $this->changes['factory'] = true;

        if (\is_string($factory) && str_contains($factory, '::')) {
            $factory = explode('::', $factory, 2);
        } elseif ($factory instanceof Reference) {
            $factory = [$factory, '__invoke'];
        }

        $this->factory = $factory;

        return $this;
    }

    /**
     * Gets the factory.
     *
     * @return string|array|null The PHP function or an array containing a class/Reference and a method to call
     */
    public function getFactory(): string|array|null
    {
        return $this->factory;
    }

    /**
     * Sets the service that this service is decorating.
     *
     * @param string|null $id        The decorated service id, use null to remove decoration
     * @param string|null $renamedId The new decorated service id
     *
     * @return $this
     *
     * @throws InvalidArgumentException in case the decorated service id and the new decorated service id are equals
     */
    public function setDecoratedService(?string $id, string $renamedId = null, int $priority = 0, int $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE): static
    {
        if ($renamedId && $id === $renamedId) {
            throw new InvalidArgumentException(sprintf('The decorated service inner name for "%s" must be different than the service name itself.', $id));
        }

        $this->changes['decorated_service'] = true;

        if (null === $id) {
            $this->decoratedService = null;
        } else {
            $this->decoratedService = [$id, $renamedId, $priority];

            if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
                $this->decoratedService[] = $invalidBehavior;
            }
        }

        return $this;
    }

    /**
     * Gets the service that this service is decorating.
     *
     * @return array|null An array composed of the decorated service id, the new id for it and the priority of decoration, null if no service is decorated
     */
    public function getDecoratedService(): ?array
    {
        return $this->decoratedService;
    }

    /**
     * Sets the service class.
     *
     * @return $this
     */
    public function setClass(?string $class): static
    {
        $this->changes['class'] = true;

        $this->class = $class;

        return $this;
    }

    /**
     * Gets the service class.
     */
    public function getClass(): ?string
    {
        return $this->class;
    }

    /**
     * Sets the arguments to pass to the service constructor/factory method.
     *
     * @return $this
     */
    public function setArguments(array $arguments): static
    {
        $this->arguments = $arguments;

        return $this;
    }

    /**
     * Sets the properties to define when creating the service.
     *
     * @return $this
     */
    public function setProperties(array $properties): static
    {
        $this->properties = $properties;

        return $this;
    }

    /**
     * Gets the properties to define when creating the service.
     */
    public function getProperties(): array
    {
        return $this->properties;
    }

    /**
     * Sets a specific property.
     *
     * @return $this
     */
    public function setProperty(string $name, mixed $value): static
    {
        $this->properties[$name] = $value;

        return $this;
    }

    /**
     * Adds an argument to pass to the service constructor/factory method.
     *
     * @return $this
     */
    public function addArgument(mixed $argument): static
    {
        $this->arguments[] = $argument;

        return $this;
    }

    /**
     * Replaces a specific argument.
     *
     * @return $this
     *
     * @throws OutOfBoundsException When the replaced argument does not exist
     */
    public function replaceArgument(int|string $index, mixed $argument): static
    {
        if (0 === \count($this->arguments)) {
            throw new OutOfBoundsException(sprintf('Cannot replace arguments for class "%s" if none have been configured yet.', $this->class));
        }

        if (\is_int($index) && ($index < 0 || $index > \count($this->arguments) - 1)) {
            throw new OutOfBoundsException(sprintf('The index "%d" is not in the range [0, %d] of the arguments of class "%s".', $index, \count($this->arguments) - 1, $this->class));
        }

        if (!\array_key_exists($index, $this->arguments)) {
            throw new OutOfBoundsException(sprintf('The argument "%s" doesn\'t exist in class "%s".', $index, $this->class));
        }

        $this->arguments[$index] = $argument;

        return $this;
    }

    /**
     * Sets a specific argument.
     *
     * @return $this
     */
    public function setArgument(int|string $key, mixed $value): static
    {
        $this->arguments[$key] = $value;

        return $this;
    }

    /**
     * Gets the arguments to pass to the service constructor/factory method.
     */
    public function getArguments(): array
    {
        return $this->arguments;
    }

    /**
     * Gets an argument to pass to the service constructor/factory method.
     *
     * @throws OutOfBoundsException When the argument does not exist
     */
    public function getArgument(int|string $index): mixed
    {
        if (!\array_key_exists($index, $this->arguments)) {
            throw new OutOfBoundsException(sprintf('The argument "%s" doesn\'t exist in class "%s".', $index, $this->class));
        }

        return $this->arguments[$index];
    }

    /**
     * Sets the methods to call after service initialization.
     *
     * @return $this
     */
    public function setMethodCalls(array $calls = []): static
    {
        $this->calls = [];
        foreach ($calls as $call) {
            $this->addMethodCall($call[0], $call[1], $call[2] ?? false);
        }

        return $this;
    }

    /**
     * Adds a method to call after service initialization.
     *
     * @param string $method       The method name to call
     * @param array  $arguments    An array of arguments to pass to the method call
     * @param bool   $returnsClone Whether the call returns the service instance or not
     *
     * @return $this
     *
     * @throws InvalidArgumentException on empty $method param
     */
    public function addMethodCall(string $method, array $arguments = [], bool $returnsClone = false): static
    {
        if (empty($method)) {
            throw new InvalidArgumentException('Method name cannot be empty.');
        }
        $this->calls[] = $returnsClone ? [$method, $arguments, true] : [$method, $arguments];

        return $this;
    }

    /**
     * Removes a method to call after service initialization.
     *
     * @return $this
     */
    public function removeMethodCall(string $method): static
    {
        foreach ($this->calls as $i => $call) {
            if ($call[0] === $method) {
                unset($this->calls[$i]);
            }
        }

        return $this;
    }

    /**
     * Check if the current definition has a given method to call after service initialization.
     */
    public function hasMethodCall(string $method): bool
    {
        foreach ($this->calls as $call) {
            if ($call[0] === $method) {
                return true;
            }
        }

        return false;
    }

    /**
     * Gets the methods to call after service initialization.
     */
    public function getMethodCalls(): array
    {
        return $this->calls;
    }

    /**
     * Sets the definition templates to conditionally apply on the current definition, keyed by parent interface/class.
     *
     * @param ChildDefinition[] $instanceof
     *
     * @return $this
     */
    public function setInstanceofConditionals(array $instanceof): static
    {
        $this->instanceof = $instanceof;

        return $this;
    }

    /**
     * Gets the definition templates to conditionally apply on the current definition, keyed by parent interface/class.
     *
     * @return ChildDefinition[]
     */
    public function getInstanceofConditionals(): array
    {
        return $this->instanceof;
    }

    /**
     * Sets whether or not instanceof conditionals should be prepended with a global set.
     *
     * @return $this
     */
    public function setAutoconfigured(bool $autoconfigured): static
    {
        $this->changes['autoconfigured'] = true;

        $this->autoconfigured = $autoconfigured;

        return $this;
    }

    public function isAutoconfigured(): bool
    {
        return $this->autoconfigured;
    }

    /**
     * Sets tags for this definition.
     *
     * @return $this
     */
    public function setTags(array $tags): static
    {
        $this->tags = $tags;

        return $this;
    }

    /**
     * Returns all tags.
     */
    public function getTags(): array
    {
        return $this->tags;
    }

    /**
     * Gets a tag by name.
     */
    public function getTag(string $name): array
    {
        return $this->tags[$name] ?? [];
    }

    /**
     * Adds a tag for this definition.
     *
     * @return $this
     */
    public function addTag(string $name, array $attributes = []): static
    {
        $this->tags[$name][] = $attributes;

        return $this;
    }

    /**
     * Whether this definition has a tag with the given name.
     */
    public function hasTag(string $name): bool
    {
        return isset($this->tags[$name]);
    }

    /**
     * Clears all tags for a given name.
     *
     * @return $this
     */
    public function clearTag(string $name): static
    {
        unset($this->tags[$name]);

        return $this;
    }

    /**
     * Clears the tags for this definition.
     *
     * @return $this
     */
    public function clearTags(): static
    {
        $this->tags = [];

        return $this;
    }

    /**
     * Sets a file to require before creating the service.
     *
     * @return $this
     */
    public function setFile(?string $file): static
    {
        $this->changes['file'] = true;

        $this->file = $file;

        return $this;
    }

    /**
     * Gets the file to require before creating the service.
     */
    public function getFile(): ?string
    {
        return $this->file;
    }

    /**
     * Sets if the service must be shared or not.
     *
     * @return $this
     */
    public function setShared(bool $shared): static
    {
        $this->changes['shared'] = true;

        $this->shared = $shared;

        return $this;
    }

    /**
     * Whether this service is shared.
     */
    public function isShared(): bool
    {
        return $this->shared;
    }

    /**
     * Sets the visibility of this service.
     *
     * @return $this
     */
    public function setPublic(bool $boolean): static
    {
        $this->changes['public'] = true;

        $this->public = $boolean;

        return $this;
    }

    /**
     * Whether this service is public facing.
     */
    public function isPublic(): bool
    {
        return $this->public;
    }

    /**
     * Whether this service is private.
     */
    public function isPrivate(): bool
    {
        return !$this->public;
    }

    /**
     * Sets the lazy flag of this service.
     *
     * @return $this
     */
    public function setLazy(bool $lazy): static
    {
        $this->changes['lazy'] = true;

        $this->lazy = $lazy;

        return $this;
    }

    /**
     * Whether this service is lazy.
     */
    public function isLazy(): bool
    {
        return $this->lazy;
    }

    /**
     * Sets whether this definition is synthetic, that is not constructed by the
     * container, but dynamically injected.
     *
     * @return $this
     */
    public function setSynthetic(bool $boolean): static
    {
        $this->synthetic = $boolean;

        if (!isset($this->changes['public'])) {
            $this->setPublic(true);
        }

        return $this;
    }

    /**
     * Whether this definition is synthetic, that is not constructed by the
     * container, but dynamically injected.
     */
    public function isSynthetic(): bool
    {
        return $this->synthetic;
    }

    /**
     * Whether this definition is abstract, that means it merely serves as a
     * template for other definitions.
     *
     * @return $this
     */
    public function setAbstract(bool $boolean): static
    {
        $this->abstract = $boolean;

        return $this;
    }

    /**
     * Whether this definition is abstract, that means it merely serves as a
     * template for other definitions.
     */
    public function isAbstract(): bool
    {
        return $this->abstract;
    }

    /**
     * Whether this definition is deprecated, that means it should not be called
     * anymore.
     *
     * @param string $package The name of the composer package that is triggering the deprecation
     * @param string $version The version of the package that introduced the deprecation
     * @param string $message The deprecation message to use
     *
     * @return $this
     *
     * @throws InvalidArgumentException when the message template is invalid
     */
    public function setDeprecated(string $package, string $version, string $message): static
    {
        if ('' !== $message) {
            if (preg_match('#[\r\n]|\*/#', $message)) {
                throw new InvalidArgumentException('Invalid characters found in deprecation template.');
            }

            if (!str_contains($message, '%service_id%')) {
                throw new InvalidArgumentException('The deprecation template must contain the "%service_id%" placeholder.');
            }
        }

        $this->changes['deprecated'] = true;
        $this->deprecation = ['package' => $package, 'version' => $version, 'message' => $message ?: self::DEFAULT_DEPRECATION_TEMPLATE];

        return $this;
    }

    /**
     * Whether this definition is deprecated, that means it should not be called
     * anymore.
     */
    public function isDeprecated(): bool
    {
        return (bool) $this->deprecation;
    }

    /**
     * @param string $id Service id relying on this definition
     */
    public function getDeprecation(string $id): array
    {
        return [
            'package' => $this->deprecation['package'],
            'version' => $this->deprecation['version'],
            'message' => str_replace('%service_id%', $id, $this->deprecation['message']),
        ];
    }

    /**
     * Sets a configurator to call after the service is fully initialized.
     *
     * @param string|array|Reference|null $configurator A PHP function, reference or an array containing a class/Reference and a method to call
     *
     * @return $this
     */
    public function setConfigurator(string|array|Reference|null $configurator): static
    {
        $this->changes['configurator'] = true;

        if (\is_string($configurator) && str_contains($configurator, '::')) {
            $configurator = explode('::', $configurator, 2);
        } elseif ($configurator instanceof Reference) {
            $configurator = [$configurator, '__invoke'];
        }

        $this->configurator = $configurator;

        return $this;
    }

    /**
     * Gets the configurator to call after the service is fully initialized.
     */
    public function getConfigurator(): string|array|null
    {
        return $this->configurator;
    }

    /**
     * Is the definition autowired?
     */
    public function isAutowired(): bool
    {
        return $this->autowired;
    }

    /**
     * Enables/disables autowiring.
     *
     * @return $this
     */
    public function setAutowired(bool $autowired): static
    {
        $this->changes['autowired'] = true;

        $this->autowired = $autowired;

        return $this;
    }

    /**
     * Gets bindings.
     *
     * @return BoundArgument[]
     */
    public function getBindings(): array
    {
        return $this->bindings;
    }

    /**
     * Sets bindings.
     *
     * Bindings map $named or FQCN arguments to values that should be
     * injected in the matching parameters (of the constructor, of methods
     * called and of controller actions).
     *
     * @return $this
     */
    public function setBindings(array $bindings): static
    {
        foreach ($bindings as $key => $binding) {
            if (0 < strpos($key, '$') && $key !== $k = preg_replace('/[ \t]*\$/', ' $', $key)) {
                unset($bindings[$key]);
                $bindings[$key = $k] = $binding;
            }
            if (!$binding instanceof BoundArgument) {
                $bindings[$key] = new BoundArgument($binding);
            }
        }

        $this->bindings = $bindings;

        return $this;
    }

    /**
     * Add an error that occurred when building this Definition.
     *
     * @return $this
     */
    public function addError(string|\Closure|Definition $error): static
    {
        if ($error instanceof self) {
            $this->errors = array_merge($this->errors, $error->errors);
        } else {
            $this->errors[] = $error;
        }

        return $this;
    }

    /**
     * Returns any errors that occurred while building this Definition.
     */
    public function getErrors(): array
    {
        foreach ($this->errors as $i => $error) {
            if ($error instanceof \Closure) {
                $this->errors[$i] = (string) $error();
            } elseif (!\is_string($error)) {
                $this->errors[$i] = (string) $error;
            }
        }

        return $this->errors;
    }

    public function hasErrors(): bool
    {
        return (bool) $this->errors;
    }
}