Convert a layer2 scan_filter parameter into the
        structure required by Layer1.
480798
def dynamize_scan_filter(self, scan_filter):
        
        d = None
        if scan_filter:
            d = {}
            for attr_name, op, value in scan_filter:
                if op == 'BETWEEN':
                    if isinstance(value, tuple):
                        avl = [self.dynamize_value(v) for v in value]
                    else:
                        msg = 'BETWEEN condition requires a tuple value'
                        raise TypeError(msg)
                elif op == 'NULL' or op == 'NOT_NULL':
                    avl = None
                elif isinstance(value, tuple):
                    msg = 'Tuple can only be supplied with BETWEEN condition'
                    raise TypeError(msg)
                else:
                    avl = [self.dynamize_value(value)]
            dd = {'ComparisonOperator': op}
            if avl:
                dd['AttributeValueList'] = avl
            d[attr_name] = dd
        return d
1013746
def apply_filters prev_filters = nil, filter_codecs = nil
      prev_filters = filter_types if prev_filters.nil?
      filter_codecs = [] if filter_codecs.nil?
      current_filters = []
      prev = nil
      line_sizes = []
      scanline_positions.push(@filtered_data.size).inject do |m, n|
        line_sizes << n - m - 1
        n
      end
      wrap_with_rewind(@filtered_data) do
        # decode all scanlines
        prev_filters.each_with_index do |type, i|
          byte = @filtered_data.read 1
          current_filters << byte.unpack('C').first
          line_size = line_sizes[i]
          line = @filtered_data.read line_size
          filter = Filter.new type, @sample_size
          if filter_codecs[i] && filter_codecs[i][:decoder]
            filter.decoder = filter_codecs[i][:decoder]
          end
          if !prev.nil? && @interlace_pass_count.include?(i + 1)  # make sure prev to be nil if interlace pass is changed
            prev = nil
          end
          decoded = filter.decode line, prev
          @filtered_data.pos -= line_size
          @filtered_data << decoded
          prev = decoded
        end
        # encode all
        filter_codecs.reverse!
        line_sizes.reverse!
        data_amount = @filtered_data.pos # should be eof
        ref = data_amount
        current_filters.reverse_each.with_index do |type, i|
          line_size = line_sizes[i]
          ref -= line_size + 1
          @filtered_data.pos = ref + 1
          line = @filtered_data.read line_size
          prev = nil
          if !line_sizes[i + 1].nil?
            @filtered_data.pos = ref - line_size
            prev = @filtered_data.read line_size
          end
          # make sure prev to be nil if interlace pass is changed
          if @interlace_pass_count.include?(current_filters.size - i)
            prev = nil
          end
          filter = Filter.new type, @sample_size
          if filter_codecs[i] && filter_codecs[i][:encoder]
            filter.encoder = filter_codecs[i][:encoder]
          end
          encoded = filter.encode line, prev
          @filtered_data.pos = ref + 1
          @filtered_data << encoded
        end
      end
    end
338967
function (filters, tpl) {
      for (var i = 0; i < filters.length; ++i) {
        tpl = filters[i](tpl)
      }
      return tpl
    }
515723
def expand_src_param(values, shp_params):
    
    if values is None:
        return dict([(key, None) for key, _ in shp_params])
    else:
        num_values = len(values)
        return dict(
            [(key, float(values[i]) if i < num_values else None)
                for i, (key, _) in enumerate(shp_params)])
1024584
def _finish_filter(self, lst, key, include_self, exclusive, biggest_first):
        """"""
        key = self._actual_key(key)
        locations = [x[0] for x in lst]

        if not include_self and key in locations:
            lst.pop(locations.index(key))

        lst.sort(key=lambda x: x[1], reverse=biggest_first)
        lst = [x for x, y in lst]

        # RoW in both key and lst, but not defined; only RoW remains if exclusive
        if key == 'RoW' and 'RoW' not in self and exclusive:
            return ['RoW'] if 'RoW' in lst else []
        elif exclusive:
            removed, remaining = set(), []
            while lst:
                current = lst.pop(0)
                faces = self[current]
                if not faces.intersection(removed):
                    removed.update(faces)
                    remaining.append(current)
            lst = remaining

        # If RoW not resolved, make it the smallest
        if 'RoW' not in self and 'RoW' in lst:
            lst[-1 if biggest_first else 0] = lst.pop(lst.index('RoW'))

        return lst
512101
def partition(predicate, iterable):
    

    t1, t2 = tee(iterable)

    return filterfalse(predicate, t1), filter(predicate, t2)
1271123
def init_net_params(scale, layer_sizes, rs=npr.RandomState(0)):
    """"""
    return [(scale * rs.randn(m, n),   # weight matrix
             scale * rs.randn(n))      # bias vector
            for m, n in zip(layer_sizes[:-1], layer_sizes[1:])]
552374
def convolutional_layer_series(initial_size, layer_sequence):
    
    size = initial_size

    for filter_size, padding, stride in layer_sequence:
        size = convolution_size_equation(size, filter_size, padding, stride)

    return size
945703
def drill_filter(esfilter, data):
    
    esfilter = unwrap(esfilter)
    primary_nested = []  # track if nested, changes if not
    primary_column = []  # only one path allowed
    primary_branch = (
        []
    )  # CONTAINS LISTS OF RECORDS TO ITERATE: constantly changing as we dfs the tree

    def parse_field(fieldname, data, depth):
        """
        RETURN (first, rest) OF fieldname
        """
        col = split_field(fieldname)
        d = data
        for i, c in enumerate(col):
            try:
                d = d[c]
            except Exception as e:
                Log.error("{{name}} does not exist", name=fieldname)
            if is_list(d) and len(col) > 1:
                if len(primary_column) <= depth + i:
                    primary_nested.append(True)
                    primary_column.append(c)
                    primary_branch.append(d)
                elif primary_nested[depth] and primary_column[depth + i] != c:
                    Log.error("only one branch of tree allowed")
                else:
                    primary_nested[depth + i] = True
                    primary_column[depth + i] = c
                    primary_branch[depth + i] = d

                return c, join_field(col[i + 1 :])
            else:
                if len(primary_column) <= depth + i:
                    primary_nested.append(False)
                    primary_column.append(c)
                    primary_branch.append([d])
        return fieldname, None

    def pe_filter(filter, data, depth):
        """
        PARTIAL EVALUATE THE filter BASED ON data GIVEN
        """
        if filter is TRUE:
            return True
        if filter is FALSE:
            return False

        filter = wrap(filter)

        if filter["and"]:
            result = True
            output = FlatList()
            for a in filter["and"]:
                f = pe_filter(a, data, depth)
                if f is False:
                    result = False
                elif f is not True:
                    output.append(f)
            if result and output:
                return {"and": output}
            else:
                return result
        elif filter["or"]:
            output = FlatList()
            for o in filter["or"]:
                f = pe_filter(o, data, depth)
                if f is True:
                    return True
                elif f is not False:
                    output.append(f)
            if output:
                return {"or": output}
            else:
                return False
        elif filter["not"]:
            f = pe_filter(filter["not"], data, depth)
            if f is True:
                return False
            elif f is False:
                return True
            else:
                return {"not": f}
        elif filter.term or filter.eq:
            eq = coalesce(filter.term, filter.eq)
            result = True
            output = {}
            for col, val in eq.items():
                first, rest = parse_field(col, data, depth)
                d = data[first]
                if not rest:
                    if d != val:
                        result = False
                else:
                    output[rest] = val

            if result and output:
                return {"term": output}
            else:
                return result
        elif filter.equal:
            a, b = filter["equal"]
            first_a, rest_a = parse_field(a, data, depth)
            first_b, rest_b = parse_field(b, data, depth)
            val_a = data[first_a]
            val_b = data[first_b]
            if not rest_a:
                if not rest_b:
                    if val_a != val_b:
                        return False
                    else:
                        return True
                else:
                    return {"term": {rest_b: val_a}}
            else:
                if not rest_b:
                    return {"term": {rest_a: val_b}}
                else:
                    return {"equal": [rest_a, rest_b]}

        elif filter.terms:
            result = True
            output = {}
            for col, vals in filter["terms"].items():
                first, rest = parse_field(col, data, depth)
                d = data[first]
                if not rest:
                    if d not in vals:
                        result = False
                else:
                    output[rest] = vals
            if result and output:
                return {"terms": output}
            else:
                return result

        elif filter.range:
            result = True
            output = {}
            for col, ranges in filter["range"].items():
                first, rest = parse_field(col, data, depth)
                d = data[first]
                if not rest:
                    for sign, val in ranges.items():
                        if sign in ("gt", ">") and d <= val:
                            result = False
                        if sign == "gte" and d < val:
                            result = False
                        if sign == "lte" and d > val:
                            result = False
                        if sign == "lt" and d >= val:
                            result = False
                else:
                    output[rest] = ranges
            if result and output:
                return {"range": output}
            else:
                return result
        elif filter.missing:
            if is_text(filter.missing):
                field = filter["missing"]
            else:
                field = filter["missing"]["field"]

            first, rest = parse_field(field, data, depth)
            d = data[first]
            if not rest:
                if d == None:
                    return True
                return False
            else:
                return {"missing": rest}
        elif filter.prefix:
            result = True
            output = {}
            for col, val in filter["prefix"].items():
                first, rest = parse_field(col, data, depth)
                d = data[first]
                if not rest:
                    if d == None or not d.startswith(val):
                        result = False
                else:
                    output[rest] = val
            if result and output:
                return {"prefix": output}
            else:
                return result

        elif filter.exists:
            if is_text(filter["exists"]):
                field = filter["exists"]
            else:
                field = filter["exists"]["field"]

            first, rest = parse_field(field, data, depth)
            d = data[first]
            if not rest:
                if d != None:
                    return True
                return False
            else:
                return {"exists": rest}
        else:
            Log.error("Can not interpret esfilter: {{esfilter}}", {"esfilter": filter})

    output = []  # A LIST OF OBJECTS MAKING THROUGH THE FILTER

    def main(sequence, esfilter, row, depth):
        """
        RETURN A SEQUENCE OF REFERENCES OF OBJECTS DOWN THE TREE
        SHORT SEQUENCES MEANS ALL NESTED OBJECTS ARE INCLUDED
        """
        new_filter = pe_filter(esfilter, row, depth)
        if new_filter is True:
            seq = list(sequence)
            seq.append(row)
            output.append(seq)
            return
        elif new_filter is False:
            return

        seq = list(sequence)
        seq.append(row)
        for d in primary_branch[depth]:
            main(seq, new_filter, d, depth + 1)

    # OUTPUT
    for i, d in enumerate(data):
        if is_data(d):
            main([], esfilter, wrap(d), 0)
        else:
            Log.error("filter is expecting a dict, not {{type}}", type=d.__class__)

    # AT THIS POINT THE primary_column[] IS DETERMINED
    # USE IT TO EXPAND output TO ALL NESTED OBJECTS
    max = 0  # EVEN THOUGH A ROW CAN HAVE MANY VALUES, WE ONLY NEED UP TO max
    for i, n in enumerate(primary_nested):
        if n:
            max = i + 1

    # OUTPUT IS A LIST OF ROWS,
    # WHERE EACH ROW IS A LIST OF VALUES SEEN DURING A WALK DOWN A PATH IN THE HIERARCHY
    uniform_output = FlatList()

    def recurse(row, depth):
        if depth == max:
            uniform_output.append(row)
        else:
            nested = row[-1][primary_column[depth]]
            if not nested:
                # PASSED FILTER, BUT NO CHILDREN, SO ADD NULL CHILDREN
                for i in range(depth, max):
                    row.append(None)
                uniform_output.append(row)
            else:
                for d in nested:
                    r = list(row)
                    r.append(d)
                    recurse(r, depth + 1)

    for o in output:
        recurse(o, 0)

    if not max:
        # SIMPLE LIST AS RESULT
        return wrap([unwrap(u[0]) for u in uniform_output])

    return PartFlatList(primary_column[0:max], uniform_output)
79470
def _get_struct_filterlist(self):
        """"""
        obj = _make_object("FilterList")
        obj.NumberOfFilters = unpack_ui8(self._src)
        obj.Filter = filters = []
        # how to decode each filter type (and name), according to the filter id
        filter_type = [
            ("DropShadowFilter", self._get_struct_dropshadowfilter),  # 0
            ("BlurFilter", self._get_struct_blurfilter),  # 1
            ("GlowFilter", self._get_struct_glowfilter),  # 2...
            ("BevelFilter", self._get_struct_bevelfilter),
            ("GradientGlowFilter", self._get_struct_gradientglowfilter),
            ("ConvolutionFilter", self._get_struct_convolutionfilter),
            ("ColorMatrixFilter", self._get_struct_colormatrixfilter),
            ("GradientBevelFilter", self._get_struct_gradientbevelfilter),  # 7
        ]

        for _ in range(obj.NumberOfFilters):
            _filter = _make_object("Filter")
            filters.append(_filter)

            _filter.FilterId = unpack_ui8(self._src)
            name, func = filter_type[_filter.FilterId]
            setattr(_filter, name, func())
983075
def wrap_filters(filters):
  
  def combined_filter(x):
    for filt in filters:
      if not filt(x):
        return False
    return True
  return combined_filter
1285332
def _merge_filters(self) -> None:
        """"""
        for opts in (["-filter:a", "-af"], ["-filter:v", "-vf"]):
            filter_list = []
            new_argv = []
            cmd_iter = iter(self._argv)
            for element in cmd_iter:
                if element in opts:
                    filter_list.insert(0, next(cmd_iter))
                else:
                    new_argv.append(element)

            # update argv if changes
            if filter_list:
                new_argv.extend([opts[0], ",".join(filter_list)])
                self._argv = new_argv.copy()
566650
function filterTransform (args, math, scope) {
    let x, callback

    if (args[0]) {
      x = args[0].compile().evaluate(scope)
    }

    if (args[1]) {
      if (isSymbolNode(args[1]) || isFunctionAssignmentNode(args[1])) {
        // a function pointer, like filter([3, -2, 5], myTestFunction)
        callback = args[1].compile().evaluate(scope)
      } else {
        // an expression like filter([3, -2, 5], x > 0)
        callback = compileInlineExpression(args[1], math, scope)
      }
    }

    return filter(x, callback)
  }
579006
def _replace_layer(self, layer_id, new_layer):
        """"""
        old_layer = self.layer_list[layer_id]
        new_layer.input = old_layer.input
        new_layer.output = old_layer.output
        new_layer.output.shape = new_layer.output_shape
        self.layer_list[layer_id] = new_layer
        self.layer_to_id[new_layer] = layer_id
        self.layer_to_id.pop(old_layer)
288693
def undo_filter_paeth(filter_unit, scanline, previous, result):
    """"""

    # Also used for ci.
    ai = -filter_unit
    for i in range(len(result)):
        x = scanline[i]
        if ai < 0:
            a = c = 0
        else:
            a = result[ai]
            c = previous[ai]
        b = previous[i]
        p = a + b - c
        pa = abs(p - a)
        pb = abs(p - b)
        pc = abs(p - c)
        if pa <= pb and pa <= pc:
            pr = a
        elif pb <= pc:
            pr = b
        else:
            pr = c
        result[i] = (x + pr) & 0xff
        ai += 1
254078
def slicenet_internal(inputs, targets, target_space, hparams, run_decoder=True):
  """"""
  with tf.variable_scope("slicenet"):
    # Project to hidden size if necessary
    if inputs.get_shape().as_list()[-1] != hparams.hidden_size:
      inputs = common_layers.conv_block(
          inputs,
          hparams.hidden_size, [((1, 1), (3, 3))],
          first_relu=False,
          padding="SAME",
          force2d=True)

    # Flatten inputs and encode.
    inputs = tf.expand_dims(common_layers.flatten4d3d(inputs), axis=2)
    inputs_mask = 1.0 - embedding_to_padding(inputs)
    inputs = common_layers.add_timing_signal(inputs)  # Add position info.
    target_space_emb = embed_target_space(target_space, hparams.hidden_size)
    extra_layers = int(hparams.num_hidden_layers * 1.5)
    inputs_encoded = multi_conv_res(
        inputs, "SAME", "encoder", extra_layers, hparams, mask=inputs_mask)
    if not run_decoder:
      return inputs_encoded
    # Do the middle part.
    decoder_start, similarity_loss = slicenet_middle(
        inputs_encoded, targets, target_space_emb, inputs_mask, hparams)
    # Decode.
    decoder_final = multi_conv_res(
        decoder_start,
        "LEFT",
        "decoder",
        hparams.num_hidden_layers,
        hparams,
        mask=inputs_mask,
        source=inputs_encoded)
    return decoder_final, tf.reduce_mean(similarity_loss)
586998
def get_value_filter(self, filter_value):
        '''
        
        '''
        self.validate_parameter(filter_value)
        f, t = self._ranges[filter_value]
        limits = {}
        # lt and gte to ensure non-overlapping ranges
        if f is not None:
            limits['gte'] = f
        if t is not None:
            limits['lt'] = t

        return Q('range', **{
            self._params['field']: limits
        })