text
stringlengths
2
99k
meta
dict
/* * Copyright (c) 2018 Gomint team * * This code is licensed under the BSD license found in the * LICENSE file in the root directory of this source tree. */ package io.gomint.world.block; import io.gomint.world.block.data.QuartzVariant; /** * @author geNAZt * @version 1.0 * @stability 3 */ public interface BlockBlockOfQuartz extends Block, BlockAxis { /** * Get the variant of this quartz block * * @return variant of this block */ QuartzVariant getVariant(); /** * Set the variant of this block * * @param variant which should be used */ void setVariant( QuartzVariant variant ); }
{ "pile_set_name": "Github" }
# Copyright 2011 Google Inc. 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. from gslib.command import Command from gslib.command import COMMAND_NAME from gslib.command import COMMAND_NAME_ALIASES from gslib.command import CONFIG_REQUIRED from gslib.command import FILE_URIS_OK from gslib.command import MAX_ARGS from gslib.command import MIN_ARGS from gslib.command import PROVIDER_URIS_OK from gslib.command import SUPPORTED_SUB_ARGS from gslib.command import URIS_START_ARG from gslib.exception import CommandException from gslib.help_provider import HELP_NAME from gslib.help_provider import HELP_NAME_ALIASES from gslib.help_provider import HELP_ONE_LINE_SUMMARY from gslib.help_provider import HELP_TEXT from gslib.help_provider import HelpType from gslib.help_provider import HELP_TYPE from gslib.util import NO_MAX _detailed_help_text = (""" <B>SYNOPSIS</B> gsutil mv [-p] src_uri dst_uri - or - gsutil mv [-p] uri... dst_uri <B>DESCRIPTION</B> The gsutil mv command allows you to move data between your local file system and the cloud, move data within the cloud, and move data between cloud storage providers. For example, to move all objects from a bucket to a local directory you could use: gsutil mv gs://my_bucket dir Similarly, to move all objects from a local directory to a bucket you could use: gsutil mv ./dir gs://my_bucket <B>RENAMING BUCKET SUBDIRECTORIES</B> You can use the gsutil mv command to rename subdirectories. For example, the command: gsutil mv gs://my_bucket/olddir gs://my_bucket/newdir would rename all objects and subdirectories under gs://my_bucket/olddir to be under gs://my_bucket/newdir, otherwise preserving the subdirectory structure. If you do a rename as specified above and you want to preserve ACLs, you should use the -p option (see OPTIONS). Note that when using mv to rename bucket subdirectories you cannot specify the source URI using wildcards. You need to spell out the complete name: gsutil mv gs://my_bucket/olddir gs://my_bucket/newdir If you have a large number of files to move you might want to use the gsutil -m option, to perform a multi-threaded/multi-processing move: gsutil -m mv gs://my_bucket/olddir gs://my_bucket/newdir <B>NON-ATOMIC OPERATION</B> Unlike the case with many file systems, the gsutil mv command does not perform a single atomic operation. Rather, it performs a copy from source to destination followed by removing the source for each object. <B>OPTIONS</B> -p Causes ACL to be preserved when moving in the cloud. Note that this option has performance and cost implications, because it is essentially performing three requests (getacl, cp, setacl). (The performance issue can be mitigated to some degree by using gsutil -m cp to cause multi-threaded/multi-processing copying.) """) class MvCommand(Command): """Implementation of gsutil mv command. Note that there is no atomic rename operation - this command is simply a shorthand for 'cp' followed by 'rm'. """ # Command specification (processed by parent class). command_spec = { # Name of command. COMMAND_NAME : 'mv', # List of command name aliases. COMMAND_NAME_ALIASES : ['move', 'ren', 'rename'], # Min number of args required by this command. MIN_ARGS : 2, # Max number of args required by this command, or NO_MAX. MAX_ARGS : NO_MAX, # Getopt-style string specifying acceptable sub args. SUPPORTED_SUB_ARGS : 'pv', # True if file URIs acceptable for this command. FILE_URIS_OK : True, # True if provider-only URIs acceptable for this command. PROVIDER_URIS_OK : False, # Index in args of first URI arg. URIS_START_ARG : 0, # True if must configure gsutil before running command. CONFIG_REQUIRED : True, } help_spec = { # Name of command or auxiliary help info for which this help applies. HELP_NAME : 'mv', # List of help name aliases. HELP_NAME_ALIASES : ['move', 'rename'], # Type of help: HELP_TYPE : HelpType.COMMAND_HELP, # One line summary of this help. HELP_ONE_LINE_SUMMARY : 'Move/rename objects and/or subdirectories', # The full help text. HELP_TEXT : _detailed_help_text, } # Command entry point. def RunCommand(self): # Check each source arg up, refusing to delete a bucket src URI (force users # to explicitly do that as a separate operation). for arg_to_check in self.args[0:-1]: if self.suri_builder.StorageUri(arg_to_check).names_bucket(): raise CommandException('You cannot move a source bucket using the mv ' 'command. If you meant to move\nall objects in ' 'the bucket, you can use a command like:\n' '\tgsutil mv %s/* %s' % (arg_to_check, self.args[-1])) # Insert command-line opts in front of args so they'll be picked up by cp # and rm commands (e.g., for -p option). Use undocumented (internal # use-only) cp -M option, which causes each original object to be deleted # after successfully copying to its destination, and also causes naming # behavior consistent with Unix mv naming behavior (see comments in # _ConstructDstUri in cp.py). unparsed_args = ['-M'] if self.recursion_requested: unparsed_args.append('-R') unparsed_args.extend(self.unparsed_args) self.command_runner.RunNamedCommand('cp', unparsed_args, self.headers, self.debug, self.parallel_operations) return 0
{ "pile_set_name": "Github" }
// // Carousel // -------------------------------------------------- // Wrapper for the slide container and indicators .carousel { position: relative; } .carousel-inner { position: relative; overflow: hidden; width: 100%; > .item { display: none; position: relative; @include transition(.6s ease-in-out left); // Account for jankitude on images > img, > a > img { @include img-responsive(); line-height: 1; } } > .active, > .next, > .prev { display: block; } > .active { left: 0; } > .next, > .prev { position: absolute; top: 0; width: 100%; } > .next { left: 100%; } > .prev { left: -100%; } > .next.left, > .prev.right { left: 0; } > .active.left { left: -100%; } > .active.right { left: 100%; } } // Left/right controls for nav // --------------------------- .carousel-control { position: absolute; top: 0; left: 0; bottom: 0; width: $carousel-control-width; @include opacity($carousel-control-opacity); font-size: $carousel-control-font-size; color: $carousel-control-color; text-align: center; text-shadow: $carousel-text-shadow; // We can't have this transition here because WebKit cancels the carousel // animation if you trip this while in the middle of another animation. // Set gradients for backgrounds &.left { @include gradient-horizontal($start-color: rgba(0,0,0,.5), $end-color: rgba(0,0,0,.0001)); } &.right { left: auto; right: 0; @include gradient-horizontal($start-color: rgba(0,0,0,.0001), $end-color: rgba(0,0,0,.5)); } // Hover/focus state &:hover, &:focus { outline: 0; color: $carousel-control-color; text-decoration: none; @include opacity(.9); } // Toggles .icon-prev, .icon-next, .glyphicon-chevron-left, .glyphicon-chevron-right { position: absolute; top: 50%; z-index: 5; display: inline-block; } .icon-prev, .glyphicon-chevron-left { left: 50%; margin-left: -10px; } .icon-next, .glyphicon-chevron-right { right: 50%; margin-right: -10px; } .icon-prev, .icon-next { width: 20px; height: 20px; margin-top: -10px; font-family: serif; } .icon-prev { &:before { content: '\2039';// SINGLE LEFT-POINTING ANGLE QUOTATION MARK (U+2039) } } .icon-next { &:before { content: '\203a';// SINGLE RIGHT-POINTING ANGLE QUOTATION MARK (U+203A) } } } // Optional indicator pips // // Add an unordered list with the following class and add a list item for each // slide your carousel holds. .carousel-indicators { position: absolute; bottom: 10px; left: 50%; z-index: 15; width: 60%; margin-left: -30%; padding-left: 0; list-style: none; text-align: center; li { display: inline-block; width: 10px; height: 10px; margin: 1px; text-indent: -999px; border: 1px solid $carousel-indicator-border-color; border-radius: 10px; cursor: pointer; // IE8-9 hack for event handling // // Internet Explorer 8-9 does not support clicks on elements without a set // `background-color`. We cannot use `filter` since that's not viewed as a // background color by the browser. Thus, a hack is needed. // // For IE8, we set solid black as it doesn't support `rgba()`. For IE9, we // set alpha transparency for the best results possible. background-color: #000 \9; // IE8 background-color: rgba(0,0,0,0); // IE9 } .active { margin: 0; width: 12px; height: 12px; background-color: $carousel-indicator-active-bg; } } // Optional captions // ----------------------------- // Hidden by default for smaller viewports .carousel-caption { position: absolute; left: 15%; right: 15%; bottom: 20px; z-index: 10; padding-top: 20px; padding-bottom: 20px; color: $carousel-caption-color; text-align: center; text-shadow: $carousel-text-shadow; & .btn { text-shadow: none; // No shadow for button elements in carousel-caption } } // Scale up controls for tablets and up @media screen and (min-width: $screen-sm-min) { // Scale up the controls a smidge .carousel-control { .glyphicon-chevron-left, .glyphicon-chevron-right, .icon-prev, .icon-next { width: 30px; height: 30px; margin-top: -15px; font-size: 30px; } .glyphicon-chevron-left, .icon-prev { margin-left: -15px; } .glyphicon-chevron-right, .icon-next { margin-right: -15px; } } // Show and left align the captions .carousel-caption { left: 20%; right: 20%; padding-bottom: 30px; } // Move up the indicators .carousel-indicators { bottom: 20px; } }
{ "pile_set_name": "Github" }
- 使用client_id去申请授权码 - 使用client_id client_secret 申请回的授权码去申请令牌(包含令牌ID, 令牌Token,令牌Token过期时间,刷新令牌Token) - 使用令牌token去访问需要鉴权的网址 ![Image text](https://user-gold-cdn.xitu.io/2019/2/28/169325d0994e5895?imageView2/0/w/1280/h/960/format/webp/ignore-error/1)
{ "pile_set_name": "Github" }
% INVFFT2 - takes inverse fft and returns real part % % Function to `wrap up' taking the inverse Fourier transform % and extracting the real part into the one operation % Peter Kovesi October 1999 function ift = invfft2(ft) ift = real(ifft2(ft));
{ "pile_set_name": "Github" }
# Copyright 2020 The TensorFlow Authors. 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. # ============================================================================== """Functions to generate bidirectional feature pyramids based on image features. Provides bidirectional feature pyramid network (BiFPN) generators that can be used to build object detection feature extractors, as proposed by Tan et al. See https://arxiv.org/abs/1911.09070 for more details. """ import collections import functools from six.moves import range from six.moves import zip import tensorflow as tf from object_detection.utils import bifpn_utils def _create_bifpn_input_config(fpn_min_level, fpn_max_level, input_max_level, level_scales=None): """Creates a BiFPN input config for the input levels from a backbone network. Args: fpn_min_level: the minimum pyramid level (highest feature map resolution) to use in the BiFPN. fpn_max_level: the maximum pyramid level (lowest feature map resolution) to use in the BiFPN. input_max_level: the maximum pyramid level that will be provided as input to the BiFPN. Accordingly, the BiFPN will compute additional pyramid levels from input_max_level, up to the desired fpn_max_level. level_scales: a list of pyramid level scale factors. If 'None', each level's scale is set to 2^level by default, which corresponds to each successive feature map scaling by a factor of 2. Returns: A list of dictionaries for each feature map expected as input to the BiFPN, where each has entries for the feature map 'name' and 'scale'. """ if not level_scales: level_scales = [2**i for i in range(fpn_min_level, fpn_max_level + 1)] bifpn_input_params = [] for i in range(fpn_min_level, min(fpn_max_level, input_max_level) + 1): bifpn_input_params.append({ 'name': '0_up_lvl_{}'.format(i), 'scale': level_scales[i - fpn_min_level] }) return bifpn_input_params def _get_bifpn_output_node_names(fpn_min_level, fpn_max_level, node_config): """Returns a list of BiFPN output node names, given a BiFPN node config. Args: fpn_min_level: the minimum pyramid level (highest feature map resolution) used by the BiFPN. fpn_max_level: the maximum pyramid level (lowest feature map resolution) used by the BiFPN. node_config: the BiFPN node_config, a list of dictionaries corresponding to each node in the BiFPN computation graph, where each entry should have an associated 'name'. Returns: A list of strings corresponding to the names of the output BiFPN nodes. """ num_output_nodes = fpn_max_level - fpn_min_level + 1 return [node['name'] for node in node_config[-num_output_nodes:]] def _create_bifpn_node_config(bifpn_num_iterations, bifpn_num_filters, fpn_min_level, fpn_max_level, input_max_level, bifpn_node_params=None, level_scales=None): """Creates a config specifying a bidirectional feature pyramid network. Args: bifpn_num_iterations: the number of top-down bottom-up feature computations to repeat in the BiFPN. bifpn_num_filters: the number of filters (channels) for every feature map used in the BiFPN. fpn_min_level: the minimum pyramid level (highest feature map resolution) to use in the BiFPN. fpn_max_level: the maximum pyramid level (lowest feature map resolution) to use in the BiFPN. input_max_level: the maximum pyramid level that will be provided as input to the BiFPN. Accordingly, the BiFPN will compute additional pyramid levels from input_max_level, up to the desired fpn_max_level. bifpn_node_params: If not 'None', a dictionary of additional default BiFPN node parameters that will be applied to all BiFPN nodes. level_scales: a list of pyramid level scale factors. If 'None', each level's scale is set to 2^level by default, which corresponds to each successive feature map scaling by a factor of 2. Returns: A list of dictionaries used to define nodes in the BiFPN computation graph, as proposed by EfficientDet, Tan et al (https://arxiv.org/abs/1911.09070). Each node's entry has the corresponding keys: name: String. The name of this node in the BiFPN. The node name follows the format '{bifpn_iteration}_{dn|up}_lvl_{pyramid_level}', where 'dn' or 'up' refers to whether the node is in the top-down or bottom-up portion of a single BiFPN iteration. scale: the scale factor for this node, by default 2^level. inputs: A list of names of nodes which are inputs to this node. num_channels: The number of channels for this node. combine_method: String. Name of the method used to combine input node feature maps, 'fast_attention' by default for nodes which have more than one input. Otherwise, 'None' for nodes with only one input node. input_op: A (partial) function which is called to construct the layers that will be applied to this BiFPN node's inputs. This function is called with the arguments: input_op(name, input_scale, input_num_channels, output_scale, output_num_channels, conv_hyperparams, is_training, freeze_batchnorm) post_combine_op: A (partial) function which is called to construct the layers that will be applied to the result of the combine operation for this BiFPN node. This function will be called with the arguments: post_combine_op(name, conv_hyperparams, is_training, freeze_batchnorm) If 'None', then no layers will be applied after the combine operation for this node. """ if not level_scales: level_scales = [2**i for i in range(fpn_min_level, fpn_max_level + 1)] default_node_params = { 'num_channels': bifpn_num_filters, 'combine_method': 'fast_attention', 'input_op': functools.partial( _create_bifpn_resample_block, downsample_method='max_pooling'), 'post_combine_op': functools.partial( bifpn_utils.create_conv_block, num_filters=bifpn_num_filters, kernel_size=3, strides=1, padding='SAME', use_separable=True, apply_batchnorm=True, apply_activation=True, conv_bn_act_pattern=False), } if bifpn_node_params: default_node_params.update(bifpn_node_params) bifpn_node_params = [] # Create additional base pyramid levels not provided as input to the BiFPN. # Note, combine_method and post_combine_op are set to None for additional # base pyramid levels because they do not combine multiple input BiFPN nodes. for i in range(input_max_level + 1, fpn_max_level + 1): node_params = dict(default_node_params) node_params.update({ 'name': '0_up_lvl_{}'.format(i), 'scale': level_scales[i - fpn_min_level], 'inputs': ['0_up_lvl_{}'.format(i - 1)], 'combine_method': None, 'post_combine_op': None, }) bifpn_node_params.append(node_params) for i in range(bifpn_num_iterations): # The first bottom-up feature pyramid (which includes the input pyramid # levels from the backbone network and the additional base pyramid levels) # is indexed at 0. So, the first top-down bottom-up pass of the BiFPN is # indexed from 1, and repeated for bifpn_num_iterations iterations. bifpn_i = i + 1 # Create top-down nodes. for level_i in reversed(range(fpn_min_level, fpn_max_level)): inputs = [] # BiFPN nodes in the top-down pass receive input from the corresponding # level from the previous BiFPN iteration's bottom-up pass, except for the # bottom-most (min) level node, which is computed once in the initial # bottom-up pass, and is afterwards only computed in each top-down pass. if level_i > fpn_min_level or bifpn_i == 1: inputs.append('{}_up_lvl_{}'.format(bifpn_i - 1, level_i)) else: inputs.append('{}_dn_lvl_{}'.format(bifpn_i - 1, level_i)) inputs.append(bifpn_node_params[-1]['name']) node_params = dict(default_node_params) node_params.update({ 'name': '{}_dn_lvl_{}'.format(bifpn_i, level_i), 'scale': level_scales[level_i - fpn_min_level], 'inputs': inputs }) bifpn_node_params.append(node_params) # Create bottom-up nodes. for level_i in range(fpn_min_level + 1, fpn_max_level + 1): # BiFPN nodes in the bottom-up pass receive input from the corresponding # level from the preceding top-down pass, except for the top (max) level # which does not have a corresponding node in the top-down pass. inputs = ['{}_up_lvl_{}'.format(bifpn_i - 1, level_i)] if level_i < fpn_max_level: inputs.append('{}_dn_lvl_{}'.format(bifpn_i, level_i)) inputs.append(bifpn_node_params[-1]['name']) node_params = dict(default_node_params) node_params.update({ 'name': '{}_up_lvl_{}'.format(bifpn_i, level_i), 'scale': level_scales[level_i - fpn_min_level], 'inputs': inputs }) bifpn_node_params.append(node_params) return bifpn_node_params def _create_bifpn_resample_block(name, input_scale, input_num_channels, output_scale, output_num_channels, conv_hyperparams, is_training, freeze_batchnorm, downsample_method=None, use_native_resize_op=False, maybe_apply_1x1_conv=True, apply_1x1_pre_sampling=True, apply_1x1_post_sampling=False): """Creates resample block layers for input feature maps to BiFPN nodes. Args: name: String. Name used for this block of layers. input_scale: Scale factor of the input feature map. input_num_channels: Number of channels in the input feature map. output_scale: Scale factor of the output feature map. output_num_channels: Number of channels in the output feature map. conv_hyperparams: A `hyperparams_builder.KerasLayerHyperparams` object containing hyperparameters for convolution ops. is_training: Indicates whether the feature generator is in training mode. freeze_batchnorm: Bool. Whether to freeze batch norm parameters during training or not. When training with a small batch size (e.g. 1), it is desirable to freeze batch norm update and use pretrained batch norm params. downsample_method: String. Method to use when downsampling feature maps. use_native_resize_op: Bool. Whether to use the native resize up when upsampling feature maps. maybe_apply_1x1_conv: Bool. If 'True', a 1x1 convolution will only be applied if the input_num_channels differs from the output_num_channels. apply_1x1_pre_sampling: Bool. Whether a 1x1 convolution will be applied to the input feature map before the up/down-sampling operation. apply_1x1_post_sampling: Bool. Whether a 1x1 convolution will be applied to the input feature map after the up/down-sampling operation. Returns: A list of layers which may be applied to the input feature maps in order to compute feature maps with the specified scale and number of channels. """ # By default, 1x1 convolutions are only applied before sampling when the # number of input and output channels differ. if maybe_apply_1x1_conv and output_num_channels == input_num_channels: apply_1x1_pre_sampling = False apply_1x1_post_sampling = False apply_bn_for_resampling = True layers = [] if apply_1x1_pre_sampling: layers.extend( bifpn_utils.create_conv_block( name=name + '1x1_pre_sample/', num_filters=output_num_channels, kernel_size=1, strides=1, padding='SAME', use_separable=False, apply_batchnorm=apply_bn_for_resampling, apply_activation=False, conv_hyperparams=conv_hyperparams, is_training=is_training, freeze_batchnorm=freeze_batchnorm)) layers.extend( bifpn_utils.create_resample_feature_map_ops(input_scale, output_scale, downsample_method, use_native_resize_op, conv_hyperparams, is_training, freeze_batchnorm, name)) if apply_1x1_post_sampling: layers.extend( bifpn_utils.create_conv_block( name=name + '1x1_post_sample/', num_filters=output_num_channels, kernel_size=1, strides=1, padding='SAME', use_separable=False, apply_batchnorm=apply_bn_for_resampling, apply_activation=False, conv_hyperparams=conv_hyperparams, is_training=is_training, freeze_batchnorm=freeze_batchnorm)) return layers def _create_bifpn_combine_op(num_inputs, name, combine_method): """Creates a BiFPN output config, a list of the output BiFPN node names. Args: num_inputs: The number of inputs to this combine operation. name: String. The name of this combine operation. combine_method: String. The method used to combine input feature maps. Returns: A function which may be called with a list of num_inputs feature maps and which will return a single feature map. """ combine_op = None if num_inputs < 1: raise ValueError('Expected at least 1 input for BiFPN combine.') elif num_inputs == 1: combine_op = lambda x: x[0] else: combine_op = bifpn_utils.BiFPNCombineLayer( combine_method=combine_method, name=name) return combine_op class KerasBiFpnFeatureMaps(tf.keras.Model): """Generates Keras based BiFPN feature maps from an input feature map pyramid. A Keras model that generates multi-scale feature maps for detection by iteratively computing top-down and bottom-up feature pyramids, as in the EfficientDet paper by Tan et al, see arxiv.org/abs/1911.09070 for details. """ def __init__(self, bifpn_num_iterations, bifpn_num_filters, fpn_min_level, fpn_max_level, input_max_level, is_training, conv_hyperparams, freeze_batchnorm, bifpn_node_params=None, name=None): """Constructor. Args: bifpn_num_iterations: The number of top-down bottom-up iterations. bifpn_num_filters: The number of filters (channels) to be used for all feature maps in this BiFPN. fpn_min_level: The minimum pyramid level (highest feature map resolution) to use in the BiFPN. fpn_max_level: The maximum pyramid level (lowest feature map resolution) to use in the BiFPN. input_max_level: The maximum pyramid level that will be provided as input to the BiFPN. Accordingly, the BiFPN will compute any additional pyramid levels from input_max_level up to the desired fpn_max_level, with each successivel level downsampling by a scale factor of 2 by default. is_training: Indicates whether the feature generator is in training mode. conv_hyperparams: A `hyperparams_builder.KerasLayerHyperparams` object containing hyperparameters for convolution ops. freeze_batchnorm: Bool. Whether to freeze batch norm parameters during training or not. When training with a small batch size (e.g. 1), it is desirable to freeze batch norm update and use pretrained batch norm params. bifpn_node_params: An optional dictionary that may be used to specify default parameters for BiFPN nodes, without the need to provide a custom bifpn_node_config. For example, if '{ combine_method: 'sum' }', then all BiFPN nodes will combine input feature maps by summation, rather than by the default fast attention method. name: A string name scope to assign to the model. If 'None', Keras will auto-generate one from the class name. """ super(KerasBiFpnFeatureMaps, self).__init__(name=name) bifpn_node_config = _create_bifpn_node_config( bifpn_num_iterations, bifpn_num_filters, fpn_min_level, fpn_max_level, input_max_level, bifpn_node_params) bifpn_input_config = _create_bifpn_input_config( fpn_min_level, fpn_max_level, input_max_level) bifpn_output_node_names = _get_bifpn_output_node_names( fpn_min_level, fpn_max_level, bifpn_node_config) self.bifpn_node_config = bifpn_node_config self.bifpn_output_node_names = bifpn_output_node_names self.node_input_blocks = [] self.node_combine_op = [] self.node_post_combine_block = [] all_node_params = bifpn_input_config all_node_names = [node['name'] for node in all_node_params] for node_config in bifpn_node_config: # Maybe transform and/or resample input feature maps. input_blocks = [] for input_name in node_config['inputs']: if input_name not in all_node_names: raise ValueError( 'Input feature map ({}) does not exist:'.format(input_name)) input_index = all_node_names.index(input_name) input_params = all_node_params[input_index] input_block = node_config['input_op']( name='{}/input_{}/'.format(node_config['name'], input_name), input_scale=input_params['scale'], input_num_channels=input_params.get('num_channels', None), output_scale=node_config['scale'], output_num_channels=node_config['num_channels'], conv_hyperparams=conv_hyperparams, is_training=is_training, freeze_batchnorm=freeze_batchnorm) input_blocks.append((input_index, input_block)) # Combine input feature maps. combine_op = _create_bifpn_combine_op( num_inputs=len(input_blocks), name=(node_config['name'] + '/combine'), combine_method=node_config['combine_method']) # Post-combine layers. post_combine_block = [] if node_config['post_combine_op']: post_combine_block.extend(node_config['post_combine_op']( name=node_config['name'] + '/post_combine/', conv_hyperparams=conv_hyperparams, is_training=is_training, freeze_batchnorm=freeze_batchnorm)) self.node_input_blocks.append(input_blocks) self.node_combine_op.append(combine_op) self.node_post_combine_block.append(post_combine_block) all_node_params.append(node_config) all_node_names.append(node_config['name']) def call(self, feature_pyramid): """Compute BiFPN feature maps from input feature pyramid. Executed when calling the `.__call__` method on input. Args: feature_pyramid: list of tuples of (tensor_name, image_feature_tensor). Returns: feature_maps: an OrderedDict mapping keys (feature map names) to tensors where each tensor has shape [batch, height_i, width_i, depth_i]. """ feature_maps = [el[1] for el in feature_pyramid] output_feature_maps = [None for node in self.bifpn_output_node_names] for index, node in enumerate(self.bifpn_node_config): node_scope = 'node_{:02d}'.format(index) with tf.name_scope(node_scope): # Apply layer blocks to this node's input feature maps. input_block_results = [] for input_index, input_block in self.node_input_blocks[index]: block_result = feature_maps[input_index] for layer in input_block: block_result = layer(block_result) input_block_results.append(block_result) # Combine the resulting feature maps. node_result = self.node_combine_op[index](input_block_results) # Apply post-combine layer block if applicable. for layer in self.node_post_combine_block[index]: node_result = layer(node_result) feature_maps.append(node_result) if node['name'] in self.bifpn_output_node_names: index = self.bifpn_output_node_names.index(node['name']) output_feature_maps[index] = node_result return collections.OrderedDict( zip(self.bifpn_output_node_names, output_feature_maps))
{ "pile_set_name": "Github" }
/* * Copyright 2008 Red Hat, Inc. All rights reserved. * Copyright 2008 Ian Kent <raven@themaw.net> * * This file is part of the Linux kernel and is made available under * the terms of the GNU General Public License, version 2, or at your * option, any later version, incorporated herein by reference. */ #include <linux/module.h> #include <linux/vmalloc.h> #include <linux/miscdevice.h> #include <linux/init.h> #include <linux/wait.h> #include <linux/namei.h> #include <linux/fcntl.h> #include <linux/file.h> #include <linux/fdtable.h> #include <linux/sched.h> #include <linux/cred.h> #include <linux/compat.h> #include <linux/syscalls.h> #include <linux/magic.h> #include <linux/dcache.h> #include <linux/uaccess.h> #include <linux/slab.h> #include "autofs_i.h" /* * This module implements an interface for routing autofs ioctl control * commands via a miscellaneous device file. * * The alternate interface is needed because we need to be able open * an ioctl file descriptor on an autofs mount that may be covered by * another mount. This situation arises when starting automount(8) * or other user space daemon which uses direct mounts or offset * mounts (used for autofs lazy mount/umount of nested mount trees), * which have been left busy at at service shutdown. */ typedef int (*ioctl_fn)(struct file *, struct autofs_sb_info *, struct autofs_dev_ioctl *); static int check_name(const char *name) { if (!strchr(name, '/')) return -EINVAL; return 0; } /* * Check a string doesn't overrun the chunk of * memory we copied from user land. */ static int invalid_str(char *str, size_t size) { if (memchr(str, 0, size)) return 0; return -EINVAL; } /* * Check that the user compiled against correct version of autofs * misc device code. * * As well as checking the version compatibility this always copies * the kernel interface version out. */ static int check_dev_ioctl_version(int cmd, struct autofs_dev_ioctl *param) { int err = 0; if ((param->ver_major != AUTOFS_DEV_IOCTL_VERSION_MAJOR) || (param->ver_minor > AUTOFS_DEV_IOCTL_VERSION_MINOR)) { pr_warn("ioctl control interface version mismatch: " "kernel(%u.%u), user(%u.%u), cmd(0x%08x)\n", AUTOFS_DEV_IOCTL_VERSION_MAJOR, AUTOFS_DEV_IOCTL_VERSION_MINOR, param->ver_major, param->ver_minor, cmd); err = -EINVAL; } /* Fill in the kernel version. */ param->ver_major = AUTOFS_DEV_IOCTL_VERSION_MAJOR; param->ver_minor = AUTOFS_DEV_IOCTL_VERSION_MINOR; return err; } /* * Copy parameter control struct, including a possible path allocated * at the end of the struct. */ static struct autofs_dev_ioctl * copy_dev_ioctl(struct autofs_dev_ioctl __user *in) { struct autofs_dev_ioctl tmp, *res; if (copy_from_user(&tmp, in, AUTOFS_DEV_IOCTL_SIZE)) return ERR_PTR(-EFAULT); if (tmp.size < AUTOFS_DEV_IOCTL_SIZE) return ERR_PTR(-EINVAL); if (tmp.size > AUTOFS_DEV_IOCTL_SIZE + PATH_MAX) return ERR_PTR(-ENAMETOOLONG); res = memdup_user(in, tmp.size); if (!IS_ERR(res)) res->size = tmp.size; return res; } static inline void free_dev_ioctl(struct autofs_dev_ioctl *param) { kfree(param); } /* * Check sanity of parameter control fields and if a path is present * check that it is terminated and contains at least one "/". */ static int validate_dev_ioctl(int cmd, struct autofs_dev_ioctl *param) { int err; err = check_dev_ioctl_version(cmd, param); if (err) { pr_warn("invalid device control module version " "supplied for cmd(0x%08x)\n", cmd); goto out; } if (param->size > AUTOFS_DEV_IOCTL_SIZE) { err = invalid_str(param->path, param->size - AUTOFS_DEV_IOCTL_SIZE); if (err) { pr_warn( "path string terminator missing for cmd(0x%08x)\n", cmd); goto out; } err = check_name(param->path); if (err) { pr_warn("invalid path supplied for cmd(0x%08x)\n", cmd); goto out; } } err = 0; out: return err; } /* * Get the autofs super block info struct from the file opened on * the autofs mount point. */ static struct autofs_sb_info *autofs_dev_ioctl_sbi(struct file *f) { struct autofs_sb_info *sbi = NULL; struct inode *inode; if (f) { inode = file_inode(f); sbi = autofs4_sbi(inode->i_sb); } return sbi; } /* Return autofs dev ioctl version */ static int autofs_dev_ioctl_version(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { /* This should have already been set. */ param->ver_major = AUTOFS_DEV_IOCTL_VERSION_MAJOR; param->ver_minor = AUTOFS_DEV_IOCTL_VERSION_MINOR; return 0; } /* Return autofs module protocol version */ static int autofs_dev_ioctl_protover(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { param->protover.version = sbi->version; return 0; } /* Return autofs module protocol sub version */ static int autofs_dev_ioctl_protosubver(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { param->protosubver.sub_version = sbi->sub_version; return 0; } /* Find the topmost mount satisfying test() */ static int find_autofs_mount(const char *pathname, struct path *res, int test(const struct path *path, void *data), void *data) { struct path path; int err; err = kern_path_mountpoint(AT_FDCWD, pathname, &path, 0); if (err) return err; err = -ENOENT; while (path.dentry == path.mnt->mnt_root) { if (path.dentry->d_sb->s_magic == AUTOFS_SUPER_MAGIC) { if (test(&path, data)) { path_get(&path); *res = path; err = 0; break; } } if (!follow_up(&path)) break; } path_put(&path); return err; } static int test_by_dev(const struct path *path, void *p) { return path->dentry->d_sb->s_dev == *(dev_t *)p; } static int test_by_type(const struct path *path, void *p) { struct autofs_info *ino = autofs4_dentry_ino(path->dentry); return ino && ino->sbi->type & *(unsigned *)p; } /* * Open a file descriptor on the autofs mount point corresponding * to the given path and device number (aka. new_encode_dev(sb->s_dev)). */ static int autofs_dev_ioctl_open_mountpoint(const char *name, dev_t devid) { int err, fd; fd = get_unused_fd_flags(O_CLOEXEC); if (likely(fd >= 0)) { struct file *filp; struct path path; err = find_autofs_mount(name, &path, test_by_dev, &devid); if (err) goto out; filp = dentry_open(&path, O_RDONLY, current_cred()); path_put(&path); if (IS_ERR(filp)) { err = PTR_ERR(filp); goto out; } fd_install(fd, filp); } return fd; out: put_unused_fd(fd); return err; } /* Open a file descriptor on an autofs mount point */ static int autofs_dev_ioctl_openmount(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { const char *path; dev_t devid; int err, fd; /* param->path has already been checked */ if (!param->openmount.devid) return -EINVAL; param->ioctlfd = -1; path = param->path; devid = new_decode_dev(param->openmount.devid); err = 0; fd = autofs_dev_ioctl_open_mountpoint(path, devid); if (unlikely(fd < 0)) { err = fd; goto out; } param->ioctlfd = fd; out: return err; } /* Close file descriptor allocated above (user can also use close(2)). */ static int autofs_dev_ioctl_closemount(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { return sys_close(param->ioctlfd); } /* * Send "ready" status for an existing wait (either a mount or an expire * request). */ static int autofs_dev_ioctl_ready(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { autofs_wqt_t token; token = (autofs_wqt_t) param->ready.token; return autofs4_wait_release(sbi, token, 0); } /* * Send "fail" status for an existing wait (either a mount or an expire * request). */ static int autofs_dev_ioctl_fail(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { autofs_wqt_t token; int status; token = (autofs_wqt_t) param->fail.token; status = param->fail.status < 0 ? param->fail.status : -ENOENT; return autofs4_wait_release(sbi, token, status); } /* * Set the pipe fd for kernel communication to the daemon. * * Normally this is set at mount using an option but if we * are reconnecting to a busy mount then we need to use this * to tell the autofs mount about the new kernel pipe fd. In * order to protect mounts against incorrectly setting the * pipefd we also require that the autofs mount be catatonic. * * This also sets the process group id used to identify the * controlling process (eg. the owning automount(8) daemon). */ static int autofs_dev_ioctl_setpipefd(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { int pipefd; int err = 0; struct pid *new_pid = NULL; if (param->setpipefd.pipefd == -1) return -EINVAL; pipefd = param->setpipefd.pipefd; mutex_lock(&sbi->wq_mutex); if (!sbi->catatonic) { mutex_unlock(&sbi->wq_mutex); return -EBUSY; } else { struct file *pipe; new_pid = get_task_pid(current, PIDTYPE_PGID); if (ns_of_pid(new_pid) != ns_of_pid(sbi->oz_pgrp)) { pr_warn("not allowed to change PID namespace\n"); err = -EINVAL; goto out; } pipe = fget(pipefd); if (!pipe) { err = -EBADF; goto out; } if (autofs_prepare_pipe(pipe) < 0) { err = -EPIPE; fput(pipe); goto out; } swap(sbi->oz_pgrp, new_pid); sbi->pipefd = pipefd; sbi->pipe = pipe; sbi->catatonic = 0; } out: put_pid(new_pid); mutex_unlock(&sbi->wq_mutex); return err; } /* * Make the autofs mount point catatonic, no longer responsive to * mount requests. Also closes the kernel pipe file descriptor. */ static int autofs_dev_ioctl_catatonic(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { autofs4_catatonic_mode(sbi); return 0; } /* Set the autofs mount timeout */ static int autofs_dev_ioctl_timeout(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { unsigned long timeout; timeout = param->timeout.timeout; param->timeout.timeout = sbi->exp_timeout / HZ; sbi->exp_timeout = timeout * HZ; return 0; } /* * Return the uid and gid of the last request for the mount * * When reconstructing an autofs mount tree with active mounts * we need to re-connect to mounts that may have used the original * process uid and gid (or string variations of them) for mount * lookups within the map entry. */ static int autofs_dev_ioctl_requester(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { struct autofs_info *ino; struct path path; dev_t devid; int err = -ENOENT; if (param->size <= AUTOFS_DEV_IOCTL_SIZE) { err = -EINVAL; goto out; } devid = sbi->sb->s_dev; param->requester.uid = param->requester.gid = -1; err = find_autofs_mount(param->path, &path, test_by_dev, &devid); if (err) goto out; ino = autofs4_dentry_ino(path.dentry); if (ino) { err = 0; autofs4_expire_wait(&path, 0); spin_lock(&sbi->fs_lock); param->requester.uid = from_kuid_munged(current_user_ns(), ino->uid); param->requester.gid = from_kgid_munged(current_user_ns(), ino->gid); spin_unlock(&sbi->fs_lock); } path_put(&path); out: return err; } /* * Call repeatedly until it returns -EAGAIN, meaning there's nothing * more that can be done. */ static int autofs_dev_ioctl_expire(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { struct vfsmount *mnt; int how; how = param->expire.how; mnt = fp->f_path.mnt; return autofs4_do_expire_multi(sbi->sb, mnt, sbi, how); } /* Check if autofs mount point is in use */ static int autofs_dev_ioctl_askumount(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { param->askumount.may_umount = 0; if (may_umount(fp->f_path.mnt)) param->askumount.may_umount = 1; return 0; } /* * Check if the given path is a mountpoint. * * If we are supplied with the file descriptor of an autofs * mount we're looking for a specific mount. In this case * the path is considered a mountpoint if it is itself a * mountpoint or contains a mount, such as a multi-mount * without a root mount. In this case we return 1 if the * path is a mount point and the super magic of the covering * mount if there is one or 0 if it isn't a mountpoint. * * If we aren't supplied with a file descriptor then we * lookup the path and check if it is the root of a mount. * If a type is given we are looking for a particular autofs * mount and if we don't find a match we return fail. If the * located path is the root of a mount we return 1 along with * the super magic of the mount or 0 otherwise. * * In both cases the the device number (as returned by * new_encode_dev()) is also returned. */ static int autofs_dev_ioctl_ismountpoint(struct file *fp, struct autofs_sb_info *sbi, struct autofs_dev_ioctl *param) { struct path path; const char *name; unsigned int type; unsigned int devid, magic; int err = -ENOENT; if (param->size <= AUTOFS_DEV_IOCTL_SIZE) { err = -EINVAL; goto out; } name = param->path; type = param->ismountpoint.in.type; param->ismountpoint.out.devid = devid = 0; param->ismountpoint.out.magic = magic = 0; if (!fp || param->ioctlfd == -1) { if (autofs_type_any(type)) err = kern_path_mountpoint(AT_FDCWD, name, &path, LOOKUP_FOLLOW); else err = find_autofs_mount(name, &path, test_by_type, &type); if (err) goto out; devid = new_encode_dev(path.dentry->d_sb->s_dev); err = 0; if (path.mnt->mnt_root == path.dentry) { err = 1; magic = path.dentry->d_sb->s_magic; } } else { dev_t dev = sbi->sb->s_dev; err = find_autofs_mount(name, &path, test_by_dev, &dev); if (err) goto out; devid = new_encode_dev(dev); err = path_has_submounts(&path); if (follow_down_one(&path)) magic = path.dentry->d_sb->s_magic; } param->ismountpoint.out.devid = devid; param->ismountpoint.out.magic = magic; path_put(&path); out: return err; } /* * Our range of ioctl numbers isn't 0 based so we need to shift * the array index by _IOC_NR(AUTOFS_CTL_IOC_FIRST) for the table * lookup. */ #define cmd_idx(cmd) (cmd - _IOC_NR(AUTOFS_DEV_IOCTL_IOC_FIRST)) static ioctl_fn lookup_dev_ioctl(unsigned int cmd) { static ioctl_fn _ioctls[] = { autofs_dev_ioctl_version, autofs_dev_ioctl_protover, autofs_dev_ioctl_protosubver, autofs_dev_ioctl_openmount, autofs_dev_ioctl_closemount, autofs_dev_ioctl_ready, autofs_dev_ioctl_fail, autofs_dev_ioctl_setpipefd, autofs_dev_ioctl_catatonic, autofs_dev_ioctl_timeout, autofs_dev_ioctl_requester, autofs_dev_ioctl_expire, autofs_dev_ioctl_askumount, autofs_dev_ioctl_ismountpoint, }; unsigned int idx = cmd_idx(cmd); return (idx >= ARRAY_SIZE(_ioctls)) ? NULL : _ioctls[idx]; } /* ioctl dispatcher */ static int _autofs_dev_ioctl(unsigned int command, struct autofs_dev_ioctl __user *user) { struct autofs_dev_ioctl *param; struct file *fp; struct autofs_sb_info *sbi; unsigned int cmd_first, cmd; ioctl_fn fn = NULL; int err = 0; cmd_first = _IOC_NR(AUTOFS_DEV_IOCTL_IOC_FIRST); cmd = _IOC_NR(command); if (_IOC_TYPE(command) != _IOC_TYPE(AUTOFS_DEV_IOCTL_IOC_FIRST) || cmd - cmd_first > AUTOFS_DEV_IOCTL_IOC_COUNT) { return -ENOTTY; } /* Only root can use ioctls other than AUTOFS_DEV_IOCTL_VERSION_CMD * and AUTOFS_DEV_IOCTL_ISMOUNTPOINT_CMD */ if (cmd != AUTOFS_DEV_IOCTL_VERSION_CMD && cmd != AUTOFS_DEV_IOCTL_ISMOUNTPOINT_CMD && !capable(CAP_SYS_ADMIN)) return -EPERM; /* Copy the parameters into kernel space. */ param = copy_dev_ioctl(user); if (IS_ERR(param)) return PTR_ERR(param); err = validate_dev_ioctl(command, param); if (err) goto out; fn = lookup_dev_ioctl(cmd); if (!fn) { pr_warn("unknown command 0x%08x\n", command); err = -ENOTTY; goto out; } fp = NULL; sbi = NULL; /* * For obvious reasons the openmount can't have a file * descriptor yet. We don't take a reference to the * file during close to allow for immediate release, * and the same for retrieving ioctl version. */ if (cmd != AUTOFS_DEV_IOCTL_VERSION_CMD && cmd != AUTOFS_DEV_IOCTL_OPENMOUNT_CMD && cmd != AUTOFS_DEV_IOCTL_CLOSEMOUNT_CMD) { fp = fget(param->ioctlfd); if (!fp) { if (cmd == AUTOFS_DEV_IOCTL_ISMOUNTPOINT_CMD) goto cont; err = -EBADF; goto out; } sbi = autofs_dev_ioctl_sbi(fp); if (!sbi || sbi->magic != AUTOFS_SBI_MAGIC) { err = -EINVAL; fput(fp); goto out; } /* * Admin needs to be able to set the mount catatonic in * order to be able to perform the re-open. */ if (!autofs4_oz_mode(sbi) && cmd != AUTOFS_DEV_IOCTL_CATATONIC_CMD) { err = -EACCES; fput(fp); goto out; } } cont: err = fn(fp, sbi, param); if (fp) fput(fp); if (err >= 0 && copy_to_user(user, param, AUTOFS_DEV_IOCTL_SIZE)) err = -EFAULT; out: free_dev_ioctl(param); return err; } static long autofs_dev_ioctl(struct file *file, unsigned int command, unsigned long u) { int err; err = _autofs_dev_ioctl(command, (struct autofs_dev_ioctl __user *) u); return (long) err; } #ifdef CONFIG_COMPAT static long autofs_dev_ioctl_compat(struct file *file, unsigned int command, unsigned long u) { return autofs_dev_ioctl(file, command, (unsigned long) compat_ptr(u)); } #else #define autofs_dev_ioctl_compat NULL #endif static const struct file_operations _dev_ioctl_fops = { .unlocked_ioctl = autofs_dev_ioctl, .compat_ioctl = autofs_dev_ioctl_compat, .owner = THIS_MODULE, .llseek = noop_llseek, }; static struct miscdevice _autofs_dev_ioctl_misc = { .minor = AUTOFS_MINOR, .name = AUTOFS_DEVICE_NAME, .fops = &_dev_ioctl_fops, .mode = 0644, }; MODULE_ALIAS_MISCDEV(AUTOFS_MINOR); MODULE_ALIAS("devname:autofs"); /* Register/deregister misc character device */ int __init autofs_dev_ioctl_init(void) { int r; r = misc_register(&_autofs_dev_ioctl_misc); if (r) { pr_err("misc_register failed for control device\n"); return r; } return 0; } void autofs_dev_ioctl_exit(void) { misc_deregister(&_autofs_dev_ioctl_misc); }
{ "pile_set_name": "Github" }
Copyright (c) 2010, Michael Bostock All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name Michael Bostock may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
{ "pile_set_name": "Github" }
# Azure Function with Transform ![Azure Public Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/201-logic-app-transform-function/PublicLastTestDate.svg) ![Azure Public Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/201-logic-app-transform-function/PublicDeployment.svg) ![Azure US Gov Last Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/201-logic-app-transform-function/FairfaxLastTestDate.svg) ![Azure US Gov Last Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/201-logic-app-transform-function/FairfaxDeployment.svg) ![Best Practice Check](https://azurequickstartsservice.blob.core.windows.net/badges/201-logic-app-transform-function/BestPracticeResult.svg) ![Cred Scan Check](https://azurequickstartsservice.blob.core.windows.net/badges/201-logic-app-transform-function/CredScanResult.svg) [![Deploy To Azure](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazure.svg?sanitize=true)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F201-logic-app-transform-function%2Fazuredeploy.json) [![Deploy To Azure US Gov](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazuregov.svg?sanitize=true)](https://portal.azure.us/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F201-logic-app-transform-function%2Fazuredeploy.json) [![Visualize](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/visualizebutton.svg?sanitize=true)](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F201-logic-app-transform-function%2Fazuredeploy.json) This template creates a webhook based C# azure function with transform capabilites to use in logic apps integration scenarios. ## Prerequisites In order to properly deploy this ARM template, you need to first create a function app/container and provide the name of that function app in the parameters.
{ "pile_set_name": "Github" }
# 2010 April 13 # # The author disclaims copyright to this source code. In place of # a legal notice, here is a blessing: # # May you do good and not evil. # May you find forgiveness for yourself and forgive others. # May you share freely, never taking more than you give. # #*********************************************************************** # This file implements regression tests for SQLite library. The # focus of this file is testing the operation of "blocking-checkpoint" # operations. # set testdir [file dirname $argv0] source $testdir/tester.tcl source $testdir/lock_common.tcl source $testdir/wal_common.tcl ifcapable !wal {finish_test ; return } do_not_use_codec set testprefix wal5 proc db_page_count {{file test.db}} { expr [file size $file] / 1024 } proc wal_page_count {{file test.db}} { wal_frame_count ${file}-wal 1024 } # A checkpoint may be requested either using the C API or by executing # an SQL PRAGMA command. To test both methods, all tests in this file are # run twice - once using each method to request checkpoints. # foreach {testprefix do_wal_checkpoint} { wal5-pragma { proc do_wal_checkpoint { dbhandle args } { array set a $args foreach key [array names a] { if {[lsearch {-mode -db} $key]<0} { error "unknown switch: $key" } } set sql "PRAGMA " if {[info exists a(-db)]} { append sql "$a(-db)." } append sql "wal_checkpoint" if {[info exists a(-mode)]} { append sql " = $a(-mode)" } uplevel [list $dbhandle eval $sql] } } wal5-capi { proc do_wal_checkpoint { dbhandle args } { set a(-mode) passive array set a $args foreach key [array names a] { if {[lsearch {-mode -db} $key]<0} { error "unknown switch: $key" } } set vals {restart full truncate} if {[lsearch -exact $vals $a(-mode)]<0} { set a(-mode) passive } set cmd [list sqlite3_wal_checkpoint_v2 $dbhandle $a(-mode)] if {[info exists a(-db)]} { lappend sql $a(-db) } uplevel $cmd } } } { eval $do_wal_checkpoint do_multiclient_test tn { set ::nBusyHandler 0 set ::busy_handler_script "" proc busyhandler {n} { incr ::nBusyHandler eval $::busy_handler_script return 0 } proc reopen_all {} { code1 {db close} code2 {db2 close} code3 {db3 close} code1 {sqlite3 db test.db} code2 {sqlite3 db2 test.db} code3 {sqlite3 db3 test.db} sql1 { PRAGMA synchronous = NORMAL } code1 { db busy busyhandler } } do_test 1.$tn.1 { reopen_all sql1 { PRAGMA page_size = 1024; PRAGMA auto_vacuum = 0; CREATE TABLE t1(x, y); PRAGMA journal_mode = WAL; INSERT INTO t1 VALUES(1, zeroblob(1200)); INSERT INTO t1 VALUES(2, zeroblob(1200)); INSERT INTO t1 VALUES(3, zeroblob(1200)); } expr [file size test.db] / 1024 } {2} # Have connection 2 grab a read-lock on the current snapshot. do_test 1.$tn.2 { sql2 { BEGIN; SELECT x FROM t1 } } {1 2 3} # Attempt a checkpoint. do_test 1.$tn.3 { code1 { do_wal_checkpoint db } list [db_page_count] [wal_page_count] } {5 9} # Write to the db again. The log cannot wrap because of the lock still # held by connection 2. The busy-handler has not yet been invoked. do_test 1.$tn.4 { sql1 { INSERT INTO t1 VALUES(4, zeroblob(1200)) } list [db_page_count] [wal_page_count] $::nBusyHandler } {5 12 0} # Now do a blocking-checkpoint. Set the busy-handler up so that connection # 2 releases its lock on the 6th invocation. The checkpointer should then # proceed to checkpoint the entire log file. Next write should go to the # start of the log file. # set ::busy_handler_script { if {$n==5} { sql2 COMMIT } } do_test 1.$tn.5 { code1 { do_wal_checkpoint db -mode restart } list [db_page_count] [wal_page_count] $::nBusyHandler } {6 12 6} do_test 1.$tn.6 { set ::nBusyHandler 0 sql1 { INSERT INTO t1 VALUES(5, zeroblob(1200)) } list [db_page_count] [wal_page_count] $::nBusyHandler } {6 12 0} do_test 1.$tn.7 { reopen_all list [db_page_count] [wal_page_count] $::nBusyHandler } [expr {[nonzero_reserved_bytes]?"/# # 0/":"7 0 0"}] do_test 1.$tn.8 { sql2 { BEGIN ; SELECT x FROM t1 } } {1 2 3 4 5} do_test 1.$tn.9 { sql1 { INSERT INTO t1 VALUES(6, zeroblob(1200)) } list [db_page_count] [wal_page_count] $::nBusyHandler } [expr {[nonzero_reserved_bytes]?"/# # #/":"7 5 0"}] do_test 1.$tn.10 { sql3 { BEGIN ; SELECT x FROM t1 } } {1 2 3 4 5 6} set ::busy_handler_script { if {$n==5} { sql2 COMMIT } if {$n==6} { set ::db_file_size [db_page_count] } if {$n==7} { sql3 COMMIT } } do_test 1.$tn.11 { code1 { do_wal_checkpoint db -mode restart } list [db_page_count] [wal_page_count] $::nBusyHandler } [expr {[nonzero_reserved_bytes]?"/# # #/":"10 5 8"}] do_test 1.$tn.12 { set ::db_file_size } 10 } #------------------------------------------------------------------------- # This block of tests explores checkpoint operations on more than one # database file. # proc setup_and_attach_aux {} { sql1 { ATTACH 'test.db2' AS aux } sql2 { ATTACH 'test.db2' AS aux } sql3 { ATTACH 'test.db2' AS aux } sql1 { PRAGMA aux.auto_vacuum = 0; PRAGMA main.auto_vacuum = 0; PRAGMA main.page_size=1024; PRAGMA main.journal_mode=WAL; PRAGMA aux.page_size=1024; PRAGMA aux.journal_mode=WAL; } } proc file_page_counts {} { list [db_page_count test.db ] \ [wal_page_count test.db ] \ [db_page_count test.db2] \ [wal_page_count test.db2] } # Test that executing "PRAGMA wal_checkpoint" checkpoints all attached # databases, not just the main db. In capi mode, check that this is # true if a NULL pointer is passed to wal_checkpoint_v2() in place of a # database name. do_multiclient_test tn { setup_and_attach_aux do_test 2.1.$tn.1 { sql1 { CREATE TABLE t1(a, b); INSERT INTO t1 VALUES(1, 2); CREATE TABLE aux.t2(a, b); INSERT INTO t2 VALUES(1, 2); } } {} do_test 2.2.$tn.2 { file_page_counts } {1 3 1 3} do_test 2.1.$tn.3 { code1 { do_wal_checkpoint db } } {0 3 3} do_test 2.1.$tn.4 { file_page_counts } {2 3 2 3} } do_multiclient_test tn { setup_and_attach_aux do_test 2.2.$tn.1 { execsql { CREATE TABLE t1(a, b); INSERT INTO t1 VALUES(1, 2); CREATE TABLE aux.t2(a, b); INSERT INTO t2 VALUES(1, 2); INSERT INTO t2 VALUES(3, 4); } } {} do_test 2.2.$tn.2 { file_page_counts } {1 3 1 4} do_test 2.2.$tn.3 { sql2 { BEGIN; SELECT * FROM t1 } } {1 2} do_test 2.2.$tn.4 { code1 { do_wal_checkpoint db -mode restart } } {1 3 3} do_test 2.2.$tn.5 { file_page_counts } {2 3 2 4} } do_multiclient_test tn { setup_and_attach_aux do_test 2.3.$tn.1 { execsql { CREATE TABLE t1(a, b); INSERT INTO t1 VALUES(1, 2); CREATE TABLE aux.t2(a, b); INSERT INTO t2 VALUES(1, 2); } } {} do_test 2.3.$tn.2 { file_page_counts } {1 3 1 3} do_test 2.3.$tn.3 { sql2 { BEGIN; SELECT * FROM t1 } } {1 2} do_test 2.3.$tn.4 { sql1 { INSERT INTO t1 VALUES(3, 4) } } {} do_test 2.3.$tn.5 { sql1 { INSERT INTO t2 VALUES(3, 4) } } {} do_test 2.3.$tn.6 { file_page_counts } {1 4 1 4} do_test 2.3.$tn.7 { code1 { do_wal_checkpoint db -mode full } } {1 4 3} # The checkpoint above only writes page 1 of the db file. The other # page (page 2) is locked by the read-transaction opened by the # [sql2] commmand above. So normally, the db is 1 page in size here. # However, in mmap() mode, the db is pre-allocated to 2 pages at the # start of the checkpoint, even though page 2 cannot be written. set nDb 2 if {[permutation]!="mmap"} {set nDb 1} ifcapable !mmap {set nDb 1} do_test 2.3.$tn.8 { file_page_counts } [list $nDb 4 2 4] } # Check that checkpoints block on the correct locks. And respond correctly # if they cannot obtain those locks. There are three locks that a checkpoint # may block on (in the following order): # # 1. The writer lock: FULL and RESTART checkpoints block until any writer # process releases its lock. # # 2. Readers using part of the log file. FULL and RESTART checkpoints block # until readers using part (but not all) of the log file have finished. # # 3. Readers using any of the log file. After copying data into the # database file, RESTART checkpoints block until readers using any part # of the log file have finished. # # This test case involves running a checkpoint while there exist other # processes holding all three types of locks. # foreach {tn1 checkpoint busy_on ckpt_expected expected} { 1 PASSIVE - {0 3 3} - 2 TYPO - {0 3 3} - 3 FULL - {0 4 4} 2 4 FULL 1 {1 3 3} 1 5 FULL 2 {1 4 3} 2 6 FULL 3 {0 4 4} 2 7 RESTART - {0 4 4} 3 8 RESTART 1 {1 3 3} 1 9 RESTART 2 {1 4 3} 2 10 RESTART 3 {1 4 4} 3 11 TRUNCATE - {0 0 0} 3 12 TRUNCATE 1 {1 3 3} 1 13 TRUNCATE 2 {1 4 3} 2 14 TRUNCATE 3 {1 4 4} 3 } { do_multiclient_test tn { setup_and_attach_aux proc busyhandler {x} { set ::max_busyhandler $x if {$::busy_on!="-" && $x==$::busy_on} { return 1 } switch -- $x { 1 { sql2 "COMMIT ; BEGIN ; SELECT * FROM t1" } 2 { sql3 "COMMIT" } 3 { sql2 "COMMIT" } } return 0 } set ::max_busyhandler - do_test 2.4.$tn1.$tn.1 { sql1 { CREATE TABLE t1(a, b); INSERT INTO t1 VALUES(1, 2); } sql2 { BEGIN; INSERT INTO t1 VALUES(3, 4) } sql3 { BEGIN; SELECT * FROM t1 } } {1 2} do_test 2.4.$tn1.$tn.2 { code1 { db busy busyhandler } code1 { do_wal_checkpoint db -mode [string tolower $checkpoint] } } $ckpt_expected do_test 2.4.$tn1.$tn.3 { set ::max_busyhandler } $expected } } do_multiclient_test tn { code1 $do_wal_checkpoint code2 $do_wal_checkpoint code3 $do_wal_checkpoint do_test 3.$tn.1 { sql1 { PRAGMA auto_vacuum = 0; PRAGMA journal_mode = WAL; PRAGMA synchronous = normal; CREATE TABLE t1(x, y); } sql2 { PRAGMA journal_mode } sql3 { PRAGMA journal_mode } } {wal} do_test 3.$tn.2 { code2 { do_wal_checkpoint db2 } } {0 2 2} do_test 3.$tn.3 { code2 { do_wal_checkpoint db2 } } {0 2 2} do_test 3.$tn.4 { code3 { do_wal_checkpoint db3 } } {0 2 2} code1 {db close} code2 {db2 close} code3 {db3 close} code1 {sqlite3 db test.db} code2 {sqlite3 db2 test.db} code3 {sqlite3 db3 test.db} do_test 3.$tn.5 { sql3 { PRAGMA journal_mode } } {wal} do_test 3.$tn.6 { code3 { do_wal_checkpoint db3 } } {0 0 0} } # Test SQLITE_CHECKPOINT_TRUNCATE. # do_multiclient_test tn { code1 $do_wal_checkpoint code2 $do_wal_checkpoint code3 $do_wal_checkpoint do_test 4.$tn.1 { sql1 { PRAGMA page_size = 1024; PRAGMA auto_vacuum = 0; PRAGMA journal_mode = WAL; PRAGMA synchronous = normal; CREATE TABLE t1(x, y); CREATE INDEX i1 ON t1(x, y); INSERT INTO t1 VALUES(1, 2); INSERT INTO t1 VALUES(3, 4); } file size test.db-wal } [wal_file_size 8 1024] do_test 4.$tn.2 { do_wal_checkpoint db -mode truncate } {0 0 0} do_test 4.$tn.3 { file size test.db-wal } 0 do_test 4.$tn.4 { sql2 { SELECT * FROM t1 } } {1 2 3 4} do_test 4.$tn.5 { sql2 { INSERT INTO t1 VALUES('a', 'b') } file size test.db-wal } [wal_file_size 2 1024] } # Test that FULL, RESTART and TRUNCATE callbacks block on other clients # and truncate the wal file as required even if the entire wal file has # already been checkpointed when they are invoked. # do_multiclient_test tn { code1 $do_wal_checkpoint code2 $do_wal_checkpoint code3 $do_wal_checkpoint do_test 5.$tn.1 { sql1 { PRAGMA page_size = 1024; PRAGMA auto_vacuum = 0; PRAGMA journal_mode = WAL; PRAGMA synchronous = normal; CREATE TABLE t1(x, y); CREATE INDEX i1 ON t1(x, y); INSERT INTO t1 VALUES(1, 2); INSERT INTO t1 VALUES(3, 4); INSERT INTO t1 VALUES(5, 6); } file size test.db-wal } [wal_file_size 10 1024] do_test 5.$tn.2 { sql2 { BEGIN; SELECT * FROM t1 } } {1 2 3 4 5 6} do_test 5.$tn.3 { do_wal_checkpoint db -mode passive } {0 10 10} do_test 5.$tn.4 { sql3 { BEGIN; INSERT INTO t1 VALUES(7, 8); } } {} do_test 5.$tn.5 { do_wal_checkpoint db -mode passive } {0 10 10} do_test 5.$tn.6 { do_wal_checkpoint db -mode full } {1 10 10} do_test 5.$tn.7 { sql3 { ROLLBACK } } {} do_test 5.$tn.8 { do_wal_checkpoint db -mode full } {0 10 10} do_test 5.$tn.9 { do_wal_checkpoint db -mode truncate } {1 10 10} do_test 5.$tn.10 { file size test.db-wal } [wal_file_size 10 1024] proc xBusyHandler {n} { sql2 { COMMIT } ; return 0 } db busy xBusyHandler do_test 5.$tn.11 { do_wal_checkpoint db -mode truncate } {0 0 0} do_test 5.$tn.12 { file size test.db-wal } 0 do_test 5.$tn.13 { sql1 { INSERT INTO t1 VALUES(7, 8); INSERT INTO t1 VALUES(9, 10); SELECT * FROM t1; } } {1 2 3 4 5 6 7 8 9 10} do_test 5.$tn.14 { sql2 { BEGIN; SELECT * FROM t1 } } {1 2 3 4 5 6 7 8 9 10} proc xBusyHandler {n} { return 1 } do_test 5.$tn.15 { do_wal_checkpoint db -mode truncate } {1 4 4} do_test 5.$tn.16 { file size test.db-wal } [wal_file_size 4 1024] do_test 5.$tn.17 { do_wal_checkpoint db -mode restart } {1 4 4} proc xBusyHandler {n} { sql2 { COMMIT } ; return 0 } db busy xBusyHandler do_test 5.$tn.18 { do_wal_checkpoint db -mode restart } {0 4 4} do_test 5.$tn.19 { file size test.db-wal } [wal_file_size 4 1024] do_test 5.$tn.20 { do_wal_checkpoint db -mode truncate } {0 0 0} do_test 5.$tn.21 { file size test.db-wal } 0 } } finish_test
{ "pile_set_name": "Github" }
blender = add alpha = 200 invisible = 1 occluded = 1 col_layer = -1 light_radius=10 render_layer = 8 on timer( 3 ) remove()
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <link rel="stylesheet" href="style.css" type="text/css"> <meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type"> <link rel="Start" href="index.html"> <link rel="previous" href="Scanf.html"> <link rel="next" href="Sort.html"> <link rel="Up" href="index.html"> <link title="Index of types" rel=Appendix href="index_types.html"> <link title="Index of exceptions" rel=Appendix href="index_exceptions.html"> <link title="Index of values" rel=Appendix href="index_values.html"> <link title="Index of class attributes" rel=Appendix href="index_attributes.html"> <link title="Index of class methods" rel=Appendix href="index_methods.html"> <link title="Index of classes" rel=Appendix href="index_classes.html"> <link title="Index of modules" rel=Appendix href="index_modules.html"> <link title="Index of module types" rel=Appendix href="index_module_types.html"> <link title="Arg" rel="Chapter" href="Arg.html"> <link title="Arg_helper" rel="Chapter" href="Arg_helper.html"> <link title="Arith_status" rel="Chapter" href="Arith_status.html"> <link title="Array" rel="Chapter" href="Array.html"> <link title="ArrayLabels" rel="Chapter" href="ArrayLabels.html"> <link title="Ast_helper" rel="Chapter" href="Ast_helper.html"> <link title="Ast_invariants" rel="Chapter" href="Ast_invariants.html"> <link title="Ast_iterator" rel="Chapter" href="Ast_iterator.html"> <link title="Ast_mapper" rel="Chapter" href="Ast_mapper.html"> <link title="Asttypes" rel="Chapter" href="Asttypes.html"> <link title="Attr_helper" rel="Chapter" href="Attr_helper.html"> <link title="Big_int" rel="Chapter" href="Big_int.html"> <link title="Bigarray" rel="Chapter" href="Bigarray.html"> <link title="Buffer" rel="Chapter" href="Buffer.html"> <link title="Builtin_attributes" rel="Chapter" href="Builtin_attributes.html"> <link title="Bytes" rel="Chapter" href="Bytes.html"> <link title="BytesLabels" rel="Chapter" href="BytesLabels.html"> <link title="Callback" rel="Chapter" href="Callback.html"> <link title="CamlinternalFormat" rel="Chapter" href="CamlinternalFormat.html"> <link title="CamlinternalFormatBasics" rel="Chapter" href="CamlinternalFormatBasics.html"> <link title="CamlinternalLazy" rel="Chapter" href="CamlinternalLazy.html"> <link title="CamlinternalMod" rel="Chapter" href="CamlinternalMod.html"> <link title="CamlinternalOO" rel="Chapter" href="CamlinternalOO.html"> <link title="Ccomp" rel="Chapter" href="Ccomp.html"> <link title="Char" rel="Chapter" href="Char.html"> <link title="Clflags" rel="Chapter" href="Clflags.html"> <link title="Complex" rel="Chapter" href="Complex.html"> <link title="Condition" rel="Chapter" href="Condition.html"> <link title="Config" rel="Chapter" href="Config.html"> <link title="Consistbl" rel="Chapter" href="Consistbl.html"> <link title="Digest" rel="Chapter" href="Digest.html"> <link title="Docstrings" rel="Chapter" href="Docstrings.html"> <link title="Dynlink" rel="Chapter" href="Dynlink.html"> <link title="Ephemeron" rel="Chapter" href="Ephemeron.html"> <link title="Event" rel="Chapter" href="Event.html"> <link title="Filename" rel="Chapter" href="Filename.html"> <link title="Format" rel="Chapter" href="Format.html"> <link title="Gc" rel="Chapter" href="Gc.html"> <link title="Genlex" rel="Chapter" href="Genlex.html"> <link title="Graphics" rel="Chapter" href="Graphics.html"> <link title="GraphicsX11" rel="Chapter" href="GraphicsX11.html"> <link title="Hashtbl" rel="Chapter" href="Hashtbl.html"> <link title="Identifiable" rel="Chapter" href="Identifiable.html"> <link title="Int32" rel="Chapter" href="Int32.html"> <link title="Int64" rel="Chapter" href="Int64.html"> <link title="Lazy" rel="Chapter" href="Lazy.html"> <link title="Lexer" rel="Chapter" href="Lexer.html"> <link title="Lexing" rel="Chapter" href="Lexing.html"> <link title="List" rel="Chapter" href="List.html"> <link title="ListLabels" rel="Chapter" href="ListLabels.html"> <link title="Location" rel="Chapter" href="Location.html"> <link title="Longident" rel="Chapter" href="Longident.html"> <link title="Map" rel="Chapter" href="Map.html"> <link title="Marshal" rel="Chapter" href="Marshal.html"> <link title="Misc" rel="Chapter" href="Misc.html"> <link title="MoreLabels" rel="Chapter" href="MoreLabels.html"> <link title="Mutex" rel="Chapter" href="Mutex.html"> <link title="Nativeint" rel="Chapter" href="Nativeint.html"> <link title="Num" rel="Chapter" href="Num.html"> <link title="Numbers" rel="Chapter" href="Numbers.html"> <link title="Obj" rel="Chapter" href="Obj.html"> <link title="Oo" rel="Chapter" href="Oo.html"> <link title="Parse" rel="Chapter" href="Parse.html"> <link title="Parser" rel="Chapter" href="Parser.html"> <link title="Parsetree" rel="Chapter" href="Parsetree.html"> <link title="Parsing" rel="Chapter" href="Parsing.html"> <link title="Pervasives" rel="Chapter" href="Pervasives.html"> <link title="Pprintast" rel="Chapter" href="Pprintast.html"> <link title="Printast" rel="Chapter" href="Printast.html"> <link title="Printexc" rel="Chapter" href="Printexc.html"> <link title="Printf" rel="Chapter" href="Printf.html"> <link title="Queue" rel="Chapter" href="Queue.html"> <link title="Random" rel="Chapter" href="Random.html"> <link title="Ratio" rel="Chapter" href="Ratio.html"> <link title="Scanf" rel="Chapter" href="Scanf.html"> <link title="Set" rel="Chapter" href="Set.html"> <link title="Sort" rel="Chapter" href="Sort.html"> <link title="Stack" rel="Chapter" href="Stack.html"> <link title="StdLabels" rel="Chapter" href="StdLabels.html"> <link title="Str" rel="Chapter" href="Str.html"> <link title="Stream" rel="Chapter" href="Stream.html"> <link title="String" rel="Chapter" href="String.html"> <link title="StringLabels" rel="Chapter" href="StringLabels.html"> <link title="Strongly_connected_components" rel="Chapter" href="Strongly_connected_components.html"> <link title="Syntaxerr" rel="Chapter" href="Syntaxerr.html"> <link title="Sys" rel="Chapter" href="Sys.html"> <link title="Tbl" rel="Chapter" href="Tbl.html"> <link title="Terminfo" rel="Chapter" href="Terminfo.html"> <link title="Thread" rel="Chapter" href="Thread.html"> <link title="ThreadUnix" rel="Chapter" href="ThreadUnix.html"> <link title="Timings" rel="Chapter" href="Timings.html"> <link title="Uchar" rel="Chapter" href="Uchar.html"> <link title="Unix" rel="Chapter" href="Unix.html"> <link title="UnixLabels" rel="Chapter" href="UnixLabels.html"> <link title="Warnings" rel="Chapter" href="Warnings.html"> <link title="Weak" rel="Chapter" href="Weak.html"><title>Set</title> </head> <body> <div class="navbar"><a class="pre" href="Scanf.html" title="Scanf">Previous</a> &nbsp;<a class="up" href="index.html" title="Index">Up</a> &nbsp;<a class="post" href="Sort.html" title="Sort">Next</a> </div> <h1>Module <a href="type_Set.html">Set</a></h1> <pre><span class="keyword">module</span> Set: <code class="code"><span class="keyword">sig</span></code> <a href="Set.html">..</a> <code class="code"><span class="keyword">end</span></code></pre><div class="info module top"> Sets over ordered types. <p> This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. <p> The <code class="code"><span class="constructor">Make</span></code> functor constructs implementations for any type, given a <code class="code">compare</code> function. For instance: <pre class="codepre"><code class="code">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">module</span>&nbsp;<span class="constructor">IntPairs</span>&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">struct</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">type</span>&nbsp;t&nbsp;=&nbsp;int&nbsp;*&nbsp;int &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">let</span>&nbsp;compare&nbsp;(x0,y0)&nbsp;(x1,y1)&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">match</span>&nbsp;<span class="constructor">Pervasives</span>.compare&nbsp;x0&nbsp;x1&nbsp;<span class="keyword">with</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;<span class="keywordsign">-&gt;</span>&nbsp;<span class="constructor">Pervasives</span>.compare&nbsp;y0&nbsp;y1 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keywordsign">|</span>&nbsp;c&nbsp;<span class="keywordsign">-&gt;</span>&nbsp;c &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">end</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">module</span>&nbsp;<span class="constructor">PairsSet</span>&nbsp;=&nbsp;<span class="constructor">Set</span>.<span class="constructor">Make</span>(<span class="constructor">IntPairs</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">let</span>&nbsp;m&nbsp;=&nbsp;<span class="constructor">PairsSet</span>.(empty&nbsp;|&gt;&nbsp;add&nbsp;(2,3)&nbsp;|&gt;&nbsp;add&nbsp;(5,7)&nbsp;|&gt;&nbsp;add&nbsp;(11,13)) &nbsp;&nbsp;&nbsp;</code></pre> <p> This creates a new module <code class="code"><span class="constructor">PairsSet</span></code>, with a new type <code class="code"><span class="constructor">PairsSet</span>.t</code> of sets of <code class="code">int * int</code>.<br> </div> <hr width="100%"> <pre><span class="keyword">module type</span> <a href="Set.OrderedType.html">OrderedType</a> = <code class="code"><span class="keyword">sig</span></code> <a href="Set.OrderedType.html">..</a> <code class="code"><span class="keyword">end</span></code></pre><div class="info"> Input signature of the functor <a href="Set.Make.html"><code class="code"><span class="constructor">Set</span>.<span class="constructor">Make</span></code></a>. </div> <pre><span class="keyword">module type</span> <a href="Set.S.html">S</a> = <code class="code"><span class="keyword">sig</span></code> <a href="Set.S.html">..</a> <code class="code"><span class="keyword">end</span></code></pre><div class="info"> Output signature of the functor <a href="Set.Make.html"><code class="code"><span class="constructor">Set</span>.<span class="constructor">Make</span></code></a>. </div> <pre><span class="keyword">module</span> <a href="Set.Make.html">Make</a>: <div class="sig_block"><code class="code"><span class="keyword">functor</span> (</code><code class="code"><span class="constructor">Ord</span></code><code class="code"> : </code><code class="type"><a href="Set.OrderedType.html">OrderedType</a></code><code class="code">) <span class="keywordsign">-&gt;</span> </code><code class="type"><a href="Set.S.html">S</a></code><code class="type"> with type elt = Ord.t</code></div></pre><div class="info"> Functor building an implementation of the set structure given a totally ordered type. </div> </body></html>
{ "pile_set_name": "Github" }
<?php /** * This web page receives requests for web-pages hosted by modules, and directs them to * the process() handler in the Module class. */ require_once('_include.php'); \SimpleSAML\Module::process()->send();
{ "pile_set_name": "Github" }
/* Copyright 2016 Goldman Sachs. 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.gs.fw.common.mithra.test; import com.gs.fw.common.mithra.MithraManagerProvider; import com.gs.fw.common.mithra.MithraTransaction; import com.gs.fw.common.mithra.TransactionalCommand; import com.gs.fw.common.mithra.test.domain.*; public class TestPersistedNonTransactional extends MithraTestAbstract { public Class[] getRestrictedClassList() { return new Class[] { OrderAsTxReadOnly.class, AuditedOrderAsTxReadOnly.class, OrderStatusAsTxReadOnly.class }; } /* Order and OrderStatus are both configured with ReadOnly txParticipation*/ public void testRetrievingFromMithraCacheUsingRelationship() { OrderAsTxReadOnly order = OrderAsTxReadOnlyFinder.findOne(OrderAsTxReadOnlyFinder.orderId().eq(1)); //first retrieval goes to DB and retrieves successfully assertNotNull(order.getOrderStatus()); //second retrieval goes to cache and throws assertNotNull(order.getOrderStatus()); } public void testNonTxRead() { OrderAsTxReadOnlyList orders = OrderAsTxReadOnlyFinder.findMany(OrderAsTxReadOnlyFinder.userId().eq(1)); assertEquals(3, orders.size()); AuditedOrderAsTxReadOnlyList moreOrders = AuditedOrderAsTxReadOnlyFinder.findMany(AuditedOrderAsTxReadOnlyFinder.userId().eq(1)); assertEquals(4, moreOrders.size()); } public void testNonTxReadInTx() { final OrderAsTxReadOnlyList orders = OrderAsTxReadOnlyFinder.findMany(OrderAsTxReadOnlyFinder.userId().eq(1)); assertEquals(3, orders.size()); final AuditedOrderAsTxReadOnlyList moreOrders = AuditedOrderAsTxReadOnlyFinder.findMany(AuditedOrderAsTxReadOnlyFinder.userId().eq(1)); assertEquals(4, moreOrders.size()); int count = this.getRetrievalCount(); MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand<Object>() { @Override public Object executeTransaction(MithraTransaction tx) throws Throwable { orders.setOrderBy(OrderAsTxReadOnlyFinder.orderId().ascendingOrderBy()); assertEquals(1, orders.get(0).getOrderId()); assertEquals(1, orders.get(0).getUserId()); moreOrders.setOrderBy(AuditedOrderAsTxReadOnlyFinder.orderId().ascendingOrderBy()); assertEquals(1, moreOrders.get(0).getOrderId()); assertEquals(1, moreOrders.get(0).getUserId()); return null; } }); assertEquals(count, this.getRetrievalCount()); } }
{ "pile_set_name": "Github" }
/** * Flot plugin that provides spline interpolation for line graphs * author: Alex Bardas < alex.bardas@gmail.com > * modified by: Avi Kohn https://github.com/AMKohn * based on the spline interpolation described at: * http://scaledinnovation.com/analytics/splines/aboutSplines.html * * Example usage: (add in plot options series object) * for linespline: * series: { * ... * lines: { * show: false * }, * splines: { * show: true, * tension: x, (float between 0 and 1, defaults to 0.5), * lineWidth: y (number, defaults to 2), * fill: z (float between 0 .. 1 or false, as in flot documentation) * }, * ... * } * areaspline: * series: { * ... * lines: { * show: true, * lineWidth: 0, (line drawing will not execute) * fill: x, (float between 0 .. 1, as in flot documentation) * ... * }, * splines: { * show: true, * tension: 0.5 (float between 0 and 1) * }, * ... * } * */ (function($) { 'use strict' /** * @param {Number} x0, y0, x1, y1: coordinates of the end (knot) points of the segment * @param {Number} x2, y2: the next knot (not connected, but needed to calculate p2) * @param {Number} tension: control how far the control points spread * @return {Array}: p1 -> control point, from x1 back toward x0 * p2 -> the next control point, returned to become the next segment's p1 * * @api private */ function getControlPoints(x0, y0, x1, y1, x2, y2, tension) { var pow = Math.pow, sqrt = Math.sqrt, d01, d12, fa, fb, p1x, p1y, p2x, p2y; // Scaling factors: distances from this knot to the previous and following knots. d01 = sqrt(pow(x1 - x0, 2) + pow(y1 - y0, 2)); d12 = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)); fa = tension * d01 / (d01 + d12); fb = tension - fa; p1x = x1 + fa * (x0 - x2); p1y = y1 + fa * (y0 - y2); p2x = x1 - fb * (x0 - x2); p2y = y1 - fb * (y0 - y2); return [p1x, p1y, p2x, p2y]; } var line = []; function drawLine(points, ctx, height, fill, seriesColor) { var c = $.color.parse(seriesColor); c.a = typeof fill == "number" ? fill : .3; c.normalize(); c = c.toString(); ctx.beginPath(); ctx.moveTo(points[0][0], points[0][1]); var plength = points.length; for (var i = 0; i < plength; i++) { ctx[points[i][3]].apply(ctx, points[i][2]); } ctx.stroke(); ctx.lineWidth = 0; ctx.lineTo(points[plength - 1][0], height); ctx.lineTo(points[0][0], height); ctx.closePath(); if (fill !== false) { ctx.fillStyle = c; ctx.fill(); } } /** * @param {Object} ctx: canvas context * @param {String} type: accepted strings: 'bezier' or 'quadratic' (defaults to quadratic) * @param {Array} points: 2 points for which to draw the interpolation * @param {Array} cpoints: control points for those segment points * * @api private */ function queue(ctx, type, points, cpoints) { if (type === void 0 || (type !== 'bezier' && type !== 'quadratic')) { type = 'quadratic'; } type = type + 'CurveTo'; if (line.length == 0) line.push([points[0], points[1], cpoints.concat(points.slice(2)), type]); else if (type == "quadraticCurveTo" && points.length == 2) { cpoints = cpoints.slice(0, 2).concat(points); line.push([points[0], points[1], cpoints, type]); } else line.push([points[2], points[3], cpoints.concat(points.slice(2)), type]); } /** * @param {Object} plot * @param {Object} ctx: canvas context * @param {Object} series * * @api private */ function drawSpline(plot, ctx, series) { // Not interested if spline is not requested if (series.splines.show !== true) { return; } var cp = [], // array of control points tension = series.splines.tension || 0.5, idx, x, y, points = series.datapoints.points, ps = series.datapoints.pointsize, plotOffset = plot.getPlotOffset(), len = points.length, pts = []; line = []; // Cannot display a linespline/areaspline if there are less than 3 points if (len / ps < 4) { $.extend(series.lines, series.splines); return; } for (idx = 0; idx < len; idx += ps) { x = points[idx]; y = points[idx + 1]; if (x == null || x < series.xaxis.min || x > series.xaxis.max || y < series.yaxis.min || y > series.yaxis.max) { continue; } pts.push(series.xaxis.p2c(x) + plotOffset.left, series.yaxis.p2c(y) + plotOffset.top); } len = pts.length; // Draw an open curve, not connected at the ends for (idx = 0; idx < len - 2; idx += 2) { cp = cp.concat(getControlPoints.apply(this, pts.slice(idx, idx + 6).concat([tension]))); } ctx.save(); ctx.strokeStyle = series.color; ctx.lineWidth = series.splines.lineWidth; queue(ctx, 'quadratic', pts.slice(0, 4), cp.slice(0, 2)); for (idx = 2; idx < len - 3; idx += 2) { queue(ctx, 'bezier', pts.slice(idx, idx + 4), cp.slice(2 * idx - 2, 2 * idx + 2)); } queue(ctx, 'quadratic', pts.slice(len - 2, len), [cp[2 * len - 10], cp[2 * len - 9], pts[len - 4], pts[len - 3]]); drawLine(line, ctx, plot.height() + 10, series.splines.fill, series.color); ctx.restore(); } $.plot.plugins.push({ init: function(plot) { plot.hooks.drawSeries.push(drawSpline); }, options: { series: { splines: { show: false, lineWidth: 2, tension: 0.5, fill: false } } }, name: 'spline', version: '0.8.2' }); })(jQuery);
{ "pile_set_name": "Github" }
/* * Copyright (C) 2013-2015 RoboVM AB * * 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.robovm.apple.arkit; /*<imports>*/ import java.io.*; import java.nio.*; import java.util.*; import org.robovm.objc.*; import org.robovm.objc.annotation.*; import org.robovm.objc.block.*; import org.robovm.rt.*; import org.robovm.rt.annotation.*; import org.robovm.rt.bro.*; import org.robovm.rt.bro.annotation.*; import org.robovm.rt.bro.ptr.*; import org.robovm.apple.foundation.*; import org.robovm.apple.avfoundation.*; import org.robovm.apple.coregraphics.*; import org.robovm.apple.uikit.*; import org.robovm.apple.scenekit.*; import org.robovm.apple.corevideo.*; import org.robovm.apple.spritekit.*; import org.robovm.apple.coremedia.*; import org.robovm.apple.dispatch.*; import org.robovm.apple.metal.*; import org.robovm.apple.imageio.*; /*</imports>*/ /*<javadoc>*/ /*</javadoc>*/ /*<annotations>*/@Marshaler(Bits.AsMachineSizedIntMarshaler.class)/*</annotations>*/ public final class /*<name>*/ARPlaneDetection/*</name>*/ extends Bits</*<name>*/ARPlaneDetection/*</name>*/> { /*<values>*/ public static final ARPlaneDetection None = new ARPlaneDetection(0L); public static final ARPlaneDetection Horizontal = new ARPlaneDetection(1L); /** * @since Available in iOS 11.3 and later. */ public static final ARPlaneDetection Vertical = new ARPlaneDetection(2L); /*</values>*/ /*<bind>*/ /*</bind>*/ /*<constants>*//*</constants>*/ /*<methods>*//*</methods>*/ private static final /*<name>*/ARPlaneDetection/*</name>*/[] values = _values(/*<name>*/ARPlaneDetection/*</name>*/.class); public /*<name>*/ARPlaneDetection/*</name>*/(long value) { super(value); } private /*<name>*/ARPlaneDetection/*</name>*/(long value, long mask) { super(value, mask); } protected /*<name>*/ARPlaneDetection/*</name>*/ wrap(long value, long mask) { return new /*<name>*/ARPlaneDetection/*</name>*/(value, mask); } protected /*<name>*/ARPlaneDetection/*</name>*/[] _values() { return values; } public static /*<name>*/ARPlaneDetection/*</name>*/[] values() { return values.clone(); } }
{ "pile_set_name": "Github" }
/* Our web app will be a micro-blogging site. It will only allow people to share 140 characters of their thoughts per post. GL2U. An example of a tweet could be: GOLANG WEB APP TRAININGS from Silicon Valley Code @sv_code_camp 1 of 2: https://youtu.be/qeREX9r20YQ 2 of 2: https://youtu.be/cIatklLmr5I Learn more about documenting your code: https://golang.org/doc/effective_go.html#commentary http://blog.golang.org/godoc-documenting-go-code Use the godoc command to see your documentation: https://godoc.org/golang.org/x/tools/cmd/godoc Try these godoc commands: godoc . godoc -http=:6060 */ package main
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title> Internet Worm Propagation Simulator - Computer Virus Simulators (VX heaven)</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <meta name="Author" content=""/> <meta name="KeyWords" lang="en" content="computer virus, virus, virii,vx, компьютерные вирусы, вирус, вири"/> <meta name="Description" content="Author's description In our research on Internet worm modeling, I have written two Internet worm propagation simulators. One simulator is for simulation of uniform scan worms, such as Code Red and Slammer; another is for simulation of sequential scan worms, such as Blaster. The sequential scan worm simulator assumes that vulnerable hosts are uniformly distributed in BGP routable space. Both are high level simulators for simulating a worm's propagation in the whole Internet. I have not considered packet-level events and Internet topological effect. These simulators do not consider human's countermeasures and congestions caused by worm scan traffic. However, you can decrease the worm's average scan rate in the codes to consider congestion effect; and you can easily modify the codes to consider simple human countermeasures, such as considering the removal of infected hosts that follows Kermack-Mckendrick epidemic model. Both simulators are written in C language for the consideration of simulation speed. They output their simulation results into data files. I write MATLAB programs to draw figures for our papers and to use Kalman filter for early worm detection (please see our papers in CCS'02 and CCS'03). The C simulator for a uniform scan worm is: simulator-codered-100run.cpp The C simulator for a sequential scan worm is: blaster-multiMonitor-100run.cpp The Matlab program for Kalman filter early detection is: KalmanDetection.m The Matlab program to draw a worm's propagation curves is: blasterCodeRedCompare.m The BGP non-overlapping prefix data used in Blaster simulator is (from Route View project for data on Sept. 22, 2003): prefix-len.20030922 The Matlab Simulink program for numerical solution of simple epidemic model is: simpleModel.mdl Notes: The simulators have detailed inline document (both are for 100 simulation runs). For further explanation of formulas, notations, and usage, please see our early worm detection paper in CCS'03 and our recent submitted journal version paper on early worm detection. You can see the Matlab program blasterCodeRedCompare.m to know how to extract data from output data files. In both simulators, we do not use any model. The propagation of a uniform scan worm or a sequential scan follows the simple epidemic model very well when the number of hosts in a simulation is large. MATLAB is very good for data processing and for generating figures for academic paper. We have seen many papers having simulation figures with too small fonts and too thin curves, which can be easily solved by using Matlab. When you use &quot;plot&quot; command in matlab to draw a figure, you can then use the menu in the matlab figure window to directly edit this figure. You can add legend, change font size of labels or axis, change the thickness of curves, add text box, draw lines or arrows, add markers (circle, triangle, square, etc) on curves, change axis' labels, etc. For me, I always first maximize the figure window, then use menu &quot;edit&quot;-&gt;&quot;figure property&quot;-&gt;&quot;apply template&quot; to change all font size to 20 and curve thickness to 2. In this way, the figure will have clear readable fonts and curves in my paper. You can set up this template by using menu &quot;edit&quot;-&gt;&quot;figure property&quot;-&gt;&quot;change template&quot;. After this &quot;apply template&quot; step, I save the figure in Matlab figure format to prepare for future edition and then export it as a EPS color file for my Latex paper. Thus for each figure, I generate two files, one is .fig and one is .eps. (this .fig is also useful when you make Powerpoint slides) After the &quot;apply template&quot; step, if I need, I can change a curve's line pattern or color, size and name of font of each individual object by first selecting this object, then using menu &quot;edit&quot;-&gt;&quot;current object properties&quot;. To add readable markers on curves, I use the following command in matlab program to generate figure: t=1:15:1000; plot(t, data(t),'b--'); Then I add markers on this curve through matlab figure window (without &quot;t&quot;, markers on one curve will squeeze together). If you use Latex to write academic paper, I have written a document to introduce how to write Latex paper in Windows more conveniently than in Linux."/> <script type="text/javascript"> //<![CDATA[ try{if (!window.CloudFlare) {var CloudFlare=[{verbose:0,p:0,byc:0,owlid:"cf",bag2:1,mirage2:0,oracle:0,paths:{cloudflare:"/cdn-cgi/nexp/dok3v=1613a3a185/"},atok:"047a5bcbf67431883fc9ed25fba33612",petok:"739312c68ec365398de91cdd21c6f5f088b6ef0a-1498760111-1800",zone:"vxheaven.org",rocket:"a",apps:{}}];document.write('<script type="text/javascript" src="//ajax.cloudflare.com/cdn-cgi/nexp/dok3v=85b614c0f6/cloudflare.min.js"><'+'\/script>');}}catch(e){}; //]]> </script> <link rel="icon" href="/favicon.ico" type="image/x-icon"/> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/> <link rel="stylesheet" type="text/css" href="/style.css"/> <script type="text/rocketscript" data-rocketsrc="https://apis.google.com/js/plusone.js">{"parsetags": "explicit"}</script> </head> <body bgcolor="#dbc8a0" text="#302000" link="#225599" vlink="#113366"> <div class="s1"> <h1><a href="/" style="text-decoration: none; color: #000000;">VX Heaven</a></h1> <span class="nav"><a href="/lib/">Biblioteka</a> <a href="/vl.php">Collection</a> <a href="/src.php">Sources</a> <a href="/vx.php?id=eidx">Engines</a> <a href="/vx.php?id=tidx">Constructors</a> <a href="/vx.php?id=sidx">Simulators</a> <a href="/vx.php?id=uidx">Utilities</a> <a href="/links.php">Links</a> <a href="/donate.php" style="color: #706020" id="donate">Donate</a> <a href="/forum" style="text-decoration: underline;">Forum</a> </span><br clear="all"/> </div> <div><div style="float:right;"><a href="/vx.php?tbs=0"><img src="/img/min.gif" alt="Minimize"/></a></div> <form id="lf" style="margin: 0; float: right;" method="get" action="/index.php"><input type="hidden" name="action" value="set"/><select name="lang" onchange="javascript:document.getElementById('lf').submit();"><option value="ru">Русский</option><option value="en">English</option><option value="ua">Українська</option><option value="de">Deutsch</option><option value="es">Español</option><option value="fr">Fran&ccedil;ais</option><option value="it">Italiano</option><option selected="selected" value="pl">Polski</option></select></form> <div style="float: right;"><div id="plusone"></div></div> <script type="text/rocketscript">gapi.plusone.render("plusone", {"size":"small","count":"true"});</script> <div style="float: right;" class="addthis_toolbox addthis_default_style"> <script type="text/rocketscript">var addthis_config = { ui_click: true }</script> <a style="text-decoration: none; font-size: 10pt;" href="/?action=addthis" class="addthis_button_compact">Bookmark</a> <script type="text/rocketscript" data-rocketsrc="http://s7.addthis.com/js/250/addthis_widget.js#username=herm1t"></script> </div> <div style="float: left;"> <script type="text/rocketscript" data-rocketsrc="http://www.google.com/cse/brand?form=cse-search-box&amp;lang=en"></script> <form action="/search.php" id="cse-search-box"> <input type="hidden" name="cx" value="002577580816726040001:z9_irkorydo"/> <input type="hidden" name="cof" value="FORID:10"/> <input type="hidden" name="ie" value="UTF-8"/> <input type="text" name="q" size="32" value=" "/> <input type="submit" name="sa" value="Search"/> </form> </div><br clear="both"/></div> <div class="s2"> [<a href="/vx.php?id=sh00">Previous</a>] [<a href="/vx.php?id=sidx">Index</a>] [<a href="/vx.php?id=sn00">Next</a>] <h1> Internet Worm Propagation Simulator</h1><p><strong>Author: Zou, Cliff</strong></p><p><strong>Author's description</strong></p> <p>In our research on Internet worm modeling, I have written two Internet worm propagation simulators. One simulator is for simulation of uniform scan worms, such as Code Red and Slammer; another is for simulation of sequential scan worms, such as Blaster. The sequential scan worm simulator assumes that vulnerable hosts are uniformly distributed in BGP routable space.</p> <p>Both are high level simulators for simulating a worm's propagation in the whole Internet. I have not considered packet-level events and Internet topological effect. These simulators do not consider human's countermeasures and congestions caused by worm scan traffic. However, you can decrease the worm's average scan rate in the codes to consider congestion effect; and you can easily modify the codes to consider simple human countermeasures, such as considering the removal of infected hosts that follows Kermack-Mckendrick epidemic model.</p> <p>Both simulators are written in C language for the consideration of simulation speed. They output their simulation results into data files. I write MATLAB programs to draw figures for our papers and to use Kalman filter for early worm detection (please see our papers in CCS'02 and CCS'03).</p> <ul> <li>The C simulator for a uniform scan worm is: simulator-codered-100run.cpp</li> <li>The C simulator for a sequential scan worm is: blaster-multiMonitor-100run.cpp</li> <li>The Matlab program for Kalman filter early detection is: KalmanDetection.m</li> <li>The Matlab program to draw a worm's propagation curves is: blasterCodeRedCompare.m</li> <li>The BGP non-overlapping prefix data used in Blaster simulator is (from Route View project for data on Sept. 22, 2003): prefix-len.20030922</li> <li>The Matlab Simulink program for numerical solution of simple epidemic model is: simpleModel.mdl</li> </ul> <p>Notes:</p> <ol> <li>The simulators have detailed inline document (both are for 100 simulation runs). For further explanation of formulas, notations, and usage, please see our early worm detection paper in CCS'03 and our recent submitted journal version paper on early worm detection. You can see the Matlab program blasterCodeRedCompare.m to know how to extract data from output data files.</li> <li>In both simulators, we do not use any model. The propagation of a uniform scan worm or a sequential scan follows the simple epidemic model very well when the number of hosts in a simulation is large.</li> <li>MATLAB is very good for data processing and for generating figures for academic paper. We have seen many papers having simulation figures with too small fonts and too thin curves, which can be easily solved by using Matlab. When you use "plot" command in matlab to draw a figure, you can then use the menu in the matlab figure window to directly edit this figure. You can add legend, change font size of labels or axis, change the thickness of curves, add text box, draw lines or arrows, add markers (circle, triangle, square, etc) on curves, change axis' labels, etc. <p>For me, I always first maximize the figure window, then use menu "edit"->"figure property"->"apply template" to change all font size to 20 and curve thickness to 2. In this way, the figure will have clear readable fonts and curves in my paper. You can set up this template by using menu "edit"->"figure property"->"change template". After this "apply template" step, I save the figure in Matlab figure format to prepare for future edition and then export it as a EPS color file for my Latex paper. Thus for each figure, I generate two files, one is .fig and one is .eps. (this .fig is also useful when you make Powerpoint slides)</p> <p>After the "apply template" step, if I need, I can change a curve's line pattern or color, size and name of font of each individual object by first selecting this object, then using menu "edit"->"current object properties". To add readable markers on curves, I use the following command in matlab program to generate figure: t=1:15:1000; plot(t, data(t),'b--'); Then I add markers on this curve through matlab figure window (without "t", markers on one curve will squeeze together).</p></li> <li>If you use Latex to write academic paper, I have written a document to introduce how to write Latex paper in Windows more conveniently than in Linux.</li> </ol><br clear="all"/><script type="text/rocketscript">var disqus_url = 'http://vxheaven.org/vx.php?id=si00';</script><a href="/vx.php?id=si00#disqus_thread">Comments</a><br/><div style="float:left;"><div style="float: left;"><strong>Download</strong></div><br clear="all"/><table cellspacing="0" cellpadding="0" border="1"><tr bgcolor="#aaa999"><th>&nbsp;</th><th>Filename</th><th>Size</th><th>Description</th><th>Date</th><th>&nbsp;</th></tr><tr bgcolor="#cccbbb"><td><form class="fr" method="post" action="/file.php"><input type="image" src="/img/dl.gif" alt="Download"/><input type="hidden" name="file" value="c2ltL2l3cHMuemlw"/></form></td><td><a name="f1461"></a><small><a href="/dl/sim/iwps.zip">iwps.zip</a></small></td><td><small>190458</small></td><td><small>IWPS</small></td><td><small>Feb 2004</small></td><td><small style="float: right; font-family: fixed;">MD5 sum 815759fc506fb4b652e9bc47caf6d3c0</small></td></tr></table></div><br clear="all"/><br/><div class="s2"> <div id="disqus_thread"></div> <script type="text/rocketscript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'vxheaven'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript></div> <div><small>By accessing, viewing, downloading or otherwise using this content you agree to be bound by the <a href="/agreement.php">Terms of Use</a>!</small> <small>vxheaven.org aka vx.netlux.org</small></div> <div style="margin-top: 2px; float: left;" class="adsapeu"> <script type="text/rocketscript"> <!-- var _acic={dataProvider:10};(function(){var e=document.createElement("script");e.type="text/javascript";e.async=true;e.src="//www.acint.net/aci.js";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)})() //--> </script> </div> <script data-rocketsrc="http://www.google-analytics.com/urchin.js" type="text/rocketscript"></script><script type="text/rocketscript">try { _uacct = "UA-590608-1"; urchinTracker(); } catch(err) {}</script> <div style="display: none;"><a href="/vx.php?lang=de&amp;id=si00">de</a><a href="/vx.php?lang=en&amp;id=si00">en</a><a href="/vx.php?lang=es&amp;id=si00">es</a><a href="/vx.php?lang=it&amp;id=si00">it</a><a href="/vx.php?lang=fr&amp;id=si00">fr</a><a href="/vx.php?lang=pl&amp;id=si00">pl</a><a href="/vx.php?lang=ru&amp;id=si00">ru</a><a href="/vx.php?lang=ua&amp;id=si00">ua</a></div> </body> </html>
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head xmlns:v="urn:"> <title>VML Playground</title> <style type="text/css"> #input { width: 90%; height: 200px; margin: 10px; } #output { margin: 10px; height: 400px; position: relative; border: 1px solid #CCC; } v\:*, v\:* * { behavior: url(#default#VML); position: absolute; } </style> <script type="text/javascript"> window.onload = function() { var input = document.getElementById('input'), output = document.getElementById('output'), timer; function update() { output.innerHTML = input.value; } input.onkeyup = function() { if (timer) { clearTimeout(timer); } timer = setTimeout(update, 500); }; update(); } </script> </head> <body> <textarea id="input"> <outset-box-shadow style="POSITION: absolute; TOP: 0px; LEFT: 0px"> <group1> <v:shape coordsize="408,208" coordorigin="1,1" path=" m-16,32 qy32,-16 l376,-16 qx424,32 l424,176 qy376,224 l32,224 qx-16,176 x e" stroked="false" filled="true" style="POSITION: absolute; WIDTH: 204px; HEIGHT: 104px; TOP: 4px; LEFT: 0px"> <v:fill type="gradientTitle" color="#999" color2="#999" colors="" opacity="0" src="" position="0,0" angle="0" method="any" focusposition="4766f,8738f" focussize="56003f,48059f" /> <v:stroke color="black" weight="0.75" dashstyle="" linestyle="single" /> </v:shape> </group1> </outset-box-shadow> <background style="POSITION: absolute; TOP: 0px; LEFT: 0px"> <group2> <v:shape coordsize="408,208" coordorigin="1,1" path=" m0,32 qy32,0 l376,0 qx408,32 l408,176 qy376,208 l32,208 qx0,176 x e" stroked="false" filled="true" style="POSITION: absolute; WIDTH: 204px; HEIGHT: 104px; TOP: 0px; LEFT: 0px"> <v:fill type="gradient" color="#9cf" color2="#03c" colors="" opacity="1" src="" position="0,0" angle="180" method="sigma" focusposition="0,0" focussize="0,0" /> <v:stroke color="black" weight="0.75" dashstyle="" linestyle="single" /> </v:shape> </group2> </background> <border style="POSITION: absolute; TOP: 0px; LEFT: 0px"> <v:shape coordsize="408,208" coordorigin="1,1" path=" m2,32 qy32,2 l376,2 qx406,32 l406,176 qy376,206 l32,206 qx2,176 x e" stroked="true" filled="false" style="POSITION: absolute; WIDTH: 204px; HEIGHT: 104px; TOP: 0px; LEFT: 0px"> <v:fill type="solid" color="white" color2="white" colors="" opacity="1" src="" position="0,0" angle="0" method="any" focusposition="0,0" focussize="0,0" /> <v:stroke color="#00c" weight="1.5" dashstyle="solid" linestyle="single" /> </v:shape> </border> <!-- <v:skew on="t" origin="0,0" matrix="1 0 0 1 0 0" /> --> </textarea> <div id="output"> <!-- VML will get inserted here --> </div> </body> </html>
{ "pile_set_name": "Github" }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('shell', function() { var words = {}; function define(style, string) { var split = string.split(' '); for(var i = 0; i < split.length; i++) { words[split[i]] = style; } }; // Atoms define('atom', 'true false'); // Keywords define('keyword', 'if then do else elif while until for in esac fi fin ' + 'fil done exit set unset export function'); // Commands define('builtin', 'ab awk bash beep cat cc cd chown chmod chroot clear cp ' + 'curl cut diff echo find gawk gcc get git grep kill killall ln ls make ' + 'mkdir openssl mv nc node npm ping ps restart rm rmdir sed service sh ' + 'shopt shred source sort sleep ssh start stop su sudo tee telnet top ' + 'touch vi vim wall wc wget who write yes zsh'); function tokenBase(stream, state) { if (stream.eatSpace()) return null; var sol = stream.sol(); var ch = stream.next(); if (ch === '\\') { stream.next(); return null; } if (ch === '\'' || ch === '"' || ch === '`') { state.tokens.unshift(tokenString(ch)); return tokenize(stream, state); } if (ch === '#') { if (sol && stream.eat('!')) { stream.skipToEnd(); return 'meta'; // 'comment'? } stream.skipToEnd(); return 'comment'; } if (ch === '$') { state.tokens.unshift(tokenDollar); return tokenize(stream, state); } if (ch === '+' || ch === '=') { return 'operator'; } if (ch === '-') { stream.eat('-'); stream.eatWhile(/\w/); return 'attribute'; } if (/\d/.test(ch)) { stream.eatWhile(/\d/); if(stream.eol() || !/\w/.test(stream.peek())) { return 'number'; } } stream.eatWhile(/[\w-]/); var cur = stream.current(); if (stream.peek() === '=' && /\w+/.test(cur)) return 'def'; return words.hasOwnProperty(cur) ? words[cur] : null; } function tokenString(quote) { return function(stream, state) { var next, end = false, escaped = false; while ((next = stream.next()) != null) { if (next === quote && !escaped) { end = true; break; } if (next === '$' && !escaped && quote !== '\'') { escaped = true; stream.backUp(1); state.tokens.unshift(tokenDollar); break; } escaped = !escaped && next === '\\'; } if (end || !escaped) { state.tokens.shift(); } return (quote === '`' || quote === ')' ? 'quote' : 'string'); }; }; var tokenDollar = function(stream, state) { if (state.tokens.length > 1) stream.eat('$'); var ch = stream.next(), hungry = /\w/; if (ch === '{') hungry = /[^}]/; if (ch === '(') { state.tokens[0] = tokenString(')'); return tokenize(stream, state); } if (!/\d/.test(ch)) { stream.eatWhile(hungry); stream.eat('}'); } state.tokens.shift(); return 'def'; }; function tokenize(stream, state) { return (state.tokens[0] || tokenBase) (stream, state); }; return { startState: function() {return {tokens:[]};}, token: function(stream, state) { return tokenize(stream, state); }, lineComment: '#', fold: "brace" }; }); CodeMirror.defineMIME('text/x-sh', 'shell'); });
{ "pile_set_name": "Github" }
// Copyright 2010 Chris Patterson // // 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 Stact.Data.Internal { using System; public class Single<T, M> : FingerTree<T, M> { readonly T _item; readonly MakeTree<T, M> _mk; public Single(Measured<T, M> m, T item) : base(m, m.Measure(item)) { _item = item; _mk = new MakeTree<T, M>(m); } public T Item { get { return _item; } } public override LeftView<T, M> Left { get { return new LeftView<T, M>(_item, _mk.Empty()); } } public override RightView<T, M> Right { get { return new RightView<T, M>(_item, _mk.Empty()); } } public override U FoldRight<U>(Func<T, Func<U, U>> f, U z) { return f(_item)(z); } public override T ReduceRight(Func<T, Func<T, T>> f) { return _item; } public override U FoldLeft<U>(Func<U, Func<T, U>> f, U z) { return f(z)(_item); } public override T ReduceLeft(Func<T, Func<T, T>> f) { return _item; } public override FingerTree<U, M> Map<U>(Func<T, U> f, Measured<U, M> m) { return new Single<U, M>(m, f(_item)); } public override U Match<U>(Func<Empty<T, M>, U> empty, Func<Single<T, M>, U> single, Func<Deep<T, M>, U> deep) { return single(this); } public override bool Visit(Func<T, bool> callback) { return callback(_item); } public override FingerTree<T, M> AddLeft(T a) { return _mk.Deep(_mk.One(a), new Empty<Node<T, M>, M>(Measured.Node), _mk.One(_item)); } public override FingerTree<T, M> AddRight(T a) { return _mk.Deep(_mk.One(_item), new Empty<Node<T, M>, M>(Measured.Node), _mk.One(a)); } public override FingerTree<T, M> Concat(FingerTree<T, M> t) { return t.AddLeft(_item); } public override Pair<FingerTree<T, M>, FingerTree<T, M>> SplitSequence(MeasurePredicate<M> predicate) { if (predicate(Size)) return new Pair<FingerTree<T, M>, FingerTree<T, M>>(new Empty<T, M>(Measured), this); return new Pair<FingerTree<T, M>, FingerTree<T, M>>(this, new Empty<T, M>(Measured)); } public override Split<T, FingerTree<T, M>, M> Split(MeasurePredicate<M> predicate, M acc) { return new Split<T, FingerTree<T, M>, M>(new Empty<T, M>(Measured), _item, new Empty<T, M>(Measured)); } } }
{ "pile_set_name": "Github" }
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Http * @subpackage Response * @version $Id: Stream.php 23775 2011-03-01 17:25:24Z ralph $ * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * Zend_Http_Response represents an HTTP 1.0 / 1.1 response message. It * includes easy access to all the response's different elemts, as well as some * convenience methods for parsing and validating HTTP responses. * * @package Zend_Http * @subpackage Response * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Http_Response_Stream extends Zend_Http_Response { /** * Response as stream * * @var resource */ protected $stream; /** * The name of the file containing the stream * * Will be empty if stream is not file-based. * * @var string */ protected $stream_name; /** * Should we clean up the stream file when this response is closed? * * @var boolean */ protected $_cleanup; /** * Get the response as stream * * @return resourse */ public function getStream() { return $this->stream; } /** * Set the response stream * * @param resourse $stream * @return Zend_Http_Response_Stream */ public function setStream($stream) { $this->stream = $stream; return $this; } /** * Get the cleanup trigger * * @return boolean */ public function getCleanup() { return $this->_cleanup; } /** * Set the cleanup trigger * * @param bool $cleanup Set cleanup trigger */ public function setCleanup($cleanup = true) { $this->_cleanup = $cleanup; } /** * Get file name associated with the stream * * @return string */ public function getStreamName() { return $this->stream_name; } /** * Set file name associated with the stream * * @param string $stream_name Name to set * @return Zend_Http_Response_Stream */ public function setStreamName($stream_name) { $this->stream_name = $stream_name; return $this; } /** * HTTP response constructor * * In most cases, you would use Zend_Http_Response::fromString to parse an HTTP * response string and create a new Zend_Http_Response object. * * NOTE: The constructor no longer accepts nulls or empty values for the code and * headers and will throw an exception if the passed values do not form a valid HTTP * responses. * * If no message is passed, the message will be guessed according to the response code. * * @param int $code Response code (200, 404, ...) * @param array $headers Headers array * @param string $body Response body * @param string $version HTTP version * @param string $message Response code as text * @throws Zend_Http_Exception */ public function __construct($code, $headers, $body = null, $version = '1.1', $message = null) { if(is_resource($body)) { $this->setStream($body); $body = ''; } parent::__construct($code, $headers, $body, $version, $message); } /** * Create a new Zend_Http_Response_Stream object from a string * * @param string $response_str * @param resource $stream * @return Zend_Http_Response_Stream */ public static function fromStream($response_str, $stream) { $code = self::extractCode($response_str); $headers = self::extractHeaders($response_str); $version = self::extractVersion($response_str); $message = self::extractMessage($response_str); return new self($code, $headers, $stream, $version, $message); } /** * Get the response body as string * * This method returns the body of the HTTP response (the content), as it * should be in it's readable version - that is, after decoding it (if it * was decoded), deflating it (if it was gzip compressed), etc. * * If you want to get the raw body (as transfered on wire) use * $this->getRawBody() instead. * * @return string */ public function getBody() { if($this->stream != null) { $this->readStream(); } return parent::getBody(); } /** * Get the raw response body (as transfered "on wire") as string * * If the body is encoded (with Transfer-Encoding, not content-encoding - * IE "chunked" body), gzip compressed, etc. it will not be decoded. * * @return string */ public function getRawBody() { if($this->stream) { $this->readStream(); } return $this->body; } /** * Read stream content and return it as string * * Function reads the remainder of the body from the stream and closes the stream. * * @return string */ protected function readStream() { if(!is_resource($this->stream)) { return ''; } if(isset($headers['content-length'])) { $this->body = stream_get_contents($this->stream, $headers['content-length']); } else { $this->body = stream_get_contents($this->stream); } fclose($this->stream); $this->stream = null; } public function __destruct() { if(is_resource($this->stream)) { fclose($this->stream); $this->stream = null; } if($this->_cleanup) { @unlink($this->stream_name); } } }
{ "pile_set_name": "Github" }
# Kubernetes Community Code of Conduct Please refer to our [Kubernetes Community Code of Conduct](https://git.k8s.io/community/code-of-conduct.md)
{ "pile_set_name": "Github" }
// Copyright 2015 The Go 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 precis import ( "testing" "golang.org/x/text/runes" ) // Compile-time regression test to ensure that Class is a Set var _ runes.Set = (*class)(nil) // Ensure that certain characters are (or are not) in the identifer class. func TestClassContains(t *testing.T) { tests := []struct { name string class *class allowed []rune disallowed []rune }{ { name: "Identifier", class: identifier, allowed: []rune("Aa0\u0021\u007e\u00df\u3007"), disallowed: []rune("\u2150\u2100\u2200\u3164\u2190\u2600\u303b\u1e9b"), }, { name: "Freeform", class: freeform, allowed: []rune("Aa0\u0021\u007e\u00df\u3007 \u2150\u2100\u2200\u2190\u2600\u1e9b"), disallowed: []rune("\u3164\u303b"), }, } for _, rt := range tests { for _, r := range rt.allowed { if !rt.class.Contains(r) { t.Errorf("Class %s should contain %U", rt.name, r) } } for _, r := range rt.disallowed { if rt.class.Contains(r) { t.Errorf("Class %s should not contain %U", rt.name, r) } } } }
{ "pile_set_name": "Github" }
<html> <head> <link rel="stylesheet" type="text/css" href="css/tips.css"> </head> <body> <h1>InspectCode(检查代码) <a href='https://www.pingfangx.com/xx/translation/feedback?from=tips'>[汉化反馈]</a></h1> <p>使用 <span class="control">Analyze | Inspect Code</span> 来运行整个项目或自定义范围内的代码分析,并以友好的视图检查结果。</p> </body> </html>
{ "pile_set_name": "Github" }
package format import ( "bufio" "bytes" "fmt" "sort" "strings" "github.com/mitchellh/colorstring" "github.com/zclconf/go-cty/cty" ctyjson "github.com/zclconf/go-cty/cty/json" "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" "github.com/hashicorp/terraform-plugin-sdk/internal/plans" "github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange" "github.com/hashicorp/terraform-plugin-sdk/internal/states" ) // ResourceChange returns a string representation of a change to a particular // resource, for inclusion in user-facing plan output. // // The resource schema must be provided along with the change so that the // formatted change can reflect the configuration structure for the associated // resource. // // If "color" is non-nil, it will be used to color the result. Otherwise, // no color codes will be included. func ResourceChange( change *plans.ResourceInstanceChangeSrc, tainted bool, schema *configschema.Block, color *colorstring.Colorize, ) string { addr := change.Addr var buf bytes.Buffer if color == nil { color = &colorstring.Colorize{ Colors: colorstring.DefaultColors, Disable: true, Reset: false, } } dispAddr := addr.String() if change.DeposedKey != states.NotDeposed { dispAddr = fmt.Sprintf("%s (deposed object %s)", dispAddr, change.DeposedKey) } switch change.Action { case plans.Create: buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be created", dispAddr))) case plans.Read: buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be read during apply\n # (config refers to values not yet known)", dispAddr))) case plans.Update: buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be updated in-place", dispAddr))) case plans.CreateThenDelete, plans.DeleteThenCreate: if tainted { buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] is tainted, so must be [bold][red]replaced", dispAddr))) } else { buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] must be [bold][red]replaced", dispAddr))) } case plans.Delete: buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be [bold][red]destroyed", dispAddr))) default: // should never happen, since the above is exhaustive buf.WriteString(fmt.Sprintf("%s has an action the plan renderer doesn't support (this is a bug)", dispAddr)) } buf.WriteString(color.Color("[reset]\n")) switch change.Action { case plans.Create: buf.WriteString(color.Color("[green] +[reset] ")) case plans.Read: buf.WriteString(color.Color("[cyan] <=[reset] ")) case plans.Update: buf.WriteString(color.Color("[yellow] ~[reset] ")) case plans.DeleteThenCreate: buf.WriteString(color.Color("[red]-[reset]/[green]+[reset] ")) case plans.CreateThenDelete: buf.WriteString(color.Color("[green]+[reset]/[red]-[reset] ")) case plans.Delete: buf.WriteString(color.Color("[red] -[reset] ")) default: buf.WriteString(color.Color("??? ")) } switch addr.Resource.Resource.Mode { case addrs.ManagedResourceMode: buf.WriteString(fmt.Sprintf( "resource %q %q", addr.Resource.Resource.Type, addr.Resource.Resource.Name, )) case addrs.DataResourceMode: buf.WriteString(fmt.Sprintf( "data %q %q ", addr.Resource.Resource.Type, addr.Resource.Resource.Name, )) default: // should never happen, since the above is exhaustive buf.WriteString(addr.String()) } buf.WriteString(" {") p := blockBodyDiffPrinter{ buf: &buf, color: color, action: change.Action, requiredReplace: change.RequiredReplace, } // Most commonly-used resources have nested blocks that result in us // going at least three traversals deep while we recurse here, so we'll // start with that much capacity and then grow as needed for deeper // structures. path := make(cty.Path, 0, 3) changeV, err := change.Decode(schema.ImpliedType()) if err != nil { // Should never happen in here, since we've already been through // loads of layers of encode/decode of the planned changes before now. panic(fmt.Sprintf("failed to decode plan for %s while rendering diff: %s", addr, err)) } // We currently have an opt-out that permits the legacy SDK to return values // that defy our usual conventions around handling of nesting blocks. To // avoid the rendering code from needing to handle all of these, we'll // normalize first. // (Ideally we'd do this as part of the SDK opt-out implementation in core, // but we've added it here for now to reduce risk of unexpected impacts // on other code in core.) changeV.Change.Before = objchange.NormalizeObjectFromLegacySDK(changeV.Change.Before, schema) changeV.Change.After = objchange.NormalizeObjectFromLegacySDK(changeV.Change.After, schema) bodyWritten := p.writeBlockBodyDiff(schema, changeV.Before, changeV.After, 6, path) if bodyWritten { buf.WriteString("\n") buf.WriteString(strings.Repeat(" ", 4)) } buf.WriteString("}\n") return buf.String() } type blockBodyDiffPrinter struct { buf *bytes.Buffer color *colorstring.Colorize action plans.Action requiredReplace cty.PathSet } const forcesNewResourceCaption = " [red]# forces replacement[reset]" // writeBlockBodyDiff writes attribute or block differences // and returns true if any differences were found and written func (p *blockBodyDiffPrinter) writeBlockBodyDiff(schema *configschema.Block, old, new cty.Value, indent int, path cty.Path) bool { path = ctyEnsurePathCapacity(path, 1) bodyWritten := false blankBeforeBlocks := false { attrNames := make([]string, 0, len(schema.Attributes)) attrNameLen := 0 for name := range schema.Attributes { oldVal := ctyGetAttrMaybeNull(old, name) newVal := ctyGetAttrMaybeNull(new, name) if oldVal.IsNull() && newVal.IsNull() { // Skip attributes where both old and new values are null // (we do this early here so that we'll do our value alignment // based on the longest attribute name that has a change, rather // than the longest attribute name in the full set.) continue } attrNames = append(attrNames, name) if len(name) > attrNameLen { attrNameLen = len(name) } } sort.Strings(attrNames) if len(attrNames) > 0 { blankBeforeBlocks = true } for _, name := range attrNames { attrS := schema.Attributes[name] oldVal := ctyGetAttrMaybeNull(old, name) newVal := ctyGetAttrMaybeNull(new, name) bodyWritten = true p.writeAttrDiff(name, attrS, oldVal, newVal, attrNameLen, indent, path) } } { blockTypeNames := make([]string, 0, len(schema.BlockTypes)) for name := range schema.BlockTypes { blockTypeNames = append(blockTypeNames, name) } sort.Strings(blockTypeNames) for _, name := range blockTypeNames { blockS := schema.BlockTypes[name] oldVal := ctyGetAttrMaybeNull(old, name) newVal := ctyGetAttrMaybeNull(new, name) bodyWritten = true p.writeNestedBlockDiffs(name, blockS, oldVal, newVal, blankBeforeBlocks, indent, path) // Always include a blank for any subsequent block types. blankBeforeBlocks = true } } return bodyWritten } func (p *blockBodyDiffPrinter) writeAttrDiff(name string, attrS *configschema.Attribute, old, new cty.Value, nameLen, indent int, path cty.Path) { path = append(path, cty.GetAttrStep{Name: name}) p.buf.WriteString("\n") p.buf.WriteString(strings.Repeat(" ", indent)) showJustNew := false var action plans.Action switch { case old.IsNull(): action = plans.Create showJustNew = true case new.IsNull(): action = plans.Delete case ctyEqualWithUnknown(old, new): action = plans.NoOp showJustNew = true default: action = plans.Update } p.writeActionSymbol(action) p.buf.WriteString(p.color.Color("[bold]")) p.buf.WriteString(name) p.buf.WriteString(p.color.Color("[reset]")) p.buf.WriteString(strings.Repeat(" ", nameLen-len(name))) p.buf.WriteString(" = ") if attrS.Sensitive { p.buf.WriteString("(sensitive value)") } else { switch { case showJustNew: p.writeValue(new, action, indent+2) if p.pathForcesNewResource(path) { p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) } default: // We show new even if it is null to emphasize the fact // that it is being unset, since otherwise it is easy to // misunderstand that the value is still set to the old value. p.writeValueDiff(old, new, indent+2, path) } } } func (p *blockBodyDiffPrinter) writeNestedBlockDiffs(name string, blockS *configschema.NestedBlock, old, new cty.Value, blankBefore bool, indent int, path cty.Path) { path = append(path, cty.GetAttrStep{Name: name}) if old.IsNull() && new.IsNull() { // Nothing to do if both old and new is null return } // Where old/new are collections representing a nesting mode other than // NestingSingle, we assume the collection value can never be unknown // since we always produce the container for the nested objects, even if // the objects within are computed. switch blockS.Nesting { case configschema.NestingSingle, configschema.NestingGroup: var action plans.Action eqV := new.Equals(old) switch { case old.IsNull(): action = plans.Create case new.IsNull(): action = plans.Delete case !new.IsWhollyKnown() || !old.IsWhollyKnown(): // "old" should actually always be known due to our contract // that old values must never be unknown, but we'll allow it // anyway to be robust. action = plans.Update case !eqV.IsKnown() || !eqV.True(): action = plans.Update } if blankBefore { p.buf.WriteRune('\n') } p.writeNestedBlockDiff(name, nil, &blockS.Block, action, old, new, indent, path) case configschema.NestingList: // For the sake of handling nested blocks, we'll treat a null list // the same as an empty list since the config language doesn't // distinguish these anyway. old = ctyNullBlockListAsEmpty(old) new = ctyNullBlockListAsEmpty(new) oldItems := ctyCollectionValues(old) newItems := ctyCollectionValues(new) // Here we intentionally preserve the index-based correspondance // between old and new, rather than trying to detect insertions // and removals in the list, because this more accurately reflects // how Terraform Core and providers will understand the change, // particularly when the nested block contains computed attributes // that will themselves maintain correspondance by index. // commonLen is number of elements that exist in both lists, which // will be presented as updates (~). Any additional items in one // of the lists will be presented as either creates (+) or deletes (-) // depending on which list they belong to. var commonLen int switch { case len(oldItems) < len(newItems): commonLen = len(oldItems) default: commonLen = len(newItems) } if blankBefore && (len(oldItems) > 0 || len(newItems) > 0) { p.buf.WriteRune('\n') } for i := 0; i < commonLen; i++ { path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))}) oldItem := oldItems[i] newItem := newItems[i] action := plans.Update if oldItem.RawEquals(newItem) { action = plans.NoOp } p.writeNestedBlockDiff(name, nil, &blockS.Block, action, oldItem, newItem, indent, path) } for i := commonLen; i < len(oldItems); i++ { path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))}) oldItem := oldItems[i] newItem := cty.NullVal(oldItem.Type()) p.writeNestedBlockDiff(name, nil, &blockS.Block, plans.Delete, oldItem, newItem, indent, path) } for i := commonLen; i < len(newItems); i++ { path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))}) newItem := newItems[i] oldItem := cty.NullVal(newItem.Type()) p.writeNestedBlockDiff(name, nil, &blockS.Block, plans.Create, oldItem, newItem, indent, path) } case configschema.NestingSet: // For the sake of handling nested blocks, we'll treat a null set // the same as an empty set since the config language doesn't // distinguish these anyway. old = ctyNullBlockSetAsEmpty(old) new = ctyNullBlockSetAsEmpty(new) oldItems := ctyCollectionValues(old) newItems := ctyCollectionValues(new) if (len(oldItems) + len(newItems)) == 0 { // Nothing to do if both sets are empty return } allItems := make([]cty.Value, 0, len(oldItems)+len(newItems)) allItems = append(allItems, oldItems...) allItems = append(allItems, newItems...) all := cty.SetVal(allItems) if blankBefore { p.buf.WriteRune('\n') } for it := all.ElementIterator(); it.Next(); { _, val := it.Element() var action plans.Action var oldValue, newValue cty.Value switch { case !val.IsKnown(): action = plans.Update newValue = val case !old.HasElement(val).True(): action = plans.Create oldValue = cty.NullVal(val.Type()) newValue = val case !new.HasElement(val).True(): action = plans.Delete oldValue = val newValue = cty.NullVal(val.Type()) default: action = plans.NoOp oldValue = val newValue = val } path := append(path, cty.IndexStep{Key: val}) p.writeNestedBlockDiff(name, nil, &blockS.Block, action, oldValue, newValue, indent, path) } case configschema.NestingMap: // For the sake of handling nested blocks, we'll treat a null map // the same as an empty map since the config language doesn't // distinguish these anyway. old = ctyNullBlockMapAsEmpty(old) new = ctyNullBlockMapAsEmpty(new) oldItems := old.AsValueMap() newItems := new.AsValueMap() if (len(oldItems) + len(newItems)) == 0 { // Nothing to do if both maps are empty return } allKeys := make(map[string]bool) for k := range oldItems { allKeys[k] = true } for k := range newItems { allKeys[k] = true } allKeysOrder := make([]string, 0, len(allKeys)) for k := range allKeys { allKeysOrder = append(allKeysOrder, k) } sort.Strings(allKeysOrder) if blankBefore { p.buf.WriteRune('\n') } for _, k := range allKeysOrder { var action plans.Action oldValue := oldItems[k] newValue := newItems[k] switch { case oldValue == cty.NilVal: oldValue = cty.NullVal(newValue.Type()) action = plans.Create case newValue == cty.NilVal: newValue = cty.NullVal(oldValue.Type()) action = plans.Delete case !newValue.RawEquals(oldValue): action = plans.Update default: action = plans.NoOp } path := append(path, cty.IndexStep{Key: cty.StringVal(k)}) p.writeNestedBlockDiff(name, &k, &blockS.Block, action, oldValue, newValue, indent, path) } } } func (p *blockBodyDiffPrinter) writeNestedBlockDiff(name string, label *string, blockS *configschema.Block, action plans.Action, old, new cty.Value, indent int, path cty.Path) { p.buf.WriteString("\n") p.buf.WriteString(strings.Repeat(" ", indent)) p.writeActionSymbol(action) if label != nil { fmt.Fprintf(p.buf, "%s %q {", name, *label) } else { fmt.Fprintf(p.buf, "%s {", name) } if action != plans.NoOp && (p.pathForcesNewResource(path) || p.pathForcesNewResource(path[:len(path)-1])) { p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) } bodyWritten := p.writeBlockBodyDiff(blockS, old, new, indent+4, path) if bodyWritten { p.buf.WriteString("\n") p.buf.WriteString(strings.Repeat(" ", indent+2)) } p.buf.WriteString("}") } func (p *blockBodyDiffPrinter) writeValue(val cty.Value, action plans.Action, indent int) { if !val.IsKnown() { p.buf.WriteString("(known after apply)") return } if val.IsNull() { p.buf.WriteString(p.color.Color("[dark_gray]null[reset]")) return } ty := val.Type() switch { case ty.IsPrimitiveType(): switch ty { case cty.String: { // Special behavior for JSON strings containing array or object src := []byte(val.AsString()) ty, err := ctyjson.ImpliedType(src) // check for the special case of "null", which decodes to nil, // and just allow it to be printed out directly if err == nil && !ty.IsPrimitiveType() && val.AsString() != "null" { jv, err := ctyjson.Unmarshal(src, ty) if err == nil { p.buf.WriteString("jsonencode(") if jv.LengthInt() == 0 { p.writeValue(jv, action, 0) } else { p.buf.WriteByte('\n') p.buf.WriteString(strings.Repeat(" ", indent+4)) p.writeValue(jv, action, indent+4) p.buf.WriteByte('\n') p.buf.WriteString(strings.Repeat(" ", indent)) } p.buf.WriteByte(')') break // don't *also* do the normal behavior below } } } fmt.Fprintf(p.buf, "%q", val.AsString()) case cty.Bool: if val.True() { p.buf.WriteString("true") } else { p.buf.WriteString("false") } case cty.Number: bf := val.AsBigFloat() p.buf.WriteString(bf.Text('f', -1)) default: // should never happen, since the above is exhaustive fmt.Fprintf(p.buf, "%#v", val) } case ty.IsListType() || ty.IsSetType() || ty.IsTupleType(): p.buf.WriteString("[") it := val.ElementIterator() for it.Next() { _, val := it.Element() p.buf.WriteString("\n") p.buf.WriteString(strings.Repeat(" ", indent+2)) p.writeActionSymbol(action) p.writeValue(val, action, indent+4) p.buf.WriteString(",") } if val.LengthInt() > 0 { p.buf.WriteString("\n") p.buf.WriteString(strings.Repeat(" ", indent)) } p.buf.WriteString("]") case ty.IsMapType(): p.buf.WriteString("{") keyLen := 0 for it := val.ElementIterator(); it.Next(); { key, _ := it.Element() if keyStr := key.AsString(); len(keyStr) > keyLen { keyLen = len(keyStr) } } for it := val.ElementIterator(); it.Next(); { key, val := it.Element() p.buf.WriteString("\n") p.buf.WriteString(strings.Repeat(" ", indent+2)) p.writeActionSymbol(action) p.writeValue(key, action, indent+4) p.buf.WriteString(strings.Repeat(" ", keyLen-len(key.AsString()))) p.buf.WriteString(" = ") p.writeValue(val, action, indent+4) } if val.LengthInt() > 0 { p.buf.WriteString("\n") p.buf.WriteString(strings.Repeat(" ", indent)) } p.buf.WriteString("}") case ty.IsObjectType(): p.buf.WriteString("{") atys := ty.AttributeTypes() attrNames := make([]string, 0, len(atys)) nameLen := 0 for attrName := range atys { attrNames = append(attrNames, attrName) if len(attrName) > nameLen { nameLen = len(attrName) } } sort.Strings(attrNames) for _, attrName := range attrNames { val := val.GetAttr(attrName) p.buf.WriteString("\n") p.buf.WriteString(strings.Repeat(" ", indent+2)) p.writeActionSymbol(action) p.buf.WriteString(attrName) p.buf.WriteString(strings.Repeat(" ", nameLen-len(attrName))) p.buf.WriteString(" = ") p.writeValue(val, action, indent+4) } if len(attrNames) > 0 { p.buf.WriteString("\n") p.buf.WriteString(strings.Repeat(" ", indent)) } p.buf.WriteString("}") } } func (p *blockBodyDiffPrinter) writeValueDiff(old, new cty.Value, indent int, path cty.Path) { ty := old.Type() typesEqual := ctyTypesEqual(ty, new.Type()) // We have some specialized diff implementations for certain complex // values where it's useful to see a visualization of the diff of // the nested elements rather than just showing the entire old and // new values verbatim. // However, these specialized implementations can apply only if both // values are known and non-null. if old.IsKnown() && new.IsKnown() && !old.IsNull() && !new.IsNull() && typesEqual { switch { case ty == cty.String: // We have special behavior for both multi-line strings in general // and for strings that can parse as JSON. For the JSON handling // to apply, both old and new must be valid JSON. // For single-line strings that don't parse as JSON we just fall // out of this switch block and do the default old -> new rendering. oldS := old.AsString() newS := new.AsString() { // Special behavior for JSON strings containing object or // list values. oldBytes := []byte(oldS) newBytes := []byte(newS) oldType, oldErr := ctyjson.ImpliedType(oldBytes) newType, newErr := ctyjson.ImpliedType(newBytes) if oldErr == nil && newErr == nil && !(oldType.IsPrimitiveType() && newType.IsPrimitiveType()) { oldJV, oldErr := ctyjson.Unmarshal(oldBytes, oldType) newJV, newErr := ctyjson.Unmarshal(newBytes, newType) if oldErr == nil && newErr == nil { if !oldJV.RawEquals(newJV) { // two JSON values may differ only in insignificant whitespace p.buf.WriteString("jsonencode(") p.buf.WriteByte('\n') p.buf.WriteString(strings.Repeat(" ", indent+2)) p.writeActionSymbol(plans.Update) p.writeValueDiff(oldJV, newJV, indent+4, path) p.buf.WriteByte('\n') p.buf.WriteString(strings.Repeat(" ", indent)) p.buf.WriteByte(')') } else { // if they differ only in insigificant whitespace // then we'll note that but still expand out the // effective value. if p.pathForcesNewResource(path) { p.buf.WriteString(p.color.Color("jsonencode( [red]# whitespace changes force replacement[reset]")) } else { p.buf.WriteString(p.color.Color("jsonencode( [dim]# whitespace changes[reset]")) } p.buf.WriteByte('\n') p.buf.WriteString(strings.Repeat(" ", indent+4)) p.writeValue(oldJV, plans.NoOp, indent+4) p.buf.WriteByte('\n') p.buf.WriteString(strings.Repeat(" ", indent)) p.buf.WriteByte(')') } return } } } if strings.Index(oldS, "\n") < 0 && strings.Index(newS, "\n") < 0 { break } p.buf.WriteString("<<~EOT") if p.pathForcesNewResource(path) { p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) } p.buf.WriteString("\n") var oldLines, newLines []cty.Value { r := strings.NewReader(oldS) sc := bufio.NewScanner(r) for sc.Scan() { oldLines = append(oldLines, cty.StringVal(sc.Text())) } } { r := strings.NewReader(newS) sc := bufio.NewScanner(r) for sc.Scan() { newLines = append(newLines, cty.StringVal(sc.Text())) } } diffLines := ctySequenceDiff(oldLines, newLines) for _, diffLine := range diffLines { p.buf.WriteString(strings.Repeat(" ", indent+2)) p.writeActionSymbol(diffLine.Action) switch diffLine.Action { case plans.NoOp, plans.Delete: p.buf.WriteString(diffLine.Before.AsString()) case plans.Create: p.buf.WriteString(diffLine.After.AsString()) default: // Should never happen since the above covers all // actions that ctySequenceDiff can return for strings p.buf.WriteString(diffLine.After.AsString()) } p.buf.WriteString("\n") } p.buf.WriteString(strings.Repeat(" ", indent)) // +4 here because there's no symbol p.buf.WriteString("EOT") return case ty.IsSetType(): p.buf.WriteString("[") if p.pathForcesNewResource(path) { p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) } p.buf.WriteString("\n") var addedVals, removedVals, allVals []cty.Value for it := old.ElementIterator(); it.Next(); { _, val := it.Element() allVals = append(allVals, val) if new.HasElement(val).False() { removedVals = append(removedVals, val) } } for it := new.ElementIterator(); it.Next(); { _, val := it.Element() allVals = append(allVals, val) if val.IsKnown() && old.HasElement(val).False() { addedVals = append(addedVals, val) } } var all, added, removed cty.Value if len(allVals) > 0 { all = cty.SetVal(allVals) } else { all = cty.SetValEmpty(ty.ElementType()) } if len(addedVals) > 0 { added = cty.SetVal(addedVals) } else { added = cty.SetValEmpty(ty.ElementType()) } if len(removedVals) > 0 { removed = cty.SetVal(removedVals) } else { removed = cty.SetValEmpty(ty.ElementType()) } for it := all.ElementIterator(); it.Next(); { _, val := it.Element() p.buf.WriteString(strings.Repeat(" ", indent+2)) var action plans.Action switch { case !val.IsKnown(): action = plans.Update case added.HasElement(val).True(): action = plans.Create case removed.HasElement(val).True(): action = plans.Delete default: action = plans.NoOp } p.writeActionSymbol(action) p.writeValue(val, action, indent+4) p.buf.WriteString(",\n") } p.buf.WriteString(strings.Repeat(" ", indent)) p.buf.WriteString("]") return case ty.IsListType() || ty.IsTupleType(): p.buf.WriteString("[") if p.pathForcesNewResource(path) { p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) } p.buf.WriteString("\n") elemDiffs := ctySequenceDiff(old.AsValueSlice(), new.AsValueSlice()) for _, elemDiff := range elemDiffs { p.buf.WriteString(strings.Repeat(" ", indent+2)) p.writeActionSymbol(elemDiff.Action) switch elemDiff.Action { case plans.NoOp, plans.Delete: p.writeValue(elemDiff.Before, elemDiff.Action, indent+4) case plans.Update: p.writeValueDiff(elemDiff.Before, elemDiff.After, indent+4, path) case plans.Create: p.writeValue(elemDiff.After, elemDiff.Action, indent+4) default: // Should never happen since the above covers all // actions that ctySequenceDiff can return. p.writeValue(elemDiff.After, elemDiff.Action, indent+4) } p.buf.WriteString(",\n") } p.buf.WriteString(strings.Repeat(" ", indent)) p.buf.WriteString("]") return case ty.IsMapType(): p.buf.WriteString("{") if p.pathForcesNewResource(path) { p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) } p.buf.WriteString("\n") var allKeys []string keyLen := 0 for it := old.ElementIterator(); it.Next(); { k, _ := it.Element() keyStr := k.AsString() allKeys = append(allKeys, keyStr) if len(keyStr) > keyLen { keyLen = len(keyStr) } } for it := new.ElementIterator(); it.Next(); { k, _ := it.Element() keyStr := k.AsString() allKeys = append(allKeys, keyStr) if len(keyStr) > keyLen { keyLen = len(keyStr) } } sort.Strings(allKeys) lastK := "" for i, k := range allKeys { if i > 0 && lastK == k { continue // skip duplicates (list is sorted) } lastK = k p.buf.WriteString(strings.Repeat(" ", indent+2)) kV := cty.StringVal(k) var action plans.Action if old.HasIndex(kV).False() { action = plans.Create } else if new.HasIndex(kV).False() { action = plans.Delete } else if eqV := old.Index(kV).Equals(new.Index(kV)); eqV.IsKnown() && eqV.True() { action = plans.NoOp } else { action = plans.Update } path := append(path, cty.IndexStep{Key: kV}) p.writeActionSymbol(action) p.writeValue(kV, action, indent+4) p.buf.WriteString(strings.Repeat(" ", keyLen-len(k))) p.buf.WriteString(" = ") switch action { case plans.Create, plans.NoOp: v := new.Index(kV) p.writeValue(v, action, indent+4) case plans.Delete: oldV := old.Index(kV) newV := cty.NullVal(oldV.Type()) p.writeValueDiff(oldV, newV, indent+4, path) default: oldV := old.Index(kV) newV := new.Index(kV) p.writeValueDiff(oldV, newV, indent+4, path) } p.buf.WriteByte('\n') } p.buf.WriteString(strings.Repeat(" ", indent)) p.buf.WriteString("}") return case ty.IsObjectType(): p.buf.WriteString("{") p.buf.WriteString("\n") forcesNewResource := p.pathForcesNewResource(path) var allKeys []string keyLen := 0 for it := old.ElementIterator(); it.Next(); { k, _ := it.Element() keyStr := k.AsString() allKeys = append(allKeys, keyStr) if len(keyStr) > keyLen { keyLen = len(keyStr) } } for it := new.ElementIterator(); it.Next(); { k, _ := it.Element() keyStr := k.AsString() allKeys = append(allKeys, keyStr) if len(keyStr) > keyLen { keyLen = len(keyStr) } } sort.Strings(allKeys) lastK := "" for i, k := range allKeys { if i > 0 && lastK == k { continue // skip duplicates (list is sorted) } lastK = k p.buf.WriteString(strings.Repeat(" ", indent+2)) kV := k var action plans.Action if !old.Type().HasAttribute(kV) { action = plans.Create } else if !new.Type().HasAttribute(kV) { action = plans.Delete } else if eqV := old.GetAttr(kV).Equals(new.GetAttr(kV)); eqV.IsKnown() && eqV.True() { action = plans.NoOp } else { action = plans.Update } path := append(path, cty.GetAttrStep{Name: kV}) p.writeActionSymbol(action) p.buf.WriteString(k) p.buf.WriteString(strings.Repeat(" ", keyLen-len(k))) p.buf.WriteString(" = ") switch action { case plans.Create, plans.NoOp: v := new.GetAttr(kV) p.writeValue(v, action, indent+4) case plans.Delete: oldV := old.GetAttr(kV) newV := cty.NullVal(oldV.Type()) p.writeValueDiff(oldV, newV, indent+4, path) default: oldV := old.GetAttr(kV) newV := new.GetAttr(kV) p.writeValueDiff(oldV, newV, indent+4, path) } p.buf.WriteString("\n") } p.buf.WriteString(strings.Repeat(" ", indent)) p.buf.WriteString("}") if forcesNewResource { p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) } return } } // In all other cases, we just show the new and old values as-is p.writeValue(old, plans.Delete, indent) if new.IsNull() { p.buf.WriteString(p.color.Color(" [dark_gray]->[reset] ")) } else { p.buf.WriteString(p.color.Color(" [yellow]->[reset] ")) } p.writeValue(new, plans.Create, indent) if p.pathForcesNewResource(path) { p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) } } // writeActionSymbol writes a symbol to represent the given action, followed // by a space. // // It only supports the actions that can be represented with a single character: // Create, Delete, Update and NoAction. func (p *blockBodyDiffPrinter) writeActionSymbol(action plans.Action) { switch action { case plans.Create: p.buf.WriteString(p.color.Color("[green]+[reset] ")) case plans.Delete: p.buf.WriteString(p.color.Color("[red]-[reset] ")) case plans.Update: p.buf.WriteString(p.color.Color("[yellow]~[reset] ")) case plans.NoOp: p.buf.WriteString(" ") default: // Should never happen p.buf.WriteString(p.color.Color("? ")) } } func (p *blockBodyDiffPrinter) pathForcesNewResource(path cty.Path) bool { if !p.action.IsReplace() { // "requiredReplace" only applies when the instance is being replaced return false } return p.requiredReplace.Has(path) } func ctyEmptyString(value cty.Value) bool { if !value.IsNull() && value.IsKnown() { valueType := value.Type() if valueType == cty.String && value.AsString() == "" { return true } } return false } func ctyGetAttrMaybeNull(val cty.Value, name string) cty.Value { attrType := val.Type().AttributeType(name) if val.IsNull() { return cty.NullVal(attrType) } // We treat "" as null here // as existing SDK doesn't support null yet. // This allows us to avoid spurious diffs // until we introduce null to the SDK. attrValue := val.GetAttr(name) if ctyEmptyString(attrValue) { return cty.NullVal(attrType) } return attrValue } func ctyCollectionValues(val cty.Value) []cty.Value { if !val.IsKnown() || val.IsNull() { return nil } ret := make([]cty.Value, 0, val.LengthInt()) for it := val.ElementIterator(); it.Next(); { _, value := it.Element() ret = append(ret, value) } return ret } // ctySequenceDiff returns differences between given sequences of cty.Value(s) // in the form of Create, Delete, or Update actions (for objects). func ctySequenceDiff(old, new []cty.Value) []*plans.Change { var ret []*plans.Change lcs := objchange.LongestCommonSubsequence(old, new) var oldI, newI, lcsI int for oldI < len(old) || newI < len(new) || lcsI < len(lcs) { for oldI < len(old) && (lcsI >= len(lcs) || !old[oldI].RawEquals(lcs[lcsI])) { isObjectDiff := old[oldI].Type().IsObjectType() && (newI >= len(new) || new[newI].Type().IsObjectType()) if isObjectDiff && newI < len(new) { ret = append(ret, &plans.Change{ Action: plans.Update, Before: old[oldI], After: new[newI], }) oldI++ newI++ // we also consume the next "new" in this case continue } ret = append(ret, &plans.Change{ Action: plans.Delete, Before: old[oldI], After: cty.NullVal(old[oldI].Type()), }) oldI++ } for newI < len(new) && (lcsI >= len(lcs) || !new[newI].RawEquals(lcs[lcsI])) { ret = append(ret, &plans.Change{ Action: plans.Create, Before: cty.NullVal(new[newI].Type()), After: new[newI], }) newI++ } if lcsI < len(lcs) { ret = append(ret, &plans.Change{ Action: plans.NoOp, Before: lcs[lcsI], After: lcs[lcsI], }) // All of our indexes advance together now, since the line // is common to all three sequences. lcsI++ oldI++ newI++ } } return ret } func ctyEqualWithUnknown(old, new cty.Value) bool { if !old.IsWhollyKnown() || !new.IsWhollyKnown() { return false } return old.Equals(new).True() } // ctyTypesEqual checks equality of two types more loosely // by avoiding checks of object/tuple elements // as we render differences on element-by-element basis anyway func ctyTypesEqual(oldT, newT cty.Type) bool { if oldT.IsObjectType() && newT.IsObjectType() { return true } if oldT.IsTupleType() && newT.IsTupleType() { return true } return oldT.Equals(newT) } func ctyEnsurePathCapacity(path cty.Path, minExtra int) cty.Path { if cap(path)-len(path) >= minExtra { return path } newCap := cap(path) * 2 if newCap < (len(path) + minExtra) { newCap = len(path) + minExtra } newPath := make(cty.Path, len(path), newCap) copy(newPath, path) return newPath } // ctyNullBlockListAsEmpty either returns the given value verbatim if it is non-nil // or returns an empty value of a suitable type to serve as a placeholder for it. // // In particular, this function handles the special situation where a "list" is // actually represented as a tuple type where nested blocks contain // dynamically-typed values. func ctyNullBlockListAsEmpty(in cty.Value) cty.Value { if !in.IsNull() { return in } if ty := in.Type(); ty.IsListType() { return cty.ListValEmpty(ty.ElementType()) } return cty.EmptyTupleVal // must need a tuple, then } // ctyNullBlockMapAsEmpty either returns the given value verbatim if it is non-nil // or returns an empty value of a suitable type to serve as a placeholder for it. // // In particular, this function handles the special situation where a "map" is // actually represented as an object type where nested blocks contain // dynamically-typed values. func ctyNullBlockMapAsEmpty(in cty.Value) cty.Value { if !in.IsNull() { return in } if ty := in.Type(); ty.IsMapType() { return cty.MapValEmpty(ty.ElementType()) } return cty.EmptyObjectVal // must need an object, then } // ctyNullBlockSetAsEmpty either returns the given value verbatim if it is non-nil // or returns an empty value of a suitable type to serve as a placeholder for it. func ctyNullBlockSetAsEmpty(in cty.Value) cty.Value { if !in.IsNull() { return in } // Dynamically-typed attributes are not supported inside blocks backed by // sets, so our result here is always a set. return cty.SetValEmpty(in.Type().ElementType()) }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <model ref="r:2cefd736-58fe-49dc-ad4d-7f3671d30e15(com.mbeddr.mpsutil.dependenciesdiagram.generator.template.main@generator)"> <persistence version="9" /> <languages> <use id="ceab5195-25ea-4f22-9b92-103b95ca8c0c" name="jetbrains.mps.lang.core" version="2" /> <use id="cab214f9-7127-4f03-923a-c64fb67fed05" name="com.mbeddr.mpsutil.dependenciesdiagram" version="0" /> <use id="b401a680-8325-4110-8fd3-84331ff25bef" name="jetbrains.mps.lang.generator" version="3" /> <use id="d7706f63-9be2-479c-a3da-ae92af1e64d5" name="jetbrains.mps.lang.generator.generationContext" version="2" /> <devkit ref="fbc25dd2-5da4-483a-8b19-70928e1b62d7(jetbrains.mps.devkit.general-purpose)" /> </languages> <imports /> <registry> <language id="b401a680-8325-4110-8fd3-84331ff25bef" name="jetbrains.mps.lang.generator"> <concept id="1095416546421" name="jetbrains.mps.lang.generator.structure.MappingConfiguration" flags="ig" index="bUwia" /> </language> <language id="ceab5195-25ea-4f22-9b92-103b95ca8c0c" name="jetbrains.mps.lang.core"> <concept id="1169194658468" name="jetbrains.mps.lang.core.structure.INamedConcept" flags="ng" index="TrEIO"> <property id="1169194664001" name="name" index="TrG5h" /> </concept> </language> </registry> <node concept="bUwia" id="6bKTjCN9ZmW"> <property role="TrG5h" value="main" /> </node> </model>
{ "pile_set_name": "Github" }
ld { GLIBC_PRIVATE { __get_cpu_features; } }
{ "pile_set_name": "Github" }
#include <stdio.h> int main() { char *buf; read(0, buf, -1); puts(buf); return 0; }
{ "pile_set_name": "Github" }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddEditedToCommentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('comments', function (Blueprint $table) { $table->timestamp('edited_at')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('comments', function (Blueprint $table) { // }); } }
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <Document style="helpdocument"> <p style="htitle">Raon-rocaide</p> <p style="hp">'S urrainn dhut do mhuinntir às-àiteachadh dha shaoghal eile le rocaidean 's crìoch a chur air a' gheama le sin.</p> <p style="hp">Feumaidh tu còig rocaidean falamh a losgadh gu soirbheachail mus urrainn dhut tòiseachadh leis an às-àiteachadh. Bidh rum airson 1000 duine anns gach rocaid às-àiteachaidh shoirbheachail.</p> <p style="hp">Tha coltas soirbheas an losgaidh co-ionnan ri ìre an teicneolais aig àm an losgaidh. Mar eisimpleir, bi thu an dùil air ceithir losgaidhean soirbheachail a-mach à còig ma bhios teicneolas de 80% agad. Bidh losgadh soirbheachail an-còmhnaidh ma tha teicneolas de 100% no as àirde agad. Feumaidh tu raon-rocaide ùr a thogail airson gach rocaid a thogas tu.</p> <p style="hp">Cha leig thu leas raointean-rocaide a cheangal ri giùlan cho fad 's a bhios margaid am fagas. Bidh thu feumach air uiread mòr de stàilinn, bathair, obrach 's airgid gus an togail. Nuair a bhios rocaid air a togail, gheibh thu teachdaireachd a' faighneachd dhiot a bheil thu airson a losgadh sa bhad no uaireigin eile. Ma chuireas tu romhad a losgadh uaireigin eile, briog air an raon nuair a bhios tu airson a losgadh. Faodaidh na thogras tu de rocaidean a' feitheamh a bhith agad.</p> <p style="hp">Nuair a bhios rocaid air a togail ach a' feitheamh air losgadh, cha chleachd i stàilinn, bathar no obair tuilleadh ach cosgaidh i fhathast mòran airgid.</p> <p style="hp">Gliocas: cleachd inneal an às-àiteachaidh gus na stòrasan nach deach a cleachdadh a thogail mus mill thu raon-rocaide air a chaitheamh.</p> <p style="hp">Seo raon-rocaide</p> <img src="images/tiles/rocket5.png" halign="center"/> <p style="hp">agus seo ìomhaigheag</p> <img src="images/gui/buttonpanel/transport/rocket.png" halign="center"/> <p style="hsubtitle">Faic cuideachd:</p> <li><a href="market">Margaid</a></li> <li><a href="commodities">Bathar-amh</a></li> <li><a href="evacuate">Às-àiteachadh</a></li> </Document>
{ "pile_set_name": "Github" }
<!-- //********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* --> <common:LayoutAwarePage x:Class="SDKSample.TextEditing.Scenario7" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:SDKSample.TextEditing" xmlns:common="using:SDKSample.Common" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Left" VerticalAlignment="Top"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid x:Name="Input" Grid.Row="0"> <TextBlock TextWrapping="Wrap" Style="{StaticResource BasicTextStyle}" Text="The PasswordBox control provides a secure and developer-customizable way for users to enter passwords. This control renders the text typed by the user as a symbol you can specify. Notice that the PasswordBox below shows a '?' for each letter entered instead of the standard dot. Another feature that has been added in Windows 8 is the password reaveal button. If the user presses this button for 2 seconds, the PasswordBox reveals the text that has been entered into the control. This gives users a way to verify what they have typed in to a PasswordBox so far."/> </Grid> <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1"> <StackPanel> <StackPanel Orientation="Horizontal" Margin="0,0,0,20"> <TextBlock Style="{StaticResource BasicTextStyle}" Width="75" HorizontalAlignment="Right" VerticalAlignment="Center">Username:</TextBlock> <TextBox Width="200" Height="30" HorizontalAlignment="Right"/> </StackPanel> <StackPanel Orientation="Horizontal" Margin="0,0,0,20"> <TextBlock Style="{StaticResource BasicTextStyle}" Width="75" HorizontalAlignment="Right" VerticalAlignment="Center">Password:</TextBlock> <PasswordBox Width="200" Height="30" HorizontalAlignment="Right" PasswordChar="?" IsPasswordRevealButtonEnabled="True"/> </StackPanel> <Button HorizontalAlignment="Left">Login</Button> </StackPanel> </Grid> <!-- Add Storyboards to the visual states below as necessary for supporting the various layouts --> <VisualStateManager.VisualStateGroups> <VisualStateGroup> <VisualState x:Name="FullScreenLandscape"/> <VisualState x:Name="Filled"/> <VisualState x:Name="FullScreenPortrait"/> <VisualState x:Name="Snapped"/> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Grid> </common:LayoutAwarePage>
{ "pile_set_name": "Github" }
--- ID: "0f45df05-546f-462d-97c0-ba4fb2b02564" Parent: "6ecd54a6-fd59-4ec3-ae87-0dbd90fe43bb" Template: "455a3e98-a627-4b40-8035-e683a0331ac7" Path: /sitecore/templates/Feature/Accounts/_MailTemplate/Email Content/Subject DB: master SharedFields: - ID: "ab162cc0-dc80-4abf-8871-998ee5d7ba32" Hint: Type Value: "Single-Line Text" - ID: "ba3f86a2-4a1c-4d78-b63d-91c2779c1b5e" Hint: __Sortorder Value: 200 - ID: "dec8d2d5-e3cf-48b6-a653-8e69e2716641" Hint: __Security Value: | ar|Everyone|pe|+field:read|!*|pd|!*|+field:read|ar|modules\Feature Accounts Admin|pe|+field:write|pd|+field:write| Languages: - Language: en Versions: - Version: 1 Fields: - ID: "25bed78c-4957-4165-998a-ca1b52f67497" Hint: __Created Value: 20151109T091345Z - Language: "ja-JP" Fields: - ID: "19a69332-a23e-4e70-8d16-b2640cb24cc8" Hint: Title Value: 件名 Versions: - Version: 1 Fields: - ID: "25bed78c-4957-4165-998a-ca1b52f67497" Hint: __Created Value: 20170323T054758Z - ID: "5dd74568-4d4b-44c1-b513-0af5f4cda34f" Hint: __Created by Value: | sitecore\Admin
{ "pile_set_name": "Github" }
package org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * @author Ruben Bermudez * @version 1.0 * Represents a link to an animated GIF file stored on the Telegram servers. By default, this * animated GIF file will be sent by the user with an optional caption. Alternatively, you can use * input_message_content to send a message with specified content instead of the animation. */ @JsonDeserialize public class InlineQueryResultCachedGif implements InlineQueryResult { private static final List<String> VALIDTHUMBTYPES = Collections.unmodifiableList(Arrays.asList("image/jpeg", "image/gif", "video/mp4")); private static final String TYPE_FIELD = "type"; private static final String ID_FIELD = "id"; private static final String GIF_FILE_ID_FIELD = "gif_file_id"; private static final String TITLE_FIELD = "title"; private static final String CAPTION_FIELD = "caption"; private static final String THUMBURL_FIELD = "thumb_url"; private static final String THUMBMIMETYPE_FIELD = "thumb_mime_type"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String PARSEMODE_FIELD = "parse_mode"; @JsonProperty(TYPE_FIELD) private final String type = "gif"; ///< Type of the result, must be "gif" @JsonProperty(ID_FIELD) private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(GIF_FILE_ID_FIELD) private String gifFileId; ///< A valid file identifier for the GIF file @JsonProperty(TITLE_FIELD) private String title; ///< Optional. Title for the result @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Caption of the GIF file to be sent @JsonProperty(INPUTMESSAGECONTENT_FIELD) private InputMessageContent inputMessageContent; ///< Optional. Content of the message to be sent instead of the GIF animation @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message @JsonProperty(PARSEMODE_FIELD) private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. @JsonProperty(THUMBURL_FIELD) private String thumbUrl; ///< Optional. URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result @JsonProperty(THUMBMIMETYPE_FIELD) private String thumbUrlType; public InlineQueryResultCachedGif() { super(); } public String getType() { return type; } public String getId() { return id; } public InlineQueryResultCachedGif setId(String id) { this.id = id; return this; } public String getGifFileId() { return gifFileId; } public InlineQueryResultCachedGif setGifFileId(String gifFileId) { this.gifFileId = gifFileId; return this; } public String getTitle() { return title; } public InlineQueryResultCachedGif setTitle(String title) { this.title = title; return this; } public String getCaption() { return caption; } public InlineQueryResultCachedGif setCaption(String caption) { this.caption = caption; return this; } public InputMessageContent getInputMessageContent() { return inputMessageContent; } public InlineQueryResultCachedGif setInputMessageContent(InputMessageContent inputMessageContent) { this.inputMessageContent = inputMessageContent; return this; } public InlineKeyboardMarkup getReplyMarkup() { return replyMarkup; } public InlineQueryResultCachedGif setReplyMarkup(InlineKeyboardMarkup replyMarkup) { this.replyMarkup = replyMarkup; return this; } public String getParseMode() { return parseMode; } public InlineQueryResultCachedGif setParseMode(String parseMode) { this.parseMode = parseMode; return this; } public String getThumbUrl() { return thumbUrl; } public InlineQueryResultCachedGif setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; return this; } public String getThumbUrlType() { return thumbUrlType; } public InlineQueryResultCachedGif setThumbUrlType(String thumbUrlType) { this.thumbUrlType = thumbUrlType; return this; } @Override public void validate() throws TelegramApiValidationException { if (id == null || id.isEmpty()) { throw new TelegramApiValidationException("ID parameter can't be empty", this); } if (gifFileId == null || gifFileId.isEmpty()) { throw new TelegramApiValidationException("GifFileId parameter can't be empty", this); } if (thumbUrlType != null && !VALIDTHUMBTYPES.contains(thumbUrlType)) { throw new TelegramApiValidationException("ThumbUrlType parameter must be one of “image/jpeg”, “image/gif”, or “video/mp4”", this); } if (inputMessageContent != null) { inputMessageContent.validate(); } if (replyMarkup != null) { replyMarkup.validate(); } } @Override public String toString() { return "InlineQueryResultCachedGif{" + "type='" + type + '\'' + ", id='" + id + '\'' + ", gifFileId='" + gifFileId + '\'' + ", title='" + title + '\'' + ", caption='" + caption + '\'' + ", inputMessageContent=" + inputMessageContent + ", replyMarkup=" + replyMarkup + ", parseMode='" + parseMode + '\'' + ", thumbUrl='" + thumbUrl + '\'' + ", thumbUrlType='" + thumbUrlType + '\'' + '}'; } }
{ "pile_set_name": "Github" }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== using System; using System.Diagnostics.Contracts; namespace System.Security.Cryptography { /// <summary> /// Wrapper around the BCrypt implementation of the SHA-512 hashing algorithm /// </summary> [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class SHA512Cng : SHA512 { private BCryptHashAlgorithm m_hashAlgorithm; public SHA512Cng() { Contract.Ensures(m_hashAlgorithm != null); m_hashAlgorithm = new BCryptHashAlgorithm(CngAlgorithm.Sha512, BCryptNative.ProviderName.MicrosoftPrimitiveProvider); } protected override void Dispose(bool disposing) { try { if (disposing) { m_hashAlgorithm.Dispose(); } } finally { base.Dispose(disposing); } } public override void Initialize() { Contract.Assert(m_hashAlgorithm != null); m_hashAlgorithm.Initialize(); } protected override void HashCore(byte[] array, int ibStart, int cbSize) { Contract.Assert(m_hashAlgorithm != null); m_hashAlgorithm.HashCore(array, ibStart, cbSize); } protected override byte[] HashFinal() { Contract.Assert(m_hashAlgorithm != null); return m_hashAlgorithm.HashFinal(); } } }
{ "pile_set_name": "Github" }
{ "e": 4000 }
{ "pile_set_name": "Github" }
/* crypto/rc4/rc4.h */ /* Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #ifndef HEADER_RC4_H # define HEADER_RC4_H # include <openssl/opensslconf.h>/* OPENSSL_NO_RC4, RC4_INT */ # ifdef OPENSSL_NO_RC4 # error RC4 is disabled. # endif # include <stddef.h> #ifdef __cplusplus extern "C" { #endif typedef struct rc4_key_st { RC4_INT x, y; RC4_INT data[256]; } RC4_KEY; const char *RC4_options(void); void RC4_set_key(RC4_KEY *key, int len, const unsigned char *data); void private_RC4_set_key(RC4_KEY *key, int len, const unsigned char *data); void RC4(RC4_KEY *key, size_t len, const unsigned char *indata, unsigned char *outdata); #ifdef __cplusplus } #endif #endif
{ "pile_set_name": "Github" }
{ "collectors": 177791, "comments": 14, "lists": 663, "plays": 461567, "votes": 7994, "watchers": 338732 }
{ "pile_set_name": "Github" }
#!/usr/bin/env python3 # # linearize-hashes.py: List blocks in a linear, no-fork version of the chain. # # Copyright (c) 2013-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from __future__ import print_function try: # Python 3 import http.client as httplib except ImportError: # Python 2 import httplib import json import re import base64 import sys settings = {} ##### Switch endian-ness ##### def hex_switchEndian(s): """ Switches the endianness of a hex string (in pairs of hex chars) """ pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)] return b''.join(pairList[::-1]).decode() class BitcoinRPC: def __init__(self, host, port, username, password): authpair = "%s:%s" % (username, password) authpair = authpair.encode('utf-8') self.authhdr = b"Basic " + base64.b64encode(authpair) self.conn = httplib.HTTPConnection(host, port=port, timeout=30) def execute(self, obj): try: self.conn.request('POST', '/', json.dumps(obj), { 'Authorization' : self.authhdr, 'Content-type' : 'application/json' }) except ConnectionRefusedError: print('RPC connection refused. Check RPC settings and the server status.', file=sys.stderr) return None resp = self.conn.getresponse() if resp is None: print("JSON-RPC: no response", file=sys.stderr) return None body = resp.read().decode('utf-8') resp_obj = json.loads(body) return resp_obj @staticmethod def build_request(idx, method, params): obj = { 'version' : '1.1', 'method' : method, 'id' : idx } if params is None: obj['params'] = [] else: obj['params'] = params return obj @staticmethod def response_is_error(resp_obj): return 'error' in resp_obj and resp_obj['error'] is not None def get_block_hashes(settings, max_blocks_per_call=10000): rpc = BitcoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpassword']) height = settings['min_height'] while height < settings['max_height']+1: num_blocks = min(settings['max_height']+1-height, max_blocks_per_call) batch = [] for x in range(num_blocks): batch.append(rpc.build_request(x, 'getblockhash', [height + x])) reply = rpc.execute(batch) if reply is None: print('Cannot continue. Program will halt.') return None for x,resp_obj in enumerate(reply): if rpc.response_is_error(resp_obj): print('JSON-RPC: error at height', height+x, ': ', resp_obj['error'], file=sys.stderr) exit(1) assert(resp_obj['id'] == x) # assume replies are in-sequence if settings['rev_hash_bytes'] == 'true': resp_obj['result'] = hex_switchEndian(resp_obj['result']) print(resp_obj['result']) height += num_blocks if __name__ == '__main__': if len(sys.argv) != 2: print("Usage: linearize-hashes.py CONFIG-FILE") sys.exit(1) f = open(sys.argv[1]) for line in f: # skip comment lines m = re.search('^\s*#', line) if m: continue # parse key=value lines m = re.search('^(\w+)\s*=\s*(\S.*)$', line) if m is None: continue settings[m.group(1)] = m.group(2) f.close() if 'host' not in settings: settings['host'] = '127.0.0.1' if 'port' not in settings: settings['port'] = 22555 if 'min_height' not in settings: settings['min_height'] = 0 if 'max_height' not in settings: settings['max_height'] = 313000 if 'rev_hash_bytes' not in settings: settings['rev_hash_bytes'] = 'false' if 'rpcuser' not in settings or 'rpcpassword' not in settings: print("Missing username and/or password in cfg file", file=stderr) sys.exit(1) settings['port'] = int(settings['port']) settings['min_height'] = int(settings['min_height']) settings['max_height'] = int(settings['max_height']) # Force hash byte format setting to be lowercase to make comparisons easier. settings['rev_hash_bytes'] = settings['rev_hash_bytes'].lower() get_block_hashes(settings)
{ "pile_set_name": "Github" }
<forms:WindowsPage x:Class="ConnectivityTest.UWP.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:ConnectivityTest.UWP" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:forms="using:Xamarin.Forms.Platform.UWP" mc:Ignorable="d"> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> </Grid> </forms:WindowsPage>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8" ?> <phpunit backupGlobals="true" backupStaticAttributes="false" bootstrap="/path/to/bootstrap.php" cacheTokens="false" colors="false" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" forceCoversAnnotation="false" mapTestClassNameToCoveredClassName="false" printerClass="PHPUnit_TextUI_ResultPrinter" stopOnFailure="false" testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader" timeoutForSmallTests="1" timeoutForMediumTests="10" timeoutForLargeTests="60" strict="false" verbose="false"> <testsuites> <testsuite name="My Test Suite"> <directory suffix="Test.php" phpVersion="5.3.0" phpVersionOperator=">=">/path/to/files</directory> <file phpVersion="5.3.0" phpVersionOperator=">=">/path/to/MyTest.php</file> </testsuite> </testsuites> <groups> <include> <group>name</group> </include> <exclude> <group>name</group> </exclude> </groups> <filter> <blacklist> <directory suffix=".php">/path/to/files</directory> <file>/path/to/file</file> <exclude> <directory suffix=".php">/path/to/files</directory> <file>/path/to/file</file> </exclude> </blacklist> <whitelist addUncoveredFilesFromWhitelist="true" processUncoveredFilesFromWhitelist="false"> <directory suffix=".php">/path/to/files</directory> <file>/path/to/file</file> <exclude> <directory suffix=".php">/path/to/files</directory> <file>/path/to/file</file> </exclude> </whitelist> </filter> <listeners> <listener class="MyListener" file="/optional/path/to/MyListener.php"> <arguments> <array> <element key="0"> <string>Sebastian</string> </element> </array> <integer>22</integer> <string>April</string> <double>19.78</double> <null/> <object class="stdClass"/> <file>MyTestFile.php</file> <directory>MyRelativePath</directory> </arguments> </listener> <listener class="IncludePathListener" file="ConfigurationTest.php" /> <listener class="CompactArgumentsListener" file="/CompactArgumentsListener.php"><arguments><integer>42</integer></arguments></listener> </listeners> <logging> <log type="coverage-html" target="/tmp/report" charset="UTF-8" highlight="false" lowUpperBound="35" highLowerBound="70"/> <log type="coverage-clover" target="/tmp/clover.xml"/> <log type="json" target="/tmp/logfile.json"/> <log type="plain" target="/tmp/logfile.txt"/> <log type="tap" target="/tmp/logfile.tap"/> <log type="junit" target="/tmp/logfile.xml" logIncompleteSkipped="false"/> <log type="testdox-html" target="/tmp/testdox.html"/> <log type="testdox-text" target="/tmp/testdox.txt"/> </logging> <php> <includePath>.</includePath> <includePath>/path/to/lib</includePath> <ini name="foo" value="bar"/> <const name="FOO" value="false"/> <const name="BAR" value="true"/> <var name="foo" value="false"/> <env name="foo" value="true"/> <post name="foo" value="bar"/> <get name="foo" value="bar"/> <cookie name="foo" value="bar"/> <server name="foo" value="bar"/> <files name="foo" value="bar"/> <request name="foo" value="bar"/> </php> <selenium> <browser name="Firefox on Linux" browser="*firefox /usr/lib/firefox/firefox-bin" host="my.linux.box" port="4444" timeout="30000"/> </selenium> </phpunit>
{ "pile_set_name": "Github" }
/***************************************************************************/ /* */ /* otvgpos.h */ /* */ /* OpenType GPOS table validator (specification). */ /* */ /* Copyright 2004-2016 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef OTVGPOS_H_ #define OTVGPOS_H_ FT_BEGIN_HEADER FT_LOCAL( void ) otv_GPOS_subtable_validate( FT_Bytes table, OTV_Validator valid ); FT_END_HEADER #endif /* OTVGPOS_H_ */ /* END */
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: af2eba76c6418bd46af05e234652275c timeCreated: 1522041409 licenseType: Pro NativeFormatImporter: externalObjects: {} mainObjectFileID: 11400000 userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
// // Navs // -------------------------------------------------- // Base class // -------------------------------------------------- .nav { margin-bottom: 0; padding-left: 0; // Override default ul/ol list-style: none; &:extend(.clearfix all); > li { position: relative; display: block; > a { position: relative; display: block; padding: @nav-link-padding; &:hover, &:focus { text-decoration: none; background-color: @nav-link-hover-bg; } } // Disabled state sets text to gray and nukes hover/tab effects &.disabled > a { color: @nav-disabled-link-color; &:hover, &:focus { color: @nav-disabled-link-hover-color; text-decoration: none; background-color: transparent; cursor: not-allowed; } } } // Open dropdowns .open > a { &, &:hover, &:focus { background-color: @nav-link-hover-bg; border-color: @link-color; } } // Nav dividers (deprecated with v3.0.1) // // This should have been removed in v3 with the dropping of `.nav-list`, but // we missed it. We don't currently support this anywhere, but in the interest // of maintaining backward compatibility in case you use it, it's deprecated. .nav-divider { .nav-divider(); } // Prevent IE8 from misplacing imgs // // See https://github.com/h5bp/html5-boilerplate/issues/984#issuecomment-3985989 > li > a > img { max-width: none; } } // Tabs // ------------------------- // Give the tabs something to sit on .nav-tabs { border-bottom: 1px solid @nav-tabs-border-color; > li { float: left; // Make the list-items overlay the bottom border margin-bottom: -1px; // Actual tabs (as links) > a { margin-right: 2px; line-height: @line-height-base; border: 1px solid transparent; border-radius: @border-radius-base @border-radius-base 0 0; &:hover { border-color: @nav-tabs-link-hover-border-color @nav-tabs-link-hover-border-color @nav-tabs-border-color; } } // Active state, and its :hover to override normal :hover &.active > a { &, &:hover, &:focus { color: @nav-tabs-active-link-hover-color; background-color: @nav-tabs-active-link-hover-bg; border: 1px solid @nav-tabs-active-link-hover-border-color; border-bottom-color: transparent; cursor: default; } } } // pulling this in mainly for less shorthand &.nav-justified { .nav-justified(); .nav-tabs-justified(); } } // Pills // ------------------------- .nav-pills { > li { float: left; // Links rendered as pills > a { border-radius: @nav-pills-border-radius; } + li { margin-left: 2px; } // Active state &.active > a { &, &:hover, &:focus { color: @nav-pills-active-link-hover-color; background-color: @nav-pills-active-link-hover-bg; } } } } // Stacked pills .nav-stacked { > li { float: none; + li { margin-top: 2px; margin-left: 0; // no need for this gap between nav items } } } // Nav variations // -------------------------------------------------- // Justified nav links // ------------------------- .nav-justified { width: 100%; > li { float: none; > a { text-align: center; margin-bottom: 5px; } } > .dropdown .dropdown-menu { top: auto; left: auto; } @media (min-width: @screen-sm-min) { > li { display: table-cell; width: 1%; > a { margin-bottom: 0; } } } } // Move borders to anchors instead of bottom of list // // Mixin for adding on top the shared `.nav-justified` styles for our tabs .nav-tabs-justified { border-bottom: 0; > li > a { // Override margin from .nav-tabs margin-right: 0; border-radius: @border-radius-base; } > .active > a, > .active > a:hover, > .active > a:focus { border: 1px solid @nav-tabs-justified-link-border-color; } @media (min-width: @screen-sm-min) { > li > a { border-bottom: 1px solid @nav-tabs-justified-link-border-color; border-radius: @border-radius-base @border-radius-base 0 0; } > .active > a, > .active > a:hover, > .active > a:focus { border-bottom-color: @nav-tabs-justified-active-link-border-color; } } } // Tabbable tabs // ------------------------- // Hide tabbable panes to start, show them when `.active` .tab-content { > .tab-pane { display: none; } > .active { display: block; } } // Dropdowns // ------------------------- // Specific dropdowns .nav-tabs .dropdown-menu { // make dropdown border overlap tab border margin-top: -1px; // Remove the top rounded corners here since there is a hard edge above the menu .border-top-radius(0); }
{ "pile_set_name": "Github" }
// +build !go1.5 // Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers. // package tlsconfig import ( "crypto/tls" ) // Client TLS cipher suites (dropping CBC ciphers for client preferred suite set) var clientCipherSuites = []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, }
{ "pile_set_name": "Github" }
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsCOMPtr.h" #include "nsTitleBarFrame.h" #include "nsIContent.h" #include "nsIDocument.h" #include "nsIDOMNodeList.h" #include "nsGkAtoms.h" #include "nsIWidget.h" #include "nsMenuPopupFrame.h" #include "nsPresContext.h" #include "nsIDocShell.h" #include "nsPIDOMWindow.h" #include "nsDisplayList.h" #include "nsContentUtils.h" #include "mozilla/MouseEvents.h" using namespace mozilla; // // NS_NewTitleBarFrame // // Creates a new TitleBar frame and returns it // nsIFrame* NS_NewTitleBarFrame(nsIPresShell* aPresShell, nsStyleContext* aContext) { return new (aPresShell) nsTitleBarFrame(aContext); } NS_IMPL_FRAMEARENA_HELPERS(nsTitleBarFrame) nsTitleBarFrame::nsTitleBarFrame(nsStyleContext* aContext) :nsBoxFrame(aContext, false) { mTrackingMouseMove = false; UpdateMouseThrough(); } void nsTitleBarFrame::BuildDisplayListForChildren(nsDisplayListBuilder* aBuilder, const nsRect& aDirtyRect, const nsDisplayListSet& aLists) { // override, since we don't want children to get events if (aBuilder->IsForEventDelivery()) { if (!mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::allowevents, nsGkAtoms::_true, eCaseMatters)) return; } nsBoxFrame::BuildDisplayListForChildren(aBuilder, aDirtyRect, aLists); } nsresult nsTitleBarFrame::HandleEvent(nsPresContext* aPresContext, WidgetGUIEvent* aEvent, nsEventStatus* aEventStatus) { NS_ENSURE_ARG_POINTER(aEventStatus); if (nsEventStatus_eConsumeNoDefault == *aEventStatus) { return NS_OK; } bool doDefault = true; switch (aEvent->mMessage) { case eMouseDown: { if (aEvent->AsMouseEvent()->button == WidgetMouseEvent::eLeftButton) { // titlebar has no effect in non-chrome shells nsCOMPtr<nsIDocShellTreeItem> dsti = aPresContext->GetDocShell(); if (dsti) { if (dsti->ItemType() == nsIDocShellTreeItem::typeChrome) { // we're tracking. mTrackingMouseMove = true; // start capture. nsIPresShell::SetCapturingContent(GetContent(), CAPTURE_IGNOREALLOWED); // remember current mouse coordinates. mLastPoint = aEvent->mRefPoint; } } *aEventStatus = nsEventStatus_eConsumeNoDefault; doDefault = false; } } break; case eMouseUp: { if (mTrackingMouseMove && aEvent->AsMouseEvent()->button == WidgetMouseEvent::eLeftButton) { // we're done tracking. mTrackingMouseMove = false; // end capture nsIPresShell::SetCapturingContent(nullptr, 0); *aEventStatus = nsEventStatus_eConsumeNoDefault; doDefault = false; } } break; case eMouseMove: { if(mTrackingMouseMove) { LayoutDeviceIntPoint nsMoveBy = aEvent->mRefPoint - mLastPoint; nsIFrame* parent = GetParent(); while (parent) { nsMenuPopupFrame* popupFrame = do_QueryFrame(parent); if (popupFrame) break; parent = parent->GetParent(); } // if the titlebar is in a popup, move the popup frame, otherwise // move the widget associated with the window if (parent) { nsMenuPopupFrame* menuPopupFrame = static_cast<nsMenuPopupFrame*>(parent); nsCOMPtr<nsIWidget> widget = menuPopupFrame->GetWidget(); LayoutDeviceIntRect bounds = widget->GetScreenBounds(); CSSPoint cssPos = (bounds.TopLeft() + nsMoveBy) / aPresContext->CSSToDevPixelScale(); menuPopupFrame->MoveTo(RoundedToInt(cssPos), false); } else { nsIPresShell* presShell = aPresContext->PresShell(); nsPIDOMWindowOuter *window = presShell->GetDocument()->GetWindow(); if (window) { window->MoveBy(nsMoveBy.x, nsMoveBy.y); } } *aEventStatus = nsEventStatus_eConsumeNoDefault; doDefault = false; } } break; case eMouseClick: { WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent(); if (mouseEvent->IsLeftClickEvent()) { MouseClicked(mouseEvent); } break; } default: break; } if ( doDefault ) return nsBoxFrame::HandleEvent(aPresContext, aEvent, aEventStatus); else return NS_OK; } void nsTitleBarFrame::MouseClicked(WidgetMouseEvent* aEvent) { // Execute the oncommand event handler. nsContentUtils::DispatchXULCommand(mContent, aEvent && aEvent->IsTrusted()); }
{ "pile_set_name": "Github" }
context("Checking polarity") test_that("polarity gives the desired output for default polarity frame",{ poldat <- structure(list(person = structure(c(4L, 4L, 1L, 5L, 4L, 1L), .Label = c("greg", "researcher", "sally", "sam", "teacher"), class = "factor"), wc = c(3L, 3L, 5L, 4L, 4L, 5L), polarity = c(0.577350269189626, -0.577350269189626, -0.447213595499958, 0, -1, 0), pos.words = list( "fun", "fun", "-", "-", "-", "-"), neg.words = list("-", "-", "dumb", "-", c("liar", "stinks"), "-"), text.var = c("Computer is fun.", "Not too fun.", "No it's not, it's dumb.", "What should we do?", "You liar, it stinks!", "I am telling the truth!")), class = c("polarity_count", "data.frame"), type = "polarity_count", .Names = c("person", "wc", "polarity", "pos.words", "neg.words", "text.var"), row.names = c("1", "2", "3", "4", "5", "6"), digits = 3) expect_equivalent( poldat, counts(with(sentSplit(DATA[1:5, ], 4), polarity(state, person))) ) }) test_that("polarity gives the desired output for phrases used in polarity.frame",{ poldat2 <- structure(list(all = "all", wc = 5L, polarity = 0.357770876399966, pos.words = list("simply the best"), neg.words = list("-"), text.var = "This is simply the best"), class = c("polarity_count", "data.frame"), type = "polarity_count", .Names = c("all", "wc", "polarity", "pos.words", "neg.words", "text.var"), row.names = "1", digits = 3) phrase <- "This is simply the best" key <- sentiment_frame(c("simply", "best", "simply the best"), "", c(0.1,0.3,0.8)) expect_equivalent( poldat2, counts(polarity(phrase, polarity.frame=key)) ) })
{ "pile_set_name": "Github" }
type: integer format: int64
{ "pile_set_name": "Github" }
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let v{{a{}{func g{func b{class g{func g{for b=c
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>ACPI</key> <dict> <key>DSDT</key> <dict> <key>Debug</key> <false/> <key>DropOEM_DSM</key> <false/> <key>Fixes</key> <dict> <key>AddDTGP</key> <true/> <key>FixHDA</key> <true/> <key>FixHPET</key> <true/> <key>FixRTC</key> <true/> <key>FixShutdown</key> <true/> </dict> <key>Patches</key> <array> <dict> <key>Comment</key> <string>change SAT0 to SATA</string> <key>Disabled</key> <false/> <key>Find</key> <data> U0FUMA== </data> <key>Replace</key> <data> U0FUQQ== </data> </dict> <dict> <key>Comment</key> <string>change CAVS to HDEF</string> <key>Disabled</key> <false/> <key>Find</key> <data> Q0FWUw== </data> <key>Replace</key> <data> SERFRg== </data> </dict> <dict> <key>Comment</key> <string>Change PC00 to PCI0</string> <key>Disabled</key> <false/> <key>Find</key> <data> UEMwMA== </data> <key>Replace</key> <data> UENJMA== </data> </dict> <dict> <key>Comment</key> <string>change PEGP to GFX0</string> <key>Disabled</key> <false/> <key>Find</key> <data> UEVHUA== </data> <key>Replace</key> <data> R0ZYMA== </data> </dict> <dict> <key>Comment</key> <string>change HDAS to HDEF</string> <key>Disabled</key> <false/> <key>Find</key> <data> SERBUw== </data> <key>Replace</key> <data> SERFRg== </data> </dict> </array> <key>ReuseFFFF</key> <false/> </dict> <key>FixHeaders</key> <true/> <key>SSDT</key> <dict> <key>DropOem</key> <false/> <key>EnableC2</key> <false/> <key>EnableC4</key> <false/> <key>EnableC6</key> <false/> <key>EnableC7</key> <true/> <key>Generate</key> <dict> <key>APLF</key> <false/> <key>APSN</key> <false/> <key>CStates</key> <true/> <key>PStates</key> <true/> <key>PluginType</key> <true/> </dict> <key>PluginType</key> <string>1</string> <key>UseSystemIO</key> <true/> </dict> </dict> <key>Boot</key> <dict> <key>Arguments</key> <string>-alcbeta dart=0 nvda_drv=1 -disablegfxfirmware shikigva=12 -lilubeta</string> <key>Debug</key> <false/> <key>DefaultVolume</key> <string>macOS</string> <key>Legacy</key> <string>PBR</string> <key>Secure</key> <false/> <key>Timeout</key> <integer>5</integer> <key>XMPDetection</key> <false/> </dict> <key>CPU</key> <dict> <key>C2</key> <true/> <key>C4</key> <true/> <key>C6</key> <true/> <key>HWPEnable</key> <true/> <key>UseARTFrequency</key> <false/> </dict> <key>Devices</key> <dict> <key>Audio</key> <dict> <key>Inject</key> <integer>7</integer> <key>ResetHDA</key> <true/> </dict> <key>FakeID</key> <dict> <key>IntelGFX</key> <string>0x59128086</string> </dict> <key>ForceHPET</key> <true/> <key>Inject</key> <false/> <key>USB</key> <dict> <key>AddClockID</key> <true/> <key>FixOwnership</key> <true/> <key>HighCurrent</key> <false/> <key>Inject</key> <true/> </dict> <key>UseIntelHDMI</key> <false/> </dict> <key>GUI</key> <dict> <key>Hide</key> <array> <string>BOOTX64.EFI</string> <string>Windows</string> </array> <key>Language</key> <string>zh_CN:0</string> <key>Mouse</key> <dict> <key>DoubleClick</key> <integer>500</integer> <key>Enabled</key> <true/> <key>Mirror</key> <false/> <key>Speed</key> <integer>8</integer> </dict> <key>Scan</key> <dict> <key>Entries</key> <true/> <key>Legacy</key> <false/> <key>Linux</key> <false/> <key>Tool</key> <false/> </dict> <key>Theme</key> <string>black_green</string> </dict> <key>Graphics</key> <dict> <key>Inject</key> <dict> <key>ATI</key> <false/> <key>Intel</key> <true/> <key>NVidia</key> <false/> </dict> <key>ig-platform-id</key> <string>0x59120003</string> </dict> <key>KernelAndKextPatches</key> <dict> <key>AppleIntelCPUPM</key> <true/> <key>AppleRTC</key> <true/> <key>KernelPm</key> <true/> <key>KextsToPatch</key> <array> <dict> <key>Comment</key> <string>External icons patch</string> <key>Disabled</key> <false/> <key>Find</key> <data> RXh0ZXJuYWw= </data> <key>InfoPlistPatch</key> <false/> <key>Name</key> <string>AppleAHCIPort</string> <key>Replace</key> <data> SW50ZXJuYWw= </data> </dict> <dict> <key>Comment</key> <string>Change 15 port limit to 24 in XHCI kext 10.13</string> <key>Disabled</key> <false/> <key>Find</key> <data> g32MEA== </data> <key>InfoPlistPatch</key> <false/> <key>Name</key> <string>AppleUSBXHCIPCI</string> <key>Replace</key> <data> g32MGw== </data> </dict> <dict> <key>Comment</key> <string>Change 15 port limit to 24 in XHCI kext 10.13.4</string> <key>Disabled</key> <false/> <key>Find</key> <data> g32UDw+DlwQ= </data> <key>InfoPlistPatch</key> <false/> <key>Name</key> <string>AppleUSBXHCIPCI</string> <key>Replace</key> <data> g32UFA+DlwQ= </data> </dict> <dict> <key>Disabled</key> <false/> <key>Find</key> <data> g32UDw+DlwQAAA== </data> <key>InfoPlistPatch</key> <false/> <key>MatchOS</key> <string>10.13.x</string> <key>Name</key> <string>com.apple.driver.usb.AppleUSBXHCI</string> <key>Replace</key> <data> g32UD5CQkJCQkA== </data> </dict> </array> </dict> <key>RtVariables</key> <dict> <key>BooterConfig</key> <string>0x28</string> <key>CsrActiveConfig</key> <string>0x67</string> </dict> <key>SMBIOS</key> <dict> <key>BiosReleaseDate</key> <string>02/08/2018</string> <key>BiosVendor</key> <string>Apple Inc.</string> <key>BiosVersion</key> <string>IM183.88Z.0157.B00.1802080917</string> <key>Board-ID</key> <string>Mac-BE088AF8C5EB4FA2</string> <key>BoardManufacturer</key> <string>Apple Inc.</string> <key>BoardSerialNumber</key> <string>C027292704NF502CB</string> <key>BoardType</key> <integer>10</integer> <key>BoardVersion</key> <string>1.0</string> <key>ChassisAssetTag</key> <string>iMac-Aluminum</string> <key>ChassisManufacturer</key> <string>Apple Inc.</string> <key>ChassisType</key> <string>0x09</string> <key>Family</key> <string>iMac</string> <key>FirmwareFeatures</key> <string>0xFC0FE137</string> <key>FirmwareFeaturesMask</key> <string>0xFF1FFF3F</string> <key>LocationInChassis</key> <string>Part Component</string> <key>Manufacturer</key> <string>Apple Inc.</string> <key>Mobile</key> <false/> <key>PlatformFeature</key> <string>0x00</string> <key>ProductName</key> <string>iMac18,3</string> <key>SerialNumber</key> <string>C02V31SSJ1GJ</string> <key>Version</key> <string>1.0</string> </dict> <key>SystemParameters</key> <dict> <key>InjectKexts</key> <string>Yes</string> <key>InjectSystemID</key> <true/> <key>NvidiaWeb</key> <true/> </dict> </dict> </plist>
{ "pile_set_name": "Github" }
StartChar: uniFE79 Encoding: 65145 65145 5434 Width: 185 Flags: HW LayerCount: 3 Fore Refer: 4633 -1 N 1 0 0 1 0 0 2 Refer: 236 1615 N 1 0 0 1 -185 0 2 Colour: ff0000 EndChar
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:c="http://java.sun.com/jstl/core" xmlns:fn="http://java.sun.com/jsp/jstl/functions" xmlns:ccInJar="http://mojarra.java.net/ccInJar"> <!-- DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. Copyright (c) 2017 Oracle and/or its affiliates. All rights reserved. The contents of this file are subject to the terms of either the GNU General Public License Version 2 only ("GPL") or the Common Development and Distribution License("CDDL") (collectively, the "License"). You may not use this file except in compliance with the License. You can obtain a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html or packager/legal/LICENSE.txt. See the License for the specific language governing permissions and limitations under the License. When distributing the software, include this License Header Notice in each file and include the License file at packager/legal/LICENSE.txt. GPL Classpath Exception: Oracle designates this particular file as subject to the "Classpath" exception as provided by Oracle in the GPL Version 2 section of the License file that accompanied this code. Modifications: If applicable, add the following below the License Header, with the fields enclosed by brackets [] replaced by your own identifying information: "Portions Copyright [year] [name of copyright owner]" Contributor(s): If you wish your version of this file to be governed by only the CDDL or only the GPL Version 2, indicate your decision by adding "[Contributor] elects to include this software in this distribution under the [CDDL or GPL Version 2] license." If you don't indicate a single choice of license, a recipient has the option to distribute your version of this file under either the CDDL, the GPL Version 2 or to extend the choice of license to its licensees as provided above. However, if you add GPL Version 2 code and therefore, elected the GPL Version 2 license, then the option applies only if the new code is made subject to such option by the copyright holder. --> <ui:include src="layoutHead.xhtml" /> <h:body> <div>[webappAll.xhtml]</div> <ui:include src="layoutAll.xhtml"/> <ui:remove>Add some request context to the response</ui:remove> <h:outputText value="[request-information]" escape="false"/> </h:body> </html>
{ "pile_set_name": "Github" }
/* * Copyright 2011 The Error Prone 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.errorprone.apply; import java.io.IOException; /** @author sjnickerson@google.com (Simon Nickerson) */ public interface FileDestination { void writeFile(SourceFile file) throws IOException; void flush() throws IOException; }
{ "pile_set_name": "Github" }
h2 { font-size: 20px; } body, html { margin: 0 0; padding: 0 0; } body > * { padding-left: 20px; padding-right: 20px; box-sizing: border-box; } .user-split { display: flex; } #profile { margin-top: 30px; width: 400px; order: 2; margin-left: auto; } #profile img { width: 100%; } .versions { list-style: none; padding-left: 0; } header a { text-decoration: none; } header a:hover { text-decoration: underline; } header #search { min-width: 80%; width: initial !important; flex-grow: 1; } header .account, header .logout { text-align: right; display: block; } header #user { margin: 0 0; margin-left: 14px; margin-right: 8px; } header .avatar img { height: 40px; } header .logout { font-size: 14px; color: #8c8c8c; } header .login { margin-left: 14px; } header .login span { display: block; font-size: 14px; } body > nav { background-color: #999; width: 100%; height: 25px; display: flex; align-items: center; border-bottom: 1px solid #666666; } body > nav > *:nth-of-type(2) { margin-left: auto; } body > nav > * { padding: 0 8px; } body > nav a { color: #e6e6e6; font-size: 14px; text-decoration: none; } body > nav a:hover { color: white; } body header { width: 100%; height: 68px; background-color: #eee; display: flex; align-items: center; border-bottom: 1px solid #bbbbbb; } .hero { min-height: 40vh; display: flex; overflow: hidden; background-image: -webkit-gradient( linear, left top, left bottom, color-stop(0, #3C7780), color-stop(1, #233C57) ); background-image: -o-linear-gradient(bottom, #3C7780 0%, #080E15 100%); background-image: -moz-linear-gradient(bottom, #3C7780 0%, #080E15 100%); background-image: -webkit-linear-gradient(bottom, #3C7780 0%, #080E15 100%); background-image: -ms-linear-gradient(bottom, #3C7780 0%, #080E15 100%); background-image: linear-gradient(to bottom, #3C7780 0%, #080E15 100%); flex-direction: column; align-items: center; } .hero { position: relative; padding-top: 100px; padding-bottom: 20px; background-color: #1b1c1d; color: white; } .hero .header .sub.header { color: orange !important; font-size: 1.4rem !important; } .hero .background { background-image: url('hero-bg-small-2.jpg'); background-repeat: no-repeat; background-size: cover; background-position : top left; transform: translateZ(0); -webkit-transform: translateZ(0); background-repeat: no-repeat; background-size: cover; position: fixed; top: 40px; bottom: 0px; left: 0px; right: 0px; pointer-events: none; } .hero .ui.list, .hero p { color: #e0e0e0; } .hero p { font-size: 1.10em; } .hero .header { color: white !important; } #get-started { margin: 0 auto; margin-bottom: 40px; width: 180px; } #get-started span { display: block; font-weight: 100; font-size: 14px; } #get-started { display: flex; } #get-started .icon { line-height: 41px; font-size: 43px; margin-right: 0; } #highlights ul { color: black; margin-top: -100px; margin-bottom: 100px; padding: 0; list-style: none; display: flex; flex-wrap: wrap; align-items: flex-start; } #highlights ul > * { width: 33.333%; flex-grow: 1; min-width: 300px; padding-right: 30px; box-sizing: border-box; } #search { margin: 0; padding: 0; width: 100%; height: 50px; display: flex; align-items: center; } #search #site-search-container { position: relative; height: 40px; border: 1px solid lightgray; overflow: hidden; background-color: white; flex-grow: 1; } #search #site-search-container:hover { border-color: #a0a0a0; } #search #site-search-container #site-search { color: #333; height: 30px; width: 100%; outline: 0; border: none; padding: 5px 10px; } #search #site-search-submit { min-width: 50px; max-width: 100px; position: absolute; right: 0; top: 0; bottom: 0; } #recents > h2 { text-align: center; color: #999; border-bottom: 1px solid #999; padding-bottom: 20px; } #recents ul { padding: 0; list-style: none; display: flex; flex-wrap: wrap; align-items: flex-start; } #recents ul > * { width: 33.333%; flex-grow: 1; min-width: 300px; padding-right: 30px; box-sizing: border-box; } #recents li:hover a { color: black; } #recents a:hover { text-decoration: underline; } #recents p { color: gray; } #recents .description { margin-top: -5px; } #recents .version { font-size: 14px; margin-top: -8px; } #recents li a { color: green; text-decoration: none; } footer { min-height: 50px; } /*# sourceMappingURL=index-style.css.map */
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="" > <head> <meta charset="utf-8"/> <title>lang="" vs HTTP</title> <link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'> <link rel='help' href='https://html.spec.whatwg.org/multipage/#the-lang-and-xml:lang-attributes'> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <meta name='flags' content='http dom'> <style type='text/css'> #colonlangcontroltest { color: red; font-weight: bold; width: 400px; } #colonlangcontroltest:lang(xx) { display:none; } .test div { width: 50px; } #box:lang(ko) { width: 100px; } </style> </head> <body> <div class="test"><div id="box">&#xA0;</div></div> <p lang='xx' id='colonlangcontroltest'>This test failed because it relies on :lang for results, but :lang is not supported by this browser.</p> <!--Notes: This test uses :lang to detect whether the language has been set. If :lang is not supported, a message will appear and the test will fail. --> <script> test(function() { assert_equals(document.getElementById('colonlangcontroltest').offsetWidth, 0) assert_equals(document.getElementById('box').offsetWidth, 50); }, "If the HTTP header contains a language declaration but the html element uses an empty lang value, the UA will not recognize the language declared in the HTTP header."); </script> <div id='log'></div> </body> </html>
{ "pile_set_name": "Github" }
""" This code is automatically generated. Never edit it manually. For details of generating the code see `rubi_parsing_guide.md` in `parsetools`. """ from sympy.external import import_module matchpy = import_module("matchpy") if matchpy: from matchpy import Pattern, ReplacementRule, CustomConstraint, is_match from sympy.integrals.rubi.utility_function import ( Int, Sum, Set, With, Module, Scan, MapAnd, FalseQ, ZeroQ, NegativeQ, NonzeroQ, FreeQ, NFreeQ, List, Log, PositiveQ, PositiveIntegerQ, NegativeIntegerQ, IntegerQ, IntegersQ, ComplexNumberQ, PureComplexNumberQ, RealNumericQ, PositiveOrZeroQ, NegativeOrZeroQ, FractionOrNegativeQ, NegQ, Equal, Unequal, IntPart, FracPart, RationalQ, ProductQ, SumQ, NonsumQ, Subst, First, Rest, SqrtNumberQ, SqrtNumberSumQ, LinearQ, Sqrt, ArcCosh, Coefficient, Denominator, Hypergeometric2F1, Not, Simplify, FractionalPart, IntegerPart, AppellF1, EllipticPi, EllipticE, EllipticF, ArcTan, ArcCot, ArcCoth, ArcTanh, ArcSin, ArcSinh, ArcCos, ArcCsc, ArcSec, ArcCsch, ArcSech, Sinh, Tanh, Cosh, Sech, Csch, Coth, LessEqual, Less, Greater, GreaterEqual, FractionQ, IntLinearcQ, Expand, IndependentQ, PowerQ, IntegerPowerQ, PositiveIntegerPowerQ, FractionalPowerQ, AtomQ, ExpQ, LogQ, Head, MemberQ, TrigQ, SinQ, CosQ, TanQ, CotQ, SecQ, CscQ, Sin, Cos, Tan, Cot, Sec, Csc, HyperbolicQ, SinhQ, CoshQ, TanhQ, CothQ, SechQ, CschQ, InverseTrigQ, SinCosQ, SinhCoshQ, LeafCount, Numerator, NumberQ, NumericQ, Length, ListQ, Im, Re, InverseHyperbolicQ, InverseFunctionQ, TrigHyperbolicFreeQ, InverseFunctionFreeQ, RealQ, EqQ, FractionalPowerFreeQ, ComplexFreeQ, PolynomialQ, FactorSquareFree, PowerOfLinearQ, Exponent, QuadraticQ, LinearPairQ, BinomialParts, TrinomialParts, PolyQ, EvenQ, OddQ, PerfectSquareQ, NiceSqrtAuxQ, NiceSqrtQ, Together, PosAux, PosQ, CoefficientList, ReplaceAll, ExpandLinearProduct, GCD, ContentFactor, NumericFactor, NonnumericFactors, MakeAssocList, GensymSubst, KernelSubst, ExpandExpression, Apart, SmartApart, MatchQ, PolynomialQuotientRemainder, FreeFactors, NonfreeFactors, RemoveContentAux, RemoveContent, FreeTerms, NonfreeTerms, ExpandAlgebraicFunction, CollectReciprocals, ExpandCleanup, AlgebraicFunctionQ, Coeff, LeadTerm, RemainingTerms, LeadFactor, RemainingFactors, LeadBase, LeadDegree, Numer, Denom, hypergeom, Expon, MergeMonomials, PolynomialDivide, BinomialQ, TrinomialQ, GeneralizedBinomialQ, GeneralizedTrinomialQ, FactorSquareFreeList, PerfectPowerTest, SquareFreeFactorTest, RationalFunctionQ, RationalFunctionFactors, NonrationalFunctionFactors, Reverse, RationalFunctionExponents, RationalFunctionExpand, ExpandIntegrand, SimplerQ, SimplerSqrtQ, SumSimplerQ, BinomialDegree, TrinomialDegree, CancelCommonFactors, SimplerIntegrandQ, GeneralizedBinomialDegree, GeneralizedBinomialParts, GeneralizedTrinomialDegree, GeneralizedTrinomialParts, MonomialQ, MonomialSumQ, MinimumMonomialExponent, MonomialExponent, LinearMatchQ, PowerOfLinearMatchQ, QuadraticMatchQ, CubicMatchQ, BinomialMatchQ, TrinomialMatchQ, GeneralizedBinomialMatchQ, GeneralizedTrinomialMatchQ, QuotientOfLinearsMatchQ, PolynomialTermQ, PolynomialTerms, NonpolynomialTerms, PseudoBinomialParts, NormalizePseudoBinomial, PseudoBinomialPairQ, PseudoBinomialQ, PolynomialGCD, PolyGCD, AlgebraicFunctionFactors, NonalgebraicFunctionFactors, QuotientOfLinearsP, QuotientOfLinearsParts, QuotientOfLinearsQ, Flatten, Sort, AbsurdNumberQ, AbsurdNumberFactors, NonabsurdNumberFactors, SumSimplerAuxQ, Prepend, Drop, CombineExponents, FactorInteger, FactorAbsurdNumber, SubstForInverseFunction, SubstForFractionalPower, SubstForFractionalPowerOfQuotientOfLinears, FractionalPowerOfQuotientOfLinears, SubstForFractionalPowerQ, SubstForFractionalPowerAuxQ, FractionalPowerOfSquareQ, FractionalPowerSubexpressionQ, Apply, FactorNumericGcd, MergeableFactorQ, MergeFactor, MergeFactors, TrigSimplifyQ, TrigSimplify, TrigSimplifyRecur, Order, FactorOrder, Smallest, OrderedQ, MinimumDegree, PositiveFactors, Sign, NonpositiveFactors, PolynomialInAuxQ, PolynomialInQ, ExponentInAux, ExponentIn, PolynomialInSubstAux, PolynomialInSubst, Distrib, DistributeDegree, FunctionOfPower, DivideDegreesOfFactors, MonomialFactor, FullSimplify, FunctionOfLinearSubst, FunctionOfLinear, NormalizeIntegrand, NormalizeIntegrandAux, NormalizeIntegrandFactor, NormalizeIntegrandFactorBase, NormalizeTogether, NormalizeLeadTermSigns, AbsorbMinusSign, NormalizeSumFactors, SignOfFactor, NormalizePowerOfLinear, SimplifyIntegrand, SimplifyTerm, TogetherSimplify, SmartSimplify, SubstForExpn, ExpandToSum, UnifySum, UnifyTerms, UnifyTerm, CalculusQ, FunctionOfInverseLinear, PureFunctionOfSinhQ, PureFunctionOfTanhQ, PureFunctionOfCoshQ, IntegerQuotientQ, OddQuotientQ, EvenQuotientQ, FindTrigFactor, FunctionOfSinhQ, FunctionOfCoshQ, OddHyperbolicPowerQ, FunctionOfTanhQ, FunctionOfTanhWeight, FunctionOfHyperbolicQ, SmartNumerator, SmartDenominator, SubstForAux, ActivateTrig, ExpandTrig, TrigExpand, SubstForTrig, SubstForHyperbolic, InertTrigFreeQ, LCM, SubstForFractionalPowerOfLinear, FractionalPowerOfLinear, InverseFunctionOfLinear, InertTrigQ, InertReciprocalQ, DeactivateTrig, FixInertTrigFunction, DeactivateTrigAux, PowerOfInertTrigSumQ, PiecewiseLinearQ, KnownTrigIntegrandQ, KnownSineIntegrandQ, KnownTangentIntegrandQ, KnownCotangentIntegrandQ, KnownSecantIntegrandQ, TryPureTanSubst, TryTanhSubst, TryPureTanhSubst, AbsurdNumberGCD, AbsurdNumberGCDList, ExpandTrigExpand, ExpandTrigReduce, ExpandTrigReduceAux, NormalizeTrig, TrigToExp, ExpandTrigToExp, TrigReduce, FunctionOfTrig, AlgebraicTrigFunctionQ, FunctionOfHyperbolic, FunctionOfQ, FunctionOfExpnQ, PureFunctionOfSinQ, PureFunctionOfCosQ, PureFunctionOfTanQ, PureFunctionOfCotQ, FunctionOfCosQ, FunctionOfSinQ, OddTrigPowerQ, FunctionOfTanQ, FunctionOfTanWeight, FunctionOfTrigQ, FunctionOfDensePolynomialsQ, FunctionOfLog, PowerVariableExpn, PowerVariableDegree, PowerVariableSubst, EulerIntegrandQ, FunctionOfSquareRootOfQuadratic, SquareRootOfQuadraticSubst, Divides, EasyDQ, ProductOfLinearPowersQ, Rt, NthRoot, AtomBaseQ, SumBaseQ, NegSumBaseQ, AllNegTermQ, SomeNegTermQ, TrigSquareQ, RtAux, TrigSquare, IntSum, IntTerm, Map2, ConstantFactor, SameQ, ReplacePart, CommonFactors, MostMainFactorPosition, FunctionOfExponentialQ, FunctionOfExponential, FunctionOfExponentialFunction, FunctionOfExponentialFunctionAux, FunctionOfExponentialTest, FunctionOfExponentialTestAux, stdev, rubi_test, If, IntQuadraticQ, IntBinomialQ, RectifyTangent, RectifyCotangent, Inequality, Condition, Simp, SimpHelp, SplitProduct, SplitSum, SubstFor, SubstForAux, FresnelS, FresnelC, Erfc, Erfi, Gamma, FunctionOfTrigOfLinearQ, ElementaryFunctionQ, Complex, UnsameQ, _SimpFixFactor, SimpFixFactor, _FixSimplify, FixSimplify, _SimplifyAntiderivativeSum, SimplifyAntiderivativeSum, _SimplifyAntiderivative, SimplifyAntiderivative, _TrigSimplifyAux, TrigSimplifyAux, Cancel, Part, PolyLog, D, Dist, Sum_doit, PolynomialQuotient, Floor, PolynomialRemainder, Factor, PolyLog, CosIntegral, SinIntegral, LogIntegral, SinhIntegral, CoshIntegral, Rule, Erf, PolyGamma, ExpIntegralEi, ExpIntegralE, LogGamma , UtilityOperator, Factorial, Zeta, ProductLog, DerivativeDivides, HypergeometricPFQ, IntHide, OneQ, Null, rubi_exp as exp, rubi_log as log, Discriminant, Negative, Quotient ) from sympy import (Integral, S, sqrt, And, Or, Integer, Float, Mod, I, Abs, simplify, Mul, Add, Pow, sign, EulerGamma) from sympy.integrals.rubi.symbol import WC from sympy.core.symbol import symbols, Symbol from sympy.functions import (sin, cos, tan, cot, csc, sec, sqrt, erf) from sympy.functions.elementary.hyperbolic import (acosh, asinh, atanh, acoth, acsch, asech, cosh, sinh, tanh, coth, sech, csch) from sympy.functions.elementary.trigonometric import (atan, acsc, asin, acot, acos, asec, atan2) from sympy import pi as Pi A_, B_, C_, F_, G_, H_, a_, b_, c_, d_, e_, f_, g_, h_, i_, j_, k_, l_, m_, n_, p_, q_, r_, t_, u_, v_, s_, w_, x_, y_, z_ = [WC(i) for i in 'ABCFGHabcdefghijklmnpqrtuvswxyz'] a1_, a2_, b1_, b2_, c1_, c2_, d1_, d2_, n1_, n2_, e1_, e2_, f1_, f2_, g1_, g2_, n1_, n2_, n3_, Pq_, Pm_, Px_, Qm_, Qr_, Qx_, jn_, mn_, non2_, RFx_, RGx_ = [WC(i) for i in ['a1', 'a2', 'b1', 'b2', 'c1', 'c2', 'd1', 'd2', 'n1', 'n2', 'e1', 'e2', 'f1', 'f2', 'g1', 'g2', 'n1', 'n2', 'n3', 'Pq', 'Pm', 'Px', 'Qm', 'Qr', 'Qx', 'jn', 'mn', 'non2', 'RFx', 'RGx']] i, ii, Pqq, Q, R, r, C, k, u = symbols('i ii Pqq Q R r C k u') _UseGamma = False ShowSteps = False StepCounter = None def miscellaneous_integration(): from sympy.integrals.rubi.constraints import cons149, cons2004, cons2, cons3, cons8, cons4, cons5, cons388, cons29, cons52, cons2005, cons2006, cons2007, cons2008, cons50, cons127, cons210, cons36, cons37, cons38, cons1101, cons2009, cons68, cons19, cons86, cons1039, cons1038, cons40, cons2010, cons10, cons2011, cons2012, cons2013, cons211, cons1833, cons1246, cons2014, cons48, cons2015, cons2016, cons2017, cons2018, cons54, cons2019, cons802, cons2020, cons20, cons2021, cons588, cons2022, cons2023, cons2024, cons2025, cons2026, cons2027, cons2028, cons2029, cons2030, cons669, cons198, cons2031, cons842, cons2032, cons21, cons2033, cons150, cons47, cons2034, cons1856, cons1249, cons263, cons2035, cons369, cons2036, cons69, cons1481, cons746, cons1484, cons167, cons2037, cons2038, cons1678, cons1257, cons2039, cons349 pattern6934 = Pattern(Integral(u_*((x_*WC('b', S(1)) + WC('a', S(0)))**n_*WC('c', S(1)))**p_, x_), cons2, cons3, cons8, cons4, cons5, cons149, cons2004) rule6934 = ReplacementRule(pattern6934, replacement6934) pattern6935 = Pattern(Integral(((d_*(x_*WC('b', S(1)) + WC('a', S(0))))**p_*WC('c', S(1)))**q_*WC('u', S(1)), x_), cons2, cons3, cons8, cons29, cons5, cons52, cons149, cons388) rule6935 = ReplacementRule(pattern6935, replacement6935) pattern6936 = Pattern(Integral((((x_*WC('b', S(1)) + WC('a', S(0)))**n_*WC('d', S(1)))**p_*WC('c', S(1)))**q_*WC('u', S(1)), x_), cons2, cons3, cons8, cons29, cons4, cons5, cons52, cons149, cons388) rule6936 = ReplacementRule(pattern6936, replacement6936) pattern6937 = Pattern(Integral((F_*sqrt(x_*WC('e', S(1)) + WC('d', S(0)))*WC('b', S(1))*WC('c', S(1))/sqrt(x_*WC('g', S(1)) + WC('f', S(0))) + WC('a', S(0)))**WC('n', S(1))/(x_**S(2)*WC('C', S(1)) + x_*WC('B', S(1)) + WC('A', S(0))), x_), cons2, cons3, cons8, cons29, cons50, cons127, cons210, cons36, cons37, cons38, cons1101, cons2005, cons2006, cons2007, cons2008) rule6937 = ReplacementRule(pattern6937, replacement6937) pattern6938 = Pattern(Integral((F_*sqrt(x_*WC('e', S(1)) + S(1))*WC('b', S(1))*WC('c', S(1))/sqrt(x_*WC('g', S(1)) + S(1)) + WC('a', S(0)))**WC('n', S(1))/(x_**S(2)*WC('C', S(1)) + WC('A', S(0))), x_), cons2, cons3, cons8, cons50, cons210, cons36, cons38, cons1101, cons2005, cons2009) rule6938 = ReplacementRule(pattern6938, replacement6938) pattern6939 = Pattern(Integral((F_**(sqrt(x_*WC('e', S(1)) + WC('d', S(0)))*WC('c', S(1))/sqrt(x_*WC('g', S(1)) + WC('f', S(0))))*WC('b', S(1)) + WC('a', S(0)))**WC('n', S(1))/(x_**S(2)*WC('C', S(1)) + x_*WC('B', S(1)) + WC('A', S(0))), x_), cons2, cons3, cons8, cons29, cons50, cons127, cons210, cons36, cons37, cons38, cons1101, cons2005, cons2006, cons2007, cons2008) rule6939 = ReplacementRule(pattern6939, replacement6939) pattern6940 = Pattern(Integral((F_**(sqrt(x_*WC('e', S(1)) + S(1))*WC('c', S(1))/sqrt(x_*WC('g', S(1)) + S(1)))*WC('b', S(1)) + WC('a', S(0)))**WC('n', S(1))/(x_**S(2)*WC('C', S(1)) + WC('A', S(0))), x_), cons2, cons3, cons8, cons50, cons210, cons36, cons38, cons1101, cons2005, cons2009) rule6940 = ReplacementRule(pattern6940, replacement6940) pattern6941 = Pattern(Integral(u_/y_, x_), CustomConstraint(With6941)) rule6941 = ReplacementRule(pattern6941, replacement6941) pattern6942 = Pattern(Integral(u_/(w_*y_), x_), CustomConstraint(With6942)) rule6942 = ReplacementRule(pattern6942, replacement6942) pattern6943 = Pattern(Integral(u_*y_**WC('m', S(1)), x_), cons19, cons68, CustomConstraint(With6943)) rule6943 = ReplacementRule(pattern6943, replacement6943) pattern6944 = Pattern(Integral(u_*y_**WC('m', S(1))*z_**WC('n', S(1)), x_), cons19, cons4, cons68, CustomConstraint(With6944)) rule6944 = ReplacementRule(pattern6944, replacement6944) pattern6945 = Pattern(Integral(u_, x_), CustomConstraint(With6945)) rule6945 = ReplacementRule(pattern6945, replacement6945) pattern6946 = Pattern(Integral((sqrt(x_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)))*WC('e', S(1)) + sqrt(x_**WC('n', S(1))*WC('d', S(1)) + WC('c', S(0)))*WC('f', S(1)))**m_*WC('u', S(1)), x_), cons2, cons3, cons8, cons29, cons50, cons127, cons4, cons86, cons1039) rule6946 = ReplacementRule(pattern6946, replacement6946) pattern6947 = Pattern(Integral((sqrt(x_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)))*WC('e', S(1)) + sqrt(x_**WC('n', S(1))*WC('d', S(1)) + WC('c', S(0)))*WC('f', S(1)))**m_*WC('u', S(1)), x_), cons2, cons3, cons8, cons29, cons50, cons127, cons4, cons86, cons1038) rule6947 = ReplacementRule(pattern6947, replacement6947) pattern6948 = Pattern(Integral(u_**WC('m', S(1))*w_*(u_**n_*WC('a', S(1)) + v_)**WC('p', S(1)), x_), cons2, cons19, cons4, cons40, cons2010, cons10) rule6948 = ReplacementRule(pattern6948, replacement6948) pattern6949 = Pattern(Integral(u_*(v_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*(y_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1)), x_), cons2, cons3, cons8, cons29, cons19, cons4, cons2011, CustomConstraint(With6949)) rule6949 = ReplacementRule(pattern6949, replacement6949) pattern6950 = Pattern(Integral(u_*(v_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*(w_*WC('f', S(1)) + WC('e', S(0)))**WC('p', S(1))*(y_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1)), x_), cons2, cons3, cons8, cons29, cons50, cons127, cons19, cons4, cons5, cons2011, cons2012, CustomConstraint(With6950)) rule6950 = ReplacementRule(pattern6950, replacement6950) pattern6951 = Pattern(Integral(u_*(v_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*(w_*WC('f', S(1)) + WC('e', S(0)))**WC('p', S(1))*(y_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1))*(z_*WC('h', S(1)) + WC('g', S(0)))**WC('q', S(1)), x_), cons2, cons3, cons8, cons29, cons50, cons127, cons210, cons211, cons19, cons4, cons5, cons52, cons2011, cons2012, cons2013, CustomConstraint(With6951)) rule6951 = ReplacementRule(pattern6951, replacement6951) pattern6952 = Pattern(Integral((a_ + y_**n_*WC('b', S(1)))*WC('u', S(1)), x_), cons2, cons3, cons4, cons1833, CustomConstraint(With6952)) rule6952 = ReplacementRule(pattern6952, replacement6952) pattern6953 = Pattern(Integral((y_**n_*WC('b', S(1)) + WC('a', S(0)))**p_*WC('u', S(1)), x_), cons2, cons3, cons4, cons5, cons1246, CustomConstraint(With6953)) rule6953 = ReplacementRule(pattern6953, replacement6953) pattern6954 = Pattern(Integral(v_**WC('m', S(1))*(y_**n_*WC('b', S(1)) + WC('a', S(0)))**WC('p', S(1))*WC('u', S(1)), x_), cons2, cons3, cons19, cons4, cons5, cons2014, CustomConstraint(With6954)) rule6954 = ReplacementRule(pattern6954, replacement6954) pattern6955 = Pattern(Integral((v_**WC('n2', S(1))*WC('c', S(1)) + y_**n_*WC('b', S(1)) + WC('a', S(0)))**p_*WC('u', S(1)), x_), cons2, cons3, cons8, cons4, cons5, cons48, cons2011, CustomConstraint(With6955)) rule6955 = ReplacementRule(pattern6955, replacement6955) pattern6956 = Pattern(Integral((A_ + y_**n_*WC('B', S(1)))*(v_**n_*WC('b', S(1)) + w_**WC('n2', S(1))*WC('c', S(1)) + WC('a', S(0)))**WC('p', S(1))*WC('u', S(1)), x_), cons2, cons3, cons8, cons36, cons37, cons4, cons5, cons48, cons2011, cons2012, CustomConstraint(With6956)) rule6956 = ReplacementRule(pattern6956, replacement6956) pattern6957 = Pattern(Integral((A_ + y_**n_*WC('B', S(1)))*(w_**WC('n2', S(1))*WC('c', S(1)) + WC('a', S(0)))**WC('p', S(1))*WC('u', S(1)), x_), cons2, cons8, cons36, cons37, cons4, cons5, cons48, cons2012, CustomConstraint(With6957)) rule6957 = ReplacementRule(pattern6957, replacement6957) pattern6958 = Pattern(Integral(v_**WC('m', S(1))*(w_**WC('n2', S(1))*WC('c', S(1)) + y_**n_*WC('b', S(1)) + WC('a', S(0)))**WC('p', S(1))*WC('u', S(1)), x_), cons2, cons3, cons8, cons19, cons4, cons5, cons48, cons2012, CustomConstraint(With6958)) rule6958 = ReplacementRule(pattern6958, replacement6958) pattern6959 = Pattern(Integral(z_**WC('m', S(1))*(A_ + y_**n_*WC('B', S(1)))*(v_**n_*WC('b', S(1)) + w_**WC('n2', S(1))*WC('c', S(1)) + WC('a', S(0)))**WC('p', S(1))*WC('u', S(1)), x_), cons2, cons3, cons8, cons36, cons37, cons19, cons4, cons5, cons48, cons2011, cons2012, CustomConstraint(With6959)) rule6959 = ReplacementRule(pattern6959, replacement6959) pattern6960 = Pattern(Integral(z_**WC('m', S(1))*(A_ + y_**n_*WC('B', S(1)))*(w_**WC('n2', S(1))*WC('c', S(1)) + WC('a', S(0)))**WC('p', S(1))*WC('u', S(1)), x_), cons2, cons8, cons36, cons37, cons19, cons4, cons5, cons48, cons2012, CustomConstraint(With6960)) rule6960 = ReplacementRule(pattern6960, replacement6960) pattern6961 = Pattern(Integral((v_**n_*WC('d', S(1)) + WC('c', S(0)))**WC('p', S(1))*(y_**n_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1))*WC('u', S(1)), x_), cons2, cons3, cons8, cons29, cons19, cons4, cons5, cons2011, CustomConstraint(With6961)) rule6961 = ReplacementRule(pattern6961, replacement6961) pattern6962 = Pattern(Integral((v_**n_*WC('d', S(1)) + WC('c', S(0)))**WC('p', S(1))*(w_**n_*WC('f', S(1)) + WC('e', S(0)))**WC('q', S(1))*(y_**n_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1))*WC('u', S(1)), x_), cons2, cons3, cons8, cons29, cons50, cons127, cons19, cons4, cons5, cons52, cons2011, cons2012, CustomConstraint(With6962)) rule6962 = ReplacementRule(pattern6962, replacement6962) pattern6963 = Pattern(Integral(F_**v_*u_, x_), cons1101, cons1101, CustomConstraint(With6963)) rule6963 = ReplacementRule(pattern6963, replacement6963) pattern6964 = Pattern(Integral(F_**v_*u_*w_**WC('m', S(1)), x_), cons1101, cons19, cons2015, CustomConstraint(With6964)) rule6964 = ReplacementRule(pattern6964, replacement6964) pattern6965 = Pattern(Integral(u_*(a_ + v_**WC('p', S(1))*w_**WC('p', S(1))*WC('b', S(1)))**WC('m', S(1)), x_), cons2, cons3, cons19, cons5, cons40, CustomConstraint(With6965)) rule6965 = ReplacementRule(pattern6965, replacement6965) pattern6966 = Pattern(Integral(u_*v_**WC('r', S(1))*(a_ + v_**WC('p', S(1))*w_**WC('q', S(1))*WC('b', S(1)))**WC('m', S(1)), x_), cons2, cons3, cons19, cons5, cons52, cons54, cons2016, cons2017, cons2018, CustomConstraint(With6966)) rule6966 = ReplacementRule(pattern6966, replacement6966) pattern6967 = Pattern(Integral(u_*v_**WC('r', S(1))*w_**WC('s', S(1))*(a_ + v_**WC('p', S(1))*w_**WC('q', S(1))*WC('b', S(1)))**WC('m', S(1)), x_), cons2, cons3, cons19, cons5, cons52, cons54, cons802, cons2019, cons2017, cons2018, CustomConstraint(With6967)) rule6967 = ReplacementRule(pattern6967, replacement6967) pattern6968 = Pattern(Integral(u_*(v_**WC('p', S(1))*WC('a', S(1)) + w_**WC('q', S(1))*WC('b', S(1)))**WC('m', S(1)), x_), cons2, cons3, cons19, cons5, cons52, cons2020, cons40, cons20, CustomConstraint(With6968)) rule6968 = ReplacementRule(pattern6968, replacement6968) pattern6969 = Pattern(Integral(u_*v_**WC('r', S(1))*(v_**WC('p', S(1))*WC('a', S(1)) + w_**WC('q', S(1))*WC('b', S(1)))**WC('m', S(1)), x_), cons2, cons3, cons19, cons5, cons52, cons54, cons2021, cons588, cons20, CustomConstraint(With6969)) rule6969 = ReplacementRule(pattern6969, replacement6969) pattern6970 = Pattern(Integral(u_*w_**WC('s', S(1))*(v_**WC('p', S(1))*WC('a', S(1)) + w_**WC('q', S(1))*WC('b', S(1)))**WC('m', S(1)), x_), cons2, cons3, cons19, cons5, cons52, cons802, cons2022, cons2023, cons2024, cons20, CustomConstraint(With6970)) rule6970 = ReplacementRule(pattern6970, replacement6970) pattern6971 = Pattern(Integral(u_*v_**WC('r', S(1))*w_**WC('s', S(1))*(v_**WC('p', S(1))*WC('a', S(1)) + w_**WC('q', S(1))*WC('b', S(1)))**WC('m', S(1)), x_), cons2, cons3, cons19, cons5, cons52, cons54, cons802, cons2025, cons2023, cons2024, cons20, CustomConstraint(With6971)) rule6971 = ReplacementRule(pattern6971, replacement6971) pattern6972 = Pattern(Integral(u_*x_**WC('m', S(1)), x_), cons19, cons68, cons2026) rule6972 = ReplacementRule(pattern6972, replacement6972) pattern6973 = Pattern(Integral(u_, x_), CustomConstraint(With6973)) rule6973 = ReplacementRule(pattern6973, replacement6973) pattern6974 = Pattern(Integral(u_, x_), CustomConstraint(With6974)) rule6974 = ReplacementRule(pattern6974, replacement6974) pattern6975 = Pattern(Integral((v_**WC('m', S(1))*w_**WC('n', S(1))*z_**WC('q', S(1))*WC('a', S(1)))**p_*WC('u', S(1)), x_), cons2, cons19, cons4, cons5, cons52, cons149, cons10, cons2027, cons2028) rule6975 = ReplacementRule(pattern6975, replacement6975) pattern6976 = Pattern(Integral((v_**WC('m', S(1))*w_**WC('n', S(1))*WC('a', S(1)))**p_*WC('u', S(1)), x_), cons2, cons19, cons4, cons5, cons149, cons10, cons2027) rule6976 = ReplacementRule(pattern6976, replacement6976) pattern6977 = Pattern(Integral((v_**WC('m', S(1))*WC('a', S(1)))**p_*WC('u', S(1)), x_), cons2, cons19, cons5, cons149, cons10, cons2029, cons2030) rule6977 = ReplacementRule(pattern6977, replacement6977) pattern6978 = Pattern(Integral((x_**n_*WC('b', S(1)) + WC('a', S(0)))**p_*WC('u', S(1)), x_), cons2, cons3, cons5, cons669, cons198, cons2031) rule6978 = ReplacementRule(pattern6978, replacement6978) pattern6979 = Pattern(Integral((v_**n_*WC('b', S(1)) + WC('a', S(0)))**p_*WC('u', S(1)), x_), cons2, cons3, cons5, cons149, cons198, cons842, cons2032) rule6979 = ReplacementRule(pattern6979, replacement6979) pattern6980 = Pattern(Integral((v_**n_*x_**WC('m', S(1))*WC('b', S(1)) + WC('a', S(0)))**p_*WC('u', S(1)), x_), cons2, cons3, cons19, cons5, cons149, cons198, cons842) rule6980 = ReplacementRule(pattern6980, replacement6980) pattern6981 = Pattern(Integral((x_**WC('r', S(1))*WC('a', S(1)) + x_**WC('s', S(1))*WC('b', S(1)))**m_*WC('u', S(1)), x_), cons2, cons3, cons19, cons54, cons802, cons21, cons2033, CustomConstraint(With6981)) rule6981 = ReplacementRule(pattern6981, replacement6981) pattern6982 = Pattern(Integral(u_/(a_ + x_**n_*WC('b', S(1))), x_), cons2, cons3, cons150, CustomConstraint(With6982)) rule6982 = ReplacementRule(pattern6982, replacement6982) pattern6983 = Pattern(Integral(u_*(x_**WC('n', S(1))*WC('b', S(1)) + x_**WC('n2', S(1))*WC('c', S(1)) + WC('a', S(0)))**WC('p', S(1)), x_), cons2, cons3, cons8, cons4, cons48, cons47, cons40, cons2034) rule6983 = ReplacementRule(pattern6983, replacement6983) pattern6984 = Pattern(Integral(u_*(x_**WC('n', S(1))*WC('b', S(1)) + x_**WC('n2', S(1))*WC('c', S(1)) + WC('a', S(0)))**p_, x_), cons2, cons3, cons8, cons4, cons5, cons48, cons47, cons149, cons2034) rule6984 = ReplacementRule(pattern6984, replacement6984) pattern6985 = Pattern(Integral(u_/(x_**WC('n', S(1))*WC('b', S(1)) + x_**WC('n2', S(1))*WC('c', S(1)) + WC('a', S(0))), x_), cons2, cons3, cons8, cons48, cons150, CustomConstraint(With6985)) rule6985 = ReplacementRule(pattern6985, replacement6985) pattern6986 = Pattern(Integral(WC('u', S(1))/(x_**WC('m', S(1))*WC('a', S(1)) + sqrt(x_**n_*WC('c', S(1)))*WC('b', S(1))), x_), cons2, cons3, cons8, cons19, cons4, cons1856) rule6986 = ReplacementRule(pattern6986, replacement6986) pattern6987 = Pattern(Integral(u_, x_), CustomConstraint(With6987)) rule6987 = ReplacementRule(pattern6987, replacement6987) pattern6988 = Pattern(Integral(u_/x_, x_), cons1249, cons2031, CustomConstraint(With6988)) rule6988 = ReplacementRule(pattern6988, replacement6988) pattern6989 = Pattern(Integral(u_*x_**WC('m', S(1)), x_), cons20, cons263, cons1249, cons2035, CustomConstraint(With6989)) rule6989 = ReplacementRule(pattern6989, replacement6989) pattern6990 = Pattern(Integral(u_*x_**m_, x_), cons369) rule6990 = ReplacementRule(pattern6990, With6990) pattern6991 = Pattern(Integral(u_, x_), cons2036, CustomConstraint(With6991)) rule6991 = ReplacementRule(pattern6991, replacement6991) pattern6992 = Pattern(Integral(S(1)/(a_ + v_**S(2)*WC('b', S(1))), x_), cons2, cons3, cons69) rule6992 = ReplacementRule(pattern6992, replacement6992) pattern6993 = Pattern(Integral(S(1)/(a_ + v_**n_*WC('b', S(1))), x_), cons2, cons3, cons1481, cons746) rule6993 = ReplacementRule(pattern6993, replacement6993) pattern6994 = Pattern(Integral(S(1)/(a_ + v_**n_*WC('b', S(1))), x_), cons2, cons3, cons1484, cons167) rule6994 = ReplacementRule(pattern6994, replacement6994) pattern6995 = Pattern(Integral(v_/(a_ + u_**WC('n', S(1))*WC('b', S(1))), x_), cons2, cons3, cons150, cons2037) rule6995 = ReplacementRule(pattern6995, replacement6995) pattern6996 = Pattern(Integral(u_, x_), CustomConstraint(With6996)) rule6996 = ReplacementRule(pattern6996, replacement6996) pattern6997 = Pattern(Integral(u_, x_), CustomConstraint(With6997)) rule6997 = ReplacementRule(pattern6997, replacement6997) pattern6998 = Pattern(Integral((x_**WC('m', S(1))*WC('b', S(1)) + WC('a', S(0)))**WC('p', S(1))*(x_**WC('n', S(1))*WC('d', S(1)) + WC('c', S(0)))**WC('q', S(1))*WC('u', S(1)), x_), cons2, cons3, cons8, cons29, cons19, cons4, cons5, cons52, cons2038, cons1678, cons1257, cons2039) rule6998 = ReplacementRule(pattern6998, replacement6998) pattern6999 = Pattern(Integral(u_*(a_ + x_**WC('n', S(1))*WC('b', S(1)) + x_**WC('n2', S(1))*WC('c', S(1)))**p_, x_), cons2, cons3, cons8, cons4, cons5, cons48, cons47, cons349) rule6999 = ReplacementRule(pattern6999, replacement6999) pattern7000 = Pattern(Integral(u_, x_), CustomConstraint(With7000)) rule7000 = ReplacementRule(pattern7000, replacement7000) pattern7001 = Pattern(Integral(u_, x_)) rule7001 = ReplacementRule(pattern7001, replacement7001) return [rule6934, rule6935, rule6936, rule6937, rule6938, rule6939, rule6940, rule6941, rule6942, rule6943, rule6944, rule6945, rule6946, rule6947, rule6948, rule6949, rule6950, rule6951, rule6952, rule6953, rule6954, rule6955, rule6956, rule6957, rule6958, rule6959, rule6960, rule6961, rule6962, rule6963, rule6964, rule6965, rule6966, rule6967, rule6968, rule6969, rule6970, rule6971, rule6972, rule6973, rule6974, rule6975, rule6976, rule6977, rule6978, rule6979, rule6980, rule6981, rule6982, rule6983, rule6984, rule6985, rule6986, rule6987, rule6988, rule6989, rule6990, rule6991, rule6992, rule6993, rule6994, rule6995, rule6996, rule6997, rule6998, rule6999, rule7000, rule7001, ] def replacement6934(a, b, c, n, p, u, x): return Dist(c**IntPart(p)*(c*(a + b*x)**n)**FracPart(p)*(a + b*x)**(-n*FracPart(p)), Int(u*(a + b*x)**(n*p), x), x) def replacement6935(a, b, c, d, p, q, u, x): return Dist((c*(d*(a + b*x))**p)**q*(a + b*x)**(-p*q), Int(u*(a + b*x)**(p*q), x), x) def replacement6936(a, b, c, d, n, p, q, u, x): return Dist((c*(d*(a + b*x)**n)**p)**q*(a + b*x)**(-n*p*q), Int(u*(a + b*x)**(n*p*q), x), x) def replacement6937(A, B, C, F, a, b, c, d, e, f, g, n, x): return Dist(g/C, Subst(Int((a + b*F(c*x))**n/x, x), x, sqrt(d + e*x)/sqrt(f + g*x)), x) def replacement6938(A, C, F, a, b, c, e, g, n, x): return Dist(g/C, Subst(Int((a + b*F(c*x))**n/x, x), x, sqrt(e*x + S(1))/sqrt(g*x + S(1))), x) def replacement6939(A, B, C, F, a, b, c, d, e, f, g, n, x): return Dist(g/C, Subst(Int((F**(c*x)*b + a)**n/x, x), x, sqrt(d + e*x)/sqrt(f + g*x)), x) def replacement6940(A, C, F, a, b, c, e, g, n, x): return Dist(g/C, Subst(Int((F**(c*x)*b + a)**n/x, x), x, sqrt(e*x + S(1))/sqrt(g*x + S(1))), x) def With6941(u, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(y, u, x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6941(u, x, y): q = DerivativeDivides(y, u, x) return Simp(q*log(RemoveContent(y, x)), x) def With6942(u, w, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(w*y, u, x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6942(u, w, x, y): q = DerivativeDivides(w*y, u, x) return Simp(q*log(RemoveContent(w*y, x)), x) def With6943(m, u, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(y, u, x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6943(m, u, x, y): q = DerivativeDivides(y, u, x) return Simp(q*y**(m + S(1))/(m + S(1)), x) def With6944(m, n, u, x, y, z): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(y*z, u*z**(-m + n), x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6944(m, n, u, x, y, z): q = DerivativeDivides(y*z, u*z**(-m + n), x) return Simp(q*y**(m + S(1))*z**(m + S(1))/(m + S(1)), x) def With6945(u, x): if isinstance(x, (int, Integer, float, Float)): return False v = SimplifyIntegrand(u, x) if SimplerIntegrandQ(v, u, x): return True return False def replacement6945(u, x): v = SimplifyIntegrand(u, x) return Int(v, x) def replacement6946(a, b, c, d, e, f, m, n, u, x): return Dist((a*e**S(2) - c*f**S(2))**m, Int(ExpandIntegrand(u*(e*sqrt(a + b*x**n) - f*sqrt(c + d*x**n))**(-m), x), x), x) def replacement6947(a, b, c, d, e, f, m, n, u, x): return Dist((b*e**S(2) - d*f**S(2))**m, Int(ExpandIntegrand(u*x**(m*n)*(e*sqrt(a + b*x**n) - f*sqrt(c + d*x**n))**(-m), x), x), x) def replacement6948(a, m, n, p, u, v, w, x): return Int(u**(m + n*p)*w*(a + u**(-n)*v)**p, x) def With6949(a, b, c, d, m, n, u, v, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(y, u, x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6949(a, b, c, d, m, n, u, v, x, y): q = DerivativeDivides(y, u, x) return Dist(q, Subst(Int((a + b*x)**m*(c + d*x)**n, x), x, y), x) def With6950(a, b, c, d, e, f, m, n, p, u, v, w, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(y, u, x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6950(a, b, c, d, e, f, m, n, p, u, v, w, x, y): q = DerivativeDivides(y, u, x) return Dist(q, Subst(Int((a + b*x)**m*(c + d*x)**n*(e + f*x)**p, x), x, y), x) def With6951(a, b, c, d, e, f, g, h, m, n, p, q, u, v, w, x, y, z): if isinstance(x, (int, Integer, float, Float)): return False try: r = DerivativeDivides(y, u, x) res = Not(FalseQ(r)) except (TypeError, AttributeError): return False if res: return True return False def replacement6951(a, b, c, d, e, f, g, h, m, n, p, q, u, v, w, x, y, z): r = DerivativeDivides(y, u, x) return Dist(r, Subst(Int((a + b*x)**m*(c + d*x)**n*(e + f*x)**p*(g + h*x)**q, x), x, y), x) def With6952(a, b, n, u, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(y, u, x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6952(a, b, n, u, x, y): q = DerivativeDivides(y, u, x) return Dist(a, Int(u, x), x) + Dist(b*q, Subst(Int(x**n, x), x, y), x) def With6953(a, b, n, p, u, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(y, u, x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6953(a, b, n, p, u, x, y): q = DerivativeDivides(y, u, x) return Dist(q, Subst(Int((a + b*x**n)**p, x), x, y), x) def With6954(a, b, m, n, p, u, v, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: q = Symbol('q') r = Symbol('r') r = Divides(y**m, v**m, x) q = DerivativeDivides(y, u, x) res = And(Not(FalseQ(Set(r, Divides(y**m, v**m, x)))), Not(FalseQ(Set(q, DerivativeDivides(y, u, x))))) except (TypeError, AttributeError): return False if res: return True return False def replacement6954(a, b, m, n, p, u, v, x, y): q = Symbol('q') r = Symbol('r') r = Divides(y**m, v**m, x) q = DerivativeDivides(y, u, x) return Dist(q*r, Subst(Int(x**m*(a + b*x**n)**p, x), x, y), x) def With6955(a, b, c, n, n2, p, u, v, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(y, u, x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6955(a, b, c, n, n2, p, u, v, x, y): q = DerivativeDivides(y, u, x) return Dist(q, Subst(Int((a + b*x**n + c*x**(S(2)*n))**p, x), x, y), x) def With6956(A, B, a, b, c, n, n2, p, u, v, w, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(y, u, x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6956(A, B, a, b, c, n, n2, p, u, v, w, x, y): q = DerivativeDivides(y, u, x) return Dist(q, Subst(Int((A + B*x**n)*(a + b*x**n + c*x**(S(2)*n))**p, x), x, y), x) def With6957(A, B, a, c, n, n2, p, u, w, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(y, u, x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6957(A, B, a, c, n, n2, p, u, w, x, y): q = DerivativeDivides(y, u, x) return Dist(q, Subst(Int((A + B*x**n)*(a + c*x**(S(2)*n))**p, x), x, y), x) def With6958(a, b, c, m, n, n2, p, u, v, w, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: q = Symbol('q') r = Symbol('r') r = Divides(y**m, v**m, x) q = DerivativeDivides(y, u, x) res = And(Not(FalseQ(Set(r, Divides(y**m, v**m, x)))), Not(FalseQ(Set(q, DerivativeDivides(y, u, x))))) except (TypeError, AttributeError): return False if res: return True return False def replacement6958(a, b, c, m, n, n2, p, u, v, w, x, y): q = Symbol('q') r = Symbol('r') r = Divides(y**m, v**m, x) q = DerivativeDivides(y, u, x) return Dist(q*r, Subst(Int(x**m*(a + b*x**n + c*x**(S(2)*n))**p, x), x, y), x) def With6959(A, B, a, b, c, m, n, n2, p, u, v, w, x, y, z): if isinstance(x, (int, Integer, float, Float)): return False try: q = Symbol('q') r = Symbol('r') r = Divides(y**m, z**m, x) q = DerivativeDivides(y, u, x) res = And(Not(FalseQ(Set(r, Divides(y**m, z**m, x)))), Not(FalseQ(Set(q, DerivativeDivides(y, u, x))))) except (TypeError, AttributeError): return False if res: return True return False def replacement6959(A, B, a, b, c, m, n, n2, p, u, v, w, x, y, z): q = Symbol('q') r = Symbol('r') r = Divides(y**m, z**m, x) q = DerivativeDivides(y, u, x) return Dist(q*r, Subst(Int(x**m*(A + B*x**n)*(a + b*x**n + c*x**(S(2)*n))**p, x), x, y), x) def With6960(A, B, a, c, m, n, n2, p, u, w, x, y, z): if isinstance(x, (int, Integer, float, Float)): return False try: q = Symbol('q') r = Symbol('r') r = Divides(y**m, z**m, x) q = DerivativeDivides(y, u, x) res = And(Not(FalseQ(Set(r, Divides(y**m, z**m, x)))), Not(FalseQ(Set(q, DerivativeDivides(y, u, x))))) except (TypeError, AttributeError): return False if res: return True return False def replacement6960(A, B, a, c, m, n, n2, p, u, w, x, y, z): q = Symbol('q') r = Symbol('r') r = Divides(y**m, z**m, x) q = DerivativeDivides(y, u, x) return Dist(q*r, Subst(Int(x**m*(A + B*x**n)*(a + c*x**(S(2)*n))**p, x), x, y), x) def With6961(a, b, c, d, m, n, p, u, v, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(y, u, x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6961(a, b, c, d, m, n, p, u, v, x, y): q = DerivativeDivides(y, u, x) return Dist(q, Subst(Int((a + b*x**n)**m*(c + d*x**n)**p, x), x, y), x) def With6962(a, b, c, d, e, f, m, n, p, q, u, v, w, x, y): if isinstance(x, (int, Integer, float, Float)): return False try: r = DerivativeDivides(y, u, x) res = Not(FalseQ(r)) except (TypeError, AttributeError): return False if res: return True return False def replacement6962(a, b, c, d, e, f, m, n, p, q, u, v, w, x, y): r = DerivativeDivides(y, u, x) return Dist(r, Subst(Int((a + b*x**n)**m*(c + d*x**n)**p*(e + f*x**n)**q, x), x, y), x) def With6963(F, u, v, x): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(v, u, x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6963(F, u, v, x): q = DerivativeDivides(v, u, x) return Simp(F**v*q/log(F), x) def With6964(F, m, u, v, w, x): if isinstance(x, (int, Integer, float, Float)): return False try: q = DerivativeDivides(v, u, x) res = Not(FalseQ(q)) except (TypeError, AttributeError): return False if res: return True return False def replacement6964(F, m, u, v, w, x): q = DerivativeDivides(v, u, x) return Dist(q, Subst(Int(F**x*x**m, x), x, v), x) def With6965(a, b, m, p, u, v, w, x): if isinstance(x, (int, Integer, float, Float)): return False c = u/(v*D(w, x) + w*D(v, x)) if FreeQ(c, x): return True return False def replacement6965(a, b, m, p, u, v, w, x): c = u/(v*D(w, x) + w*D(v, x)) return Dist(c, Subst(Int((a + b*x**p)**m, x), x, v*w), x) def With6966(a, b, m, p, q, r, u, v, w, x): if isinstance(x, (int, Integer, float, Float)): return False c = u/(p*w*D(v, x) + q*v*D(w, x)) if FreeQ(c, x): return True return False def replacement6966(a, b, m, p, q, r, u, v, w, x): c = u/(p*w*D(v, x) + q*v*D(w, x)) return Dist(c*p/(r + S(1)), Subst(Int((a + b*x**(p/(r + S(1))))**m, x), x, v**(r + S(1))*w), x) def With6967(a, b, m, p, q, r, s, u, v, w, x): if isinstance(x, (int, Integer, float, Float)): return False c = u/(p*w*D(v, x) + q*v*D(w, x)) if FreeQ(c, x): return True return False def replacement6967(a, b, m, p, q, r, s, u, v, w, x): c = u/(p*w*D(v, x) + q*v*D(w, x)) return Dist(c*p/(r + S(1)), Subst(Int((a + b*x**(p/(r + S(1))))**m, x), x, v**(r + S(1))*w**(s + S(1))), x) def With6968(a, b, m, p, q, u, v, w, x): if isinstance(x, (int, Integer, float, Float)): return False c = u/(p*w*D(v, x) - q*v*D(w, x)) if FreeQ(c, x): return True return False def replacement6968(a, b, m, p, q, u, v, w, x): c = u/(p*w*D(v, x) - q*v*D(w, x)) return Dist(c*p, Subst(Int((a*x**p + b)**m, x), x, v*w**(m*q + S(1))), x) def With6969(a, b, m, p, q, r, u, v, w, x): if isinstance(x, (int, Integer, float, Float)): return False c = u/(p*w*D(v, x) - q*v*D(w, x)) if FreeQ(c, x): return True return False def replacement6969(a, b, m, p, q, r, u, v, w, x): c = u/(p*w*D(v, x) - q*v*D(w, x)) return -Dist(c*q, Subst(Int((a + b*x**q)**m, x), x, v**(m*p + r + S(1))*w), x) def With6970(a, b, m, p, q, s, u, v, w, x): if isinstance(x, (int, Integer, float, Float)): return False c = u/(p*w*D(v, x) - q*v*D(w, x)) if FreeQ(c, x): return True return False def replacement6970(a, b, m, p, q, s, u, v, w, x): c = u/(p*w*D(v, x) - q*v*D(w, x)) return -Dist(c*q/(s + S(1)), Subst(Int((a + b*x**(q/(s + S(1))))**m, x), x, v**(m*p + S(1))*w**(s + S(1))), x) def With6971(a, b, m, p, q, r, s, u, v, w, x): if isinstance(x, (int, Integer, float, Float)): return False c = u/(p*w*D(v, x) - q*v*D(w, x)) if FreeQ(c, x): return True return False def replacement6971(a, b, m, p, q, r, s, u, v, w, x): c = u/(p*w*D(v, x) - q*v*D(w, x)) return -Dist(c*q/(s + S(1)), Subst(Int((a + b*x**(q/(s + S(1))))**m, x), x, v**(m*p + r + S(1))*w**(s + S(1))), x) def replacement6972(m, u, x): return Dist(S(1)/(m + S(1)), Subst(Int(SubstFor(x**(m + S(1)), u, x), x), x, x**(m + S(1))), x) def With6973(u, x): if isinstance(x, (int, Integer, float, Float)): return False try: lst = SubstForFractionalPowerOfLinear(u, x) res = And(Not(FalseQ(lst)), SubstForFractionalPowerQ(u, Part(lst, S(3)), x)) except (TypeError, AttributeError): return False if res: return True return False def replacement6973(u, x): lst = SubstForFractionalPowerOfLinear(u, x) return Dist(Part(lst, S(2))*Part(lst, S(4)), Subst(Int(Part(lst, S(1)), x), x, Part(lst, S(3))**(S(1)/Part(lst, S(2)))), x) def With6974(u, x): if isinstance(x, (int, Integer, float, Float)): return False try: lst = SubstForFractionalPowerOfQuotientOfLinears(u, x) res = Not(FalseQ(lst)) except (TypeError, AttributeError): return False if res: return True return False def replacement6974(u, x): lst = SubstForFractionalPowerOfQuotientOfLinears(u, x) return Dist(Part(lst, S(2))*Part(lst, S(4)), Subst(Int(Part(lst, S(1)), x), x, Part(lst, S(3))**(S(1)/Part(lst, S(2)))), x) def replacement6975(a, m, n, p, q, u, v, w, x, z): return Dist(a**IntPart(p)*v**(-m*FracPart(p))*w**(-n*FracPart(p))*z**(-q*FracPart(p))*(a*v**m*w**n*z**q)**FracPart(p), Int(u*v**(m*p)*w**(n*p)*z**(p*q), x), x) def replacement6976(a, m, n, p, u, v, w, x): return Dist(a**IntPart(p)*v**(-m*FracPart(p))*w**(-n*FracPart(p))*(a*v**m*w**n)**FracPart(p), Int(u*v**(m*p)*w**(n*p), x), x) def replacement6977(a, m, p, u, v, x): return Dist(a**IntPart(p)*v**(-m*FracPart(p))*(a*v**m)**FracPart(p), Int(u*v**(m*p), x), x) def replacement6978(a, b, n, p, u, x): return Dist(FullSimplify(x**(-n/S(2))*sqrt(a + b*x**n)/sqrt(a*x**(-n) + b)), Int(u*x**(n*p)*(a*x**(-n) + b)**p, x), x) def replacement6979(a, b, n, p, u, v, x): return Dist(v**(-n*FracPart(p))*(a + b*v**n)**FracPart(p)*(a*v**(-n) + b)**(-FracPart(p)), Int(u*v**(n*p)*(a*v**(-n) + b)**p, x), x) def replacement6980(a, b, m, n, p, u, v, x): return Dist(v**(-n*FracPart(p))*(a + b*v**n*x**m)**FracPart(p)*(a*v**(-n) + b*x**m)**(-FracPart(p)), Int(u*v**(n*p)*(a*v**(-n) + b*x**m)**p, x), x) def With6981(a, b, m, r, s, u, x): if isinstance(x, (int, Integer, float, Float)): return False v = x**(-r*FracPart(m))*(a + b*x**(-r + s))**(-FracPart(m))*(a*x**r + b*x**s)**FracPart(m) if Not(EqQ(v, S(1))): return True return False def replacement6981(a, b, m, r, s, u, x): v = x**(-r*FracPart(m))*(a + b*x**(-r + s))**(-FracPart(m))*(a*x**r + b*x**s)**FracPart(m) return Dist(v, Int(u*x**(m*r)*(a + b*x**(-r + s))**m, x), x) def With6982(a, b, n, u, x): if isinstance(x, (int, Integer, float, Float)): return False v = RationalFunctionExpand(u/(a + b*x**n), x) if SumQ(v): return True return False def replacement6982(a, b, n, u, x): v = RationalFunctionExpand(u/(a + b*x**n), x) return Int(v, x) def replacement6983(a, b, c, n, n2, p, u, x): return Dist(S(4)**(-p)*c**(-p), Int(u*(b + S(2)*c*x**n)**(S(2)*p), x), x) def replacement6984(a, b, c, n, n2, p, u, x): return Dist((b + S(2)*c*x**n)**(-S(2)*p)*(a + b*x**n + c*x**(S(2)*n))**p, Int(u*(b + S(2)*c*x**n)**(S(2)*p), x), x) def With6985(a, b, c, n, n2, u, x): if isinstance(x, (int, Integer, float, Float)): return False v = RationalFunctionExpand(u/(a + b*x**n + c*x**(S(2)*n)), x) if SumQ(v): return True return False def replacement6985(a, b, c, n, n2, u, x): v = RationalFunctionExpand(u/(a + b*x**n + c*x**(S(2)*n)), x) return Int(v, x) def replacement6986(a, b, c, m, n, u, x): return Int(u*(a*x**m - b*sqrt(c*x**n))/(a**S(2)*x**(S(2)*m) - b**S(2)*c*x**n), x) def With6987(u, x): if isinstance(x, (int, Integer, float, Float)): return False try: lst = FunctionOfLinear(u, x) res = Not(FalseQ(lst)) except (TypeError, AttributeError): return False if res: return True return False def replacement6987(u, x): lst = FunctionOfLinear(u, x) return Dist(S(1)/Part(lst, S(3)), Subst(Int(Part(lst, S(1)), x), x, x*Part(lst, S(3)) + Part(lst, S(2))), x) def With6988(u, x): if isinstance(x, (int, Integer, float, Float)): return False try: lst = PowerVariableExpn(u, S(0), x) res = And(Not(FalseQ(lst)), NonzeroQ(Part(lst, S(2)))) except (TypeError, AttributeError): return False if res: return True return False def replacement6988(u, x): lst = PowerVariableExpn(u, S(0), x) return Dist(S(1)/Part(lst, S(2)), Subst(Int(NormalizeIntegrand(Part(lst, S(1))/x, x), x), x, (x*Part(lst, S(3)))**Part(lst, S(2))), x) def With6989(m, u, x): if isinstance(x, (int, Integer, float, Float)): return False try: lst = PowerVariableExpn(u, m + S(1), x) res = And(Not(FalseQ(lst)), NonzeroQ(-m + Part(lst, S(2)) + S(-1))) except (TypeError, AttributeError): return False if res: return True return False def replacement6989(m, u, x): lst = PowerVariableExpn(u, m + S(1), x) return Dist(S(1)/Part(lst, S(2)), Subst(Int(NormalizeIntegrand(Part(lst, S(1))/x, x), x), x, (x*Part(lst, S(3)))**Part(lst, S(2))), x) def With6990(m, u, x): k = Denominator(m) return Dist(k, Subst(Int(x**(k*(m + S(1)) + S(-1))*ReplaceAll(u, Rule(x, x**k)), x), x, x**(S(1)/k)), x) def With6991(u, x): if isinstance(x, (int, Integer, float, Float)): return False try: lst = FunctionOfSquareRootOfQuadratic(u, x) res = Not(FalseQ(lst)) except (TypeError, AttributeError): return False if res: return True return False def replacement6991(u, x): lst = FunctionOfSquareRootOfQuadratic(u, x) return Dist(S(2), Subst(Int(Part(lst, S(1)), x), x, Part(lst, S(2))), x) def replacement6992(a, b, v, x): return Dist(S(1)/(S(2)*a), Int(Together(S(1)/(-v/Rt(-a/b, S(2)) + S(1))), x), x) + Dist(S(1)/(S(2)*a), Int(Together(S(1)/(v/Rt(-a/b, S(2)) + S(1))), x), x) def replacement6993(a, b, n, v, x): return Dist(S(2)/(a*n), Sum_doit(Int(Together(S(1)/(S(1) - (S(-1))**(-S(4)*k/n)*v**S(2)/Rt(-a/b, n/S(2)))), x), List(k, S(1), n/S(2))), x) def replacement6994(a, b, n, v, x): return Dist(S(1)/(a*n), Sum_doit(Int(Together(S(1)/(S(1) - (S(-1))**(-S(2)*k/n)*v/Rt(-a/b, n))), x), List(k, S(1), n)), x) def replacement6995(a, b, n, u, v, x): return Int(ReplaceAll(ExpandIntegrand(PolynomialInSubst(v, u, x)/(a + b*x**n), x), Rule(x, u)), x) def With6996(u, x): if isinstance(x, (int, Integer, float, Float)): return False v = NormalizeIntegrand(u, x) if UnsameQ(v, u): return True return False def replacement6996(u, x): v = NormalizeIntegrand(u, x) return Int(v, x) def With6997(u, x): if isinstance(x, (int, Integer, float, Float)): return False v = ExpandIntegrand(u, x) if SumQ(v): return True return False def replacement6997(u, x): v = ExpandIntegrand(u, x) return Int(v, x) def replacement6998(a, b, c, d, m, n, p, q, u, x): return Dist(x**(-m*p)*(a + b*x**m)**p*(c + d*x**n)**q, Int(u*x**(m*p), x), x) def replacement6999(a, b, c, n, n2, p, u, x): return Dist((S(4)*c)**(S(1)/2 - p)*sqrt(a + b*x**n + c*x**(S(2)*n))/(b + S(2)*c*x**n), Int(u*(b + S(2)*c*x**n)**(S(2)*p), x), x) def With7000(u, x): if isinstance(x, (int, Integer, float, Float)): return False try: lst = SubstForFractionalPowerOfLinear(u, x) res = Not(FalseQ(lst)) except (TypeError, AttributeError): return False if res: return True return False def replacement7000(u, x): lst = SubstForFractionalPowerOfLinear(u, x) return Dist(Part(lst, S(2))*Part(lst, S(4)), Subst(Int(Part(lst, S(1)), x), x, Part(lst, S(3))**(S(1)/Part(lst, S(2)))), x) def replacement7001(u, x): return Int(u, x)
{ "pile_set_name": "Github" }
AUTHORS COPYING ChangeLog INSTALL NEWS README doc/designstyle.css doc/glog.html
{ "pile_set_name": "Github" }
/* Name: usbdrvasm20.inc * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers * Author: Jeroen Benschop * Based on usbdrvasm16.inc from Christian Starkjohann * Creation Date: 2008-03-05 * Tabsize: 4 * Copyright: (c) 2008 by Jeroen Benschop and OBJECTIVE DEVELOPMENT Software GmbH * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt) * Revision: $Id: usbdrvasm20.inc 740 2009-04-13 18:23:31Z cs $ */ /* Do not link this file! Link usbdrvasm.S instead, which includes the * appropriate implementation! */ /* General Description: This file is the 20 MHz version of the asssembler part of the USB driver. It requires a 20 MHz crystal (not a ceramic resonator and not a calibrated RC oscillator). See usbdrv.h for a description of the entire driver. Since almost all of this code is timing critical, don't change unless you really know what you are doing! Many parts require not only a maximum number of CPU cycles, but even an exact number of cycles! */ #define leap2 x3 #ifdef __IAR_SYSTEMS_ASM__ #define nextInst $+2 #else #define nextInst .+0 #endif ;max stack usage: [ret(2), YL, SREG, YH, bitcnt, shift, x1, x2, x3, x4, cnt] = 12 bytes ;nominal frequency: 20 MHz -> 13.333333 cycles per bit, 106.666667 cycles per byte ; Numbers in brackets are clocks counted from center of last sync bit ; when instruction starts ;register use in receive loop: ; shift assembles the byte currently being received ; x1 holds the D+ and D- line state ; x2 holds the previous line state ; x4 (leap) is used to add a leap cycle once every three bytes received ; X3 (leap2) is used to add a leap cycle once every three stuff bits received ; bitcnt is used to determine when a stuff bit is due ; cnt holds the number of bytes left in the receive buffer USB_INTR_VECTOR: ;order of registers pushed: YL, SREG YH, [sofError], bitcnt, shift, x1, x2, x3, x4, cnt push YL ;[-28] push only what is necessary to sync with edge ASAP in YL, SREG ;[-26] push YL ;[-25] push YH ;[-23] ;---------------------------------------------------------------------------- ; Synchronize with sync pattern: ;---------------------------------------------------------------------------- ;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K] ;sync up with J to K edge during sync pattern -- use fastest possible loops ;The first part waits at most 1 bit long since we must be in sync pattern. ;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to ;waitForJ, ensure that this prerequisite is met. waitForJ: inc YL sbis USBIN, USBMINUS brne waitForJ ; just make sure we have ANY timeout waitForK: ;The following code results in a sampling window of < 1/4 bit which meets the spec. sbis USBIN, USBMINUS ;[-19] rjmp foundK ;[-18] sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK sbis USBIN, USBMINUS rjmp foundK #if USB_COUNT_SOF lds YL, usbSofCount inc YL sts usbSofCount, YL #endif /* USB_COUNT_SOF */ #ifdef USB_SOF_HOOK USB_SOF_HOOK #endif rjmp sofError foundK: ;[-16] ;{3, 5} after falling D- edge, average delay: 4 cycles ;bit0 should be at 34 for center sampling. Currently at 4 so 30 cylces till bit 0 sample ;use 1 bit time for setup purposes, then sample again. Numbers in brackets ;are cycles from center of first sync (double K) bit after the instruction push bitcnt ;[-16] ; [---] ;[-15] lds YL, usbInputBufOffset;[-14] ; [---] ;[-13] clr YH ;[-12] subi YL, lo8(-(usbRxBuf));[-11] [rx loop init] sbci YH, hi8(-(usbRxBuf));[-10] [rx loop init] push shift ;[-9] ; [---] ;[-8] ldi shift,0x40 ;[-7] set msb to "1" so processing bit7 can be detected nop2 ;[-6] ; [---] ;[-5] ldi bitcnt, 5 ;[-4] [rx loop init] sbis USBIN, USBMINUS ;[-3] we want two bits K (sample 3 cycles too early) rjmp haveTwoBitsK ;[-2] pop shift ;[-1] undo the push from before pop bitcnt ;[1] rjmp waitForK ;[3] this was not the end of sync, retry ; The entire loop from waitForK until rjmp waitForK above must not exceed two ; bit times (= 27 cycles). ;---------------------------------------------------------------------------- ; push more registers and initialize values while we sample the first bits: ;---------------------------------------------------------------------------- haveTwoBitsK: push x1 ;[0] push x2 ;[2] push x3 ;[4] (leap2) ldi leap2, 0x55 ;[6] add leap cycle on 2nd,5th,8th,... stuff bit push x4 ;[7] == leap ldi leap, 0x55 ;[9] skip leap cycle on 2nd,5th,8th,... byte received push cnt ;[10] ldi cnt, USB_BUFSIZE ;[12] [rx loop init] ldi x2, 1<<USBPLUS ;[13] current line state is K state. D+=="1", D-=="0" bit0: in x1, USBIN ;[0] sample line state andi x1, USBMASK ;[1] filter only D+ and D- bits rjmp handleBit ;[2] make bit0 14 cycles long ;---------------------------------------------------------------------------- ; Process bit7. However, bit 6 still may need unstuffing. ;---------------------------------------------------------------------------- b6checkUnstuff: dec bitcnt ;[9] breq unstuff6 ;[10] bit7: subi cnt, 1 ;[11] cannot use dec becaus it does not affect the carry flag brcs overflow ;[12] Too many bytes received. Ignore packet in x1, USBIN ;[0] sample line state andi x1, USBMASK ;[1] filter only D+ and D- bits cpse x1, x2 ;[2] when previous line state equals current line state, handle "1" rjmp b7handle0 ;[3] when line state differs, handle "0" sec ;[4] ror shift ;[5] shift "1" into the data st y+, shift ;[6] store the data into the buffer ldi shift, 0x40 ;[7] reset data for receiving the next byte subi leap, 0x55 ;[9] trick to introduce a leap cycle every 3 bytes brcc nextInst ;[10 or 11] it will fail after 85 bytes. However low speed can only receive 11 dec bitcnt ;[11 or 12] brne bit0 ;[12 or 13] ldi x1, 1 ;[13 or 14] unstuffing bit 7 in bitcnt, USBIN ;[0] sample stuff bit rjmp unstuff ;[1] b7handle0: mov x2,x1 ;[5] Set x2 to current line state ldi bitcnt, 6 ;[6] lsr shift ;[7] shift "0" into the data st y+, shift ;[8] store data into the buffer ldi shift, 0x40 ;[10] reset data for receiving the next byte subi leap, 0x55 ;[11] trick to introduce a leap cycle every 3 bytes brcs bit0 ;[12] it will fail after 85 bytes. However low speed can only receive 11 rjmp bit0 ;[13] ;---------------------------------------------------------------------------- ; Handle unstuff ; x1==0xFF indicate unstuffing bit6 ;---------------------------------------------------------------------------- unstuff6: ldi x1,0xFF ;[12] indicate unstuffing bit 6 in bitcnt, USBIN ;[0] sample stuff bit nop ;[1] fix timing unstuff: ;b0-5 b6 b7 mov x2,bitcnt ;[3] [2] [3] Set x2 to match line state subi leap2, 0x55 ;[4] [3] [4] delay loop brcs nextInst ;[5] [4] [5] add one cycle every three stuff bits sbci leap2,0 ;[6] [5] [6] ldi bitcnt,6 ;[7] [6] [7] reset bit stuff counter andi x2, USBMASK ;[8] [7] [8] only keep D+ and D- cpi x1,0 ;[9] [8] [9] brmi bit7 ;[10] [9] [10] finished unstuffing bit6 When x1<0 breq bitloop ;[11] --- [11] finished unstuffing bit0-5 when x1=0 nop ;--- --- [12] in x1, USBIN ;--- --- [0] sample line state for bit0 andi x1, USBMASK ;--- --- [1] filter only D+ and D- bits rjmp handleBit ;--- --- [2] make bit0 14 cycles long ;---------------------------------------------------------------------------- ; Receiver loop (numbers in brackets are cycles within byte after instr) ;---------------------------------------------------------------------------- bitloop: in x1, USBIN ;[0] sample line state andi x1, USBMASK ;[1] filter only D+ and D- bits breq se0 ;[2] both lines are low so handle se0 handleBit: cpse x1, x2 ;[3] when previous line state equals current line state, handle "1" rjmp handle0 ;[4] when line state differs, handle "0" sec ;[5] ror shift ;[6] shift "1" into the data brcs b6checkUnstuff ;[7] When after shift C is set, next bit is bit7 nop2 ;[8] dec bitcnt ;[10] brne bitloop ;[11] ldi x1,0 ;[12] indicate unstuff for bit other than bit6 or bit7 in bitcnt, USBIN ;[0] sample stuff bit rjmp unstuff ;[1] handle0: mov x2, x1 ;[6] Set x2 to current line state ldi bitcnt, 6 ;[7] reset unstuff counter. lsr shift ;[8] shift "0" into the data brcs bit7 ;[9] When after shift C is set, next bit is bit7 nop ;[10] rjmp bitloop ;[11] ;---------------------------------------------------------------------------- ; End of receive loop. Now start handling EOP ;---------------------------------------------------------------------------- macro POP_STANDARD ; 14 cycles pop cnt pop x4 pop x3 pop x2 pop x1 pop shift pop bitcnt endm macro POP_RETI ; 7 cycles pop YH pop YL out SREG, YL pop YL endm #include "asmcommon.inc" ; USB spec says: ; idle = J ; J = (D+ = 0), (D- = 1) ; K = (D+ = 1), (D- = 0) ; Spec allows 7.5 bit times from EOP to SOP for replies ; 7.5 bit times is 100 cycles. This implementation arrives a bit later at se0 ; then specified in the include file but there is plenty of time bitstuffN: eor x1, x4 ;[8] ldi x2, 0 ;[9] nop2 ;[10] out USBOUT, x1 ;[12] <-- out rjmp didStuffN ;[0] bitstuff7: eor x1, x4 ;[6] ldi x2, 0 ;[7] Carry is zero due to brcc rol shift ;[8] compensate for ror shift at branch destination nop2 ;[9] rjmp didStuff7 ;[11] sendNakAndReti: ldi x3, USBPID_NAK ;[-18] rjmp sendX3AndReti ;[-17] sendAckAndReti: ldi cnt, USBPID_ACK ;[-17] sendCntAndReti: mov x3, cnt ;[-16] sendX3AndReti: ldi YL, 20 ;[-15] x3==r20 address is 20 ldi YH, 0 ;[-14] ldi cnt, 2 ;[-13] ; rjmp usbSendAndReti fallthrough ;usbSend: ;pointer to data in 'Y' ;number of bytes in 'cnt' -- including sync byte [range 2 ... 12] ;uses: x1...x4, btcnt, shift, cnt, Y ;Numbers in brackets are time since first bit of sync pattern is sent ;We don't match the transfer rate exactly (don't insert leap cycles every third ;byte) because the spec demands only 1.5% precision anyway. usbSendAndReti: ; 12 cycles until SOP in x2, USBDDR ;[-12] ori x2, USBMASK ;[-11] sbi USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups) in x1, USBOUT ;[-8] port mirror for tx loop out USBDDR, x2 ;[-7] <- acquire bus ; need not init x2 (bitstuff history) because sync starts with 0 ldi x4, USBMASK ;[-6] exor mask ldi shift, 0x80 ;[-5] sync byte is first byte sent txByteLoop: ldi bitcnt, 0x49 ;[-4] [10] binary 01001001 txBitLoop: sbrs shift, 0 ;[-3] [10] [11] eor x1, x4 ;[-2] [11] [12] out USBOUT, x1 ;[-1] [12] [13] <-- out N ror shift ;[0] [13] [14] ror x2 ;[1] didStuffN: nop2 ;[2] nop ;[4] cpi x2, 0xfc ;[5] brcc bitstuffN ;[6] lsr bitcnt ;[7] brcc txBitLoop ;[8] brne txBitLoop ;[9] sbrs shift, 0 ;[10] eor x1, x4 ;[11] didStuff7: out USBOUT, x1 ;[-1] [13] <-- out 7 ror shift ;[0] [14] ror x2 ;[1] nop ;[2] cpi x2, 0xfc ;[3] brcc bitstuff7 ;[4] ld shift, y+ ;[5] dec cnt ;[7] brne txByteLoop ;[8] ;make SE0: cbr x1, USBMASK ;[9] prepare SE0 [spec says EOP may be 25 to 30 cycles] lds x2, usbNewDeviceAddr;[10] lsl x2 ;[12] we compare with left shifted address out USBOUT, x1 ;[13] <-- out SE0 -- from now 2 bits = 22 cycles until bus idle subi YL, 20 + 2 ;[0] Only assign address on data packets, not ACK/NAK in x3 sbci YH, 0 ;[1] ;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm: ;set address only after data packet was sent, not after handshake breq skipAddrAssign ;[2] sts usbDeviceAddr, x2; if not skipped: SE0 is one cycle longer skipAddrAssign: ;end of usbDeviceAddress transfer ldi x2, 1<<USB_INTR_PENDING_BIT;[4] int0 occurred during TX -- clear pending flag USB_STORE_PENDING(x2) ;[5] ori x1, USBIDLE ;[6] in x2, USBDDR ;[7] cbr x2, USBMASK ;[8] set both pins to input mov x3, x1 ;[9] cbr x3, USBMASK ;[10] configure no pullup on both pins ldi x4, 5 ;[11] se0Delay: dec x4 ;[12] [15] [18] [21] [24] brne se0Delay ;[13] [16] [19] [22] [25] out USBOUT, x1 ;[26] <-- out J (idle) -- end of SE0 (EOP signal) out USBDDR, x2 ;[27] <-- release bus now out USBOUT, x3 ;[28] <-- ensure no pull-up resistors are active rjmp doReturn
{ "pile_set_name": "Github" }
""" MTGJSON simple utilities """ import collections import hashlib import inspect import itertools import json import logging import os import pathlib import time from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union import gevent.pool import requests import requests.adapters import requests_cache import urllib3 from . import consts from .consts import BAD_FILE_NAMES, CACHE_PATH, LOG_PATH, USE_CACHE LOGGER = logging.getLogger(__name__) def init_logger() -> None: """ Initialize the main system logger """ LOG_PATH.mkdir(parents=True, exist_ok=True) start_time = time.strftime("%Y-%m-%d_%H.%M.%S") logging.basicConfig( level=logging.DEBUG if os.environ.get("MTGJSON5_DEBUG", "").lower() in ["true", "1"] else logging.INFO, format="[%(levelname)s] %(asctime)s: %(message)s", handlers=[ logging.StreamHandler(), logging.FileHandler(str(LOG_PATH.joinpath(f"mtgjson_{start_time}.log"))), ], ) logging.getLogger("urllib3").setLevel(logging.ERROR) def url_keygen(unique_seed: Union[int, str], with_leading: bool = True) -> str: """ Generates a key that MTGJSON will use for redirection :param unique_seed: Link seed :param with_leading: Should URL be included :return: URL Key """ return_value = "https://mtgjson.com/links/" if with_leading else "" return f"{return_value}{hashlib.sha256(str(unique_seed).encode()).hexdigest()[:16]}" def to_camel_case(snake_str: str) -> str: """ Convert "snake_case" => "snakeCase" :param snake_str: Snake String :return: Camel String """ components = snake_str.split("_") return components[0] + "".join(x.title() for x in components[1:]) def parse_magic_rules_subset( magic_rules: str, start_header: str = "", end_header: str = "" ) -> str: """ Split up the magic rules to get a smaller working subset for parsing :param magic_rules: Magic rules to split up :param start_header: Start of content :param end_header: End of content :return: Smaller set of content """ # Keyword actions are found in section XXX if start_header and end_header: magic_rules = magic_rules.split(start_header)[2].split(end_header)[0] # Windows line endings... yuck valid_line_segments = "\n".join(magic_rules.splitlines()) return valid_line_segments def retryable_session( retries: int = 8, ) -> Union[requests.Session, requests_cache.CachedSession]: """ Session with requests to allow for re-attempts at downloading missing data :param retries: How many retries to attempt :return: Session that does downloading """ if USE_CACHE: stack = inspect.stack() calling_class = stack[1][0].f_locals["self"].__class__.__name__ session = requests_cache.CachedSession(str(CACHE_PATH.joinpath(calling_class))) else: session = requests.Session() retry = urllib3.util.retry.Retry( total=retries, read=retries, connect=retries, backoff_factor=0.3, status_forcelist=(500, 502, 504), ) adapter = requests.adapters.HTTPAdapter(max_retries=retry) session.mount("http://", adapter) session.mount("https://", adapter) session.headers.update({"User-Agent": "Mozilla/5.0 Firefox/75.0 www.mtgjson.com"}) return session def parallel_call( function: Callable, args: Any, repeatable_args: Union[Tuple[Any, ...], List[Any]] = None, fold_list: bool = False, fold_dict: bool = False, force_starmap: bool = False, pool_size: int = 32, ) -> Any: """ Execute a function in parallel :param function: Function to execute :param args: Args to pass to the function :param repeatable_args: Repeatable args to pass with the original args :param fold_list: Compress the results into a 1D list :param fold_dict: Compress the results into a single dictionary :param force_starmap: Force system to use Starmap over normal selection process :param pool_size: How large the gevent pool should be :return: Results from execution, with modifications if desired """ pool = gevent.pool.Pool(pool_size) if repeatable_args: extra_args_rep = [itertools.repeat(arg) for arg in repeatable_args] results = pool.map(lambda g_args: function(*g_args), zip(args, *extra_args_rep)) elif force_starmap: results = pool.map(lambda g_args: function(*g_args), args) else: results = pool.map(function, args) if fold_list: return list(itertools.chain.from_iterable(results)) if fold_dict: return dict(collections.ChainMap(*results)) return results def sort_internal_lists(data: Any) -> Any: """ Sort all lists & sets within a given data structure :param data: Data structure to internally sort :return Data structure with sorted lists """ if isinstance(data, dict): for key, value in data.items(): data[key] = sort_internal_lists(value) elif isinstance(data, (set, list)): return sorted(list(data)) return data def fix_windows_set_name(set_name: str) -> str: """ In the Windows OS, there are certain file names that are not allowed. In case we have a set with such a name, we will add a _ to the end to allow its existence on Windows. :param set_name: Set name :return: Set name with a _ if necessary """ if set_name in BAD_FILE_NAMES: return set_name + "_" return set_name def get_file_hash(file_to_hash: pathlib.Path, block_size: int = 65536) -> str: """ Given a file, generate a hash of the contents :param file_to_hash: File to generate the hash of :param block_size: How big a chunk to read in at a time :return file hash """ if not file_to_hash.is_file(): LOGGER.warning(f"Unable to find {file_to_hash}, no hashes generated") return "" # Hash can be adjusted in consts.py file hash_operation = consts.HASH_TO_GENERATE.copy() with file_to_hash.open("rb") as file: while True: data = file.read(block_size) if not data: break hash_operation.update(data) return hash_operation.hexdigest() def get_str_or_none(value: Any) -> Optional[str]: """ Given a value, get its string representation or None object :param value: Input value :return String value of input or None """ if not value: return None return str(value) def send_push_notification(message: str) -> bool: """ Send a push notification to project maintainers. These alerts can be disabled by removing the Pushover category from the properties file. :param message: Message to send :return If the message send successfully to everyone """ if "Pushover" not in consts.CONFIG.sections(): LOGGER.warning("Pushover section not established. Skipping alerts") return False pushover_app_token = consts.CONFIG.get("Pushover", "app_token") pushover_app_users = list( filter(None, consts.CONFIG.get("Pushover", "user_tokens").split(",")) ) if not (pushover_app_token and pushover_app_token): LOGGER.warning("Pushover keys values missing. Skipping alerts") return False all_succeeded = True for user in pushover_app_users: response = requests.post( "https://api.pushover.net/1/messages.json", data={ "token": pushover_app_token, "user": user, "title": f"MTGJSON {consts.MTGJSON_VERSION}", "message": message, }, ) if not response.ok: LOGGER.warning(f"Error sending Pushover notification: {response.text}") all_succeeded = False return all_succeeded def deep_merge_dictionaries( first_dict: Dict[str, Any], *other_dicts: Dict[str, Any] ) -> Dict[str, Any]: """ Merge N dictionaries together, recursively :param first_dict: Left hand dictionary :param other_dicts: Right hand dictionaries :return: Combined Dictionaries """ result = first_dict.copy() for dictionary in other_dicts: for key, new in dictionary.items(): old = result.get(key) if isinstance(old, dict) and isinstance(new, dict): new = deep_merge_dictionaries(old, new) result[key] = new return result def get_all_cards_and_tokens_from_content( all_printings_content: Dict[str, Any] ) -> List[Dict[str, Any]]: """ Convert the content of AllPrintings into a list of card objects :param all_printings_content: Content of AllPrintings :return List of cards """ cards_and_tokens_with_set_code = [] for value in all_printings_content.values(): for card in value.get("cards", []) + value.get("tokens", []): cards_and_tokens_with_set_code.append(card) return cards_and_tokens_with_set_code def get_all_cards_and_tokens( all_printings_path: pathlib.Path, ) -> Iterator[Dict[str, Any]]: """ Grab every card and token object from an AllPrintings file for future iteration :param all_printings_path: AllPrintings.json to refer when building :return Iterator for all card and token objects """ all_printings_path = all_printings_path.expanduser() if not all_printings_path.exists(): LOGGER.error(f"File {all_printings_path} does not exist, cannot iterate") return with all_printings_path.open(encoding="utf-8") as f: file_contents = json.load(f).get("data", {}) for card in get_all_cards_and_tokens_from_content(file_contents): yield card def generate_card_mapping( all_printings_path: pathlib.Path, left_side_components: Tuple[str, ...], right_side_components: Tuple[str, ...], ) -> Dict[str, Any]: """ Construct a mapping from one component of the card to another. The components are nested ops to get to the final value. :param all_printings_path: AllPrintings file to load card data from :param left_side_components: Inner left hand side components ([foo, bar] => card[foo][bar]) :param right_side_components: Inner right hand side components ([foo, bar] => card[foo][bar]) :return Dict mapping from left components => right components """ dump_map: Dict[str, Any] = {} for card in get_all_cards_and_tokens(all_printings_path): try: key = card for inside_component in left_side_components: key = key[inside_component] value = card for inside_component in right_side_components: value = value[inside_component] dump_map[str(key)] = value except KeyError: pass return dump_map
{ "pile_set_name": "Github" }
/* ****** * * HX-2015-04: * for JavaScript code * translated from ATS * ****** */ /* ****** * beg of [baconjs_cats.js] ****** */ /* ****** ****** */ // function ats2js_bacon_Bacon_more() { return Bacon.more; } function ats2js_bacon_Bacon_noMore() { return Bacon.noMore; } // /* ****** ****** */ // function ats2js_bacon_Bacon_once(x) { return Bacon.once(x); } function ats2js_bacon_Bacon_never() { return Bacon.never(); } // function ats2js_bacon_Bacon_later(delay, x) { return Bacon.later(delay, x); } // function ats2js_bacon_Bacon_interval (int, x) { return Bacon.interval(int, x); } // function ats2js_bacon_Bacon_repeatedly (int, xs) { return Bacon.repeatedly(int, xs); } // function ats2js_bacon_Bacon_sequentially (int, xs) { return Bacon.sequentially(int, xs); } // function ats2js_bacon_Bacon_repeat(fopr) { return Bacon.repeat(function(i){return ats2jspre_cloref1_app(fopr, i);}); } // /* ****** ****** */ // function ats2js_bacon_EStream_map(xs, f) { return ats2js_bacon_Observable_map(xs, f); } function ats2js_bacon_Property_map(xs, f) { return ats2js_bacon_Observable_map(xs, f); } function ats2js_bacon_Observable_map(xs, f) { return xs.map( function(x){return ats2jspre_cloref1_app(f, x);} ); // end of [return] } // /* ****** ****** */ // function ats2js_bacon_EStream_filter(xs, f) { return ats2js_bacon_Observable_filter(xs, f); } function ats2js_bacon_Property_filter(xs, f) { return ats2js_bacon_Observable_filter(xs, f); } function ats2js_bacon_Observable_filter(xs, f) { return xs.filter( function(x){return ats2jspre_cloref1_app(f, x);} ); // end of [return] } // /* ****** ****** */ // function ats2js_bacon_EStream_map_property(xs, ys) { return xs.map(ys); } function ats2js_bacon_EStream_filter_property(xs, bs) { return xs.filter(bs); } // /* ****** ****** */ function ats2js_bacon_EStream_scan(xs, ini, f) { return xs.scan( ini, function(y, x){return ats2jspre_cloref2_app(f, y, x);} ); // end of [return] } /* ****** ****** */ // function ats2js_bacon_EStream_merge2 ( xs1, xs2 ) { return Bacon.mergeAll(xs1, xs2); } function ats2js_bacon_EStream_merge3 ( xs1, xs2, xs3 ) { return Bacon.mergeAll(xs1, xs2, xs3); } function ats2js_bacon_EStream_merge4 ( xs1, xs2, xs3, xs4 ) { return Bacon.mergeAll(xs1, xs2, xs3, xs4); } function ats2js_bacon_EStream_merge5 ( xs1, xs2, xs3, xs4, xs5 ) { return Bacon.mergeAll(xs1, xs2, xs3, xs4, xs5); } function ats2js_bacon_EStream_merge6 ( xs1, xs2, xs3, xs4, xs5, xs6 ) { return Bacon.mergeAll(xs1, xs2, xs3, xs4, xs5, xs6); } // /* ****** ****** */ // function ats2js_bacon_EStream_flatMap(xs, f) { return ats2js_bacon_Observable_flatMap(xs, f); } function ats2js_bacon_Property_flatMap(xs, f) { return ats2js_bacon_Observable_flatMap(xs, f); } function ats2js_bacon_Observable_flatMap(xs, f) { return xs.flatMap( function(x){return ats2jspre_cloref1_app(f, x);} ); // end of [return] } // /* ****** ****** */ function ats2js_bacon_Bacon_combineWith2(xs1, xs2, f) { var theCombined = Bacon.combineWith( function(x1,x2){ return ats2jspre_cloref2_app(f, x1, x2); }, xs1, xs2 ) // end of [var] return theCombined; } function ats2js_bacon_Bacon_combineWith3(xs1, xs2, xs3, f) { var theCombined = Bacon.combineWith( function(x1,x2,x3){ return ats2jspre_cloref3_app(f, x1, x2, x3); }, xs1, xs2, xs3 ) // end of [var] return theCombined; } /* ****** ****** */ // function ats2js_bacon_EStream_toProperty(xs) { return xs.toProperty(); } function ats2js_bacon_EStream_toProperty_init(xs, x0) { return xs.toProperty(x0); } // /* ****** ****** */ // function ats2js_bacon_Property_changes(xs) { return xs.changes(); } function ats2js_bacon_Property_toEventStream(xs) { return xs.toEventStream(); } // /* ****** ****** */ function ats2js_bacon_EStream_onValue(xs, f) { return ats2js_bacon_Observable_onValue(xs, f); } function ats2js_bacon_Property_onValue(xs, f) { return ats2js_bacon_Observable_onValue(xs, f); } function ats2js_bacon_Observable_onValue(xs, f) { return xs.onValue(function(x){return ats2jspre_cloref1_app(f, x);}); } /* ****** ****** */ function ats2js_bacon_EStream_subscribe(xs, f) { return ats2js_bacon_Observable_subscribe(xs, f); } function ats2js_bacon_Property_subscribe(xs, f) { return ats2js_bacon_Observable_subscribe(xs, f); } function ats2js_bacon_Observable_subscribe(xs, f) { return xs.subscribe(function(x){return ats2jspre_cloref1_app(f, x);}); } /* ****** ****** */ // function ats2js_bacon_Property_startWith (xs, x0) { return xs.startWith(x0); } // /* ****** ****** */ // function ats2js_bacon_EStream_doAction(xs, f0) { return ats2js_bacon_Observable_doAction(xs, f0); } function ats2js_bacon_Property_doAction(xs, f0) { return ats2js_bacon_Observable_doAction(xs, f0); } function ats2js_bacon_Observable_doAction(xs, f0) { return xs.doAction( function(x){ats2jspre_cloref1_app(f0, x); return;} ); // end of [return] } // /* ****** ****** */ // function ats2js_bacon_Property_sampledBy_estream (xs, ys) { return xs.sampledBy(ys); } function ats2js_bacon_Property_sampledBy_estream_cfun(xs, ys, f) { return xs.sampledBy( ys,function(x,y){return ats2jspre_cloref2_app(f,x,y);} ); // end of [return] } // /* ****** ****** */ // function ats2js_bacon_Property_sampledBy_property (xs, ys) { return xs.sampledBy(ys); } function ats2js_bacon_Property_sampledBy_property_cfun(xs, ys, f0) { return xs.sampledBy( ys,function(x,y){return ats2jspre_cloref2_app(f0,x,y);} ); // end of [return] } // /* ****** ****** */ // function ats2js_bacon_EStream_zip_estream_cfun(xs, ys, f0) { return xs.zip( ys,function(x,y){return ats2jspre_cloref2_app(f0,x,y);} ); /* end of [return] */ } // /* ****** ****** */ function ats2js_bacon_Bacon_new_bus() { return new Bacon.Bus(); } /* ****** ****** */ // function ats2js_bacon_EStream_bus_push(bus, x0) { return bus.push(x0); } function ats2js_bacon_EStream_bus_plug(bus, xs) { return bus.plug(xs); } // /* ****** ****** */ /* end of [baconjs_cats.js] */ /* ** ** The JavaScript code is generated by atscc2js ** The starting compilation time is: 2017-2-14: 9h:19m ** */ function _ats2js_bacon_patsfun_1__closurerize(env0) { return [function(cenv, arg0) { return _ats2js_bacon_patsfun_1(cenv[1], arg0); }, env0]; } function _ats2js_bacon_patsfun_3__closurerize(env0) { return [function(cenv, arg0) { return _ats2js_bacon_patsfun_3(cenv[1], arg0); }, env0]; } function _ats2js_bacon_patsfun_5__closurerize(env0) { return [function(cenv, arg0) { return _ats2js_bacon_patsfun_5(cenv[1], arg0); }, env0]; } function _ats2js_bacon_patsfun_7__closurerize(env0) { return [function(cenv, arg0, arg1) { return _ats2js_bacon_patsfun_7(cenv[1], arg0, arg1); }, env0]; } function _ats2js_bacon_patsfun_9__closurerize(env0) { return [function(cenv, arg0) { return _ats2js_bacon_patsfun_9(cenv[1], arg0); }, env0]; } function _ats2js_bacon_patsfun_11__closurerize(env0) { return [function(cenv, arg0) { return _ats2js_bacon_patsfun_11(cenv[1], arg0); }, env0]; } function _ats2js_bacon_patsfun_13__closurerize(env0) { return [function(cenv, arg0) { return _ats2js_bacon_patsfun_13(cenv[1], arg0); }, env0]; } function _ats2js_bacon_patsfun_15__closurerize(env0) { return [function(cenv, arg0) { return _ats2js_bacon_patsfun_15(cenv[1], arg0); }, env0]; } function _ats2js_bacon_patsfun_17__closurerize(env0) { return [function(cenv, arg0) { return _ats2js_bacon_patsfun_17(cenv[1], arg0); }, env0]; } function _ats2js_bacon_patsfun_19__closurerize(env0) { return [function(cenv, arg0) { return _ats2js_bacon_patsfun_19(cenv[1], arg0); }, env0]; } function _ats2js_bacon_patsfun_21__closurerize(env0) { return [function(cenv, arg0) { return _ats2js_bacon_patsfun_21(cenv[1], arg0); }, env0]; } function _ats2js_bacon_patsfun_23__closurerize(env0) { return [function(cenv, arg0) { return _ats2js_bacon_patsfun_23(cenv[1], arg0); }, env0]; } function ats2js_bacon_EStream_map_method(arg0, arg1) { // // knd = 0 var tmpret0 var tmplab, tmplab_js // // __patsflab_EStream_map_method tmpret0 = _ats2js_bacon_patsfun_1__closurerize(arg0); return tmpret0; } // end-of-function function _ats2js_bacon_patsfun_1(env0, arg0) { // // knd = 0 var tmpret1 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_patsfun_1 tmpret1 = ats2js_bacon_EStream_map(env0, arg0); return tmpret1; } // end-of-function function ats2js_bacon_Property_map_method(arg0, arg1) { // // knd = 0 var tmpret2 var tmplab, tmplab_js // // __patsflab_Property_map_method tmpret2 = _ats2js_bacon_patsfun_3__closurerize(arg0); return tmpret2; } // end-of-function function _ats2js_bacon_patsfun_3(env0, arg0) { // // knd = 0 var tmpret3 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_patsfun_3 tmpret3 = ats2js_bacon_Property_map(env0, arg0); return tmpret3; } // end-of-function function ats2js_bacon_EStream_filter_method(arg0) { // // knd = 0 var tmpret4 var tmplab, tmplab_js // // __patsflab_EStream_filter_method tmpret4 = _ats2js_bacon_patsfun_5__closurerize(arg0); return tmpret4; } // end-of-function function _ats2js_bacon_patsfun_5(env0, arg0) { // // knd = 0 var tmpret5 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_patsfun_5 tmpret5 = ats2js_bacon_EStream_filter(env0, arg0); return tmpret5; } // end-of-function function ats2js_bacon_EStream_scan_method(arg0, arg1) { // // knd = 0 var tmpret6 var tmplab, tmplab_js // // __patsflab_EStream_scan_method tmpret6 = _ats2js_bacon_patsfun_7__closurerize(arg0); return tmpret6; } // end-of-function function _ats2js_bacon_patsfun_7(env0, arg0, arg1) { // // knd = 0 var tmpret7 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_patsfun_7 tmpret7 = ats2js_bacon_EStream_scan(env0, arg0, arg1); return tmpret7; } // end-of-function function ats2js_bacon_EStream_flatMap_method(arg0, arg1) { // // knd = 0 var tmpret8 var tmplab, tmplab_js // // __patsflab_EStream_flatMap_method tmpret8 = _ats2js_bacon_patsfun_9__closurerize(arg0); return tmpret8; } // end-of-function function _ats2js_bacon_patsfun_9(env0, arg0) { // // knd = 0 var tmpret9 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_patsfun_9 tmpret9 = ats2js_bacon_EStream_flatMap(env0, arg0); return tmpret9; } // end-of-function function ats2js_bacon_Property_flatMap_method(arg0, arg1) { // // knd = 0 var tmpret10 var tmplab, tmplab_js // // __patsflab_Property_flatMap_method tmpret10 = _ats2js_bacon_patsfun_11__closurerize(arg0); return tmpret10; } // end-of-function function _ats2js_bacon_patsfun_11(env0, arg0) { // // knd = 0 var tmpret11 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_patsfun_11 tmpret11 = ats2js_bacon_Property_flatMap(env0, arg0); return tmpret11; } // end-of-function function ats2js_bacon_EStream_onValue_method(arg0) { // // knd = 0 var tmpret12 var tmplab, tmplab_js // // __patsflab_EStream_onValue_method tmpret12 = _ats2js_bacon_patsfun_13__closurerize(arg0); return tmpret12; } // end-of-function function _ats2js_bacon_patsfun_13(env0, arg0) { // // knd = 0 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_patsfun_13 ats2js_bacon_EStream_onValue(env0, arg0); return/*_void*/; } // end-of-function function ats2js_bacon_Property_onValue_method(arg0) { // // knd = 0 var tmpret14 var tmplab, tmplab_js // // __patsflab_Property_onValue_method tmpret14 = _ats2js_bacon_patsfun_15__closurerize(arg0); return tmpret14; } // end-of-function function _ats2js_bacon_patsfun_15(env0, arg0) { // // knd = 0 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_patsfun_15 ats2js_bacon_Property_onValue(env0, arg0); return/*_void*/; } // end-of-function function ats2js_bacon_EStream_subscribe_method(arg0) { // // knd = 0 var tmpret16 var tmplab, tmplab_js // // __patsflab_EStream_subscribe_method tmpret16 = _ats2js_bacon_patsfun_17__closurerize(arg0); return tmpret16; } // end-of-function function _ats2js_bacon_patsfun_17(env0, arg0) { // // knd = 0 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_patsfun_17 ats2js_bacon_EStream_subscribe(env0, arg0); return/*_void*/; } // end-of-function function ats2js_bacon_Property_subscribe_method(arg0) { // // knd = 0 var tmpret18 var tmplab, tmplab_js // // __patsflab_Property_subscribe_method tmpret18 = _ats2js_bacon_patsfun_19__closurerize(arg0); return tmpret18; } // end-of-function function _ats2js_bacon_patsfun_19(env0, arg0) { // // knd = 0 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_patsfun_19 ats2js_bacon_Property_subscribe(env0, arg0); return/*_void*/; } // end-of-function function ats2js_bacon_EStream_doAction_method(arg0) { // // knd = 0 var tmpret20 var tmplab, tmplab_js // // __patsflab_EStream_doAction_method tmpret20 = _ats2js_bacon_patsfun_21__closurerize(arg0); return tmpret20; } // end-of-function function _ats2js_bacon_patsfun_21(env0, arg0) { // // knd = 0 var tmpret21 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_patsfun_21 tmpret21 = ats2js_bacon_EStream_doAction(env0, arg0); return tmpret21; } // end-of-function function ats2js_bacon_Property_doAction_method(arg0) { // // knd = 0 var tmpret22 var tmplab, tmplab_js // // __patsflab_Property_doAction_method tmpret22 = _ats2js_bacon_patsfun_23__closurerize(arg0); return tmpret22; } // end-of-function function _ats2js_bacon_patsfun_23(env0, arg0) { // // knd = 0 var tmpret23 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_patsfun_23 tmpret23 = ats2js_bacon_Property_doAction(env0, arg0); return tmpret23; } // end-of-function /* ****** ****** */ /* end-of-compilation-unit */ /* ** ** The JavaScript code is generated by atscc2js ** The starting compilation time is: 2017-2-14: 9h:19m ** */ function _ats2js_bacon_ext_patsfun_1__closurerize(env0, env1) { return [function(cenv, arg0, arg1) { return _ats2js_bacon_ext_patsfun_1(cenv[1], cenv[2], arg0, arg1); }, env0, env1]; } function _ats2js_bacon_ext_patsfun_4__closurerize(env0) { return [function(cenv, arg0) { return _ats2js_bacon_ext_patsfun_4(cenv[1], arg0); }, env0]; } function _ats2js_bacon_ext_patsfun_6__closurerize(env0, env1) { return [function(cenv, arg0) { return _ats2js_bacon_ext_patsfun_6(cenv[1], cenv[2], arg0); }, env0, env1]; } function _ats2js_bacon_ext_patsfun_8__closurerize() { return [function(cenv, arg0, arg1) { return _ats2js_bacon_ext_patsfun_8(arg0, arg1); }]; } function _ats2js_bacon_ext_patsfun_9__closurerize(env0) { return [function(cenv, arg0) { return _ats2js_bacon_ext_patsfun_9(cenv[1], arg0); }, env0]; } function _ats2js_bacon_ext_patsfun_10__closurerize() { return [function(cenv, arg0, arg1) { return _ats2js_bacon_ext_patsfun_10(arg0, arg1); }]; } function _ats2js_bacon_ext_patsfun_11__closurerize() { return [function(cenv, arg0) { return _ats2js_bacon_ext_patsfun_11(arg0); }]; } function _ats2js_bacon_ext_patsfun_12__closurerize() { return [function(cenv, arg0) { return _ats2js_bacon_ext_patsfun_12(arg0); }]; } function ats2js_bacon_ext_EStream_scan_stream_opt(arg0, arg1, arg2, arg3) { // // knd = 0 var tmpret0 var tmp1 var tmp10 var tmplab, tmplab_js // // __patsflab_EStream_scan_stream_opt tmp1 = ats2jspre_ref(arg2); tmp10 = _ats2js_bacon_ext_patsfun_1__closurerize(arg3, tmp1); tmpret0 = ats2js_bacon_EStream_scan(arg0, arg1, tmp10); return tmpret0; } // end-of-function function _ats2js_bacon_ext_patsfun_1(env0, env1, arg0, arg1) { // // knd = 0 var tmpret2 var tmp3 var tmp4 var tmp5 var tmp6 var tmp7 var tmp8 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_ext_patsfun_1 tmp3 = ats2jspre_ref_get_elt(env1); tmp4 = ATSPMVlazyval_eval(tmp3); // ATScaseofseq_beg tmplab_js = 1; while(true) { tmplab = tmplab_js; tmplab_js = 0; switch(tmplab) { // ATSbranchseq_beg case 1: // __atstmplab0 if(ATSCKptriscons(tmp4)) { tmplab_js = 4; break; } case 2: // __atstmplab1 tmpret2 = arg0; break; // ATSbranchseq_end // ATSbranchseq_beg case 3: // __atstmplab2 case 4: // __atstmplab3 tmp5 = tmp4[0]; tmp6 = tmp4[1]; tmp7 = env0[0](env0, arg0, arg1, tmp5); // ATScaseofseq_beg tmplab_js = 1; while(true) { tmplab = tmplab_js; tmplab_js = 0; switch(tmplab) { // ATSbranchseq_beg case 1: // __atstmplab4 if(ATSCKptriscons(tmp7)) { tmplab_js = 4; break; } case 2: // __atstmplab5 tmpret2 = arg0; break; // ATSbranchseq_end // ATSbranchseq_beg case 3: // __atstmplab6 case 4: // __atstmplab7 tmp8 = tmp7[0]; // ATSINSfreecon(tmp7); ats2jspre_ref_set_elt(env1, tmp6); tmpret2 = tmp8; break; // ATSbranchseq_end } // end-of-switch if (tmplab_js === 0) break; } // endwhile // ATScaseofseq_end break; // ATSbranchseq_end } // end-of-switch if (tmplab_js === 0) break; } // endwhile // ATScaseofseq_end return tmpret2; } // end-of-function function ats2js_bacon_ext_EValue_get_elt(arg0) { // // knd = 0 var tmpret11 var tmplab, tmplab_js // // __patsflab_EValue_get_elt tmpret11 = ats2jspre_ref_get_elt(arg0); return tmpret11; } // end-of-function function ats2js_bacon_ext_EValue_make_property(arg0) { // // knd = 0 var tmpret12 var tmp13 var tmplab, tmplab_js // // __patsflab_EValue_make_property tmp13 = ats2jspre_ref(0); ats2js_bacon_Property_onValue(arg0, _ats2js_bacon_ext_patsfun_4__closurerize(tmp13)); tmpret12 = tmp13; return tmpret12; } // end-of-function function _ats2js_bacon_ext_patsfun_4(env0, arg0) { // // knd = 0 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_ext_patsfun_4 ats2jspre_ref_set_elt(env0, arg0); return/*_void*/; } // end-of-function function ats2js_bacon_ext_EValue_make_estream_scan(arg0, arg1, arg2) { // // knd = 0 var tmpret16 var tmp17 var tmplab, tmplab_js // // __patsflab_EValue_make_estream_scan tmp17 = ats2jspre_ref(arg0); ats2js_bacon_EStream_onValue(arg1, _ats2js_bacon_ext_patsfun_6__closurerize(arg2, tmp17)); tmpret16 = tmp17; return tmpret16; } // end-of-function function _ats2js_bacon_ext_patsfun_6(env0, env1, arg0) { // // knd = 0 var tmp20 var tmp21 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_ext_patsfun_6 tmp21 = ats2jspre_ref_get_elt(env1); tmp20 = env0[0](env0, tmp21, arg0); ats2jspre_ref_set_elt(env1, tmp20); return/*_void*/; } // end-of-function function ats2js_bacon_ext_EStream_singpair_trans(arg0, arg1) { // // knd = 0 var tmpret22 var tmp23 var tmp24 var tmp28 var tmp29 var tmp33 var tmp34 var tmp35 var tmp36 var tmp37 var tmp38 var tmp39 var tmp40 var tmp58 var tmplab, tmplab_js // // __patsflab_EStream_singpair_trans tmp24 = [0, 0, 0]; tmp23 = ats2js_bacon_EStream_scan(arg0, tmp24, _ats2js_bacon_ext_patsfun_8__closurerize()); tmp28 = ats2js_bacon_Property_changes(tmp23); tmp29 = ats2js_bacon_EStream_flatMap(tmp28, _ats2js_bacon_ext_patsfun_9__closurerize(arg1)); tmp38 = ats2js_bacon_EStream_merge2(tmp28, tmp29); tmp40 = null; tmp39 = [0, tmp40]; tmp37 = ats2js_bacon_EStream_scan(tmp38, tmp39, _ats2js_bacon_ext_patsfun_10__closurerize()); tmp36 = ats2js_bacon_Property_changes(tmp37); tmp35 = ats2js_bacon_EStream_filter_method(tmp36); tmp34 = tmp35[0](tmp35, _ats2js_bacon_ext_patsfun_11__closurerize()); tmp58 = 0; tmp33 = ats2js_bacon_EStream_map_method(tmp34, tmp58); tmpret22 = tmp33[0](tmp33, _ats2js_bacon_ext_patsfun_12__closurerize()); return tmpret22; } // end-of-function function _ats2js_bacon_ext_patsfun_8(arg0, arg1) { // // knd = 0 var tmpret25 var tmp26 var tmp27 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_ext_patsfun_8 if(!ATSCKpat_con1(arg0, 0)) ATSINScaseof_fail("/home/hwxi/Research/ATS-Postiats/contrib/libatscc2js/ATS2-0.3.2/DATS/Bacon.js/baconjs_ext.dats: 3373(line=189, offs=11) -- 3392(line=189, offs=30)"); tmp26 = arg0[1]; tmp27 = ats2jspre_add_int0_int0(tmp26, 1); tmpret25 = [0, tmp27, arg1]; return tmpret25; } // end-of-function function _ats2js_bacon_ext_patsfun_9(env0, arg0) { // // knd = 0 var tmpret30 var tmp31 var tmp32 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_ext_patsfun_9 if(!ATSCKpat_con1(arg0, 0)) ATSINScaseof_fail("/home/hwxi/Research/ATS-Postiats/contrib/libatscc2js/ATS2-0.3.2/DATS/Bacon.js/baconjs_ext.dats: 3581(line=200, offs=11) -- 3598(line=200, offs=28)"); tmp31 = arg0[1]; tmp32 = [1, tmp31]; tmpret30 = ats2js_bacon_Bacon_later(env0, tmp32); return tmpret30; } // end-of-function function _ats2js_bacon_ext_patsfun_10(arg0, arg1) { // // knd = 0 var tmpret41 var tmp42 var tmp43 var tmp45 var tmp46 var tmp47 var tmp48 var tmp50 var tmp51 var tmp52 var tmp53 var tmp54 var tmp55 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_ext_patsfun_10 // ATScaseofseq_beg tmplab_js = 1; while(true) { tmplab = tmplab_js; tmplab_js = 0; switch(tmplab) { // ATSbranchseq_beg case 1: // __atstmplab8 if(!ATSCKpat_con1(arg0, 0)) { tmplab_js = 4; break; } case 2: // __atstmplab9 // ATScaseofseq_beg tmplab_js = 1; while(true) { tmplab = tmplab_js; tmplab_js = 0; switch(tmplab) { // ATSbranchseq_beg case 1: // __atstmplab12 if(!ATSCKpat_con1(arg1, 1)) { tmplab_js = 4; break; } case 2: // __atstmplab13 tmp47 = null; tmpret41 = [0, tmp47]; break; // ATSbranchseq_end // ATSbranchseq_beg case 3: // __atstmplab14 case 4: // __atstmplab15 tmp45 = arg1[1]; tmp46 = arg1[2]; tmpret41 = [1, tmp45, tmp46]; break; // ATSbranchseq_end } // end-of-switch if (tmplab_js === 0) break; } // endwhile // ATScaseofseq_end break; // ATSbranchseq_end // ATSbranchseq_beg case 3: // __atstmplab10 case 4: // __atstmplab11 tmp42 = arg0[1]; tmp43 = arg0[2]; // ATScaseofseq_beg tmplab_js = 1; while(true) { tmplab = tmplab_js; tmplab_js = 0; switch(tmplab) { // ATSbranchseq_beg case 1: // __atstmplab16 if(!ATSCKpat_con1(arg1, 1)) { tmplab_js = 4; break; } case 2: // __atstmplab17 tmp48 = arg1[1]; tmp51 = ats2jspre_lt_int0_int0(tmp48, tmp42); if(tmp51) { tmpret41 = arg0; } else { tmp53 = [0, tmp43]; tmp52 = [tmp53]; tmpret41 = [0, tmp52]; } // endif break; // ATSbranchseq_end // ATSbranchseq_beg case 3: // __atstmplab18 case 4: // __atstmplab19 tmp50 = arg1[2]; tmp55 = [1, tmp43, tmp50]; tmp54 = [tmp55]; tmpret41 = [0, tmp54]; break; // ATSbranchseq_end } // end-of-switch if (tmplab_js === 0) break; } // endwhile // ATScaseofseq_end break; // ATSbranchseq_end } // end-of-switch if (tmplab_js === 0) break; } // endwhile // ATScaseofseq_end return tmpret41; } // end-of-function function _ats2js_bacon_ext_patsfun_11(arg0) { // // knd = 0 var tmpret56 var tmp57 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_ext_patsfun_11 // ATScaseofseq_beg tmplab_js = 1; while(true) { tmplab = tmplab_js; tmplab_js = 0; switch(tmplab) { // ATSbranchseq_beg case 1: // __atstmplab20 if(!ATSCKpat_con1(arg0, 0)) { tmplab_js = 3; break; } case 2: // __atstmplab21 tmp57 = arg0[1]; tmpret56 = ats2jspre_option_is_some(tmp57); break; // ATSbranchseq_end // ATSbranchseq_beg case 3: // __atstmplab22 tmpret56 = false; break; // ATSbranchseq_end } // end-of-switch if (tmplab_js === 0) break; } // endwhile // ATScaseofseq_end return tmpret56; } // end-of-function function _ats2js_bacon_ext_patsfun_12(arg0) { // // knd = 0 var tmpret59 var tmp60 var tmp61 var tmplab, tmplab_js // // __patsflab__ats2js_bacon_ext_patsfun_12 // ATScaseofseq_beg tmplab_js = 1; while(true) { tmplab = tmplab_js; tmplab_js = 0; switch(tmplab) { // ATSbranchseq_beg case 1: // __atstmplab23 if(!ATSCKpat_con1(arg0, 0)) ATSINScaseof_fail("/home/hwxi/Research/ATS-Postiats/contrib/libatscc2js/ATS2-0.3.2/DATS/Bacon.js/baconjs_ext.dats: 4529(line=254, offs=5) -- 4586(line=254, offs=62)"); case 2: // __atstmplab24 tmp60 = arg0[1]; // ATScaseofseq_beg tmplab_js = 1; while(true) { tmplab = tmplab_js; tmplab_js = 0; switch(tmplab) { // ATSbranchseq_beg case 1: // __atstmplab25 if(ATSCKptrisnull(tmp60)) ATSINScaseof_fail("/home/hwxi/Research/ATS-Postiats/contrib/libatscc2js/ATS2-0.3.2/DATS/Bacon.js/baconjs_ext.dats: 4560(line=254, offs=36) -- 4585(line=254, offs=61)"); case 2: // __atstmplab26 tmp61 = tmp60[0]; tmpret59 = tmp61; break; // ATSbranchseq_end } // end-of-switch if (tmplab_js === 0) break; } // endwhile // ATScaseofseq_end break; // ATSbranchseq_end } // end-of-switch if (tmplab_js === 0) break; } // endwhile // ATScaseofseq_end return tmpret59; } // end-of-function /* ****** ****** */ /* end-of-compilation-unit */
{ "pile_set_name": "Github" }
--- src/3rdparty/chromium/printing/backend/print_backend_cups.cc.orig 2015-10-12 21:36:42.000000000 -0700 +++ src/3rdparty/chromium/printing/backend/print_backend_cups.cc 2016-10-25 05:50:33.000000000 -0700 @@ -6,6 +6,7 @@ #include "build/build_config.h" +#include <cups/ppd.h> #include <dlfcn.h> #include <errno.h> #include <pthread.h>
{ "pile_set_name": "Github" }
Command `run script.move`: Compiling 1 source file(s) Execution aborted with code 17 in transaction script
{ "pile_set_name": "Github" }
; Joomla! Project ; Copyright (C) 2005 - 2017 Open Source Matters. All rights reserved. ; License GNU General Public License version 2 or later; see LICENSE.txt, see LICENSE.php ; Note : All ini files need to be saved as UTF-8 MOD_VERSION="Joomla! Version Information" MOD_VERSION_LAYOUT_DEFAULT="Default" MOD_VERSION_XML_DESCRIPTION="This module displays the Joomla! version."
{ "pile_set_name": "Github" }
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. #include "../../precomp.hpp" #include "common.hpp" #include "internal.hpp" namespace cv { namespace dnn { namespace vkcom { #ifdef HAVE_VULKAN std::vector<uint32_t> compile(const std::string& name, shaderc_shader_kind kind, const std::string& data) { std::vector<uint32_t> result; #ifdef USE_SHADERC shaderc::Compiler compiler; shaderc::CompileOptions options; // Like -DMY_DEFINE=1 //options.AddMacroDefinition("MY_DEFINE", "1"); options.SetGenerateDebugInfo(); options.SetTargetEnvironment(shaderc_target_env_vulkan, shaderc_env_version_vulkan_1_1); shaderc::SpvCompilationResult module = compiler.CompileGlslToSpv( data.c_str(), data.size(), kind, name.c_str(), options); if (module.GetCompilationStatus() != shaderc_compilation_status_success) { std::cerr << module.GetErrorMessage(); } //std::vector<uint32_t> result(module.cbegin(), module.cend()); result.assign(module.cbegin(), module.cend()); return result; #else assert(0); return result; #endif } void bindTensor(VkDevice& device, Tensor& tensor, int binding, VkDescriptorSet descriptor_set) { VkDescriptorBufferInfo desc_buffer_info = {}; desc_buffer_info.buffer = tensor.getBuffer()->getVkBuffer(); desc_buffer_info.offset = 0; desc_buffer_info.range = tensor.size(); VkWriteDescriptorSet write_descriptor_set = {}; write_descriptor_set.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write_descriptor_set.dstSet = descriptor_set; write_descriptor_set.dstBinding = binding; write_descriptor_set.descriptorCount = 1; write_descriptor_set.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write_descriptor_set.pBufferInfo = &desc_buffer_info; vkUpdateDescriptorSets(device, 1, &write_descriptor_set, 0, NULL); } void computeConvOutputShapeAndPadding(const PaddingMode& padding_mode, int& padding_top, int& padding_left, const int& in_h, const int& in_w, const int& filter_h, const int& filter_w, const int& dilation_h, const int& dilation_w, const int& stride_h, const int& stride_w, int& out_h, int& out_w) { if (padding_mode == kPaddingModeValid) { padding_top = 0; padding_left = 0; out_h = ceil((in_h - (filter_h - 1) * dilation_h) / stride_h); out_w = ceil((in_w - (filter_w - 1) * dilation_w) / stride_w); } else if (padding_mode == kPaddingModeSame) { padding_top = ((filter_h - 1) * dilation_h + 1) / 2; padding_left = ((filter_w - 1) * dilation_w + 1) / 2; out_h = ceil(in_h / stride_h); out_w = ceil(in_w / stride_w); } else if (padding_mode == kPaddingModeCaffe) { const int filter_h_actual = dilation_h * (filter_h - 1) + 1; const int filter_w_actual = dilation_w * (filter_w - 1) + 1; out_h = (in_h + 2 * padding_top - filter_h_actual) / stride_h + 1; out_w = (in_w + 2 * padding_left - filter_w_actual) / stride_w + 1; } else { CV_Error(Error::StsError, format("Invalid padding mode:%d", padding_mode)); } } void computePoolOutputShape(const PaddingMode& padding_mode, const int& padding_top, const int& padding_left, const int& in_h, const int& in_w, const int& filter_h, const int& filter_w, const int& stride_h, const int& stride_w, int& out_h, int& out_w) { if (padding_mode == kPaddingModeValid) { assert(padding_top == 0); assert(padding_left == 0); out_h = ceil((in_h - (filter_h - 1)) / stride_h); out_w = ceil((in_h - (filter_w - 1)) / stride_w); } else if (padding_mode == kPaddingModeSame) { const int padding_top_ = filter_h / 2; const int padding_left_ = filter_w / 2; CV_Assert(padding_top == padding_top_); CV_Assert(padding_left == padding_left_); out_h = ceil(in_h / stride_h); out_w = ceil(in_h / stride_w); } else if (padding_mode == kPaddingModeCaffe) { int out_h_ = static_cast<int>(ceil(static_cast<float>( in_h + 2 * padding_top - filter_h) / stride_h)) + 1; int out_w_ = static_cast<int>(ceil(static_cast<float>( in_h + 2 * padding_left - filter_w) / stride_w)) + 1; if (padding_top || padding_left) { // If we have padding, ensure that the last pooling starts strictly // inside the image (instead of at the padding); otherwise clip the last. if ((out_h_ - 1) * stride_h >= in_h + padding_top) { --out_h_; } if ((out_w - 1) * stride_h >= in_h + padding_left) { --out_w; } assert((out_h_ - 1) * stride_h < in_h + padding_top); assert((out_w_ - 1) * stride_w < in_h + padding_left); } out_h = out_h_; out_w = out_w_; } else { CV_Error(Error::StsError, format("Invalid padding mode:%d", padding_mode)); } } #endif // HAVE_VULKAN }}} // namespace cv::dnn::vkcom
{ "pile_set_name": "Github" }
/* * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.iot.model; import java.util.HashMap; import java.util.Map; /** * Job Status */ public enum JobStatus { IN_PROGRESS("IN_PROGRESS"), CANCELED("CANCELED"), COMPLETED("COMPLETED"), DELETION_IN_PROGRESS("DELETION_IN_PROGRESS"); private String value; private JobStatus(String value) { this.value = value; } @Override public String toString() { return value; } private static final Map<String, JobStatus> enumMap; static { enumMap = new HashMap<String, JobStatus>(); enumMap.put("IN_PROGRESS", IN_PROGRESS); enumMap.put("CANCELED", CANCELED); enumMap.put("COMPLETED", COMPLETED); enumMap.put("DELETION_IN_PROGRESS", DELETION_IN_PROGRESS); } /** * Use this in place of valueOf. * * @param value real value * @return JobStatus corresponding to the value */ public static JobStatus fromValue(String value) { if (value == null || value.isEmpty()) { throw new IllegalArgumentException("Value cannot be null or empty!"); } else if (enumMap.containsKey(value)) { return enumMap.get(value); } else { throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } } }
{ "pile_set_name": "Github" }
<?php namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2; use un\unece\uncefact\data\specification\UnqualifiedDataTypesSchemaModule\_2; /** * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2 * @xmlType IdentifierType * @xmlName OrangeHazardPlacardIDType * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\OrangeHazardPlacardIDType */ class OrangeHazardPlacardIDType extends _2\IdentifierType { } // end class OrangeHazardPlacardIDType
{ "pile_set_name": "Github" }
name=Lovisa Coldeyes image=https://magiccards.info/scans/en/cs/90.jpg value=3.917 rarity=R type=Legendary,Creature subtype=Human cost={3}{R}{R} pt=3/3 ability=Each creature that's a Barbarian, a Warrior, or a Berserker gets +2/+2 and has haste. timing=main oracle=Each creature that's a Barbarian, a Warrior, or a Berserker gets +2/+2 and has haste.
{ "pile_set_name": "Github" }
#include <stdint.h> #include <ctype.h> #include <assert.h> #include "heatshrink_encoder.h" #include "heatshrink_decoder.h" #include "greatest.h" #if !HEATSHRINK_DYNAMIC_ALLOC #error Must set HEATSHRINK_DYNAMIC_ALLOC to 1 for dynamic allocation test suite. #endif SUITE(encoding); SUITE(decoding); SUITE(integration); #ifdef HEATSHRINK_HAS_THEFT SUITE(properties); #endif static void dump_buf(char *name, uint8_t *buf, uint16_t count) { for (int i=0; i<count; i++) { uint8_t c = (uint8_t)buf[i]; printf("%s %d: 0x%02x ('%c')\n", name, i, c, isprint(c) ? c : '.'); } } TEST encoder_alloc_should_reject_invalid_arguments(void) { ASSERT_EQ(NULL, heatshrink_encoder_alloc( HEATSHRINK_MIN_WINDOW_BITS - 1, 8)); ASSERT_EQ(NULL, heatshrink_encoder_alloc( HEATSHRINK_MAX_WINDOW_BITS + 1, 8)); ASSERT_EQ(NULL, heatshrink_encoder_alloc(8, HEATSHRINK_MIN_LOOKAHEAD_BITS - 1)); ASSERT_EQ(NULL, heatshrink_encoder_alloc(8, 9)); PASS(); } TEST encoder_sink_should_reject_nulls(void) { heatshrink_encoder *hse = heatshrink_encoder_alloc(8, 7); uint8_t input[] = {'f', 'o', 'o'}; size_t input_size = 0; ASSERT(hse); ASSERT_EQ(HSER_SINK_ERROR_NULL, heatshrink_encoder_sink(NULL, input, 3, &input_size)); ASSERT_EQ(HSER_SINK_ERROR_NULL, heatshrink_encoder_sink(hse, NULL, 3, &input_size)); ASSERT_EQ(HSER_SINK_ERROR_NULL, heatshrink_encoder_sink(hse, input, 3, NULL)); heatshrink_encoder_free(hse); PASS(); } TEST encoder_poll_should_reject_nulls(void) { heatshrink_encoder *hse = heatshrink_encoder_alloc(8, 7); uint8_t output[256]; size_t output_size = 0; ASSERT_EQ(HSER_POLL_ERROR_NULL, heatshrink_encoder_poll(NULL, output, 256, &output_size)); ASSERT_EQ(HSER_POLL_ERROR_NULL, heatshrink_encoder_poll(hse, NULL, 256, &output_size)); ASSERT_EQ(HSER_POLL_ERROR_NULL, heatshrink_encoder_poll(hse, output, 256, NULL)); heatshrink_encoder_free(hse); PASS(); } TEST encoder_finish_should_reject_nulls(void) { ASSERT_EQ(HSER_FINISH_ERROR_NULL, heatshrink_encoder_finish(NULL)); PASS(); } TEST encoder_sink_should_accept_input_when_it_will_fit(void) { heatshrink_encoder *hse = heatshrink_encoder_alloc(8, 7); ASSERT(hse); uint8_t input[256]; size_t bytes_copied = 0; memset(input, '*', 256); ASSERT_EQ(HSER_SINK_OK, heatshrink_encoder_sink(hse, input, 256, &bytes_copied)); ASSERT_EQ(256, bytes_copied); heatshrink_encoder_free(hse); PASS(); } TEST encoder_sink_should_accept_partial_input_when_some_will_fit(void) { heatshrink_encoder *hse = heatshrink_encoder_alloc(8, 7); ASSERT(hse); uint8_t input[512]; size_t bytes_copied = 0; memset(input, '*', 512); ASSERT_EQ(HSER_SINK_OK, heatshrink_encoder_sink(hse, input, 512, &bytes_copied)); ASSERT_EQ(256, bytes_copied); heatshrink_encoder_free(hse); PASS(); } TEST encoder_poll_should_indicate_when_no_input_is_provided(void) { heatshrink_encoder *hse = heatshrink_encoder_alloc(8, 7); uint8_t output[512]; size_t output_size = 0; HSE_poll_res res = heatshrink_encoder_poll(hse, output, 512, &output_size); ASSERT_EQ(HSER_POLL_EMPTY, res); heatshrink_encoder_free(hse); PASS(); } TEST encoder_should_emit_data_without_repetitions_as_literal_sequence(void) { heatshrink_encoder *hse = heatshrink_encoder_alloc(8, 7); ASSERT(hse); uint8_t input[5]; uint8_t output[1024]; size_t copied = 0; uint8_t expected[] = { 0x80, 0x40, 0x60, 0x50, 0x38, 0x20 }; for (int i=0; i<5; i++) { input[i] = i; } memset(output, 0, 1024); ASSERT_EQ(HSER_SINK_OK, heatshrink_encoder_sink(hse, input, 5, &copied)); ASSERT_EQ(5, copied); /* Should get no output yet, since encoder doesn't know input is complete. */ copied = 0; HSE_poll_res pres = heatshrink_encoder_poll(hse, output, 1024, &copied); ASSERT_EQ(HSER_POLL_EMPTY, pres); ASSERT_EQ(0, copied); /* Mark input stream as done, to force small input to be processed. */ HSE_finish_res fres = heatshrink_encoder_finish(hse); ASSERT_EQ(HSER_FINISH_MORE, fres); pres = heatshrink_encoder_poll(hse, output, 1024, &copied); ASSERT_EQ(HSER_POLL_EMPTY, pres); for (size_t i=0; i<sizeof(expected); i++) { ASSERT_EQ(expected[i], output[i]); } ASSERT_EQ(HSER_FINISH_DONE, heatshrink_encoder_finish(hse)); heatshrink_encoder_free(hse); PASS(); } TEST encoder_should_emit_series_of_same_byte_as_literal_then_backref(void) { heatshrink_encoder *hse = heatshrink_encoder_alloc(8, 7); ASSERT(hse); uint8_t input[5]; uint8_t output[1024]; size_t copied = 0; uint8_t expected[] = {0xb0, 0x80, 0x01, 0x80}; for (int i=0; i<5; i++) { input[i] = 'a'; } /* "aaaaa" */ memset(output, 0, 1024); ASSERT_EQ(HSER_SINK_OK, heatshrink_encoder_sink(hse, input, 5, &copied)); ASSERT_EQ(5, copied); /* Should get no output yet, since encoder doesn't know input is complete. */ copied = 0; HSE_poll_res pres = heatshrink_encoder_poll(hse, output, 1024, &copied); ASSERT_EQ(HSER_POLL_EMPTY, pres); ASSERT_EQ(0, copied); /* Mark input stream as done, to force small input to be processed. */ HSE_finish_res fres = heatshrink_encoder_finish(hse); ASSERT_EQ(HSER_FINISH_MORE, fres); pres = heatshrink_encoder_poll(hse, output, 1024, &copied); ASSERT_EQ(HSER_POLL_EMPTY, pres); ASSERT_EQ(4, copied); if (0) dump_buf("output", output, copied); for (size_t i=0; i<copied; i++) ASSERT_EQ(expected[i], output[i]); ASSERT_EQ(HSER_FINISH_DONE, heatshrink_encoder_finish(hse)); heatshrink_encoder_free(hse); PASS(); } TEST encoder_poll_should_detect_repeated_substring(void) { heatshrink_encoder *hse = heatshrink_encoder_alloc(8, 3); uint8_t input[] = {'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'}; uint8_t output[1024]; uint8_t expected[] = {0xb0, 0xd8, 0xac, 0x76, 0x40, 0x1b }; size_t copied = 0; memset(output, 0, 1024); HSE_sink_res sres = heatshrink_encoder_sink(hse, input, sizeof(input), &copied); ASSERT_EQ(HSER_SINK_OK, sres); ASSERT_EQ(sizeof(input), copied); HSE_finish_res fres = heatshrink_encoder_finish(hse); ASSERT_EQ(HSER_FINISH_MORE, fres); ASSERT_EQ(HSER_POLL_EMPTY, heatshrink_encoder_poll(hse, output, 1024, &copied)); fres = heatshrink_encoder_finish(hse); ASSERT_EQ(HSER_FINISH_DONE, fres); if (0) dump_buf("output", output, copied); ASSERT_EQ(sizeof(expected), copied); for (size_t i=0; i<sizeof(expected); i++) ASSERT_EQ(expected[i], output[i]); heatshrink_encoder_free(hse); PASS(); } TEST encoder_poll_should_detect_repeated_substring_and_preserve_trailing_literal(void) { heatshrink_encoder *hse = heatshrink_encoder_alloc(8, 3); uint8_t input[] = {'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'e'}; uint8_t output[1024]; uint8_t expected[] = {0xb0, 0xd8, 0xac, 0x76, 0x40, 0x1b, 0xb2, 0x80 }; size_t copied = 0; memset(output, 0, 1024); HSE_sink_res sres = heatshrink_encoder_sink(hse, input, sizeof(input), &copied); ASSERT_EQ(HSER_SINK_OK, sres); ASSERT_EQ(sizeof(input), copied); HSE_finish_res fres = heatshrink_encoder_finish(hse); ASSERT_EQ(HSER_FINISH_MORE, fres); ASSERT_EQ(HSER_POLL_EMPTY, heatshrink_encoder_poll(hse, output, 1024, &copied)); fres = heatshrink_encoder_finish(hse); ASSERT_EQ(HSER_FINISH_DONE, fres); if (0) dump_buf("output", output, copied); ASSERT_EQ(sizeof(expected), copied); for (size_t i=0; i<sizeof(expected); i++) ASSERT_EQ(expected[i], output[i]); heatshrink_encoder_free(hse); PASS(); } SUITE(encoding) { RUN_TEST(encoder_alloc_should_reject_invalid_arguments); RUN_TEST(encoder_sink_should_reject_nulls); RUN_TEST(encoder_sink_should_accept_input_when_it_will_fit); RUN_TEST(encoder_sink_should_accept_partial_input_when_some_will_fit); RUN_TEST(encoder_poll_should_reject_nulls); RUN_TEST(encoder_poll_should_indicate_when_no_input_is_provided); RUN_TEST(encoder_finish_should_reject_nulls); RUN_TEST(encoder_should_emit_data_without_repetitions_as_literal_sequence); RUN_TEST(encoder_should_emit_series_of_same_byte_as_literal_then_backref); RUN_TEST(encoder_poll_should_detect_repeated_substring); RUN_TEST(encoder_poll_should_detect_repeated_substring_and_preserve_trailing_literal); } TEST decoder_alloc_should_reject_excessively_small_window(void) { ASSERT_EQ(NULL, heatshrink_decoder_alloc(256, HEATSHRINK_MIN_WINDOW_BITS - 1, 4)); PASS(); } TEST decoder_alloc_should_reject_zero_byte_input_buffer(void) { ASSERT_EQ(NULL, heatshrink_decoder_alloc(0, HEATSHRINK_MIN_WINDOW_BITS, 4)); PASS(); } TEST decoder_sink_should_reject_null_hsd_pointer(void) { uint8_t input[] = {0,1,2,3,4,5}; size_t count = 0; ASSERT_EQ(HSDR_SINK_ERROR_NULL, heatshrink_decoder_sink(NULL, input, 6, &count)); PASS(); } TEST decoder_sink_should_reject_null_input_pointer(void) { heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, HEATSHRINK_MIN_WINDOW_BITS, 4); size_t count = 0; ASSERT_EQ(HSDR_SINK_ERROR_NULL, heatshrink_decoder_sink(hsd, NULL, 6, &count)); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_sink_should_reject_null_count_pointer(void) { uint8_t input[] = {0,1,2,3,4,5}; heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, HEATSHRINK_MIN_WINDOW_BITS, 4); ASSERT_EQ(HSDR_SINK_ERROR_NULL, heatshrink_decoder_sink(hsd, input, 6, NULL)); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_sink_should_reject_excessively_large_input(void) { uint8_t input[] = {0,1,2,3,4,5}; heatshrink_decoder *hsd = heatshrink_decoder_alloc(1, HEATSHRINK_MIN_WINDOW_BITS, 4); size_t count = 0; // Sink as much as will fit HSD_sink_res res = heatshrink_decoder_sink(hsd, input, 6, &count); ASSERT_EQ(HSDR_SINK_OK, res); ASSERT_EQ(1, count); // And now, no more should fit. res = heatshrink_decoder_sink(hsd, &input[count], sizeof(input) - count, &count); ASSERT_EQ(HSDR_SINK_FULL, res); ASSERT_EQ(0, count); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_sink_should_sink_data_when_preconditions_hold(void) { uint8_t input[] = {0,1,2,3,4,5}; heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, HEATSHRINK_MIN_WINDOW_BITS, 4); size_t count = 0; HSD_sink_res res = heatshrink_decoder_sink(hsd, input, 6, &count); ASSERT_EQ(HSDR_SINK_OK, res); ASSERT_EQ(hsd->input_size, 6); ASSERT_EQ(hsd->input_index, 0); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_poll_should_return_empty_if_empty(void) { uint8_t output[256]; size_t out_sz = 0; heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, HEATSHRINK_MIN_WINDOW_BITS, 4); HSD_poll_res res = heatshrink_decoder_poll(hsd, output, 256, &out_sz); ASSERT_EQ(HSDR_POLL_EMPTY, res); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_poll_should_reject_null_hsd(void) { uint8_t output[256]; size_t out_sz = 0; HSD_poll_res res = heatshrink_decoder_poll(NULL, output, 256, &out_sz); ASSERT_EQ(HSDR_POLL_ERROR_NULL, res); PASS(); } TEST decoder_poll_should_reject_null_output_buffer(void) { size_t out_sz = 0; heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, HEATSHRINK_MIN_WINDOW_BITS, 4); HSD_poll_res res = heatshrink_decoder_poll(hsd, NULL, 256, &out_sz); ASSERT_EQ(HSDR_POLL_ERROR_NULL, res); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_poll_should_reject_null_output_size_pointer(void) { uint8_t output[256]; heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, HEATSHRINK_MIN_WINDOW_BITS, 4); HSD_poll_res res = heatshrink_decoder_poll(hsd, output, 256, NULL); ASSERT_EQ(HSDR_POLL_ERROR_NULL, res); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_poll_should_expand_short_literal(void) { uint8_t input[] = {0xb3, 0x5b, 0xed, 0xe0 }; //"foo" uint8_t output[4]; heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, 7, 3); size_t count = 0; HSD_sink_res sres = heatshrink_decoder_sink(hsd, input, sizeof(input), &count); ASSERT_EQ(HSDR_SINK_OK, sres); size_t out_sz = 0; HSD_poll_res pres = heatshrink_decoder_poll(hsd, output, 4, &out_sz); ASSERT_EQ(HSDR_POLL_EMPTY, pres); ASSERT_EQ(3, out_sz); ASSERT_EQ('f', output[0]); ASSERT_EQ('o', output[1]); ASSERT_EQ('o', output[2]); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_poll_should_expand_short_literal_and_backref(void) { uint8_t input[] = {0xb3, 0x5b, 0xed, 0xe0, 0x40, 0x80}; //"foofoo" uint8_t output[6]; heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, 7, 7); memset(output, 0, sizeof(*output)); size_t count = 0; HSD_sink_res sres = heatshrink_decoder_sink(hsd, input, sizeof(input), &count); ASSERT_EQ(HSDR_SINK_OK, sres); size_t out_sz = 0; (void)heatshrink_decoder_poll(hsd, output, 6, &out_sz); if (0) dump_buf("output", output, out_sz); ASSERT_EQ(6, out_sz); ASSERT_EQ('f', output[0]); ASSERT_EQ('o', output[1]); ASSERT_EQ('o', output[2]); ASSERT_EQ('f', output[3]); ASSERT_EQ('o', output[4]); ASSERT_EQ('o', output[5]); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_poll_should_expand_short_self_overlapping_backref(void) { /* "aaaaa" == (literal, 1), ('a'), (backref, 1 back, 4 bytes) */ uint8_t input[] = {0xb0, 0x80, 0x01, 0x80}; uint8_t output[6]; uint8_t expected[] = {'a', 'a', 'a', 'a', 'a'}; heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, 8, 7); size_t count = 0; HSD_sink_res sres = heatshrink_decoder_sink(hsd, input, sizeof(input), &count); ASSERT_EQ(HSDR_SINK_OK, sres); size_t out_sz = 0; (void)heatshrink_decoder_poll(hsd, output, sizeof(output), &out_sz); if (0) dump_buf("output", output, out_sz); ASSERT_EQ(sizeof(expected), out_sz); for (size_t i=0; i<sizeof(expected); i++) ASSERT_EQ(expected[i], output[i]); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_poll_should_suspend_if_out_of_space_in_output_buffer_during_literal_expansion(void) { uint8_t input[] = {0xb3, 0x5b, 0xed, 0xe0, 0x40, 0x80}; uint8_t output[1]; heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, 7, 7); size_t count = 0; HSD_sink_res sres = heatshrink_decoder_sink(hsd, input, sizeof(input), &count); ASSERT_EQ(HSDR_SINK_OK, sres); size_t out_sz = 0; HSD_poll_res pres = heatshrink_decoder_poll(hsd, output, 1, &out_sz); ASSERT_EQ(HSDR_POLL_MORE, pres); ASSERT_EQ(1, out_sz); ASSERT_EQ('f', output[0]); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_poll_should_suspend_if_out_of_space_in_output_buffer_during_backref_expansion(void) { uint8_t input[] = {0xb3, 0x5b, 0xed, 0xe0, 0x40, 0x80}; //"foofoo" uint8_t output[4]; heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, 7, 7); memset(output, 0, sizeof(*output)); size_t count = 0; HSD_sink_res sres = heatshrink_decoder_sink(hsd, input, 6, &count); ASSERT_EQ(HSDR_SINK_OK, sres); size_t out_sz = 0; HSD_poll_res pres = heatshrink_decoder_poll(hsd, output, 4, &out_sz); ASSERT_EQ(HSDR_POLL_MORE, pres); ASSERT_EQ(4, out_sz); ASSERT_EQ('f', output[0]); ASSERT_EQ('o', output[1]); ASSERT_EQ('o', output[2]); ASSERT_EQ('f', output[3]); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_poll_should_expand_short_literal_and_backref_when_fed_input_byte_by_byte(void) { uint8_t input[] = {0xb3, 0x5b, 0xed, 0xe0, 0x40, 0x80}; //"foofoo" uint8_t output[7]; heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, 7, 7); memset(output, 0, sizeof(*output)); size_t count = 0; HSD_sink_res sres; for (int i=0; i<6; i++) { sres = heatshrink_decoder_sink(hsd, &input[i], 1, &count); ASSERT_EQ(HSDR_SINK_OK, sres); } heatshrink_decoder_finish(hsd); size_t out_sz = 0; HSD_poll_res pres = heatshrink_decoder_poll(hsd, output, 7, &out_sz); ASSERT_EQ(6, out_sz); ASSERT_EQ(HSDR_POLL_EMPTY, pres); ASSERT_EQ('f', output[0]); ASSERT_EQ('o', output[1]); ASSERT_EQ('o', output[2]); ASSERT_EQ('f', output[3]); ASSERT_EQ('o', output[4]); ASSERT_EQ('o', output[5]); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_finish_should_reject_null_input(void) { heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, 7, 7); HSD_finish_res exp = HSDR_FINISH_ERROR_NULL; ASSERT_EQ(exp, heatshrink_decoder_finish(NULL)); heatshrink_decoder_free(hsd); PASS(); } TEST decoder_finish_should_note_when_done(void) { uint8_t input[] = {0xb3, 0x5b, 0xed, 0xe0, 0x40, 0x80}; //"foofoo" uint8_t output[7]; heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, 7, 7); memset(output, 0, sizeof(*output)); size_t count = 0; HSD_sink_res sres = heatshrink_decoder_sink(hsd, input, sizeof(input), &count); ASSERT_EQ(HSDR_SINK_OK, sres); size_t out_sz = 0; HSD_poll_res pres = heatshrink_decoder_poll(hsd, output, sizeof(output), &out_sz); ASSERT_EQ(HSDR_POLL_EMPTY, pres); ASSERT_EQ(6, out_sz); ASSERT_EQ('f', output[0]); ASSERT_EQ('o', output[1]); ASSERT_EQ('o', output[2]); ASSERT_EQ('f', output[3]); ASSERT_EQ('o', output[4]); ASSERT_EQ('o', output[5]); HSD_finish_res fres = heatshrink_decoder_finish(hsd); ASSERT_EQ(HSDR_FINISH_DONE, fres); heatshrink_decoder_free(hsd); PASS(); } TEST gen(void) { heatshrink_encoder *hse = heatshrink_encoder_alloc(8, 7); uint8_t input[] = {'a', 'a', 'a', 'a', 'a'}; uint8_t output[1024]; size_t copied = 0; memset(output, 0, 1024); HSE_sink_res sres = heatshrink_encoder_sink(hse, input, sizeof(input), &copied); ASSERT_EQ(HSER_SINK_OK, sres); ASSERT_EQ(sizeof(input), copied); HSE_finish_res fres = heatshrink_encoder_finish(hse); ASSERT_EQ(HSER_FINISH_MORE, fres); ASSERT_EQ(HSER_POLL_EMPTY, heatshrink_encoder_poll(hse, output, 1024, &copied)); fres = heatshrink_encoder_finish(hse); ASSERT_EQ(HSER_FINISH_DONE, fres); if (0) { printf("{"); for (size_t i=0; i<copied; i++) printf("0x%02x, ", output[i]); printf("}\n"); } heatshrink_encoder_free(hse); PASS(); } TEST decoder_should_not_get_stuck_with_finish_yielding_MORE_but_0_bytes_output_from_poll(void) { uint8_t input[512]; memset(input, 0xff, 256); uint8_t output[1024]; heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, 8, 4); ASSERT(hsd); /* Confirm that no byte of trailing context can lead to * heatshrink_decoder_finish erroneously returning HSDR_FINISH_MORE * when heatshrink_decoder_poll will yield 0 bytes. * * Before 0.3.1, a final byte of 0xFF could potentially cause * this to happen, if at exactly the byte boundary. */ for (uint16_t byte = 0; byte < 256; byte++) { for (int i = 1; i < 512; i++) { input[i] = byte; heatshrink_decoder_reset(hsd); memset(output, 0, sizeof(*output)); size_t count = 0; HSD_sink_res sres = heatshrink_decoder_sink(hsd, input, i, &count); ASSERT_EQ(HSDR_SINK_OK, sres); size_t out_sz = 0; HSD_poll_res pres = heatshrink_decoder_poll(hsd, output, sizeof(output), &out_sz); ASSERT_EQ(HSDR_POLL_EMPTY, pres); HSD_finish_res fres = heatshrink_decoder_finish(hsd); ASSERT_EQ(HSDR_FINISH_DONE, fres); input[i] = 0xff; } } heatshrink_decoder_free(hsd); PASS(); } SUITE(decoding) { RUN_TEST(decoder_alloc_should_reject_excessively_small_window); RUN_TEST(decoder_alloc_should_reject_zero_byte_input_buffer); RUN_TEST(decoder_sink_should_reject_null_hsd_pointer); RUN_TEST(decoder_sink_should_reject_null_input_pointer); RUN_TEST(decoder_sink_should_reject_null_count_pointer); RUN_TEST(decoder_sink_should_reject_excessively_large_input); RUN_TEST(decoder_sink_should_sink_data_when_preconditions_hold); RUN_TEST(gen); RUN_TEST(decoder_poll_should_return_empty_if_empty); RUN_TEST(decoder_poll_should_reject_null_hsd); RUN_TEST(decoder_poll_should_reject_null_output_buffer); RUN_TEST(decoder_poll_should_reject_null_output_size_pointer); RUN_TEST(decoder_poll_should_expand_short_literal); RUN_TEST(decoder_poll_should_expand_short_literal_and_backref); RUN_TEST(decoder_poll_should_expand_short_self_overlapping_backref); RUN_TEST(decoder_poll_should_suspend_if_out_of_space_in_output_buffer_during_literal_expansion); RUN_TEST(decoder_poll_should_suspend_if_out_of_space_in_output_buffer_during_backref_expansion); RUN_TEST(decoder_poll_should_expand_short_literal_and_backref_when_fed_input_byte_by_byte); RUN_TEST(decoder_finish_should_reject_null_input); RUN_TEST(decoder_finish_should_note_when_done); // Regressions RUN_TEST(decoder_should_not_get_stuck_with_finish_yielding_MORE_but_0_bytes_output_from_poll); } typedef struct { uint8_t log_lvl; uint8_t window_sz2; uint8_t lookahead_sz2; size_t decoder_input_buffer_size; } cfg_info; static int compress_and_expand_and_check(uint8_t *input, uint32_t input_size, cfg_info *cfg) { heatshrink_encoder *hse = heatshrink_encoder_alloc(cfg->window_sz2, cfg->lookahead_sz2); heatshrink_decoder *hsd = heatshrink_decoder_alloc(cfg->decoder_input_buffer_size, cfg->window_sz2, cfg->lookahead_sz2); size_t comp_sz = input_size + (input_size/2) + 4; size_t decomp_sz = input_size + (input_size/2) + 4; uint8_t *comp = malloc(comp_sz); uint8_t *decomp = malloc(decomp_sz); if (comp == NULL) FAILm("malloc fail"); if (decomp == NULL) FAILm("malloc fail"); memset(comp, 0, comp_sz); memset(decomp, 0, decomp_sz); size_t count = 0; if (cfg->log_lvl > 1) { printf("\n^^ COMPRESSING\n"); dump_buf("input", input, input_size); } size_t sunk = 0; size_t polled = 0; while (sunk < input_size) { ASSERT(heatshrink_encoder_sink(hse, &input[sunk], input_size - sunk, &count) >= 0); sunk += count; if (cfg->log_lvl > 1) printf("^^ sunk %zd\n", count); if (sunk == input_size) { ASSERT_EQ(HSER_FINISH_MORE, heatshrink_encoder_finish(hse)); } HSE_poll_res pres; do { /* "turn the crank" */ pres = heatshrink_encoder_poll(hse, &comp[polled], comp_sz - polled, &count); ASSERT(pres >= 0); polled += count; if (cfg->log_lvl > 1) printf("^^ polled %zd\n", count); } while (pres == HSER_POLL_MORE); ASSERT_EQ(HSER_POLL_EMPTY, pres); if (polled >= comp_sz) FAILm("compression should never expand that much"); if (sunk == input_size) { ASSERT_EQ(HSER_FINISH_DONE, heatshrink_encoder_finish(hse)); } } if (cfg->log_lvl > 0) printf("in: %u compressed: %zu ", input_size, polled); size_t compressed_size = polled; sunk = 0; polled = 0; if (cfg->log_lvl > 1) { printf("\n^^ DECOMPRESSING\n"); dump_buf("comp", comp, compressed_size); } while (sunk < compressed_size) { ASSERT(heatshrink_decoder_sink(hsd, &comp[sunk], compressed_size - sunk, &count) >= 0); sunk += count; if (cfg->log_lvl > 1) printf("^^ sunk %zd\n", count); if (sunk == compressed_size) { ASSERT_EQ(HSDR_FINISH_MORE, heatshrink_decoder_finish(hsd)); } HSD_poll_res pres; do { pres = heatshrink_decoder_poll(hsd, &decomp[polled], decomp_sz - polled, &count); ASSERT(pres >= 0); ASSERT(count > 0); polled += count; if (cfg->log_lvl > 1) printf("^^ polled %zd\n", count); } while (pres == HSDR_POLL_MORE); ASSERT_EQ(HSDR_POLL_EMPTY, pres); if (sunk == compressed_size) { HSD_finish_res fres = heatshrink_decoder_finish(hsd); ASSERT_EQ(HSDR_FINISH_DONE, fres); } if (polled > input_size) { printf("\nExpected %zd, got %zu\n", (size_t)input_size, polled); FAILm("Decompressed data is larger than original input"); } } if (cfg->log_lvl > 0) printf("decompressed: %zu\n", polled); if (polled != input_size) { FAILm("Decompressed length does not match original input length"); } if (cfg->log_lvl > 1) dump_buf("decomp", decomp, polled); for (uint32_t i=0; i<input_size; i++) { if (input[i] != decomp[i]) { printf("*** mismatch at %d\n", i); if (0) { for (uint32_t j=0; j<=/*i*/ input_size; j++) { printf("in[%d] == 0x%02x ('%c') => out[%d] == 0x%02x ('%c') %c\n", j, input[j], isprint(input[j]) ? input[j] : '.', j, decomp[j], isprint(decomp[j]) ? decomp[j] : '.', input[j] == decomp[j] ? ' ' : 'X'); } } } ASSERT_EQ(input[i], decomp[i]); } free(comp); free(decomp); heatshrink_encoder_free(hse); heatshrink_decoder_free(hsd); PASS(); } TEST data_without_duplication_should_match(void) { uint8_t input[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; cfg_info cfg; cfg.log_lvl = 0; cfg.window_sz2 = 8; cfg.lookahead_sz2 = 3; cfg.decoder_input_buffer_size = 256; return compress_and_expand_and_check(input, sizeof(input), &cfg); } TEST data_with_simple_repetition_should_compress_and_decompress_properly(void) { uint8_t input[] = {'a', 'b', 'c', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}; cfg_info cfg; cfg.log_lvl = 0; cfg.window_sz2 = 8; cfg.lookahead_sz2 = 3; cfg.decoder_input_buffer_size = 256; return compress_and_expand_and_check(input, sizeof(input), &cfg); } TEST data_without_duplication_should_match_with_absurdly_tiny_buffers(void) { heatshrink_encoder *hse = heatshrink_encoder_alloc(8, 3); heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, 8, 3); uint8_t input[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; uint8_t comp[60]; uint8_t decomp[60]; size_t count = 0; int log = 0; if (log) dump_buf("input", input, sizeof(input)); for (uint32_t i=0; i<sizeof(input); i++) { ASSERT(heatshrink_encoder_sink(hse, &input[i], 1, &count) >= 0); } ASSERT_EQ(HSER_FINISH_MORE, heatshrink_encoder_finish(hse)); size_t packed_count = 0; do { ASSERT(heatshrink_encoder_poll(hse, &comp[packed_count], 1, &count) >= 0); packed_count += count; } while (heatshrink_encoder_finish(hse) == HSER_FINISH_MORE); if (log) dump_buf("comp", comp, packed_count); for (uint32_t i=0; i<packed_count; i++) { HSD_sink_res sres = heatshrink_decoder_sink(hsd, &comp[i], 1, &count); //printf("sres is %d\n", sres); ASSERT(sres >= 0); } for (uint32_t i=0; i<sizeof(input); i++) { ASSERT(heatshrink_decoder_poll(hsd, &decomp[i], 1, &count) >= 0); } if (log) dump_buf("decomp", decomp, sizeof(input)); for (uint32_t i=0; i<sizeof(input); i++) ASSERT_EQ(input[i], decomp[i]); heatshrink_encoder_free(hse); heatshrink_decoder_free(hsd); PASS(); } TEST data_with_simple_repetition_should_match_with_absurdly_tiny_buffers(void) { heatshrink_encoder *hse = heatshrink_encoder_alloc(8, 3); heatshrink_decoder *hsd = heatshrink_decoder_alloc(256, 8, 3); uint8_t input[] = {'a', 'b', 'c', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}; uint8_t comp[60]; uint8_t decomp[60]; size_t count = 0; int log = 0; if (log) dump_buf("input", input, sizeof(input)); for (uint32_t i=0; i<sizeof(input); i++) { ASSERT(heatshrink_encoder_sink(hse, &input[i], 1, &count) >= 0); } ASSERT_EQ(HSER_FINISH_MORE, heatshrink_encoder_finish(hse)); size_t packed_count = 0; do { ASSERT(heatshrink_encoder_poll(hse, &comp[packed_count], 1, &count) >= 0); packed_count += count; } while (heatshrink_encoder_finish(hse) == HSER_FINISH_MORE); if (log) dump_buf("comp", comp, packed_count); for (uint32_t i=0; i<packed_count; i++) { HSD_sink_res sres = heatshrink_decoder_sink(hsd, &comp[i], 1, &count); //printf("sres is %d\n", sres); ASSERT(sres >= 0); } for (uint32_t i=0; i<sizeof(input); i++) { ASSERT(heatshrink_decoder_poll(hsd, &decomp[i], 1, &count) >= 0); } if (log) dump_buf("decomp", decomp, sizeof(input)); for (uint32_t i=0; i<sizeof(input); i++) ASSERT_EQ(input[i], decomp[i]); heatshrink_encoder_free(hse); heatshrink_decoder_free(hsd); PASS(); } static void fill_with_pseudorandom_letters(uint8_t *buf, uint32_t size, uint32_t seed) { uint64_t rn = 9223372036854775783; /* prime under 2^64 */ for (uint32_t i=0; i<size; i++) { rn = rn*seed + seed; buf[i] = (rn % 26) + 'a'; } } TEST pseudorandom_data_should_match(uint32_t size, uint32_t seed, cfg_info *cfg) { uint8_t input[size]; if (cfg->log_lvl > 0) { printf("\n-- size %u, seed %u, input buf %zu\n", size, seed, cfg->decoder_input_buffer_size); } fill_with_pseudorandom_letters(input, size, seed); return compress_and_expand_and_check(input, size, cfg); } TEST small_input_buffer_should_not_impact_decoder_correctness(void) { int size = 5; uint8_t input[size]; cfg_info cfg; cfg.log_lvl = 0; cfg.window_sz2 = 8; cfg.lookahead_sz2 = 3; cfg.decoder_input_buffer_size = 5; for (uint16_t i=0; i<size; i++) input[i] = 'a' + (i % 26); if (compress_and_expand_and_check(input, size, &cfg) != 0) return -1; PASS(); } TEST regression_backreference_counters_should_not_roll_over(void) { /* Searching was scanning the entire context buffer, not just * the maximum range addressable by the backref index.*/ uint32_t size = 337; uint32_t seed = 3; uint8_t input[size]; fill_with_pseudorandom_letters(input, size, seed); cfg_info cfg; cfg.log_lvl = 0; cfg.window_sz2 = 8; cfg.lookahead_sz2 = 3; cfg.decoder_input_buffer_size = 64; // 1 return compress_and_expand_and_check(input, size, &cfg); } TEST regression_index_fail(void) { /* Failured when indexed, cause unknown. * * This has something to do with bad data at the very last * byte being indexed, due to spillover. */ uint32_t size = 507; uint32_t seed = 3; uint8_t input[size]; fill_with_pseudorandom_letters(input, size, seed); cfg_info cfg; cfg.log_lvl = 0; cfg.window_sz2 = 8; cfg.lookahead_sz2 = 3; cfg.decoder_input_buffer_size = 64; return compress_and_expand_and_check(input, size, &cfg); } TEST sixty_four_k(void) { /* Regression: An input buffer of 64k should not cause an * overflow that leads to an infinite loop. */ uint32_t size = 64 * 1024; uint32_t seed = 1; uint8_t input[size]; fill_with_pseudorandom_letters(input, size, seed); cfg_info cfg; cfg.log_lvl = 0; cfg.window_sz2 = 8; cfg.lookahead_sz2 = 3; cfg.decoder_input_buffer_size = 64; return compress_and_expand_and_check(input, size, &cfg); } SUITE(integration) { RUN_TEST(data_without_duplication_should_match); RUN_TEST(data_with_simple_repetition_should_compress_and_decompress_properly); RUN_TEST(data_without_duplication_should_match_with_absurdly_tiny_buffers); RUN_TEST(data_with_simple_repetition_should_match_with_absurdly_tiny_buffers); // Regressions from fuzzing RUN_TEST(small_input_buffer_should_not_impact_decoder_correctness); RUN_TEST(regression_backreference_counters_should_not_roll_over); RUN_TEST(regression_index_fail); RUN_TEST(sixty_four_k); #if __STDC_VERSION__ >= 19901L printf("\n\nFuzzing (single-byte sizes):\n"); for (uint8_t lsize=3; lsize < 8; lsize++) { for (uint32_t size=1; size < 128*1024L; size <<= 1) { if (GREATEST_IS_VERBOSE()) printf(" -- size %u\n", size); for (uint16_t ibs=32; ibs<=8192; ibs <<= 1) { /* input buffer size */ if (GREATEST_IS_VERBOSE()) printf(" -- input buffer %u\n", ibs); for (uint32_t seed=1; seed<=10; seed++) { if (GREATEST_IS_VERBOSE()) printf(" -- seed %u\n", seed); cfg_info cfg; cfg.log_lvl = 0; cfg.window_sz2 = 8; cfg.lookahead_sz2 = lsize; cfg.decoder_input_buffer_size = ibs; RUN_TESTp(pseudorandom_data_should_match, size, seed, &cfg); } } } } printf("\nFuzzing (multi-byte sizes):\n"); for (uint8_t lsize=6; lsize < 9; lsize++) { for (uint32_t size=1; size < 128*1024L; size <<= 1) { if (GREATEST_IS_VERBOSE()) printf(" -- size %u\n", size); for (uint16_t ibs=32; ibs<=8192; ibs <<= 1) { /* input buffer size */ if (GREATEST_IS_VERBOSE()) printf(" -- input buffer %u\n", ibs); for (uint32_t seed=1; seed<=10; seed++) { if (GREATEST_IS_VERBOSE()) printf(" -- seed %u\n", seed); cfg_info cfg; cfg.log_lvl = 0; cfg.window_sz2 = 11; cfg.lookahead_sz2 = lsize; cfg.decoder_input_buffer_size = ibs; RUN_TESTp(pseudorandom_data_should_match, size, seed, &cfg); } } } } #endif } /* Add all the definitions that need to be in the test runner's main file. */ GREATEST_MAIN_DEFS(); int main(int argc, char **argv) { GREATEST_MAIN_BEGIN(); /* command-line arguments, initialization. */ RUN_SUITE(encoding); RUN_SUITE(decoding); RUN_SUITE(integration); #ifdef HEATSHRINK_HAS_THEFT RUN_SUITE(properties); #endif GREATEST_MAIN_END(); /* display results */ }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug MX|Win32"> <Configuration>Debug MX</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug MX|x64"> <Configuration>Debug MX</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release MX|Win32"> <Configuration>Release MX</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release MX|x64"> <Configuration>Release MX</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Template|Win32"> <Configuration>Template</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Template|x64"> <Configuration>Template</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <SccProjectName /> <SccLocalPath /> <ProjectGuid>{719C8A48-DF6D-49DB-A689-C1F1E4FB13CA}</ProjectGuid> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Template|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <PlatformToolset>v140</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Template|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <PlatformToolset>v140</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <PlatformToolset>v140</PlatformToolset> <UseOfMfc>false</UseOfMfc> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <PlatformToolset>v140</PlatformToolset> <UseOfMfc>false</UseOfMfc> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release MX|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <PlatformToolset>v140</PlatformToolset> <UseOfMfc>false</UseOfMfc> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release MX|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <PlatformToolset>v140</PlatformToolset> <UseOfMfc>false</UseOfMfc> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <PlatformToolset>v140</PlatformToolset> <UseOfMfc>false</UseOfMfc> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <PlatformToolset>v140</PlatformToolset> <UseOfMfc>false</UseOfMfc> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug MX|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <PlatformToolset>v140</PlatformToolset> <UseOfMfc>false</UseOfMfc> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug MX|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <PlatformToolset>v140</PlatformToolset> <UseOfMfc>false</UseOfMfc> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Template|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Template|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release MX|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release MX|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug MX|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug MX|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug MX|Win32'"> <OutDir>.\../../bin\</OutDir> <IntDir>.\static/debug-mx\</IntDir> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug MX|x64'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <OutDir>.\../../bin\</OutDir> <IntDir>.\static/debug\</IntDir> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release MX|Win32'"> <OutDir>.\../../bin\</OutDir> <IntDir>.\static/release-mx\</IntDir> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release MX|x64'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <OutDir>.\../../bin\</OutDir> <IntDir>.\static/release\</IntDir> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug MX|Win32'"> <ClCompile> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <InlineFunctionExpansion>Default</InlineFunctionExpansion> <FunctionLevelLinking>false</FunctionLevelLinking> <Optimization>Disabled</Optimization> <SuppressStartupBanner>true</SuppressStartupBanner> <WarningLevel>Level3</WarningLevel> <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;WIN32_LEAN_AND_MEAN;VC_EXTRA_LEAN;GLEW_MX;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AssemblerListingLocation>.\static/debug-mx\</AssemblerListingLocation> <PrecompiledHeaderOutputFile>.\static/debug-mx\visualinfo.pch</PrecompiledHeaderOutputFile> <ObjectFileName>.\static/debug-mx\</ObjectFileName> <ProgramDataBaseFileName>.\static/debug-mx\</ProgramDataBaseFileName> <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> </ClCompile> <Midl> <TypeLibraryName>.\../../bin\visualinfo.tlb</TypeLibraryName> </Midl> <ResourceCompile> <Culture>0x0409</Culture> <PreprocessorDefinitions>_DEBUG;GLEW_MX;%(PreprocessorDefinitions)</PreprocessorDefinitions> </ResourceCompile> <Bscmake> <SuppressStartupBanner>true</SuppressStartupBanner> <OutputFile>.\../../bin\visualinfo.bsc</OutputFile> </Bscmake> <Link> <SuppressStartupBanner>true</SuppressStartupBanner> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Console</SubSystem> <OutputFile>../../bin/visualinfo-mxd.exe</OutputFile> <AdditionalDependencies>../../lib/glew32mxsd.lib;glu32.lib;opengl32.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug MX|x64'"> <ClCompile> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <InlineFunctionExpansion>Default</InlineFunctionExpansion> <FunctionLevelLinking>false</FunctionLevelLinking> <Optimization>Disabled</Optimization> <SuppressStartupBanner>true</SuppressStartupBanner> <WarningLevel>Level3</WarningLevel> <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;WIN32_LEAN_AND_MEAN;VC_EXTRA_LEAN;GLEW_MX;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AssemblerListingLocation>.\static/debug-mx\</AssemblerListingLocation> <PrecompiledHeaderOutputFile>.\static/debug-mx\visualinfo.pch</PrecompiledHeaderOutputFile> <ObjectFileName>.\static/debug-mx\</ObjectFileName> <ProgramDataBaseFileName>.\static/debug-mx\</ProgramDataBaseFileName> <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> </ClCompile> <Midl> <TypeLibraryName>.\../../bin\visualinfo.tlb</TypeLibraryName> </Midl> <ResourceCompile> <Culture>0x0409</Culture> <PreprocessorDefinitions>_DEBUG;GLEW_MX;%(PreprocessorDefinitions)</PreprocessorDefinitions> </ResourceCompile> <Bscmake> <SuppressStartupBanner>true</SuppressStartupBanner> <OutputFile>.\../../bin\visualinfo.bsc</OutputFile> </Bscmake> <Link> <SuppressStartupBanner>true</SuppressStartupBanner> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Console</SubSystem> <OutputFile>../../bin/visualinfo-mxd.exe</OutputFile> <AdditionalDependencies>../../lib/glew32mxsd.lib;glu32.lib;opengl32.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <InlineFunctionExpansion>Default</InlineFunctionExpansion> <FunctionLevelLinking>false</FunctionLevelLinking> <Optimization>Disabled</Optimization> <SuppressStartupBanner>true</SuppressStartupBanner> <WarningLevel>Level3</WarningLevel> <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;WIN32_LEAN_AND_MEAN;VC_EXTRA_LEAN;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AssemblerListingLocation>.\static/debug\</AssemblerListingLocation> <PrecompiledHeaderOutputFile>.\static/debug\visualinfo.pch</PrecompiledHeaderOutputFile> <ObjectFileName>.\static/debug\</ObjectFileName> <ProgramDataBaseFileName>.\static/debug\</ProgramDataBaseFileName> <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> </ClCompile> <Midl> <TypeLibraryName>.\../../bin\visualinfo.tlb</TypeLibraryName> </Midl> <ResourceCompile> <Culture>0x0409</Culture> <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> </ResourceCompile> <Bscmake> <SuppressStartupBanner>true</SuppressStartupBanner> <OutputFile>.\../../bin\visualinfo.bsc</OutputFile> </Bscmake> <Link> <SuppressStartupBanner>true</SuppressStartupBanner> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Console</SubSystem> <OutputFile>../../bin/visualinfod.exe</OutputFile> <AdditionalDependencies>../../lib/glew32sd.lib;glu32.lib;opengl32.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <InlineFunctionExpansion>Default</InlineFunctionExpansion> <FunctionLevelLinking>false</FunctionLevelLinking> <Optimization>Disabled</Optimization> <SuppressStartupBanner>true</SuppressStartupBanner> <WarningLevel>Level3</WarningLevel> <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;WIN32_LEAN_AND_MEAN;VC_EXTRA_LEAN;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AssemblerListingLocation>.\static/debug\</AssemblerListingLocation> <PrecompiledHeaderOutputFile>.\static/debug\visualinfo.pch</PrecompiledHeaderOutputFile> <ObjectFileName>.\static/debug\</ObjectFileName> <ProgramDataBaseFileName>.\static/debug\</ProgramDataBaseFileName> <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> </ClCompile> <Midl> <TypeLibraryName>.\../../bin\visualinfo.tlb</TypeLibraryName> </Midl> <ResourceCompile> <Culture>0x0409</Culture> <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> </ResourceCompile> <Bscmake> <SuppressStartupBanner>true</SuppressStartupBanner> <OutputFile>.\../../bin\visualinfo.bsc</OutputFile> </Bscmake> <Link> <SuppressStartupBanner>true</SuppressStartupBanner> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Console</SubSystem> <OutputFile>../../bin/visualinfod.exe</OutputFile> <AdditionalDependencies>../../lib/glew32sd.lib;glu32.lib;opengl32.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release MX|Win32'"> <ClCompile> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <InlineFunctionExpansion>Default</InlineFunctionExpansion> <StringPooling>true</StringPooling> <FunctionLevelLinking>true</FunctionLevelLinking> <Optimization>MaxSpeed</Optimization> <SuppressStartupBanner>true</SuppressStartupBanner> <WarningLevel>Level3</WarningLevel> <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;WIN32_MEAN_AND_LEAN;VC_EXTRALEAN;GLEW_MX;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AssemblerListingLocation>.\static/release-mx\</AssemblerListingLocation> <PrecompiledHeaderOutputFile>.\static/release-mx\visualinfo.pch</PrecompiledHeaderOutputFile> <ObjectFileName>.\static/release-mx\</ObjectFileName> <ProgramDataBaseFileName>.\static/release-mx\</ProgramDataBaseFileName> </ClCompile> <Midl> <TypeLibraryName>.\../../bin\visualinfo.tlb</TypeLibraryName> </Midl> <ResourceCompile> <Culture>0x0409</Culture> <PreprocessorDefinitions>NDEBUG;GLEW_MX;%(PreprocessorDefinitions)</PreprocessorDefinitions> </ResourceCompile> <Bscmake> <SuppressStartupBanner>true</SuppressStartupBanner> <OutputFile>.\../../bin\visualinfo.bsc</OutputFile> </Bscmake> <Link> <SuppressStartupBanner>true</SuppressStartupBanner> <SubSystem>Console</SubSystem> <OutputFile>../../bin/visualinfo-mx.exe</OutputFile> <AdditionalDependencies>../../lib/glew32mxs.lib;glu32.lib;opengl32.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release MX|x64'"> <ClCompile> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <InlineFunctionExpansion>Default</InlineFunctionExpansion> <StringPooling>true</StringPooling> <FunctionLevelLinking>true</FunctionLevelLinking> <Optimization>MaxSpeed</Optimization> <SuppressStartupBanner>true</SuppressStartupBanner> <WarningLevel>Level3</WarningLevel> <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;WIN32_MEAN_AND_LEAN;VC_EXTRALEAN;GLEW_MX;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AssemblerListingLocation>.\static/release-mx\</AssemblerListingLocation> <PrecompiledHeaderOutputFile>.\static/release-mx\visualinfo.pch</PrecompiledHeaderOutputFile> <ObjectFileName>.\static/release-mx\</ObjectFileName> <ProgramDataBaseFileName>.\static/release-mx\</ProgramDataBaseFileName> </ClCompile> <Midl> <TypeLibraryName>.\../../bin\visualinfo.tlb</TypeLibraryName> </Midl> <ResourceCompile> <Culture>0x0409</Culture> <PreprocessorDefinitions>NDEBUG;GLEW_MX;%(PreprocessorDefinitions)</PreprocessorDefinitions> </ResourceCompile> <Bscmake> <SuppressStartupBanner>true</SuppressStartupBanner> <OutputFile>.\../../bin\visualinfo.bsc</OutputFile> </Bscmake> <Link> <SuppressStartupBanner>true</SuppressStartupBanner> <SubSystem>Console</SubSystem> <OutputFile>../../bin/visualinfo-mx.exe</OutputFile> <AdditionalDependencies>../../lib/glew32mxs.lib;glu32.lib;opengl32.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <InlineFunctionExpansion>Default</InlineFunctionExpansion> <StringPooling>true</StringPooling> <FunctionLevelLinking>true</FunctionLevelLinking> <Optimization>MaxSpeed</Optimization> <SuppressStartupBanner>true</SuppressStartupBanner> <WarningLevel>Level3</WarningLevel> <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;WIN32_MEAN_AND_LEAN;VC_EXTRALEAN;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AssemblerListingLocation>.\static/release\</AssemblerListingLocation> <PrecompiledHeaderOutputFile>.\static/release\visualinfo.pch</PrecompiledHeaderOutputFile> <ObjectFileName>.\static/release\</ObjectFileName> <ProgramDataBaseFileName>.\static/release\</ProgramDataBaseFileName> </ClCompile> <Midl> <TypeLibraryName>.\../../bin\visualinfo.tlb</TypeLibraryName> </Midl> <ResourceCompile> <Culture>0x0409</Culture> <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> </ResourceCompile> <Bscmake> <SuppressStartupBanner>true</SuppressStartupBanner> <OutputFile>.\../../bin\visualinfo.bsc</OutputFile> </Bscmake> <Link> <SuppressStartupBanner>true</SuppressStartupBanner> <SubSystem>Console</SubSystem> <OutputFile>.\../../bin\visualinfo.exe</OutputFile> <AdditionalDependencies>../../lib/glew32s.lib;glu32.lib;opengl32.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ClCompile> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <InlineFunctionExpansion>Default</InlineFunctionExpansion> <StringPooling>true</StringPooling> <FunctionLevelLinking>true</FunctionLevelLinking> <Optimization>MaxSpeed</Optimization> <SuppressStartupBanner>true</SuppressStartupBanner> <WarningLevel>Level3</WarningLevel> <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;WIN32_MEAN_AND_LEAN;VC_EXTRALEAN;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AssemblerListingLocation>.\static/release\</AssemblerListingLocation> <PrecompiledHeaderOutputFile>.\static/release\visualinfo.pch</PrecompiledHeaderOutputFile> <ObjectFileName>.\static/release\</ObjectFileName> <ProgramDataBaseFileName>.\static/release\</ProgramDataBaseFileName> </ClCompile> <Midl> <TypeLibraryName>.\../../bin\visualinfo.tlb</TypeLibraryName> </Midl> <ResourceCompile> <Culture>0x0409</Culture> <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> </ResourceCompile> <Bscmake> <SuppressStartupBanner>true</SuppressStartupBanner> <OutputFile>.\../../bin\visualinfo.bsc</OutputFile> </Bscmake> <Link> <SuppressStartupBanner>true</SuppressStartupBanner> <SubSystem>Console</SubSystem> <OutputFile>.\../../bin\visualinfo.exe</OutputFile> <AdditionalDependencies>../../lib/glew32s.lib;glu32.lib;opengl32.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemGroup> <ClCompile Include="..\..\src\visualinfo.c" /> </ItemGroup> <ItemGroup> <ResourceCompile Include="visualinfo.rc" /> </ItemGroup> <ItemGroup> <ProjectReference Include="glew_static.vcxproj"> <Project>{1904de3d-17b3-4e4b-a7f2-acdb2d4d45a2}</Project> <ReferenceOutputAssembly>false</ReferenceOutputAssembly> </ProjectReference> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
{ "pile_set_name": "Github" }
# -*- encoding : utf-8 -*- require_relative 'spec_helper' describe Cequel::Record::Scoped do model :Post do key :blog_subdomain, :text key :id, :uuid, auto: true column :name, :text end it 'should use current scoped key values to populate new record' do expect(Post['bigdata'].new.blog_subdomain).to eq('bigdata') end it "should not mess up class' #puts" do StringIO.new.tap do |out| out.puts Post expect(out.string).to eq("Post\n") end end end
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="pl.bclogic.pulsator4droid.demo"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" tools:ignore="AllowBackup,GoogleAppIndexingWarning"> <activity android:name="pl.bclogic.pulsator4droid.demo.MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest>
{ "pile_set_name": "Github" }
<html> <body> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="resources/feature-policy-navigation.js"></script> <script> (async () => { await test_frame( "HTTPS_REMOTE_ORIGIN", "device-memory=true&dpr=false&viewport-width=false&sec-ch-ua=false&sec-ch-ua-mobile=false", "", "Client hints loaded on cross-origin iframe request with feature policy."); await test_frame( "HTTPS_ORIGIN", "device-memory=true&dpr=false&viewport-width=true&sec-ch-ua=true&sec-ch-ua-mobile=false", "", "Client hints loaded on same-origin iframe request with feature policy."); await test_frame( "HTTPS_REMOTE_ORIGIN", "", "", "Iframe trying to set Accept-CH-Lifetime.", "/client-hints/resources/iframe-accept-ch-lifetime.html"); await test_frame( "HTTPS_REMOTE_ORIGIN", "device-memory=true&dpr=false&viewport-width=false&sec-ch-ua=false&sec-ch-ua-mobile=false", "", "Client hints loaded on cross-origin iframe request with feature policy after attempting to set independently."); })(); </script> </body> </html>
{ "pile_set_name": "Github" }
# https://www.youtube.com/watch?v=-lWf7Z8aoRU # 厦门菜市场神奇小吃,4元大肉条,没一点肥肉吃着香!5个阿姨忙晕 # Amazing street food in Xiamen farmer's market, 4 yuan meat roll, no fat meat and delicious, five worker are busy # 今天来到了厦门网红菜市场——八市! # 这里的美食众多,一时让人迈不动脚步。 # 当然了,想迈也迈不了,人太多啦。 # 好不容易挤进去,找到了在本地很有名气的五香店。 # 五香就是用豆皮包裹着猪肉、洋葱,成卷状, # 然后放入油锅炸5分钟, # 出锅后金黄诱人, # 饿的时候恨不得一口下肚! # 价格是4元一根, # 基本上从开门到营业结束,顾客都是接踵而至的。 # We came to the famous "bashi" market in Xiamen today, # There are so many of street foods here. It's hard to walk away! # Of course I can't walk even I wanted to, because it's so crowded here. # We found a famous local shop that sells "Wuxiang" (Five-spice meat roll) # Wuxiang is a pork and onion roll wrapped in tofu skin # that's deep fried for five minutes. # The color is golden brown and I can't wait to devour. # The price is 4 Yuan each, # It's always crowded throughout the day 0:00:01.880,0:00:06.280 # 福建·厦门 Xiamen, Fujian 0:00:13.760,0:00:15.840 # 今天我们到的是厦门的 We are around Bashi seafood market 0:00:15.840,0:00:17.480 # 八市海鲜市场这一边 of Xiamen today 0:00:17.480,0:00:21.320 # 这边的海鲜水产真的是让人看花了眼 There is plenty of seafood 0:00:21.320,0:00:24.840 # 各种鱼 虾 蟹啊 贝类 应有尽有 Plenty types of fish, shrimp, and shellfish 0:00:25.440,0:00:27.120 # 因为不认识 很多情况下 As we can't recognize the kinds, in many cases 0:00:27.120,0:00:30.320 # 我们都是这样 大眼瞪着小眼 we can only stare at each other awkwardly like this 0:00:34.080,0:00:36.600 # 不过我们今天不打算吃海鲜 However, we don’t plan to have seafood today 0:00:36.600,0:00:39.800 # 打算找一些比较特别的小吃吧 We plan to find some special street food 0:00:39.800,0:00:43.320 # 这边有种食物叫做 五香还挺吸引我的 There is a street food called "wuxiang" (five-spice) roll, which is quite attractive 0:00:43.320,0:00:45.240 # 看看前面有没有 Let's see if there is any ahead 0:01:11.320,0:01:13.840 # 你好 我想问一下 是这个是叫五香吗 Hello, is this called “wuxiang” (five spiced) 0:01:13.840,0:01:14.400 # 是的 Yes 0:01:14.400,0:01:16.080 # 这个是什么做的 What's that made of? 0:01:16.080,0:01:17.040 # 猪肉 洋葱 Pork, onion 0:01:17.040,0:01:18.120 # 猪肉和洋葱 Pork and onion 0:01:18.120,0:01:19.800 # 外面包的是什么 What's the wrapper outside? 0:01:19.800,0:01:20.520 # 豆皮 Tofu skin 0:01:20.520,0:01:21.260 # 多少钱 How much? 0:01:21.260,0:01:21.880 # 4块钱 4 yuan 0:01:25.120,0:01:26.320 # 4块钱 4 yuan 0:01:27.400,0:01:28.600 # 买10条 I want 10 0:01:31.040,0:01:32.800 # 来6条吧 six 0:01:41.720,0:01:44.040 # 哎呀 来6条吧 Aiya, I'll have six 0:02:15.000,0:02:16.280 # 给我拿两条 Can I have two? 0:02:16.280,0:02:16.980 # 切吗? Cut it? 0:02:16.980,0:02:18.240 # 切 Cut it 0:02:41.120,0:02:42.440 # 谢谢 Thank you 0:02:47.120,0:02:51.800 # 穿过拥挤的人潮 我买到了五香卷 Going through the crowd, I bought the spiced rolls 0:02:51.800,0:02:54.120 # 五香卷给我放进去的时候 She digged two holes on the box 0:02:54.120,0:02:56.840 # 还在盒子上面戳了两个孔 When she put the spiced rolls in 0:02:56.840,0:02:59.560 # 所以我的手能够感受到刚炸出来 So I can feel the hot air 0:02:59.560,0:03:01.760 # 五香的这种热气 of freshly fried spiced rolls 0:03:04.840,0:03:07.400 # 走了十多分钟 总算走出来了 10 minutes later, we have finally moved outside 0:03:07.400,0:03:11.040 # 我们要去尝一尝自己买的五香啦 We are going to taste the spiced rolls we ordered 0:03:30.000,0:03:32.600 # 刚才买五香的时候 旁边的阿姨说 When buying them, the auntie told me 0:03:32.600,0:03:34.880 # 这个五香在过年的时候 during Chinese New Year 0:03:34.880,0:03:36.440 # 能够卖一万条 they can sell 10,000 rolls 0:03:36.440,0:03:37.440 # 一天一万条 10,000 rolls every day 0:03:37.440,0:03:40.360 # 咱们呢 只是买了两条来解解馋 For us, we bought only two to have a taste 0:03:40.360,0:03:43.520 # 还没有打开盖子 你就能闻到这个香味 You can smell the fragrance even without opening the box 0:03:43.520,0:03:47.400 # 感觉是这种油炸的香味 还带点蒜味 Feels like the fragrance of fried food, and a bit of garlic 0:03:48.360,0:03:50.080 # 打开了 opened 0:03:53.560,0:03:56.360 # 让我们一睹尊容 Let's have a look of its appearance 0:03:58.280,0:04:02.360 # 五香看起来 颜色是偏向于深褐色的 The color of the spiced roll is kind of dark brown 0:04:02.360,0:04:04.400 # 通过它的横截面 你能够看到 Looking at the cross section, you can see 0:04:04.400,0:04:07.840 # 它里面包裹的肉馅还有洋葱 it is stuffed with meat and onion 0:04:07.840,0:04:10.360 # 它这个五香外皮是带有点褶皱的 The wrapper is a little wrinkled 0:04:10.360,0:04:14.560 # 所以说 看上去很像烧腊 烧鹅的外貌 so it looks quite similar to Cantonese BBQ, roasted goose 0:04:14.560,0:04:16.520 # 这个五香一口咬下去是这种 As you take a bite of the spiced roll 0:04:16.520,0:04:18.080 # 甜甜糯糯的口感 the mouthfeel is sweet and mashy 0:04:18.080,0:04:20.600 # 它这个甜 不是说没有咸味 It's not purely sweet without salt 0:04:20.600,0:04:22.720 # 而是甜味占了上风 but instead, it's mostly sweet 0:04:22.720,0:04:26.360 # 这种甜味是夹带着洋葱的甜味 The sweetness also contains the sweetness of onions 0:04:26.360,0:04:28.560 # 门口的小姐姐说 这里面用的肉馅 The sis at the entrance said that 0:04:28.560,0:04:29.920 # 没有一点肥的 the meat stuffing here is lean only without any fat 0:04:29.920,0:04:31.760 # 经过油炸之后 吃起来 After deep frying, 0:04:31.760,0:04:34.440 # 也不会觉得有那么油腻 it doesn't feel very greasy 0:04:38.320,0:04:40.000 # 但是吃多了 还是会觉得 You might still feel a little greasy 0:04:40.000,0:04:42.120 # 有些油腻的 if you eat too much 0:04:42.120,0:04:44.640 # 你看 咱们吃五香会觉得它有点甜 You see, we feel it is a little too sweet when we eat it 0:04:44.640,0:04:45.960 # 但是我看很多老人 However, I saw a lot of elderly people 0:04:45.960,0:04:49.000 # 都会在这个五香上 再抹一些甜辣酱 Add sweet and spicy sauce on top 0:04:49.000,0:04:52.040 # 这个口感 可能会更符合他的口味吧 They probably prefer a mouthfeel like that 0:05:09.400,0:05:11.280 # 在这里 你不能走很快 You should not walk too fast there 0:05:11.280,0:05:12.520 # 因为在不经意间 Because inadvertently 0:05:12.520,0:05:15.360 # 你可能就错过了很多的好吃的 you might have missed a lot of delicious food 0:05:29.480,0:05:32.080 # 关 注 雪 鱼 探 店 Subscribe 0:05:32.780,0:05:33.820 # 因为戴了咬合垫 As I'm wearing a bite plate 0:05:33.820,0:05:35.460 # 我小口抿的吃饭方式 the way I eat by small bites 0:05:35.460,0:05:36.760 # 受到伙伴的嘲笑 is mocked by the team 0:05:36.760,0:05:39.420 # 于是 摄影师决定亲自上阵 So, the cameraman decided to take the role 0:05:39.420,0:05:41.740 # 来说一说 它是什么样的味道 and tell how it tastes like 0:05:45.400,0:05:49.120 # 问题:什么样的感受 Question: what's the feeling? 0:05:51.600,0:05:54.020 # 黏黏糯糯的 一口下去都是肉 Sticky and mashy, full of meat in the mouth 0:05:54.600,0:05:57.460 # 听到没 甜甜糯糯的 一口下去都是肉 Did you hear that? Sticky and mashy, full of meat in the mouth 0:05:59.680,0:06:00.360 # 还有吗? Anything else? 0:06:01.880,0:06:05.060 # 不知道什么味 再给我吃一个 Can't tell the taste. Give me another one 0:06:10.780,0:06:12.240 # 再见 Goodbye
{ "pile_set_name": "Github" }
<?php /** * Class Sheep_Debug_EmailController * * @category Sheep * @package Sheep_Debug * @license Copyright: Pirate Sheep, 2016 * @link https://piratesheep.com */ class Sheep_Debug_EmailController extends Sheep_Debug_Controller_Front_Action { /** * E-mail body action */ public function getBodyAction() { if ($email = $this->_initEmail()) { $this->getResponse()->setHeader('Content-Type', $email->getIsPlain() ? 'text/plain' : 'text/html'); $this->getResponse()->setBody($email->getBody()); } } /** * Returns query references in request parameters * * @return Sheep_Debug_Model_Email */ protected function _initEmail() { $token = $this->getRequest()->getParam('token'); $index = $this->getRequest()->getParam('index'); if ($token === null || $index === null) { $this->getResponse()->setHttpResponseCode(400)->setBody('Invalid parameters'); return null; } /** @var Sheep_Debug_Model_RequestInfo $requestProfile */ $requestProfile = Mage::getModel('sheep_debug/requestInfo')->load($token, 'token'); if (!$requestProfile->getId()) { $this->getResponse()->setHttpResponseCode(404)->setBody('Request profile not found'); return null; } $emails = $requestProfile->getEmails(); if (!$emails || !($index < count($emails))) { $this->getResponse()->setHttpResponseCode(404)->setBody('E-mail not found'); return null; } return $emails[(int)$index]; } }
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); /* * This file is part of the Explicit Architecture POC, * which is created on top of the Symfony Demo application. * * (c) Herberto Graça <herberto.graca@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Acme\App\Infrastructure\Persistence\Doctrine\Type; use Doctrine\DBAL\Types\GuidType; /** * It is preferable to use the AbstractBinaryUuidType, because the querying will be faster and the space taken will * be less. * However, if you need to look at the DB and see the actual UUID there, this is the mapper you should use. */ abstract class AbstractUuidType extends GuidType { use TypeTrait; }
{ "pile_set_name": "Github" }
/* BranchIA64.h */ #ifndef __BRANCH_IA64_H #define __BRANCH_IA64_H #include "BranchTypes.h" UInt32 IA64_Convert(Byte *data, UInt32 size, UInt32 nowPos, int encoding); #endif
{ "pile_set_name": "Github" }
{ "shadowCopy": false }
{ "pile_set_name": "Github" }
-- boundary2.test -- -- db eval { -- SELECT a FROM t1 WHERE r >= 4294967295 ORDER BY a DESC -- } SELECT a FROM t1 WHERE r >= 4294967295 ORDER BY a DESC
{ "pile_set_name": "Github" }
/* * MaxentStressGTest.cpp * * Created on: Apr 19, 2016 * Author: Michael */ #include <gtest/gtest.h> #include <vector> #include <string> #include <networkit/graph/Graph.hpp> #include <networkit/viz/Point.hpp> #include <networkit/io/METISGraphReader.hpp> #include <networkit/io/METISGraphWriter.hpp> #include <networkit/graph/Graph.hpp> #include <networkit/components/ConnectedComponents.hpp> #include <networkit/viz/MaxentStress.hpp> #include <networkit/numerics/LAMG/Lamg.hpp> #include <networkit/numerics/ConjugateGradient.hpp> #include <networkit/numerics/Preconditioner/IdentityPreconditioner.hpp> #include <networkit/numerics/Preconditioner/DiagonalPreconditioner.hpp> #include <networkit/community/PLM.hpp> #include <networkit/sparsification/LocalDegreeScore.hpp> #include <networkit/sparsification/RandomEdgeScore.hpp> #include <networkit/sparsification/GlobalThresholdFilter.hpp> #include <networkit/auxiliary/Timer.hpp> #include <networkit/auxiliary/Random.hpp> #include <iostream> #include <unordered_map> #include <random> #include <networkit/viz/PivotMDS.hpp> #include <cstdio> namespace NetworKit { class MaxentStressGTest : public testing::Test {}; TEST_F(MaxentStressGTest, benchMaxentStressCoordinatesLAMG) { std::vector<std::string> graphFiles = {"input/airfoil1.graph"}; METISGraphReader reader; for (const std::string& graphFile : graphFiles) { Graph graph = reader.read(graphFile); double runtime = 0; double fullStress = 0; double maxentStress = 0; Aux::Random::setSeed(Aux::Random::integer(), false); Aux::Timer t; t.start(); PivotMDS pivotMds(graph, 2, 30); pivotMds.run(); MaxentStress maxentStressAlgo(graph, 2, pivotMds.getCoordinates(), 1, 0.001, MaxentStress::LinearSolverType::LAMG); maxentStressAlgo.run(); t.stop(); runtime = t.elapsedMicroseconds(); if (graph.numberOfNodes() < 1e5) { maxentStressAlgo.scaleLayout(); fullStress = maxentStressAlgo.fullStressMeasure(); maxentStress = maxentStressAlgo.maxentMeasure(); } runtime /= 1000; INFO(graphFile, "\t", maxentStress, "\t", fullStress, "\t", runtime); } } TEST_F(MaxentStressGTest, benchMaxentStressConjGradIdPrecAlgebraicDistance) { std::vector<std::string> graphFiles = {"input/airfoil1.graph"}; METISGraphReader reader; for (const std::string& graphFile : graphFiles) { Graph graph = reader.read(graphFile); double runtime = 0; double fullStress = 0; double maxentStress = 0; Aux::Random::setSeed(Aux::Random::integer(), false); Aux::Timer t; t.start(); MaxentStress maxentStressAlgo(graph, 2, 1, 0.001, MaxentStress::LinearSolverType::CONJUGATE_GRADIENT_IDENTITY_PRECONDITIONER, true, MaxentStress::GraphDistance::ALGEBRAIC_DISTANCE); maxentStressAlgo.run(); t.stop(); runtime = t.elapsedMicroseconds(); if (graph.numberOfNodes() < 1e5) { maxentStressAlgo.scaleLayout(); fullStress = maxentStressAlgo.fullStressMeasure(); maxentStress = maxentStressAlgo.maxentMeasure(); } runtime /= 1000; INFO(graphFile, "\t", maxentStress, "\t", fullStress, "\t", runtime); } } TEST_F(MaxentStressGTest, benchMaxentStressConjGradDiagPrecond) { std::vector<std::string> graphFiles = {"input/airfoil1.graph"}; METISGraphReader reader; for (const std::string& graphFile : graphFiles) { Graph graph = reader.read(graphFile); double runtime = 0; double fullStress = 0; double maxentStress = 0; Aux::Random::setSeed(Aux::Random::integer(), false); Aux::Timer t; t.start(); MaxentStress maxentStressAlgo(graph, 2, 1, 0.001, MaxentStress::LinearSolverType::CONJUGATE_GRADIENT_DIAGONAL_PRECONDITIONER); maxentStressAlgo.run(); t.stop(); runtime = t.elapsedMicroseconds(); if (graph.numberOfNodes() < 1e5) { maxentStressAlgo.scaleLayout(); fullStress = maxentStressAlgo.fullStressMeasure(); maxentStress = maxentStressAlgo.maxentMeasure(); } runtime /= 1000; INFO(graphFile, "\t", maxentStress, "\t", fullStress, "\t", runtime); } } TEST_F(MaxentStressGTest, benchMaxentStressCoordConjGradIdPrecond) { std::vector<std::string> graphFiles = {"input/airfoil1.graph"}; METISGraphReader reader; for (const std::string& graphFile : graphFiles) { Graph graph = reader.read(graphFile); double runtime = 0; double fullStress = 0; double maxentStress = 0; Aux::Random::setSeed(Aux::Random::integer(), false); Aux::Timer t; t.start(); PivotMDS pivotMds(graph, 2, 30); pivotMds.run(); MaxentStress maxentStressAlgo(graph, 2, pivotMds.getCoordinates(), 1, 0.001, MaxentStress::LinearSolverType::CONJUGATE_GRADIENT_IDENTITY_PRECONDITIONER, false, MaxentStress::GraphDistance::ALGEBRAIC_DISTANCE); maxentStressAlgo.run(); t.stop(); runtime = t.elapsedMicroseconds(); if (graph.numberOfNodes() < 1e5) { maxentStressAlgo.scaleLayout(); fullStress = maxentStressAlgo.fullStressMeasure(); maxentStress = maxentStressAlgo.maxentMeasure(); } runtime /= 1000; INFO(graphFile, "\t", maxentStress, "\t", fullStress, "\t", runtime); } } } /* namespace NetworKit */
{ "pile_set_name": "Github" }
// -*- C++ -*- //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <vector> // class vector // bool empty() const noexcept; // UNSUPPORTED: c++98, c++03, c++11, c++14, c++17 // UNSUPPORTED: clang-3.3, clang-3.4, clang-3.5, clang-3.6, clang-3.7, clang-3.8 #include <vector> #include "test_macros.h" int main () { std::vector<bool> c; c.empty(); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}} }
{ "pile_set_name": "Github" }
//: operators/Casting.java package operators; /* Added by Eclipse.py */ public class Casting { public static void main(String[] args) { int i = 200; long lng = (long)i; lng = i; // "Widening," so cast not really required long lng2 = (long)200; lng2 = 200; // A "narrowing conversion": i = (int)lng2; // Cast required } } ///:~
{ "pile_set_name": "Github" }
/* * Copyright (c) 2019, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import Foundation public class SceneRange: RangeObject, Codable { public var firstScene: Address { return range.lowerBound } public var lastScene: Address { return range.upperBound } // MARK: - Codable private enum CodingKeys: String, CodingKey { case firstScene case lastScene } public required convenience init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let firstSceneAsString = try container.decode(String.self, forKey: .firstScene) let lastSceneAsString = try container.decode(String.self, forKey: .lastScene) guard let firstScene = Scene(hex: firstSceneAsString) else { throw DecodingError.dataCorruptedError(forKey: .firstScene, in: container, debugDescription: "Scene must be 4-character hexadecimal string") } guard let lastScene = Scene(hex: lastSceneAsString) else { throw DecodingError.dataCorruptedError(forKey: .lastScene, in: container, debugDescription: "Scene must be 4-character hexadecimal string") } self.init(from: firstScene, to: lastScene) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(range.lowerBound.hex, forKey: .firstScene) try container.encode(range.upperBound.hex, forKey: .lastScene) } }
{ "pile_set_name": "Github" }
//Copyright 2017 Ryan Wick //This file is part of Bandage //Bandage is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. //Bandage is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. //You should have received a copy of the GNU General Public License //along with Bandage. If not, see <http://www.gnu.org/licenses/>. #ifndef DEBRUIJNEDGE_H #define DEBRUIJNEDGE_H #include "../ogdf/basic/Graph.h" #include "debruijnnode.h" class GraphicsItemEdge; class DeBruijnEdge { public: //CREATORS DeBruijnEdge(DeBruijnNode * startingNode, DeBruijnNode * endingNode); //ACCESSORS bool isStartingNode(DeBruijnNode * node) const {return node == m_startingNode;} DeBruijnNode * getStartingNode() const {return m_startingNode;} DeBruijnNode * getEndingNode() const {return m_endingNode;} GraphicsItemEdge * getGraphicsItemEdge() const {return m_graphicsItemEdge;} DeBruijnEdge * getReverseComplement() const {return m_reverseComplement;} bool isDrawn() const {return m_drawn;} int getOverlap() const {return m_overlap;} EdgeOverlapType getOverlapType() const {return m_overlapType;} DeBruijnNode * getOtherNode(const DeBruijnNode * node) const; bool testExactOverlap(int overlap) const; void tracePaths(bool forward, int stepsRemaining, std::vector<std::vector<DeBruijnNode *> > * allPaths, DeBruijnNode * startingNode, std::vector<DeBruijnNode *> pathSoFar = std::vector<DeBruijnNode *>()) const; bool leadsOnlyToNode(bool forward, int stepsRemaining, DeBruijnNode * target, std::vector<DeBruijnNode *> pathSoFar, bool includeReverseComplement) const; QByteArray getGfaLinkLine() const; bool isPositiveEdge() const; bool isNegativeEdge() const {return !isPositiveEdge();} bool isOwnReverseComplement() const {return this == getReverseComplement();} static bool compareEdgePointers(DeBruijnEdge * a, DeBruijnEdge * b); //MODIFERS void setGraphicsItemEdge(GraphicsItemEdge * gie) {m_graphicsItemEdge = gie;} void setReverseComplement(DeBruijnEdge * rc) {m_reverseComplement = rc;} void setOverlap(int ol) {m_overlap = ol;} void setOverlapType(EdgeOverlapType olt) {m_overlapType = olt;} void reset() {m_graphicsItemEdge = 0; m_drawn = false;} void determineIfDrawn() {m_drawn = edgeIsVisible();} void setExactOverlap(int overlap) {m_overlap = overlap; m_overlapType = EXACT_OVERLAP;} void autoDetermineExactOverlap(); void addToOgdfGraph(ogdf::Graph * ogdfGraph, ogdf::EdgeArray<double> * edgeArray) const; private: DeBruijnNode * m_startingNode; DeBruijnNode * m_endingNode; GraphicsItemEdge * m_graphicsItemEdge; DeBruijnEdge * m_reverseComplement; bool m_drawn; EdgeOverlapType m_overlapType; int m_overlap; bool edgeIsVisible() const; int timesNodeInPath(DeBruijnNode * node, std::vector<DeBruijnNode *> * path) const; std::vector<DeBruijnEdge *> findNextEdgesInPath(DeBruijnNode * nextNode, bool forward) const; }; #endif // DEBRUIJNEDGE_H
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <string>Alabama</string> <string>Alaska</string> <string>Arizona</string> <string>Arkansas</string> <string>California</string> <string>Colorado</string> <string>Connecticut</string> <string>Delaware</string> <string>Delaware</string> <string>Delaware</string> <string>Florida</string> <string>Georgia</string> <string>Hawaii</string> <string>Hawaii</string> <string>Hawaii</string> <string>Idaho</string> <string>Illinois</string> <string>Indiana</string> <string>Iowa</string> <string>Kansas</string> <string>Kentucky</string> <string>Louisiana</string> <string>Maine</string> <string>Maryland</string> <string>Maryland</string> <string>massachusettes</string> <string>Michigan</string> <string>Michigan</string> <string>Minnesota</string> <string>Mississippi</string> <string>Missouri</string> <string>Montana</string> <string>Nebraska</string> <string>Nevada</string> <string>New Hampshire</string> <string>New Jersey</string> <string>New Jersey</string> <string>New Jersey</string> <string>New Mexico</string> <string>New York</string> <string>North Carolina</string> <string>North Dakota</string> <string>Ohio</string> <string>Oklahoma</string> <string>Oregon</string> <string>Pennsylvania</string> <string>Rhode Island</string> <string>Rhode Island</string> <string>South Carolina</string> <string>South Dakota</string> <string>Tennessee</string> <string>Texas</string> <string>Utah</string> <string>Vermont</string> <string>Virginia</string> <string>Washington</string> <string>Washington D.C.</string> <string>Washington D.C.</string> <string>West Virginia</string> <string>Wisconsin</string> <string>Wyoming</string> </array> </plist>
{ "pile_set_name": "Github" }
#include "ling_common.h" #include "console.h" #include "outlet.h" #include <stdlib.h> #include <stdbool.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #define constwrite1(s) write(1, (s), sizeof(s)-1) static outlet_t *attached_outlet; struct termios saved_termios; bool console_available = false; void console_restore_termios(void) { tcsetattr(STDIN_FILENO, TCSANOW, &saved_termios); } void console_init(void) { int ret; int flag = O_NONBLOCK; fcntl(STDIN_FILENO, F_SETFL, flag); console_available = true; /* switch TTY to raw mode */ ret = tcgetattr(STDIN_FILENO, &saved_termios); if (ret) return; struct termios raw_termios = saved_termios; cfmakeraw(&raw_termios); raw_termios.c_oflag |= OPOST; ret = tcsetattr(STDIN_FILENO, TCSANOW, &raw_termios); if (ret) return; /* don't forget to clean up */ atexit(console_restore_termios); } int console_is_initialized(void) { return console_available; } void console_attach(outlet_t *ol) { attached_outlet = ol; } void console_detach(outlet_t *ol) { debug("%s()\n", __FUNCTION__); attached_outlet = NULL; } int console_write(char *buf, int len) { return write(STDOUT_FILENO, buf, len); } int ser_cons_write(char *buf, int len) { return len; } int console_do_pending(void) { char buf[1]; int total = 0; while (read(STDIN_FILENO, buf, 1) == 1) { if (attached_outlet) outlet_pass_new_data(attached_outlet, (uint8_t *)buf, 1); total++; } return total; } #if LING_DEBUG #include <stdarg.h> int debug(const char *fmt, ...) { va_list ap; va_start(ap, fmt); int ret = vfprintf(stderr, fmt, ap); va_end(ap); return ret; } #endif
{ "pile_set_name": "Github" }
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/CoreMediaStream.framework/CoreMediaStream */ #import <CoreMediaStream/CoreMediaStream-Structs.h> #import <CoreMediaStream/XXUnknownSuperclass.h> @interface MSObjectQueue : XXUnknownSuperclass { @private sqlite3 *_db; // 4 = 0x4 CFDictionaryRef _statements; // 8 = 0x8 } @property(readonly, assign) long long count; // G=0x20005; - (void)commitObjectsWrappers:(id)wrappers; // 0x20d55 - (void)commitErrorCountsForObjectWrappers:(id)objectWrappers; // 0x20b25 - (void)removeObjectWrappersFromQueue:(id)queue; // 0x20959 - (id)smallestObjectWrappersTargetTotalSize:(long long)size maxCount:(long long)count; // 0x20729 - (id)objectWrappersWithZeroSizeMaxCount:(long long)zeroSizeMaxCount; // 0x2057d - (id)allObjectWrappersMaxCount:(long long)count; // 0x203d1 - (id)_objectWrapperFromQueueQuery:(sqlite3_stmt *)queueQuery outSize:(long long *)size; // 0x202c1 - (void)appendObjectWrappers:(id)wrappers; // 0x2004d // declared property getter: - (long long)count; // 0x20005 - (sqlite3_stmt *)_statementLabel:(id)label query:(const char *)query; // 0x1ff4d - (void)dealloc; // 0x1fe91 - (id)initWithPath:(id)path; // 0x1fc15 @end
{ "pile_set_name": "Github" }
[ { "geometry": { "type": "Polygon", "coordinates": [ [ [ -79.46205139160156, 43.63532972467448 ], [ -79.46205139160156, 43.642535173141056 ], [ -79.4556999206543, 43.642535173141056 ], [ -79.4556999206543, 43.63532972467448 ], [ -79.46205139160156, 43.63532972467448 ] ] ] }, "type": "Feature", "properties": { "position": "bottom" }, "source": "zones", "state": {} }, { "geometry": { "type": "Polygon", "coordinates": [ [ [ -79.46462631225586, 43.64750394449095 ], [ -79.46462631225586, 43.65458373355483 ], [ -79.45793151855469, 43.65458373355483 ], [ -79.45793151855469, 43.64750394449095 ], [ -79.46462631225586, 43.64750394449095 ] ] ] }, "type": "Feature", "properties": { "position": "middle" }, "source": "zones", "state": {} }, { "geometry": { "type": "Polygon", "coordinates": [ [ [ -79.46788787841797, 43.655577321374295 ], [ -79.46788787841797, 43.66290452383666 ], [ -79.45700883865356, 43.66290452383666 ], [ -79.45700883865356, 43.655577321374295 ], [ -79.46788787841797, 43.655577321374295 ] ] ] }, "type": "Feature", "properties": { "position": "top" }, "source": "zones", "state": {} } ]
{ "pile_set_name": "Github" }
/** * Copyright (c) 2017 Anup Patel. * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * @file gpio-power.c * @author Anup Patel (anup@brainfault.org) * @brief GPIO Power Slave Emulator. */ #include <vmm_error.h> #include <vmm_stdio.h> #include <vmm_heap.h> #include <vmm_modules.h> #include <vmm_devemu.h> #undef DEBUG #ifdef DEBUG #define DPRINTF(msg...) vmm_printf(msg) #else #define DPRINTF(msg...) #endif #define MODULE_DESC "GPIO Power Emulator" #define MODULE_AUTHOR "Anup Patel" #define MODULE_LICENSE "GPL" #define MODULE_IPRIORITY 0 #define MODULE_INIT gpio_power_emulator_init #define MODULE_EXIT gpio_power_emulator_exit enum gpio_power_sample_type { GPIO_POWER_SAMPLE_EDGE_FALLING = 0, GPIO_POWER_SAMPLE_EDGE_RISING = 1, }; struct gpio_power_state { struct vmm_guest *guest; vmm_spinlock_t lock; enum gpio_power_sample_type sample_type; u32 in_data; u32 in_irq[2]; }; static int gpio_power_emulator_reset(struct vmm_emudev *edev) { struct gpio_power_state *s = edev->priv; vmm_spin_lock(&s->lock); s->in_data = 0; vmm_spin_unlock(&s->lock); return VMM_OK; } /* Process IRQ asserted in device emulation framework */ static void gpio_power_irq_handle(u32 irq, int cpu, int level, void *opaque) { u32 mask; int i, line; bool trigger = FALSE; struct gpio_power_state *s = opaque; DPRINTF("%s: irq=%d cpu=%d level=%d\n", __func__, irq, cpu, level); line = -1; for (i = 0; i < 2; i++) { if (s->in_irq[i] == irq) { line = i; break; } } if (line == -1) { return; } mask = 1 << line; vmm_spin_lock(&s->lock); switch (s->sample_type) { case GPIO_POWER_SAMPLE_EDGE_FALLING: if ((s->in_data & mask) && !level) trigger = TRUE; break; case GPIO_POWER_SAMPLE_EDGE_RISING: if (!(s->in_data & mask) && level) trigger = TRUE; break; default: break; }; s->in_data &= ~mask; s->in_data |= (level) ? mask : 0x0; vmm_spin_unlock(&s->lock); if (trigger) { switch (line) { case 0: vmm_manager_guest_reboot_request(s->guest); break; case 1: vmm_manager_guest_shutdown_request(s->guest); break; default: break; }; } } static struct vmm_devemu_irqchip gpio_power_irqchip = { .name = "GPIO_POWER", .handle = gpio_power_irq_handle, }; static int gpio_power_emulator_probe(struct vmm_guest *guest, struct vmm_emudev *edev, const struct vmm_devtree_nodeid *eid) { int rc = VMM_OK; const char *str; struct gpio_power_state *s; s = vmm_zalloc(sizeof(struct gpio_power_state)); if (!s) { rc = VMM_EFAIL; goto gpio_power_emulator_probe_done; } rc = vmm_devtree_read_u32_array(edev->node, "in_irq", s->in_irq, array_size(s->in_irq)); if (rc) { goto gpio_power_emulator_probe_freestate_failed; } s->guest = guest; INIT_SPIN_LOCK(&s->lock); rc = vmm_devtree_read_string(edev->node, "sample_type", &str); if (rc) { goto gpio_power_emulator_probe_freestate_failed; } if (!strcmp(str, "edge-falling")) { s->sample_type = GPIO_POWER_SAMPLE_EDGE_FALLING; } else if (!strcmp(str, "edge-rising")) { s->sample_type = GPIO_POWER_SAMPLE_EDGE_RISING; } else { rc = VMM_EINVALID; goto gpio_power_emulator_probe_freestate_failed; } vmm_devemu_register_irqchip(guest, s->in_irq[0], &gpio_power_irqchip, s); vmm_devemu_register_irqchip(guest, s->in_irq[1], &gpio_power_irqchip, s); edev->priv = s; goto gpio_power_emulator_probe_done; gpio_power_emulator_probe_freestate_failed: vmm_free(s); gpio_power_emulator_probe_done: return rc; } static int gpio_power_emulator_remove(struct vmm_emudev *edev) { struct gpio_power_state *s = edev->priv; if (!s) { return VMM_EFAIL; } vmm_devemu_unregister_irqchip(s->guest, s->in_irq[0], &gpio_power_irqchip, s); vmm_devemu_unregister_irqchip(s->guest, s->in_irq[1], &gpio_power_irqchip, s); vmm_free(s); edev->priv = NULL; return VMM_OK; } static struct vmm_devtree_nodeid gpio_power_emuid_table[] = { { .type = "gpio-slave", .compatible = "gpio-power", }, { /* end of list */ }, }; static struct vmm_emulator gpio_power_emulator = { .name = "gpio-power", .match_table = gpio_power_emuid_table, .endian = VMM_DEVEMU_NATIVE_ENDIAN, .probe = gpio_power_emulator_probe, .reset = gpio_power_emulator_reset, .remove = gpio_power_emulator_remove, }; static int __init gpio_power_emulator_init(void) { return vmm_devemu_register_emulator(&gpio_power_emulator); } static void __exit gpio_power_emulator_exit(void) { vmm_devemu_unregister_emulator(&gpio_power_emulator); } VMM_DECLARE_MODULE(MODULE_DESC, MODULE_AUTHOR, MODULE_LICENSE, MODULE_IPRIORITY, MODULE_INIT, MODULE_EXIT);
{ "pile_set_name": "Github" }
# $NetBSD: options.mk,v 1.2 2020/03/26 11:31:48 nia Exp $ PKG_OPTIONS_VAR= PKG_OPTIONS.netcdf-fortran PKG_SUPPORTED_OPTIONS= f90 .include "../../mk/bsd.options.mk" PLIST_VARS+= f90 .if !empty(PKG_OPTIONS:Mf90) USE_LANGUAGES+= fortran PLIST.f90= yes .else CONFIGURE_ARGS+= --disable-f90 .endif
{ "pile_set_name": "Github" }
/* * Copyright (C) STMicroelectronics SA 2015 * Authors: Arnaud Pouliquen <arnaud.pouliquen@st.com> * for STMicroelectronics. * License terms: GNU General Public License (GPL), version 2 */ #include <linux/io.h> #include <linux/module.h> #include <linux/regmap.h> #include <linux/reset.h> #include <linux/mfd/syscon.h> #include <sound/soc.h> #include <sound/soc-dapm.h> /* DAC definitions */ /* stih407 DAC registers */ /* sysconf 5041: Audio-Gue-Control */ #define STIH407_AUDIO_GLUE_CTRL 0x000000A4 /* sysconf 5042: Audio-DAC-Control */ #define STIH407_AUDIO_DAC_CTRL 0x000000A8 /* DAC definitions */ #define STIH407_DAC_SOFTMUTE 0x0 #define STIH407_DAC_STANDBY_ANA 0x1 #define STIH407_DAC_STANDBY 0x2 #define STIH407_DAC_SOFTMUTE_MASK BIT(STIH407_DAC_SOFTMUTE) #define STIH407_DAC_STANDBY_ANA_MASK BIT(STIH407_DAC_STANDBY_ANA) #define STIH407_DAC_STANDBY_MASK BIT(STIH407_DAC_STANDBY) /* SPDIF definitions */ #define SPDIF_BIPHASE_ENABLE 0x6 #define SPDIF_BIPHASE_IDLE 0x7 #define SPDIF_BIPHASE_ENABLE_MASK BIT(SPDIF_BIPHASE_ENABLE) #define SPDIF_BIPHASE_IDLE_MASK BIT(SPDIF_BIPHASE_IDLE) enum { STI_SAS_DAI_SPDIF_OUT, STI_SAS_DAI_ANALOG_OUT, }; static const struct reg_default stih407_sas_reg_defaults[] = { { STIH407_AUDIO_DAC_CTRL, 0x000000000 }, { STIH407_AUDIO_GLUE_CTRL, 0x00000040 }, }; struct sti_dac_audio { struct regmap *regmap; struct regmap *virt_regmap; struct regmap_field **field; struct reset_control *rst; int mclk; }; struct sti_spdif_audio { struct regmap *regmap; struct regmap_field **field; int mclk; }; /* device data structure */ struct sti_sas_dev_data { const struct regmap_config *regmap; const struct snd_soc_dai_ops *dac_ops; /* DAC function callbacks */ const struct snd_soc_dapm_widget *dapm_widgets; /* dapms declaration */ const int num_dapm_widgets; /* dapms declaration */ const struct snd_soc_dapm_route *dapm_routes; /* route declaration */ const int num_dapm_routes; /* route declaration */ }; /* driver data structure */ struct sti_sas_data { struct device *dev; const struct sti_sas_dev_data *dev_data; struct sti_dac_audio dac; struct sti_spdif_audio spdif; }; /* Read a register from the sysconf reg bank */ static int sti_sas_read_reg(void *context, unsigned int reg, unsigned int *value) { struct sti_sas_data *drvdata = context; int status; u32 val; status = regmap_read(drvdata->dac.regmap, reg, &val); *value = (unsigned int)val; return status; } /* Read a register from the sysconf reg bank */ static int sti_sas_write_reg(void *context, unsigned int reg, unsigned int value) { struct sti_sas_data *drvdata = context; int status; status = regmap_write(drvdata->dac.regmap, reg, value); return status; } static int sti_sas_init_sas_registers(struct snd_soc_codec *codec, struct sti_sas_data *data) { int ret; /* * DAC and SPDIF are activated by default * put them in IDLE to save power */ /* Initialise bi-phase formatter to disabled */ ret = snd_soc_update_bits(codec, STIH407_AUDIO_GLUE_CTRL, SPDIF_BIPHASE_ENABLE_MASK, 0); if (!ret) /* Initialise bi-phase formatter idle value to 0 */ ret = snd_soc_update_bits(codec, STIH407_AUDIO_GLUE_CTRL, SPDIF_BIPHASE_IDLE_MASK, 0); if (ret < 0) { dev_err(codec->dev, "Failed to update SPDIF registers\n"); return ret; } /* Init DAC configuration */ /* init configuration */ ret = snd_soc_update_bits(codec, STIH407_AUDIO_DAC_CTRL, STIH407_DAC_STANDBY_MASK, STIH407_DAC_STANDBY_MASK); if (!ret) ret = snd_soc_update_bits(codec, STIH407_AUDIO_DAC_CTRL, STIH407_DAC_STANDBY_ANA_MASK, STIH407_DAC_STANDBY_ANA_MASK); if (!ret) ret = snd_soc_update_bits(codec, STIH407_AUDIO_DAC_CTRL, STIH407_DAC_SOFTMUTE_MASK, STIH407_DAC_SOFTMUTE_MASK); if (ret < 0) { dev_err(codec->dev, "Failed to update DAC registers\n"); return ret; } return ret; } /* * DAC */ static int sti_sas_dac_set_fmt(struct snd_soc_dai *dai, unsigned int fmt) { /* Sanity check only */ if ((fmt & SND_SOC_DAIFMT_MASTER_MASK) != SND_SOC_DAIFMT_CBS_CFS) { dev_err(dai->codec->dev, "%s: ERROR: Unsupporter master mask 0x%x\n", __func__, fmt & SND_SOC_DAIFMT_MASTER_MASK); return -EINVAL; } return 0; } static const struct snd_soc_dapm_widget stih407_sas_dapm_widgets[] = { SND_SOC_DAPM_OUT_DRV("DAC standby ana", STIH407_AUDIO_DAC_CTRL, STIH407_DAC_STANDBY_ANA, 1, NULL, 0), SND_SOC_DAPM_DAC("DAC standby", "dac_p", STIH407_AUDIO_DAC_CTRL, STIH407_DAC_STANDBY, 1), SND_SOC_DAPM_OUTPUT("DAC Output"), }; static const struct snd_soc_dapm_route stih407_sas_route[] = { {"DAC Output", NULL, "DAC standby ana"}, {"DAC standby ana", NULL, "DAC standby"}, }; static int stih407_sas_dac_mute(struct snd_soc_dai *dai, int mute, int stream) { struct snd_soc_codec *codec = dai->codec; if (mute) { return snd_soc_update_bits(codec, STIH407_AUDIO_DAC_CTRL, STIH407_DAC_SOFTMUTE_MASK, STIH407_DAC_SOFTMUTE_MASK); } else { return snd_soc_update_bits(codec, STIH407_AUDIO_DAC_CTRL, STIH407_DAC_SOFTMUTE_MASK, 0); } } /* * SPDIF */ static int sti_sas_spdif_set_fmt(struct snd_soc_dai *dai, unsigned int fmt) { if ((fmt & SND_SOC_DAIFMT_MASTER_MASK) != SND_SOC_DAIFMT_CBS_CFS) { dev_err(dai->codec->dev, "%s: ERROR: Unsupporter master mask 0x%x\n", __func__, fmt & SND_SOC_DAIFMT_MASTER_MASK); return -EINVAL; } return 0; } /* * sti_sas_spdif_trigger: * Trigger function is used to ensure that BiPhase Formater is disabled * before CPU dai is stopped. * This is mandatory to avoid that BPF is stalled */ static int sti_sas_spdif_trigger(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: return snd_soc_update_bits(codec, STIH407_AUDIO_GLUE_CTRL, SPDIF_BIPHASE_ENABLE_MASK, SPDIF_BIPHASE_ENABLE_MASK); case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: return snd_soc_update_bits(codec, STIH407_AUDIO_GLUE_CTRL, SPDIF_BIPHASE_ENABLE_MASK, 0); default: return -EINVAL; } } static bool sti_sas_volatile_register(struct device *dev, unsigned int reg) { if (reg == STIH407_AUDIO_GLUE_CTRL) return true; return false; } /* * CODEC DAIS */ /* * sti_sas_set_sysclk: * get MCLK input frequency to check that MCLK-FS ratio is coherent */ static int sti_sas_set_sysclk(struct snd_soc_dai *dai, int clk_id, unsigned int freq, int dir) { struct snd_soc_codec *codec = dai->codec; struct sti_sas_data *drvdata = dev_get_drvdata(codec->dev); if (dir == SND_SOC_CLOCK_OUT) return 0; if (clk_id != 0) return -EINVAL; switch (dai->id) { case STI_SAS_DAI_SPDIF_OUT: drvdata->spdif.mclk = freq; break; case STI_SAS_DAI_ANALOG_OUT: drvdata->dac.mclk = freq; break; } return 0; } static int sti_sas_prepare(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; struct sti_sas_data *drvdata = dev_get_drvdata(codec->dev); struct snd_pcm_runtime *runtime = substream->runtime; switch (dai->id) { case STI_SAS_DAI_SPDIF_OUT: if ((drvdata->spdif.mclk / runtime->rate) != 128) { dev_err(codec->dev, "unexpected mclk-fs ratio\n"); return -EINVAL; } break; case STI_SAS_DAI_ANALOG_OUT: if ((drvdata->dac.mclk / runtime->rate) != 256) { dev_err(codec->dev, "unexpected mclk-fs ratio\n"); return -EINVAL; } break; } return 0; } static const struct snd_soc_dai_ops stih407_dac_ops = { .set_fmt = sti_sas_dac_set_fmt, .mute_stream = stih407_sas_dac_mute, .prepare = sti_sas_prepare, .set_sysclk = sti_sas_set_sysclk, }; static const struct regmap_config stih407_sas_regmap = { .reg_bits = 32, .val_bits = 32, .fast_io = true, .max_register = STIH407_AUDIO_DAC_CTRL, .reg_defaults = stih407_sas_reg_defaults, .num_reg_defaults = ARRAY_SIZE(stih407_sas_reg_defaults), .volatile_reg = sti_sas_volatile_register, .cache_type = REGCACHE_RBTREE, .reg_read = sti_sas_read_reg, .reg_write = sti_sas_write_reg, }; static const struct sti_sas_dev_data stih407_data = { .regmap = &stih407_sas_regmap, .dac_ops = &stih407_dac_ops, .dapm_widgets = stih407_sas_dapm_widgets, .num_dapm_widgets = ARRAY_SIZE(stih407_sas_dapm_widgets), .dapm_routes = stih407_sas_route, .num_dapm_routes = ARRAY_SIZE(stih407_sas_route), }; static struct snd_soc_dai_driver sti_sas_dai[] = { { .name = "sas-dai-spdif-out", .id = STI_SAS_DAI_SPDIF_OUT, .playback = { .stream_name = "spdif_p", .channels_min = 2, .channels_max = 2, .rates = SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_64000 | SNDRV_PCM_RATE_88200 | SNDRV_PCM_RATE_96000 | SNDRV_PCM_RATE_192000, .formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S32_LE, }, .ops = (struct snd_soc_dai_ops[]) { { .set_fmt = sti_sas_spdif_set_fmt, .trigger = sti_sas_spdif_trigger, .set_sysclk = sti_sas_set_sysclk, .prepare = sti_sas_prepare, } }, }, { .name = "sas-dai-dac", .id = STI_SAS_DAI_ANALOG_OUT, .playback = { .stream_name = "dac_p", .channels_min = 2, .channels_max = 2, .rates = SNDRV_PCM_RATE_8000_48000, .formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S32_LE, }, }, }; #ifdef CONFIG_PM_SLEEP static int sti_sas_resume(struct snd_soc_codec *codec) { struct sti_sas_data *drvdata = dev_get_drvdata(codec->dev); return sti_sas_init_sas_registers(codec, drvdata); } #else #define sti_sas_resume NULL #endif static int sti_sas_codec_probe(struct snd_soc_codec *codec) { struct sti_sas_data *drvdata = dev_get_drvdata(codec->dev); int ret; ret = sti_sas_init_sas_registers(codec, drvdata); return ret; } static struct snd_soc_codec_driver sti_sas_driver = { .probe = sti_sas_codec_probe, .resume = sti_sas_resume, }; static const struct of_device_id sti_sas_dev_match[] = { { .compatible = "st,stih407-sas-codec", .data = &stih407_data, }, {}, }; static int sti_sas_driver_probe(struct platform_device *pdev) { struct device_node *pnode = pdev->dev.of_node; struct sti_sas_data *drvdata; const struct of_device_id *of_id; /* Allocate device structure */ drvdata = devm_kzalloc(&pdev->dev, sizeof(struct sti_sas_data), GFP_KERNEL); if (!drvdata) return -ENOMEM; /* Populate data structure depending on compatibility */ of_id = of_match_node(sti_sas_dev_match, pnode); if (!of_id->data) { dev_err(&pdev->dev, "data associated to device is missing\n"); return -EINVAL; } drvdata->dev_data = (struct sti_sas_dev_data *)of_id->data; /* Initialise device structure */ drvdata->dev = &pdev->dev; /* Request the DAC & SPDIF registers memory region */ drvdata->dac.virt_regmap = devm_regmap_init(&pdev->dev, NULL, drvdata, drvdata->dev_data->regmap); if (IS_ERR(drvdata->dac.virt_regmap)) { dev_err(&pdev->dev, "audio registers not enabled\n"); return PTR_ERR(drvdata->dac.virt_regmap); } /* Request the syscon region */ drvdata->dac.regmap = syscon_regmap_lookup_by_phandle(pnode, "st,syscfg"); if (IS_ERR(drvdata->dac.regmap)) { dev_err(&pdev->dev, "syscon registers not available\n"); return PTR_ERR(drvdata->dac.regmap); } drvdata->spdif.regmap = drvdata->dac.regmap; sti_sas_dai[STI_SAS_DAI_ANALOG_OUT].ops = drvdata->dev_data->dac_ops; /* Set dapms*/ sti_sas_driver.component_driver.dapm_widgets = drvdata->dev_data->dapm_widgets; sti_sas_driver.component_driver.num_dapm_widgets = drvdata->dev_data->num_dapm_widgets; sti_sas_driver.component_driver.dapm_routes = drvdata->dev_data->dapm_routes; sti_sas_driver.component_driver.num_dapm_routes = drvdata->dev_data->num_dapm_routes; /* Store context */ dev_set_drvdata(&pdev->dev, drvdata); return snd_soc_register_codec(&pdev->dev, &sti_sas_driver, sti_sas_dai, ARRAY_SIZE(sti_sas_dai)); } static int sti_sas_driver_remove(struct platform_device *pdev) { snd_soc_unregister_codec(&pdev->dev); return 0; } static struct platform_driver sti_sas_platform_driver = { .driver = { .name = "sti-sas-codec", .of_match_table = sti_sas_dev_match, }, .probe = sti_sas_driver_probe, .remove = sti_sas_driver_remove, }; module_platform_driver(sti_sas_platform_driver); MODULE_DESCRIPTION("audio codec for STMicroelectronics sti platforms"); MODULE_AUTHOR("Arnaud.pouliquen@st.com"); MODULE_LICENSE("GPL v2");
{ "pile_set_name": "Github" }
/** * * This package contains interfaces and classes for manipulating Java beans. * It is used by most other Spring packages. * * <p>A BeanWrapper object may be used to set and get bean properties, * singly or in bulk. * * <p>The classes in this package are discussed in Chapter 11 of * <a href="http://www.amazon.com/exec/obidos/tg/detail/-/0764543857/">Expert One-On-One J2EE Design and Development</a> * by Rod Johnson (Wrox, 2002). * */ package org.springframework.beans;
{ "pile_set_name": "Github" }
'use strict'; // https://github.com/tc39/proposal-string-pad-start-end var $export = require('./_export') , $pad = require('./_string-pad'); $export($export.P, 'String', { padEnd: function padEnd(maxLength /*, fillString = ' ' */){ return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); } });
{ "pile_set_name": "Github" }
/* * This file is part of WebLookAndFeel library. * * WebLookAndFeel library is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WebLookAndFeel library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with WebLookAndFeel library. If not, see <http://www.gnu.org/licenses/>. */ package com.alee.utils.swing.menu; import com.alee.api.annotations.NotNull; import com.alee.api.annotations.Nullable; import com.alee.api.resource.ClassResource; import com.alee.api.resource.FileResource; import com.alee.api.resource.Resource; import com.alee.api.resource.UrlResource; import com.alee.laf.menu.*; import com.alee.managers.hotkey.HotkeyData; import com.alee.managers.language.LM; import com.alee.managers.style.StyleId; import com.alee.utils.ImageUtils; import com.alee.utils.TextUtils; import com.alee.utils.UtilityException; import com.alee.utils.swing.UnselectableButtonGroup; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.io.File; import java.net.URL; /** * Base class for custom menu generators. * Menu generators shorten various menus creation code and make it much more convenient to read and support. * * There are implementations for next menu types: * {@link WebMenuBar} - {@link MenuBarGenerator} * {@link WebMenu} - {@link MenuGenerator} * {@link WebPopupMenu} - {@link PopupMenuGenerator} * * @param <C> menu component type * @author Mikle Garin * @see MenuBarGenerator * @see MenuGenerator * @see PopupMenuGenerator */ public abstract class AbstractMenuGenerator<C extends JComponent> { /** * Default constants used within generator methods. */ protected static final StyleId defaultStyleId = StyleId.auto; protected static final Object defaultIcon = null; protected static final HotkeyData defaultHotkey = null; protected static final boolean defaultEnabled = true; protected static final ActionListener defaultAction = null; /** * Class near which menu icons are placed. * In case it is null path is used as file system path. */ @Nullable protected Class nearClass; /** * Path to menu icons folder. * It is used as path relative to class in case nearClass variable is not null. */ @Nullable protected String path; /** * Menu icons format. */ @Nullable protected String extension; /** * Menu language key prefix. */ @Nullable protected String languagePrefix; /** * Buttons grouping. */ @Nullable protected UnselectableButtonGroup group; /** * Menu {@link JComponent}. */ @NotNull protected final C menu; /** * Constructs new menu generator with the specified menu component. * * @param menu base menu component */ public AbstractMenuGenerator ( @NotNull final C menu ) { this.menu = menu; } /** * Returns class near which menu icons are placed. * * @return class near which menu icons are placed */ @Nullable public Class getNearClass () { return nearClass; } /** * Sets class near which menu icons are placed. * * @param nearClass class near which menu icons are placed */ public void setNearClass ( @Nullable final Class nearClass ) { this.nearClass = nearClass; } /** * Returns path to menu icons folder relative to class. * * @return path to menu icons folder relative to class */ @Nullable public String getPath () { return path; } /** * Sets path to menu icons folder relative to class. * * @param path path to menu icons folder relative to class */ public void setPath ( @Nullable final String path ) { this.path = path; } /** * Returns menu icons format. * * @return menu icons format */ @Nullable public String getExtension () { return extension; } /** * Sets menu icons format. * * @param extension menu icons format */ public void setExtension ( @Nullable final String extension ) { this.extension = extension == null ? null : extension.startsWith ( "." ) ? extension : "." + extension; } /** * Sets menu icons location and format. * * @param path path to menu icons folder in file system * @param extension menu icons format */ public void setIconSettings ( @Nullable final String path, @Nullable final String extension ) { setIconSettings ( null, path, extension ); } /** * Sets menu icons location and format. * * @param nearClass class near which menu icons are placed * @param path path to menu icons folder relative to class * @param extension menu icons format */ public void setIconSettings ( @Nullable final Class nearClass, @Nullable final String path, @Nullable final String extension ) { setNearClass ( nearClass ); setPath ( path ); setExtension ( extension ); } /** * Returns menu language key prefix. * * @return menu language key prefix */ @Nullable public String getLanguagePrefix () { return languagePrefix; } /** * Sets menu language key prefix. * todo Update all existing items? * * @param prefix menu language key prefix */ public void setLanguagePrefix ( @Nullable final String prefix ) { this.languagePrefix = TextUtils.notEmpty ( prefix ) ? prefix : null; } /** * Returns menu item language key for the specified name. * * @param text menu item name or text * @return menu item language key for the specified name */ @Nullable public String getLanguageKey ( @Nullable final String text ) { final String languageKey; if ( text != null ) { final String prefix = getLanguagePrefix (); if ( prefix != null ) { final String key = prefix + "." + text; languageKey = LM.containsText ( key ) ? key : text; } else { languageKey = text; } } else { languageKey = null; } return languageKey; } /** * Adds {@link WebMenuItem} into menu. * * @param text {@link WebMenuItem} text * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @Nullable final String text, @Nullable final ActionListener actionListener ) { return addItem ( defaultStyleId, defaultIcon, text, defaultHotkey, defaultEnabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param text {@link WebMenuItem} text * @param hotkey {@link WebMenuItem} accelerator * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @Nullable final String text, @Nullable final HotkeyData hotkey, @Nullable final ActionListener actionListener ) { return addItem ( defaultStyleId, defaultIcon, text, hotkey, defaultEnabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param text {@link WebMenuItem} text * @param enabled whether {@link WebMenuItem} is enabled or not * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @Nullable final String text, final boolean enabled, @Nullable final ActionListener actionListener ) { return addItem ( defaultStyleId, defaultIcon, text, defaultHotkey, enabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param text {@link WebMenuItem} text * @param hotkey {@link WebMenuItem} accelerator * @param enabled whether {@link WebMenuItem} is enabled or not * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, @Nullable final ActionListener actionListener ) { return addItem ( defaultStyleId, defaultIcon, text, hotkey, enabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenuItem} text * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @Nullable final Object icon, @Nullable final String text, @Nullable final ActionListener actionListener ) { return addItem ( defaultStyleId, icon, text, defaultHotkey, defaultEnabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenuItem} text * @param hotkey {@link WebMenuItem} accelerator * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, @Nullable final ActionListener actionListener ) { return addItem ( defaultStyleId, icon, text, hotkey, defaultEnabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenuItem} text * @param enabled whether {@link WebMenuItem} is enabled or not * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @Nullable final Object icon, @Nullable final String text, final boolean enabled, @Nullable final ActionListener actionListener ) { return addItem ( defaultStyleId, icon, text, defaultHotkey, enabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenuItem} text * @param hotkey {@link WebMenuItem} accelerator * @param enabled whether {@link WebMenuItem} is enabled or not * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, @Nullable final ActionListener actionListener ) { return addItem ( defaultStyleId, icon, text, hotkey, enabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param id {@link WebMenuItem} {@link StyleId} * @param text {@link WebMenuItem} text * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @NotNull final StyleId id, @Nullable final String text, @Nullable final ActionListener actionListener ) { return addItem ( id, defaultIcon, text, defaultHotkey, defaultEnabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param id {@link WebMenuItem} {@link StyleId} * @param text {@link WebMenuItem} text * @param hotkey {@link WebMenuItem} accelerator * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @NotNull final StyleId id, @Nullable final String text, @Nullable final HotkeyData hotkey, @Nullable final ActionListener actionListener ) { return addItem ( id, defaultIcon, text, hotkey, defaultEnabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param id {@link WebMenuItem} {@link StyleId} * @param text {@link WebMenuItem} text * @param enabled whether {@link WebMenuItem} is enabled or not * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @NotNull final StyleId id, @Nullable final String text, final boolean enabled, @Nullable final ActionListener actionListener ) { return addItem ( id, defaultIcon, text, defaultHotkey, enabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param id {@link WebMenuItem} {@link StyleId} * @param text {@link WebMenuItem} text * @param hotkey {@link WebMenuItem} accelerator * @param enabled whether {@link WebMenuItem} is enabled or not * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @NotNull final StyleId id, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, @Nullable final ActionListener actionListener ) { return addItem ( id, defaultIcon, text, hotkey, enabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param id {@link WebMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenuItem} text * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, @Nullable final ActionListener actionListener ) { return addItem ( id, icon, text, defaultHotkey, defaultEnabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param id {@link WebMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenuItem} text * @param hotkey {@link WebMenuItem} accelerator * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, @Nullable final ActionListener actionListener ) { return addItem ( id, icon, text, hotkey, defaultEnabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param id {@link WebMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenuItem} text * @param enabled whether {@link WebMenuItem} is enabled or not * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, final boolean enabled, @Nullable final ActionListener actionListener ) { return addItem ( id, icon, text, defaultHotkey, enabled, actionListener ); } /** * Adds {@link WebMenuItem} into menu. * * @param id {@link WebMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenuItem} text * @param hotkey {@link WebMenuItem} accelerator * @param enabled whether {@link WebMenuItem} is enabled or not * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull public WebMenuItem addItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, @Nullable final ActionListener actionListener ) { final WebMenuItem item = createItem ( id, icon, text, hotkey, enabled, actionListener ); getMenu ().add ( item ); return item; } /** * Returns newly created {@link WebMenuItem}. * * @param id {@link WebMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenuItem} text * @param hotkey {@link WebMenuItem} accelerator * @param enabled whether {@link WebMenuItem} is enabled or not * @param actionListener {@link WebMenuItem} {@link ActionListener} * @return newly created {@link WebMenuItem} */ @NotNull protected WebMenuItem createItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, @Nullable final ActionListener actionListener ) { final WebMenuItem item = new WebMenuItem ( id, getLanguageKey ( text ) ); item.setIcon ( getIcon ( icon ) ); item.setAccelerator ( hotkey ); item.setEnabled ( enabled ); if ( actionListener != null ) { item.addActionListener ( actionListener ); } return item; } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param text {@link WebCheckBoxMenuItem} text * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @Nullable final String text, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( defaultStyleId, defaultIcon, text, defaultHotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param text {@link WebCheckBoxMenuItem} text * @param hotkey {@link WebCheckBoxMenuItem} accelerator * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( defaultStyleId, defaultIcon, text, hotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param text {@link WebCheckBoxMenuItem} text * @param enabled whether {@link WebCheckBoxMenuItem} is enabled or not * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @Nullable final String text, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( defaultStyleId, defaultIcon, text, defaultHotkey, enabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param text {@link WebCheckBoxMenuItem} text * @param hotkey {@link WebCheckBoxMenuItem} accelerator * @param enabled whether {@link WebCheckBoxMenuItem} is enabled or not * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( defaultStyleId, defaultIcon, text, hotkey, enabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebCheckBoxMenuItem} text * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @Nullable final Object icon, @Nullable final String text, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( defaultStyleId, icon, text, defaultHotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebCheckBoxMenuItem} text * @param hotkey {@link WebCheckBoxMenuItem} accelerator * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( defaultStyleId, icon, text, hotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebCheckBoxMenuItem} text * @param enabled whether {@link WebCheckBoxMenuItem} is enabled or not * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @Nullable final Object icon, @Nullable final String text, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( defaultStyleId, icon, text, defaultHotkey, enabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebCheckBoxMenuItem} text * @param hotkey {@link WebCheckBoxMenuItem} accelerator * @param enabled whether {@link WebCheckBoxMenuItem} is enabled or not * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( defaultStyleId, icon, text, hotkey, enabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param id {@link WebCheckBoxMenuItem} {@link StyleId} * @param text {@link WebCheckBoxMenuItem} text * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @NotNull final StyleId id, @Nullable final String text, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( id, defaultIcon, text, defaultHotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param id {@link WebCheckBoxMenuItem} {@link StyleId} * @param text {@link WebCheckBoxMenuItem} text * @param hotkey {@link WebCheckBoxMenuItem} accelerator * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @NotNull final StyleId id, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( id, defaultIcon, text, hotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param id {@link WebCheckBoxMenuItem} {@link StyleId} * @param text {@link WebCheckBoxMenuItem} text * @param enabled whether {@link WebCheckBoxMenuItem} is enabled or not * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @NotNull final StyleId id, @Nullable final String text, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( id, defaultIcon, text, defaultHotkey, enabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param id {@link WebCheckBoxMenuItem} {@link StyleId} * @param text {@link WebCheckBoxMenuItem} text * @param hotkey {@link WebCheckBoxMenuItem} accelerator * @param enabled whether {@link WebCheckBoxMenuItem} is enabled or not * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @NotNull final StyleId id, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( id, defaultIcon, text, hotkey, enabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param id {@link WebCheckBoxMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebCheckBoxMenuItem} text * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( id, icon, text, defaultHotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param id {@link WebCheckBoxMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebCheckBoxMenuItem} text * @param hotkey {@link WebCheckBoxMenuItem} accelerator * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( id, icon, text, hotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param id {@link WebCheckBoxMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebCheckBoxMenuItem} text * @param enabled whether {@link WebCheckBoxMenuItem} is enabled or not * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addCheckItem ( id, icon, text, defaultHotkey, enabled, selected, actionListener ); } /** * Adds {@link WebCheckBoxMenuItem} into menu. * * @param id {@link WebCheckBoxMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebCheckBoxMenuItem} text * @param hotkey {@link WebCheckBoxMenuItem} accelerator * @param enabled whether {@link WebCheckBoxMenuItem} is enabled or not * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull public WebCheckBoxMenuItem addCheckItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { final WebCheckBoxMenuItem item = createCheckItem ( id, icon, text, hotkey, enabled, selected, actionListener ); getMenu ().add ( item ); return item; } /** * Returns newly created {@link WebCheckBoxMenuItem}. * * @param id {@link WebCheckBoxMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebCheckBoxMenuItem} text * @param hotkey {@link WebCheckBoxMenuItem} accelerator * @param enabled whether {@link WebCheckBoxMenuItem} is enabled or not * @param selected whether {@link WebCheckBoxMenuItem} is selected or not * @param actionListener {@link WebCheckBoxMenuItem} {@link ActionListener} * @return newly created {@link WebCheckBoxMenuItem} */ @NotNull protected WebCheckBoxMenuItem createCheckItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { final WebCheckBoxMenuItem item = new WebCheckBoxMenuItem ( id, getLanguageKey ( text ) ); final Icon resolvedIcon = getIcon ( icon ); if ( resolvedIcon != null ) { item.setIcon ( resolvedIcon ); } item.setAccelerator ( hotkey ); item.setEnabled ( enabled ); item.setSelected ( selected ); if ( actionListener != null ) { item.addActionListener ( actionListener ); } if ( isGroupOpen () ) { group ( item ); } return item; } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param text {@link WebRadioButtonMenuItem} text * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @Nullable final String text, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( defaultStyleId, defaultIcon, text, defaultHotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param text {@link WebRadioButtonMenuItem} text * @param hotkey {@link WebRadioButtonMenuItem} accelerator * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( defaultStyleId, defaultIcon, text, hotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param text {@link WebRadioButtonMenuItem} text * @param enabled whether {@link WebRadioButtonMenuItem} is enabled or not * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @Nullable final String text, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( defaultStyleId, defaultIcon, text, defaultHotkey, enabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param text {@link WebRadioButtonMenuItem} text * @param hotkey {@link WebRadioButtonMenuItem} accelerator * @param enabled whether {@link WebRadioButtonMenuItem} is enabled or not * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( defaultStyleId, defaultIcon, text, hotkey, enabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebRadioButtonMenuItem} text * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @Nullable final Object icon, @Nullable final String text, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( defaultStyleId, icon, text, defaultHotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebRadioButtonMenuItem} text * @param hotkey {@link WebRadioButtonMenuItem} accelerator * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( defaultStyleId, icon, text, hotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebRadioButtonMenuItem} text * @param enabled whether {@link WebRadioButtonMenuItem} is enabled or not * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @Nullable final Object icon, @Nullable final String text, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( defaultStyleId, icon, text, defaultHotkey, enabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebRadioButtonMenuItem} text * @param hotkey {@link WebRadioButtonMenuItem} accelerator * @param enabled whether {@link WebRadioButtonMenuItem} is enabled or not * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( defaultStyleId, icon, text, hotkey, enabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param id {@link WebRadioButtonMenuItem} {@link StyleId} * @param text {@link WebRadioButtonMenuItem} text * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @NotNull final StyleId id, @Nullable final String text, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( id, defaultIcon, text, defaultHotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param id {@link WebRadioButtonMenuItem} {@link StyleId} * @param text {@link WebRadioButtonMenuItem} text * @param hotkey {@link WebRadioButtonMenuItem} accelerator * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @NotNull final StyleId id, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( id, defaultIcon, text, hotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param id {@link WebRadioButtonMenuItem} {@link StyleId} * @param text {@link WebRadioButtonMenuItem} text * @param enabled whether {@link WebRadioButtonMenuItem} is enabled or not * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @NotNull final StyleId id, @Nullable final String text, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( id, defaultIcon, text, defaultHotkey, enabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param id {@link WebRadioButtonMenuItem} {@link StyleId} * @param text {@link WebRadioButtonMenuItem} text * @param hotkey {@link WebRadioButtonMenuItem} accelerator * @param enabled whether {@link WebRadioButtonMenuItem} is enabled or not * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @NotNull final StyleId id, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( id, defaultIcon, text, hotkey, enabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param id {@link WebRadioButtonMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebRadioButtonMenuItem} text * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( id, icon, text, defaultHotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param id {@link WebRadioButtonMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebRadioButtonMenuItem} text * @param hotkey {@link WebRadioButtonMenuItem} accelerator * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( id, icon, text, hotkey, defaultEnabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param id {@link WebRadioButtonMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebRadioButtonMenuItem} text * @param enabled whether {@link WebRadioButtonMenuItem} is enabled or not * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { return addRadioItem ( id, icon, text, defaultHotkey, enabled, selected, actionListener ); } /** * Adds {@link WebRadioButtonMenuItem} into menu. * * @param id {@link WebRadioButtonMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebRadioButtonMenuItem} text * @param hotkey {@link WebRadioButtonMenuItem} accelerator * @param enabled whether {@link WebRadioButtonMenuItem} is enabled or not * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull public WebRadioButtonMenuItem addRadioItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { final WebRadioButtonMenuItem item = createRadioItem ( id, icon, text, hotkey, enabled, selected, actionListener ); getMenu ().add ( item ); return item; } /** * Returns newly created {@link WebRadioButtonMenuItem}. * * @param id {@link WebRadioButtonMenuItem} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebRadioButtonMenuItem} text * @param hotkey {@link WebRadioButtonMenuItem} accelerator * @param enabled whether {@link WebRadioButtonMenuItem} is enabled or not * @param selected whether {@link WebRadioButtonMenuItem} is selected or not * @param actionListener {@link WebRadioButtonMenuItem} {@link ActionListener} * @return newly created {@link WebRadioButtonMenuItem} */ @NotNull protected WebRadioButtonMenuItem createRadioItem ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, @Nullable final HotkeyData hotkey, final boolean enabled, final boolean selected, @Nullable final ActionListener actionListener ) { final WebRadioButtonMenuItem item = new WebRadioButtonMenuItem ( id, getLanguageKey ( text ) ); final Icon resolvedIcon = getIcon ( icon ); if ( resolvedIcon != null ) { item.setIcon ( resolvedIcon ); } item.setAccelerator ( hotkey ); item.setEnabled ( enabled ); item.setSelected ( selected ); if ( actionListener != null ) { item.addActionListener ( actionListener ); } if ( isGroupOpen () ) { group ( item ); } return item; } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param text {@link WebMenu} text * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @Nullable final String text ) { return addSubMenu ( defaultStyleId, defaultIcon, text, defaultEnabled, defaultAction ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param text {@link WebMenu} text * @param enabled whether {@link WebMenu} is enabled or not * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @Nullable final String text, final boolean enabled ) { return addSubMenu ( defaultStyleId, defaultIcon, text, enabled, defaultAction ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param text {@link WebMenu} text * @param actionListener {@link WebMenu} {@link ActionListener} * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @Nullable final String text, @Nullable final ActionListener actionListener ) { return addSubMenu ( defaultStyleId, defaultIcon, text, defaultEnabled, actionListener ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param text {@link WebMenu} text * @param enabled whether {@link WebMenu} is enabled or not * @param actionListener {@link WebMenu} {@link ActionListener} * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @Nullable final String text, final boolean enabled, @Nullable final ActionListener actionListener ) { return addSubMenu ( defaultStyleId, defaultIcon, text, enabled, actionListener ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenu} text * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @Nullable final Object icon, @Nullable final String text ) { return addSubMenu ( defaultStyleId, icon, text, defaultEnabled, defaultAction ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenu} text * @param enabled whether {@link WebMenu} is enabled or not * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @Nullable final Object icon, @Nullable final String text, final boolean enabled ) { return addSubMenu ( defaultStyleId, icon, text, enabled, defaultAction ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenu} text * @param actionListener {@link WebMenu} {@link ActionListener} * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @Nullable final Object icon, @Nullable final String text, @Nullable final ActionListener actionListener ) { return addSubMenu ( defaultStyleId, icon, text, defaultEnabled, actionListener ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenu} text * @param enabled whether {@link WebMenu} is enabled or not * @param actionListener {@link WebMenu} {@link ActionListener} * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @Nullable final Object icon, @Nullable final String text, final boolean enabled, @Nullable final ActionListener actionListener ) { return addSubMenu ( defaultStyleId, icon, text, enabled, actionListener ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param id {@link WebMenu} {@link StyleId} * @param text {@link WebMenu} text * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @NotNull final StyleId id, @Nullable final String text ) { return addSubMenu ( id, defaultIcon, text, defaultEnabled, defaultAction ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param id {@link WebMenu} {@link StyleId} * @param text {@link WebMenu} text * @param enabled whether {@link WebMenu} is enabled or not * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @NotNull final StyleId id, @Nullable final String text, final boolean enabled ) { return addSubMenu ( id, defaultIcon, text, enabled, defaultAction ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param id {@link WebMenu} {@link StyleId} * @param text {@link WebMenu} text * @param actionListener {@link WebMenu} {@link ActionListener} * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @NotNull final StyleId id, @Nullable final String text, @Nullable final ActionListener actionListener ) { return addSubMenu ( id, defaultIcon, text, defaultEnabled, actionListener ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param id {@link WebMenu} {@link StyleId} * @param text {@link WebMenu} text * @param enabled whether {@link WebMenu} is enabled or not * @param actionListener {@link WebMenu} {@link ActionListener} * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @NotNull final StyleId id, @Nullable final String text, final boolean enabled, @Nullable final ActionListener actionListener ) { return addSubMenu ( id, defaultIcon, text, enabled, actionListener ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param id {@link WebMenu} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenu} text * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text ) { return addSubMenu ( id, icon, text, defaultEnabled, defaultAction ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param id {@link WebMenu} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenu} text * @param enabled whether {@link WebMenu} is enabled or not * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, final boolean enabled ) { return addSubMenu ( id, icon, text, enabled, defaultAction ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param id {@link WebMenu} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenu} text * @param actionListener {@link WebMenu} {@link ActionListener} * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, @Nullable final ActionListener actionListener ) { return addSubMenu ( id, icon, text, defaultEnabled, actionListener ); } /** * Adds {@link WebMenu} into this {@link AbstractMenuGenerator}. * Returned {@link MenuGenerator} will have the same settings as current one, but you can modify those later. * * @param id {@link WebMenu} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenu} text * @param enabled whether {@link WebMenu} is enabled or not * @param actionListener {@link WebMenu} {@link ActionListener} * @return {@link MenuGenerator} for newly created {@link WebMenu} */ @NotNull public MenuGenerator addSubMenu ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, final boolean enabled, @Nullable final ActionListener actionListener ) { final WebMenu menu = createSubMenu ( id, icon, text, enabled, actionListener ); getMenu ().add ( menu ); // Creating submenu generator final MenuGenerator menuGenerator = new MenuGenerator ( menu ); menuGenerator.setIconSettings ( getNearClass (), getPath (), getExtension () ); menuGenerator.setLanguagePrefix ( getLanguagePrefix () ); return menuGenerator; } /** * Returns newly created {@link WebMenu}. * * @param id {@link WebMenu} {@link StyleId} * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @param text {@link WebMenu} text * @param enabled whether {@link WebMenu} is enabled or not * @param actionListener {@link WebMenu} {@link ActionListener} * @return newly created {@link WebMenu} */ @NotNull protected WebMenu createSubMenu ( @NotNull final StyleId id, @Nullable final Object icon, @Nullable final String text, final boolean enabled, @Nullable final ActionListener actionListener ) { final WebMenu menu = new WebMenu ( id, getLanguageKey ( text ) ); menu.setIcon ( getIcon ( icon ) ); menu.setEnabled ( enabled ); if ( actionListener != null ) { menu.addActionListener ( actionListener ); } return menu; } /** * Adds separator into this {@link AbstractMenuGenerator}. */ public void addSeparator () { final C menuComponent = getMenu (); if ( menuComponent instanceof WebMenu ) { ( ( WebMenu ) menuComponent ).addSeparator (); } else if ( menuComponent instanceof WebPopupMenu ) { ( ( WebPopupMenu ) menuComponent ).addSeparator (); } } /** * Starts grouping menu items. * All items created after this call and before {@code closeGroup()} call will get grouped. * * @return {@link UnselectableButtonGroup} used for grouping */ @NotNull public UnselectableButtonGroup openGroup () { return openGroup ( false ); } /** * Starts grouping menu items. * All items created after this call and before {@code closeGroup()} call will get grouped. * * @param unselectable whether items should be unselectable or not * @return {@link UnselectableButtonGroup} used for grouping */ @NotNull public UnselectableButtonGroup openGroup ( final boolean unselectable ) { group = new UnselectableButtonGroup ( unselectable ); return group; } /** * Returns whether or not {@link UnselectableButtonGroup} is currently used for grouping. * * @return {@code true} if {@link UnselectableButtonGroup} is currently used for grouping, {@code false} otherwise */ public boolean isGroupOpen () { return group != null; } /** * Adds specified {@link AbstractButton} into currently used {@link UnselectableButtonGroup}. * * @param button {@link AbstractButton} to add into {@link UnselectableButtonGroup} * @return {@link UnselectableButtonGroup} used for grouping */ @NotNull public UnselectableButtonGroup group ( @NotNull final AbstractButton button ) { if ( group == null ) { throw new UtilityException ( "Button group must be opened first" ); } group.add ( button ); return group; } /** * Finishes grouping menu items. * * @return {@link UnselectableButtonGroup} used for grouping */ @NotNull public UnselectableButtonGroup closeGroup () { if ( group == null ) { throw new UtilityException ( "Button group must be opened first" ); } final UnselectableButtonGroup group = this.group; this.group = null; return group; } /** * Returns menu {@link JComponent}. * * @return menu {@link JComponent} */ @NotNull public C getMenu () { return menu; } /** * Returns whether menu is empty or not. * * @return true if menu is empty, false otherwise */ public boolean isEmpty () { return getMenu ().getComponentCount () == 0; } /** * Returns {@link Icon} for the specified source {@link Object}. * * @param icon either {@link Icon}, {@link Image}, {@link Resource}, path, {@link File} or {@link URL} * @return {@link Icon} for the specified source {@link Object} */ @Nullable protected Icon getIcon ( @Nullable final Object icon ) { final Icon result; if ( icon != null ) { if ( icon instanceof Icon ) { result = ( Icon ) icon; } else if ( icon instanceof Image ) { result = new ImageIcon ( ( Image ) icon ); } else { final Resource resource; if ( icon instanceof Resource ) { resource = ( Resource ) icon; } else if ( icon instanceof String ) { try { if ( getNearClass () != null ) { resource = new ClassResource ( getNearClass (), getPath () + icon + getExtension () ); } else { resource = new FileResource ( new File ( getPath (), icon + getExtension () ) ); } } catch ( final Exception e ) { throw new UtilityException ( "Unable to find menu icon for path: " + getPath () + icon + getExtension (), e ); } } else if ( icon instanceof File ) { resource = new FileResource ( ( File ) icon ); } else if ( icon instanceof URL ) { resource = new UrlResource ( ( URL ) icon ); } else { throw new UtilityException ( "Unknown icon object type provided: " + icon ); } result = ImageUtils.loadImageIcon ( resource ); } } else { result = null; } return result; } }
{ "pile_set_name": "Github" }
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.coreui; public final class R { public static final class attr { public static final int coordinatorLayoutStyle = 0x7f0400ba; public static final int font = 0x7f0400ed; public static final int fontProviderAuthority = 0x7f0400ef; public static final int fontProviderCerts = 0x7f0400f0; public static final int fontProviderFetchStrategy = 0x7f0400f1; public static final int fontProviderFetchTimeout = 0x7f0400f2; public static final int fontProviderPackage = 0x7f0400f3; public static final int fontProviderQuery = 0x7f0400f4; public static final int fontStyle = 0x7f0400f5; public static final int fontVariationSettings = 0x7f0400f6; public static final int fontWeight = 0x7f0400f7; public static final int keylines = 0x7f040123; public static final int layout_anchor = 0x7f040128; public static final int layout_anchorGravity = 0x7f040129; public static final int layout_behavior = 0x7f04012a; public static final int layout_dodgeInsetEdges = 0x7f04014f; public static final int layout_insetEdge = 0x7f04015b; public static final int layout_keyline = 0x7f04015c; public static final int statusBarBackground = 0x7f0401b9; public static final int ttcIndex = 0x7f04021a; } public static final class bool { public static final int abc_action_bar_embed_tabs = 0x7f050000; } public static final class color { public static final int notification_action_color_filter = 0x7f060067; public static final int notification_icon_bg_color = 0x7f060068; public static final int ripple_material_light = 0x7f060073; public static final int secondary_text_default_material_light = 0x7f060075; } public static final class dimen { public static final int compat_button_inset_horizontal_material = 0x7f070052; public static final int compat_button_inset_vertical_material = 0x7f070053; public static final int compat_button_padding_horizontal_material = 0x7f070054; public static final int compat_button_padding_vertical_material = 0x7f070055; public static final int compat_control_corner_material = 0x7f070056; public static final int notification_action_icon_size = 0x7f0700cb; public static final int notification_action_text_size = 0x7f0700cc; public static final int notification_big_circle_margin = 0x7f0700cd; public static final int notification_content_margin_start = 0x7f0700ce; public static final int notification_large_icon_height = 0x7f0700cf; public static final int notification_large_icon_width = 0x7f0700d0; public static final int notification_main_column_padding_top = 0x7f0700d1; public static final int notification_media_narrow_margin = 0x7f0700d2; public static final int notification_right_icon_size = 0x7f0700d3; public static final int notification_right_side_padding_top = 0x7f0700d4; public static final int notification_small_icon_background_padding = 0x7f0700d5; public static final int notification_small_icon_size_as_large = 0x7f0700d6; public static final int notification_subtext_size = 0x7f0700d7; public static final int notification_top_pad = 0x7f0700d8; public static final int notification_top_pad_large_text = 0x7f0700d9; } public static final class drawable { public static final int notification_action_background = 0x7f080075; public static final int notification_bg = 0x7f080076; public static final int notification_bg_low = 0x7f080077; public static final int notification_bg_low_normal = 0x7f080078; public static final int notification_bg_low_pressed = 0x7f080079; public static final int notification_bg_normal = 0x7f08007a; public static final int notification_bg_normal_pressed = 0x7f08007b; public static final int notification_icon_background = 0x7f08007c; public static final int notification_template_icon_bg = 0x7f08007d; public static final int notification_template_icon_low_bg = 0x7f08007e; public static final int notification_tile_bg = 0x7f08007f; public static final int notify_panel_notification_icon_bg = 0x7f080080; } public static final class id { public static final int action_container = 0x7f09000e; public static final int action_divider = 0x7f090010; public static final int action_image = 0x7f090011; public static final int action_text = 0x7f090017; public static final int actions = 0x7f090018; public static final int async = 0x7f09001f; public static final int blocking = 0x7f090025; public static final int bottom = 0x7f090028; public static final int chronometer = 0x7f090035; public static final int end = 0x7f09005c; public static final int forever = 0x7f090070; public static final int icon = 0x7f090076; public static final int icon_group = 0x7f090077; public static final int info = 0x7f09007b; public static final int italic = 0x7f09007d; public static final int left = 0x7f090082; public static final int line1 = 0x7f090083; public static final int line3 = 0x7f090084; public static final int none = 0x7f09009b; public static final int normal = 0x7f09009c; public static final int notification_background = 0x7f09009d; public static final int notification_main_column = 0x7f09009e; public static final int notification_main_column_container = 0x7f09009f; public static final int right = 0x7f0900b4; public static final int right_icon = 0x7f0900b5; public static final int right_side = 0x7f0900b6; public static final int start = 0x7f0900e1; public static final int tag_transition_group = 0x7f0900ea; public static final int text = 0x7f0900eb; public static final int text2 = 0x7f0900ec; public static final int time = 0x7f0900f3; public static final int title = 0x7f0900f4; public static final int top = 0x7f0900f9; } public static final class integer { public static final int status_bar_notification_info_maxnum = 0x7f0a000c; } public static final class layout { public static final int notification_action = 0x7f0c003b; public static final int notification_action_tombstone = 0x7f0c003c; public static final int notification_template_custom_big = 0x7f0c0043; public static final int notification_template_icon_group = 0x7f0c0044; public static final int notification_template_part_chronometer = 0x7f0c0048; public static final int notification_template_part_time = 0x7f0c0049; } public static final class string { public static final int status_bar_notification_info_overflow = 0x7f100083; } public static final class style { public static final int TextAppearance_Compat_Notification = 0x7f11010b; public static final int TextAppearance_Compat_Notification_Info = 0x7f11010c; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f11010e; public static final int TextAppearance_Compat_Notification_Time = 0x7f110111; public static final int TextAppearance_Compat_Notification_Title = 0x7f110113; public static final int Widget_Compat_NotificationActionContainer = 0x7f1101b7; public static final int Widget_Compat_NotificationActionText = 0x7f1101b8; public static final int Widget_Support_CoordinatorLayout = 0x7f1101d9; } public static final class styleable { public static final int[] CoordinatorLayout = { 0x7f040123, 0x7f0401b9 }; public static final int CoordinatorLayout_keylines = 0; public static final int CoordinatorLayout_statusBarBackground = 1; public static final int[] CoordinatorLayout_Layout = { 0x010100b3, 0x7f040128, 0x7f040129, 0x7f04012a, 0x7f04014f, 0x7f04015b, 0x7f04015c }; public static final int CoordinatorLayout_Layout_android_layout_gravity = 0; public static final int CoordinatorLayout_Layout_layout_anchor = 1; public static final int CoordinatorLayout_Layout_layout_anchorGravity = 2; public static final int CoordinatorLayout_Layout_layout_behavior = 3; public static final int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 4; public static final int CoordinatorLayout_Layout_layout_insetEdge = 5; public static final int CoordinatorLayout_Layout_layout_keyline = 6; public static final int[] FontFamily = { 0x7f0400ef, 0x7f0400f0, 0x7f0400f1, 0x7f0400f2, 0x7f0400f3, 0x7f0400f4 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x01010532, 0x01010533, 0x0101053f, 0x0101056f, 0x01010570, 0x7f0400ed, 0x7f0400f5, 0x7f0400f6, 0x7f0400f7, 0x7f04021a }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.mail; /** * The context in which a piece of Message content is contained. A * <code>MessageContext</code> object is returned by the * <code>getMessageContext</code> method of the * <code>MessageAware</code> interface. <code>MessageAware</code> is * typically implemented by <code>DataSources</code> to allow a * <code>DataContentHandler</code> to pass on information about the * context in which a data content object is operating. * * @see jakarta.mail.MessageAware * @see jakarta.activation.DataSource * @see jakarta.activation.DataContentHandler * @since JavaMail 1.1 */ public class MessageContext { private Part part; /** * Create a MessageContext object describing the context of the given Part. * * @param part the Part */ public MessageContext(Part part) { this.part = part; } /** * Return the Part that contains the content. * * @return the containing Part, or null if not known */ public Part getPart() { return part; } /** * Return the Message that contains the content. * Follows the parent chain up through containing Multipart * objects until it comes to a Message object, or null. * * @return the containing Message, or null if not known */ public Message getMessage() { try { return getMessage(part); } catch (MessagingException ex) { return null; } } /** * Return the Message containing an arbitrary Part. * Follows the parent chain up through containing Multipart * objects until it comes to a Message object, or null. * * @return the containing Message, or null if none * @see jakarta.mail.BodyPart#getParent * @see jakarta.mail.Multipart#getParent */ private static Message getMessage(Part p) throws MessagingException { while (p != null) { if (p instanceof Message) return (Message)p; BodyPart bp = (BodyPart)p; Multipart mp = bp.getParent(); if (mp == null) // MimeBodyPart might not be in a MimeMultipart return null; p = mp.getParent(); } return null; } /** * Return the Session we're operating in. * * @return the Session, or null if not known */ public Session getSession() { Message msg = getMessage(); return msg != null ? msg.getSession() : null; } }
{ "pile_set_name": "Github" }
The FAME! Speech Corpus The components of the Frisian data collection are speech and language resources gathered for building a large vocabulary ASR system for the Frisian language. Firstly, a new broadcast database is created by collecting recordings from the archives of the regional broadcaster Omrop Fryslân, and annotating them with various information such as the language switches and speaker details. The second component of this collection is a language model created on a text corpus with diverse vocabulary. Thirdly, a Frisian phonetic dictionary with the mappings between the Frisian words and phones is built to make the ASR viable for this under-resourced language. Finally, an ASR recipe is provided which uses all previous resources to perform recognition and present the recognition performances. The Corpus consists of short utterances extracted from 203 audio segments of approximately 5 minutes long which are parts of various radio programs covering a time span of almost 50 years (1966-2015), adding a longitudinal dimension to the database. The content of the recordings are very diverse including radio programs about culture, history, literature, sports, nature, agriculture, politics, society and languages. The total duration of the manually annotated radio broadcasts sums up to 18 hours, 33 minutes and 57 seconds. The stereo audio data has a sampling frequency of 48 kHz and 16-bit resolution per sample. The available meta-information helped the annotators to identify these speakers and mark them either using their names or the same label (if the name is not known). There are 309 identified speakers in the FAME! Speech Corpus, 21 of whom appear at least 3 times in the database. These speakers are mostly program presenters and celebrities appearing multiple times in different recordings over years. There are 233 unidentified speakers due to lack of meta-information. The total number of word- and sentence-level code-switching cases in the FAME! Speech Corpus is equal to 3837. Music portions have been removed, except where these overlap with speech. A full description of the FAME! Speech Corpus is provided in: E. Yılmaz, H. van den Heuvel, J. Dijkstra, H. Van de Velde, F. Kampstra, J. Algra and D. van Leeuwen, "Open Source Speech and Language Resources for Frisian," In Proc. INTERSPEECH, pp. 1536-1540, San Francisco, CA, USA, Sept. 2016. Speaker clustering and verification corpus details are provided in: E. Yılmaz, J. Dijkstra, H. Van de Velde, F. Kampstra, J. Algra, H. van den Heuvel and D. van Leeuwen, "Longitudinal Speaker Clustering and Verification Corpus with Code-switching Frisian-Dutch Speech," in Proc. INTERSPEECH, pp. 37-41 Stockholm, Sweden, August 2017. Please check http://www.ru.nl/clst/datasets/ to get the FAME! Speech Corpus. The ASR scripts are in ./s5. The GMM-UBM and DNN-UBM SV scripts are in ./v1 and ./v2 respectively.
{ "pile_set_name": "Github" }
/******************************************************************************** * Copyright (c) 2020 Cedalo AG * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0. * * SPDX-License-Identifier: EPL-2.0 * ********************************************************************************/ /* eslint-disable */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { withStyles } from '@material-ui/core/styles/index'; import Button from '@material-ui/core/Button'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogTitle from '@material-ui/core/DialogTitle'; import Dialog from '@material-ui/core/Dialog'; import Warning from '@material-ui/icons/Warning'; import { FormattedMessage } from 'react-intl'; import StreamHelper from '../../../helper/StreamHelper'; import AdminConstants from '../../../constants/AdminConstants'; import styles from '../styles'; import * as Actions from '../../../actions/actions'; import { IconMachine, IconStream, IconProducer } from '../../icons'; import { intl } from '../../../helper/IntlGlobalProvider'; import { Path } from '../../../helper/Path'; class StreamDeleteDialog extends React.Component { static propTypes = { onDelete: PropTypes.func, }; static defaultProps = { onDelete: undefined }; getListOfConflicts(conflicts) { const stream = StreamHelper.getActiveConfiguration(this.props); const consumers = conflicts.map(c => { if(c.className && c.className === AdminConstants.CONFIG_CLASS.ConsumerConfiguration) { return (<ListItem key={c.id} button onClick={(event) => this.handleConflictClick(c, event)} > <ListItemIcon> <IconStream /> </ListItemIcon> <ListItemText primary={c.name} /> </ListItem>); } return undefined; }); const producers = conflicts.map(c => { if(c.className && c.className === AdminConstants.CONFIG_CLASS.ProducerConfiguration) { return (<ListItem key={c.id} button onClick={(event) => this.handleConflictClick(c, event)} > <ListItemIcon> <IconProducer /> </ListItemIcon> <ListItemText primary={c.name} /> </ListItem>); } return undefined; }); const machines = conflicts.map(c => { if(!c.className) { return (<ListItem key={c.id} button onClick={(event) => this.handleConflictClick(c, event)} > <ListItemIcon> <IconMachine /> </ListItemIcon> <ListItemText primary={c.name} /> </ListItem>); } return undefined; }); return ( <div> <DialogContentText> <div style={{ textAlign: 'center' }}><Warning color='action'/></div> <p> <FormattedMessage id="Admin.deleteStreamNotPossible" defaultMessage="Deleting {streamName} is not possible because of the following dependencies:" values={{ streamName: stream.name }} /> </p> </DialogContentText> <List> {[...consumers, ...producers, ...machines]} </List> </div> ); } handleConflictClick(conflict) { if(conflict && conflict.id && conflict.className) { window.open(Path.stream(conflict.id)); } else if(conflict && conflict.id) { window.open(Path.machine(conflict.id)) } } onDelete = async (event) => { const action = event.currentTarget.getAttribute('data-action'); if (action) { const configuration = StreamHelper.getActiveConfiguration(this.props); const resp = await this.props.deleteActiveConfiguration(configuration.id); if(resp && resp.response && resp.response.result === 1) { this.forceUpdate(); if(typeof this.props.onDelete === 'function') { this.props.onDelete(true); this.closeDeleteDialog(); } } else { this.props.setFormFeedback({ title: 'Delete ', error: 'STREAM_DELETE_FAILED', message: intl.formatMessage( { id: 'STREAM_DELETE_FAILED', defaultMessage: 'Delete failed' }, ), }); } } }; closeDeleteDialog = () => { this.props.setDeleteDialogOpen(false); }; render() { const { open } = this.props; const stream = StreamHelper.getActiveConfiguration(this.props); if(!stream) return null; const conflicts = StreamHelper.getConficts(this.props); return ( <div> <Dialog open={open} > <DialogTitle> <FormattedMessage id="Admin.deleteStream" defaultMessage="Delete Stream: {streamName}" values={{ streamName: stream && stream.name }} /> </DialogTitle> <DialogContent style={{ marginTop: '20px', }} > { conflicts.length>0 ? this.getListOfConflicts(conflicts) : ( <DialogContentText> <FormattedMessage id="Admin.deleteStreamInfo" defaultMessage="You are about to delete the active data source." /> </DialogContentText> ) } </DialogContent> <DialogActions> <Button onClick={this.closeDeleteDialog} color="primary"> <FormattedMessage id="Cancel" defaultMessage="Cancel" /> </Button> <Button disabled={conflicts.length>0} data-action="delete" onClick={this.onDelete} color="primary" autoFocus > <FormattedMessage id="Delete" defaultMessage="Delete" /> </Button> </DialogActions> </Dialog> </div> ); } } function mapStateToProps(state) { return { open: state.appState.streamDeleteDialog.open, activeConfigurationId: state.appState.streamDeleteDialog.configId, providers: state.streams.providers, connectors: state.streams.connectors, consumers: state.streams.consumers, producers: state.streams.producers, }; } function mapDispatchToProps(dispatch) { return bindActionCreators({ ...Actions }, dispatch); } export default withStyles(styles)(connect(mapStateToProps, mapDispatchToProps)(StreamDeleteDialog));
{ "pile_set_name": "Github" }
// RUN: %swift -typecheck -verify -parse-stdlib -module-name Swift -target x86_64-apple-macosx10.10 %s // Fake declarations of some standard library features for -parse-stdlib. precedencegroup AssignmentPrecedence {} enum Optional<T> { case none case some(T) } @available(OSX, introduced: 10.5, deprecated: 10.8, obsoleted: 10.9, message: "you don't want to do that anyway") func doSomething() { } // expected-note @-1{{'doSomething()' was obsoleted in macOS 10.9}} doSomething() // expected-error{{'doSomething()' is unavailable in macOS: you don't want to do that anyway}} // Preservation of major.minor.micro @available(OSX, introduced: 10.5, deprecated: 10.8, obsoleted: 10.9.1) func doSomethingElse() { } // expected-note @-1{{'doSomethingElse()' was obsoleted in macOS 10.9.1}} doSomethingElse() // expected-error{{'doSomethingElse()' is unavailable in macOS}} // Preservation of minor-only version @available(OSX, introduced: 8.0, deprecated: 8.5, obsoleted: 10) func doSomethingReallyOld() { } // expected-note @-1{{'doSomethingReallyOld()' was obsoleted in macOS 10}} doSomethingReallyOld() // expected-error{{'doSomethingReallyOld()' is unavailable in macOS}} // Test deprecations in 10.10 and later @available(OSX, introduced: 10.5, deprecated: 10.10, message: "Use another function") func deprecatedFunctionWithMessage() { } deprecatedFunctionWithMessage() // expected-warning{{'deprecatedFunctionWithMessage()' was deprecated in macOS 10.10: Use another function}} @available(OSX, introduced: 10.5, deprecated: 10.10) func deprecatedFunctionWithoutMessage() { } deprecatedFunctionWithoutMessage() // expected-warning{{'deprecatedFunctionWithoutMessage()' was deprecated in macOS 10.10}} @available(OSX, introduced: 10.5, deprecated: 10.10, message: "Use BetterClass instead") class DeprecatedClass { } func functionWithDeprecatedParameter(p: DeprecatedClass) { } // expected-warning{{'DeprecatedClass' was deprecated in macOS 10.10: Use BetterClass instead}} @available(OSX, introduced: 10.5, deprecated: 10.11, message: "Use BetterClass instead") class DeprecatedClassIn10_11 { } // Elements deprecated later than the minimum deployment target (which is 10.10, in this case) should not generate warnings func functionWithDeprecatedLaterParameter(p: DeprecatedClassIn10_11) { } // Unconditional platform unavailability @available(OSX, unavailable) func doSomethingNotOnOSX() { } // expected-note @-1{{'doSomethingNotOnOSX()' has been explicitly marked unavailable here}} doSomethingNotOnOSX() // expected-error{{'doSomethingNotOnOSX()' is unavailable in macOS}} @available(iOS, unavailable) func doSomethingNotOniOS() { } doSomethingNotOniOS() // okay // Unconditional platform deprecation @available(OSX, deprecated) func doSomethingDeprecatedOnOSX() { } doSomethingDeprecatedOnOSX() // expected-warning{{'doSomethingDeprecatedOnOSX()' is deprecated in macOS}} @available(iOS, deprecated) func doSomethingDeprecatedOniOS() { } doSomethingDeprecatedOniOS() // okay struct TestStruct {} @available(macOS 10.10, *) extension TestStruct { // expected-note {{enclosing scope here}} @available(swift 400) func doTheThing() {} // expected-note {{'doTheThing()' was introduced in Swift 400}} @available(macOS 10.9, *) // expected-error {{declaration cannot be more available than enclosing scope}} @available(swift 400) func doAnotherThing() {} // expected-note {{'doAnotherThing()' was introduced in Swift 400}} @available(macOS 10.12, *) @available(swift 400) func doThirdThing() {} // expected-note {{'doThirdThing()' was introduced in Swift 400}} @available(macOS 10.12, *) @available(swift 1) func doFourthThing() {} @available(*, deprecated) func doDeprecatedThing() {} } @available(macOS 10.11, *) func testMemberAvailability() { TestStruct().doTheThing() // expected-error {{'doTheThing()' is unavailable}} TestStruct().doAnotherThing() // expected-error {{'doAnotherThing()' is unavailable}} TestStruct().doThirdThing() // expected-error {{'doThirdThing()' is unavailable}} TestStruct().doFourthThing() // expected-error {{'doFourthThing()' is only available in macOS 10.12 or newer}} expected-note {{'if #available'}} TestStruct().doDeprecatedThing() // expected-warning {{'doDeprecatedThing()' is deprecated}} } extension TestStruct { struct Data { mutating func mutate() {} } var unavailableGetter: Data { @available(macOS, unavailable, message: "bad getter") get { return Data() } // expected-note 2 {{here}} set {} } var unavailableSetter: Data { get { return Data() } @available(macOS, obsoleted: 10.5, message: "bad setter") set {} // expected-note 2 {{setter for 'unavailableSetter' was obsoleted in macOS 10.5}} } } func testAccessors() { var t = TestStruct() _ = t.unavailableGetter // expected-error {{getter for 'unavailableGetter' is unavailable in macOS}} t.unavailableGetter = .init() t.unavailableGetter.mutate() // expected-error {{getter for 'unavailableGetter' is unavailable in macOS}} _ = t.unavailableSetter t.unavailableSetter = .init() // expected-error {{setter for 'unavailableSetter' is unavailable in macOS: bad setter}} t.unavailableSetter.mutate() // expected-error {{setter for 'unavailableSetter' is unavailable in macOS: bad setter}} } // Check available on extensions @available(macOS, unavailable) extension TestStruct { func unavailInExtension() {} // expected-note 2 {{'unavailInExtension()' has been explicitly marked unavailable here}} } @available(macOS, obsoleted: 10.0) extension TestStruct { func obsoletedInExtension() {} // expected-note 2 {{'obsoletedInExtension()' was obsoleted in macOS 10.0}} } @available(macOS, deprecated: 10.0) extension TestStruct { func deprecatedInExtension() {} } @available(swift, introduced: 50.0) extension TestStruct { func introducedInExtensionSwift() {} // expected-note 2 {{'introducedInExtensionSwift()' was introduced in Swift 50.0}} } @available(macOS, introduced: 10.50) extension TestStruct { func introducedInExtensionMacOS() {} } TestStruct().unavailInExtension() // expected-error {{'unavailInExtension()' is unavailable in macOS}} TestStruct().obsoletedInExtension() // expected-error {{'obsoletedInExtension()' is unavailable}} TestStruct().deprecatedInExtension() // expected-warning {{'deprecatedInExtension()' was deprecated in macOS 10.0}} TestStruct().introducedInExtensionSwift() // expected-error {{'introducedInExtensionSwift()' is unavailable}} TestStruct().introducedInExtensionMacOS() // expected-error {{'introducedInExtensionMacOS()' is only available in macOS 10.50 or newer}} // expected-note@-1{{add 'if #available' version check}} extension TestStruct { func availableFunc() { unavailInExtension() // expected-error {{'unavailInExtension()' is unavailable in macOS}} obsoletedInExtension() // expected-error {{'obsoletedInExtension()' is unavailable}} deprecatedInExtension() // expected-warning {{'deprecatedInExtension()' was deprecated in macOS 10.0}} introducedInExtensionSwift() // expected-error {{'introducedInExtensionSwift()' is unavailable}} } } extension TestStruct { // expected-note{{add @available attribute to enclosing extension}} func availableFuncMacOS() { // expected-note{{add @available attribute to enclosing instance method}} introducedInExtensionMacOS() // expected-error {{'introducedInExtensionMacOS()' is only available in macOS 10.50 or newer}} // expected-note@-1{{add 'if #available' version check}} } } @available(macOS, introduced: 10.50) extension TestStruct { func futureFuncMacOS() { introducedInExtensionMacOS() } } @available(macOS, unavailable) struct UnavailableStruct { } @available(macOS, unavailable) extension UnavailableStruct { } // no-error #if os(macOS) @available(macOS, unavailable) extension UnavailableStruct { } // no-error #endif
{ "pile_set_name": "Github" }
<html xmlns="http://www.w3.org/1999/xhtml" class="reftest-wait"> <head> <script> function doDraw() { var ctx = document.getElementById('canvas').getContext('2d'); var grad = ctx.createLinearGradient(120,20,300,20); grad.addColorStop(0, '#0000ff'); grad.addColorStop(1, '#000000'); ctx.fillStyle = grad; ctx.fillRect(0,0,300,300); ctx = document.getElementById('canvas2').getContext('2d'); grad = ctx.createLinearGradient(30,300,30,0); grad.addColorStop(0, '#00ff00'); grad.addColorStop(1, '#000000'); ctx.fillStyle = grad; ctx.fillRect(0,0,300,300); document.documentElement.removeAttribute('class'); } </script> </head> <body onload="doDraw();"> <canvas id="canvas" width="300" height="300" style="position: absolute; top: 30px; left: 30px;"></canvas> <br/><br/> <canvas id="canvas2" width="300" height="300" style="position: absolute; top: 360px; left: 30px;"></canvas> </body> </html>
{ "pile_set_name": "Github" }
import re, urllib, sys, cPickle metra_pages={ 'Union Pacific North Line':[ ('http://www.metrarail.com/Sched/cnw_n/cnwn_wki.shtml',1), ('http://www.metrarail.com/Sched/cnw_n/cnwn_wko.shtml',1), ('http://www.metrarail.com/Sched/cnw_n/cnwn_sai.shtml',2), ('http://www.metrarail.com/Sched/cnw_n/cnwn_sao.shtml',2), ('http://www.metrarail.com/Sched/cnw_n/cnwn_sui.shtml',3), ('http://www.metrarail.com/Sched/cnw_n/cnwn_suo.shtml',3)], 'North Central Service':[ ('http://www.metrarail.com/Sched/ncs/ncs_wkin.shtml',1), ('http://www.metrarail.com/Sched/ncs/ncs_wkout.shtml',1)], 'Milwakee District North Line':[ ('http://www.metrarail.com/Sched/md_n/mdn_wki.shtml',1), ('http://www.metrarail.com/Sched/md_n/mdn_wko.shtml',1), ('http://www.metrarail.com/Sched/md_n/mdn_sai.shtml',2), ('http://www.metrarail.com/Sched/md_n/mdn_sao.shtml',2), ('http://www.metrarail.com/Sched/md_n/mdn_sui.shtml',3), ('http://www.metrarail.com/Sched/md_n/mdn_suo.shtml',3)], 'Union Pacific Northest Line':[ ('http://www.metrarail.com/Sched/cnw_nw/cnwnwwi.shtml',1), ('http://www.metrarail.com/Sched/cnw_nw/cnwnwwo.shtml',1), ('http://www.metrarail.com/Sched/cnw_nw/cnwnw6i.shtml',2), ('http://www.metrarail.com/Sched/cnw_nw/cnwnw6o.shtml',2), ('http://www.metrarail.com/Sched/cnw_nw/cnwnw7i.shtml',3), ('http://www.metrarail.com/Sched/cnw_nw/cnwnw7o.shtml',3)], 'Milwakee District West Line':[ ('http://www.metrarail.com/Sched/md_w/mdw_wki.shtml',1), ('http://www.metrarail.com/Sched/md_w/mdw_wko.shtml',1), ('http://www.metrarail.com/Sched/md_w/mdw_sai.shtml',2), ('http://www.metrarail.com/Sched/md_w/mdw_sao.shtml',2), ('http://www.metrarail.com/Sched/md_w/mdw_sui.shtml',3), ('http://www.metrarail.com/Sched/md_w/mdw_suo.shtml',3)], 'Union Pacific West Line':[ ('http://www.metrarail.com/Sched/cnw_w/cnwwwki.shtml',1), ('http://www.metrarail.com/Sched/cnw_w/cnwwwko.shtml',1), ('http://www.metrarail.com/Sched/cnw_w/cnwwsai.shtml',2), ('http://www.metrarail.com/Sched/cnw_w/cnwwsao.shtml',2), ('http://www.metrarail.com/Sched/cnw_w/cnwwsui.shtml',3), ('http://www.metrarail.com/Sched/cnw_w/cnwwsuo.shtml',3)], 'BNSF Railway Line':[ ('http://www.metrarail.com/Sched/bn/bn_wki.shtml',1), ('http://www.metrarail.com/Sched/bn/bn_wko.shtml',1), ('http://www.metrarail.com/Sched/bn/bn_sati.shtml',2), ('http://www.metrarail.com/Sched/bn/bn_sato.shtml',2), ('http://www.metrarail.com/Sched/bn/bn_suni.shtml',3), ('http://www.metrarail.com/Sched/bn/bn_suno.shtml',3)], 'Heritage Corridor':[ ('http://www.metrarail.com/Sched/mhc/mhc_all.shtml',1)], 'Southwest Service':[ ('http://www.metrarail.com/Sched/sws/sws_all.shtml',1)], 'Rock Island District Line':[ ('http://www.metrarail.com/Sched/ri/ri_wki.shtml',1), ('http://www.metrarail.com/Sched/ri/ri_wko.shtml',1), ('http://www.metrarail.com/Sched/ri/ri_sai.shtml',2), ('http://www.metrarail.com/Sched/ri/ri_sao.shtml',2), ('http://www.metrarail.com/Sched/ri/ri_sui.shtml',3), ('http://www.metrarail.com/Sched/ri/ri_suo.shtml',3)], #'Metra Electric Line':[ #('http://www.metrarail.com/Sched/me/me_msi.shtml',1), #('http://www.metrarail.com/Sched/me/me_mso.shtml',1), #('http://www.metrarail.com/Sched/me/me_msi.shtml',2), #('http://www.metrarail.com/Sched/me/me_mso.shtml',2), #('http://www.metrarail.com/Sched/me/me_sui.shtml',3), #('http://www.metrarail.com/Sched/me/me_suo.shtml',3)] } def parse(page): stop=0 routes={} nn=len('Kenosha (WI) LV') while 1: start=page.find('<pre><h4>',stop) if start<0: break stop=page.find('<hr',start) if stop<0: break table=page[start+9:stop] k=0 stations=[] for line in re.compile('<.+?>').sub(' ',table).split('\n'): if not line.strip(): continue if k==0: numbers=re.compile('\d+').findall(line) for number in numbers: routes[number]=[] elif k==1: ampm=re.compile('(AM|PM)').findall(line) else: name=re.sub('\s+',' ',line[:nn].strip()) stations.append(name) times=re.compile('[\d\:\.]+|[\-]+|[\|]').findall(line[nn:]) for i,x in enumerate(times): if not x in ['|','----','-','--','---']: h,m=x.split(':') if x.find(':')>0 else x.split('.') t=int(h)*60+int(m) if ampm[i].lower()=='pm' and not int(h)==12: t+=12*60 elif ampm[i].lower()=='am' and int(h)==12: t+=12*60 t=t%(24*60) routes[numbers[i]].append((name,t)) k+=1 return routes if __name__=='__main__': obj=[] for line,items in metra_pages.items(): for item in items: print line, item page=urllib.urlopen(item[0]).read() obj.append((line,item[1],parse(page))) cPickle.dump(obj,open('metra.pickle','w'))
{ "pile_set_name": "Github" }