text:
require 'rails_helper'

RSpec.describe "chains/edit", type: :view do
  before(:each) do
    @chain = assign(:chain, Chain.create!(
      :actuator => nil,
      :function => 'activate',
      :hashtag => "MyString"
    ))
  end

  it "renders the edit chain form" do
    render

    assert_select "form[action=?][method=?]", chain_path(@chain), "post" do

      assert_select "select#chain_actuator_id[name=?]", "chain[actuator_id]"

      assert_select "select#chain_function[name=?]", "chain[function]"

      assert_select "input#chain_hashtag[name=?]", "chain[hashtag]"
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
module Gitlab
  module Diff
    class File
      attr_reader :diff

      delegate :new_file, :deleted_file, :renamed_file,
        :old_path, :new_path, to: :diff, prefix: false

      def initialize(diff)
        @diff = diff
      end

      # Array of Gitlab::DIff::Line objects
      def diff_lines
        @lines ||= parser.parse(raw_diff.lines)
      end

      def mode_changed?
        !!(diff.a_mode && diff.b_mode && diff.a_mode != diff.b_mode)
      end

      def parser
        Gitlab::Diff::Parser.new
      end

      def raw_diff
        diff.diff.to_s
      end

      def next_line(index)
        diff_lines[index + 1]
      end

      def prev_line(index)
        if index > 0
          diff_lines[index - 1]
        end
      end

      def file_path
        if diff.new_path.present?
          diff.new_path
        elsif diff.old_path.present?
          diff.old_path
        end
      end
    end
  end
end


text:
CUIEditBoxEx::CUIEditBoxEx() {
    m_pFrameWindow = xr_new<CUIFrameWindow>();
    AttachChild(m_pFrameWindow);

    TextItemControl()->SetTextComplexMode(true);
}

CUIEditBoxEx::~CUIEditBoxEx() { xr_delete(m_pFrameWindow); }

void CUIEditBoxEx::InitCustomEdit(Fvector2 pos, Fvector2 size) {
    m_pFrameWindow->SetWndSize(size);
    m_pFrameWindow->SetWndPos(Fvector2().set(0, 0));
    CUICustomEdit::InitCustomEdit(pos, size);
}

void CUIEditBoxEx::InitTextureEx(LPCSTR texture, LPCSTR shader) {
    m_pFrameWindow->InitTextureEx(texture, shader);
}
void CUIEditBoxEx::InitTexture(LPCSTR texture) { m_pFrameWindow->InitTexture(texture); }


text:
package org.panteleyev.ofx;

import java.util.List;

public record AccountStatementList(List<AccountStatement> accountStatementList) {
    public AccountInfo getAccountInfo() {
        return accountStatementList.isEmpty() ?
                new AccountInfo() : accountStatementList.get(0).bankAccountFrom();
    }

    public BankTransactionList getBankTransactionList() {
        return accountStatementList.isEmpty() ?
                new BankTransactionList() : accountStatementList.get(0).bankTransactionList();
    }
}


text:
(function(){

	//
	// Test AJAX calls on various ports.
	//
	dohx.add({name:"Basics",
		mqcExecutionOrderBaseOffset:90000, // This number is the base offset for the execution order, the test ID gets added. Never change this number unless you know what you are doing.
		tests:[
			{
				id:100,
				name:'window.Widget',
				test:function(t){
					t.assertTrue(!!window.Widget);
				}
			},{
				id:200,
				name:"window['Widget']",
				test:function(t){
					t.assertTrue(!!window['Widget']);
				}
			},{
				id:300,
				name:"Widget",
				test:function(t){
					t.assertTrue(!!Widget);
				}
			},{
				id:400,
				name:'typeof window!="undefined"',
				test:function(t){
					t.assertTrue(typeof window!="undefined");
				}
			},{
				id:500,
				name:'typeof Widget!="undefined"',
				test:function(t){
					t.assertTrue(typeof Widget!="undefined");
				}
			},{
				id:600,
				name:'typeof window.Widget!="undefined"',
				test:function(t){
					t.assertTrue(typeof window.Widget!="undefined");
				}
			},{
				id:700,
				name:'typeof window.widget!="undefined"',
				test:function(t){
					t.assertTrue(typeof window.widget!="undefined");
				}
			},{
				id:800,
				name:'Is "Widget" in window?',
				test:function(t){
					var hasWidget = false;
					for (var key in window){
						if (key=="Widget"){
							hasWidget = true;
							break;
						}
					}
					t.assertTrue(hasWidget);
				}
			},{
				id:900,
				name:'!!Widget.Device',
				test:function(t){
					t.assertTrue(!!Widget.Device);
				}
			},{
				id:1000,
				name:'!!window.Widget.Device',
				test:function(t){
					t.assertTrue(!!window.Widget.Device);
				}
			}
		]
	});
})();


text:
#include "obstacles.h"

Obstacles::Obstacles()
{
}

/**
 * @brief Obstacles are stored as rectangles. Rectangle is denoted by two points : topLeft and bottomRight.
 * @param firstPoint
 * @param secondPoint
 */
void Obstacles::addObstacle(Vector2f firstPoint, Vector2f secondPoint)
{
    // Get topLeft and bottomRight points from the given points.
    Vector2f tmp;
    if (firstPoint.x() > secondPoint.x() && firstPoint.y() > secondPoint.y()) {
        tmp = firstPoint;
        firstPoint = secondPoint;
        secondPoint = tmp;
    } else if (firstPoint.x() < secondPoint.x() && firstPoint.y() > secondPoint.y()) {
        int height = firstPoint.y() - secondPoint.y();
        firstPoint.y() -= height;
        secondPoint.y() += height;
    } else if (firstPoint.x() > secondPoint.x() && firstPoint.y() < secondPoint.y()) {
        int length = firstPoint.x() - secondPoint.x();
        firstPoint.x() -= length;
        secondPoint.x() += length;
    }
    firstPoint.x() -= BOT_CLEARANCE;
    firstPoint.y() -= BOT_CLEARANCE;
    secondPoint.x() += BOT_CLEARANCE;
    secondPoint.y() += BOT_CLEARANCE;
    obstacles.push_back(make_pair(firstPoint, secondPoint));
}

/**
 * @brief Check if a line segment intersects a rectangle.
 * @param p1
 * @param p2
 * @return
 */
bool Obstacles::isSegmentInObstacle(Vector2f &p1, Vector2f &p2)
{
    QLineF lineSegment(p1.x(), p1.y(), p2.x(), p2.y());
    QPointF *intersectPt = new QPointF;
    for(int i = 0; i < (int)obstacles.size(); i++) {
        float length = obstacles[i].second.x() - obstacles[i].first.x();
        float breadth = obstacles[i].second.y() - obstacles[i].first.y();
        QLineF lseg1(obstacles[i].first.x(), obstacles[i].first.y(), obstacles[i].first.x() + length, obstacles[i].first.y());
        QLineF lseg2(obstacles[i].first.x(), obstacles[i].first.y(), obstacles[i].first.x(), obstacles[i].first.y() + breadth);
        QLineF lseg3(obstacles[i].second.x(), obstacles[i].second.y(), obstacles[i].second.x(), obstacles[i].second.y() - breadth);
        QLineF lseg4(obstacles[i].second.x(), obstacles[i].second.y(), obstacles[i].second.x() - length, obstacles[i].second.y());
        QLineF::IntersectType x1 = lineSegment.intersect(lseg1, intersectPt);
        QLineF::IntersectType x2 = lineSegment.intersect(lseg2, intersectPt);
        QLineF::IntersectType x3 = lineSegment.intersect(lseg3, intersectPt);
        QLineF::IntersectType x4 = lineSegment.intersect(lseg4, intersectPt);
        // check for bounded intersection. IntersectType for bounded intersection is 1.
        if (x1 == 1 || x2 == 1 || x3 == 1 || x4 == 1)
            return true;
    }
    return false;
}


text:
package eu.seaclouds.platform.dashboard.proxy;

import com.squareup.okhttp.mockwebserver.MockResponse;
import eu.seaclouds.platform.dashboard.util.ObjectMapperHelpers;
import eu.seaclouds.platform.dashboard.utils.TestFixtures;
import eu.seaclouds.platform.dashboard.utils.TestUtils;
import org.apache.brooklyn.rest.domain.ApplicationSummary;
import org.apache.brooklyn.rest.domain.EntitySummary;
import org.apache.brooklyn.rest.domain.SensorSummary;
import org.apache.brooklyn.rest.domain.TaskSummary;
import org.testng.annotations.*;

import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.UUID;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;

public class DeployerProxyTest extends AbstractProxyTest<DeployerProxy> {
    private final String RANDOM_STRING = UUID.randomUUID().toString();

    @Override
    public DeployerProxy getProxy() {
        return getSupport().getConfiguration().getDeployerProxy();
    }

    @Test
    public void testGetApplication() throws Exception {
        String json = TestUtils.getStringFromPath(TestFixtures.APPLICATION_PATH);

        getMockWebServer().enqueue(new MockResponse()
                        .setBody(json)
                        .setHeader("Accept", MediaType.APPLICATION_JSON)
                        .setHeader("Content-Type", MediaType.APPLICATION_JSON)
        );
        assertEquals(ObjectMapperHelpers.JsonToObject(json, ApplicationSummary.class), getProxy().getApplication(RANDOM_STRING));
    }

    @Test
    public void testRemoveApplication() throws Exception {
        String json = TestUtils.getStringFromPath(TestFixtures.TASK_SUMMARY_DELETE_PATH);

        getMockWebServer().enqueue(new MockResponse()
                        .setBody(json)
                        .setHeader("Accept", MediaType.APPLICATION_JSON)
                        .setHeader("Content-Type", MediaType.APPLICATION_JSON)
        );

        TaskSummary response = getProxy().removeApplication(RANDOM_STRING);

        // TaskSummary doesn't implement equals(), so we are going to check the IDs
        TaskSummary fixture = ObjectMapperHelpers.JsonToObject(json, TaskSummary.class);
        assertEquals(fixture.getId(), response.getId());
    }

    @Test
    public void testDeployApplication() throws Exception {
        String json = TestUtils.getStringFromPath(TestFixtures.TASK_SUMMARY_DEPLOY_PATH);
        String tosca = TestUtils.getStringFromPath(TestFixtures.TOSCA_DAM_PATH);

        getMockWebServer().enqueue(new MockResponse()
                        .setBody(json)
                        .setHeader("Accept", MediaType.APPLICATION_JSON)
                        .setHeader("Content-Type", MediaType.APPLICATION_JSON)
        );
        TaskSummary response = getProxy().deployApplication(tosca);

        // TaskSummary doesn't implement equals(), so we are going to check the IDs
        TaskSummary fixture = ObjectMapperHelpers.JsonToObject(json, TaskSummary.class);
        assertEquals(fixture.getId(), response.getId());
    }

    @Test
    public void testGetEntitiesFromApplication() throws Exception {
        String json = TestUtils.getStringFromPath(TestFixtures.ENTITIES_PATH);

        getMockWebServer().enqueue(new MockResponse()
                        .setBody(json)
                        .setHeader("Accept", MediaType.APPLICATION_JSON)
                        .setHeader("Content-Type", MediaType.APPLICATION_JSON)
        );
        List<EntitySummary> response = getProxy().getEntitiesFromApplication(RANDOM_STRING);

        List<EntitySummary> fixture = ObjectMapperHelpers.JsonToObjectCollection(json, EntitySummary.class);
        assertEquals(fixture, response);
    }

    @Test
    public void testGetEntitySensors() throws Exception {
        String json = TestUtils.getStringFromPath(TestFixtures.SENSORS_SUMMARIES_PATH);

        getMockWebServer().enqueue(new MockResponse()
                        .setBody(json)
                        .setHeader("Accept", MediaType.APPLICATION_JSON)
                        .setHeader("Content-Type", MediaType.APPLICATION_JSON)
        );
        List<SensorSummary> response = getProxy().getEntitySensors(RANDOM_STRING, RANDOM_STRING);

        List<SensorSummary> fixture = ObjectMapperHelpers.JsonToObjectCollection(json, SensorSummary.class);
        assertEquals(fixture, response);
    }

    @Test
    public void testGetEntitySensorsValue() throws Exception {
        getMockWebServer().enqueue(new MockResponse()
                        .setBody("0.7")
                        .setHeader("Accept", MediaType.APPLICATION_JSON)
                        .setHeader("Content-Type", MediaType.APPLICATION_JSON)
        );

        String response = getProxy().getEntitySensorsValue(RANDOM_STRING, RANDOM_STRING, RANDOM_STRING);
        assertEquals("0.7", response);
    }
}


text:
<!doctype html>

<title>Web Episodes</title>
<meta charset="UTF-8">

code

Web Episodes

Web Episodes is a script for gathering Real User Measurement (RUM) performance timings from web pages.
The key aspects of Web Episodes are:

 it loads asynchronously

 it supports Navigation Timing and Resource Timing

 it supports measuring Web 2.0 applications

 measurements are made using JavaScript events so there can be multiple listeners

 it's designed to be an industry standard for web developers, web metrics service providers, tool developers, and browser developers

 it's open source

Examples:

 example 1 - a simple example using default settings

See these slides for more information.


text:
package org.apache.kafka.test;

import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.header.Headers;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.streams.processor.MockProcessorContext;
import org.apache.kafka.streams.processor.StateRestoreCallback;
import org.apache.kafka.streams.processor.StateStore;
import org.apache.kafka.streams.processor.StreamPartitioner;
import org.apache.kafka.streams.processor.TaskId;
import org.apache.kafka.streams.processor.internals.InternalProcessorContext;
import org.apache.kafka.streams.processor.internals.ProcessorNode;
import org.apache.kafka.streams.processor.internals.ProcessorRecordContext;
import org.apache.kafka.streams.processor.internals.RecordCollector;
import org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl;
import org.apache.kafka.streams.state.internals.ThreadCache;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import static java.util.Collections.unmodifiableList;

public class MockInternalProcessorContext extends MockProcessorContext implements InternalProcessorContext {
    public static final class MockRecordCollector implements RecordCollector {
        private final List<ProducerRecord<byte[], byte[]>> collected = new LinkedList<>();

        @Override
        public <K, V> void send(final String topic,
                                final K key,
                                final V value,
                                final Headers headers,
                                final Integer partition,
                                final Long timestamp,
                                final Serializer<K> keySerializer,
                                final Serializer<V> valueSerializer) {
            collected.add(new ProducerRecord<>(topic,
                                               partition,
                                               timestamp,
                                               keySerializer.serialize(topic, key),
                                               valueSerializer.serialize(topic, value),
                                               headers));
        }

        @Override
        public <K, V> void send(final String topic,
                                final K key,
                                final V value,
                                final Headers headers,
                                final Long timestamp,
                                final Serializer<K> keySerializer,
                                final Serializer<V> valueSerializer,
                                final StreamPartitioner<? super K, ? super V> partitioner) {
            throw new UnsupportedOperationException();
        }

        @Override
        public void init(final Producer<byte[], byte[]> producer) {

        }

        @Override
        public void flush() {

        }

        @Override
        public void close() {

        }

        @Override
        public Map<TopicPartition, Long> offsets() {
            return null;
        }

        public List<ProducerRecord<byte[], byte[]>> collected() {
            return unmodifiableList(collected);
        }
    }

    private final Map<String, StateRestoreCallback> restoreCallbacks = new LinkedHashMap<>();
    private ProcessorNode currentNode;
    private RecordCollector recordCollector;

    public MockInternalProcessorContext() {
    }

    public MockInternalProcessorContext(final Properties config, final TaskId taskId, final File stateDir) {
        super(config, taskId, stateDir);
    }

    @Override
    public StreamsMetricsImpl metrics() {
        return (StreamsMetricsImpl) super.metrics();
    }

    @Override
    public ProcessorRecordContext recordContext() {
        return new ProcessorRecordContext(timestamp(), offset(), partition(), topic(), headers());
    }

    @Override
    public void setRecordContext(final ProcessorRecordContext recordContext) {
        setRecordMetadata(
            recordContext.topic(),
            recordContext.partition(),
            recordContext.offset(),
            recordContext.headers(),
            recordContext.timestamp()
        );
    }

    @Override
    public void setCurrentNode(final ProcessorNode currentNode) {
        this.currentNode = currentNode;
    }

    @Override
    public ProcessorNode currentNode() {
        return currentNode;
    }

    @Override
    public ThreadCache getCache() {
        return null;
    }

    @Override
    public void initialize() {}

    @Override
    public void uninitialize() {}

    @Override
    public RecordCollector recordCollector() {
        return recordCollector;
    }

    public void setRecordCollector(final RecordCollector recordCollector) {
        this.recordCollector = recordCollector;
    }

    @Override
    public void register(final StateStore store, final StateRestoreCallback stateRestoreCallback) {
        restoreCallbacks.put(store.name(), stateRestoreCallback);
        super.register(store, stateRestoreCallback);
    }

    public StateRestoreCallback stateRestoreCallback(final String storeName) {
        return restoreCallbacks.get(storeName);
    }
}


text:
import os.path
FILE_PATH = os.path.dirname(os.path.realpath(__file__))
DATA_PATH = FILE_PATH + '/../data/'
import sys
sys.path.append(FILE_PATH + '/..')
import matplotlib.pyplot as plt

import csv
from numpy import arange
from pybbsens import units
from pybbsens import isotope
from pybbsens import experiment
from pybbsens import conflimits
from pybbsens import nmeset

isotope.SelectNMESet(nmeset.nmedb['QRPA_Jy'])

########################################
### EXPERIMENT DATA ####################

name = "GeFuture"
isot = isotope.Ge76
eff  = 0.62
eres = isot.Qbb * 0.0015
bkg  = 1E-3 / (units.keV*units.kg*units.year)
mass = 500. *units.kg               #dummy
expo = 2000 *units.kg*units.year    #dummy

nmes=["ISM","IBM2","QRPA_Tu","QRPA_Jy","EDF"]

########################################
### Create a confidence-limit calculator.
### We use in this case the Feldman-Cousins memoizer.
fcm = conflimits.FCMemoizer(0.9)
fcm.ReadTableAverageUpperLimits(DATA_PATH+'FC90.dat')

exp = experiment.Experiment(name, isotope.Ge76, eff, eres, bkg, mass)

for nme in nmes:
	filename = 'GeExp_' + nme + '.txt'
	writer = csv.writer(open(filename, 'w'))

	isotope.SelectNMESet(nmeset.nmedb[nme])
	for exposure in arange(100., 10010., 10.):
		exposure = exposure * units.kg * units.year
		mbb = exp.sensitivity(exposure, fcm) / units.meV
		exposure = exposure / (units.kg*units.year)
		writer.writerow([exposure,mbb])


text:
package org.ohdsi.webapi;

import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.annotation.PostConstruct;
import java.util.TimeZone;
import org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration;

/**
 * Launch as java application or deploy as WAR (@link {@link WebApplication}
 * will source this file).
 */
@EnableScheduling
@SpringBootApplication(exclude={HibernateJpaAutoConfiguration.class, ErrorMvcAutoConfiguration.class, SolrAutoConfiguration.class})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class WebApi extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(WebApi.class);
    }

    public static void main(final String[] args) throws Exception
    {
        TomcatURLStreamHandlerFactory.disable();
        new SpringApplicationBuilder(WebApi.class).run(args);
    }

    @PostConstruct
    public void init() {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    }

}


text:
template<int N>
static bool round_test_imp()
{
  typedef boost::multiprecision::cpp_dec_float<N> mp_backend_type;
  typedef boost::multiprecision::number<mp_backend_type, boost::multiprecision::et_off> mp_type;

  const mp_type original_digits(1.0F);

  const mp_type scale = pow(mp_type(10), N);

  mp_type these_digits = original_digits * scale;

  these_digits  = boost::math::round(these_digits);
  these_digits /= scale;

  const std::string result = these_digits.str();

  return (result == original_digits.str());
}

template<int N>
struct round_test
{
  static bool test()
  {
    return (round_test_imp<N>() && round_test<N - 1>::test());
  }
};

template<>
struct round_test<0>
{
  static bool test()
  {
    return round_test_imp<0>();
  }
};

int main()
{
   //
   // Test cpp_dec_float rounding with boost::math::round() at various precisions:
   //
   const bool round_test_result = round_test<40>::test();

   BOOST_CHECK_EQUAL(round_test_result, true);

   return boost::report_errors();
}


text:
<?xml version="1.0"?>
<Document>

	<Sentence>
		<value>Week 4   - Once the blastocyst reaches the uterus, it buries itself in the uterine wall.</value>
		<pattern_crowdsource> Week 4   - Once the blastocyst reaches the [[uterus|C0042149]], it buries itself in the [[uterine wall|C0447620]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Week</surface-form>
				<RDF-ID>C0439230</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>blastocyst</surface-form>
				<RDF-ID>C0005705</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>uterus</surface-form>
				<RDF-ID>C0042149</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>uterine wall</surface-form>
				<RDF-ID>C0447620</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0447620 LOCATION_OF C0042149</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>- At this point in the mother's menstrual cycle, the lining of the uterus is thick with blood and ready to support a baby.</value>
		<pattern_crowdsource> - At this point in the [[mother's|C0026591]] [[menstrual cycle|C0025329]], the lining of the [[uterus|C0042149]] is thick with [[blood|C0005767]] and ready to support a baby.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>mother's</surface-form>
				<RDF-ID>C0026591</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>menstrual cycle</surface-form>
				<RDF-ID>C0025329</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>uterus</surface-form>
				<RDF-ID>C0042149</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>thick</surface-form>
				<RDF-ID>C1280412</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>blood</surface-form>
				<RDF-ID>C0005767</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>baby</surface-form>
				<RDF-ID>C0021270</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0025329 PROCESS_OF C0026591</triple>
			<triple>C0005767 PART_OF C0042149</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>This includes certain medicines, illegal drug use, heavy alcohol use, infections such as rubella, and other factors.</value>
		<pattern_crowdsource> This includes certain medicines, illegal drug use, heavy alcohol use, [[infections|C0021311]] such as [[rubella|C0035920]], and other factors.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>certain</surface-form>
				<RDF-ID>C0205423</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>medicines</surface-form>
				<RDF-ID>C0013227</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>illegal drug use</surface-form>
				<RDF-ID>C0281875</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>heavy alcohol use</surface-form>
				<RDF-ID>C0687132</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>infections</surface-form>
				<RDF-ID>C0021311</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>rubella</surface-form>
				<RDF-ID>C0035920</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>factors</surface-form>
				<RDF-ID>C1521761</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0035920 ISA C0021311</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>- Nails appear on the fingers and toes.</value>
		<pattern_crowdsource> - [[Nails|C0027342]] appear on the [[fingers|C0016129]] and toes.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Nails</surface-form>
				<RDF-ID>C0027342</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>fingers</surface-form>
				<RDF-ID>C0016129</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>toes</surface-form>
				<RDF-ID>C0040357</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0016129 LOCATION_OF C0027342</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>- Fine hair called lanugo develops on baby's head.</value>
		<pattern_crowdsource> - Fine hair called [[lanugo|C0023032]] develops on baby's [[head|C0018670]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Fine hair</surface-form>
				<RDF-ID>C0423867</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lanugo</surface-form>
				<RDF-ID>C0023032</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>baby's</surface-form>
				<RDF-ID>C0021270</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>head</surface-form>
				<RDF-ID>C0018670</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0018670 LOCATION_OF C0023032</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>- The mother may feel a fluttering in the lower abdomen.</value>
		<pattern_crowdsource> - The mother may feel a [[fluttering|C0016385]] in the [[lower abdomen|C0230166]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>mother</surface-form>
				<RDF-ID>C0026591</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>fluttering</surface-form>
				<RDF-ID>C0016385</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lower abdomen</surface-form>
				<RDF-ID>C0230166</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0230166 LOCATION_OF C0016385</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>- The baby is more active with increased muscle development.</value>
		<pattern_crowdsource> - The [[baby|C0021270]] is more active with increased [[muscle development|C0949649]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>baby</surface-form>
				<RDF-ID>C0021270</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>more</surface-form>
				<RDF-ID>C0205172</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>active</surface-form>
				<RDF-ID>C0205177</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>increased</surface-form>
				<RDF-ID>C0205217</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>muscle development</surface-form>
				<RDF-ID>C0949649</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0949649 PROCESS_OF C0021270</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>- The lower airways of the baby's lungs develop.</value>
		<pattern_crowdsource> - The lower [[airways|C0178987]] of the [[baby's|C0021270]] [[lungs|C0024109]] develop.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>lower</surface-form>
				<RDF-ID>C0441994</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>airways</surface-form>
				<RDF-ID>C0178987</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>baby's</surface-form>
				<RDF-ID>C0021270</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lungs</surface-form>
				<RDF-ID>C0024109</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0024109 PART_OF C0021270</triple>
			<triple>C0024109 LOCATION_OF C0178987</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>- Baby has definite sleeping patterns.</value>
		<pattern_crowdsource> - [[Baby|C0021270]] has definite [[sleeping patterns|C0474396]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Baby</surface-form>
				<RDF-ID>C0021270</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>definite</surface-form>
				<RDF-ID>C0439544</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>sleeping patterns</surface-form>
				<RDF-ID>C0474396</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0474396 PROCESS_OF C0021270</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Week 38 to 40   - Lanugo is gone except for on the upper arms and shoulders.</value>
		<pattern_crowdsource> Week 38 to 40   - [[Lanugo|C0023032]] is gone except for on the [[upper arms|C0446516]] and shoulders.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Week</surface-form>
				<RDF-ID>C0439230</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Lanugo</surface-form>
				<RDF-ID>C0023032</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>upper arms</surface-form>
				<RDF-ID>C0446516</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>shoulders</surface-form>
				<RDF-ID>C0037004</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0446516 LOCATION_OF C0023032</triple>
		</triples>
	</Sentence>

</Document>


text:
<%#
 Copyright 2013-2018 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see http://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
/// <reference path="../../../../node_modules/@types/jasmine/index.d.ts" />
import 'core-js';
import 'zone.js/dist/zone';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/proxy';
import 'zone.js/dist/jasmine-patch';
import 'rxjs';
import 'intl/locale-data/jsonp/en-US.js';
import { TestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';

TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());

declare let require: any;
const testsContext: any = require.context('./', true, /\.spec/);
testsContext.keys().forEach(testsContext);


text:
package com.fw.edc;

import com.github.shyiko.mysql.binlog.event.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by mxu2 on 5/31/15.
 */
public class PackagedEvent {
    private EventType type;
    private String database;
    private String tableName;
    private String entryName;
    private String entryId;
    private List<List<Field>> recordFields = new ArrayList<List<Field>>();

    public PackagedEvent(List<Event> events) throws Exception {
        Event mainEvent = events.get(events.size() - 1);
        this.type = mainEvent.getHeader().getEventType();

        TableMapEventData tableMap = (TableMapEventData) events.get(events.size() - 2).getData();
        this.database = tableMap.getDatabase();
        this.tableName = tableMap.getTable();

        List<MysqlField> fields = MysqlMetadata.getInstance().getFieldList(database, this.tableName);
        if (EventType.isUpdate(this.type)) {
            UpdateRowsEventData updateData = (UpdateRowsEventData) mainEvent.getData();
            for (Map.Entry<Serializable[], Serializable[]> row : updateData.getRows()) {
                Serializable[] oldValues = row.getKey();
                Serializable[] newValues = row.getValue();
                List<Field> recordField = new ArrayList<Field>();
                for (int i = 0; i < fields.size(); i++) {
                    MysqlField mField = fields.get(i);
                    Serializable oldValue = oldValues[i];
                    Serializable newValue = newValues[i];
                    if (mField.isEnumType()) {
                        oldValue = mField.enumConvert(oldValue);
                        newValue = mField.enumConvert(newValue);
                    }
                    Field field = new Field(mField.getName(), oldValue, newValue);
                    recordField.add(field);
                }
                recordFields.add(recordField);
            }
        } else if (EventType.isWrite(this.type)) {
            WriteRowsEventData writeData = (WriteRowsEventData) mainEvent.getData();
            for (Serializable[] row : writeData.getRows()) {
                List<Field> recordField = new ArrayList<Field>();
                for (int i = 0; i < fields.size(); i++) {
                    MysqlField mField = fields.get(i);
                    Serializable insertValue = row[i];
                    if (mField.isEnumType()) {
                        insertValue = mField.enumConvert(insertValue);
                    }
                    Field field = new Field(mField.getName(), "", insertValue);
                    recordField.add(field);
                }
                recordFields.add(recordField);
            }
        } else if (EventType.isDelete(this.type)) {
            DeleteRowsEventData deleteData = (DeleteRowsEventData) mainEvent.getData();
            for (Serializable[] row : deleteData.getRows()) {
                List<Field> recordField = new ArrayList<Field>();
                for (int i = 0; i < fields.size(); i++) {
                    MysqlField mField = fields.get(i);
                    Serializable deleteValue = row[i];
                    if (mField.isEnumType()) {
                        deleteValue = mField.enumConvert(deleteValue);
                    }
                    Field field = new Field(mField.getName(), deleteValue, "");
                    recordField.add(field);
                }
                recordFields.add(recordField);
            }
        }
    }

    public PackagedEvent() {

    }

    public static String showType(EventType type) {
        if (EventType.isUpdate(type)) {
            return "UPDATE";
        }
        if (EventType.isWrite(type)) {
            return "INSERT";
        }
        if (EventType.isDelete(type)) {
            return "DELETE";
        }
        return "";
    }

    public static EventType convertType(String type) {
        if ("INSERT".equals(type)) {
            return EventType.WRITE_ROWS;
        } else if ("UPDATE".equals(type)) {
            return EventType.UPDATE_ROWS;
        } else if ("DELETE".equals(type)) {
            return EventType.DELETE_ROWS;
        }
        return null;
    }

    public String getDatabase() {
        return database;
    }

    public void setDatabase(String database) {
        this.database = database;
    }

    public EventType getType() {
        return type;
    }

    public void setType(EventType type) {
        this.type = type;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public List<List<Field>> getRecordFields() {
        return recordFields;
    }

    public void setRecordFields(List<List<Field>> recordFields) {
        this.recordFields = recordFields;
    }

    public boolean filterOutBy(List<EventFilter> eventFilters) {
        for (EventFilter ef : eventFilters) {
            if (!this.database.equals(ef.getDatabase()) && !"*".equals(ef.getDatabase())) {
                continue;
            } else {
                if (!this.tableName.equals(ef.getTableName()) && !"*".equals(ef.getTableName())) {
                    continue;
                } else {
                    if ("*".equals(ef.getFieldName())) {
                        return true;
                    } else {
                        for (List<Field> recordField : recordFields) {
                            for (Field field : recordField) {
                                boolean otherUpdated = false;
                                for (Field field1 : recordField) {
                                    if (!field1.name.equals(ef.getFieldName()) && field1.updated) {
                                        otherUpdated = true;
                                    }
                                }
                                if (field.name.equals(ef.getFieldName()) && field.updated && !otherUpdated) {
                                    return true;
                                }
                            }
                        }
                    }

                }
            }
        }
        return false;
    }

    public String getEntryName() {
        return entryName;
    }

    public void setEntryName(String entryName) {
        this.entryName = entryName;
    }

    public String getEntryId() {
        return entryId;
    }

    public void setEntryId(String entryId) {
        this.entryId = entryId;
    }

    static class Field {
        String name;
        Serializable oldValue;
        Serializable newValue;
        boolean updated = false;

        public Field() {
        }

        public Field(String name, Serializable oldValue, Serializable newValue) {
            this.name = name;
            this.oldValue = oldValue;
            this.newValue = newValue;
            if (oldValue == null) {
                if (newValue != null) {
                    this.updated = true;
                }
            } else {
                if (newValue == null) {
                    this.updated = true;
                } else {
                    if (!oldValue.toString().equals(newValue.toString())) {
                        this.updated = true;
                    }
                }
            }
        }

    }
}


text:
package com.mgmtp.jfunk.web.util;

import org.openqa.selenium.WebElement;

/**
 * {@link RuntimeException} related to exceptions with {@link WebElement}s.
 *
 * @author rnaegele
 */
public class WebElementException extends RuntimeException {

	public WebElementException(final String message, final Throwable cause) {
		super(message, cause);
	}

	public WebElementException(final String message) {
		super(message);
	}

	public WebElementException(final Throwable cause) {
		super(cause);
	}
}


text:
<!doctype html>

	<meta charset="utf-8"/>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<link href="/lib/bootstrap2/css/bootstrap.min.css" rel="stylesheet" media="screen">

	<link rel="stylesheet" href="/lib/jquery/jquery-ui.css">
	<link rel="stylesheet" href="/lib/jquery/jquery-ui-timepicker-addon.css">

	<link rel="stylesheet" href="/dist/styles/main.css">
	<link rel="stylesheet" href="/package/logpresso/backup/backup.css">
	<link rel="stylesheet" href="/package/logpresso/logquery/logquery2.css">
	<link rel="stylesheet" href="/package/logpresso/table/table.css">


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Encyclop. Mycol. (Paris), <b>1</b> Le Genre Inocybe 1: 235 (1931)

#### Original name
Inocybe descissa var. macrospora R. Heim

### Remarks
null


text:
layout: archive
lang: en
ref: cm-530
read_time: true
share: true
author_profile: false
permalink: /docs/en/parts/controller/cm-530/
sidebar:
  title: CM-530
  nav: "cm-530"
---

# [Introduction](#introduction)

![](/assets/images/parts/controller/cm-530/cm-530_product.png)

> CM-530

# [Specifications](#specifications)

|Item|Description|
|:---:|:---:|
|Weight|54g|
|CPU|STM32F103RE|
|Voltage Supply|Range : 6V ~ 15V
Recommended : 11.1V (3S1P Li-Po)|
|Current Consumption|Standby : 50mA
External I/O Max Current : 300mA
Total Max Current : 10A(Fuse)|
|Operation Temperature|-5°C ~ 70°C|
|Internal I/O Device|Button x 5(Reset 1, Port 5)
MIC for sound detection x 1
Voltage Sensor x 1|
|External I/O Device|ROBOTIS 5-Pin Port x 6
AX/MX Series Dynamixel Connector x 5|

# [Layout](#layout)

![](/assets/images/parts/controller/cm-530/cm-530_01.png)

- **PC Link (Serial Cable)** : Used to connect the serial cable to the CM-530 and PC via USB. Used for communication with other PC or downloading task code.
- **Communication Device Connection Jack** : Used for wireless communicate with ZIG-110A, BT-110A, IR receiver modules or other boards
- **Battery Jack** : Used to connect with the battery.
- **Power Jack** : Used to connect the SMPS power supply
- **Power LED** : ON and OFF LED status for the power
- **Power Switch** : Used to turn the robot ON / OFF.
- **MODE Button** : Used to change the operation mode of CM-530. Please read below for more information.
- **START Button** : Used to START selected mode. Please read below for more information.
- **U / L / D / R Button** : Used for input purposes when a program is playing. These buttons can be used to send commands to the robot.
- **AX/MX Serise Bus Port** : Used to connect the AX/MX Dynamixel in a daisy chain method.
- **ROBOTIS 5-Pin Port** : Used to connect Distance Measurement Sensor, Touch Sensor, IR Sensor, and peripheral devices. The port numbers for each port are represented in bars such as I , II , III, IIII , IIIII , and IIIIII.
- **Mode Display LED** : LED to display current operation mode of CM-530; Detailed descriptions are provided as below.

## [MANAGE]
- It displays Dynamixel Management Mode is in progress.
- It is used to set or test the operations of CM-530 and AX-12A using [RoboPlus Manager].
- It is automatically executed when RoboPlus Manager and CM-530 are connected.

## [PROGRAM]
- It displays the motion edit mode is in progress.
- It is used when the motions are editted with [RoboPlus Motion].
- It is automatically executed when RoboPlus Motion and CM-530 are connected.

## [PLAY]
- It displays the task code mode is in progress.
- It is used after downloading the written code to CM-530 with [RoboPlus Task].
- The Start button must be pressed directly by the user to execute when PLAY LED flickers.

- **Status Display LED** : The LED represents the current status of CM-530. Detailed discriptions are provided as below.
  - **TxD** : Turned on while CM-530 is transmitting the data to the outside.
  - **RxD** : Turned on while CM-530 is receiving the data from the outside.
  - **AUX** : Assigned LED to be used by the user in the program.  It can be turned on or off using task code.

## [Pinout](#pinout)

### Power

The pin composition of CM-530 Power is as below.

![](/assets/images/parts/controller/cm-530/cm-530_06.png)

### External 5-Pin Port

The pin composition of CM-530 external port is as below.

![](/assets/images/parts/controller/cm-530/cm-530_07.png)

![](/assets/images/parts/controller/cm-530/cm-530_08.png)

1. OUT : 3.3V- Torque Possible (Maximum Allowed Current 0.3A)
2. VDD (5V)
3. ADC : The analog signals from the sensor made by the user can be read.
4. GND
5. OUT2 : 3.3V- Torque Possible (Maximum Allowed Current 0.3A)

### Communication Device Connection Port

The functions on the pins of communication device connection port are as below.

![](/assets/images/parts/controller/cm-530/cm-530_09.png)

1. GND : Ground Level (0v)
2. VDD :  Supply Voltage ( 2.7~3.6V )
3. RXD : Receive Signal Terminal
4. TXD :  Transmit Signal Terminal

### 3-Pin Connector Port

The functions of pins on the 3-pin connector port are as follows. Please refer to [AX-Series Pin Assignment] for more information.
Please be careful not to change the direction considering the angular part.

![](/assets/images/parts/controller/cm-510/cm-510_13.png)

1. GND : Ground Level (0v)
2. VDD :  Supply Voltage (It is equal to the voltage of battery)
3. DATA :  Data Transmission Pin

{% include en/dxl/pinout_warning.md %}

# [Connecting Power](#connecting-power)

The power is applied  if the battery is connected to battery socket of CM-530 or if the power switch is set to ON after connecting SMPS to power jack socket. If the power is impressed, Power LED is turned on and one of the Mode Display LEDs flickers.

![](/assets/images/parts/controller/cm-530/cm-530_02.jpg)

# [How to Operate](#how-to-operate)

- **Turning the power on** : The power is turned on by moving the switch from OFF to ON.
  ※ If the power is not turned on in spite of moving the switch to ON, the batteries may have been discharged.
  Pleaser refer to Charging to recharge, or connect the power using SMPS.
- **Start** : Move to PLAY using Mode Button to operate robots.  Press START Button to execute when the LED on PLAY flickers.
  ※ If START button is pressed, the LED on PLAY is not supposed to be flickering any more; that is the normal status of the execution.
- **End** :  If you want to stop the executed operations, press MODE Button to get back to waiting mode stauts, or turn OFF the power using Power Switch.
- It is used to control Dynamixel and the peripherals, and it can connect Dynamixel(AX/MX Dynamixel... etc.) and various parts of OLLO(Touch Sensor, LED Module, IR Sensor etc.).
- Specific motions can be edited and saved through RoboPlus Motion.  The saved motion (mtn file) can be always executed by RoboPlus Task, and also the motions of each part can be controlled by writing the task codes for control.

- RoboPlus Motion

![](/assets/images/parts/controller/cm-5/cm-5_04.jpg)

- RoboPlus Task

![](/assets/images/parts/controller/cm-5/cm-5_05.jpg)

- RoboPlus Manager

![](/assets/images/parts/controller/cm-5/cm-5_06.jpg)

- Embedded C
  The controller of CM-530 can be controlled in C language.  Please refer to [Embedded C] for more information.

# [Connect to PC](#connect-to-pc)

PC Link(Serial Cable) of CM-530 and Serial Port of PC must be connected using download cable to communication with PC.

![](/assets/images/parts/controller/cm-530/cm-530_03.jpg)

# [Wireless Communication](#wireless-communication)

[ZIG-110]/[BT-110]/[BT-410] Wireless Communication Module can be connected to CM-530.

![](/assets/images/parts/controller/cm-530/cm-530_04.jpg)

![](/assets/images/parts/controller/cm-530/cm-530_05.jpg)

# [Charging](#charging)

You may obtain Lithium polymer batteries from [www.robotis-shop-en.com](www.robotis-shop-en.com).

If the robot alarm sounds off during operations then recharge the battery.

During charging the charger's red LED turns on. When complete the green LED turns on.

1. Take the battery out

  ![](/assets/images/parts/controller/cm-530/cm_530_battery_charge_01.png)

2. Connect the charger

  ![](/assets/images/parts/controller/cm-530/cm_530_battery_charge_02.png)

3. Charge

  Charging(Red LED), Complete(Green LED)

  ![](/assets/images/parts/controller/cm-530/cm_530_battery_charge_03.png)

- You can connect the robot to an external power source through SMPS.

  ![](/assets/images/parts/controller/cm-530/cm_530_battery_charge_04.png)

- The battery is equipped with a connector to charge the battery and another to move the robot

  ![](/assets/images/parts/controller/cm-530/cm_530_battery_charge_05.jpg)

## Charging Time and Battery Life/Operating

### Charging Time

- When fully discharged : 1~1.5 hour
- Leaving the battery fully discharged for too long may reduce its lifespan drastically.
- Time to charge the battery depends on the status of the battery(If the charging time or battery life becomes too short, you may need to replace your battery).

{% capture stem_charge_caution_01 %}
`Caution`
1. Do NOT  keep the battery connected with a robot or a charger.
2. If you will not use the battery for a long time from now on, please keep it HALF-CHARGED.
3. Do NOT  put the battery with an environment with high temperature or humidity.
{% endcapture %}

  {{ stem_charge_caution_01 | markdownify }}

# [Fuse Replacement](#fuse-replacement)

{% include en/parts/controller/fuse_cm510_530.md %}

# [Videos](#videos)

[RoboPlus Task]: /docs/en/software/rplus1/task/getting_started/
[RoboPlus Motion]: /docs/en/software/rplus1/motion/
[RoboPlus Manager]: /docs/en/software/rplus1/manager/
[Embedded C]: /docs/en/software/embedded_sdk/embedded_c_cm530/
[Number of pressed Start button]: /docs/en/software/rplus1/task/programming_02/#button-count
[Start button]: /docs/en/software/rplus1/task/programming_02/#button-count
[LN-101]: /docs/en/parts/interface/ln-101/
[ZIG-110]: /docs/en/parts/communication/zig-110/
[BT-110]: /docs/en/parts/communication/bt-110/
[BT-210]: /docs/en/parts/communication/bt-210/
[BT-410]: /docs/en/parts/communication/bt-410/
[Automatic Turn-off]: /docs/en/software/rplus1/task/programming_02/#powersave-timer
[Firmware Update]: /docs/en/software/rplus1/manager/#firmware-update
[AX-Series Pin Assignment]: /docs/en/dxl/ax/ax-12a/#pin-assignment


text:
var arrayMap = require('./_arrayMap'),
    baseClone = require('./_baseClone'),
    baseUnset = require('./_baseUnset'),
    castPath = require('./_castPath'),
    copyObject = require('./_copyObject'),
    flatRest = require('./_flatRest'),
    getAllKeysIn = require('./_getAllKeysIn');

/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
    CLONE_FLAT_FLAG = 2,
    CLONE_SYMBOLS_FLAG = 4;

/**
 * The opposite of `_.pick`; this method creates an object composed of the
 * own and inherited enumerable property paths of `object` that are not omitted.
 *
 * **Note:** This method is considerably slower than `_.pick`.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The source object.
 * @param {...(string|string[])} [paths] The property paths to omit.
 * @returns {Object} Returns the new object.
 * @example
 *
 * var object = { 'a': 1, 'b': '2', 'c': 3 };
 *
 * _.omit(object, ['a', 'c']);
 * // => { 'b': '2' }
 */
var omit = flatRest(function(object, paths) {
  var result = {};
  if (object == null) {
    return result;
  }
  var bitmask = CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG;
  paths = arrayMap(paths, function(path) {
    path = castPath(path, object);
    bitmask |= (path.length > 1 ? CLONE_DEEP_FLAG : 0);
    return path;
  });

  copyObject(object, getAllKeysIn(object), result);
  result = baseClone(result, bitmask);

  var length = paths.length;
  while (length--) {
    baseUnset(result, paths[length]);
  }
  return result;
});

module.exports = omit;


text:
fhand = open('mbox-short.txt')
for line in fhand:
    line = line.rstrip()
    if line.startswith('From:') :
        print line


text:
import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class UsersService {

  constructor(private http: Http) {}

addNew(usercreds:any) {
  var headers = new Headers();
        var creds = 'name=' + usercreds.username + '&password=' + usercreds.password;
        var emailid = 'name=' + usercreds.username;

        headers.append('Content-Type', 'application/X-www-form-urlencoded');

        this.http.post('http://localhost:5555/adduser', creds, {headers: headers}).subscribe((data) => {
            if(data.json().success) {
                this.http.post('http://localhost:5555/sendmail', emailid, {headers: headers}).subscribe((data) => {
            if(data.json().success) {
              console.log('Sent successfully');
            }
         })
       }
    })
  }
}


text:
package net.chrisrichardson.foodToGo.domain.hibernate;

import java.sql.*;
import java.util.*;
import java.util.Date;

import net.chrisrichardson.foodToGo.domain.*;
import net.chrisrichardson.foodToGo.domain.Order;
import net.chrisrichardson.foodToGo.util.*;
import net.chrisrichardson.foodToGo.util.hibernate.*;
import net.chrisrichardson.ormunit.hibernate.*;
import net.chrisrichardson.util.*;

import org.hibernate.*;
import org.hibernate.criterion.*;
import org.springframework.orm.hibernate3.*;

public class HibernateOrderRepositoryImplTests extends
		HibernatePersistenceTests {

	@Override
	protected String[] getConfigLocations() {
		return HibernateTestConstants.HIBERNATE_DOMAIN_CONTEXT;

	}

	private final class ScrollHibernateCallback implements HibernateCallback {
		public Object doInHibernate(Session session) throws HibernateException,
				SQLException {
			ScrollableResults results = session.createCriteria(Order.class)
					.add(Restrictions.eq("deliveryAddress.city", "Oakland"))
					.setFetchMode("restaurant", FetchMode.JOIN).scroll();
			List orders = new ArrayList();
			int pageSize = 100;
			if (results.first() && results.scroll(1)) {
				for (int i = 0; i < pageSize; i++) {
					orders.add(results.get(0));
					if (!results.next())
						break;
				}
			}

			Order order = (Order) orders.get(0);
			Restaurant r = order.getRestaurant();
			return null;
		}
	}

	private HibernateOrderRepositoryImpl repository;

	private OrderSearchCriteria criteria;

	private String orderId1;

	private String orderId2;

	protected void onSetUp() throws Exception {
		super.onSetUp();

		insertTestData();

		HibernateWrapper queryExecutor = new HibernateQueryExecutor(
				getHibernateTemplate());
		repository = new HibernateOrderRepositoryImpl(getHibernateTemplate(),
				queryExecutor);
		criteria = new OrderSearchCriteria();
	}

	private void insertTestData() throws HibernateException {

		doWithTransaction(new TxnCallback() {

			public void execute() throws Throwable {
				delete(OrderLineItem.class);
				delete(Order.class);
				Calendar c = Calendar.getInstance();
				Date order2Time = c.getTime();
				c.add(Calendar.DAY_OF_YEAR, -30);
				Date order1Time = c.getTime();
				Order o1 = OrderMother.makeOrder(order1Time);
				Order o2 = OrderMother.makeOrder(order2Time);
				save(o1.getRestaurant());
				save(o2.getRestaurant());
				save(o1);
				save(o2);
				orderId1 = o1.getId();
				orderId2 = o2.getId();
			}
		});
	}

	public void testFindOrder() throws Exception {
		Order order = repository.findOrder(orderId1);
		assertNotNull(((OrderLineItem) order.getLineItems().get(0)).getName());
	}

	public void testFindOrders() throws Exception {
		PagedQueryResult results = repository.findOrdersInline(0, 10, criteria);
		assertFalse(results.getResults().isEmpty());
	}

	public void testFindOrders_since() throws Exception {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_YEAR, -20);
		criteria.setDeliveryTime(c.getTime());
		PagedQueryResult results = repository.findOrdersInline(0, 10, criteria);
		assertFalse(results.getResults().isEmpty());
	}

	public void testFindOrders_fromTwo() throws Exception {
		PagedQueryResult results = repository.findOrdersInline(2, 10, criteria);
		assertTrue(results.getResults().isEmpty());
	}

	public void testFindOrdersExecute_validCity() throws Exception {
		criteria.setDeliveryCity("Oakland");
		PagedQueryResult results = repository.findOrdersInline(0, 10, criteria);
		assertFalse(results.getResults().isEmpty());
	}

	public void testFindOrdersExecute_bogusCity() throws Exception {
		criteria.setDeliveryCity("xxxxOaxkxlaxnd");
		PagedQueryResult results = repository.findOrdersInline(0, 10, criteria);
		assertTrue(results.getResults().isEmpty());
	}

	public void testFindOrdersExecute_restaurant() throws Exception {
		criteria.setRestaurantName("Ajanta");
		PagedQueryResult results = repository.findOrdersInline(0, 10, criteria);
		assertFalse(results.getResults().isEmpty());
	}

	public void testFindOrdersExecute_all() throws Exception {
		criteria.setDeliveryCity("Oakland");
		criteria.setState(Order.PLACED);
		criteria.setRestaurantName("Ajanta");
		PagedQueryResult results = repository.findOrdersInline(0, 10, criteria);
		assertFalse(results.getResults().isEmpty());
	}

	public void testFindOrdersSomething() throws Exception {
		getHibernateTemplate()
				.find(
						"select o from Order o     inner join fetch o.lineItems     inner join fetch o.restaurant where o.deliveryAddress.city='Oakland'");
	}

	public void testFindOrdersProjection() throws Exception {
		List orders = repository.findOrdersUsingScroll();
		assertNotNull(orders);
	}

	public void testScroll() throws Exception {
		getHibernateTemplate().execute(new ScrollHibernateCallback());
	}

	public void testSqlUsingList() throws Exception {
		List orders = repository.findOrdersUsingSQLAndList();
		assertNotNull(orders);
		Object[] firstResult = (Object[]) orders.get(0);
		Order o = (Order) firstResult[0];
		Restaurant r = (Restaurant) firstResult[1];
	}

	public void testSqlUsingScroll() throws Exception {
		List orders = repository.findOrdersUsingSQLAndScroll();
		assertNotNull(orders);
	}

}


text:
maintainer        "37signals"
maintainer_email  "sysadmins@37signals.com"
description       "Configures gnupg"
version           "0.1"


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util;

import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.NotNullFactory;
import com.intellij.util.containers.Convertor;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.lang.reflect.Proxy;
import java.util.Comparator;
import java.util.List;

/**
 * @author peter
 */
public class ObjectUtils {
  private ObjectUtils() {
  }

  /**
   * @see NotNullizer
   */
  public static final Object NULL = sentinel("ObjectUtils.NULL");

  /**
   * Creates a new object which could be used as sentinel value (special value to distinguish from any other object). It does not equal
   * to any other object. Usually should be assigned to the static final field.
   *
   * @param name an object name, returned from {@link #toString()} to simplify the debugging or heap dump analysis
   *             (guaranteed to be stored as sentinel object field). If sentinel is assigned to the static final field,
   *             it's recommended to supply that field name (possibly qualified with the class name).
   * @return a new sentinel object
   */
  @NotNull
  public static Object sentinel(@NotNull String name) {
    return new Sentinel(name);
  }

  /**
   * They promise in http://mail.openjdk.java.net/pipermail/core-libs-dev/2018-February/051312.html that
   * the object reference won't be removed by JIT and GC-ed until this call.
  */
  public static void reachabilityFence(@SuppressWarnings("unused") Object o) {}

  private static class Sentinel {
    private final String myName;

    Sentinel(@NotNull String name) {
      myName = name;
    }

    @Override
    public String toString() {
      return myName;
    }
  }

  /**
   * Creates an instance of class {@code ofInterface} with its {@link Object#toString()} method returning {@code name}.
   * No other guarantees about return value behaviour.
   * {@code ofInterface} must represent an interface class.
   * Useful for stubs in generic code, e.g. for storing in {@code List<T>} to represent empty special value.
   */
  @NotNull
  public static <T> T sentinel(@NotNull final String name, @NotNull Class<T> ofInterface) {
    if (!ofInterface.isInterface()) {
      throw new IllegalArgumentException("Expected interface but got: " + ofInterface);
    }
    // java.lang.reflect.Proxy.ProxyClassFactory fails if the class is not available via the classloader.
    // We must use interface own classloader because classes from plugins are not available via ObjectUtils' classloader.
    //noinspection unchecked
    return (T)Proxy.newProxyInstance(ofInterface.getClassLoader(), new Class[]{ofInterface}, (proxy, method, args) -> {
      if ("toString".equals(method.getName()) && args.length == 0) {
        return name;
      }
      throw new AbstractMethodError();
    });
  }

  @NotNull
  public static <T> T assertNotNull(@Nullable T t) {
    return notNull(t);
  }

  public static <T> void assertAllElementsNotNull(@NotNull T[] array) {
    for (int i = 0; i < array.length; i++) {
      T t = array[i];
      if (t == null) {
        throw new NullPointerException("Element [" + i + "] is null");
      }
    }
  }

  @Contract(value = "!null, _ -> !null; _, !null -> !null; null, null -> null", pure = true)
  public static <T> T chooseNotNull(@Nullable T t1, @Nullable T t2) {
    return t1 == null? t2 : t1;
  }

  @Contract(value = "!null, _ -> !null; _, !null -> !null; null, null -> null", pure = true)
  public static <T> T coalesce(@Nullable T t1, @Nullable T t2) {
    return chooseNotNull(t1, t2);
  }

  @Contract(value = "!null, _, _ -> !null; _, !null, _ -> !null; _, _, !null -> !null; null,null,null -> null", pure = true)
  public static <T> T coalesce(@Nullable T t1, @Nullable T t2, @Nullable T t3) {
    return t1 != null ? t1 : t2 != null ? t2 : t3;
  }

  @Nullable
  public static <T> T coalesce(@Nullable Iterable<T> o) {
    if (o == null) return null;
    for (T t : o) {
      if (t != null) return t;
    }
    return null;
  }

  @NotNull
  public static <T> T notNull(@Nullable T value) {
    //noinspection ConstantConditions
    return notNull(value, value);
  }

  @NotNull
  @Contract(pure = true)
  public static <T> T notNull(@Nullable T value, @NotNull T defaultValue) {
    return value == null ? defaultValue : value;
  }

  @NotNull
  public static <T> T notNull(@Nullable T value, @NotNull NotNullFactory<? extends T> defaultValue) {
    return value == null ? defaultValue.create() : value;
  }

  @Contract(value = "null, _ -> null", pure = true)
  @Nullable
  public static <T> T tryCast(@Nullable Object obj, @NotNull Class<T> clazz) {
    if (clazz.isInstance(obj)) {
      return clazz.cast(obj);
    }
    return null;
  }

  @Nullable
  public static <T, S> S doIfCast(@Nullable Object obj, @NotNull Class<T> clazz, final Convertor<? super T, ? extends S> convertor) {
    if (clazz.isInstance(obj)) {
      //noinspection unchecked
      return convertor.convert((T)obj);
    }
    return null;
  }

  @Contract("null, _ -> null")
  @Nullable
  public static <T, S> S doIfNotNull(@Nullable T obj, @NotNull Function<? super T, ? extends S> function) {
    return obj == null ? null : function.fun(obj);
  }

  public static <T> void consumeIfCast(@Nullable Object obj, @NotNull Class<T> clazz, final Consumer<? super T> consumer) {
    if (clazz.isInstance(obj)) {
      //noinspection unchecked
      consumer.consume((T)obj);
    }
  }

  @Nullable
  @Contract("null, _ -> null")
  public static <T> T nullizeByCondition(@Nullable final T obj, @NotNull final Condition<? super T> condition) {
    if (condition.value(obj)) {
      return null;
    }
    return obj;
  }

  /**
   * Performs binary search on the range [fromIndex, toIndex)
   * @param indexComparator a comparator which receives a middle index and returns the result of comparision of the value at this index and the goal value
   *                        (e.g 0 if found, -1 if the value[middleIndex] < goal, or 1 if value[middleIndex] > goal)
   * @return index for which {@code indexComparator} returned 0 or {@code -insertionIndex-1} if wasn't found
   * @see java.util.Arrays#binarySearch(Object[], Object, Comparator)
   * @see java.util.Collections#binarySearch(List, Object, Comparator)
   */
  public static int binarySearch(int fromIndex, int toIndex, @NotNull IntIntFunction indexComparator) {
    int low = fromIndex;
    int high = toIndex - 1;
    while (low <= high) {
      int mid = (low + high) >>> 1;
      int cmp = indexComparator.fun(mid);
      if (cmp < 0) low = mid + 1;
      else if (cmp > 0) high = mid - 1;
      else return mid;
    }
    return -(low + 1);
  }
}


text:
import unittest

from tracing.mre import threaded_work_queue

class ThreadedWorkQueueTests(unittest.TestCase):

  def testSingleThreaded(self):
    wq = threaded_work_queue.ThreadedWorkQueue(num_threads=1)
    self._RunSimpleDecrementingTest(wq)

  def testMultiThreaded(self):
    wq = threaded_work_queue.ThreadedWorkQueue(num_threads=4)
    self._RunSimpleDecrementingTest(wq)

  def _RunSimpleDecrementingTest(self, wq):

    remaining = [10]

    def Decrement():
      remaining[0] -= 1
      if remaining[0]:
        wq.PostMainThreadTask(Done)

    def Done():
      wq.Stop(314)

    wq.PostAnyThreadTask(Decrement)
    res = wq.Run()
    self.assertEquals(res, 314)


text:
namespace AspRecipeStorage.Models
{
    using System;
    using System.Collections.Generic;

    public partial class UserLogin
    {
        public int UserId { get; set; }
        public string LoginProvider { get; set; }
        public string ProviderKey { get; set; }

        public virtual User User { get; set; }
    }
}


text:
package com.cinchapi.concourse;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Set;

import org.junit.Assert;
import org.junit.Test;

import com.cinchapi.concourse.Timestamp;
import com.cinchapi.concourse.importer.CsvImporter;
import com.cinchapi.concourse.importer.Importer;
import com.cinchapi.concourse.lang.Criteria;
import com.cinchapi.concourse.test.ConcourseIntegrationTest;
import com.cinchapi.concourse.test.Variables;
import com.cinchapi.concourse.thrift.Operator;
import com.cinchapi.concourse.util.Resources;
import com.google.common.base.Throwables;
import com.google.common.collect.Sets;

/**
 * Unit tests to make sure that the find operation works with complex
 * {@link Criteria}.
 *
 * @author Jeff Nelson
 */
public class FindCriteriaTest extends ConcourseIntegrationTest {

    private Statement sql;

    @Override
    protected void beforeEachTest() {
        // Import data into Concourse
        System.out.println("Importing college data into Concourse");
        Importer importer = new CsvImporter(client);
        importer.importFile(Resources.get("/college.csv").getFile());

        // Load up the SQL db which also contains a copy of the data
        System.out.println("Loading SQL database with college data");
        try {
            // NOTE: The JDBC API is atrocious :o=
            Class.forName("org.sqlite.JDBC");
            Connection conn = DriverManager.getConnection("jdbc:sqlite:"
                    + Resources.get("/college.db").getFile());
            sql = conn.createStatement();
        }
        catch (Exception e) {
            throw Throwables.propagate(e);
        }

        super.beforeEachTest();
    }

    @Test
    public void testSimpleWithTime() {
        Set<Long> results = client.find(Criteria.where().key("graduation_rate")
                .operator(Operator.GREATER_THAN).value(90));
        Timestamp t1 = Timestamp.now();
        System.out.println("Importing college data into Concourse");
        Importer importer = new CsvImporter(client);
        importer.importFile(Resources.get("/college.csv").getFile());
        Assert.assertEquals(
                results,
                client.find(Criteria.where().key("graduation_rate")
                        .operator(Operator.GREATER_THAN).value(90).at(t1)));

    }

    @Test
    public void testBuildableStateParamSucceeds() {
        Assert.assertEquals(
                client.find(Criteria.where().key("graduation_rate")
                        .operator(Operator.GREATER_THAN).value(90)),
                client.find(Criteria.where().key("graduation_rate")
                        .operator(Operator.GREATER_THAN).value(90).build()));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNonBuildableStateParamDoesNotSucceed() {
        client.find(new Object());
    }

    @Test
    public void testSimple() {
        Assert.assertTrue(hasSameResults(Criteria.where()
                .key("graduation_rate").operator(Operator.GREATER_THAN)
                .value(90).build()));
    }

    @Test
    public void testSimpleAnd() {
        Assert.assertTrue(hasSameResults(Criteria.where()
                .key("graduation_rate").operator(Operator.GREATER_THAN)
                .value(90).and().key("percent_undergrad_black")
                .operator(Operator.GREATER_THAN_OR_EQUALS).value(5).build()));
    }

    @Test
    public void testSimpleOr() {
        Assert.assertTrue(hasSameResults(Criteria.where()
                .key("graduation_rate").operator(Operator.GREATER_THAN)
                .value(90).or().key("percent_undergrad_black")
                .operator(Operator.GREATER_THAN_OR_EQUALS).value(5).build()));
    }

    @Test
    public void testSimpleAndOr() {
        Assert.assertTrue(hasSameResults(Criteria.where()
                .key("graduation_rate").operator(Operator.GREATER_THAN)
                .value(90).and().key("percent_undergrad_black")
                .operator(Operator.GREATER_THAN_OR_EQUALS).value(5).or()
                .key("total_cost_out_state").operator(Operator.GREATER_THAN)
                .value(50000).build()));
    }

    @Test
    public void testSimpleOrAnd() {
        Assert.assertTrue(hasSameResults(Criteria.where()
                .key("graduation_rate").operator(Operator.GREATER_THAN)
                .value(90).or().key("percent_undergrad_black")
                .operator(Operator.GREATER_THAN_OR_EQUALS).value(5).and()
                .key("total_cost_out_state").operator(Operator.GREATER_THAN)
                .value(50000).build()));
    }

    @Test
    public void testAndGroupOr() {
        Assert.assertTrue(hasSameResults(Criteria
                .where()
                .key("graduation_rate")
                .operator(Operator.GREATER_THAN)
                .value(90)
                .and()
                .group(Criteria.where().key("percent_undergrad_black")
                        .operator(Operator.GREATER_THAN_OR_EQUALS).value(5)
                        .or().key("total_cost_out_state")
                        .operator(Operator.GREATER_THAN).value(50000).build())
                .build()));
    }

    @Test
    public void testOrGroupAnd() {
        Assert.assertTrue(hasSameResults(Criteria
                .where()
                .key("graduation_rate")
                .operator(Operator.GREATER_THAN)
                .value(90)
                .or()
                .group(Criteria.where().key("percent_undergrad_black")
                        .operator(Operator.GREATER_THAN_OR_EQUALS).value(5)
                        .and().key("total_cost_out_state")
                        .operator(Operator.GREATER_THAN).value(50000).build())
                .build()));
    }

    @Test
    public void testGroupAndOrGroupAnd() {
        Assert.assertTrue(hasSameResults(Criteria
                .where()
                .group(Criteria.where().key("graduation_rate")
                        .operator(Operator.GREATER_THAN).value(90).and()
                        .key("yield_men").operator(Operator.EQUALS).value(20)
                        .build())
                .or()
                .group(Criteria.where().key("percent_undergrad_black")
                        .operator(Operator.GREATER_THAN_OR_EQUALS).value(5)
                        .and().key("total_cost_out_state")
                        .operator(Operator.GREATER_THAN).value(50000).build())
                .build()));
    }

    @Test
    public void testGroupOrAndGroupOr() {
        Assert.assertTrue(hasSameResults(Criteria
                .where()
                .group(Criteria.where().key("graduation_rate")
                        .operator(Operator.GREATER_THAN).value(90).or()
                        .key("yield_men").operator(Operator.EQUALS).value(20)
                        .build())
                .and()
                .group(Criteria.where().key("percent_undergrad_black")
                        .operator(Operator.GREATER_THAN_OR_EQUALS).value(5)
                        .or().key("total_cost_out_state")
                        .operator(Operator.GREATER_THAN).value(50000).build())
                .build()));
    }

    /**
     * Validate that the {@code criteria} returns the same result in Concourse
     * as it does in a relational database.
     *
     * @param criteria
     * @return {@code true} if the Concourse and SQL result sets are the same
     */
    private boolean hasSameResults(Criteria criteria) {
        try {
            Set<Object> a = Sets.newHashSet(client.get("ipeds_id",
                    client.find(criteria)).values());
            String query = "SELECT ipeds_id FROM data WHERE "
                    + criteria.toString();
            ResultSet rs = sql.executeQuery(query);
            rs.next(); // skip column header
            Set<Object> b = Sets.newHashSet();
            while (rs.next()) {
                b.add(rs.getInt(1));
            }
            Variables.register("query", query);
            Variables.register("con", a);
            Variables.register("sql", b);
            Variables.register("diff", Sets.symmetricDifference(a, b));
            return a.equals(b);

        }
        catch (Exception e) {
            throw Throwables.propagate(e);
        }
    }

}


text:
"""
Created on Jun 01, 2012

@author: Bilel Msekni
@contact: bilel.msekni@telecom-sudparis.eu
@author: Houssem Medhioub
@contact: houssem.medhioub@it-sudparis.eu
@organization: Institut Mines-Telecom - Telecom SudParis
@license: Apache License, Version 2.0
"""

import pyocni.pyocni_tools.config as config
import pyocni.pyocni_tools.occi_Joker as joker

import pyocni.pyocni_tools.uuid_Generator as uuid_Generator

try:
    import simplejson as json
except ImportError:
    import json

from pyocni.pyocni_tools.config import return_code

# getting the Logger
logger = config.logger

class ResourceManager(object):
    """
    Manager of resource documents
    """

    def register_resources(self, occi_descriptions, url_path, db_occi_ids_locs, default_attributes):
        """
        Add new resources to the database
        Args:

            @param occi_descriptions: the OCCI description of the new resources
            @param db_occi_ids_locs: OCCI IDs and OCCI Location extracted from the database
            @param url_path: URL path of the request
            @param default_attributes: the default attributes extracted from kind
        """
        loc_res = list()
        kind_occi_id = None

        #Step[1]: Get the kind on which the request was sent

        for elem in db_occi_ids_locs:
            if elem['OCCI_Location'] == url_path:
                kind_occi_id = elem['OCCI_ID']
                break

        if kind_occi_id is not None:
            for desc in occi_descriptions:
                #Note: Verify if the kind to which this request is sent is the same as the one in the link description
                if desc['kind'] == kind_occi_id:
                    ## added by Marouen Mechtri to generate automatically the category ID
                    if 'id' not in desc:
                        desc['id'] = uuid_Generator.get_UUID()
                    #Note: create the url of the id based on the id provided in the request
                    loc = joker.make_entity_location_from_url(url_path, desc['id'])
                    exist_same = joker.verify_existences_teta([loc], db_occi_ids_locs)

                    #Step[2]: Create the new resource
                    if exist_same is False:
                        jData = dict()
                        jData['_id'] = uuid_Generator.get_UUID()
                        jData['OCCI_Location'] = loc
                        full_att = joker.complete_occi_description_with_default_attributes(desc['attributes'],
                            default_attributes)
                        desc['attributes'] = full_att
                        jData['OCCI_Description'] = desc
                        jData['Type'] = "Resource"
                        loc_res.append(jData)
                    else:
                        logger.error(" ===== Register_resources : Bad Resource id ===== ")
                        return list(), return_code['Conflict']

                else:
                    mesg = "Kind description and kind location don't match"
                    logger.error("===== Register_resources: " + mesg + " ===== ")
                    return list(), return_code['Conflict']
            #Step[3]: return the list of resources for creation
            logger.debug("===== Register_resources: Resources sent for creation =====")
            return loc_res, return_code['OK, and location returned']
        else:
            mesg = "No kind corresponding to this location was found"
            logger.error("===== Register_resources: " + mesg + " =====")
            return list(), return_code['Not Found']

    def get_filtered_resources(self, filters, descriptions_res):
        """
        Retrieve the resources that match the filters provided
        Args:
            @param filters: Filters
            @param descriptions_res: Resource descriptions
        """
        var = list()
        try:
            for desc in descriptions_res:
                for filter in filters:
                    #Step[1]: Check if descriptions match the filters
                    checks = joker.filter_occi_description(desc['OCCI_Description'], filter)

                    if checks is True:
                        #Step[2]: Keep record of those description matching the filter
                        var.append(desc['OCCI_ID'])
                        logger.debug("===== Get_filtered_resources: A resource document is found =====")

            return var, return_code['OK']

        except Exception as e:
            logger.error("===== Get_filtered_resources : " + e.message + " =====")
            return list(), return_code['Internal Server Error']

    def register_custom_resource(self, occi_description, path_url, db_occi_ids_locs):
        """
        Add a new resource with a custom URL to the database
        Args:

            @param occi_description: Resource description
            @param path_url: Custom URL of the resource
            @param db_occi_ids_locs: Ids and locations from the database
        """

        #Step[1]: Verify if the kind of the new resource exists
        ok_k = joker.verify_existences_beta([occi_description['kind']], db_occi_ids_locs)

        #Step[2]: create the resource
        if ok_k is True:
            jData = dict()
            jData['_id'] = uuid_Generator.get_UUID()
            jData['OCCI_Location'] = path_url
            jData['OCCI_Description'] = occi_description
            jData['Type'] = "Resource"

        else:
            mesg = "This kind does not exist"
            logger.error(" ===== Register_custom_resource : " + mesg + " =====")
            return list(), return_code['Not Found']

        #Step[3]: send resource for creation
        logger.debug("===== Register_custom_resource :  Resources sent for creation")
        return jData, return_code['OK, and location returned']

    def update_resource(self, old_doc, occi_new_description):
        """
        Fully update the resource's old description
        Args:
            @param old_doc: Old resource document
            @param occi_new_description: New resource description
        """
        try:

            logger.debug("===== Update_resource: Resource sent for update =====")
            #Step[1]: Replace the old occi description with the new occi description
            old_doc['OCCI_Description'] = occi_new_description
            #Step[2]: Return the hole document for update
            return old_doc, return_code['OK, and location returned']

        except Exception as e:

            logger.error("===== Update_resource: Resource couldn't be updated =====")
            return {}, return_code['Internal Server Error']

    def partial_resource_update(self, old_data, occi_description):
        """
        Partially update the resource's old occi description
        Args:

            @param occi_description: Resource description
            @param old_data: Old resource description
        """

        #Step[1]: try a partial resource update
        problems, updated_data = joker.update_occi_entity_description(old_data, occi_description)

        #Step[2]: if no problem then return the new data for update else return the old data with conflict status code
        if problems is False:
            logger.debug("===== Update_partial_resource: Resource sent for update =====")
            return updated_data, return_code['OK, and location returned']
        else:
            logger.error("===== Update_partial_resource: Resource couldn't have been fully updated =====")
            return old_data, return_code['Conflict']


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width initial-scale=1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <title>Kai Wu | Creating a page to organize tags</title>
  <meta name="description" content="A simple, whitespace theme for academics. Based on [*folio](https://github.com/bogoli/-folio) design.
">

  <link rel="shortcut icon" href="https://imkaywu.github.io/assets/img/favicon.ico">
  <link rel="stylesheet" href="https://imkaywu.github.io/assets/css/main.css">
  <link rel="canonical" href="https://imkaywu.github.io/blog/2013/09/jekyll-creating-tags-page/">

        Kai Wu

        about

        blog

            code

            links

            projects

            tutorials

Creating a page to organize tags

September 19, 2013

I'm an organized person, so I want my blogs to be organized as well. I want to organize the posts according to their tags. Unfortunately, it's not that convenient to create that kind of a page. After searching the internet for a while, I found some solutions, here is the one I'm using now.

Add a tag.mkd file and put the following code inside.

<div id='tag_cloud'>
{% for tag in site.tags %}
<a href="#{{ tag[0] }}" title="{{ tag[0] }}" rel="{{ tag[1].size }}">{{ tag[0] }}</a>
{% endfor %}
</div>

<ul id='tag_list'>
{% for tag in site.tags %}
  <li class='tag_item' id="{{ tag[0] }}">
    <span class='tag_name'>{{ tag[0] }}</span>
    <span>
      <ul>
      {% for post in tag[1] %}
        <li class='tag_post'><a href="{{ post.url }}" title="{{ post.title }}">{{ post.date|date_to_long_string }}&nbsp;&nbsp;&nbsp;&nbsp;{{ post.title }}</a></li>
      {% endfor %}
      </ul>
    </span>
  </li>
{% endfor %}
</ul>

<script src="/assets/js/jquery-2.0.3.min.js" type="text/javascript" charset="utf-8"></script>
<script src="/assets/js/jquery.tagcloud.js" type="text/javascript" charset="utf-8"></script>
<script language="javascript">
$.fn.tagcloud.defaults = {
    size: {start: 0.9, end: 2, unit: 'em'},
      color: {start: '#e77471', end: '#f62817'}
};

$(function () {
    $('#tag_cloud a').tagcloud();
});
</script>

And this suffice to do the trick. However, I still have some bugs to fix and the fond and color of the text is not elegant at all. So still got a lot of things to do. You can fork this project in github and see the raw code, or if you have any suggestion and ideas, feel free to email me or @ me in weibo.

    © Copyright 2020 Kai Wu.
    Powered by Jekyll with al-folio theme. Hosted by GitHub Pages.

<link rel="stylesheet" href="https://imkaywu.github.io/assets/css/font-awesome.min.css">
<link rel="stylesheet" href="https://imkaywu.github.io/assets/css/academicons.min.css">


text:
class Coolschedule {
public:
    Coolschedule() {}

    Coolschedule(double tinit,
                 double tmin_ = std::numeric_limits<double>::epsilon(),
                 const std::string& schedule_ = "exp");

    // Temperature cooling function.
    double cool(unsigned k) const;

private:
    double t0;             // initial temperature
    double tmin;           // minimum temperature allowed
    std::string schedule;  // cooling method
};

inline Coolschedule::Coolschedule(double tinit,
                                  double tmin_,
                                  const std::string& schedule_)
{
    t0       = tinit;
    tmin     = tmin_;
    schedule = schedule_;
}

#endif  // SRS_MATH_COOLSCHEDULE_H


text:
<!DOCTYPE html>

        <title>Pre-recorded media streaming ® Muaz Khan</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
        <link rel="author" type="text/html" href="https://plus.google.com/100325991024054712503">
        <meta name="author" content="Muaz Khan">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <link rel="stylesheet" href="https://www.webrtc-experiment.com/style.css">

                    Pre-recorded media streaming ®
                    Muaz Khan

                    HOME
                     ©
                    Muaz Khan

                    .
                    @WebRTCWeb

                    .
                    Github

                    .
                    Latest issues

                    .
                    What's New?

                <video autoplay poster="https://pbs.twimg.com/profile_images/458943715046727680/rh9nRmeW_400x400.png"></video>

                    Download WebM video
                    <input type="file" title="Select WebM file / Size must be less than 800KB">

How to stream your own video?

<script src="https://www.webrtc-experiment.com/streamer.js"> </script>
<script> var streamer = new Streamer(); </script>

pre-recorded media sender instance

<script>
    streamer.push = function (chunk) {
        socket.send(chunk);
    };

    document.querySelector('input[type=file]').onchange = function () {
        streamer.stream(this.files[0]);
    };
</script>

pre-recorded media receiver instance

<script>
    streamer.video = document.querySelector('video');
    streamer.receive();

    function onData(data) {
        if (data.end) streamer.end();
        else streamer.append(data);
    }
</script>

socket.io/websocket to push chunks

<script>
    socket.onmessage = onData;

    // or
    socket.on('message', onData);
</script>

Chrome >=M28 (or Firefox with flag "media.mediasource.enabled=true") is mandatory to test this experiment.

Streaming pre-recorded video (media file)

Currently, using Firebase for streaming chunks of data because MediaSource APIs are only supported on chrome canary which has unreliable RTP (RTCDataChannel) streams. Note: SCTP data channels landed on chrome M >=30 under a flag.

Streaming WebM files only (in the moment!)

WebM file's size must be less than 1000KB; otherwise it will fail. It is a bug will be fixed soon.

It is an early release!

This experiment is an early release. In future, RTCDataChannel APIs will be used to stream pre-recorded media in realtime! (until "video.captureStream" gets implemented. Note: Firefox implemented a prefixed version of captureStream API i.e. mozCaptureStreamUntilEnded)

MediaSource APIs are not made for streaming pre-recorded Medias, though!

Waiting for "video.captureStream" implementation that is proposed for pre-recorded media streaming, unfortunately still in draft!

In
                    future:

partial interface HTMLMediaElement {
    readonly attribute MediaStream stream;

    MediaStream captureStream();
    MediaStream captureStreamUntilEnded();
    readonly attribute boolean audioCaptured;

    attribute any src;
};

                    We will be able to get stream from video like this:

video.src = 'your pre-recorded webm/etc. video';
var preRecordedStream = video.captureStream();
peer.addStream ( preRecordedStream );

Other possibilities

var videoStream = video.createMediaElementSource();
var audioStream = audio.createMediaElementSource();

                    "createMediaElementSource" is also landed on chrome M >= 30. It is also useful for streaming pre-recorded medias.

How this experiment works?

Getting access to WebM video file using File API

Reading it as array buffer using File Reader API

Splitting buffers in predefined small chunks; and posting/transmitting those chunks in a loop using Firebase.

As soon as other party receives first chunk; MediaSource API will start playing video without waiting for all chunks to be downloaded!

You can save/store/record those chunks in any database; because it is a typed array [Uint8Array].

Let's say you want to:

Stream 5min to 7min of video data i.e. total two minutes of video data (over all sockets) from first WebM file.

Then, quickly you want to stream 17 to 19 minutes i.e. total two minutes of data from second WebM file.

Then you want to stream 11 to 15 minutes i.e. total 4 minutes of data from third WebM file.

You can do all such things today!

In simple words; you can stream part of video from first WebM file; part of video from second WebM file and so on, in realtime!

Latest Updates

Feedback

                    <textarea id="message" style="border: 1px solid rgb(189, 189, 189); height: 8em; margin: .2em; outline: none; resize: vertical; width: 98%;" placeholder="Have any message? Suggestions or something went wrong?"></textarea>

                <button id="send-message" style="font-size: 1em;">Send Message</button>Enter your email too; if you want "direct" reply!

                WebRTC Experiments
                © Muaz Khan
                muazkh@gmail.com


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 51: 216 (1994)

#### Original name
Phomatospora striatispora M.E. Barr, 1994

### Remarks
null


text:
/*
Package cachedwriter provides cache for compress writers.

BUG:This package is NOT COMPLETED yet! See comment above ResetableWriter interface.
*/
package cachedwriter


text:
/* vi: set sw=4 ts=4: */
/*
 * Copyright 1989 - 1991, Julianne Frances Haugh <jockgrrl@austin.rr.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of Julianne F. Haugh nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY JULIE HAUGH AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL JULIE HAUGH OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "libbb.h"

/* Return 1 if SHELL is a restricted shell (one not returned by
   getusershell), else 0, meaning it is a standard shell.  */
int restricted_shell(const char *shell)
{
	char *line;

	setusershell();
	while ((line = getusershell())) {
		if (*line != '#' && strcmp(line, shell) == 0)
			return 0;
	}
	endusershell();
	return 1;
}


text:
package com.emitrom.ti4j.mobile.client.ui.interfaces;

public interface HasExtremum {

    /**
     * @return The maximum value of the progress bar
     */
    public double getMax();

    public void setMax(double value);

    /**
     * @return The minimum value of the progress bar
     */
    public double getMin();

    public void setMin(double value);

}


text:
package com.amazonaws.services.clouddirectory.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.clouddirectory.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * CreateTypedLinkFacetRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CreateTypedLinkFacetRequestMarshaller {

    private static final MarshallingInfo<String> SCHEMAARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.HEADER)
            .marshallLocationName("x-amz-data-partition").build();
    private static final MarshallingInfo<StructuredPojo> FACET_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Facet").build();

    private static final CreateTypedLinkFacetRequestMarshaller instance = new CreateTypedLinkFacetRequestMarshaller();

    public static CreateTypedLinkFacetRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(CreateTypedLinkFacetRequest createTypedLinkFacetRequest, ProtocolMarshaller protocolMarshaller) {

        if (createTypedLinkFacetRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(createTypedLinkFacetRequest.getSchemaArn(), SCHEMAARN_BINDING);
            protocolMarshaller.marshall(createTypedLinkFacetRequest.getFacet(), FACET_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
              xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
    <navigation-rule>
        <from-view-id>/log.xhtml</from-view-id>
        <navigation-case>
            <from-outcome>success</from-outcome>
            <to-view-id>/main.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>

    <application>
        <action-listener>
            org.primefaces.application.DialogActionListener
        </action-listener>
        <navigation-handler>
            org.primefaces.application.DialogNavigationHandler
        </navigation-handler>
        <view-handler>
            org.primefaces.application.DialogViewHandler
        </view-handler>
    </application>
    <managed-bean>
        <managed-bean-name>nptpSessionBean</managed-bean-name>
        <managed-bean-class>com.oakeel.PtpSessionBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
</faces-config>