package org.apereo.cas.support.saml.idp.metadata;

import org.apereo.cas.couchdb.saml.CouchDbSamlIdPMetadataDocument;
import org.apereo.cas.couchdb.saml.SamlIdPMetadataCouchDbRepository;
import org.apereo.cas.support.saml.idp.metadata.generator.BaseSamlIdPMetadataGenerator;
import org.apereo.cas.support.saml.idp.metadata.generator.SamlIdPMetadataGeneratorConfigurationContext;
import org.apereo.cas.support.saml.services.SamlRegisteredService;
import org.apereo.cas.support.saml.services.idp.metadata.SamlIdPMetadataDocument;

import lombok.SneakyThrows;
import org.apache.commons.lang3.tuple.Pair;

import java.util.Optional;

/**
 * This is {@link CouchDbSamlIdPMetadataGenerator}.
 *
 * @author Timur Duehr
 * @since 6.0.0
 */
public class CouchDbSamlIdPMetadataGenerator extends BaseSamlIdPMetadataGenerator {

    private final SamlIdPMetadataCouchDbRepository couchDb;

    public CouchDbSamlIdPMetadataGenerator(final SamlIdPMetadataGeneratorConfigurationContext context,
                                           final SamlIdPMetadataCouchDbRepository couchDb) {
        super(context);
        this.couchDb = couchDb;
    }

    @Override
    protected SamlIdPMetadataDocument finalizeMetadataDocument(final SamlIdPMetadataDocument doc,
                                                               final Optional<SamlRegisteredService> registeredService) {
        var couchDoc = registeredService.isPresent()
            ? couchDb.getForService(registeredService)
            : couchDb.getForAll();
        if (couchDoc == null) {
            couchDoc = new CouchDbSamlIdPMetadataDocument(doc);
            couchDoc.setAppliesTo(couchDb.getAppliesToFor(registeredService));
            couchDb.add(couchDoc);
        } else {
            couchDb.update(couchDoc.merge(doc));
        }
        return couchDoc;
    }

    @Override
    @SneakyThrows
    public Pair<String, String> buildSelfSignedEncryptionCert(final Optional<SamlRegisteredService> registeredService) {
        return generateCertificateAndKey();
    }

    @Override
    @SneakyThrows
    public Pair<String, String> buildSelfSignedSigningCert(final Optional<SamlRegisteredService> registeredService) {
        return generateCertificateAndKey();
    }
}

{'repo_name': 'apereo/cas', 'stars': '7776', 'repo_language': 'Java', 'file_name': 'CacheStatisticsTests.java', 'mime_type': 'text/x-java', 'hash': 3572950083854587410, 'source_dataset': 'data'}


package eu.modernmt.cleaning.filters;

import eu.modernmt.cleaning.CorpusFilter;
import eu.modernmt.lang.Language;
import org.jetbrains.annotations.NotNull;

import java.util.*;
import java.util.regex.Pattern;

/**
 * Created by davide on 17/11/16.
 */
public class RareNgramFilter implements CorpusFilter {

    private static final int MIN_CORPUS_LINES = 500;
    private static final int MIN_SENTENCE_LENGTH = 30;

    private HashSet<String> words = null;

    @Override
    public Initializer getInitializer() {
        return new Initializer() {

            private final HashMap<String, Counter> map = new HashMap<>();
            private int lines = 0;

            @Override
            public void onBegin() {
                words = null;
            }

            @Override
            public void onLine(Language language, String line, int index) {
                lines++;

                line = normalize(line);

                if (line.length() < MIN_SENTENCE_LENGTH)
                    return;

                for (String token : tokenize(line))
                    map.computeIfAbsent(token, key -> new Counter()).count++;
            }

            @Override
            public void onEnd() {
                words = lines < MIN_CORPUS_LINES ? null : filterCounts(map, .9);
            }

            private HashSet<String> filterCounts(HashMap<String, Counter> vocabulary, double threshold) {
                ArrayList<Entry> entries = new ArrayList<>(vocabulary.size());
                for (Map.Entry<String, Counter> e : vocabulary.entrySet())
                    entries.add(new Entry(e.getKey(), e.getValue().count));

                Collections.sort(entries);
                Collections.reverse(entries);

                double size = 0;
                for (Entry e : entries)
                    size += e.count;

                HashSet<String> result = new HashSet<>();

                double accumulator = 0;
                for (Entry e : entries) {
                    accumulator += e.count;
                    result.add(e.term);

                    if ((accumulator / size) >= threshold)
                        break;
                }

                return result;
            }

        };
    }

    private static final Pattern SKIP_CHARS_REGEX = Pattern.compile("[\\p{Punct}\\s]+");
    private static final Pattern DIGITS_REGEX = Pattern.compile("[0-9]");

    private static String normalize(String line) {
        line = line.toLowerCase();
        line = SKIP_CHARS_REGEX.matcher(line).replaceAll("");
        line = DIGITS_REGEX.matcher(line).replaceAll("0");
        return line;
    }

    private static String[] tokenize(String string) {
        int length = string.length();
        if (length < 3)
            return new String[0];

        int size = length - length % 3 - 2;

        String[] result = new String[size];

        if (size > 0) {
            for (int i = 0; i < size; i++)
                result[i] = string.substring(i, i + 3);
        }

        return result;
    }

    @Override
    public boolean accept(Language language, String line, int index) {
        if (words == null)
            return true;

        line = normalize(line);

        if (line.length() < MIN_SENTENCE_LENGTH)
            return true;

        return match(line) >= .3;
    }

    private double match(String line) {
        int matches = 0;
        int length = 0;

        for (String token : tokenize(line)) {
            length++;
            if (words.contains(token))
                matches++;
        }

        return matches / ((double) length);
    }

    @Override
    public void clear() {
        words = null;
    }

    private static final class Counter {

        public long count = 0;

    }

    private static final class Entry implements Comparable<Entry> {

        public final String term;
        public final long count;

        public Entry(String term, long count) {
            this.term = term;
            this.count = count;
        }

        @Override
        public int compareTo(@NotNull Entry o) {
            return Long.compare(count, o.count);
        }

        @Override
        public String toString() {
            return term + '(' + count + ')';
        }
    }

}

{'repo_name': 'modernmt/modernmt', 'stars': '202', 'repo_language': 'Java', 'file_name': 'newversion', 'mime_type': 'text/x-shellscript', 'hash': 7743473158335487218, 'source_dataset': 'data'}


// Copyright (c) 2016, 2018, 2020, Oracle and/or its affiliates.  All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.

package cloudguard

import (
	"github.com/oracle/oci-go-sdk/v25/common"
	"net/http"
)

// GetManagedListRequest wrapper for the GetManagedList operation
type GetManagedListRequest struct {

	// The cloudguard list OCID to be passed in the request.
	ManagedListId *string `mandatory:"true" contributesTo:"path" name:"managedListId"`

	// The client request ID for tracing.
	OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`

	// Metadata about the request. This information will not be transmitted to the service, but
	// represents information that the SDK will consume to drive retry behavior.
	RequestMetadata common.RequestMetadata
}

func (request GetManagedListRequest) String() string {
	return common.PointerString(request)
}

// HTTPRequest implements the OCIRequest interface
func (request GetManagedListRequest) HTTPRequest(method, path string) (http.Request, error) {
	return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}

// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request GetManagedListRequest) RetryPolicy() *common.RetryPolicy {
	return request.RequestMetadata.RetryPolicy
}

// GetManagedListResponse wrapper for the GetManagedList operation
type GetManagedListResponse struct {

	// The underlying http response
	RawResponse *http.Response

	// The ManagedList instance
	ManagedList `presentIn:"body"`

	// Unique Oracle-assigned identifier for the request. If you need to contact
	// Oracle about a particular request, please provide the request ID.
	OpcRequestId *string `presentIn:"header" name:"opc-request-id"`

	// For optimistic concurrency control. See `if-match`.
	Etag *string `presentIn:"header" name:"etag"`
}

func (response GetManagedListResponse) String() string {
	return common.PointerString(response)
}

// HTTPResponse implements the OCIResponse interface
func (response GetManagedListResponse) HTTPResponse() *http.Response {
	return response.RawResponse
}

{'repo_name': 'terraform-providers/terraform-provider-oci', 'stars': '349', 'repo_language': 'Go', 'file_name': 'identity_auth_token_resource.go', 'mime_type': 'text/plain', 'hash': 3332549604244855812, 'source_dataset': 'data'}


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Error</title>
</head>
<body>

An error has occurred. Retry later.<br/>
If the problems persists, contact the system administrator.

</body>
</html>

{'repo_name': 'KnowageLabs/Knowage-Server', 'stars': '244', 'repo_language': 'Java', 'file_name': 'AbstractModelEditingTest.java', 'mime_type': 'text/x-java', 'hash': 970053822169232720, 'source_dataset': 'data'}


/*
 * ModeShape (http://www.modeshape.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.modeshape.common.collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * A {@link Multimap} implementation that uses an {@link ArrayList} to store the values associated with a key. This implementation
 * allows duplicates and the values are ordered.
 *
 * @param <K> the key type
 * @param <V> the value type
 */
public class ArrayListMultimap<K, V> extends AbstractMultimap<K, V> implements ListMultimap<K, V> {

    /**
     * Creates a new, empty {@code LinkedHashMultimap} (that allows no duplicates) with the default initial capacity.
     *
     * @param <K> the key type
     * @param <V> the value type
     * @return the new linked-hash multimap; never null
     */
    public static <K, V> ArrayListMultimap<K, V> create() {
        return new ArrayListMultimap<K, V>();
    }

    protected ArrayListMultimap() {
        super(new HashMap<K, Collection<V>>());
    }

    @Override
    protected Collection<V> createCollection() {
        return new ArrayList<V>();
    }

    @Override
    protected Collection<V> createUnmodifiableEmptyCollection() {
        return Collections.emptyList();
    }

    @Override
    public List<V> get( K key ) {
        return (List<V>)super.get(key);
    }
}

{'repo_name': 'ModeShape/modeshape', 'stars': '208', 'repo_language': 'Java', 'file_name': 'README.md', 'mime_type': 'text/plain', 'hash': 5520432890284580016, 'source_dataset': 'data'}


/*
 * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

namespace TencentCloud.Bmvpc.V20180625.Models
{
    using Newtonsoft.Json;
    using System.Collections.Generic;
    using TencentCloud.Common;

    public class DeleteVpcRequest : AbstractModel
    {

        /// <summary>
        /// VPC实例ID。可通过DescribeVpcs接口返回值中的VpcId获取。
        /// </summary>
        [JsonProperty("VpcId")]
        public string VpcId{ get; set; }

        /// <summary>
        /// For internal usage only. DO NOT USE IT.
        /// </summary>
        internal override void ToMap(Dictionary<string, string> map, string prefix)
        {
            this.SetParamSimple(map, prefix + "VpcId", this.VpcId);
        }
    }
}

{'repo_name': 'TencentCloud/tencentcloud-sdk-dotnet', 'stars': '235', 'repo_language': 'C#', 'file_name': 'Resources.Designer.cs', 'mime_type': 'text/plain', 'hash': -1222506300232229643, 'source_dataset': 'data'}


// RUN: %clang_cc1 -analyze -analyzer-store=region -analyzer-constraints=range -fblocks -analyzer-opt-analyze-nested-blocks -analyzer-checker=alpha.deadcode.IdempotentOperations -verify %s

// C++ specific false positives

extern void test(int i);
extern void test_ref(int &i);

// Test references affecting pseudoconstants
void false1() {
  int a = 0;
  int five = 5;
  int &b = a;
   test(five * a); // expected-warning {{The right operand to '*' is always 0}}
   b = 4;
}

// Test not flagging idempotent operations because we aborted the analysis
// of a path because of an unsupported construct.
struct RDar9219143_Foo {
  ~RDar9219143_Foo();
  operator bool() const;
};

RDar9219143_Foo foo();
unsigned RDar9219143_bar();
void RDar9219143_test() {
  unsigned i, e;
  for (i = 0, e = RDar9219143_bar(); i != e; ++i)
    if (foo())
      break;
  if (i == e) // no-warning
    return;
}

{'repo_name': 'KhronosGroup/SPIR', 'stars': '164', 'repo_language': 'C++', 'file_name': '__init__.py', 'mime_type': 'text/plain', 'hash': -4087904387918330704, 'source_dataset': 'data'}


# Batch Normalization

##  Internal Covariate Shift
### Definition
The change in the distribution of network activations due to the change in networkparameters during training.

### Why is this a problem?
Because the layers need to continuously adapt to the new distribution.

## Batch Normalization
### Basic Idea
Whitening the activation of each layer so that the activation of each layer is always normal distributed, so the next layer don't need to learn new distribution.

### Algorithm
- Training

- Testing

Using the mean and variance statistics during training so that each layer's output only depends on its input.

### Explaination
- The `normalize step` (third equation) ensures that the mean and variance of output activations are the same during training.
- The `scale and shift step` (fourth equation) gives Batch Normalization the ability to `undo` the normalization. For instance, if
 Then we can recover the original activations.
- For fully-connected layers, normalization is done in every dimension of **x**, while in convolutional layers, normalization is done in each feature map. That means, there is one pair of *γ(k)* and *β(k)* for each feature map. This makes activations whithin the same feature map normalized in the same way, with respect to what convolution does.

## Advantages of Batch Normalization
- Enables higher learning rate: BN helps to amplify small changes into larger and suboptimal changes in activations in gradients as well as stabilize the parameter growth.
- Less careful about initialization
- Eliminate or reduce Dropout

## Reference
Ioffe S, Szegedy C. Batch normalization: Accelerating deep network training by reducing internal covariate shift[J]. arXiv preprint arXiv:1502.03167, 2015.

{'repo_name': 'sunshineatnoon/Paper-Collection', 'stars': '190', 'repo_language': 'None', 'file_name': 'deepvideocolorprop.md', 'mime_type': 'text/plain', 'hash': -6155600325799049017, 'source_dataset': 'data'}


<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>robo.acquisition_functions.integrated_acquisition — Robo API 1 documentation</title>

    <link rel="stylesheet" href="../../../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../../genindex.html" />
    <link rel="search" title="Search" href="../../../search.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

          RoBO
        0.2.0

Start

Installation

Tutorial

APIs

Contact

  Site

Installation

Tutorials

APIs

Examples

Contact

<form class="navbar-form navbar-right" action="../../../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Source code for robo.acquisition_functions.integrated_acquisition

import logging
import numpy as np

from copy import deepcopy
from robo.acquisition_functions.base_acquisition import BaseAcquisitionFunction

logger = logging.getLogger(__name__)

[docs]class IntegratedAcquisition(BaseAcquisitionFunction):

    def __init__(self, model, acquisition_func,
                 X_lower, X_upper, cost_model=None, is_dngo=False):
        '''
        Meta acquisition_functions function that allows to marginalise the
        acquisition_functions function over GP hyperparameter.

        Parameters
        ----------
        model: Model object
            The model of the objective function, it has to be an instance of
            GaussianProcessMCMC or GPyModelMCMC.
        acquisition_func: BaseAcquisitionFunction object
            The acquisition_functions function that will be integrated.
        cost_model: Model object
            If the acquisition_functions function also takes the cost into account, we
            have to specify here the model for the cost function. cost_model
            has to be an instance of GaussianProcessMCMC or GPyModelMCMC.
        is_dngo: boolean
            If you use DNGO as model set this flag to true in order to
            apply first the basis functions to the input data point
        '''

        self.model = model
        self.is_dngo = is_dngo

        # Save also the cost model if the acquisition_functions function needs it
        if cost_model is not None:

            self.cost_model = cost_model

        # Keep for each model an extra acquisition_functions function module
        self.estimators = []
        for _ in range(self.model.n_hypers):
            # Copy the acquisition_functions function for this model
            estimator = deepcopy(acquisition_func)
            estimator.model = None
            if cost_model is not None:
                estimator.cost_model = None
            self.estimators.append(estimator)

        super(IntegratedAcquisition, self).__init__(model, X_lower, X_upper)

[docs]    def update(self, model, cost_model=None, **kwargs):
        """
        Updates each acquisition_functions function object if the models
        have changed

        Parameters
        ----------
        model: Model object
            The model of the objective function, it has to be an instance of
            GaussianProcessMCMC or GPyModelMCMC.
        cost_model: Model object
            If the acquisition_functions function also takes the cost into account, we
            have to specify here the model for the cost function. cost_model
            has to be an instance of GaussianProcessMCMC or GPyModelMCMC.
        """

        self.model = model
        if cost_model is not None:
            self.cost_model = cost_model
        for i in range(self.model.n_hypers):
            if cost_model is not None:
                self.estimators[i].update(self.model.models[i],
                                          self.cost_model.models[i],
                                          **kwargs)
            else:
                self.estimators[i].update(self.model.models[i], **kwargs)

[docs]    def compute(self, X, derivative=False):
        """
        Integrates the acquisition_functions function over the GP's hyperparameters by
        averaging the acquisition_functions value for X of each hyperparameter sample.

        Parameters
        ----------
        X: np.ndarray(1, D), The input point where the acquisition_functions function
            should be evaluate. The dimensionality of X is (N, D), with N as
            the number of points to evaluate at and D is the number of
            dimensions of one X.

        derivative: Boolean
            If is set to true also the derivative of the acquisition_functions
            function at X is returned

        Returns
        -------
        np.ndarray(1,1)
            Integrated acquisition_functions value of X
        np.ndarray(1,D)
            Derivative of the acquisition_functions value at X (only if derivative=True)
        """
        acquisition_values = np.zeros([self.model.n_hypers])

        if self.is_dngo:
            import lasagne
            X_ = (X - self.model.X_mean) / self.model.X_std

            # Get features from the net
            layers = lasagne.layers.get_all_layers(self.model.network)
            theta = lasagne.layers.get_output(layers[:-1], X_)[-1].eval()
        else:
            theta = X

        # Integrate over the acquisition_functions values
        for i in range(self.model.n_hypers):
            acquisition_values[i] = self.estimators[i](theta,
                                                    derivative=derivative)

        return np.array([[acquisition_values.mean()]])

      Back to top

        © Copyright 2017, AAD Group.

      Created using Sphinx 1.6.1.

{'repo_name': 'automl/RoBO', 'stars': '387', 'repo_language': 'Python', 'file_name': 'test_information_gain_per_unit_cost.py', 'mime_type': 'text/x-python', 'hash': -4516507493461945324, 'source_dataset': 'data'}


// Leica Scope Families
// These need slightly different commands here and there
const int g_DMI456 = 0;
const int g_CTRMIC = 1;

// List of Device numbers (from Leica documentation)
const int g_AFC = 48; // adaptive focus control / autofocus
const int g_Fast_Filter_Wheel = 54; // fast filter wheel with 5 positions
const int g_Mirror_House = 55; // motorized with 2 positions
const int g_MA4_Mirror = 56; // flapping mirror for MA4
const int g_TL_Arm = 58; // general settings
const int g_Side_Port = 59; // Fixed prism or motorized prism with 4 positions
const int g_Bottom_Port = 60; // motorized with 2 positions
const int g_Flapping_Filter_1 = 61;
const int g_Flapping_Filter_2 = 62;
const int g_Dark_Flap_Tl = 63;
const int g_Constant_Color_Intensity_Control_Il = 64; // 12 bits
const int g_Master = 70; // DMI
const int g_ZDrive = 71; // motorized
const int g_XDrive = 72; // motorized
const int g_YDrive = 73; // motorized
const int g_Microscope_Buttons = 74;
const int g_Microscope_Display = 75;
const int g_Revolver = 76; //motorized, encoded 6 positions
const int g_Lamp = 77; // 12 bits
const int g_IL_Turret = 78; // motorized, 6 positions
const int g_Mag_Changer_Mot = 79; // motorized magnifictaion changer with 4 positions
const int g_Tube = 80; // fixed or non-coded switching tube
const int g_Flapping_Condenser = 81; // motorized with 7 positions
const int g_Condensor = 82; // motorized with 7 positions
const int g_Field_Diaphragm_TL = 83; // motorized iris diaphragm
const int g_Aperture_Diaphragm_TL = 84; // mptorized iris diaphragm in the condenser
const int g_DIC_Turret = 85; // motorized DIC disk with 4 positions
const int g_Z_Handwheel = 86;
const int g_Field_Diaphragm_IL = 94; // motorized with maximum 12 positions
const int g_Aperture_Diaphragm_IL = 95; // motorized diaphragm disk with maximum 12 positions
const int g_Constant_Color_Intensity_Control_TL = 97; // 12 bits
const int g_TL_Polarizer = 98; // motorizedin the condenser

//////////////////////////////////////////////////////////////////////////////
// Error codes
//
#define COM_ERR         999
#define ID_ERR          998
#define FUI_ERR         997
#define ERR_UNKNOWN_POSITION         10002
#define ERR_INVALID_SPEED            10003
#define ERR_PORT_CHANGE_FORBIDDEN    10004
#define ERR_SET_POSITION_FAILED      10005
#define ERR_INVALID_STEP_SIZE        10006
#define ERR_INVALID_MODE             10008
#define ERR_CANNOT_CHANGE_PROPERTY   10009
#define ERR_UNEXPECTED_ANSWER        10010
#define ERR_INVALID_TURRET           10011
#define ERR_SCOPE_NOT_ACTIVE         10012
#define ERR_INVALID_TURRET_POSITION  10013
#define ERR_MODULE_NOT_FOUND         10014
#define ERR_ANSWER_TIMEOUT           10015
#define ERR_PORT_NOT_OPEN            10016
#define ERR_TURRET_NOT_ENGAGED       10017
#define ERR_MAGNIFIER_NOT_ENGAGED    10018

{'repo_name': 'micro-manager/micro-manager', 'stars': '104', 'repo_language': 'C++', 'file_name': 'upload_file.php', 'mime_type': 'text/x-php', 'hash': -9157785086709071679, 'source_dataset': 'data'}


From: Alexander Duyck <alexander.h.duyck@redhat.com>
Date: Wed, 31 Dec 2014 10:56:06 -0800
Subject: [PATCH] fib_trie: Optimize fib_table_insert

This patch updates the fib_table_insert function to take advantage of the
changes made to improve the performance of fib_table_lookup.  As a result
the code should be smaller and run faster then the original.

Signed-off-by: Alexander Duyck <alexander.h.duyck@redhat.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
---

--- a/net/ipv4/fib_trie.c
+++ b/net/ipv4/fib_trie.c
@@ -222,31 +222,6 @@ static inline t_key tkey_extract_bits(t_
 		return 0;
 }

-static inline int tkey_equals(t_key a, t_key b)
-{
-	return a == b;
-}
-
-static inline int tkey_sub_equals(t_key a, int offset, int bits, t_key b)
-{
-	if (bits == 0 || offset >= KEYLENGTH)
-		return 1;
-	bits = bits > KEYLENGTH ? KEYLENGTH : bits;
-	return ((a ^ b) << offset) >> (KEYLENGTH - bits) == 0;
-}
-
-static inline int tkey_mismatch(t_key a, int offset, t_key b)
-{
-	t_key diff = a ^ b;
-	int i = offset;
-
-	if (!diff)
-		return 0;
-	while ((diff << i) >> (KEYLENGTH-1) == 0)
-		i++;
-	return i;
-}
-
 /*
   To understand this stuff, an understanding of keys and all their bits is
   necessary. Every node in the trie has a key associated with it, but not
@@ -485,6 +460,15 @@ static void tnode_put_child_reorg(struct
 	rcu_assign_pointer(tn->child[i], n);
 }

+static void put_child_root(struct tnode *tp, struct trie *t,
+			   t_key key, struct tnode *n)
+{
+	if (tp)
+		put_child(tp, get_index(key, tp), n);
+	else
+		rcu_assign_pointer(t->trie, n);
+}
+
 #define MAX_WORK 10
 static struct tnode *resize(struct trie *t, struct tnode *tn)
 {
@@ -959,138 +943,100 @@ static void trie_rebalance(struct trie *

 static struct list_head *fib_insert_node(struct trie *t, u32 key, int plen)
 {
-	int pos, newpos;
-	struct tnode *tp = NULL, *tn = NULL;
-	struct tnode *n;
-	struct tnode *l;
-	int missbit;
 	struct list_head *fa_head = NULL;
+	struct tnode *l, *n, *tp = NULL;
 	struct leaf_info *li;
-	t_key cindex;

-	pos = 0;
+	li = leaf_info_new(plen);
+	if (!li)
+		return NULL;
+	fa_head = &li->falh;
+
 	n = rtnl_dereference(t->trie);

 	/* If we point to NULL, stop. Either the tree is empty and we should
 	 * just put a new leaf in if, or we have reached an empty child slot,
 	 * and we should just put our new leaf in that.
-	 * If we point to a T_TNODE, check if it matches our key. Note that
-	 * a T_TNODE might be skipping any number of bits - its 'pos' need
-	 * not be the parent's 'pos'+'bits'!
-	 *
-	 * If it does match the current key, get pos/bits from it, extract
-	 * the index from our key, push the T_TNODE and walk the tree.
-	 *
-	 * If it doesn't, we have to replace it with a new T_TNODE.
 	 *
-	 * If we point to a T_LEAF, it might or might not have the same key
-	 * as we do. If it does, just change the value, update the T_LEAF's
-	 * value, and return it.
-	 * If it doesn't, we need to replace it with a T_TNODE.
+	 * If we hit a node with a key that does't match then we should stop
+	 * and create a new tnode to replace that node and insert ourselves
+	 * and the other node into the new tnode.
 	 */
+	while (n) {
+		unsigned long index = get_index(key, n);

-	while (n && IS_TNODE(n)) {
-		if (tkey_sub_equals(n->key, pos, n->pos-pos, key)) {
-			tp = n;
-			pos = n->pos + n->bits;
-			n = tnode_get_child(n,
-					    tkey_extract_bits(key,
-							      n->pos,
-							      n->bits));
-
-			BUG_ON(n && node_parent(n) != tp);
-		} else
+		/* This bit of code is a bit tricky but it combines multiple
+		 * checks into a single check.  The prefix consists of the
+		 * prefix plus zeros for the "bits" in the prefix. The index
+		 * is the difference between the key and this value.  From
+		 * this we can actually derive several pieces of data.
+		 *   if !(index >> bits)
+		 *     we know the value is child index
+		 *   else
+		 *     we have a mismatch in skip bits and failed
+		 */
+		if (index >> n->bits)
 			break;
-	}
-
-	/*
-	 * n  ----> NULL, LEAF or TNODE
-	 *
-	 * tp is n's (parent) ----> NULL or TNODE
-	 */

-	BUG_ON(tp && IS_LEAF(tp));
-
-	/* Case 1: n is a leaf. Compare prefixes */
-
-	if (n != NULL && IS_LEAF(n) && tkey_equals(key, n->key)) {
-		li = leaf_info_new(plen);
-
-		if (!li)
-			return NULL;
+		/* we have found a leaf. Prefixes have already been compared */
+		if (IS_LEAF(n)) {
+			/* Case 1: n is a leaf, and prefixes match*/
+			insert_leaf_info(&n->list, li);
+			return fa_head;
+		}

-		fa_head = &li->falh;
-		insert_leaf_info(&n->list, li);
-		goto done;
+		tp = n;
+		n = rcu_dereference_rtnl(n->child[index]);
 	}
-	l = leaf_new(key);
-
-	if (!l)
-		return NULL;

-	li = leaf_info_new(plen);
-
-	if (!li) {
-		node_free(l);
+	l = leaf_new(key);
+	if (!l) {
+		free_leaf_info(li);
 		return NULL;
 	}

-	fa_head = &li->falh;
 	insert_leaf_info(&l->list, li);

-	if (t->trie && n == NULL) {
-		/* Case 2: n is NULL, and will just insert a new leaf */
-
-		node_set_parent(l, tp);
-
-		cindex = tkey_extract_bits(key, tp->pos, tp->bits);
-		put_child(tp, cindex, l);
-	} else {
-		/* Case 3: n is a LEAF or a TNODE and the key doesn't match. */
-		/*
-		 *  Add a new tnode here
-		 *  first tnode need some special handling
-		 */
+	/* Case 2: n is a LEAF or a TNODE and the key doesn't match.
+	 *
+	 *  Add a new tnode here
+	 *  first tnode need some special handling
+	 *  leaves us in position for handling as case 3
+	 */
+	if (n) {
+		struct tnode *tn;
+		int newpos;

-		if (n) {
-			pos = tp ? tp->pos+tp->bits : 0;
-			newpos = tkey_mismatch(key, pos, n->key);
-			tn = tnode_new(n->key, newpos, 1);
-		} else {
-			newpos = 0;
-			tn = tnode_new(key, newpos, 1); /* First tnode */
-		}
+		newpos = KEYLENGTH - __fls(n->key ^ key) - 1;

+		tn = tnode_new(key, newpos, 1);
 		if (!tn) {
 			free_leaf_info(li);
 			node_free(l);
 			return NULL;
 		}

-		node_set_parent(tn, tp);
-
-		missbit = tkey_extract_bits(key, newpos, 1);
-		put_child(tn, missbit, l);
-		put_child(tn, 1-missbit, n);
-
-		if (tp) {
-			cindex = tkey_extract_bits(key, tp->pos, tp->bits);
-			put_child(tp, cindex, tn);
-		} else {
-			rcu_assign_pointer(t->trie, tn);
-		}
+		/* initialize routes out of node */
+		NODE_INIT_PARENT(tn, tp);
+		put_child(tn, get_index(key, tn) ^ 1, n);
+
+		/* start adding routes into the node */
+		put_child_root(tp, t, key, tn);
+		node_set_parent(n, tn);

+		/* parent now has a NULL spot where the leaf can go */
 		tp = tn;
 	}

-	if (tp && tp->pos + tp->bits > 32)
-		pr_warn("fib_trie tp=%p pos=%d, bits=%d, key=%0x plen=%d\n",
-			tp, tp->pos, tp->bits, key, plen);
-
-	/* Rebalance the trie */
+	/* Case 3: n is NULL, and will just insert a new leaf */
+	if (tp) {
+		NODE_INIT_PARENT(l, tp);
+		put_child(tp, get_index(key, tp), l);
+		trie_rebalance(t, tp);
+	} else {
+		rcu_assign_pointer(t->trie, l);
+	}

-	trie_rebalance(t, tp);
-done:
 	return fa_head;
 }

@@ -1470,11 +1416,11 @@ static void trie_leaf_remove(struct trie
 	pr_debug("entering trie_leaf_remove(%p)\n", l);

 	if (tp) {
-		t_key cindex = tkey_extract_bits(l->key, tp->pos, tp->bits);
-		put_child(tp, cindex, NULL);
+		put_child(tp, get_index(l->key, tp), NULL);
 		trie_rebalance(t, tp);
-	} else
+	} else {
 		RCU_INIT_POINTER(t->trie, NULL);
+	}

 	node_free(l);
 }

{'repo_name': 'openwrt/chaos_calmer', 'stars': '102', 'repo_language': 'C', 'file_name': 'Makefile', 'mime_type': 'text/plain', 'hash': 6159150647540553754, 'source_dataset': 'data'}


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">

<meta name="generator" content="JDiff v1.1.0">

<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
Method Changes Index
</TITLE>
<link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" />

    Filter the Index:

All Methods

Removals

Additions

Changes

Listed as: Added,  Removed,  Changed

G
L
S
 TOP

<nobr>getReferrer
(Activity)</nobr>

L
G
S
 TOP

<nobr>launchUrl
(Context, Uri)</nobr>

S
G
L
 TOP

<nobr>startActivity
(Context, Intent, Bundle)</nobr>

{'repo_name': 'ResurrectionRemix/android_frameworks_base', 'stars': '101', 'repo_language': 'Java', 'file_name': 'NsdServiceInfo.java', 'mime_type': 'text/x-java', 'hash': 4456948334610635479, 'source_dataset': 'data'}


#pragma warning disable
using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;
using Dev2.Activities.Debug;
using Dev2.Common.ExtMethods;
using Dev2.Common.Interfaces.Diagnostics.Debug;
using Dev2.Common.Interfaces.Enums;
using Dev2.Common.Interfaces.Toolbox;
using Dev2.Common.State;
using Dev2.Data;
using Dev2.Data.TO;
using Dev2.DataList.Contract;
using Dev2.Development.Languages.Scripting;
using Dev2.Diagnostics;
using Dev2.Interfaces;
using Dev2.Util;
using Microsoft.CSharp.RuntimeBinder;
using Unlimited.Applications.BusinessDesignStudio.Activities;
using Unlimited.Applications.BusinessDesignStudio.Activities.Utilities;
using Warewolf.Core;
using Warewolf.Resource.Errors;
using Warewolf.Storage.Interfaces;

namespace Dev2.Activities.Scripting
{
    /// <summary>
    /// Activity used for executing JavaScript through a tool
    /// </summary>
    [ToolDescriptorInfo("Scripting-JavaScript", "JavaScript", ToolType.Native, "B857B914-216D-49A2-83D3-225EC622FB47", "Dev2.Activities", "1.0.0.0", "Legacy", "Scripting", "/Warewolf.Studio.Themes.Luna;component/Images.xaml", "Tool_Javascript")]
    public class DsfJavascriptActivity : DsfActivityAbstract<string>, IEquatable<DsfJavascriptActivity>
    {
        public DsfJavascriptActivity()
            : base("JavaScript")
        {
            ScriptType = enScriptType.JavaScript;
            _sources = new StringScriptSources();
            Script = string.Empty;
            Result = string.Empty;
            EscapeScript = true;
            IncludeFile = "";
        }

        [FindMissing]
        [Inputs("Script")]
        public string Script { get; set; }

        public enScriptType ScriptType { get; set; }

        [Inputs("EscapeScript")]
        public bool EscapeScript { get; set; }

        [FindMissing]
        [Outputs("Result")]
        public new string Result { get; set; }

        [FindMissing]
        [Inputs("IncludeFile")]
        public string IncludeFile { get; set; }

        readonly IStringScriptSources _sources;

        public override IEnumerable<StateVariable> GetState()
        {
            return new[] {
                new StateVariable
                {
                    Name = "Script",
                    Value = Script,
                    Type = StateVariable.StateType.Input
                },
                 new StateVariable
                {
                    Name = "IncludeFile",
                    Value = IncludeFile,
                    Type = StateVariable.StateType.Input
                },
                 new StateVariable
                {
                    Name = "EscapeScript",
                    Value = EscapeScript.ToString(),
                    Type = StateVariable.StateType.Input
                },
                new StateVariable
                {
                    Name="Result",
                    Value = Result,
                    Type = StateVariable.StateType.Output
                }
            };
        }

        #region Overrides of DsfNativeActivity<string>

        /// <summary>
        /// When overridden runs the activity's execution logic
        /// </summary>
        /// <param name="context">The context to be used.</param>
        protected override void OnExecute(NativeActivityContext context)
        {
            var dataObject = context.GetExtension<IDSFDataObject>();
            ExecuteTool(dataObject, 0);
        }

        protected override void ExecuteTool(IDSFDataObject dataObject, int update)
        {
            AddScriptSourcePathsToList();
            var allErrors = new ErrorResultTO();
            var env = dataObject.Environment;
            InitializeDebug(dataObject);
            try
            {

                if (dataObject.IsDebugMode())
                {
                    var language = ScriptType.GetDescription();
                    AddDebugInputItem(new DebugItemStaticDataParams(language, "Language"));
                    AddDebugInputItem(new DebugEvalResult(Script, "Script", env, update));
                }

                TryExecute(dataObject, update, allErrors, env);
            }
            catch (Exception e) when (e is NullReferenceException || e is RuntimeBinderException)
            {
                allErrors.AddError(e.GetType() == typeof(NullReferenceException) || e.GetType() == typeof(RuntimeBinderException) ? ErrorResource.ScriptingErrorReturningValue : e.Message.Replace(" for main:Object", string.Empty));
            }
            finally
            {
                // Handle Errors
                if (allErrors.HasErrors())
                {
                    DisplayAndWriteError("DsfScriptingJavaScriptActivity", allErrors);
                    var errorString = allErrors.MakeDisplayReady();
                    dataObject.Environment.AddError(errorString);
                }

                if (dataObject.IsDebugMode())
                {
                    if (allErrors.HasErrors())
                    {
                        AddDebugOutputItem(new DebugItemStaticDataParams("", Result, ""));
                    }
                    DispatchDebugState(dataObject, StateType.Before, update);
                    DispatchDebugState(dataObject, StateType.After, update);
                }
            }
        }

        private void TryExecute(IDSFDataObject dataObject, int update, ErrorResultTO allErrors, IExecutionEnvironment env)
        {
            var scriptItr = new WarewolfIterator(dataObject.Environment.Eval(Script, update, false, EscapeScript));
            while (scriptItr.HasMoreData())
            {
                var engine = new ScriptingEngineRepo().CreateEngine(ScriptType, _sources);
                var value = engine.Execute(scriptItr.GetNextValue());

                foreach (var region in DataListCleaningUtils.SplitIntoRegions(Result))
                {

                    env.Assign(region, value, update);
                    if (dataObject.IsDebugMode() && !allErrors.HasErrors() && !string.IsNullOrEmpty(region))
                    {
                        AddDebugOutputItem(new DebugEvalResult(region, "", env, update));
                    }

                }
            }
        }

        void AddScriptSourcePathsToList()
        {
            if (!string.IsNullOrEmpty(IncludeFile))
            {
                _sources.AddPaths(IncludeFile);
            }
        }
        public override void UpdateForEachInputs(IList<Tuple<string, string>> updates)
        {
            foreach (Tuple<string, string> t in updates)
            {
                if (t.Item1 == Script)
                {
                    Script = t.Item2;
                }
            }
        }

        public override void UpdateForEachOutputs(IList<Tuple<string, string>> updates)
        {
            var itemUpdate = updates?.FirstOrDefault(tuple => tuple.Item1 == Result);
            if (itemUpdate != null)
            {
                Result = itemUpdate.Item2;
            }
        }

        #endregion

        public override List<string> GetOutputs() => new List<string> { Result };

        #region Get Debug Inputs/Outputs

        public override List<DebugItem> GetDebugInputs(IExecutionEnvironment env, int update)
        {
            foreach (IDebugItem debugInput in _debugInputs)
            {
                debugInput.FlushStringBuilder();
            }
            return _debugInputs;
        }

        public override List<DebugItem> GetDebugOutputs(IExecutionEnvironment env, int update)
        {
            foreach (IDebugItem debugOutput in _debugOutputs)
            {
                debugOutput.FlushStringBuilder();
            }
            return _debugOutputs;
        }

        #endregion Get Debug Inputs/Outputs

        #region GetForEachInputs/Outputs

        public override IList<DsfForEachItem> GetForEachInputs() => GetForEachItems(Script);

        public override IList<DsfForEachItem> GetForEachOutputs() => GetForEachItems(Result);

        #endregion GetForEachInputs/Outputs

        public bool Equals(DsfJavascriptActivity other)
        {
            if (ReferenceEquals(null, other))
            {
                return false;
            }

            if (ReferenceEquals(this, other))
            {
                return true;
            }

            return base.Equals(other)
                && string.Equals(Script, other.Script)
                && ScriptType == other.ScriptType
                && EscapeScript == other.EscapeScript
                && string.Equals(Result, other.Result)
                && string.Equals(IncludeFile, other.IncludeFile);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }

            if (ReferenceEquals(this, obj))
            {
                return true;
            }

            if (obj.GetType() != this.GetType())
            {
                return false;
            }

            return Equals((DsfJavascriptActivity)obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = base.GetHashCode();
                hashCode = (hashCode * 397) ^ (_sources != null ? _sources.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (Script != null ? Script.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (int)ScriptType;
                hashCode = (hashCode * 397) ^ EscapeScript.GetHashCode();
                hashCode = (hashCode * 397) ^ (Result != null ? Result.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (DisplayName != null ? DisplayName.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (IncludeFile != null ? IncludeFile.GetHashCode() : 0);
                return hashCode;
            }
        }
    }
}

{'repo_name': 'Warewolf-ESB/Warewolf', 'stars': '227', 'repo_language': 'C#', 'file_name': 'testElasticsearchSource.xml', 'mime_type': 'text/plain', 'hash': 2897367380144795969, 'source_dataset': 'data'}


using Core.DataAccess.MongoDb.Abstract;
using Core.DataAccess.MongoDb.Concrete.Models;
using Microsoft.EntityFrameworkCore;
using MongoDB.Bson;
using MongoDB.Driver;
using Org.BouncyCastle.Operators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Core.DataAccess.MongoDb.Abstract
{
    public abstract class MongoDbRepositoryBase<T> : IMongoDbRepository<T> where T : MongoBaseEntity
    {
        private readonly IMongoCollection<T> _collection;
        protected string collectionName;
        protected MongoDbRepositoryBase(MongoConnectionSettings mongoConnectionSetting, string collectionName)
        {
            ConnectionSettingControl(mongoConnectionSetting);

            MongoClient client = mongoConnectionSetting.GetMongoClientSettings() == null ?
                 new MongoClient(mongoConnectionSetting.ConnectionString) :
                 new MongoClient(mongoConnectionSetting.GetMongoClientSettings());

            this.collectionName = collectionName;

            var database = client.GetDatabase(mongoConnectionSetting.DatabaseName);
            _collection = database.GetCollection<T>(collectionName);

        }

        public virtual void Delete(ObjectId id)
        {
            _collection.FindOneAndDelete(x => x.Id==id);
        }

        public virtual void Delete(T record)
        {
            _collection.FindOneAndDelete(x => x.Id == record.Id);
        }

        public virtual async Task DeleteAsync(ObjectId id)
        {
            await _collection.FindOneAndDeleteAsync(x => x.Id == id);
        }

        public virtual async Task DeleteAsync(T record)
        {
            await _collection.FindOneAndDeleteAsync(x => x.Id == record.Id);
        }

        public virtual T GetById(ObjectId id)
        {
            return _collection.Find(x => x.Id == id).FirstOrDefault();
        }

        public virtual async Task<T> GetByIdAsync(ObjectId id)
        {
            return await _collection.Find(x => x.Id == id).FirstOrDefaultAsync();
        }

        public virtual void Insert(T entity)
        {
            var options = new InsertOneOptions { BypassDocumentValidation = false };
            _collection.InsertOne(entity, options);

        }

        public virtual async Task InsertAsync(T entity)
        {
            var options = new InsertOneOptions { BypassDocumentValidation = false };
            await _collection.InsertOneAsync(entity, options);

        }

        public virtual void InsertMany(IEnumerable<T> entities)
        {
            var options = new BulkWriteOptions { IsOrdered = false, BypassDocumentValidation = false };
            _collection.BulkWriteAsync((IEnumerable<WriteModel<T>>)entities, options);
        }

        public virtual async Task InsertManyAsync(IEnumerable<T> entities)
        {
            var options = new BulkWriteOptions { IsOrdered = false, BypassDocumentValidation = false };
            await _collection.BulkWriteAsync((IEnumerable<WriteModel<T>>)entities, options);
        }

        public virtual IQueryable<T> LoadRecords(Expression<Func<T, bool>> predicate = null)
        {
            return predicate == null
               ?  _collection.AsQueryable()
               :  _collection.AsQueryable().Where(predicate);
        }

        public virtual async Task<IQueryable<T>> LoadRecordsAsync(Expression<Func<T, bool>> predicate = null)
        {
           return await Task.Run(() =>
            {
                return predicate == null
               ? _collection.AsQueryable()
               : _collection.AsQueryable().Where(predicate);
            });

        }

        public virtual void Update(ObjectId id, T record)
        {
            _collection.FindOneAndReplace(x => x.Id == id, record);
        }

        public virtual void Update(T record, Expression<Func<T, bool>> predicate)
        {
             _collection.FindOneAndReplace(predicate, record);
        }

        public virtual async Task UpdateAsync(ObjectId id, T record)
        {
            await _collection.FindOneAndReplaceAsync(x => x.Id == id, record);
        }

        public virtual async Task UpdateAsync(T record, Expression<Func<T, bool>> predicate)
        {
            await _collection.FindOneAndReplaceAsync(predicate, record);
        }

        private void ConnectionSettingControl(MongoConnectionSettings settings)
        {
            //if (settings.GetMongoClientSettings() != null &&
            //   (string.IsNullOrEmpty(collectionName) || string.IsNullOrEmpty(settings.DatabaseName)))
            //    throw new Exception("Value cannot be null or empty");

            //if (string.IsNullOrEmpty(collectionName) ||
            //   string.IsNullOrEmpty(settings.ConnectionString) ||
            //   string.IsNullOrEmpty(settings.DatabaseName))
            //    throw new Exception("Value cannot be null or empty");

        }
    }
}

{'repo_name': 'keremvaris/Sennedjem', 'stars': '142', 'repo_language': 'PureBasic', 'file_name': 'CustomProfile.pubxml.user', 'mime_type': 'text/xml', 'hash': -1502102729287980071, 'source_dataset': 'data'}


# This is the official list of freegeoip authors for copyright purposes.
# This file is distinct from the CONTRIBUTORS file.
#
# Names should be added to this file as
#	Name or Organization <email address>
#
# The email address is not required for organizations.
#
# Please keep the list sorted.

Alexandre Fiori <fiorix@gmail.com>

{'repo_name': 'ethersphere/swarm', 'stars': '303', 'repo_language': 'Go', 'file_name': 'mime.types', 'mime_type': 'text/plain', 'hash': -2290666375211189279, 'source_dataset': 'data'}


// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.browser_ui.util;

import org.chromium.base.Callback;
import org.chromium.content_public.common.BrowserControlsState;

import java.util.ArrayList;
import java.util.List;

/**
 * Delegate for the visibility of browser controls that combines the results of other delegates.
 */
public class ComposedBrowserControlsVisibilityDelegate extends BrowserControlsVisibilityDelegate {
    private final List<BrowserControlsVisibilityDelegate> mDelegates;
    private final Callback<Integer> mConstraintsUpdatedCallback;

    private boolean mSetDisabled;

    /**
     * Constructs a composed visibility delegate that will generate results based on the delegates
     * passed in.
     */
    public ComposedBrowserControlsVisibilityDelegate(
            BrowserControlsVisibilityDelegate... delegates) {
        super(BrowserControlsState.BOTH);
        mSetDisabled = true;
        mDelegates = new ArrayList<>();
        mConstraintsUpdatedCallback = (constraints) -> super.set(calculateVisibilityConstraints());
        for (int i = 0; i < delegates.length; i++) addDelegate(delegates[i]);
        super.set(calculateVisibilityConstraints());
    }

    /**
     * Adds an additional delegate to the composed visibility delegate that will determine the
     * overall visibility constraints.
     * @param delegate The delegate to be added.
     */
    public void addDelegate(BrowserControlsVisibilityDelegate delegate) {
        mDelegates.add(delegate);
        delegate.addObserver(mConstraintsUpdatedCallback);
    }

    @Override
    public void set(Integer value) {
        // Allow set(...) to only be called via the super constructor.  After initial construction,
        // no client should be allowed to update the value through anything other than the
        // attached delegates.
        if (mSetDisabled) {
            throw new IllegalStateException("Calling set on the composed delegate is not allowed.");
        }
        super.set(value);
    }

    private @BrowserControlsState int calculateVisibilityConstraints() {
        boolean shouldBeShown = false;
        for (int i = 0; i < mDelegates.size(); i++) {
            @BrowserControlsState
            int delegateConstraints = mDelegates.get(i).get();
            if (delegateConstraints == BrowserControlsState.HIDDEN) {
                return BrowserControlsState.HIDDEN;
            }
            shouldBeShown |= delegateConstraints == BrowserControlsState.SHOWN;
        }
        return shouldBeShown ? BrowserControlsState.SHOWN : BrowserControlsState.BOTH;
    }
}

{'repo_name': 'nwjs/chromium.src', 'stars': '111', 'repo_language': 'None', 'file_name': 'AndroidManifest.xml', 'mime_type': 'text/xml', 'hash': -6944119550164694393, 'source_dataset': 'data'}


apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: sqlfiddle
  name: mysql56
spec:
  selector:
    matchLabels:
      type: mysql56
  replicas: 1
  template:
    metadata:
      labels:
        type: mysql56
    spec:
      containers:
        - image: sqlfiddle/mysql56host:{{ .Values.mysql56Version }}
          imagePullPolicy: IfNotPresent
          name: mysql56
          ports:
            - containerPort: 3306
              protocol: TCP
          resources:
              requests:
                memory: "512Mi"
          readinessProbe:
            exec:
              command:
                - "/ready.sh"
            initialDelaySeconds: 5
            timeoutSeconds: 5
            periodSeconds: 10
---
kind: Service
apiVersion: v1
metadata:
  namespace: sqlfiddle
  name: mysql56-service
  labels:
    role: host
spec:
  clusterIP: None
  ports:
    - port: 3306
      name: database
  selector:
    type: mysql56

{'repo_name': 'zzzprojects/sqlfiddle3', 'stars': '197', 'repo_language': 'JavaScript', 'file_name': 'default.vcl', 'mime_type': 'text/plain', 'hash': 5620630114396788493, 'source_dataset': 'data'}


# -*- coding: utf-8 -*-
#
# Swift Static Web documentation build configuration file, created by
# sphinx-quickstart on Tue Apr 17 02:17:37 2012.
#
# This file is execfile()d with the current directory set to its containing
# dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import swift3

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.append(os.path.abspath('.'))

# -- General configuration ----------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo',
              'sphinx.ext.coverage']

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Swift S3 Compatibility Middleware'
copyright = u'2012 OpenStack, LLC.'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '.'.join(str(v) for v in swift3.version_info[:-1])
# The full version, including alpha/beta/rc tags.
release = swift3.version

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of documents that shouldn't be included in the build.
#unused_docs = []

# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = []

# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages.  Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'default'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_use_modindex = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''

# Output file base name for HTML help builder.
htmlhelp_basename = 'Swift3webdoc'

# -- Options for LaTeX output -------------------------------------------------

# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'

# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual])
latex_documents = [
  ('index', 'Swift3web.tex', u'Swift3 Documentation',
   u'OpenStack, LLC.', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# Additional stuff for the LaTeX preamble.
#latex_preamble = ''

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_use_modindex = True

{'repo_name': 'JiYou/openstack', 'stars': '376', 'repo_language': 'Python', 'file_name': 'glance-no-swift.sh', 'mime_type': 'text/x-shellscript', 'hash': -450313122335937748, 'source_dataset': 'data'}


/*
 *
 * Form
 *
 */

import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {
  camelCase,
  compact,
  concat,
  findIndex,
  filter,
  get,
  has,
  includes,
  isEmpty,
  isObject,
  isUndefined,
  map,
  size,
  split,
  take,
  toNumber,
  replace,
} from 'lodash';
import { FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
import moment from 'moment';
import { router } from 'app';

import { temporaryContentTypeFieldsUpdated, storeTemporaryMenu } from 'containers/App/actions';
import { addAttributeToContentType, addAttributeRelationToContentType, editContentTypeAttribute, editContentTypeAttributeRelation, updateContentType } from 'containers/ModelPage/actions';

import AttributeCard from 'components/AttributeCard';
import InputCheckboxWithNestedInputs from 'components/InputCheckboxWithNestedInputs';
import PopUpForm from 'components/PopUpForm';
import PopUpRelations from 'components/PopUpRelations';

// Utils
import { checkFormValidity } from '../../utils/formValidations';
import { storeData } from '../../utils/storeData';

import checkAttributeValidations from './utils/attributeValidations';
import setParallelAttribute, { setTempAttribute } from './utils/setAttribute';
import {
  changeInput,
  changeInputAttribute,
  connectionsFetch,
  contentTypeCreate,
  contentTypeEdit,
  contentTypeFetch,
  contentTypeFetchSucceeded,
  removeContentTypeRequiredError,
  resetFormErrors,
  resetIsFormSet,
  setAttributeForm,
  setAttributeFormEdit,
  setForm,
  setFormErrors,
} from './actions';
import selectForm from './selectors';

import styles from './styles.scss';
import forms from './forms.json';

/* eslint-disable react/sort-comp */
/* eslint-disable consistent-return */
/* eslint-disable react/jsx-wrap-multilines */

export class Form extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = {
      showModal: false,
      popUpTitleEdit: '',
    };

    this.checkAttributeValidations = checkAttributeValidations.bind(this);
    this.setParallelAttribute = setParallelAttribute.bind(this);
    this.setTempAttribute = setTempAttribute.bind(this);
  }

  componentDidMount() {
    // Get available db connections
    this.props.connectionsFetch();
    this.initComponent(this.props, true);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.hash !== this.props.hash) {
      this.initComponent(nextProps, !nextProps.isFormSet);
    }

    // Close modal when updating a content type && success updating
    if (nextProps.shouldRefetchContentType !== this.props.shouldRefetchContentType) {
      // Check if localStorage because the PluginLeftMenu is based on the localStorage
      if (storeData.getMenu()) {
        // Update localStorage
        const oldMenu = storeData.getMenu();
        const index = findIndex(oldMenu, ['name', replace(this.props.hash.split('::')[0], '#edit', '')]);
        const modifiedContentType = {
          name: this.props.modifiedDataEdit.name,
          icon: 'fa-caret-square-o-right',
        };

        oldMenu.splice(index, 1, modifiedContentType);
        const newMenu = oldMenu;
        storeData.setMenu(newMenu);
      }
      // Close Modal
      const redirectToModelPage = includes(this.props.redirectRoute, 'models') ? `/${this.props.modifiedDataEdit.name}` : '';
      router.push(`${this.props.redirectRoute}${redirectToModelPage}`);
      // Reset props
      this.props.resetIsFormSet();

      // Sagas are cancelled on location change so to update the content type description and collectionName we have to force it
      if (this.props.isModelPage) {
        this.props.updateContentType(this.props.modifiedDataEdit);
      }
    }
  }

  componentDidUpdate(prevProps) {
    if (prevProps.modelLoading !== this.props.modelLoading && !isEmpty(this.props.hash)) {
      this.initComponent(this.props, true);
    }
  }

  addAttributeToContentType = () => {
    const formErrors = this.checkAttributeValidations(checkFormValidity(this.props.modifiedDataAttribute, this.props.formValidations));

    if (!isEmpty(formErrors)) {
      return this.props.setFormErrors(formErrors);
    }

    // Check if user is adding a relation with the same content type
    if (includes(this.props.hash, 'attributerelation') && this.props.modifiedDataAttribute.params.target === this.props.modelName) {
      // Insert two attributes
      this.props.addAttributeRelationToContentType(this.props.modifiedDataAttribute);
    } else {
      // Update the parent container (ModelPage)
      this.props.addAttributeToContentType(this.props.modifiedDataAttribute);
    }
    // Empty the store
    this.props.resetIsFormSet();
    // Empty errors
    this.props.resetFormErrors();
    // Close modal
    router.push(`${this.props.redirectRoute}/${replace(this.props.hash.split('::')[0], '#create', '')}`);
  }

  addAttributeToTempContentType = () => {
    const formErrors = this.checkAttributeValidations(checkFormValidity(this.props.modifiedDataAttribute, this.props.formValidations));

    if (!isEmpty(formErrors)) {
      return this.props.setFormErrors(formErrors);
    }

    // Get the entire content type from the reducer
    const contentType = this.props.modifiedDataEdit;
    // Add the new attribute to the content type attribute list
    const newAttribute = this.setTempAttribute();
    contentType.attributes = compact(concat(contentType.attributes, newAttribute, this.setParallelAttribute(newAttribute)));
    // Reset the store and update the parent container
    this.props.contentTypeCreate(contentType);
    // Get the displayed model from the localStorage
    const model = storeData.getModel();
    // Set the new field number in the localStorage
    model.fields = size(contentType.attributes);
    // Update the global store (app container) to add the new value to the model without refetching
    this.props.temporaryContentTypeFieldsUpdated(model.fields);
    // Store the updated model in the localStorage
    storeData.setModel(model);
    this.props.resetFormErrors();
    // Close modal
    router.push(`${this.props.redirectRoute}/${contentType.name}`);
  }

  createContentType = (data) => {
    // Check form errors
    const formErrors = checkFormValidity(data, this.props.formValidations);
    // Check if content type name already exists
    const sameContentTypeNames = filter(this.props.menuData[0].items, (contentType) => contentType.name === data.name);

    if (size(sameContentTypeNames) > 0 && (includes(this.props.hash, '#create') || data.name !== replace(split(this.props.hash, '::')[0], '#edit', ''))) {
      formErrors.push({ name: 'name', errors: [{ id: 'content-type-builder.error.contentTypeName.taken' }]});
    }

    if (!isEmpty(formErrors)) {
      return this.props.setFormErrors(formErrors);
    }
    const oldMenu = !isEmpty(this.props.menuData) ? this.props.menuData[0].items : [];
    // Check if link already exist in the menu to remove it
    const index = findIndex(oldMenu, [ 'name', replace(split(this.props.hash, '::')[0], '#edit', '')]);
    // Insert at a specific position or before the add button the not saved contentType
    const position = index !== -1 ? index  : size(oldMenu) - 1;
    oldMenu.splice(position, index !== -1 ? 1 : 0, { icon: 'fa-cube', fields: 0, description: data.description, name: data.name, isTemporary: true });
    const newMenu = oldMenu;
    const contentType = data;

    map(contentType.attributes, (attr, key) => {
      if (get(attr.params, 'target') === this.props.modelName) {
        contentType.attributes[key].params.target = data.name;
      }
    });
    // Store the temporary contentType in the localStorage
    this.props.contentTypeCreate(contentType);
    // Store new menu in localStorage and update App leftMenu
    this.props.storeTemporaryMenu(newMenu, position, index !== -1 ? 1 : 0);
    // Reset popUp form
    this.props.resetIsFormSet();
    // Reset formErrors
    this.props.resetFormErrors();
    // Close modal
    const modelPage = includes(this.props.redirectRoute, 'models') ? '' : '/models';
    router.push(`${this.props.redirectRoute}${modelPage}/${data.name}`);
  }

  checkForNestedInput = (item) => {
    const hasNestedInput = item.items && item.type !== 'select';
    return hasNestedInput;
  }

  checkInputContentType = (item) => {
    const shouldOverrideHandleBlur = item.name === 'name' && includes(this.props.hash, 'contentType');
    return shouldOverrideHandleBlur;
  }

  // Function used when modified the name of the content type and not the attributes
  // Fires Form sagas
  contentTypeEdit = () => {
    const formErrors = checkFormValidity(this.props.modifiedDataEdit, this.props.formValidations);
    const sameContentTypeNames = filter(this.props.menuData[0].items, (contentType) => contentType.name === this.props.modifiedDataEdit.name);

    if (size(sameContentTypeNames) > 0 && this.props.modifiedDataEdit.name !== replace(split(this.props.hash, '::')[0], '#edit', '')) {
    // if (size(sameContentTypeNames) > 0 && this.props.modifiedDataEdit.name !== this.props.modelName) {
      formErrors.push({ name: 'name', errors: [{ id: 'content-type-builder.error.contentTypeName.taken' }]});
    }

    if (!isEmpty(formErrors)) {
      return this.props.setFormErrors(formErrors);
    }

    const contentType = storeData.getContentType();

    // Update relation key of the temporary contentType
    if (contentType) {
      map(contentType.attributes, (attr, key) => {
        if (get(attr.params, 'target') === replace(split(this.props.hash, '::')[0], '#edit', '')) {
          contentType.attributes[key].params.target = this.props.modifiedDataEdit.name;
        }
      });
      this.props.contentTypeCreate(contentType);
    }

    this.setState({ showModal: false });
    return this.props.contentTypeEdit(this.context);
  }

  editContentTypeAttribute = () => {
    const formErrors = this.checkAttributeValidations(checkFormValidity(this.props.modifiedDataAttribute, this.props.formValidations));
    const hashArray = split(this.props.hash, '::');

    if (!isEmpty(formErrors)) {
      return this.props.setFormErrors(formErrors);
    }

    if (!isUndefined(hashArray[4])) {
      // Update the parent container (ModelPage)
      this.props.editContentTypeAttributeRelation(this.props.modifiedDataAttribute, hashArray[3], hashArray[4], this.props.modifiedDataAttribute.params.target !== this.props.modelName);
    } else {
      this.props.editContentTypeAttribute(this.props.modifiedDataAttribute, hashArray[3], this.props.modifiedDataAttribute.params.target === this.props.modelName);
    }
    // Empty the store
    this.props.resetIsFormSet();
    // Empty errors
    this.props.resetFormErrors();
    // Close modal
    router.push(`${this.props.redirectRoute}/${replace(hashArray[0], '#edit', '')}`);
  }

  editTempContentTypeAttribute = () => {
    const formErrors = this.checkAttributeValidations(checkFormValidity(this.props.modifiedDataAttribute, this.props.formValidations));

    if (!isEmpty(formErrors)) {
      return this.props.setFormErrors(formErrors);
    }

    const contentType = storeData.getContentType();
    const newAttribute = this.setTempAttribute();
    const oldAttribute = contentType.attributes[this.props.hash.split('::')[3]];
    contentType.attributes[this.props.hash.split('::')[3]] = newAttribute;

    if (newAttribute.params.target === this.props.modelName) {
      const parallelAttribute = this.setParallelAttribute(newAttribute);
      contentType.attributes[findIndex(contentType.attributes, ['name', oldAttribute.params.key])] = parallelAttribute;
    }

    if (oldAttribute.params.target === this.props.modelName && newAttribute.params.target !== this.props.modelName) {
      contentType.attributes.splice(findIndex(contentType.attributes, ['name', oldAttribute.params.key]), 1);
    }

    this.editContentTypeAttribute();

    const newContentType = contentType;
    // Empty errors
    this.props.resetFormErrors();
    storeData.setContentType(newContentType);
  }

  fetchModel = (contentTypeName) => {
    this.testContentType(
      contentTypeName,
      this.props.contentTypeFetchSucceeded,
      { model: storeData.getContentType() },
      this.props.contentTypeFetch,
      contentTypeName
    );
  }

  generatePopUpTitle = (popUpFormType) => {
    let popUpTitle;

    const type = split(this.props.hash, '::')[0];
    const isCreating = includes(type, 'create');

    switch (true) {
      case isCreating && popUpFormType === 'contentType':
        popUpTitle = `content-type-builder.popUpForm.create.${popUpFormType}.header.title`;
        break;
      case isCreating:
        popUpTitle = 'content-type-builder.popUpForm.create';
        break;
      case includes(type, 'choose'):
        popUpTitle = `content-type-builder.popUpForm.choose.${popUpFormType}.header.title`;
        break;
      case includes(type, 'edit') && popUpFormType === 'contentType':
        popUpTitle = `content-type-builder.popUpForm.edit.${popUpFormType}.header.title`;
        break;
      default:
        popUpTitle = 'content-type-builder.popUpForm.edit';
    }

    return popUpTitle;
  }

  getValues = () => {
    let values;
    // Three kinds of values are available modifiedData and modifiedDataEdit
    // Allows the user to start creating a contentType and modifying an existing one at the same time
    switch (true) {
      case includes(this.props.hash, 'edit') && !includes(this.props.hash, 'attribute'):
        values = this.props.modifiedDataEdit;
        break;
      case includes(this.props.hash.split('::')[1], 'attribute'):
        values = this.props.modifiedDataAttribute;
        break;
      default:
        values = this.props.modifiedData;
    }

    return values;
  }

  goToAttributeTypeView = (attributeType) => {
    const settings = attributeType === 'relation' ? 'defineRelation' : 'baseSettings';
    router.push(`${this.props.routePath}#create${this.props.modelName}::attribute${attributeType}::${settings}`);
  }

  handleBlur = ({ target }) => {
    if (target.name === 'name') {
      this.props.changeInput(target.name, camelCase(target.value), includes(this.props.hash, 'edit'));
      if (!isEmpty(target.value)) {
        // The input name for content type doesn't have the default handleBlur validation so we need to manually remove the error
        this.props.removeContentTypeRequiredError();
      }
    }
  }

  handleChange = ({ target }) => {
    let value = target.type === 'number' && target.value !== '' ? toNumber(target.value) : target.value;

    if (isObject(target.value) && target.value._isAMomentObject === true) {
      value = moment(target.value, 'YYYY-MM-DD HH:mm:ss').format();
    }

    if (includes(this.props.hash.split('::')[1], 'attribute')) {
      this.props.changeInputAttribute(target.name, value);

      if (target.name === 'params.nature' && target.value === "manyToMany") {
        this.props.changeInputAttribute('params.dominant', true);
      }

    } else {
      this.props.changeInput(target.name, value, includes(this.props.hash, 'edit'));
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const hashArray = split(this.props.hash, ('::'));
    const valueToReplace = includes(this.props.hash, '#create') ? '#create' : '#edit';
    const contentTypeName = replace(hashArray[0], valueToReplace, '');

    let cbSuccess;
    let dataSucces = null;
    let cbFail;

    switch (true) {
      case includes(hashArray[0], '#edit'): {
        // Check if the user is editing the attribute
        const isAttribute = includes(hashArray[1], 'attribute');
        cbSuccess = isAttribute ? this.editTempContentTypeAttribute : this.createContentType;
        dataSucces = isAttribute ? null : this.props.modifiedDataEdit;
        cbFail = isAttribute ? this.editContentTypeAttribute : this.contentTypeEdit;
        return this.testContentType(contentTypeName, cbSuccess, dataSucces, cbFail);
      }
      case includes(hashArray[0], 'create') && includes(this.props.hash.split('::')[1], 'attribute'): {
        cbSuccess = this.addAttributeToTempContentType;
        cbFail = this.addAttributeToContentType;
        return this.testContentType(contentTypeName, cbSuccess, dataSucces, cbFail);
      }
      default: {
        return this.createContentType(this.props.modifiedData);
      }
    }
  }

  initComponent = (props, condition) => {
    if (!isEmpty(props.hash)) {
      this.setState({ showModal: true });
      const valueToReplace = includes(props.hash, '#create') ? '#create' : '#edit';
      const contentTypeName = replace(split(props.hash, '::')[0], valueToReplace, '');
      const isPopUpAttribute = includes(props.hash, 'attribute');
      const isCreating = valueToReplace === '#create';

      if (condition && !isEmpty(contentTypeName) && contentTypeName !== '#choose') {
        this.fetchModel(contentTypeName);
      }

      switch (true) {
        case isPopUpAttribute && contentTypeName !== '#choose': {
          if (isCreating) {
            this.props.setAttributeForm(props.hash);
          } else if (get(props.contentTypeData, 'name')) {
            this.setState({ popUpTitleEdit: get(props.contentTypeData, ['attributes', split(props.hash, '::')[3], 'name']) });
            this.props.setAttributeFormEdit(props.hash, props.contentTypeData);
          }
          break;
        }
        case includes(props.hash, 'contentType'):
          this.props.setForm(props.hash);
          break;
        default:
      }
    } else {
      this.setState({ showModal: false });
    }
  }

  renderModalBodyChooseAttributes = () => {
    const attributesDisplay = forms.attributesDisplay.items;

    // Don't display the media field if the upload plugin isn't installed
    if (!has(this.context.plugins.toJS(), 'upload')) {
      attributesDisplay.splice(8, 1);
    }

    return (
      map(attributesDisplay, (attribute, key) => (
        <AttributeCard
          key={key}
          attribute={attribute}
          autoFocus={key === 0}
          routePath={this.props.routePath}
          handleClick={this.goToAttributeTypeView}
          tabIndex={key}
        />
      ))
    );
  }

  testContentType = (contentTypeName, cbSuccess, successData, cbFail, failData) => {
    // Check if the content type is in the localStorage (not saved) to prevent request error
    if (storeData.getIsModelTemporary() && get(storeData.getContentType(), 'name') === contentTypeName) {
      cbSuccess(successData);
    } else {
      cbFail(failData);
    }
  }

  toggle = () => {
    this.props.toggle();
    // Set the isFormSet props to false when the modal is closing so the store is emptied
    this.props.resetIsFormSet();
    this.props.resetFormErrors();
  }

  overrideCustomBootstrapClass = () => {
    return includes(this.props.hash, 'attributenumber');
  }

  renderInput = (item, key) => (
    <InputCheckboxWithNestedInputs
      key={key}
      data={item}
      value={this.props.modifiedDataAttribute.params}
      onChange={this.handleChange}
      errors={this.props.formErrors}
      didCheckErrors={this.props.didCheckErrors}
    />
  )

  renderCustomPopUpHeader = (startTitle) => {
    const italicText = !includes(this.props.hash, '#edit') ?
      <FormattedMessage id='popUpForm.header' defaultMessage='{title}' values={{ title: replace(split(this.props.hash, ('::'))[1], 'attribute', '') }}>
        {(message) => {message}}
      </FormattedMessage>
      : {this.state.popUpTitleEdit};
    return (

        <FormattedMessage id={startTitle} />

        {italicText}

        <FormattedMessage id="content-type-builder.popUpForm.field" />

    );
  }

  render() {
    // Ensure typeof(popUpFormType) is String
    const popUpFormType = split(this.props.hash, '::')[1] || '';
    const popUpTitle = this.generatePopUpTitle(popUpFormType);
    const values = this.getValues();
    const noNav = includes(this.props.hash, 'choose');
    // Override the default rendering
    const renderModalBody = includes(this.props.hash, '#choose') ? this.renderModalBodyChooseAttributes : false;
    // Hide the button in the modal
    const noButtons = includes(this.props.hash, '#choose');
    const buttonSubmitMessage = includes(this.props.hash.split('::')[1], 'contentType') ? 'form.button.save' : 'form.button.continue';
    const renderCustomPopUpHeader = !includes(this.props.hash, '#choose') && includes(this.props.hash, '::attribute') ? this.renderCustomPopUpHeader(popUpTitle) : false;
    const dropDownItems = take(get(this.props.menuData, ['0', 'items']), size(get(this.props.menuData[0], 'items')) - 1);
    const edit = includes(this.props.hash, '#edit');
    const selectOptions = includes(this.props.hash, 'attributenumber') ? get(this.props.form, ['items', '1', 'items']) : this.props.selectOptions;

    if (includes(popUpFormType, 'relation')) {
      const contentType = this.props.modelName.split('&source=');
      const contentTypeIndex = contentType.length === 2 ? { name: contentType[0], source: contentType[1] } : { name: contentType[0] };

      return (
        <PopUpRelations
          isOpen={this.state.showModal}
          toggle={this.toggle}
          renderCustomPopUpHeader={renderCustomPopUpHeader}
          popUpTitle={popUpTitle}
          routePath={`${this.props.routePath}/${this.props.hash}`}
          contentType={get(dropDownItems, [findIndex(dropDownItems, contentTypeIndex)])}
          form={this.props.form}
          showRelation={includes(this.props.hash, 'defineRelation')}
          onChange={this.handleChange}
          values={this.props.modifiedDataAttribute}
          dropDownItems={dropDownItems}
          onSubmit={this.handleSubmit}
          formErrors={this.props.formErrors}
          didCheckErrors={this.props.didCheckErrors}
          isEditting={edit}
        />
      );
    }

    return (

        <PopUpForm
          isOpen={this.state.showModal}
          toggle={this.toggle}
          popUpFormType={popUpFormType}
          popUpTitle={popUpTitle}
          routePath={`${this.props.routePath}/${this.props.hash}`}
          popUpHeaderNavLinks={this.props.popUpHeaderNavLinks}
          form={this.props.form}
          values={values}
          selectOptions={selectOptions}
          onChange={this.handleChange}
          onBlur={this.handleBlur}
          onSubmit={this.handleSubmit}
          noNav={noNav}
          renderModalBody={renderModalBody}
          noButtons={noButtons}
          overrideRenderInputCondition={this.checkForNestedInput}
          overrideRenderInput={this.renderInput}
          buttonSubmitMessage={buttonSubmitMessage}
          showLoader={this.props.showButtonLoading}
          renderCustomPopUpHeader={renderCustomPopUpHeader}
          overrideHandleBlurCondition={this.checkInputContentType}
          formErrors={this.props.formErrors}
          didCheckErrors={this.props.didCheckErrors}
          pluginID="content-type-builder"
          overrideCustomBootstrapClass={includes(this.props.hash, 'attributenumber') && includes(this.props.hash, 'baseSettings')}
          customBootstrapClass='col-md-6'
        />

    );
  }
}

Form.contextTypes = {
  plugins: PropTypes.object,
  updatePlugin: PropTypes.func,
};

const mapStateToProps = selectForm();

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    {
      addAttributeRelationToContentType,
      addAttributeToContentType,
      editContentTypeAttribute,
      editContentTypeAttributeRelation,
      changeInput,
      changeInputAttribute,
      connectionsFetch,
      contentTypeCreate,
      contentTypeEdit,
      contentTypeFetch,
      contentTypeFetchSucceeded,
      removeContentTypeRequiredError,
      resetFormErrors,
      resetIsFormSet,
      setAttributeForm,
      setAttributeFormEdit,
      setForm,
      setFormErrors,
      storeTemporaryMenu,
      temporaryContentTypeFieldsUpdated,
      updateContentType,
    },
    dispatch
  );
}

Form.propTypes = {
  addAttributeRelationToContentType: PropTypes.func.isRequired,
  addAttributeToContentType: PropTypes.func.isRequired,
  changeInput: PropTypes.func.isRequired,
  changeInputAttribute: PropTypes.func.isRequired,
  connectionsFetch: PropTypes.func.isRequired,
  contentTypeCreate: PropTypes.func.isRequired,
  contentTypeEdit: PropTypes.func.isRequired,
  contentTypeFetch: PropTypes.func.isRequired,
  contentTypeFetchSucceeded: PropTypes.func.isRequired,
  didCheckErrors: PropTypes.bool.isRequired,
  editContentTypeAttribute: PropTypes.func.isRequired,
  editContentTypeAttributeRelation: PropTypes.func.isRequired,
  form: PropTypes.oneOfType([
    PropTypes.array.isRequired,
    PropTypes.object.isRequired,
  ]).isRequired,
  formErrors: PropTypes.array.isRequired,
  formValidations: PropTypes.array.isRequired,
  hash: PropTypes.string.isRequired,
  isFormSet: PropTypes.bool.isRequired,
  isModelPage: PropTypes.bool,
  menuData: PropTypes.array.isRequired,
  modelLoading: PropTypes.bool, // eslint-disable-line react/require-default-props
  modelName: PropTypes.string,
  modifiedData: PropTypes.object.isRequired,
  modifiedDataAttribute: PropTypes.object.isRequired,
  modifiedDataEdit: PropTypes.object.isRequired,
  popUpHeaderNavLinks: PropTypes.array.isRequired,
  redirectRoute: PropTypes.string.isRequired,
  removeContentTypeRequiredError: PropTypes.func.isRequired,
  resetFormErrors: PropTypes.func.isRequired,
  resetIsFormSet: PropTypes.func.isRequired,
  routePath: PropTypes.string.isRequired,
  selectOptions: PropTypes.array.isRequired,
  setAttributeForm: PropTypes.func.isRequired,
  setAttributeFormEdit: PropTypes.func.isRequired,
  setForm: PropTypes.func.isRequired,
  setFormErrors: PropTypes.func.isRequired,
  shouldRefetchContentType: PropTypes.bool.isRequired,
  showButtonLoading: PropTypes.bool.isRequired,
  storeTemporaryMenu: PropTypes.func.isRequired,
  temporaryContentTypeFieldsUpdated: PropTypes.func.isRequired,
  toggle: PropTypes.func.isRequired,
  updateContentType: PropTypes.func.isRequired,
};

Form.defaultProps = {
  isModelPage: false,
  modelName: '',
};

const withConnect = connect(mapStateToProps, mapDispatchToProps);

export default withConnect(Form);

{'repo_name': 'strapi/strapi-examples', 'stars': '883', 'repo_language': 'JavaScript', 'file_name': 'index.html', 'mime_type': 'text/html', 'hash': 5716615331729512586, 'source_dataset': 'data'}


shader_type canvas_item;

// Gonkee's noise textures, original video: https://youtu.be/ybbJz6C9YYA
// this file heavily references https://thebookofshaders.com/

float rand(vec2 coord){
	// prevents randomness decreasing from coordinates too large
	coord = mod(coord, 10000.0);
	// returns "random" float between 0 and 1
	return fract(sin(dot(coord, vec2(12.9898,78.233))) * 43758.5453);
}

vec2 rand2( vec2 coord ) {
	// prevents randomness decreasing from coordinates too large
	coord = mod(coord, 10000.0);
	// returns "random" vec2 with x and y between 0 and 1
    return fract(sin( vec2( dot(coord,vec2(127.1,311.7)), dot(coord,vec2(269.5,183.3)) ) ) * 43758.5453);
}

float value_noise(vec2 coord){
	vec2 i = floor(coord);
	vec2 f = fract(coord);

	// 4 corners of a rectangle surrounding our point
	float tl = rand(i);
	float tr = rand(i + vec2(1.0, 0.0));
	float bl = rand(i + vec2(0.0, 1.0));
	float br = rand(i + vec2(1.0, 1.0));

	vec2 cubic = f * f * (3.0 - 2.0 * f);

	float topmix = mix(tl, tr, cubic.x);
	float botmix = mix(bl, br, cubic.x);
	float wholemix = mix(topmix, botmix, cubic.y);

	return wholemix;

}

float perlin_noise(vec2 coord) {
	vec2 i = floor(coord);
	vec2 f = fract(coord);

	// 4 corners of a rectangle surrounding our point
	// must be up to 2pi radians to allow the random vectors to face all directions
	float tl = rand(i) * 6.283;
	float tr = rand(i + vec2(1.0, 0.0)) * 6.283;
	float bl = rand(i + vec2(0.0, 1.0)) * 6.283;
	float br = rand(i + vec2(1.0, 1.0)) * 6.283;

	// original unit vector = (0, 1) which points downwards
	vec2 tlvec = vec2(-sin(tl), cos(tl));
	vec2 trvec = vec2(-sin(tr), cos(tr));
	vec2 blvec = vec2(-sin(bl), cos(bl));
	vec2 brvec = vec2(-sin(br), cos(br));

	// getting dot product of each corner's vector and its distance vector to current point
	float tldot = dot(tlvec, f);
	float trdot = dot(trvec, f - vec2(1.0, 0.0));
	float bldot = dot(blvec, f - vec2(0.0, 1.0));
	float brdot = dot(brvec, f - vec2(1.0, 1.0));

	// putting these values through abs() gives an interesting effect
//	tldot = abs(tldot);
//	trdot = abs(trdot);
//	bldot = abs(bldot);
//	brdot = abs(brdot);

	vec2 cubic = f * f * (3.0 - 2.0 * f);

	float topmix = mix(tldot, trdot, cubic.x);
	float botmix = mix(bldot, brdot, cubic.x);
	float wholemix = mix(topmix, botmix, cubic.y);

	return 0.5 + wholemix;
}

float cellular_noise(vec2 coord) {
	vec2 i = floor(coord);
	vec2 f = fract(coord);

	float min_dist = 99999.0;
	// going through the current tile and the tiles surrounding it
	for(float x = -1.0; x <= 1.0; x++) {
		for(float y = -1.0; y <= 1.0; y++) {

			// generate a random point in each tile,
			// but also account for whether it's a farther, neighbouring tile
			vec2 node = rand2(i + vec2(x, y)) + vec2(x, y);

			// check for distance to the point in that tile
			// decide whether it's the minimum
			float dist = sqrt((f - node).x * (f - node).x + (f - node).y * (f - node).y);
			min_dist = min(min_dist, dist);
		}
	}
	return min_dist;
}

float fbm(vec2 coord){
	int OCTAVES = 4;

	float normalize_factor = 0.0;
	float value = 0.0;
	float scale = 0.5;

	for(int i = 0; i < OCTAVES; i++){
		value += perlin_noise(coord) * scale;
		normalize_factor += scale;
		coord *= 2.0;
		scale *= 0.5;
	}
	return value / normalize_factor;
}

void fragment() {
	vec2 coord = UV * 10.0;

	float noise;
//	noise = rand(coord);
//	noise = value_noise(coord);
//	noise = perlin_noise(coord);
//	noise = cellular_noise(coord);
	noise = fbm(coord);

	COLOR = vec4(vec3(noise), 1.0);
}

{'repo_name': 'Gonkee/Gonkees-Shaders', 'stars': '139', 'repo_language': 'GDScript', 'file_name': 'Global.gd', 'mime_type': 'text/plain', 'hash': 5880706988235625232, 'source_dataset': 'data'}


Манзанита Пост

Вапити Индијска резервација

Ван Хорн трговачка пошта

{'repo_name': 'jeanropke/RDR2CollectorsMap', 'stars': '263', 'repo_language': 'JavaScript', 'file_name': 'day_3.json', 'mime_type': 'text/plain', 'hash': 4768467153322114823, 'source_dataset': 'data'}


/*
 * Copyright (C) 2007 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.common.io;

import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;

/**
 * Package-protected abstract class that implements the line reading algorithm used by {@link
 * LineReader}. Line separators are per {@link java.io.BufferedReader}: line feed, carriage return,
 * or carriage return followed immediately by a linefeed.
 *
 * <p>Subclasses must implement {@link #handleLine}, call {@link #add} to pass character data, and
 * call {@link #finish} at the end of stream.
 *
 * @author Chris Nokleberg
 * @since 1.0
 */
@GwtIncompatible
abstract class LineBuffer {
  /** Holds partial line contents. */
  private StringBuilder line = new StringBuilder();
  /** Whether a line ending with a CR is pending processing. */
  private boolean sawReturn;

  /**
   * Process additional characters from the stream. When a line separator is found the contents of
   * the line and the line separator itself are passed to the abstract {@link #handleLine} method.
   *
   * @param cbuf the character buffer to process
   * @param off the offset into the buffer
   * @param len the number of characters to process
   * @throws IOException if an I/O error occurs
   * @see #finish
   */
  protected void add(char[] cbuf, int off, int len) throws IOException {
    int pos = off;
    if (sawReturn && len > 0) {
      // Last call to add ended with a CR; we can handle the line now.
      if (finishLine(cbuf[pos] == '\n')) {
        pos++;
      }
    }

    int start = pos;
    for (int end = off + len; pos < end; pos++) {
      switch (cbuf[pos]) {
        case '\r':
          line.append(cbuf, start, pos - start);
          sawReturn = true;
          if (pos + 1 < end) {
            if (finishLine(cbuf[pos + 1] == '\n')) {
              pos++;
            }
          }
          start = pos + 1;
          break;

        case '\n':
          line.append(cbuf, start, pos - start);
          finishLine(true);
          start = pos + 1;
          break;

        default:
          // do nothing
      }
    }
    line.append(cbuf, start, off + len - start);
  }

  /** Called when a line is complete. */
  @CanIgnoreReturnValue
  private boolean finishLine(boolean sawNewline) throws IOException {
    String separator = sawReturn ? (sawNewline ? "\r\n" : "\r") : (sawNewline ? "\n" : "");
    handleLine(line.toString(), separator);
    line = new StringBuilder();
    sawReturn = false;
    return sawNewline;
  }

  /**
   * Subclasses must call this method after finishing character processing, in order to ensure that
   * any unterminated line in the buffer is passed to {@link #handleLine}.
   *
   * @throws IOException if an I/O error occurs
   */
  protected void finish() throws IOException {
    if (sawReturn || line.length() > 0) {
      finishLine(false);
    }
  }

  /**
   * Called for each line found in the character data passed to {@link #add}.
   *
   * @param line a line of text (possibly empty), without any line separators
   * @param end the line separator; one of {@code "\r"}, {@code "\n"}, {@code "\r\n"}, or {@code ""}
   * @throws IOException if an I/O error occurs
   */
  protected abstract void handleLine(String line, String end) throws IOException;
}

{'repo_name': 'google/guava', 'stars': '38126', 'repo_language': 'Java', 'file_name': 'SomeClassThatDoesNotUseNullable.java', 'mime_type': 'text/plain', 'hash': 4174352861342456955, 'source_dataset': 'data'}