text:
/*
 * patPublicTransportSegment.cc
 *
 *  Created on: Jul 22, 2011
 *      Author: jchen
 */

#include "patPublicTransportSegment.h"
#include "patNetworkElements.h"
#include "patDisplay.h"
patPublicTransportSegment::patPublicTransportSegment() {
	m_length = -1.0;
}

patPublicTransportSegment::~patPublicTransportSegment() {
	//
}

bool operator==(const patPublicTransportSegment& seg_a, const patPublicTransportSegment& seg_b){
	vector<const patArc*> arc_list_a = seg_a.getArcList();
	vector<const patArc*> arc_list_b = seg_b.getArcList();
	if (arc_list_a.size()!=arc_list_b.size()){
		return false;
	}
	vector<const patArc*>::iterator iter_a =arc_list_a.begin();
	vector<const patArc*>::iterator iter_b =arc_list_b.begin();
	while(iter_a!=arc_list_a.end()){
		if(*iter_a != *iter_b){
			return false;
		}
		++iter_a;
		++iter_b;
	}
	return true;

}
bool operator<(const patPublicTransportSegment& seg_a, const patPublicTransportSegment& seg_b){
	if(seg_a.getLength()<seg_b.getLength()){
		return true;
	}
	if(seg_a.getLength()>seg_b.getLength()){
			return false;
	}
	if(seg_a.size()<seg_b.size()){
		return true;
	}
	if(seg_a.size()>seg_b.size()){
			return false;
	}

	vector<const patArc*> arc_list_a = seg_a.getArcList();
	vector<const patArc*> arc_list_b = seg_b.getArcList();
	vector<const patArc*>::iterator iter_a =arc_list_a.begin();
	vector<const patArc*>::iterator iter_b =arc_list_b.begin();
	while(iter_a!=arc_list_a.end()){
		if(*iter_a < *iter_b){
			return true;
		}
		else if(*iter_a > *iter_b){
			return false;
		}
		++iter_a;
		++iter_b;
	}
	return false;

}
ostream& operator<<(ostream& str, const patPublicTransportSegment& x) {
	vector<const patArc*> arc_list = x.getArcList();
	for (vector<const patArc*>::iterator arc_iter = arc_list.begin();
			arc_iter != arc_list.end(); ++arc_iter) {
		str << **arc_iter << "\n";
	}
}

 bool patPublicTransportSegment::addArcToBack(const patArc* arc,
		int direction) {
	if (m_directions.back() != 3 && direction != 3) {
		if (m_directions.back() != direction) {
			return false;
		}
	}
	if (patArcSequence::addArcToBack(arc) == false) {
		return false;
	}
	m_directions.push_back(direction);
	return true;
}
 const patArc* patPublicTransportSegment::deleteArcToBack() {

	if (m_arcs.empty() || m_directions.empty()) {
		return NULL;
	}
	const patArc* backArc = m_arcs.back();
	m_arcs.pop_back();
	m_directions.pop_back();
	return backArc;
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>REU Site: The Summer Institute for Nano- and Biomaterials Research at Carnegie Mellon University</AwardTitle>
    <AwardEffectiveDate>05/01/2010</AwardEffectiveDate>
    <AwardExpirationDate>04/30/2013</AwardExpirationDate>
    <AwardAmount>525000</AwardAmount>
    <AwardInstrument>
      <Value>Continuing grant</Value>
    </AwardInstrument>
    <Organization>
      03070000
      <Directorate>
        <LongName>Direct For Mathematical & Physical Scien</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Materials Research</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Michael J. Scott</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>The Research Experiences for Undergraduates (REU) Site at Carnegie Mellon University (CMU), the Summer Institute for Nano- and Biomaterials Research, will expose fifteen science and engineering undergraduates to cutting edge research each year. The student research projects are highly interdisciplinary, spanning seven departments and two colleges at CMU, including intra- and inter-departmental collaborations between researchers, allowing the students to interact with faculty, graduate and undergraduate students from a wide variety of disciplines. This REU site at Carnegie Mellon will positively impact the emerging nano- and biomaterials fields by providing educated personnel. The institute includes a summer curriculum development program for high school teachers that will raise the level of awareness about the emerging science of nano- and biomaterials among pre-college students.</AbstractNarration>
    <MinAmdLetterDate>04/29/2010</MinAmdLetterDate>
    <MaxAmdLetterDate>12/07/2011</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1005076</AwardID>
    <Investigator>
      <FirstName>Mohammad</FirstName>
      <LastName>Islam</LastName>
      <EmailAddress>mohammad@andrew.cmu.edu</EmailAddress>
      <StartDate>04/29/2010</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Gregory</FirstName>
      <LastName>Rohrer</LastName>
      <EmailAddress>gr20@andrew.cmu.edu</EmailAddress>
      <StartDate>04/29/2010</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Carnegie-Mellon University</Name>
      <CityName>PITTSBURGH</CityName>
      <ZipCode>152133815</ZipCode>
      <PhoneNumber>4122689527</PhoneNumber>
      <StreetAddress>5000 Forbes Avenue</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Pennsylvania</StateName>
      <StateCode>PA</StateCode>
    </Institution>
    <FoaInformation>
      0106000
      <Name>Materials Research</Name>
    </FoaInformation>
    <ProgramElement>
      7222
      <Text>XC-Crosscutting Activities Pro</Text>
    </ProgramElement>
    <ProgramReference>
      7237
      <Text>NANO NON-SOLIC SCI & ENG AWD</Text>
    </ProgramReference>
    <ProgramReference>
      9161
      <Text>SINGLE DIVISION/UNIVERSITY</Text>
    </ProgramReference>
    <ProgramReference>
      9178
      <Text>UNDERGRADUATE EDUCATION</Text>
    </ProgramReference>
    <ProgramReference>
      9250
      <Text>RES EXPER FOR UNDERGRADS-SITE</Text>
    </ProgramReference>
    <ProgramReference>
      7573
      <Text>BIO-RELATED MATERIALS RESEARCH</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 297028 $ -->
<chapter xml:id="phar.creating" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <title>Creating Phar Archives</title>

 <section xml:id="phar.creating.intro" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <title>Creating Phar Archives: Introduction</title>
 <para>
  To be written fully in the near future.  Before reading this, be sure to read
  <link linkend="phar.using">How to use Phar Archives</link>.
 </para>
 <para>
  A great place to start is by reading about <function>Phar::buildFromIterator</function>,
  and the specifics of the <link linkend="phar.fileformat">file format</link> choices
  available for archives.  A healthy understanding of what a stub is and does is crucial
  to phar archive creation, and so <function>Phar::setStub</function> and
  <function>Phar::createDefaultStub</function> are good places to start as well.
  If you are distributing a web-based application, it is crucial to know about
  <function>Phar::webPhar</function> and related method
  <function>Phar::mungServer</function>.  Any application that accesses
  its own files should also consider using <function>Phar::interceptFileFuncs</function>.
 </para>
</section>
</chapter>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
package org.apache.geode.redis.internal.executor.sortedset;

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

import org.apache.geode.cache.Region;
import org.apache.geode.cache.query.Query;
import org.apache.geode.cache.query.SelectResults;
import org.apache.geode.redis.internal.ByteArrayWrapper;
import org.apache.geode.redis.internal.Coder;
import org.apache.geode.redis.internal.Command;
import org.apache.geode.redis.internal.DoubleWrapper;
import org.apache.geode.redis.internal.ExecutionHandlerContext;
import org.apache.geode.redis.internal.RedisConstants.ArityDef;
import org.apache.geode.redis.internal.RedisDataType;
import org.apache.geode.redis.internal.executor.SortedSetQuery;

public class ZRemRangeByLexExecutor extends SortedSetExecutor {

  private final int ERROR_NOT_EXISTS = 0;

  private final String ERROR_ILLEGAL_SYNTAX =
      "The min and max strings must either start with a (, [ or be - or +";

  @Override
  public void executeCommand(Command command, ExecutionHandlerContext context) {
    List<byte[]> commandElems = command.getProcessedCommand();

    if (commandElems.size() < 4) {
      command.setResponse(
          Coder.getErrorResponse(context.getByteBufAllocator(), ArityDef.ZREMRANGEBYLEX));
      return;
    }

    ByteArrayWrapper key = command.getKey();

    checkDataType(key, RedisDataType.REDIS_SORTEDSET, context);
    Region<ByteArrayWrapper, DoubleWrapper> keyRegion = getRegion(context, key);

    if (keyRegion == null) {
      command
          .setResponse(Coder.getIntegerResponse(context.getByteBufAllocator(), ERROR_NOT_EXISTS));
      return;
    }

    boolean minInclusive = false;
    boolean maxInclusive = false;

    byte[] minArray = commandElems.get(2);
    byte[] maxArray = commandElems.get(3);
    String startString = Coder.bytesToString(minArray);
    String stopString = Coder.bytesToString(maxArray);

    if (minArray[0] == Coder.OPEN_BRACE_ID) {
      startString = startString.substring(1);
      minInclusive = false;
    } else if (minArray[0] == Coder.OPEN_BRACKET_ID) {
      startString = startString.substring(1);
      minInclusive = true;
    } else if (minArray[0] != Coder.HYPHEN_ID) {
      command
          .setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ERROR_ILLEGAL_SYNTAX));
      return;
    }

    if (maxArray[0] == Coder.OPEN_BRACE_ID) {
      stopString = stopString.substring(1);
      maxInclusive = false;
    } else if (maxArray[0] == Coder.OPEN_BRACKET_ID) {
      stopString = stopString.substring(1);
      maxInclusive = true;
    } else if (maxArray[0] != Coder.PLUS_ID) {
      command
          .setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ERROR_ILLEGAL_SYNTAX));
      return;
    }

    Collection<ByteArrayWrapper> removeList;
    try {
      removeList = getRange(key, keyRegion, context, Coder.stringToByteArrayWrapper(startString),
          Coder.stringToByteArrayWrapper(stopString), minInclusive, maxInclusive);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    int numRemoved = 0;

    for (ByteArrayWrapper entry : removeList) {
      Object oldVal = keyRegion.remove(entry);
      if (oldVal != null)
        numRemoved++;
    }

    command.setResponse(Coder.getIntegerResponse(context.getByteBufAllocator(), numRemoved));
  }

  private Collection<ByteArrayWrapper> getRange(ByteArrayWrapper key,
      Region<ByteArrayWrapper, DoubleWrapper> keyRegion, ExecutionHandlerContext context,
      ByteArrayWrapper start, ByteArrayWrapper stop, boolean startInclusive, boolean stopInclusive)
      throws Exception {
    if (start.equals(minus) && stop.equals(plus))
      return new ArrayList<ByteArrayWrapper>(keyRegion.keySet());
    else if (start.equals(plus) || stop.equals(minus))
      return null;

    Query query;
    Object[] params;
    if (start.equals(minus)) {
      if (stopInclusive) {
        query = getQuery(key, SortedSetQuery.ZRANGEBYLEXNINFI, context);
      } else {
        query = getQuery(key, SortedSetQuery.ZRANGEBYLEXNINF, context);
      }
      params = new Object[] {stop, INFINITY_LIMIT};
    } else if (stop.equals(plus)) {
      if (startInclusive) {
        query = getQuery(key, SortedSetQuery.ZRANGEBYLEXPINFI, context);
      } else {
        query = getQuery(key, SortedSetQuery.ZRANGEBYLEXPINF, context);
      }
      params = new Object[] {start, INFINITY_LIMIT};
    } else {
      if (startInclusive) {
        if (stopInclusive) {
          query = getQuery(key, SortedSetQuery.ZRANGEBYLEXSTISI, context);
        } else {
          query = getQuery(key, SortedSetQuery.ZRANGEBYLEXSTI, context);
        }
      } else {
        if (stopInclusive) {
          query = getQuery(key, SortedSetQuery.ZRANGEBYLEXSI, context);
        } else {
          query = getQuery(key, SortedSetQuery.ZRANGEBYLEX, context);
        }
      }
      params = new Object[] {start, stop, INFINITY_LIMIT};
    }

    @SuppressWarnings("unchecked")
    SelectResults<ByteArrayWrapper> results =
        (SelectResults<ByteArrayWrapper>) query.execute(params);

    return results.asList();
  }

}


text:
require 'builder'
require 'singleton'

module Debugger
  module Formatters
    class Xml
      include Singleton

      def xml
        Builder::XmlMarkup.new indent: 2
      end

      def message msg, *args
        xml.message do
          msg % args
        end
      end

      def debug msg, *args
        Debugger.print_debug msg, *args
        if Debugger.remote_debug
          xml.message debug: true do
            msg % args
          end
        end
      end

      def error msg, *args
        xml.error do
          msg % args
        end
      end

      def frames context, current_frame_id
        xml.frames do |frames|
          (0 ... context.stack_size).each do |id|
            frame_attributes =  {
              no: id + 1,
              file: File.expand_path(context.frame_file(id)),
              line: context.frame_line(id)
            }
            frame_attributes[:current] = true if id == current_frame_id

            frames.frame frame_attributes
          end
        end
      end

      def contexts contexts
        xml.threads do |thr|
          contexts.each do |c|
            thread_attributes = {
              id: c.thnum,
              status: c.thread.status,
              pid: Process.pid
            }
            thread_attributes[:current] = true if context.thread == Thread.current
            thr.thread thread_attributes
          end
        end
      end

      def array array
        xml.variables do |vars|
          array.each_with_index do |item, idx|
            variable vars, "[#{i}]", item, 'instance'
          end
        end
      end

      def hash hash
        xml.variables do |vars|
          hash.each_pair do |k,v|
            name = k.acts_like_string? ? "'#{k}'" : k.to_s
            variable vars, name, v, 'instance'
          end
        end
      end

      def breakpoint(breakpts)
        xml.breakpoints do |bps|
          breakpts.sort_by { |b| b.id }.each do |b|
            bps.breakpoint n: b.id, file: b.source, line: b.pos
          end
        end
      end

      def breakpoint_added(b)
        xml.breakpointAdded no: b.id, location: "#{b.source}:#{b.pos}"
      end

      def breakpoint_deleted(b)
        xml.breakpointDeleted no: b.id
      end

      def breakpoint_enabled(b)
        xml.breakpointEnabled bp_id: b.id
      end

      def breakpoint_disabled(b)
        xml.breakpointDisabled bp_id: b.id
      end

      def condition_set bp_id
        xml.conditionSet bp_id: bp_id
      end

      def catchpoint_set exception_class_name
        xml.catchpointSet exception: exception_class_name
      end

      def expressions exps
        xml.expressions do
          expressions.each_with_index do |(exp, value), idx|
            xml.display name: exp, value: value, no: idx
          end
        end
      end

      def eval exp, value
        xml.eval expression: exp, value: value
      end

      def pp value
        value
      end

      def list b, e, file, line
        str = "[#{b}, #{e}] in #{file}"
        if lines = Debugger.source_for(file)
          b.upto(e) do |n|
            if n > 0 && lines[n-1]
              if n == line
                str += "=> #{n}  #{lines[n-1].chomp}"
              else
                str += "   #{n}  #{lines[n-1].chomp}"
              end
            end
          end
        else
          str = "No sourcefile available for #{file}"
        end
      end

      def methods methods
        xml.methods do |meths|
          methods.each do |method|
            meths.method name: method
          end
        end
      end

      def breakpoint n, breakpoint
        breakpoint_attributes = {
          file:       breakpoint.source,
          line:       breakpoint.pos,
          threadId:   Debugger.current_context.thnum
        }
        xml.breakpoint breakpoint_attributes
      end

      def catchpoint
        context = Debugger.current_context
        catchpoint_attributes = {
          file:       context.frame_file(0),
          line:       context.frame_line(0),
          type:       exception.class,
          message:    exception.message,
          threadId:   context.thnum
        }
        xml.exception catchpoint_attributes
      end

      def trace context, file, line
        trace_attributes = {
          file:       file,
          line:       line,
          threadId:   context.thnum
        }
        xml.trace trace_attributes
      end

      def at_line context, file, line
        suspend_attributes = {
          file:      File.expand_path(file),
          line:      line,
          context:   context.thnum,
          frames:    context.stack_size
        }
        xml.suspended suspend_attributes
      end

      def exception exception, binding
        variables("error", "exception") do |var|
          proxy = Debugger::ExceptionProxy.new(exception)
          InspectCommand.reference_result(proxy)
          proxy
        end
      rescue
        xml.processingException type: exception.class, message: exception.messages
      end

      def inspect eval_result
        xml.variables do |vars|
          variable vars, "eval_result", eval_results, "local"
        end
      end

      def load_results file, exception
        if exception
          xml.loadResult file: file, exceptionType: exception.class, exceptionMessage: exception.message
        else
          xml.loadResult file: file, status: "OK"
        end
      end

      def variables variables, kind
        xml.variables do |vars|
          if vars.include? 'self'
            variable vars, 'self', yield('self'), kind
          end

          vars.sort.each do |v|
            variable(vars, v, yield(v), kind) unless v == 'self'
          end
        end
      end

      private
      def variable builder, name, value, kind
        name = name.to_s
        has_children = false
        if value.nil?
          builder.variable name: name, kind: kind
          return
        end

        if value.is_a?(Array) || value.is_a?(Hash)
          unless value.empty?
            has_children = true
            value_str = "#{value.class} (#{value.size} elements(s))"
          else
            has_children = false
            value_str = "Empty #{value.class}"
          end
        else
          has_children = !value.instance_variables.empty? || !value.class.class_variables.empty?
          value_str = value.to_s || 'nil' rescue "<#to_s method raised exception ##{$!}>"
          unless value_str.acts_like_string?
            value_str = "ERROR: #{value.class}.to_s method returns #{value_str.class}. Should return String."
          end
        end

        if value_str.andand.is_binary_data?
          value_str = "[Binary Data]"
        end
        variable_attributes = {
          name:          name,
          kind:          kind,
          value:         value_str,
          type:          value.class,
          hasChildren:   has_children,
          objectId:      value.andand.object_id || value.id
        }

        builder.variable variable_attributes
      end
    end
  end
end


text:
package com.carloseduardo.movie.search.ui.movies;

import android.os.Bundle;
import android.support.v7.widget.Toolbar;

import com.carloseduardo.movie.search.R;
import com.carloseduardo.movie.search.base.BaseActivity;
import com.carloseduardo.movie.search.data.source.MoviesRepository;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MoviesActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @Inject
    MoviesRepository moviesRepository;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.movies_activity);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);

        configureMoviesFragment();
    }

    private void configureMoviesFragment() {

        MoviesFragment moviesFragment = new MoviesFragment();
        new MoviesPresenter(moviesFragment, moviesRepository);

        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.movies_coordinator, moviesFragment)
                .commit();

    }

    @Override
    protected void inject() {

        getComponent().inject(this);
    }
}


text:
//
//  tool_router.c
//  cpili
//
//  Created by 0dayZh on 15/9/16.
//  Copyright (c) 2015年 pili-engineering. All rights reserved.
//

#include "tool_router.h"
#include "tool_help.h"
#include "tool_version.h"
#include "protocol_defines.h"

#include <string.h>
#include <unistd.h>

/**
 * flv -> rtmp
 */
static void flv2rtmp(cpili_task_param_t param) {
    puts("FLV file -> RTMP stream");
    cpili_url_context_t flv_ctx, rtmp_ctx;

    flv_ctx.url = param.input.options.file_path;
    flv_ctx.user_data = NULL;

    rtmp_ctx.url = param.output.options.url;
    rtmp_ctx.user_data = NULL;

    for (int i = 0; i < PROTOCOL_COUNT; i++) {
        cpili_protocol_t protocol = protocols[i];

        if (!strcmp("flv", protocol.name)) {
            cpili_protocol_cpy(flv_ctx.protocol, protocol);
        } else if (!strcmp("rtmp", protocol.name)) {
            cpili_protocol_cpy(rtmp_ctx.protocol, protocol);
        }
    }

    if (!flv_ctx.protocol.url_open(&flv_ctx, flv_ctx.url)) {
        puts("fail to open flv file");
        return;
    }

    if (rtmp_ctx.protocol.url_open(&rtmp_ctx, rtmp_ctx.url)) {
        puts("fail to connect rtmp");
        return;
    }

    bool res = true;
    uint32_t pre_tag_ts = 0;
    do {
        flv_tag_p flv_tag = flv_create_tag();
        res = flv_ctx.protocol.url_read(&flv_ctx, (unsigned char *)flv_tag, sizeof(flv_tag_t));

        uint32_t tag_ts = flv_tag->timestamp;
        if (!pre_tag_ts) {
            usleep(40000);
        } else {
            printf("%d, %u\n", flv_tag->tag_type, tag_ts);
            usleep(tag_ts - pre_tag_ts);
        }
        pre_tag_ts = tag_ts;

        rtmp_ctx.protocol.url_write(&rtmp_ctx, (unsigned char *)flv_tag, sizeof(flv_tag_t));
        flv_release_tag(flv_tag);

    } while (res);
}

//-----------

static void opt_usage(cpili_task_param_t param) {
    print_help();
}

static void opt_version(cpili_task_param_t param) {
    print_version();
}

static void opt_streaming(cpili_task_param_t param) {
    if (CPILI_FILE_FORMAT_FLV == param.input.file_format) {
        if (CPILI_IO_TYPE_STREAM == param.output.type && CPILI_STREAM_PROTOCOL_RTMP == param.output.stream_protocol) {
            flv2rtmp(param);
        }
    }
}

static const cpili_task_handler operation[] = {
    opt_usage,
    opt_version,
    opt_streaming
};

void tool_route(cpili_task_operation_t opt, cpili_task_t *task) {
    task->handler = operation[opt];
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="GradleSettings">
    <option name="linkedExternalProjectsSettings">
      <GradleProjectSettings>
        <option name="distributionType" value="LOCAL" />
        <option name="externalProjectPath" value="$PROJECT_DIR$" />
        <option name="gradleHome" value="$APPLICATION_HOME_DIR$/gradle/gradle-2.14.1" />
        <option name="modules">
          <set>
            <option value="$PROJECT_DIR$" />
            <option value="$PROJECT_DIR$/app" />
            <option value="$PROJECT_DIR$/../../SensorLib/sensorlib" />
            <option value="$PROJECT_DIR$/../../SensorLib/sensorlibutils" />
            <option value="$PROJECT_DIR$/../../SensorLib/sls-fitnessshirt" />
            <option value="$PROJECT_DIR$/../../SensorLib/sls-muse" />
            <option value="$PROJECT_DIR$/../../SensorLib/sls-shimmer" />
            <option value="$PROJECT_DIR$/../../SensorLib/sls-simblee" />
            <option value="$PROJECT_DIR$/../../SensorLib/sls-smartband2" />
            <option value="$PROJECT_DIR$/../../SensorLib/sls-smartwatch" />
            <option value="$PROJECT_DIR$/../../SensorLib/sls-tek" />
          </set>
        </option>
        <option name="resolveModulePerSourceSet" value="false" />
      </GradleProjectSettings>
    </option>
  </component>
</project>


text:
"""
Describe Tub files found in one or more directories.
"""
import os
import time
import argparse
import json
from datetime import datetime
from pathlib import Path

import numpy as np
import donkeycar as dk
from donkeycar.parts.datastore import Tub
from donkeycar.parts.tub_v2 import Tub as Tub2

class EmptyTub:
    def __init__(self, base_path):
        self.meta = dict()
        self.path = base_path
        self.base_path = base_path

        manifest_path = Path(os.path.join(self.base_path, 'manifest.json'))
        if not manifest_path.exists():
            raise ValueError(f"No manifest.json in {base_path}")

        with open(manifest_path, 'r') as f:
            self.inputs = json.loads(f.readline()) # inputs
            self.types = json.loads(f.readline()) # types
            self.meta = json.loads(f.readline())

    def __len__(self):
        return 0

def removeComments( dir_list ):
    for i in reversed(range(len(dir_list))):
        if dir_list[i].startswith("#"):
            del dir_list[i]
        elif len(dir_list[i]) == 0:
            del dir_list[i]

def preprocessFileList( filelist ):
    dirs = []
    if filelist is not None:
        for afile in filelist:
            afile = os.path.expanduser(afile)
            with open(afile, "r") as f:
                tmp_dirs = f.read().split('\n')
                dirs.extend(tmp_dirs)

    removeComments( dirs )
    return dirs

def describe_tub( tub, stats=False, time_of_day=False, meta=[], img=False ):
    """ TODO: This should be generalized to return only user-requested meta data.
        TODO: Add a check for image sizes
    """

    # Handle differences between v1 and v2 Tubs
    # TODO: Add __len__ and base_path and manifest and version and a read_only flag to Tub v1
    if hasattr(tub, "get_num_records") and callable(tub.get_num_records):
        count = tub.get_num_records()
        version = "v1"
    else:
        count = len(tub)
        version = "v2"
    if hasattr(tub,"meta"):
        tub_meta = tub.meta
        tub_inputs = tub.inputs
    else:
        tub_meta = tub.manifest.metadata
        tub_inputs = tub.manifest.inputs
    if hasattr(tub,"path"):
        base_path = tub.path
    else:
        base_path = tub.base_path
    base_path = os.path.basename(base_path)

    loc = tub_meta.get("location", "NA")
    task = tub_meta.get("task", "NA")
    driver = tub_meta.get("driver", "NA")
    tod = tub_meta.get("start", None)
    throttle = tub_meta.get("JOYSTICK_MAX_THROTTLE", "NA")
    steering = tub_meta.get("JOYSTICK_STEERING_SCALE", "NA")
    if stats:
        recs = tub.gather_records()
        thr = []
        reward = []
        for rec in recs:
            with open(rec, 'r') as fp:
                json_data = json.load(fp)
            angle, one_thr = Tub.get_angle_throttle(json_data)
            thr.append( one_thr )
            if 'sim/reward' in json_data:
                reward.append( json_data['sim/reward'] )
            elif 'sim/info' in json_data:
                reward.append( json_data['sim/info']['reward'] )
        thr_m = np.mean(thr)
        thr_v = np.std(thr)
        st = "\t{:0.3}/{:0.3}".format( float(thr_m), float(thr_v) )
        if len(reward) > 0:
            st = "\t{:0.3}/{:0.3}/{:0.3}/{:0.3}".format( float(np.min(reward)), float(np.mean(reward)), float(np.std(reward)), float(np.max(reward)) )
        else:
            st = "\tNA"
    else:
        st = ""

    if time_of_day:
        if tod is not None:
            tod = int(tod)
            tod = datetime.fromtimestamp(tod).strftime('\t%H:%M')
        else:
            tod = "\t"
    else:
        tod = ""

    meta_st = ""
    for key in meta:
        if key in tub_inputs:
            meta_st += "\tInput"
        elif key in tub_meta:
            meta_st += "\t{}".format( tub_meta[key] )
        else:
            meta_st += "\tNo"

    img_st = ""
    if img:
        data = tub.get_record(1)
        img_array = data['cam/image_array']
        img_st = "\t{}".format( img_array.shape )

    print( "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}{}{}{}{}".format( base_path, version, count, loc, task, driver, throttle, steering, st, tod, meta_st, img_st ) )
    return count

def make_tub( apath ):
    if os.path.isdir(apath):
        meta_path = os.path.join( apath, "meta.json" )
        if os.path.exists(meta_path):
            return Tub(apath)
        else:
            t = None

            try:
                t = Tub2(apath, read_only=True)
            except ValueError as val_ex:
                pass
            except FileNotFoundError as nof_ex:
                pass
            except Exception as ex:
                print( f"Failed to open Tub v2: {apath}" )
                print( f"   Reason: {type(ex)}  {ex}" )

            if t is None:
                try:
                    t = EmptyTub(apath)
                except ValueError as val_ex:
                    pass # Not a tub of any kind
            return t

    return None

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Describe Tub files found in one or more directories.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-s', '--stats', action='store_true', default=False, help='Calculate mean and standard deviation for throttle.')
    parser.add_argument('--tod', action='store_true', default=False, help='Display time of day for beginning of each tub file.')
    parser.add_argument('--img', action='store_true', default=False, help='Display image size.')
    parser.add_argument('-f', '--file', nargs="*", help='A text file containing paths to tub files, one per line. Option may be used more than once.')
    parser.add_argument('dir', nargs='*', help='One or more directories that are Tub files, or contain Tub files.')
    parser.add_argument('--meta', nargs='*', default=["DONKEY_GYM_ENV_NAME"], help='One or more meta keys to search for in Tub files.')

    args = parser.parse_args()

    dirs = preprocessFileList( args.file )
    dirs.extend( args.dir )
    dirs = [os.path.expanduser(adir) for adir in dirs]

    done = []
    counts = []
    if args.stats:
        stat_str = "\tMean/Std"
    else:
        stat_str = ""
    if args.tod:
        tod_header = "\tTime"
    else:
        tod_header = ""
    meta_header = ""
    for meta in args.meta:
        meta_header += "\t" + meta

    img_header = ""
    if args.img:
        img_header = "\tImg Size"

    tubs = []

    for adir in sorted(dirs):
        if adir not in done and os.path.isdir(adir):
            tub = make_tub( adir )
            if tub is not None:
                tubs.append(tub)
                done.append(adir)
            else:
                for afile in sorted(os.listdir(adir)):
                    fpath = os.path.join(adir, afile)
                    if fpath not in done:
                        tub = make_tub(fpath)
                        if tub is not None:
                            tubs.append(tub)
                            done.append(fpath)

    print( "\nTub\tVersion\t# Samples\tLocation\tTask\tDriver\tThrottle\tSteering{}{}{}{}".format( stat_str, tod_header, meta_header, img_header ) )

    for tub in tubs:
        cnt = describe_tub(tub, stats=args.stats, time_of_day=args.tod, meta=args.meta, img=args.img)
        counts.append( cnt )

    print()
    print( "Total samples: {}".format( np.sum(counts) ) )


text:
namespace SwiftSnapper {
    export namespace Views {
        export module Overview {
            export function OnView () {
                Application.getLanguageStrings(SwiftSnapper.language, function (lang) {
                    let template = Handlebars.compile($('#template').html());
                    $('#PageContent').html(template(lang));

                    //Init Owl Carousel
                    views = $('#views');
                    views.owlCarousel({
                        loop: false,
                        nav: false,
                        dots: false,
                        video: true,
                        margin: 0,
                        startPosition: 1,
                        pullDrag: false,
                        fallbackEasing: 'easeInOutQuart',
                        responsive: {
                            0: {
                                items: 1
                            },
                            1024: {
                                items: 3
                            }
                        }
                    });

                    views.on('initialized.owl.carousel changed.owl.carousel', function (event) {
                        let pos = event.item.index;
                        SwiftSnapper.currentItem = pos;
                        if (pos == 1) {
                            WindowManager.hideStatusBar();
                        } else
                            WindowManager.showStatusBar();
                    });

                    CameraManager.initialize({
                        'frontFacing': false
                    });

                    let cn = new SwiftSnapper.Backend(),
                        snaps;

                    cn.Get({
                        endpoint: 'snaps'
                    }).then((res: any) => {
                        snaps = res.data;
                        localStorage.setItem('AuthToken', res.authToken);

                        if (!snaps || snaps.length < 1)
                            return $('#SnapsView .SnapsList').append('
' + lang.views.overview.emptyFeed + '
');

                        for (let n = 0; n < snaps.length; n++) {
                            let snap = snaps[n],
                                output =
                                    '

' +
                                    '
' + snap.sender + '
' +
                                    '
Length: ' + snap.timer.toString() + '
' +
                                    '

';

                            $('#SnapsView .SnapsList').append(output);
                        }
                    }).catch((err) => {
                        MessageManager.alert('Error: ' + err, 'Error!', null);
                        $('#SnapsView .SnapsList').append('
' + lang.views.overview.emptyFeed + '
');
                    });

                    //Temp for showing snaps
                    $('body').on('click tap', '#SnapsView .SnapsList .item', (e) => {
                        let snap = $(e.currentTarget).data('id');

                        cn.Get({
                            endpoint: 'snaps/' + snap + '/' + localStorage.getItem('AuthToken')
                        }).then((res: any) => {

                            $('#ShowSnapView').css('display', 'block');
                            $('#ShowSnapView img').attr('src', 'data:image/*;base64,' + btoa(res));
                        }).catch((err) => {
                            console.log(err);
                        });
                    });

                    $('#ShowSnapView').on('click tap', () => {
                        $('#ShowSnapView').css('display', 'none');
                    });

                    $('#ViewSnapsBtn').on('click tap', () => {
                        views.trigger('prev.owl.carousel', [300]);
                    });
                    $('#ViewStoriesBtn').on('click tap', () => {
                        views.trigger('next.owl.carousel', [300]);
                    });

                    $('#CameraToggleBtn').on('click tap', () => {
                        $('#CameraPreview').toggleClass('FrontFacing');

                        if ($('#CameraPreview').hasClass('FrontFacing')) {
                            CameraManager.initialize({
                                frontFacing: true
                            });
                        } else {
                            CameraManager.initialize({
                                frontFacing: false
                            });
                        }
                        }
                    );
                    $('#ShutterBtn').on('click tap', () => {
                        let IStream = CameraManager.takePhotoAsync();
                        console.log('Picture Taken');
                        if (IStream != null) {
                            MessageManager.alert('Picture Taken!', 'Success', null);
                            // Send to SnapChat or editor view or something.
                            // SnapchatClient.PostSnap(IStream, [['paraName1', 'Val'], ['paraName2', 'Val']], {});
                        }
                        else {
                            MessageManager.alert('No Camera!', 'Failure', null);
                        }
                    });
                    $('#SettingsBtn').on('click tap', () => {
                        $('body').load('views/settings/index.html');
                    });

                    if (typeof Windows !== 'undefined' && Windows.Foundation.Metadata['ApiInformation'].isTypePresent('Windows.Phone.UI.Input.HardwareButtons')) {
                        Windows['Phone'].UI.Input.HardwareButtons.addEventListener('camerapressed', function (e) {
                            $('#ShutterBtn').click();
                        });
                    }
                });
            }
        }
    }
}


text:
using Ptr = uint8_t *;

namespace taichi::lang {

class JITModule;
class LlvmRuntimeExecutor;

class SNodeTreeBufferManager {
 public:
  explicit SNodeTreeBufferManager(LlvmRuntimeExecutor *runtime_exec);

  void merge_and_insert(Ptr ptr, std::size_t size);

  Ptr allocate(JITModule *runtime_jit,
               void *runtime,
               std::size_t size,
               std::size_t alignment,
               const int snode_tree_id,
               uint64 *result_buffer);

  void destroy(SNodeTree *snode_tree);

 private:
  std::set<std::pair<std::size_t, Ptr>> size_set_;
  std::map<Ptr, std::size_t> ptr_map_;
  LlvmRuntimeExecutor *runtime_exec_;
  Ptr roots_[kMaxNumSnodeTreesLlvm];
  std::size_t sizes_[kMaxNumSnodeTreesLlvm];
};

}  // namespace taichi::lang


text:
<!DOCTYPE html>

    <title>Security with Spring Boot</title>

Access is Denied!

Go to Home Page


text:
/**
 * Created by yuan on 2016/3/8.
 */
//alert('hello world!');
'use strict';

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
//import Button from './components/Button/Button';
import App from './container/App';

class HelloWorld extends Component{
    render(){
        return(
            <h1> Hello world Hello world</h1>
        )
    }
}

let root = document.getElementById('app');
let button = document.getElementById('button');

ReactDOM.render(<App />, button);
ReactDOM.render(<HelloWorld />, root);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.pentaho.di.plugins</groupId>
    <artifactId>pentaho-kettle-repository-locator-assemblies</artifactId>
    <version>9.4.0.0-SNAPSHOT</version>
  </parent>

  <artifactId>kettle-repository-locator-platform-plugin</artifactId>
  <version>9.4.0.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <name>Pentaho Repository Locator Plugin</name>

  <dependencies>
    <dependency>
      <groupId>org.pentaho.di.plugins</groupId>
      <artifactId>pentaho-kettle-repository-locator-impl-platform</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>
</project>


text:
package tencentcr

import (
	"net/http"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func Test_newRateLimitedTransport(t *testing.T) {
	tests := []struct {
		name      string
		rate      int
		transport http.RoundTripper
	}{
		{"1qps", 1, http.DefaultTransport},
	}
	var req = &http.Request{}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := newRateLimitedTransport(tt.rate, tt.transport)
			start := time.Now()
			for i := 0; i <= tt.rate; i++ {
				got.RoundTrip(req)
			}
			used := int64(time.Since(start).Milliseconds()) / int64(tt.rate)
			assert.GreaterOrEqualf(t, used/int64(tt.rate), int64(1e3/tt.rate), "used %d ms per req", used/int64(tt.rate))
		})
	}
}


text:
<?php
class DB_CONN{
    private $db_host = "";
    private $db_name = "";
    private $db_login = "";
    private $db_pass = "";

    public $conn;

    public function __construct()
    {
        $this->conn = new mysqli($this->db_host,$this->db_login,$this->db_pass,$this->db_name);
        $this->conn->set_charset('utf8');
        $this->conn->query('use $db_name;');
        if($this->conn){
        }else{
            echo "Error: Unable to connect to MySQL." . PHP_EOL;
            echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
            echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
        }
    }

    private function xssafe($data,$encoding='UTF-8')
    {
        return htmlspecialchars($data,ENT_QUOTES | ENT_HTML401,$encoding);
    }

    public function CountUserByLogin($data){
        $login = $this->xssafe($data);
        $stmt = $this->conn->query("SELECT * FROM Users WHERE Login='$login'");

        return $stmt->num_rows;
    }

    public function InsertUser($login,$password,$first_name,$last_name){
        $stmt = $this->conn->prepare("INSERT INTO Users(Login, Password, First_Name, Last_Name) VALUE (?,?,?,?)");
        $login=                     $this->xssafe($login);
        $first_name=                $this->xssafe($first_name);
        $last_name=                 $this->xssafe($last_name);
        $password=password_hash(    $password,PASSWORD_BCRYPT);
        $stmt->bind_param("ssss",$login,$password,$first_name,$last_name);

        if($stmt->execute()){
            return $stmt->insert_id;
        }else{
            return false;
        }
    }

    public function LoginUser($login,$password){
        $id = $this->GetIdByLogin($login);
        $hash = $this->GetHashById($id);
        if(password_verify($password,$hash)){
            return $id;
        }else{
            return false;
        }
    }

    public function GetFirstNameById($id){
        $stmt = $this->conn->prepare("SELECT First_Name FROM Users WHERE Id_User=?");
        $stmt->bind_param('i',$id);
        $stmt->execute();
        $stmt->bind_result($res);
        $stmt->fetch();
        return $res;
        }
    public function GetLastNameById($id){
        $stmt = $this->conn->prepare("SELECT Last_Name FROM Users WHERE Id_User=?");
        $stmt->bind_param('i',$id);
        $stmt->execute();
        $stmt->bind_result($res);
        $stmt->fetch();
        return $res;
        }
    public function GetLoginById($id){
        $stmt = $this->conn->prepare("SELECT Login FROM Users WHERE Id_User=?");
        $stmt->bind_param('i',$id);
        $stmt->execute();
        $stmt->bind_result($res);
        $stmt->fetch();
        return $res;
        }
    private function GetHashById($id){
        $stmt = $this->conn->prepare("SELECT Password FROM Users WHERE Id_User=?");
        $stmt->bind_param('i',$id);
        $stmt->execute();
        $stmt->bind_result($res);
        $stmt->fetch();
        return $res;
        }

    public function GetIdByLogin($login){
        $stmt = $this->conn->prepare("SELECT Id_User FROM Users WHERE Login = ?");
        $stmt->bind_param('s',$login);
        $stmt->execute();
        $stmt->bind_result($res);
        $stmt->fetch();
        return $res;
    }
    public function GetToDosById($id){
        $stmt = $this->conn->prepare("SELECT * FROM Todos WHERE Author = ? ORDER BY Todos.Display_order ASC");
        $stmt->bind_param('i',$id);
        $stmt->execute();
        $res = array();
        $task_no = 0;
        do {
            $stmt->bind_result($res[$task_no]['ID'], $res[$task_no]['Author'], $res[$task_no]['Title'], $res[$task_no]['Add_date'],$res[$task_no]['Cat_id'],$res[$task_no]['Display_order']);
            $task_no++;
        }while ($stmt->fetch());
        array_pop($res);
        return $res;
    }
    public function CheckToDoOwnAuthor($id_a, $id_todo){
        $stmt = $this->conn->prepare("SELECT Title FROM Todos WHERE Author = ? AND Id_todo = ?");
        $stmt->bind_param("ii",$id_a,$id_todo);
        $stmt->execute();
        $stmt->bind_result($res);
        $stmt->fetch();
        if($res){
            return true;
        }else{
            return false;
        }
    }

    public function GetTasksById($id){
        $stmt = $this->conn->prepare("SELECT * FROM Tasks WHERE Id_todo=?");
        $stmt->bind_param("i",$id);
        $stmt->execute();
        $res = array();
        $task_no = 0;
        do {
            $stmt->bind_result($res[$task_no]['Id_task'], $res[$task_no]['Id_todo'], $res[$task_no]['Content'], $res[$task_no]['Done']);
            $task_no++;
        }while ($stmt->fetch());
        array_pop($res);
        return $res;

    }

    private function GetDisplayOrderById($id){
        $stmt = $this->conn->prepare("SELECT Display_order FROM Todos WHERE Id_todo = ?");
        $stmt->bind_param("i",$id);
        $stmt->execute();
        $stmt->bind_result($do);
        $stmt->fetch();
        return $do;
    }

    public function SwapToDos($id1, $id2){
        $do1 = $this->GetDisplayOrderById($id1);
        $do2 = $this->GetDisplayOrderById($id2);

        if($do1 && $do2){
            $q1 = $this->conn->query("UPDATE Todos SET Display_order = $do2 WHERE Id_todo=$id1");
            $q2 = $this->conn->query("UPDATE Todos SET Display_order = $do1 WHERE Id_todo=$id2");

            if($q1 && $q2){
                return true;
            }else{
                return false;
            }
        }
    }
    private function GetTaskStatus($task_id){
        $stmt = $this->conn->prepare("SELECT Done FROM Tasks WHERE Id_task=?");
        $stmt->bind_param('i',$task_id);
        $stmt->execute();
        $stmt->bind_result($res);
        $stmt->fetch();
        return (int)$res;

    }

    public function CheckTaskOwnAuthor($id_task,$id_user){
        $res = $this->conn->query("SELECT Id_task from Tasks JOIN Todos ON Tasks.Id_todo = Todos.Id_todo WHERE Tasks.Id_task=$id_task  AND Author=$id_user");
        if($res->num_rows>0){
            return true;
        }else{
            return false;
        }
    }

    public function ChangeTaskStatus($task_id){

        $status = $this->GetTaskStatus($task_id);
        if($status == 0){
            $this->conn->query("UPDATE Tasks SET Done = 1 WHERE Id_task=$task_id");
            return true;
        }elseif ($status == 1){
            $this->conn->query("UPDATE Tasks SET Done = 0 WHERE Id_task=$task_id");
            return true;
        }else{
            return false;
        }
    }

    public function ChangeTaskContent($id_task,$content){
        $cont = $this->xssafe($content);
        if($this->conn->query("UPDATE Tasks SET Content = '$cont' WHERE Id_task = $id_task") === TRUE){
            return true;
        }else{
            return false;
        }
    }

    public function RemoveTask($id_task){
        if($this->conn->query("DELETE FROM Tasks WHERE Id_task = $id_task") === TRUE){
            return true;
        }else{
            return false;
        }
    }

    public function AddTask($todo_id,$content){
        $cont = $this->xssafe($content);
        $stmt = $this->conn->prepare("INSERT INTO Tasks (Id_todo, Content) VALUES (?,?)");
        $stmt->bind_param("is",$todo_id,$cont);
        $stmt->execute();
        return $this->conn->insert_id;
    }

    public function ChangeToDoTitle($todo_id, $title){
        $titl = $this->xssafe($title);
        $this->conn->query("UPDATE Todos SET Title = '$titl' WHERE Id_todo = $todo_id");
        if($this->conn->affected_rows>0){
            return true;
        }else{
            return false;
        }
    }

    public function RemoveToDo($todo_id){
        $this->conn->query("DELETE FROM Todos WHERE Id_todo = $todo_id");
        if($this->conn->affected_rows>0){
            return true;
        }else{
            return false;
        }
    }

    public function GetLastToDoDisplayOrder($id_author){
        $stmt = $this->conn->query("SELECT Display_order FROM Todos WHERE Author=$id_author ORDER BY Display_order DESC LIMIT 1");
        $last_do = $stmt->fetch_assoc();
        return (int)$last_do['Display_order'];
    }

    public function AddToDo($title, $id_cat, $id_author){
        $titl=$this->xssafe($title);
        $curr_date = date('Y-m-d H:i:s');
        $displ_ord = $this->GetLastToDoDisplayOrder($id_author);
        $displ_ord++;
        $stmt = $this->conn->prepare("INSERT INTO Todos (Author, Title, Add_date, Cat_id,Display_order)  VALUES (?,?, ? ,?,?)");
        $stmt->bind_param('issii', $id_author, $titl, $curr_date, $id_cat,$displ_ord);
        $stmt->execute();
        $response=['date'=>$curr_date,'insert_id'=>$this->conn->insert_id];
        return $response;
    }
}
?>


text:
#include "pipeline_state.h"

bool operator==(const VkVertexInputAttributeDescription &lhs, const VkVertexInputAttributeDescription &rhs)
{
	return std::tie(lhs.binding, lhs.format, lhs.location, lhs.offset) == std::tie(rhs.binding, rhs.format, rhs.location, rhs.offset);
}

bool operator==(const VkVertexInputBindingDescription &lhs, const VkVertexInputBindingDescription &rhs)
{
	return std::tie(lhs.binding, lhs.inputRate, lhs.stride) == std::tie(rhs.binding, rhs.inputRate, rhs.stride);
}

bool operator==(const vkb::ColorBlendAttachmentState &lhs, const vkb::ColorBlendAttachmentState &rhs)
{
	return std::tie(lhs.alpha_blend_op, lhs.blend_enable, lhs.color_blend_op, lhs.color_write_mask, lhs.dst_alpha_blend_factor, lhs.dst_color_blend_factor, lhs.src_alpha_blend_factor, lhs.src_color_blend_factor) ==
	       std::tie(rhs.alpha_blend_op, rhs.blend_enable, rhs.color_blend_op, rhs.color_write_mask, rhs.dst_alpha_blend_factor, rhs.dst_color_blend_factor, rhs.src_alpha_blend_factor, rhs.src_color_blend_factor);
}

bool operator!=(const vkb::StencilOpState &lhs, const vkb::StencilOpState &rhs)
{
	return std::tie(lhs.compare_op, lhs.depth_fail_op, lhs.fail_op, lhs.pass_op) != std::tie(rhs.compare_op, rhs.depth_fail_op, rhs.fail_op, rhs.pass_op);
}

bool operator!=(const vkb::VertexInputState &lhs, const vkb::VertexInputState &rhs)
{
	return lhs.attributes != rhs.attributes || lhs.bindings != rhs.bindings;
}

bool operator!=(const vkb::InputAssemblyState &lhs, const vkb::InputAssemblyState &rhs)
{
	return std::tie(lhs.primitive_restart_enable, lhs.topology) != std::tie(rhs.primitive_restart_enable, rhs.topology);
}

bool operator!=(const vkb::RasterizationState &lhs, const vkb::RasterizationState &rhs)
{
	return std::tie(lhs.cull_mode, lhs.depth_bias_enable, lhs.depth_clamp_enable, lhs.front_face, lhs.front_face, lhs.polygon_mode, lhs.rasterizer_discard_enable) !=
	       std::tie(rhs.cull_mode, rhs.depth_bias_enable, rhs.depth_clamp_enable, rhs.front_face, rhs.front_face, rhs.polygon_mode, rhs.rasterizer_discard_enable);
}

bool operator!=(const vkb::ViewportState &lhs, const vkb::ViewportState &rhs)
{
	return lhs.viewport_count != rhs.viewport_count || lhs.scissor_count != rhs.scissor_count;
}

bool operator!=(const vkb::MultisampleState &lhs, const vkb::MultisampleState &rhs)
{
	return std::tie(lhs.alpha_to_coverage_enable, lhs.alpha_to_one_enable, lhs.min_sample_shading, lhs.rasterization_samples, lhs.sample_mask, lhs.sample_shading_enable) !=
	       std::tie(rhs.alpha_to_coverage_enable, rhs.alpha_to_one_enable, rhs.min_sample_shading, rhs.rasterization_samples, rhs.sample_mask, rhs.sample_shading_enable);
}

bool operator!=(const vkb::DepthStencilState &lhs, const vkb::DepthStencilState &rhs)
{
	return std::tie(lhs.depth_bounds_test_enable, lhs.depth_compare_op, lhs.depth_test_enable, lhs.depth_write_enable, lhs.stencil_test_enable) !=
	           std::tie(rhs.depth_bounds_test_enable, rhs.depth_compare_op, rhs.depth_test_enable, rhs.depth_write_enable, rhs.stencil_test_enable) ||
	       lhs.back != rhs.back || lhs.front != rhs.front;
}

bool operator!=(const vkb::ColorBlendState &lhs, const vkb::ColorBlendState &rhs)
{
	return std::tie(lhs.logic_op, lhs.logic_op_enable) != std::tie(rhs.logic_op, rhs.logic_op_enable) ||
	       lhs.attachments.size() != rhs.attachments.size() ||
	       !std::equal(lhs.attachments.begin(), lhs.attachments.end(), rhs.attachments.begin(),
	                   [](const vkb::ColorBlendAttachmentState &lhs, const vkb::ColorBlendAttachmentState &rhs) {
		                   return lhs == rhs;
	                   });
}

namespace vkb
{
void SpecializationConstantState::reset()
{
	if (dirty)
	{
		specialization_constant_state.clear();
	}

	dirty = false;
}

bool SpecializationConstantState::is_dirty() const
{
	return dirty;
}

void SpecializationConstantState::clear_dirty()
{
	dirty = false;
}

void SpecializationConstantState::set_constant(uint32_t constant_id, const std::vector<uint8_t> &value)
{
	auto data = specialization_constant_state.find(constant_id);

	if (data != specialization_constant_state.end() && data->second == value)
	{
		return;
	}

	dirty = true;

	specialization_constant_state[constant_id] = value;
}

void SpecializationConstantState::set_specialization_constant_state(const std::map<uint32_t, std::vector<uint8_t>> &state)
{
	specialization_constant_state = state;
}

const std::map<uint32_t, std::vector<uint8_t>> &SpecializationConstantState::get_specialization_constant_state() const
{
	return specialization_constant_state;
}

void PipelineState::reset()
{
	clear_dirty();

	pipeline_layout = nullptr;

	render_pass = nullptr;

	specialization_constant_state.reset();

	vertex_input_state = {};

	input_assembly_state = {};

	rasterization_state = {};

	multisample_state = {};

	depth_stencil_state = {};

	color_blend_state = {};

	subpass_index = {0U};
}

void PipelineState::set_pipeline_layout(PipelineLayout &new_pipeline_layout)
{
	if (pipeline_layout)
	{
		if (pipeline_layout->get_handle() != new_pipeline_layout.get_handle())
		{
			pipeline_layout = &new_pipeline_layout;

			dirty = true;
		}
	}
	else
	{
		pipeline_layout = &new_pipeline_layout;

		dirty = true;
	}
}

void PipelineState::set_render_pass(const RenderPass &new_render_pass)
{
	if (render_pass)
	{
		if (render_pass->get_handle() != new_render_pass.get_handle())
		{
			render_pass = &new_render_pass;

			dirty = true;
		}
	}
	else
	{
		render_pass = &new_render_pass;

		dirty = true;
	}
}

void PipelineState::set_specialization_constant(uint32_t constant_id, const std::vector<uint8_t> &data)
{
	specialization_constant_state.set_constant(constant_id, data);

	if (specialization_constant_state.is_dirty())
	{
		dirty = true;
	}
}

void PipelineState::set_vertex_input_state(const VertexInputState &new_vertex_input_state)
{
	if (vertex_input_state != new_vertex_input_state)
	{
		vertex_input_state = new_vertex_input_state;

		dirty = true;
	}
}

void PipelineState::set_input_assembly_state(const InputAssemblyState &new_input_assembly_state)
{
	if (input_assembly_state != new_input_assembly_state)
	{
		input_assembly_state = new_input_assembly_state;

		dirty = true;
	}
}

void PipelineState::set_rasterization_state(const RasterizationState &new_rasterization_state)
{
	if (rasterization_state != new_rasterization_state)
	{
		rasterization_state = new_rasterization_state;

		dirty = true;
	}
}

void PipelineState::set_viewport_state(const ViewportState &new_viewport_state)
{
	if (viewport_state != new_viewport_state)
	{
		viewport_state = new_viewport_state;

		dirty = true;
	}
}

void PipelineState::set_multisample_state(const MultisampleState &new_multisample_state)
{
	if (multisample_state != new_multisample_state)
	{
		multisample_state = new_multisample_state;

		dirty = true;
	}
}

void PipelineState::set_depth_stencil_state(const DepthStencilState &new_depth_stencil_state)
{
	if (depth_stencil_state != new_depth_stencil_state)
	{
		depth_stencil_state = new_depth_stencil_state;

		dirty = true;
	}
}

void PipelineState::set_color_blend_state(const ColorBlendState &new_color_blend_state)
{
	if (color_blend_state != new_color_blend_state)
	{
		color_blend_state = new_color_blend_state;

		dirty = true;
	}
}

void PipelineState::set_subpass_index(uint32_t new_subpass_index)
{
	if (subpass_index != new_subpass_index)
	{
		subpass_index = new_subpass_index;

		dirty = true;
	}
}

const PipelineLayout &PipelineState::get_pipeline_layout() const
{
	assert(pipeline_layout && "Graphics state Pipeline layout is not set");
	return *pipeline_layout;
}

const RenderPass *PipelineState::get_render_pass() const
{
	return render_pass;
}

const SpecializationConstantState &PipelineState::get_specialization_constant_state() const
{
	return specialization_constant_state;
}

const VertexInputState &PipelineState::get_vertex_input_state() const
{
	return vertex_input_state;
}

const InputAssemblyState &PipelineState::get_input_assembly_state() const
{
	return input_assembly_state;
}

const RasterizationState &PipelineState::get_rasterization_state() const
{
	return rasterization_state;
}

const ViewportState &PipelineState::get_viewport_state() const
{
	return viewport_state;
}

const MultisampleState &PipelineState::get_multisample_state() const
{
	return multisample_state;
}

const DepthStencilState &PipelineState::get_depth_stencil_state() const
{
	return depth_stencil_state;
}

const ColorBlendState &PipelineState::get_color_blend_state() const
{
	return color_blend_state;
}

uint32_t PipelineState::get_subpass_index() const
{
	return subpass_index;
}

bool PipelineState::is_dirty() const
{
	return dirty || specialization_constant_state.is_dirty();
}

void PipelineState::clear_dirty()
{
	dirty = false;
	specialization_constant_state.clear_dirty();
}
}        // namespace vkb


text:
local DoubleBlock
if game then
  local pluginModel = script.Parent.Parent.Parent.Parent
  DoubleBlock = require(pluginModel.com.blacksheepherd.code.DoubleBlock)
else
  DoubleBlock = require("com.blacksheepherd.code.DoubleBlock")
end
local IfElseBlock
do
  local _parent_0 = DoubleBlock
  local _base_0 = {
    BeforeRender = function(self)
      return tostring(self._indent) .. "if " .. tostring(self._condition) .. " then"
    end,
    MiddleRender = function(self)
      return tostring(self._indent) .. "else"
    end,
    AfterRender = function(self)
      return tostring(self._indent) .. "end"
    end
  }
  _base_0.__index = _base_0
  setmetatable(_base_0, _parent_0.__base)
  local _class_0 = setmetatable({
    __init = function(self, condition)
      _parent_0.__init(self)
      self._condition = condition
    end,
    __base = _base_0,
    __name = "IfElseBlock",
    __parent = _parent_0
  }, {
    __index = function(cls, name)
      local val = rawget(_base_0, name)
      if val == nil then
        return _parent_0[name]
      else
        return val
      end
    end,
    __call = function(cls, ...)
      local _self_0 = setmetatable({}, _base_0)
      cls.__init(_self_0, ...)
      return _self_0
    end
  })
  _base_0.__class = _class_0
  if _parent_0.__inherited then
    _parent_0.__inherited(_parent_0, _class_0)
  end
  IfElseBlock = _class_0
end
return IfElseBlock


text:
@interface IOCNotificationsController ()
@property(nonatomic,strong)GHNotifications *notifications;
@property(nonatomic,strong)NSMutableDictionary *notificationsByRepository;
@end

@implementation IOCNotificationsController

- (id)initWithNotifications:(GHNotifications *)notifications {
	self = [super initWithStyle:UITableViewStylePlain];
	if (self) {
		self.title = @"Notifications";
		self.notifications = notifications;
	}
	return self;
}

#pragma mark View Events

- (void)viewDidLoad {
	[super viewDidLoad];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"MarkRead.png"] style:UIBarButtonItemStylePlain target:self action:@selector(markAllAsRead:)];
	self.navigationItem.rightBarButtonItem.accessibilityLabel = NSLocalizedString(@"Mark all as read", nil);
    self.navigationItem.rightBarButtonItem.enabled = NO;
	[self setupPullToRefresh];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
	if (!self.notificationsByRepository) [self rebuildByRepository];
	[self setupActions];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	[self refreshLastUpdate];
	[self refreshIfRequired];
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark Actions

// marks the notification as read, but keeps the cell
- (void)markAsRead:(NSIndexPath *)indexPath {
    NSArray *notifications = [self notificationsInSection:indexPath.section];
    if (indexPath.row >= notifications.count) return;
    GHNotification *notification = notifications[indexPath.row];
    [self.notifications markAsRead:notification start:nil success:nil failure:nil];
}

// marks the notification as read and removes the cell
- (void)removeNotification:(NSIndexPath *)indexPath {
	NSInteger section = indexPath.section;
	NSString *repoId = [self repoIdForSection:section];
	NSMutableArray *notificationsInSection = self.notificationsByRepository[repoId];
	GHNotification *notification = [self notificationsInSection:section][indexPath.row];
	// mark as read, remove notification, and eventually the associated repo key
	[self.notifications markAsRead:notification start:nil success:^(GHResource *instance, id data) {
		if ([(GHNotifications *)instance unreadCount] == 0) {
			[self refreshIfRequired];
		}
	} failure:nil];
	[self.notifications removeObject:notification];
	[notificationsInSection removeObject:notification];
	if (notificationsInSection.count == 0) {
		[self.notificationsByRepository removeObjectForKey:repoId];
	}
	// update table:
	// reload if this was the last notification
	if (!self.resourceHasData) {
		[self markedAllAsRead];
	}
	// remove the section if it was the last notification in this section
	else if (!self.notificationsByRepository[repoId]) {
		NSMutableIndexSet *sections = [NSMutableIndexSet indexSetWithIndex:section];
		[self.tableView deleteSections:sections withRowAnimation:UITableViewRowAnimationFade];
	}
	// remove the cell
	else {
		[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
	}
}

- (void)markAllAsRead:(id)sender {
	[self.notifications markAllAsReadStart:^(GHResource *notifications) {
		[self.notificationsByRepository removeAllObjects];
		[self markedAllAsRead];
	} success:^(GHResource *notifications, id data) {
		[self refreshIfRequired];
	} failure:^(GHResource *notifications, id data) {
		[self refreshIfRequired];
	}];
}

- (void)markAllAsReadInSection:(GradientButton *)sender {
	NSString *repoId = sender.identifierTag;
	NSInteger section = [self.notificationsByRepository.allKeys indexOfObject:repoId];
	[self.notifications markAllAsReadForRepoId:repoId start:nil success:^(GHResource *instance, id data) {
		if ([(GHNotifications *)instance unreadCount] == 0) {
			[self refreshIfRequired];
		}
	} failure:nil];
	[self.notificationsByRepository removeObjectForKey:repoId];
	// update table:
	// reload if this was the last section
	if (!self.resourceHasData) {
		[self markedAllAsRead];
	}
	// remove the section
	else if (!self.notificationsByRepository[repoId]) {
		NSMutableIndexSet *sections = [NSMutableIndexSet indexSetWithIndex:section];
		[self.tableView deleteSections:sections withRowAnimation:UITableViewRowAnimationFade];
	}
}

- (void)markedAllAsRead {
	[self setupActions];
	[self.tableView reloadData];
}

- (void)openRepoForSection:(GradientButton *)sender {
	NSString *repoId = sender.identifierTag;
    NSArray *comps = [repoId componentsSeparatedByString:@"/"];
    if (comps.count == 2) {
        GHRepository *repo = [[GHRepository alloc] initWithOwner:comps[0] andName:comps[1]];
        IOCRepositoryController *viewController = [[IOCRepositoryController alloc] initWithRepository:repo];
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

#pragma mark TableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return self.resourceHasData ? self.notificationsByRepository.allKeys.count : 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return self.resourceHasData ? [[self notificationsInSection:section] count] : 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	return [self repoIdForSection:section];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return ([self tableView:tableView titleForHeaderInSection:section]) ? 40 : 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NSString *title = [self tableView:tableView titleForHeaderInSection:section];
    if (!title) {
		return nil;
	} else {
		IOCNotificationsSectionHeader *header = [IOCNotificationsSectionHeader headerForTableView:tableView title:title];
        NSString *repoId = [self repoIdForSection:section];
        header.titleButton.identifierTag = repoId;
        header.markReadButton.identifierTag = repoId;
        [header.titleButton addTarget:self action:@selector(openRepoForSection:) forControlEvents:UIControlEventTouchUpInside];
        [header.markReadButton addTarget:self action:@selector(markAllAsReadInSection:) forControlEvents:UIControlEventTouchUpInside];
        return header;
	}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	if (!self.resourceHasData) {
		UITableViewCell *allReadCell = [tableView dequeueReusableCellWithIdentifier:@"AllReadCell"];
		if (!allReadCell) {
			allReadCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AllReadCell"];
			allReadCell.selectionStyle = UITableViewCellSelectionStyleNone;
			allReadCell.textLabel.font = [UIFont systemFontOfSize:15];
			allReadCell.textLabel.text = NSLocalizedString(@"Inbox Zero, good job!", @"Notifications: Inbox Zero");
			allReadCell.textLabel.textColor = [UIColor grayColor];
			allReadCell.textLabel.textAlignment = NSTextAlignmentCenter;
		}
		return allReadCell;
	}
	IOCNotificationCell *cell = (IOCNotificationCell *)[tableView dequeueReusableCellWithIdentifier:@"NotificationCell"];
	if (!cell) cell = [IOCNotificationCell cellWithReuseIdentifier:@"NotificationCell"];
	NSArray *notifications = [self notificationsInSection:indexPath.section];
	GHNotification *notification = notifications[indexPath.row];
	cell.notification = notification;
	notification.read ? [cell markAsRead] : [cell markAsNew];
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if (!self.resourceHasData) return;
	GHNotification *notification = [self notificationsInSection:indexPath.section][indexPath.row];
	UIViewController *viewController = nil;
	if ([notification.subject isKindOfClass:GHPullRequest.class]) {
		viewController = [[IOCPullRequestController alloc] initWithPullRequest:(GHPullRequest *)notification.subject];
	} else if ([notification.subject isKindOfClass:GHIssue.class]) {
		viewController = [[IOCIssueController alloc] initWithIssue:(GHIssue *)notification.subject];
	} else if ([notification.subject isKindOfClass:GHCommit.class]) {
		viewController = [[IOCCommitController alloc] initWithCommit:(GHCommit *)notification.subject];
	}
	if (viewController) {
        [notification.subject whenLoaded:^(GHResource *instance, id data) {
            [self markAsRead:indexPath];
            [self.tableView reloadData];
        }];
        [self.navigationController pushViewController:viewController animated:YES];
	}
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
	[self removeNotification:indexPath];
}

#pragma mark Helpers

- (BOOL)resourceHasData {
	return self.notificationsByRepository.allKeys.count > 0;
}

- (NSString *)repoIdForSection:(NSInteger)section {
	return self.resourceHasData ? self.notificationsByRepository.allKeys[section] : nil;
}

- (NSArray *)notificationsInSection:(NSInteger)section {
	if (!self.resourceHasData) return nil;
	NSArray *keys = self.notificationsByRepository.allKeys;
	NSString *key = keys[section];
	return self.notificationsByRepository[key];
}

- (void)rebuildByRepository {
	self.notificationsByRepository = [NSMutableDictionary dictionary];
	for (GHNotification *notification in self.notifications.items) {
		if (!self.notificationsByRepository[notification.repository.repoId]) {
			self.notificationsByRepository[notification.repository.repoId] = [NSMutableArray array];
		}
		[self.notificationsByRepository[notification.repository.repoId] addObject:notification];
	}
}

// Right now the GitHub API does not fully support pagination for notifications.
// This is a temporary workaround that disables the "Mark all as read" button if
// the maximum number of 50 notifications was loaded, because in this case we do
// not know whether or not there are more notifications (which the user did not
// see) - so don't make it possible to mark all as read in this case.
- (void)setupActions {
	BOOL markAllReadEnabled = self.resourceHasData && self.notifications.unreadCount < 50;
	self.navigationItem.rightBarButtonItem.enabled = markAllReadEnabled;
}

- (void)setupPullToRefresh {
	__weak __typeof(&*self)weakSelf = self;
	[self.tableView addPullToRefreshWithActionHandler:^{
        if (weakSelf.notifications.isLoading) {
            dispatch_async(dispatch_get_main_queue(),^ {
                [weakSelf.tableView.pullToRefreshView performSelector:@selector(stopAnimating) withObject:nil afterDelay:.25];
            });
        } else if (!weakSelf.notifications.canReload) {
            dispatch_async(dispatch_get_main_queue(),^ {
                [weakSelf.tableView.pullToRefreshView performSelector:@selector(stopAnimating) withObject:nil afterDelay:.25];
            });
            NSString *message = [NSString stringWithFormat:NSLocalizedString(@"Notifications currently can be reloaded every %d seconds", @"Notifications: Reload throttle message"), weakSelf.notifications.pollInterval];
            [iOctocat reportWarning:NSLocalizedString(@"Please wait", @"Notifications: Reload throttle title") with:message];
        } else {
            [weakSelf.notifications loadWithParams:nil start:^(GHResource *instance) {
                [weakSelf setupActions];
            } success:^(GHResource *instance, id data) {
                [weakSelf refreshLastUpdate];
                [weakSelf rebuildByRepository];
                [weakSelf setupActions];
                dispatch_async(dispatch_get_main_queue(),^ {
                    [weakSelf.tableView reloadData];
                    [weakSelf.tableView.pullToRefreshView performSelector:@selector(stopAnimating) withObject:nil afterDelay:.25];
                });
            } failure:^(GHResource *instance, NSError *error) {
                dispatch_async(dispatch_get_main_queue(),^ {
                    [weakSelf.tableView reloadData];
                    [weakSelf.tableView.pullToRefreshView performSelector:@selector(stopAnimating) withObject:nil afterDelay:.25];
                });
                [iOctocat reportLoadingError:error.localizedDescription];
            }];
        }
    }];
    [self refreshLastUpdate];
}

- (void)refreshIfRequired {
    if (!self.notifications.isLoading && self.notifications.canReload) {
        NSTimeInterval refreshInterval = 15 * 60; // automatically refresh every 15 minutes
        NSDate *refreshThreshold = [self.notifications.lastUpdate dateByAddingTimeInterval:refreshInterval];
        NSDate *lastActivatedDate = [[NSUserDefaults standardUserDefaults] objectForKey:kLastActivatedDateDefaultsKey];
        if (!self.resourceHasData || [refreshThreshold compare:lastActivatedDate] == NSOrderedAscending) {
            [self.tableView triggerPullToRefresh];
        }
    }
}

- (void)refreshLastUpdate {
	if (self.notifications.lastUpdate) {
		NSString *lastRefresh = [NSString stringWithFormat:NSLocalizedString(@"Last refresh %@", @"Notifications/Events: Last refresh shown in header"), [self.notifications.lastUpdate ioc_prettyDate]];
		[self.tableView.pullToRefreshView setSubtitle:lastRefresh forState:SVPullToRefreshStateAll];
	}
}

- (void)handleBecomeActive {
	[self refreshLastUpdate];
	[self.tableView setContentOffset:CGPointZero animated:YES];
	[self performSelector:@selector(refreshIfRequired) withObject:nil afterDelay:1.25];
}

@end


text:
MapaComedoresSociales
=====================

Queremos desarrollar una web responsive que permita mapear los comedores sociales con el objetivo de agilizar el proceso de recogida de alimentos y facilitar a ciudadanos y organizaciones que cubran las necesidades de los comedores sociales que tienen en su entorno más cercano.

Es un proyecto totalmente libre, realizado con la última tecnología pero sobretodo, con mucho cariño.

[ In development ]


text:
var Buildings = {

  project: function(p, m) {
    return {
      x: (p.x-CAM_X) * m + CAM_X <<0,
      y: (p.y-CAM_Y) * m + CAM_Y <<0
    };
  },

  render: function() {
    var context = this.context;
    context.clearRect(0, 0, WIDTH, HEIGHT);

    // show on high zoom levels only and avoid rendering during zoom
    if (ZOOM < MIN_ZOOM || isZooming) {
      return;
    }

    var
      item,
      h, mh,
      sortCam = { x:CAM_X+ORIGIN_X, y:CAM_Y+ORIGIN_Y },
      footprint,
      wallColor, altColor, roofColor,
      dataItems = Data.items;

    dataItems.sort(function(a, b) {
      return (a.minHeight-b.minHeight) || getDistance(b.center, sortCam) - getDistance(a.center, sortCam) || (b.height-a.height);
    });

    for (var i = 0, il = dataItems.length; i < il; i++) {
      item = dataItems[i];

      if (Simplified.isSimple(item)) {
        continue;
      }

      footprint = item.footprint;

      if (!isVisible(footprint)) {
        continue;
      }

      // when fading in, use a dynamic height
      h = item.scale < 1 ? item.height*item.scale : item.height;

      mh = 0;
      if (item.minHeight) {
        mh = item.scale < 1 ? item.minHeight*item.scale : item.minHeight;
      }

      wallColor = item.wallColor || WALL_COLOR_STR;
      altColor  = item.altColor  || ALT_COLOR_STR;
      roofColor = item.roofColor || ROOF_COLOR_STR;
      context.strokeStyle = altColor;

      switch (item.shape) {
        case 'cylinder': Cylinder.draw(context, item.center, item.radius, item.radius, h, mh, wallColor, altColor, roofColor); break;
        case 'cone':     Cylinder.draw(context, item.center, item.radius, 0, h, mh, wallColor, altColor);                      break;
        case 'dome':     Cylinder.draw(context, item.center, item.radius, item.radius/2, h, mh, wallColor, altColor);          break;
        case 'sphere':   Cylinder.draw(context, item.center, item.radius, item.radius, h, mh, wallColor, altColor, roofColor); break;
        case 'pyramid':  Pyramid.draw(context, footprint, item.center, h, mh, wallColor, altColor);                            break;
        default:         Block.draw(context, footprint, item.holes, h, mh, wallColor, altColor, roofColor);
      }

      switch (item.roofShape) {
        case 'cone':    Cylinder.draw(context, item.center, item.radius, 0, h+item.roofHeight, h, roofColor, ''+ Color.parse(roofColor).lightness(0.9));             break;
        case 'dome':    Cylinder.draw(context, item.center, item.radius, item.radius/2, h+item.roofHeight, h, roofColor, ''+ Color.parse(roofColor).lightness(0.9)); break;
        case 'pyramid': Pyramid.draw(context, footprint, item.center, h+item.roofHeight, h, roofColor, Color.parse(roofColor).lightness(0.9));                       break;
      }
    }
  }
};


text:
typedef std::vector<std::vector<std::vector < double>>> vector3D;
typedef std::vector<std::vector<double>> vector2D;
typedef std::vector<double> vector1D;

class FileLoader {
public:
    vector2D loadFile(const char* filePath, size_t row, size_t col);
    virtual void printLoadMode()=0;
protected:
    std::stringstream ss;
private:
    virtual void loadToSS(const char* filePath)=0;

    vector2D ssToVector(size_t row, size_t col);

};

class LfsLoader: public FileLoader {
    virtual void printLoadMode();
private:
    virtual void loadToSS(const char* filePath);

};

class HdfsLoader: public FileLoader {
    virtual void printLoadMode();
private:
    size_t fileSize;
    virtual void loadToSS(const char* filePath);

};

#endif //FASTLSH_FILELOADER_H


text:
"""
Tests for biblio.webquery.querythrottle, using nose.
"""

### IMPORTS ###

import time

from biblio.webquery import querythrottle

### CONSTANTS & DEFINES ###

### TESTS ###

def test_waitonfail():
	# use WaitNSecondsThrottle to test fail behaviour
	throttle = querythrottle.WaitNSecondsThrottle (0.3)
	# should immediately be okay
	start_time = time.time()
	throttle.check_limit (None)
	new_time = time.time()
	assert ((new_time - start_time) < 0.1)
	# should wait for rest of period
	throttle.check_limit (None)
	last_time = time.time()
	assert (0.3 < (last_time - new_time))

def test_raiseonfail():
	# use WaitNSecondsThrottle to test fail behaviour
	throttle = querythrottle.WaitNSecondsThrottle (0.3,
		querythrottle.FAIL_AND_RAISE)
	# should immediately be okay
	start_time = time.time()
	throttle.check_limit (None)
	new_time = time.time()
	assert ((new_time - start_time) < 0.1)
	# should throw since we can't fulfil
	try:
		throttle.check_limit (None)
		assert ("shouldn't get here")
	except:
		pass

def test_waitnsecondsthrottle():
	# check timing works
	throttle = querythrottle.WaitNSecondsThrottle (0.4)
	# should immediately be okay
	assert (throttle.within_limit (None))
	throttle.log_success (None)
	# should be locked down and return false just after success
	assert (not throttle.within_limit (None))
	time.sleep (0.2)
	# shiould still be false, as still within limit
	assert (not throttle.within_limit (None))
	time.sleep (0.3)
	# should have reset by now
	assert (throttle.within_limit (None))

def test_waitonesecondthrottle():
	# check timing works
	throttle = querythrottle.WaitOneSecondThrottle()
	# should immediately be okay
	assert (throttle.within_limit (None))
	throttle.log_success (None)
	# should be locked down and return false for rest of period
	assert (not throttle.within_limit (None))
	time.sleep (0.9)
	assert (not throttle.within_limit (None))
	time.sleep (0.2)
	assert (throttle.within_limit (None))

def test_absolutenumberthrottle():
	throttle = querythrottle.AbsoluteNumberThrottle (5)
	for i in range (5):
		assert (throttle.within_limit (None))
		throttle.log_success (None)
	assert (not throttle.within_limit (None))
	throttle = querythrottle.AbsoluteNumberThrottle (5)
	for i in range (5):
		throttle.check_limit (None)
	try:
		throttle.check_limit (None)
		assert ("shouldn't get here")
	except:
		pass

### END ######################################################################


text:
package com.defterp.modules.users.converters;

import com.defterp.dataAccess.GenericDAO;
import com.defterp.modules.users.entities.User;
import com.defterp.util.JsfUtil;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author MOHAMMED BOUNAGA
 *
 * github.com/medbounaga
 */

@FacesConverter(value = "userConverter")
public class UserConverter implements Converter {

    @Inject
    private GenericDAO dataAccess;

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
        if (value == null || value.length() == 0 || JsfUtil.isDummySelectItem(component, value)) {
            return null;
        }
        return dataAccess.findById(getKey(value), User.class);
    }

    private Integer getKey(String value) {
        Integer key;
        key = Integer.valueOf(value);
        return key;
    }

    private String getStringKey(java.lang.Integer value) {
        StringBuffer sb = new StringBuffer();
        sb.append(value);
        return sb.toString();
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
        if (object == null || (object instanceof String && ((String) object).length() == 0)) {
            return null;
        }
        if (object instanceof User) {
            User o = (User) object;
            return getStringKey(o.getId());
        } else {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), User.class.getName()});
            return null;
        }
    }

}


text:
package com.intellij.execution.testframework.sm.runner.ui;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.intellij.execution.testframework.sm.runner.SMTestProxy;

/**
 * @author Roman Chernyatchik
 *
 * Should be used when one component wan't to propagate (transmit) selection to
 * other component(with/without capturing focus)
 */
public interface PropagateSelectionHandler {
  void handlePropagateSelectionRequest(@Nullable SMTestProxy selectedTestProxy,
                                       @NotNull Object sender,
                                       boolean requestFocus);
}


text:
const path = require('path');
const config = require('../../jest.config');

const projectDir = path.join(__dirname, '../../');

module.exports = {
  preset: 'jest-preset-angular',
  globals: {
    'ts-jest': {
      tsConfig: path.join(__dirname, 'src/tsconfig.spec.json'),
      stringifyContentPathRegex: '\\.html$',
      astTransformers: {
        before: [
          'jest-preset-angular/build/InlineFilesTransformer',
          'jest-preset-angular/build/StripStylesTransformer',
        ],
      },
    },
  },
  roots: [__dirname],
  transform: {
    '^.+\\.stories\\.[jt]sx?$': '@storybook/addon-storyshots/injectFileName',
    '^.+\\.(ts|html)$': 'ts-jest',
    '^.+\\.jsx?$': path.join(projectDir, 'scripts/utils/jest-transform-js.js'),
    '^.+\\.mdx$': '@storybook/addon-docs/jest-transform-mdx',
  },
  moduleFileExtensions: [...config.moduleFileExtensions, 'html'],
  snapshotSerializers: [
    'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js',
    'jest-preset-angular/build/AngularSnapshotSerializer.js',
    'jest-preset-angular/build/HTMLCommentSerializer.js',
  ],
  setupFilesAfterEnv: ['./jest-config/setup.ts'],
  testPathIgnorePatterns: ['app.component.spec.ts'],
};


text:
declare module 'aurelia-history' {

  /**
   * The options that can be specified as part of a history navigation request.
   */
  export interface HistoryOptions {

    /**
       * Replace the existing route.
       */
    replace?: boolean;

    /**
       * Trigger the router.
       */
    trigger?: boolean;
  }

  /**
   * An abstract base class for implementors of the basic history api.
   */
  export class History {

    /**
       * Activates the history object.
       * @param options The set of options to activate history with.
       */
    activate(options: Object): boolean;

    /**
       * Deactivates the history object.
       */
    deactivate(): void;

    /**
       * Causes a history navigation to occur.
       * @param fragment The history fragment to navigate to.
       * @param options The set of options that specify how the navigation should occur.
       */
    navigate(fragment: string, options?: HistoryOptions): boolean;

    /**
       * Causes the history state to navigate back.
       */
    navigateBack(): void;
  }
}


text:
import json
from server.BaseHandler import BaseHandler
from server import jsonEncode
from TirageModele import Tirage

class TirageHandler(BaseHandler):
    def get(self):
        response = { 'tirages': [] }
        tirages = Tirage.query().order(-Tirage.datecreation).fetch()
        for tirage in tirages:
            response['tirages'].append({
                'nomtirage': tirage.nomtirage,
                'datecreation': str(tirage.datecreation)[0:19]
            })
        self.response.write(jsonEncode.encode(response))

    def post(self):
        mode = self.request.GET.get("mode", self.request.url.split("/")[-1].split('?')[0])
        if mode == "creertirage":
            lebody = json.loads(self.request.body)
            pseudo = str(lebody.get('pseudo')).lower()
            pseudo = pseudo.replace(" ", "")
            existe = Tirage.query(Tirage.nomtirage == pseudo).get()
            if existe == None:
                nomtirage = ""
            else:
                nomtirage = existe.nomtirage
            if pseudo != "" and pseudo != None and pseudo != "none" and pseudo != nomtirage:
                tirage = Tirage(nomtirage=pseudo)
                tirage.put()
                response = {
                    'message': 'ok'
                }
                self.response.write(jsonEncode.encode(response))
            else:
                if pseudo == "none":
                    response = {
                        'message': 'none'
                    }
                else:
                    response = {
                        'message': 'ko'
                    }

                self.response.write(jsonEncode.encode(response))

    def put(self):
        pass

    def delete(self):
        pass


text:
'use strict'

var debug = require('debug')('sample')

module.exports.register = function (container) {
  container.component({
    name: 'db',
    factory: createDatabase
  })
}

function createDatabase () {
  debug('creating database')
  // we return a fake database
  return {
    get: function (key) {
      return {title: key, body: 'sample text for ' + key}
    }
  }
}


text:
using updater::StackString;

namespace {
class InstallerStringTest : public testing::Test {
 protected:
  void SetUp() override {}
  void TearDown() override {}
};
}  // namespace

// Tests the strcat/strcpy/length support of the StackString class.
TEST_F(InstallerStringTest, StackStringOverflow) {
  static const wchar_t kTestString[] = L"1234567890";

  StackString<MAX_PATH> str;
  EXPECT_EQ(static_cast<size_t>(MAX_PATH), str.capacity());

  std::wstring compare_str;

  EXPECT_EQ(str.length(), compare_str.length());
  EXPECT_EQ(0, compare_str.compare(str.get()));

  size_t max_chars = str.capacity() - 1;

  while ((str.length() + (_countof(kTestString) - 1)) <= max_chars) {
    EXPECT_TRUE(str.append(kTestString));
    compare_str.append(kTestString);
    EXPECT_EQ(str.length(), compare_str.length());
    EXPECT_EQ(0, compare_str.compare(str.get()));
  }

  EXPECT_GT(static_cast<size_t>(MAX_PATH), str.length());

  // Now we've exhausted the space we allocated for the string,
  // so append should fail.
  EXPECT_FALSE(str.append(kTestString));

  // ...and remain unchanged.
  EXPECT_EQ(0, compare_str.compare(str.get()));
  EXPECT_EQ(str.length(), compare_str.length());

  // Last test for fun.
  str.clear();
  compare_str.clear();
  EXPECT_EQ(0, compare_str.compare(str.get()));
  EXPECT_EQ(str.length(), compare_str.length());
}


text:
package ch.chuv.lren.woken.config

import com.typesafe.config.Config
import ch.chuv.lren.woken.cromwell.core.ConfigUtil._
import ch.chuv.lren.woken.messages.remoting.BasicAuthentication

import cats.data.Validated._
import cats.implicits._

// TODO: review use of the following configuration elements: disableWorkers, jobServiceName

/** Configuration for the application
  *
  * @param clusterSystemName Name of the Akka cluster
  * @param dockerBridgeNetwork If Docker bridge networking is used, name of the bridge - to be used when spanning Docker containers
  * @param networkInterface Network interface to listen to for the web API.
  * @param webServicesPort Port used to expose services of the web API.
  * @param webServicesHttps If true, setup https for the web API.
  * @param disableWorkers If true, disable or ignore worker processes in the cluster (companion Woken validation processes)
  * @param basicAuth Authentication credentials for external access to Woken Web API
  */
case class AppConfiguration(
    clusterSystemName: String,
    dockerBridgeNetwork: Option[String],
    networkInterface: String,
    webServicesPort: Int,
    webServicesHttps: Boolean,
    disableWorkers: Boolean,
    basicAuth: BasicAuthentication
)

object AppConfiguration {

  @SuppressWarnings(Array("org.wartremover.warts.DefaultArguments"))
  def read(config: Config, path: List[String] = List("app")): Validation[AppConfiguration] = {
    val appConfig = config.validateConfig(path.mkString("."))

    appConfig.andThen { app =>
      val clusterSystemName   = app.validateString("clusterSystemName")
      val dockerBridgeNetwork = app.validateOptionalString("dockerBridgeNetwork")
      val networkInterface    = app.validateString("networkInterface")
      val port                = app.validateInt("webServicesPort")

      val https: Validation[Boolean] =
        app.validateBoolean("webServicesHttps").orElse(true.validNel[String])
      val disableWorkers: Validation[Boolean] =
        app.validateBoolean("disableWorkers").orElse(false.validNel[String])

      val basicAuth: Validation[BasicAuthentication] = app.validateConfig("basicAuth").andThen {
        c =>
          val user     = c.validateString("user")
          val password = c.validateString("password")
          (user, password) mapN BasicAuthentication.apply
      }

      (
        clusterSystemName,
        dockerBridgeNetwork,
        networkInterface,
        port,
        https,
        disableWorkers,
        basicAuth
      ) mapN AppConfiguration.apply
    }
  }

}